repo_name
stringlengths
5
114
repo_url
stringlengths
24
133
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
directory_id
stringlengths
40
40
branch_name
stringclasses
209 values
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
9.83k
683M
star_events_count
int64
0
22.6k
fork_events_count
int64
0
4.15k
gha_license_id
stringclasses
17 values
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_language
stringclasses
115 values
files
listlengths
1
13.2k
num_files
int64
1
13.2k
PhilipWidegren/Machine-Learning
https://github.com/PhilipWidegren/Machine-Learning
0663611c836fd5725b9972fadcdfde28ef4d066c
1e7fc1efc99b2baeb0bc86769b435696dee4c0a1
119533d98eaa6656aedc8e4505ce8d963a657d8e
refs/heads/master
2019-03-20T15:19:37.814042
2018-03-12T18:48:45
2018-03-12T18:48:45
123,970,582
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.6643192768096924, "alphanum_fraction": 0.6921215057373047, "avg_line_length": 30.778554916381836, "blob_id": "33e5974140d58c9d3b4aed5f5e7182421a1515c4", "content_id": "fb6b09a961a3fa6fe95c4d6abe8e9e65d50e7df2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13632, "license_type": "no_license", "max_line_length": 119, "num_lines": 429, "path": "/features.py", "repo_name": "PhilipWidegren/Machine-Learning", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 1 20:25:43 2018\n\n@author: philipwidegren\n\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame(np.random.rand(1000,3),columns=['mid','bid','ask'])\n\ndef rollingMin(x,n):\n return None\n \ndef rollingMax(x,n):\n return None\n \ndef drawdown(x,n):\n return None\n \ndef maximumDrawdown(x,n):\n return None\n\"\"\"\n HELP FCNS\n\"\"\"\ndef positive(x):\n return x>0\ndef negative(x):\n return x<0\n \ndef positive_values(x):\n return x*(x>0)\ndef negative_values(x):\n return x*(x<0) \n \n\"\"\"\n FILTERS\n\"\"\"\n\ndf = pd.DataFrame(np.random.rand(1000,3),columns=['mid','bid','ask'])\n\ndef mult(x):\n return x*range(0,2)\ndf.rolling(2).apply(mult)\n\ndef sma(x,n):\n return x.rolling(n).mean()\n\ndef ema(x,n):\n return pd.ewma(x, span = n)\n \ndef wma(x,n):\n return None\n\n\"\"\"\n TECHNICAL OVERLAYS\n\"\"\"\ndef bollingerBands(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:bollinger_bands\n w = x.rolling(n)\n mu = w.mean()\n std = w.std()\n \n return mu, mu-std*2, mu+std*2\n \ndef chandelierExit(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:chandelier_exit\n return None\n\ndef ichimokuClouds(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:ichimoku_cloud\n return None \n\ndef KAMA(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:kaufman_s_adaptive_moving_average\n return None\n\ndef keltnerChannels(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:keltner_channels\n return None \n \ndef movingAveragesEnvelope(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:moving_average_envelopes\n return None\n \ndef parabolicSAR(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:parabolic_sar\n return None\n\ndef pivotPoints(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:pivot_points\n return None\n\ndef priceChannels(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:price_channels\n return None\n\ndef volumeByPrice(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:volume_by_price\n return None\n \ndef vwap(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:vwap_intraday\n return None\n \ndef zigZag(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:zigzag\n return None\n \n \n\"\"\"\n TECHNICAL INDICATORS\n\"\"\"\ndef accumulationDistributionLine(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:accumulation_distribution_line\n\n# NEED VOLUME\n return None\n\ndef aroon(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:aroon\n w = x.rolling(n)\n return (w.apply(np.argmax))/n,(w.apply(np.argmin))/n\n\ndef aroonOscillator(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:aroon_oscillator\n z = aroon(x,n)\n return z[0]-z[1]\n \ndef averageDirectionalIndex(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:average_directional_index_adx \n return None\n \n\ndef trueRange(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:average_true_range_atr\n w = x.rolling(n)\n minimum = w.min()\n maximum = w.max()\n \n return maximum-minimum\n\ndef averageTrueRange(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:average_true_range_atr\n z = np.zeros((len(x),1))\n for i in range(0,len(x)):\n if i == 0:\n z[0] = x[0]\n else:\n z[i] = (z[i-1]*(n-1)+x[i])/n\n \n return z \n \ndef bollingerBandWidth(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:bollinger_band_width \n z = bollingerBands(x,n) \n \n return (z[2]-z[1])/z[0]\n\ndef percentageBIndicator(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:bollinger_band_perce\n z = bollingerBands(x,n) \n return (x-z[1])/(z[2]-z[1])\n \ndef chaikinMoneyFlow(close,high,low,volume,n=20):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:chaikin_money_flow_cmf\n z_multiplier = ((close-low)-(high-close))/(high-low)\n z_volume = z_multiplier*volume\n\n return z_volume.rolling(n).sum()/volume.rolling(n).sum()\n \ndef chandeTrendMeter(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:chande_trend_meter\n return None\n \ndef commodityChannelIndex(close,high,low,n=20,c=0.15):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:commodity_channel_index_cci\n tp = (high+low+close)/3\n\n tp_sma = tp.rolling(n).mean()\n \n md = (tp-tp_sma).abs()\n md = md.rolling(n).mean()\n\n return (tp - tp_sma) / (c * md)\n \ndef coppockCurve(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:coppock_curve \n return None\n\ndef correlationCoefficient(x,y,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:correlation_coeffici\n return pd.rolling_corr(x,y,window=n)\n\ndef decisionPointPriceMomentumOscillator(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:dppmo\n return None\n \ndef detrendedPriceOscillator(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:detrended_price_osci\n return None\n\nz = df_tmp['mid']\nchaikinMoneyFlow(z,z,z-1,z,10) \ndef easeOfMovement(high,low,volume,n=14):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:ease_of_movement_emv\n prior_high, prior_low = high.shift(1), low.shift(1)\n dm = ((high + low)/2 - (prior_high + prior_low)/2) \n br = ((volume/100000000)/(high - low))\n emv = dm / br\n\n return emv.rolling(n).mean()\n \ndef forceIndex(close,volume,n=13):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:force_index\n prior_close = close.shift(1)\n fi = (close-prior_close)*volume\n\n return pd.ewma(fi, span = n)\n \ndef massIndex(high,low,n1=9,n2=9,n3=25):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:mass_index\n sEMA = pd.ewma(high-low, span = n1)\n dEMA = pd.ewma(sEMA, span = n2)\n ratio = sEMA/dEMA\n\n return ratio.rolling(n3).sum()\n \ndef macdLine(x,n1=12,n2=26):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:moving_average_convergence_divergence_macd\n z = pd.ewma(x, span=n1)-pd.ewma(x, span=n2)\n return z\n\ndef macdSignalLine(x,n1=12,n2=26,n3=9):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:moving_average_convergence_divergence_macd\n z1 = macd(x,n1,n2)\n z2 = pd.ewma(z1, span=n3)\n \n return z2\n \ndef macdHistogram(x,n1=12,n2=26,n3=9):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:moving_average_convergence_divergence_macd\n z1 = macd(x,n1,n2)\n z2 = pd.ewma(z1, span=n3)\n \n return z1-z2\n \nz.apply(positive).rolling(10).sum() \nprint z.sum()\n \ndef moneyFlowIndex(close,high,low,volume,n=14):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:money_flow_index_mfi \n tp = (high + low + close)/3\n rmf = tp*volume\n mfr = (rmf.apply(positive_values).rolling(10).sum()/rmf.apply(positive).rolling(10).sum())\n mfr /= (rmf.apply(negative_values).rolling(10).sum()/rmf.apply(negative).rolling(10).sum())\n \n return 100-100/(1+mfr)\n \ndef negativeVolumeIndex(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:negative_volume_inde\n\n# NEED VOLUME\n return None \n\ndef onBalanceVolume(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:on_balance_volume_obv\n\n# NEED VOLUME\n return None\n \ndef priceOscillators(x,n1=12,n2=26,n3=9):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:price_oscillators_ppo\n ppo = (pd.ewma(x, span=n1)-pd.ewma(x, span=n2))/pd.ewma(x, span=n2)\n signalLine = pd.ewma(ppo,span=n3)\n ppo_histogram = ppo-signalLine\n\n return ppo, signalLine, ppo_histogram\n \ndef percentageVolumeOscillator(x,n1,n2,n3):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:percentage_volume_oscillator_pvo\n pvo = (pd.ewma(x, span=n1)-pd.ewma(x, span=n2))/pd.ewma(x, span=n2)\n signalLine = pd.ewma(pvo,span=n3)\n pvo_histogram = pvo-signalLine\n\n return pvo, signalLine, pvo_histogram\n \ndef priceRelative(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:price_relative \n return None\n \nz.shift(1) \ndef knowSureThing(close, n0=9, n1 = (10,10), n2 =(10,15), n3 =(10,20), n4 =(15,30)):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:know_sure_thing_kst \n\n sma_1 = (close/close.shift(n1[0])-1).rolling(n1[1]).sum()\n sma_2 = (close/close.shift(n2[0])-1).rolling(n2[1]).sum()\n sma_3 = (close/close.shift(n3[0])-1).rolling(n3[1]).sum()\n sma_4 = (close/close.shift(n4[0])-1).rolling(n4[1]).sum()\n\n kst = sma_1*1 + sma_2*2 + sma_3*3 + sma_4*4\n\n return kst.rolling(n0).mean()\n \ndef pringsSpecialK(x,n): \n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:pring_s_special_k \n return None\n \ndef rateOfChange(close,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:rate_of_change_roc_and_momentum\n return close/close.shift(n)-1\n\ndef relativeStrengthIndex(close,n=14):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:relative_strength_index_rsi\n rsi = (close.apply(positive_values).rolling(n).sum()/close.apply(positive).rolling(n).sum())\n rsi /= (close.apply(negative_values).rolling(n).sum()/close.apply(negative).rolling(n).sum())\n \n return 100-100/(1+rsi)\n\n \ndef rrgRelativeStrength(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:rrg_relative_strength\n return None\n \ndef stockChartsTechnicalRank(close,n1=(200,125), n2=(50,20), n3=(3,14)):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:sctr \n lt_ema = (close/pd.ewma(close, span=n1[0])-1)\n lt_roc = (close/close.shift(n1[1])-1)\n \n mt_ema = (close/pd.ewma(close, span=n2[0])-1)\n mt_roc = (close/close.shift(n1[1])-1)\n \n st_ppo = priceOscillators(close).rolling(n3[0]).last()/priceOscillators(close).rolling(n3[0]).first()\n st_rsi = relativeStrengthIndex(close,n3[1])\n \n return lt_pct*0.3+lt_ema*0.3+mt_ema*0.15+mt_roc*0.15+st_ppo*0.05+st_rsi*0.05\n\ndef slope(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:slope\n return None\n\ndef std(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:standard_deviation_volatility\n return x.rolling(n).std()\n\ndef stochasticOscillator(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:stochastic_oscillator_fast_slow_and_full\n return None\n\ndef stochRsi(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:stochrsi\n rsi = relativeStrengthIndex(close,n=14)\n\n return (rsi-rsi.rolling(n).min())/(rsi.rolling(n).max()-rsi.rolling(n).min())\n\ndef trix(x,n=(15,15,15)):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:trix\n sEMA = pd.ewma(x, span=n[0])\n dEMA = pd.ewma(x, span=n[1])\n tEMA = pd.ewma(x, span=n[2])\n\n return tEMA/tEMA.shift(1)-1\n\ndef trueStrengthIndex(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:true_strength_index\n pc = x-x.shift(1)\n fs = pd.ewma(pc, span=25)\n ss = pd.ewma(fs, span=13)\n \n apc = pc.abs()\n afs = pd.ewma(apc, span=25)\n ass = pd.ewma(fs, span=13) \n \n return 100*(ss/ass)\n\ndef ulcerIndex(close,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:ulcer_index\n\n pdd = (close/close.rolling(14)-1)*100\n sqd = (pdd**2).rolling(14).mean()\n return sqa**(1/2.0)\n\ndef ultimateOscillator(close,high,low,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:ultimate_oscillator\n bp = close-np.min(low,close.shift(1))\n\n tr = np.max(high,close.shift(1))-np.min(low,close.shift(1))\n \n av07 = bp.rolling(7).sum()/tr.rolling(7).sum()\n av14 = bp.rolling(14).sum()/tr.rolling(14).sum()\n av28 = bp.rolling(28).sum()/tr.rolling(28).sum()\n\n return 100*(4*Av07+2*Av14+1*Av28)/(4+2+1)\n\ndef vortexIndicator(x,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:vortex_indicator\n return None\n\ndef williamsR(close,high,low,n):\n#http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:williams_r\n\n return (high.rolling(14).max()-close)/(high.rolling(14).max()-low.rolling(14).min())*-100 \n \n \nz4 = rateOfChange(df['mid'],1)\nz3=df['mid'].rolling(5)\n\nz3.apply(np.min)\n\n\"\"\"\n SOURCES:\n - http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators\n\"\"\"\ndef chandelierExit(x,n)\nChandelier Exit (long) = 22-day High - ATR(22) x 3 \nChandelier Exit (short) = 22-day Low + ATR(22) x 3\n \nz = bollingerBands(df['mid'],20)\n\ndef maximum(mid,bid,ask):\n \n return np.max(mid)\n \n \nz2 = pd.rolling_apply(df, func = maximum, window=2, min_periods=None, args=(df['mid'],df['mid']))\n\"\"\"" } ]
1
wied03/ansible-ruby
https://github.com/wied03/ansible-ruby
df67d10197b517605379141d978b634f72604b1c
2593d8ddde629f9ca479386325064492e4705d89
b7c2839aede42b3eb9e42d0fe0953fad12216045
refs/heads/master
2022-09-07T18:37:48.228612
2022-03-18T21:59:31
2022-03-18T21:59:31
66,167,091
17
0
BSD-2-Clause
2016-08-20T20:39:14
2022-05-25T01:30:54
2022-07-22T09:25:25
Ruby
[ { "alpha_fraction": 0.6892703771591187, "alphanum_fraction": 0.6935622096061707, "avg_line_length": 45.599998474121094, "blob_id": "012ccc361407c07d024e7e2b2fd2e310d01b6ee0", "content_id": "f5c8c0fb307fff576b08c3f8c5e310c9e09fa020", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1165, "license_type": "permissive", "max_line_length": 380, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_cdot_aggregate.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or destroy aggregates on NetApp cDOT.\n class Na_cdot_aggregate < Base\n # @return [:present, :absent] Whether the specified aggregate should exist or not.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String] The name of the aggregate to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Integer, nil] Number of disks to place into the aggregate, including parity disks.,The disks in this newly-created aggregate come from the spare disk pool.,The smallest disks in this pool join the aggregate first, unless the C(disk-size) argument is provided.,Either C(disk-count) or C(disks) must be supplied. Range [0..2^31-1].,Required when C(state=present).\n attribute :disk_count\n validates :disk_count, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7121779322624207, "alphanum_fraction": 0.7163620591163635, "avg_line_length": 71.0793685913086, "blob_id": "c1db292eab29558a3d1d10b44ed3f4e718e3e091", "content_id": "2fe2c894554cfb7ae7430abf72ed44b7fd1a07fb", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4541, "license_type": "permissive", "max_line_length": 483, "num_lines": 63, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_container_cluster.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # A Google Container Engine cluster.\n class Gcp_container_cluster < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] The name of this cluster. The name must be unique within this project and zone, and can be up to 40 characters. Must be Lowercase letters, numbers, and hyphens only. Must start with a letter. Must end with a number or a letter.\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] An optional description of this cluster.\n attribute :description\n\n # @return [Integer] The number of nodes to create in this cluster. You must ensure that your Compute Engine resource quota is sufficient for this number of instances. You must also have available firewall and routes quota. For requests, this field should only be used in lieu of a \"nodePool\" object, since this configuration (along with the \"nodeConfig\") will be used to create a \"NodePool\" object with an auto-generated name. Do not use this and a nodePool at the same time.\n attribute :initial_node_count\n validates :initial_node_count, presence: true, type: Integer\n\n # @return [Hash, nil] Parameters used in creating the cluster's nodes.,For requests, this field should only be used in lieu of a \"nodePool\" object, since this configuration (along with the \"initialNodeCount\") will be used to create a \"NodePool\" object with an auto-generated name. Do not use this and a nodePool at the same time. For responses, this field will be populated with the node configuration of the first node pool. If unspecified, the defaults are used.\n attribute :node_config\n validates :node_config, type: Hash\n\n # @return [Hash, nil] The authentication information for accessing the master endpoint.\n attribute :master_auth\n validates :master_auth, type: Hash\n\n # @return [:\"logging.googleapis.com\", :none, nil] The logging service the cluster should use to write logs. Currently available options: logging.googleapis.com - the Google Cloud Logging service.,none - no logs will be exported from the cluster.,if left as an empty string,logging.googleapis.com will be used.\n attribute :logging_service\n validates :logging_service, expression_inclusion: {:in=>[:\"logging.googleapis.com\", :none], :message=>\"%{value} needs to be :\\\"logging.googleapis.com\\\", :none\"}, allow_nil: true\n\n # @return [:\"monitoring.googleapis.com\", :none, nil] The monitoring service the cluster should use to write metrics.,Currently available options: monitoring.googleapis.com - the Google Cloud Monitoring service.,none - no metrics will be exported from the cluster.,if left as an empty string, monitoring.googleapis.com will be used.\n attribute :monitoring_service\n validates :monitoring_service, expression_inclusion: {:in=>[:\"monitoring.googleapis.com\", :none], :message=>\"%{value} needs to be :\\\"monitoring.googleapis.com\\\", :none\"}, allow_nil: true\n\n # @return [Object, nil] The name of the Google Compute Engine network to which the cluster is connected. If left unspecified, the default network will be used.,To ensure it exists and it is operations, configure the network using 'gcompute_network' resource.\n attribute :network\n\n # @return [Object, nil] The IP address range of the container pods in this cluster, in CIDR notation (e.g. 10.96.0.0/14). Leave blank to have one automatically chosen or specify a /14 block in 10.0.0.0/8.\n attribute :cluster_ipv4_cidr\n\n # @return [Object, nil] Configurations for the various addons available to run in the cluster.\n attribute :addons_config\n\n # @return [Object, nil] The name of the Google Compute Engine subnetwork to which the cluster is connected.\n attribute :subnetwork\n\n # @return [Object, nil] The list of Google Compute Engine locations in which the cluster's nodes should be located.\n attribute :location\n\n # @return [String] The zone where the cluster is deployed.\n attribute :zone\n validates :zone, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6735848784446716, "alphanum_fraction": 0.6735848784446716, "avg_line_length": 39.15151596069336, "blob_id": "352ebb8aed6753fca1287ae6862fa16bdd4a15a9", "content_id": "3fef9043af6cec2dfb334c2174140701f7458a98", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2650, "license_type": "permissive", "max_line_length": 312, "num_lines": 66, "path": "/lib/ansible/ruby/modules/generated/network/panos/panos_query_rules.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # - Security policies allow you to enforce rules and take action, and can be as general or specific as needed. The policy rules are compared against the incoming traffic in sequence, and because the first rule that matches the traffic is applied, the more specific rules must precede the more general ones.\n\n class Panos_query_rules < Base\n # @return [String] IP address (or hostname) of PAN-OS firewall or Panorama management console being queried.\n attribute :ip_address\n validates :ip_address, presence: true, type: String\n\n # @return [String, nil] Username credentials to use for authentication.\n attribute :username\n validates :username, type: String\n\n # @return [String] Password credentials to use for authentication.\n attribute :password\n validates :password, presence: true, type: String\n\n # @return [String, nil] API key that can be used instead of I(username)/I(password) credentials.\n attribute :api_key\n validates :api_key, type: String\n\n # @return [Object, nil] Name of the application or application group to be queried.\n attribute :application\n\n # @return [String, nil] Name of the source security zone to be queried.\n attribute :source_zone\n validates :source_zone, type: String\n\n # @return [Object, nil] The source IP address to be queried.\n attribute :source_ip\n\n # @return [Object, nil] The source port to be queried.\n attribute :source_port\n\n # @return [String, nil] Name of the destination security zone to be queried.\n attribute :destination_zone\n validates :destination_zone, type: String\n\n # @return [String, nil] The destination IP address to be queried.\n attribute :destination_ip\n validates :destination_ip, type: String\n\n # @return [String, nil] The destination port to be queried.\n attribute :destination_port\n validates :destination_port, type: String\n\n # @return [String, nil] The protocol used to be queried. Must be either I(tcp) or I(udp).\n attribute :protocol\n validates :protocol, type: String\n\n # @return [String, nil] Name of the rule tag to be queried.\n attribute :tag_name\n validates :tag_name, type: String\n\n # @return [Object, nil] The Panorama device group in which to conduct the query.\n attribute :devicegroup\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5435886383056641, "alphanum_fraction": 0.5450698137283325, "avg_line_length": 26.31791877746582, "blob_id": "cdf978f0463c7ff58d3cc425a48da78527e3bec2", "content_id": "ded7184512b00010abc20cd91ecdb8d34ab21d43", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4726, "license_type": "permissive", "max_line_length": 198, "num_lines": 173, "path": "/lib/ansible/ruby/dsl_builders/task.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'ansible/ruby/dsl_builders/base'\nrequire 'ansible/ruby/dsl_builders/module_call'\nrequire 'ansible/ruby/dsl_builders/result'\nrequire 'ansible/ruby/models/task'\nrequire 'ansible/ruby/models/handler'\nrequire 'ansible/ruby/dsl_builders/unit'\n\nmodule Ansible\n module Ruby\n module DslBuilders\n class Task < Unit\n @counter_variable = 0\n\n class << self\n attr_reader :counter_variable\n attr_writer :counter_variable\n end\n\n def initialize(name, model)\n super()\n @name = name\n @model = model\n @module = nil\n @inclusion = nil\n # Until the variable is utilized, we don't know if 'register' should be set, the supplied lambda\n name_fetcher = lambda do\n self.class.counter_variable += 1\n name = \"result_#{self.class.counter_variable}\"\n @task_args[:register] = name\n name\n end\n @register = Result.new name_fetcher\n end\n\n def no_log(value)\n @task_args[:no_log] = value\n end\n\n def connection(value)\n @task_args[:connection] = value\n end\n\n def changed_when(clause)\n @task_args[:changed_when] = clause\n end\n\n def failed_when(clause)\n @task_args[:failed_when] = clause\n end\n\n def with_dict(clause)\n @task_args[:with_dict] = clause\n return unless block_given?\n\n hash_key = JinjaItemNode.new('item.key')\n hash_value = JinjaItemNode.new('item.value')\n yield [hash_key, hash_value]\n end\n\n def with_items(*clause)\n # 1 arg is probably a variable reference, so don't use an array\n @task_args[:with_items] = clause.length == 1 ? clause[0] : clause\n yield JinjaItemNode.new if block_given?\n end\n\n def async(value)\n @task_args[:async] = value\n end\n\n def poll(value)\n @task_args[:poll] = value\n end\n\n def notify(value)\n @task_args[:notify] = value\n end\n\n def local_action\n @task_args[:local_action] = true\n yield\n end\n\n def delegate_to(value)\n @task_args[:delegate_to] = value\n end\n\n def delegate_facts(value)\n @task_args[:delegate_facts] = value\n end\n\n def remote_user(value)\n @task_args[:remote_user] = value\n end\n\n def respond_to_missing?(*)\n !@module || super\n end\n\n def _register\n @register\n end\n\n # allow for other attributes besides the module in any order\n def _result\n args = {\n name: @name\n }.merge @task_args\n args[:module] = @module if @module\n args[:inclusion] = @inclusion if @inclusion\n args[:block] = @block if @block\n args[:rescue] = @rescue if @rescue\n args[:always] = @always if @always\n task = @model.new args\n # Quick feedback if the type is wrong, etc.\n task.validate! if validate?\n task\n end\n\n def validate?\n true\n end\n\n def ansible_block(&block)\n block_builder = Block.new\n block_builder.instance_eval(&block)\n @block = block_builder._result\n nil\n end\n\n def ansible_rescue(&block)\n block_builder = Block.new\n block_builder.instance_eval(&block)\n @rescue = block_builder._result\n nil\n end\n\n def ansible_always(&block)\n block_builder = Block.new\n block_builder.instance_eval(&block)\n @always = block_builder._result\n nil\n end\n\n private\n\n def _process_method(id, *args, &block)\n if id == :ansible_include\n @inclusion = _ansible_include(*args, &block)\n return\n end\n if id == :listen && @model == Models::Handler\n @task_args[:listen] = args[0]\n return\n end\n mcb = ModuleCall.new\n # only 1 module allowed per task, give a good error message\n raise \"Invalid module call `#{id}' since `#{@module.ansible_name}' module has already been used in this task. Only valid options are #{_valid_attributes}\" if @module && mcb.respond_to?(id)\n\n no_method_error id, \"Only valid options are #{_valid_attributes}\" if @module\n mcb.send(id, *args, &block)\n @module = mcb._result\n end\n\n def method_missing_return(_id, _result, *_args)\n # Allow module call to return the register vsriable\n @register\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6451414227485657, "alphanum_fraction": 0.6451414227485657, "avg_line_length": 40.69230651855469, "blob_id": "d029484366ae029def9dfca268fa2f3ebcd9fdd2", "content_id": "cdb6db3cd92114a5b6254bdcf2676055911d0ef5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1626, "license_type": "permissive", "max_line_length": 188, "num_lines": 39, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_project.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, suspend, activate and remove projects.\n class Cs_project < Base\n # @return [String] Name of the project.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Display text of the project.,If not specified, C(name) will be used as C(display_text).\n attribute :display_text\n validates :display_text, type: String\n\n # @return [:present, :absent, :active, :suspended, nil] State of the project.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :active, :suspended], :message=>\"%{value} needs to be :present, :absent, :active, :suspended\"}, allow_nil: true\n\n # @return [Object, nil] Domain the project is related to.\n attribute :domain\n\n # @return [Object, nil] Account the project is related to.\n attribute :account\n\n # @return [Array<Hash>, Hash, nil] List of tags. Tags are a list of dictionaries having keys C(key) and C(value).,If you want to delete all tags, set a empty list e.g. C(tags: []).\n attribute :tags\n validates :tags, type: TypeGeneric.new(Hash)\n\n # @return [:yes, :no, nil] Poll async jobs until job has finished.\n attribute :poll_async\n validates :poll_async, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.612738847732544, "alphanum_fraction": 0.628025472164154, "avg_line_length": 29.19230842590332, "blob_id": "7cc1790e88ee1d58bca434aac2bb881aebc1e19e", "content_id": "2eb4f5b5e76aba661e66f72719b0ef3aae912fd1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 785, "license_type": "permissive", "max_line_length": 102, "num_lines": 26, "path": "/lib/ansible/ruby/modules/custom/utilities/logic/set_fact.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# VALIDATED_CHECKSUM: 432kIRjLB27tSAStA2y4wzL9tkImyKJkFq2Zdh54JY0=\n\nrequire 'ansible/ruby/modules/generated/utilities/logic/set_fact'\nrequire 'ansible/ruby/modules/free_form'\n\nmodule Ansible\n module Ruby\n module Modules\n class Set_fact\n # key_value is on the module but it really needs to function like free_form\n attribute :free_form\n include FreeForm\n remove_existing_validations :key_value\n remove_existing_validations :free_form\n # free_form is usually a Hash\n validates :free_form,\n type: {\n type: Hash,\n message: 'set_fact(%{value}), %{value} is expected to be a Hash but was a %{type}'\n }\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6697459816932678, "alphanum_fraction": 0.6697459816932678, "avg_line_length": 24.47058868408203, "blob_id": "3d472a1608bfa46bf305f0d977ec93971a6a9010", "content_id": "22e1b16984dd19f76727c23b8c5b8e103dc0a575", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 433, "license_type": "permissive", "max_line_length": 57, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_hostname.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage the hostname of a BIG-IP.\n class Bigip_hostname < Base\n # @return [String] Hostname of the BIG-IP host.\n attribute :hostname\n validates :hostname, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6650349497795105, "alphanum_fraction": 0.6650349497795105, "avg_line_length": 33.878047943115234, "blob_id": "d2e70332f23acd082629beb9eda35e080658e0b3", "content_id": "3711e8cb072f95207bef9ae025be607d91e30506", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1430, "license_type": "permissive", "max_line_length": 116, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_resource_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Obtain facts of any resource using Azure REST API.\n # This module gives access to resources that are not supported via Ansible modules.\n # Refer to https://docs.microsoft.com/en-us/rest/api/ regarding details related to specific resource REST API.\n class Azure_rm_resource_facts < Base\n # @return [Object, nil] Azure RM Resource URL.\n attribute :url\n\n # @return [String] Specific API version to be used.\n attribute :api_version\n validates :api_version, presence: true, type: String\n\n # @return [String, nil] Provider type, should be specified in no URL is given\n attribute :provider\n validates :provider, type: String\n\n # @return [String, nil] Resource group to be used.,Required if URL is not specified.\n attribute :resource_group\n validates :resource_group, type: String\n\n # @return [String, nil] Resource type.\n attribute :resource_type\n validates :resource_type, type: String\n\n # @return [String, nil] Resource name.\n attribute :resource_name\n validates :resource_name, type: String\n\n # @return [Object, nil] List of subresources\n attribute :subresource\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6568537354469299, "alphanum_fraction": 0.6568537354469299, "avg_line_length": 37.82143020629883, "blob_id": "11ded755074e33f4c00877ff9f3426ea35ca87f5", "content_id": "57a7d9bdc449f823efceacd8d58e7561f717492d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1087, "license_type": "permissive", "max_line_length": 147, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/windows/win_rabbitmq_plugin.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage RabbitMQ plugins.\n class Win_rabbitmq_plugin < Base\n # @return [String] Comma-separated list of plugin names.\n attribute :names\n validates :names, presence: true, type: String\n\n # @return [:yes, :no, nil] Only enable missing plugins.,Does not disable plugins that are not in the names list.\n attribute :new_only\n validates :new_only, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:disabled, :enabled, nil] Specify if plugins are to be enabled or disabled.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:disabled, :enabled], :message=>\"%{value} needs to be :disabled, :enabled\"}, allow_nil: true\n\n # @return [Object, nil] Specify a custom install prefix to a Rabbit.\n attribute :prefix\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7072643041610718, "alphanum_fraction": 0.7112828493118286, "avg_line_length": 61.21154022216797, "blob_id": "675bf08ec3f284f2c1b69a74295ffa66652e5238", "content_id": "fc4fa7dc9813c2e9194db521baddbd015726140a", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3235, "license_type": "permissive", "max_line_length": 500, "num_lines": 52, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_gtm_monitor_external.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages external GTM monitors on a BIG-IP.\n class Bigip_gtm_monitor_external < Base\n # @return [String] Specifies the name of the monitor.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The parent template of this monitor template. Once this value has been set, it cannot be changed. By default, this value is the C(http) parent on the C(Common) partition.\n attribute :parent\n validates :parent, type: String\n\n # @return [Object, nil] Specifies any command-line arguments that the script requires.\n attribute :arguments\n\n # @return [Object, nil] IP address part of the IP/port definition. If this parameter is not provided when creating a new monitor, then the default value will be '*'.\n attribute :ip\n\n # @return [Object, nil] Port address part of the IP/port definition. If this parameter is not provided when creating a new monitor, then the default value will be '*'. Note that if specifying an IP address, a value between 1 and 65535 must be specified.\n attribute :port\n\n # @return [Object, nil] Specifies the name of the file for the monitor to use. In order to reference a file, you must first import it using options on the System > File Management > External Monitor Program File List > Import screen. The BIG-IP system automatically places the file in the proper location on the file system.\n attribute :external_program\n\n # @return [Object, nil] The interval specifying how frequently the monitor instance of this template will run. If this parameter is not provided when creating a new monitor, then the default value will be 30. This value B(must) be less than the C(timeout) value.\n attribute :interval\n\n # @return [Integer, nil] The number of seconds in which the node or service must respond to the monitor request. If the target responds within the set time period, it is considered up. If the target does not respond within the set time period, it is considered down. You can change this number to any number you want, however, it should be 3 times the interval number of seconds plus 1 second. If this parameter is not provided when creating a new monitor, then the default value will be 120.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [Hash, nil] Specifies any variables that the script requires.,Note that double quotes in values will be suppressed.\n attribute :variables\n validates :variables, type: Hash\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [:present, :absent, nil] When C(present), ensures that the monitor exists.,When C(absent), ensures the monitor is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6862302422523499, "alphanum_fraction": 0.6926260590553284, "avg_line_length": 58.06666564941406, "blob_id": "3102349c7ca8d5bdc21f1ec5cdd74b693712f885", "content_id": "1be105169444ddc1d1017de83bb6447a2e6b064e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2658, "license_type": "permissive", "max_line_length": 374, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_bfd_session.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages BFD session configuration, creates a BFD session or deletes a specified BFD session on HUAWEI CloudEngine devices.\n class Ce_bfd_session < Base\n # @return [Object] Specifies the name of a BFD session. The value is a string of 1 to 15 case-sensitive characters without spaces.\n attribute :session_name\n validates :session_name, presence: true\n\n # @return [:static, :auto, nil] BFD session creation mode, the currently created BFD session only supports static or static auto-negotiation mode.\n attribute :create_type\n validates :create_type, expression_inclusion: {:in=>[:static, :auto], :message=>\"%{value} needs to be :static, :auto\"}, allow_nil: true\n\n # @return [:ipv4, nil] Specifies the peer IP address type.\n attribute :addr_type\n validates :addr_type, expression_inclusion: {:in=>[:ipv4], :message=>\"%{value} needs to be :ipv4\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the type and number of the interface bound to the BFD session.\n attribute :out_if_name\n\n # @return [Object, nil] Specifies the peer IP address bound to the BFD session.\n attribute :dest_addr\n\n # @return [Object, nil] Indicates the source IP address carried in BFD packets.\n attribute :src_addr\n\n # @return [Object, nil] Specifies the name of a Virtual Private Network (VPN) instance that is bound to a BFD session. The value is a string of 1 to 31 case-sensitive characters, spaces not supported. When double quotation marks are used around the string, spaces are allowed in the string. The value _public_ is reserved and cannot be used as the VPN instance name.\n attribute :vrf_name\n\n # @return [:yes, :no, nil] Indicates the default multicast IP address that is bound to a BFD session. By default, BFD uses the multicast IP address 224.0.0.184. You can set the multicast IP address by running the default-ip-address command. The value is a bool type.\n attribute :use_default_ip\n validates :use_default_ip, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Determines whether the config should be present or not on the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7110609412193298, "alphanum_fraction": 0.7133182883262634, "avg_line_length": 67.15384674072266, "blob_id": "caebf4c5c16b5e6cdc2048e5eb25329adbf45949", "content_id": "cba5104877fbe95a32e4572d3c1e8578b0ed72bc", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1772, "license_type": "permissive", "max_line_length": 331, "num_lines": 26, "path": "/lib/ansible/ruby/modules/generated/system/timezone.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module configures the timezone setting, both of the system clock and of the hardware clock. If you want to set up the NTP, use M(service) module.\n # It is recommended to restart C(crond) after changing the timezone, otherwise the jobs may run at the wrong time.\n # Several different tools are used depending on the OS/Distribution involved. For Linux it can use C(timedatectl) or edit C(/etc/sysconfig/clock) or C(/etc/timezone) and C(hwclock). On SmartOS, C(sm-set-timezone), for macOS, C(systemsetup), for BSD, C(/etc/localtime) is modified.\n # As of version 2.3 support was added for SmartOS and BSDs.\n # As of version 2.4 support was added for macOS.\n # Windows, AIX and HPUX are not supported, please let us know if you find any other OS/distro in which this fails.\n class Timezone < Base\n # @return [String, nil] Name of the timezone for the system clock. Default is to keep current setting. B(At least one of name and hwclock are required.)\n attribute :name\n validates :name, type: String\n\n # @return [:UTC, :local, nil] Whether the hardware clock is in UTC or in local timezone. Default is to keep current setting. Note that this option is recommended not to change and may fail to configure, especially on virtual environments such as AWS. B(At least one of name and hwclock are required.) I(Only used on Linux.)\n attribute :hwclock\n validates :hwclock, expression_inclusion: {:in=>[:UTC, :local], :message=>\"%{value} needs to be :UTC, :local\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.643478274345398, "alphanum_fraction": 0.643478274345398, "avg_line_length": 43.385963439941406, "blob_id": "f9eb179f40906ad96d51557997688f390a46082f", "content_id": "18c6178f2a2f229506d78483859255b0b22380de", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2530, "license_type": "permissive", "max_line_length": 160, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/ansible_tower/tower_project.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, or destroy Ansible Tower projects. See U(https://www.ansible.com/tower) for an overview.\n class Tower_project < Base\n # @return [String] Name to use for the project.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Description to use for the project.\n attribute :description\n validates :description, type: String\n\n # @return [:manual, :git, :hg, :svn, nil] Type of SCM resource.\n attribute :scm_type\n validates :scm_type, expression_inclusion: {:in=>[:manual, :git, :hg, :svn], :message=>\"%{value} needs to be :manual, :git, :hg, :svn\"}, allow_nil: true\n\n # @return [Object, nil] URL of SCM resource.\n attribute :scm_url\n\n # @return [Object, nil] The server playbook directory for manual projects.\n attribute :local_path\n\n # @return [Object, nil] The branch to use for the SCM resource.\n attribute :scm_branch\n\n # @return [Object, nil] Name of the credential to use with this SCM resource.\n attribute :scm_credential\n\n # @return [:yes, :no, nil] Remove local modifications before updating.\n attribute :scm_clean\n validates :scm_clean, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Remove the repository completely before updating.\n attribute :scm_delete_on_update\n validates :scm_delete_on_update, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Before an update to the local repository before launching a job with this project.\n attribute :scm_update_on_launch\n validates :scm_update_on_launch, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Primary key of organization for project.\n attribute :organization\n validates :organization, type: String\n\n # @return [:present, :absent, nil] Desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7046413421630859, "alphanum_fraction": 0.7236286997795105, "avg_line_length": 25.33333396911621, "blob_id": "9d763ceabdbd6972a22b4cad5c6dcafb030fbf68", "content_id": "fe306159533a0657696f80f8b6a71ce0df113ad0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 474, "license_type": "permissive", "max_line_length": 135, "num_lines": 18, "path": "/lib/ansible/ruby/modules/custom/system/firewalld.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# VALIDATED_CHECKSUM: 2Xw3BWuyYAdBR5uBu3zJMb/O3rosKreeI2Cpo0B0ul8=\n\n# see LICENSE.txt in project root\n\nrequire 'ansible/ruby/modules/generated/system/firewalld'\n\nmodule Ansible\n module Ruby\n module Modules\n class Firewalld\n remove_existing_validations :permanent\n validates :permanent, expression_inclusion: { in: [true, false], message: '%{value} needs to be true, false' }, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6633817553520203, "alphanum_fraction": 0.6639004349708557, "avg_line_length": 42.818180084228516, "blob_id": "b98507da48f5a774f2758cc7c655b44f5d5f344f", "content_id": "45b4032a5743dfd540eb643be5258a4b59c13257", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1928, "license_type": "permissive", "max_line_length": 183, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/source_control/gitlab_deploy_key.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Adds, updates and removes project deploy keys\n class Gitlab_deploy_key < Base\n # @return [String] GitLab API url, e.g. https://gitlab.example.com/api\n attribute :api_url\n validates :api_url, presence: true, type: String\n\n # @return [String, nil] The oauth key provided by GitLab. One of access_token or private_token is required. See https://docs.gitlab.com/ee/api/oauth2.html\n attribute :access_token\n validates :access_token, type: String\n\n # @return [Object, nil] Personal access token to use. One of private_token or access_token is required. See https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html\n attribute :private_token\n\n # @return [String] Numeric project id or name of project in the form of group/name\n attribute :project\n validates :project, presence: true, type: String\n\n # @return [String] Deploy key's title\n attribute :title\n validates :title, presence: true, type: String\n\n # @return [String] Deploy key\n attribute :key\n validates :key, presence: true, type: String\n\n # @return [:yes, :no, nil] Whether this key can push to the project\n attribute :can_push\n validates :can_push, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent] When C(present) the deploy key added to the project if it doesn't exist.,When C(absent) it will be removed from the project if it exists\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7072463631629944, "alphanum_fraction": 0.7094202637672424, "avg_line_length": 56.5, "blob_id": "114bf2215581b03972484c0c103f42c87bf7701a", "content_id": "43914a2302f58e83c55ccf96777f2d7519f6c952", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1380, "license_type": "permissive", "max_line_length": 421, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_install_os.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Install an operating system by setting the boot options like boot image and kickstart image and optionally select to install using ISSU (In Server Software Upgrade).\n class Nxos_install_os < Base\n # @return [String] Name of the system (or combined) image file on flash.\n attribute :system_image_file\n validates :system_image_file, presence: true, type: String\n\n # @return [Object, nil] Name of the kickstart image file on flash. (Not required on all Nexus platforms)\n attribute :kickstart_image_file\n\n # @return [:required, :desired, :yes, :no, nil] Upgrade using In Service Software Upgrade (ISSU). (Supported on N5k, N7k, N9k platforms),Selecting 'required' or 'yes' means that upgrades will only proceed if the switch is capable of ISSU.,Selecting 'desired' means that upgrades will use ISSU if possible but will fall back to disruptive upgrade if needed.,Selecting 'no' means do not use ISSU. Forced disruptive.\n attribute :issu\n validates :issu, expression_inclusion: {:in=>[:required, :desired, :yes, :no], :message=>\"%{value} needs to be :required, :desired, :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6758849620819092, "alphanum_fraction": 0.6758849620819092, "avg_line_length": 36.66666793823242, "blob_id": "a914c7623f4905ade7d8953efc181dbad60788ac", "content_id": "c433baeecbb73d9694d21cf5524645d5f476b72e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 904, "license_type": "permissive", "max_line_length": 130, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_server_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Retrieve facts about server instances from OpenStack.\n class Os_server_facts < Base\n # @return [String, nil] restrict results to servers with names or UUID matching this glob expression (e.g., <web*>).\n attribute :server\n validates :server, type: String\n\n # @return [:yes, :no, nil] when true, return additional detail about servers at the expense of additional API calls.\n attribute :detailed\n validates :detailed, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7216319441795349, "alphanum_fraction": 0.7216319441795349, "avg_line_length": 60.921051025390625, "blob_id": "485abf1e698ecd80628f7e33e836cbe26a20ad06", "content_id": "4e51a026ca6894ff284e0ef69e09dcf3f6f355c2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2353, "license_type": "permissive", "max_line_length": 264, "num_lines": 38, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_ses_identity.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows the user to manage verified email and domain identity for SES.\n # This covers verifying and removing identities as well as setting up complaint, bounce and delivery notification settings.\n class Aws_ses_identity < Base\n # @return [String] This is the email address or domain to verify / delete.,If this contains an '@' then it will be considered an email. Otherwise it will be considered a domain.\n attribute :identity\n validates :identity, presence: true, type: String\n\n # @return [:present, :absent, nil] Whether to create(or update) or delete the identity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Hash, nil] Setup the SNS topic used to report bounce notifications.,If omitted, bounce notifications will not be delivered to a SNS topic.,If bounce notifications are not delivered to a SNS topic, I(feedback_forwarding) must be enabled.\n attribute :bounce_notifications\n validates :bounce_notifications, type: Hash\n\n # @return [Hash, nil] Setup the SNS topic used to report complaint notifications.,If omitted, complaint notifications will not be delivered to a SNS topic.,If complaint notifications are not delivered to a SNS topic, I(feedback_forwarding) must be enabled.\n attribute :complaint_notifications\n validates :complaint_notifications, type: Hash\n\n # @return [Hash, nil] Setup the SNS topic used to report delivery notifications.,If omitted, delivery notifications will not be delivered to a SNS topic.\n attribute :delivery_notifications\n validates :delivery_notifications, type: Hash\n\n # @return [Boolean, nil] Whether or not to enable feedback forwarding.,This can only be false if both I(bounce_notifications) and I(complaint_notifications) specify SNS topics.\n attribute :feedback_forwarding\n validates :feedback_forwarding, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6757659912109375, "alphanum_fraction": 0.6757659912109375, "avg_line_length": 38.88888931274414, "blob_id": "4ac22eb7f6f7df8e053525f6c15b1a73c9aba630", "content_id": "bec493c973b48350c8fd9881dbdc5858ab41cf07", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1795, "license_type": "permissive", "max_line_length": 154, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/remote_management/stacki/stacki_host.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Use this module to add or remove hosts to a stacki front-end via API.\n # U(https://github.com/StackIQ/stacki)\n class Stacki_host < Base\n # @return [String] Name of the host to be added to Stacki.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] Username for authenticating with Stacki API, but if not specified, the environment variable C(stacki_user) is used instead.\n attribute :stacki_user\n validates :stacki_user, presence: true, type: String\n\n # @return [String] Password for authenticating with Stacki API, but if not specified, the environment variable C(stacki_password) is used instead.\n attribute :stacki_password\n validates :stacki_password, presence: true, type: String\n\n # @return [String] URL for the Stacki API Endpoint.\n attribute :stacki_endpoint\n validates :stacki_endpoint, presence: true, type: String\n\n # @return [String, nil] MAC Address for the primary PXE boot network interface.\n attribute :prim_intf_mac\n validates :prim_intf_mac, type: String\n\n # @return [String, nil] IP Address for the primary network interface.\n attribute :prim_intf_ip\n validates :prim_intf_ip, type: String\n\n # @return [String, nil] Name of the primary network interface.\n attribute :prim_intf\n validates :prim_intf, type: String\n\n # @return [Object, nil] Set value to True to force node into install state if it already exists in stacki.\n attribute :force_install\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7028712034225464, "alphanum_fraction": 0.7040045261383057, "avg_line_length": 61.282352447509766, "blob_id": "40ec5dfff49ddd5166702ae9159ca678bb86c446", "content_id": "3c93bddf54e5defff69c79fc65159018e9281c33", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5294, "license_type": "permissive", "max_line_length": 551, "num_lines": 85, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/ansible_tower/tower_inventory_source.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, or destroy Ansible Tower inventories source. See U(https://www.ansible.com/tower) for an overview.\n class Tower_inventory_source < Base\n # @return [String] The name to use for the inventory source.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The description to use for the inventory source.\n attribute :description\n validates :description, type: String\n\n # @return [String] The inventory the source is linked to.\n attribute :inventory\n validates :inventory, presence: true, type: String\n\n # @return [:file, :scm, :ec2, :gce, :azure, :azure_rm, :vmware, :satellite6, :cloudforms, :openstack, :rhv, :tower, :custom] Types of inventory source.\n attribute :source\n validates :source, presence: true, expression_inclusion: {:in=>[:file, :scm, :ec2, :gce, :azure, :azure_rm, :vmware, :satellite6, :cloudforms, :openstack, :rhv, :tower, :custom], :message=>\"%{value} needs to be :file, :scm, :ec2, :gce, :azure, :azure_rm, :vmware, :satellite6, :cloudforms, :openstack, :rhv, :tower, :custom\"}\n\n # @return [String, nil] Credential to use to retrieve the inventory from.\n attribute :credential\n validates :credential, type: String\n\n # @return [String, nil] The source_vars allow to Override variables found in the source config file. For example with Openstack, specifying *private: false* would change the output of the openstack.py script. It has to be YAML or JSON.\n attribute :source_vars\n validates :source_vars, type: String\n\n # @return [Object, nil] Number in seconds after which the Tower API methods will time out.\n attribute :timeout\n\n # @return [Object, nil] Use a *project* as a source for the *inventory*.\n attribute :source_project\n\n # @return [Object, nil] Path to the file to use as a source in the selected *project*.\n attribute :source_path\n\n # @return [Symbol, nil] That parameter will sync the inventory when the project is synced. It can only be used with a SCM source.\n attribute :update_on_project_update\n validates :update_on_project_update, type: Symbol\n\n # @return [Object, nil] List of regions for your cloud provider. You can include multiple all regions. Only Hosts associated with the selected regions will be updated. Refer to Ansible Tower documentation for more detail.\n attribute :source_regions\n\n # @return [Object, nil] Provide a comma-separated list of filter expressions. Hosts are imported when all of the filters match. Refer to Ansible Tower documentation for more detail.\n attribute :instance_filters\n\n # @return [Object, nil] Specify which groups to create automatically. Group names will be created similar to the options selected. If blank, all groups above are created. Refer to Ansible Tower documentation for more detail.\n attribute :group_by\n\n # @return [Object, nil] The source custom script to use to build the inventory. It needs to exist.\n attribute :source_script\n\n # @return [Symbol, nil] If set, any hosts and groups that were previously present on the external source but are now removed will be removed from the Tower inventory. Hosts and groups that were not managed by the inventory source will be promoted to the next manually created group or if there is no manually created group to promote them into, they will be left in the \"all\" default group for the inventory. When not checked, local child hosts and groups not found on the external source will remain untouched by the inventory update process.\n attribute :overwrite\n validates :overwrite, type: Symbol\n\n # @return [Symbol, nil] If set, all variables for child groups and hosts will be removed and replaced by those found on the external source. When not checked, a merge will be performed, combining local variables with those found on the external source.\n attribute :overwrite_vars\n validates :overwrite_vars, type: Symbol\n\n # @return [Symbol, nil] Each time a job runs using this inventory, refresh the inventory from the selected source before executing job tasks.\n attribute :update_on_launch\n validates :update_on_launch, type: Symbol\n\n # @return [Object, nil] Time in seconds to consider an inventory sync to be current. During job runs and callbacks the task system will evaluate the timestamp of the latest sync. If it is older than Cache Timeout, it is not considered current, and a new inventory sync will be performed.\n attribute :update_cache_timeout\n\n # @return [:present, :absent, nil] Desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Symbol, nil] Tower option to avoid certificates check.\n attribute :tower_verify_ssl\n validates :tower_verify_ssl, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7146090269088745, "alphanum_fraction": 0.719135046005249, "avg_line_length": 62.126983642578125, "blob_id": "aa43fda0818728a48acce464dd30492e798c61d5", "content_id": "9f49c24f86b7a6b8daefe1c1909ae3816b671c1f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3977, "license_type": "permissive", "max_line_length": 489, "num_lines": 63, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_compute_instance.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # An instance is a virtual machine (VM) hosted on Google's infrastructure.\n class Gcp_compute_instance < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Symbol, nil] Allows this instance to send and receive packets with non-matching destination or source IPs. This is required if you plan to use this instance to forward routes.\n attribute :can_ip_forward\n validates :can_ip_forward, type: Symbol\n\n # @return [Array<Hash>, Hash, nil] An array of disks that are associated with the instances that are created from this template.\n attribute :disks\n validates :disks, type: TypeGeneric.new(Hash)\n\n # @return [Object, nil] List of the type and count of accelerator cards attached to the instance .\n attribute :guest_accelerators\n\n # @return [Object, nil] A fingerprint for this request, which is essentially a hash of the metadata's contents and used for optimistic locking. The fingerprint is initially generated by Compute Engine and changes after every request to modify or update metadata. You must always provide an up-to-date fingerprint hash in order to update or change metadata.\n attribute :label_fingerprint\n\n # @return [Hash, nil] The metadata key/value pairs to assign to instances that are created from this template. These pairs can consist of custom metadata or predefined keys.\n attribute :metadata\n validates :metadata, type: Hash\n\n # @return [String, nil] A reference to a machine type which defines VM kind.\n attribute :machine_type\n validates :machine_type, type: String\n\n # @return [Object, nil] Specifies a minimum CPU platform for the VM instance. Applicable values are the friendly names of CPU platforms .\n attribute :min_cpu_platform\n\n # @return [String, nil] The name of the resource, provided by the client when initially creating the resource. The resource name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash.\n attribute :name\n validates :name, type: String\n\n # @return [Array<Hash>, Hash, nil] An array of configurations for this interface. This specifies how this interface is configured to interact with other network services, such as connecting to the internet. Only one network interface is supported per instance.\n attribute :network_interfaces\n validates :network_interfaces, type: TypeGeneric.new(Hash)\n\n # @return [Object, nil] Sets the scheduling options for this instance.\n attribute :scheduling\n\n # @return [Object, nil] A list of service accounts, with their specified scopes, authorized for this instance. Only one service account per VM instance is supported.\n attribute :service_accounts\n\n # @return [Object, nil] A list of tags to apply to this instance. Tags are used to identify valid sources or targets for network firewalls and are specified by the client during instance creation. The tags can be later modified by the setTags method. Each tag within the list must comply with RFC1035.\n attribute :tags\n\n # @return [String] A reference to the zone where the machine resides.\n attribute :zone\n validates :zone, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6770998239517212, "alphanum_fraction": 0.6814579963684082, "avg_line_length": 45.74074172973633, "blob_id": "57eac7d5f4b171679806aa0ea744787d626aa708", "content_id": "c6af235ec40e8bf7d9b0536406348d8e889b7742", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2524, "license_type": "permissive", "max_line_length": 278, "num_lines": 54, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_glue_job.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage an AWS Glue job. See U(https://aws.amazon.com/glue/) for details.\n class Aws_glue_job < Base\n # @return [Object, nil] The number of AWS Glue data processing units (DPUs) to allocate to this Job. From 2 to 100 DPUs can be allocated; the default is 10. A DPU is a relative measure of processing power that consists of 4 vCPUs of compute capacity and 16 GB of memory.\n attribute :allocated_capacity\n\n # @return [String, nil] The name of the job command. This must be 'glueetl'.\n attribute :command_name\n validates :command_name, type: String\n\n # @return [String] The S3 path to a script that executes a job.\n attribute :command_script_location\n validates :command_script_location, presence: true, type: String\n\n # @return [Object, nil] A list of Glue connections used for this job.\n attribute :connections\n\n # @return [Object, nil] A dict of default arguments for this job. You can specify arguments here that your own job-execution script consumes, as well as arguments that AWS Glue itself consumes.\n attribute :default_arguments\n\n # @return [Object, nil] Description of the job being defined.\n attribute :description\n\n # @return [Object, nil] The maximum number of concurrent runs allowed for the job. The default is 1. An error is returned when this threshold is reached. The maximum value you can specify is controlled by a service limit.\n attribute :max_concurrent_runs\n\n # @return [Object, nil] The maximum number of times to retry this job if it fails.\n attribute :max_retries\n\n # @return [String] The name you assign to this job definition. It must be unique in your account.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] The name or ARN of the IAM role associated with this job.\n attribute :role\n validates :role, presence: true, type: String\n\n # @return [:present, :absent] Create or delete the AWS Glue job.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [Object, nil] The job timeout in minutes.\n attribute :timeout\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6746940612792969, "alphanum_fraction": 0.6821950078010559, "avg_line_length": 51.77083206176758, "blob_id": "8488c62ca313edfbd480fd5d1de6cffe21e602b7", "content_id": "0c9f4498aa5cef68f706da61cec16ddd56eb599e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2533, "license_type": "permissive", "max_line_length": 210, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudscale/cloudscale_floating_ip.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, assign and delete floating IPs on the cloudscale.ch IaaS service.\n # All operations are performed using the cloudscale.ch public API v1.\n # For details consult the full API documentation: U(https://www.cloudscale.ch/en/api/v1).\n # A valid API token is required for all operations. You can create as many tokens as you like using the cloudscale.ch control panel at U(https://control.cloudscale.ch).\n class Cloudscale_floating_ip < Base\n # @return [:present, :absent, nil] State of the floating IP.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Floating IP address to change.,Required to assign the IP to a different server or if I(state) is absent.\n attribute :ip\n validates :ip, type: String\n\n # @return [4, 6, nil] IP protocol version of the floating IP.\n attribute :ip_version\n validates :ip_version, expression_inclusion: {:in=>[4, 6], :message=>\"%{value} needs to be 4, 6\"}, allow_nil: true\n\n # @return [String, nil] UUID of the server assigned to this floating IP.,Required unless I(state) is absent.\n attribute :server\n validates :server, type: String\n\n # @return [56, nil] Only valid if I(ip_version) is 6.,Prefix length for the IPv6 network. Currently only a prefix of /56 can be requested. If no I(prefix_length) is present, a single address is created.\n attribute :prefix_length\n validates :prefix_length, expression_inclusion: {:in=>[56], :message=>\"%{value} needs to be 56\"}, allow_nil: true\n\n # @return [String, nil] Reverse PTR entry for this address.,You cannot set a reverse PTR entry for IPv6 floating networks. Reverse PTR entries are only allowed for single addresses.\n attribute :reverse_ptr\n validates :reverse_ptr, type: String\n\n # @return [String, nil] cloudscale.ch API token.,This can also be passed in the CLOUDSCALE_API_TOKEN environment variable.\n attribute :api_token\n validates :api_token, type: String\n\n # @return [Integer, nil] Timeout in seconds for calls to the cloudscale.ch API.\n attribute :api_timeout\n validates :api_timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6917164921760559, "alphanum_fraction": 0.6917164921760559, "avg_line_length": 48.82978820800781, "blob_id": "eea79445b9cd4b33b0426a541ebaeaa80257e737", "content_id": "9826e7f9941aa9e73c73679f2f9cff7b88f57540", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2342, "license_type": "permissive", "max_line_length": 199, "num_lines": 47, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/data_pipeline.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create and manage AWS Datapipelines. Creation is not idempotent in AWS, so the I(uniqueId) is created by hashing the options (minus objects) given to the datapipeline.\n # The pipeline definition must be in the format given here U(http://docs.aws.amazon.com/datapipeline/latest/APIReference/API_PutPipelineDefinition.html#API_PutPipelineDefinition_RequestSyntax).\n # Also operations will wait for a configurable amount of time to ensure the pipeline is in the requested state.\n class Data_pipeline < Base\n # @return [String] The name of the Datapipeline to create/modify/delete.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] An optional description for the pipeline being created.\n attribute :description\n validates :description, type: String\n\n # @return [String, nil] A list of pipeline object definitions, each of which is a dict that takes the keys C(id), C(name) and C(fields).\n attribute :objects\n validates :objects, type: String\n\n # @return [String, nil] A list of parameter objects (dicts) in the pipeline definition.\n attribute :parameters\n validates :parameters, type: String\n\n # @return [String, nil] A list of parameter values (dicts) in the pipeline definition. Each dict takes the keys C(id) and C(stringValue) both of which are strings.\n attribute :values\n validates :values, type: String\n\n # @return [Integer, nil] Time in seconds to wait for the pipeline to transition to the requested state, fail otherwise.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [:present, :absent, :active, :inactive, nil] The requested state of the pipeline.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :active, :inactive], :message=>\"%{value} needs to be :present, :absent, :active, :inactive\"}, allow_nil: true\n\n # @return [Hash, nil] A dict of key:value pair(s) to add to the pipeline.\n attribute :tags\n validates :tags, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.723991870880127, "alphanum_fraction": 0.723991870880127, "avg_line_length": 73.39726257324219, "blob_id": "d4350b2510ed0610f85ab8067bd7a6e51f3d59f0", "content_id": "59996339d52d54e38967fc4eb9012f933958daec", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5431, "license_type": "permissive", "max_line_length": 764, "num_lines": 73, "path": "/lib/ansible/ruby/modules/generated/monitoring/logicmonitor.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # LogicMonitor is a hosted, full-stack, infrastructure monitoring platform.\n # This module manages hosts, host groups, and collectors within your LogicMonitor account.\n class Logicmonitor < Base\n # @return [:collector, :host, :datsource, :hostgroup] The type of LogicMonitor object you wish to manage.,Collector: Perform actions on a LogicMonitor collector.,NOTE You should use Ansible service modules such as M(service) or M(supervisorctl) for managing the Collector 'logicmonitor-agent' and 'logicmonitor-watchdog' services. Specifically, you'll probably want to start these services after a Collector add and stop these services before a Collector remove.,Host: Perform actions on a host device.,Hostgroup: Perform actions on a LogicMonitor host group.,NOTE Host and Hostgroup tasks should always be performed via delegate_to: localhost. There are no benefits to running these tasks on the remote host and doing so will typically cause problems.\\r\\n\n attribute :target\n validates :target, presence: true, expression_inclusion: {:in=>[:collector, :host, :datsource, :hostgroup], :message=>\"%{value} needs to be :collector, :host, :datsource, :hostgroup\"}\n\n # @return [:add, :remove, :update, :sdt] The action you wish to perform on target.,Add: Add an object to your LogicMonitor account.,Remove: Remove an object from your LogicMonitor account.,Update: Update properties, description, or groups (target=host) for an object in your LogicMonitor account.,SDT: Schedule downtime for an object in your LogicMonitor account.\n attribute :action\n validates :action, presence: true, expression_inclusion: {:in=>[:add, :remove, :update, :sdt], :message=>\"%{value} needs to be :add, :remove, :update, :sdt\"}\n\n # @return [String] The LogicMonitor account company name. If you would log in to your account at \"superheroes.logicmonitor.com\" you would use \"superheroes.\"\n attribute :company\n validates :company, presence: true, type: String\n\n # @return [String] A LogicMonitor user name. The module will authenticate and perform actions on behalf of this user.\n attribute :user\n validates :user, presence: true, type: String\n\n # @return [String] The password of the specified LogicMonitor user\n attribute :password\n validates :password, presence: true, type: String\n\n # @return [Object, nil] The fully qualified domain name of a collector in your LogicMonitor account.,This is required for the creation of a LogicMonitor host (target=host action=add).,This is required for updating, removing or scheduling downtime for hosts if 'displayname' isn't specified (target=host action=update action=remove action=sdt).\n attribute :collector\n\n # @return [String, nil] The hostname of a host in your LogicMonitor account, or the desired hostname of a device to manage.,Optional for managing hosts (target=host).\n attribute :hostname\n validates :hostname, type: String\n\n # @return [String, nil] The display name of a host in your LogicMonitor account or the desired display name of a device to manage.,Optional for managing hosts (target=host).\n attribute :displayname\n validates :displayname, type: String\n\n # @return [String, nil] The long text description of the object in your LogicMonitor account.,Optional for managing hosts and host groups (target=host or target=hostgroup; action=add or action=update).\n attribute :description\n validates :description, type: String\n\n # @return [Object, nil] A dictionary of properties to set on the LogicMonitor host or host group.,Optional for managing hosts and host groups (target=host or target=hostgroup; action=add or action=update).,This parameter will add or update existing properties in your LogicMonitor account.\n attribute :properties\n\n # @return [Object, nil] A list of groups that the host should be a member of.,Optional for managing hosts (target=host; action=add or action=update).\n attribute :groups\n\n # @return [Object, nil] ID of the datasource to target.,Required for management of LogicMonitor datasources (target=datasource).\n attribute :id\n\n # @return [Object, nil] The fullpath of the host group object you would like to manage.,Recommend running on a single Ansible host.,Required for management of LogicMonitor host groups (target=hostgroup).\n attribute :fullpath\n\n # @return [:yes, :no, nil] A boolean flag to turn alerting on or off for an object.,Optional for managing all hosts (action=add or action=update).\n attribute :alertenable\n validates :alertenable, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] The time that the Scheduled Down Time (SDT) should begin.,Optional for managing SDT (action=sdt).,Y-m-d H:M\n attribute :starttime\n validates :starttime, type: String\n\n # @return [Integer, nil] The duration (minutes) of the Scheduled Down Time (SDT).,Optional for putting an object into SDT (action=sdt).\n attribute :duration\n validates :duration, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6820021867752075, "alphanum_fraction": 0.6820021867752075, "avg_line_length": 47.51785659790039, "blob_id": "1674bae039001ec3a77df15481f53a40df381540", "content_id": "2688e3ceabdc855e31ca3a98f6a4d3ff0d16c84f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2717, "license_type": "permissive", "max_line_length": 263, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/network/bigswitch/bigmon_policy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create and remove a bigmon out-of-band policy.\n class Bigmon_policy < Base\n # @return [String] The name of the policy.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Description of policy.\n attribute :policy_description\n validates :policy_description, type: String\n\n # @return [:forward, :drop, :\"flow-gen\", nil] Forward matching packets to delivery interfaces, Drop is for measure rate of matching packets, but do not forward to delivery interfaces, capture packets and write to a PCAP file, or enable NetFlow generation.\n attribute :action\n validates :action, expression_inclusion: {:in=>[:forward, :drop, :\"flow-gen\"], :message=>\"%{value} needs to be :forward, :drop, :\\\"flow-gen\\\"\"}, allow_nil: true\n\n # @return [Integer, nil] A priority associated with this policy. The higher priority policy takes precedence over a lower priority.\n attribute :priority\n validates :priority, type: Integer\n\n # @return [Integer, nil] Run policy for duration duration or until delivery_packet_count packets are delivered, whichever comes first.\n attribute :duration\n validates :duration, type: Integer\n\n # @return [String, nil] Date the policy becomes active\n attribute :start_time\n validates :start_time, type: String\n\n # @return [Integer, nil] Run policy until delivery_packet_count packets are delivered.\n attribute :delivery_packet_count\n validates :delivery_packet_count, type: Integer\n\n # @return [:present, :absent, nil] Whether the policy should be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The controller address.\n attribute :controller\n validates :controller, presence: true, type: String\n\n # @return [Boolean, nil] If C(false), SSL certificates will not be validated. This should only be used on personally controlled devices using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] Bigmon access token. If this isn't set, the environment variable C(BIGSWITCH_ACCESS_TOKEN) is used.\n attribute :access_token\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7282127141952515, "alphanum_fraction": 0.736189067363739, "avg_line_length": 98.55882263183594, "blob_id": "721430ee0eaba6b311f060300dab7566ebbe4a95", "content_id": "63e377e3dea84351390f205c5045b71e0dca92cb", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3393, "license_type": "permissive", "max_line_length": 753, "num_lines": 34, "path": "/lib/ansible/ruby/modules/generated/crypto/acme/acme_certificate_revoke.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows to revoke certificates issued by a CA supporting the L(ACME protocol,https://tools.ietf.org/html/draft-ietf-acme-acme-14), such as L(Let's Encrypt,https://letsencrypt.org/).\n class Acme_certificate_revoke < Base\n # @return [String] Path to the certificate to revoke.\n attribute :certificate\n validates :certificate, presence: true, type: String\n\n # @return [String, nil] Path to a file containing the ACME account RSA or Elliptic Curve key.,RSA keys can be created with C(openssl rsa ...). Elliptic curve keys can be created with C(openssl ecparam -genkey ...). Any other tool creating private keys in PEM format can be used as well.,Mutually exclusive with C(account_key_content).,Required if C(account_key_content) is not used.\n attribute :account_key_src\n validates :account_key_src, type: String\n\n # @return [Object, nil] Content of the ACME account RSA or Elliptic Curve key.,Note that exactly one of C(account_key_src), C(account_key_content), C(private_key_src) or C(private_key_content) must be specified.,I(Warning): the content will be written into a temporary file, which will be deleted by Ansible when the module completes. Since this is an important private key — it can be used to change the account key, or to revoke your certificates without knowing their private keys —, this might not be acceptable.,In case C(cryptography) is used, the content is not written into a temporary file. It can still happen that it is written to disk by Ansible in the process of moving the module with its argument to the node where it is executed.\n attribute :account_key_content\n\n # @return [String, nil] Path to the certificate's private key.,Note that exactly one of C(account_key_src), C(account_key_content), C(private_key_src) or C(private_key_content) must be specified.\n attribute :private_key_src\n validates :private_key_src, type: String\n\n # @return [Object, nil] Content of the certificate's private key.,Note that exactly one of C(account_key_src), C(account_key_content), C(private_key_src) or C(private_key_content) must be specified.,I(Warning): the content will be written into a temporary file, which will be deleted by Ansible when the module completes. Since this is an important private key — it can be used to change the account key, or to revoke your certificates without knowing their private keys —, this might not be acceptable.,In case C(cryptography) is used, the content is not written into a temporary file. It can still happen that it is written to disk by Ansible in the process of moving the module with its argument to the node where it is executed.\n attribute :private_key_content\n\n # @return [Object, nil] One of the revocation reasonCodes defined in L(https://tools.ietf.org/html/rfc5280#section-5.3.1, Section 5.3.1 of RFC5280).,Possible values are C(0) (unspecified), C(1) (keyCompromise), C(2) (cACompromise), C(3) (affiliationChanged), C(4) (superseded), C(5) (cessationOfOperation), C(6) (certificateHold), C(8) (removeFromCRL), C(9) (privilegeWithdrawn), C(10) (aACompromise)\n attribute :revoke_reason\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6830015182495117, "alphanum_fraction": 0.6860643029212952, "avg_line_length": 44.034481048583984, "blob_id": "61cd374c38eaefb6b67a123522c5c9528d1b6c1b", "content_id": "2affe9ffe8b9dab866e97aeae1d4442da1395eba", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1306, "license_type": "permissive", "max_line_length": 185, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/identity/ipa/ipa_subca.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add, modify, enable, disable and delete an IPA Lightweight Sub Certificate Authorities using IPA API.\n class Ipa_subca < Base\n # @return [String] The Sub Certificate Authority name which needs to be managed.\n attribute :subca_name\n validates :subca_name, presence: true, type: String\n\n # @return [Array<String>, String] The Sub Certificate Authority's Subject. e.g., 'CN=SampleSubCA1,O=testrelm.test'\n attribute :subca_subject\n validates :subca_subject, presence: true, type: TypeGeneric.new(String)\n\n # @return [String] The Sub Certificate Authority's description.\n attribute :subca_desc\n validates :subca_desc, presence: true, type: String\n\n # @return [:present, :absent, :enabled, :disabled, nil] State to ensure,State 'disable' and 'enable' is available for FreeIPA 4.4.2 version and onwards\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :enabled, :disabled], :message=>\"%{value} needs to be :present, :absent, :enabled, :disabled\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6668989658355713, "alphanum_fraction": 0.6668989658355713, "avg_line_length": 38.86111068725586, "blob_id": "e7a014e5da04ea3f3298c4cd58e3cb93c8c3f0c8", "content_id": "a6c90ad342fc0373f2f5bf987591a13e9752a7fa", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1435, "license_type": "permissive", "max_line_length": 154, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_object.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or Delete objects and containers from OpenStack\n class Os_object < Base\n # @return [String] The name of the container in which to create the object\n attribute :container\n validates :container, presence: true, type: String\n\n # @return [String, nil] Name to be give to the object. If omitted, operations will be on the entire container\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] Path to local file to be uploaded.\n attribute :filename\n validates :filename, type: String\n\n # @return [:private, :public, nil] desired container access level.\n attribute :container_access\n validates :container_access, expression_inclusion: {:in=>[:private, :public], :message=>\"%{value} needs to be :private, :public\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Should the resource be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6892430186271667, "alphanum_fraction": 0.6892430186271667, "avg_line_length": 28.52941131591797, "blob_id": "4c4fcb05da5e181ff3bd4750759c2dbd86d1389b", "content_id": "7835893207be47f5f624f652a0d803665b67b905", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 502, "license_type": "permissive", "max_line_length": 90, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/cloud/digital_ocean/digital_ocean_tag_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to gather facts about DigitalOcean provided tags.\n class Digital_ocean_tag_facts < Base\n # @return [String, nil] Tag name that can be used to identify and reference a tag.\n attribute :tag_name\n validates :tag_name, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6670010089874268, "alphanum_fraction": 0.6670010089874268, "avg_line_length": 33.379310607910156, "blob_id": "e57aaf763b0b107b317339f248a29748eaa29867", "content_id": "97a0c85f39d31b3ab801ae77de1ed668a1eee642", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 997, "license_type": "permissive", "max_line_length": 221, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/efs_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Module searches Amazon EFS file systems\n class Efs_facts < Base\n # @return [String, nil] Creation Token of Amazon EFS file system.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] ID of Amazon EFS.\n attribute :id\n validates :id, type: String\n\n # @return [Hash, nil] List of tags of Amazon EFS. Should be defined as dictionary\n attribute :tags\n validates :tags, type: Hash\n\n # @return [Array<String>, String, nil] list of targets on which to filter the returned results,result must match all of the specified targets, each of which can be a security group ID, a subnet ID or an IP address\n attribute :targets\n validates :targets, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6431306004524231, "alphanum_fraction": 0.6431306004524231, "avg_line_length": 40.24561309814453, "blob_id": "0266f1ac17eb396d5b350c106f7f3ac89359982e", "content_id": "e2880f290efab4b77c927182a8936b6710a79d02", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2351, "license_type": "permissive", "max_line_length": 180, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/monitoring/datadog_event.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows to post events to Datadog (www.datadoghq.com) service.\n # Uses http://docs.datadoghq.com/api/#events API.\n class Datadog_event < Base\n # @return [String] Your DataDog API key.\n attribute :api_key\n validates :api_key, presence: true, type: String\n\n # @return [String] Your DataDog app key.\n attribute :app_key\n validates :app_key, presence: true, type: String\n\n # @return [String] The event title.\n attribute :title\n validates :title, presence: true, type: String\n\n # @return [String] The body of the event.\n attribute :text\n validates :text, presence: true, type: String\n\n # @return [String, nil] POSIX timestamp of the event.,Default value is now.\n attribute :date_happened\n validates :date_happened, type: String\n\n # @return [:normal, :low, nil] The priority of the event.\n attribute :priority\n validates :priority, expression_inclusion: {:in=>[:normal, :low], :message=>\"%{value} needs to be :normal, :low\"}, allow_nil: true\n\n # @return [String, nil] Host name to associate with the event.\n attribute :host\n validates :host, type: String\n\n # @return [Array<String>, String, nil] Comma separated list of tags to apply to the event.\n attribute :tags\n validates :tags, type: TypeGeneric.new(String)\n\n # @return [:error, :warning, :info, :success, nil] Type of alert.\n attribute :alert_type\n validates :alert_type, expression_inclusion: {:in=>[:error, :warning, :info, :success], :message=>\"%{value} needs to be :error, :warning, :info, :success\"}, allow_nil: true\n\n # @return [Object, nil] An arbitrary string to use for aggregation.\n attribute :aggregation_key\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7018319368362427, "alphanum_fraction": 0.7056222558021545, "avg_line_length": 59.88461685180664, "blob_id": "9fff5348b392123c079a0af8987d9dd21c63e5fd", "content_id": "8c66cd95d8b1e74b801b11cc3aea79c32ce84456", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1583, "license_type": "permissive", "max_line_length": 399, "num_lines": 26, "path": "/lib/ansible/ruby/modules/generated/windows/win_user_right.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add, remove or set User Rights for a group or users or groups.\n # You can set user rights for both local and domain accounts.\n class Win_user_right < Base\n # @return [String] The name of the User Right as shown by the C(Constant Name) value from U(https://technet.microsoft.com/en-us/library/dd349804.aspx).,The module will return an error if the right is invalid.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Array<String>, String] A list of users or groups to add/remove on the User Right.,These can be in the form DOMAIN\\user-group, [email protected] for domain users/groups.,For local users/groups it can be in the form user-group, .\\user-group, SERVERNAME\\user-group where SERVERNAME is the name of the remote server.,You can also add special local accounts like SYSTEM and others.\n attribute :users\n validates :users, presence: true, type: TypeGeneric.new(String)\n\n # @return [:add, :remove, :set, nil] C(add) will add the users/groups to the existing right.,C(remove) will remove the users/groups from the existing right.,C(set) will replace the users/groups of the existing right.\n attribute :action\n validates :action, expression_inclusion: {:in=>[:add, :remove, :set], :message=>\"%{value} needs to be :add, :remove, :set\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.725623607635498, "alphanum_fraction": 0.7346938848495483, "avg_line_length": 24.941177368164062, "blob_id": "d9fdab471a0d6a35e39aef378e4fa804525b2690", "content_id": "8d226a1d3bef959ae7706cb4a4aaadd5aefb80b4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 441, "license_type": "permissive", "max_line_length": 68, "num_lines": 17, "path": "/lib/ansible/ruby/modules/custom/packaging/os/yum_repository.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# VALIDATED_CHECKSUM: akAVXAlaPNtfb0X9tXCzclGwvmnUxsycQ1rTm0Rc+Mo=\n\nrequire 'ansible/ruby/modules/generated/packaging/os/yum_repository'\n\nmodule Ansible\n module Ruby\n module Modules\n class Yum_repository\n remove_existing_validations :description\n # Description is required, it will fail without it\n validates :description, type: String, presence: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6491835713386536, "alphanum_fraction": 0.6491835713386536, "avg_line_length": 48.29268264770508, "blob_id": "7f4fdd34c5c508a693d25e57ffe25d657cf16cf2", "content_id": "722d41e2978386900ff90a43657dd79ecad1a43a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2021, "license_type": "permissive", "max_line_length": 273, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/storage/purestorage/purefa_host.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, delete or modify hosts on Pure Storage FlashArrays.\n class Purefa_host < Base\n # @return [String] The name of the host.\n attribute :host\n validates :host, presence: true, type: String\n\n # @return [:absent, :present, nil] Define whether the host should exist or not.,When removing host all connected volumes will be disconnected.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:fc, :iscsi, :mixed, nil] Defines the host connection protocol for volumes.\n attribute :protocol\n validates :protocol, expression_inclusion: {:in=>[:fc, :iscsi, :mixed], :message=>\"%{value} needs to be :fc, :iscsi, :mixed\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] List of wwns of the host if protocol is fc or mixed.\n attribute :wwns\n validates :wwns, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] List of IQNs of the host if protocol is iscsi or mixed.\n attribute :iqn\n validates :iqn, type: TypeGeneric.new(String)\n\n # @return [String, nil] Volume name to map to the host.\n attribute :volume\n validates :volume, type: String\n\n # @return [:hpux, :vms, :aix, :esxi, :solaris, :\"hitachi-vsp\", :\"oracle-vm-server\", :\"\", nil] Define which operating systen the host is. Recommend for ActiveCluster integration\n attribute :personality\n validates :personality, expression_inclusion: {:in=>[:hpux, :vms, :aix, :esxi, :solaris, :\"hitachi-vsp\", :\"oracle-vm-server\", :\"\"], :message=>\"%{value} needs to be :hpux, :vms, :aix, :esxi, :solaris, :\\\"hitachi-vsp\\\", :\\\"oracle-vm-server\\\", :\\\"\\\"\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6615878343582153, "alphanum_fraction": 0.6615878343582153, "avg_line_length": 34.628570556640625, "blob_id": "d03ce133ca334c8f4a8cdef0c0ce9137b47beb0f", "content_id": "519c9c94d07fcf8e1cab003a6a3b1976447cbcab", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1247, "license_type": "permissive", "max_line_length": 144, "num_lines": 35, "path": "/lib/ansible/ruby/modules/generated/monitoring/logstash_plugin.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages Logstash plugins.\n class Logstash_plugin < Base\n # @return [String] Install plugin with that name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Apply plugin state.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Specify logstash-plugin to use for plugin management.\n attribute :plugin_bin\n validates :plugin_bin, type: String\n\n # @return [Object, nil] Proxy host to use during plugin installation.\n attribute :proxy_host\n\n # @return [Object, nil] Proxy port to use during plugin installation.\n attribute :proxy_port\n\n # @return [String, nil] Specify plugin Version of the plugin to install. If plugin exists with previous version, it will NOT be updated.\n attribute :version\n validates :version, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6868175268173218, "alphanum_fraction": 0.6893495917320251, "avg_line_length": 75.13253021240234, "blob_id": "f0559bd0680b3ba24cfdad4b1bce9fc25cd674e3", "content_id": "c44b7ed7ca7bcd97d45fa5c4779330a5f0fea854", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6319, "license_type": "permissive", "max_line_length": 665, "num_lines": 83, "path": "/lib/ansible/ruby/modules/generated/database/postgresql/postgresql_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove PostgreSQL users (roles) from a remote host and, optionally, grant the users access to an existing database or tables.\n # The fundamental function of the module is to create, or delete, roles from a PostgreSQL cluster. Privilege assignment, or removal, is an optional step, which works on one database at a time. This allows for the module to be called several times in the same module to modify the permissions on different databases, or to grant permissions to already existing users.\n # A user cannot be removed until all the privileges have been stripped from the user. In such situation, if the module tries to remove the user it will fail. To avoid this from happening the fail_on_user option signals the module to try to remove the user, but if not possible keep going; the module will report if changes happened and separately if the user was removed or not.\n class Postgresql_user < Base\n # @return [String] Name of the user (role) to add or remove.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Set the user's password, before 1.4 this was required.,Password can be passed unhashed or hashed (MD5-hashed).,Unhashed password will automatically be hashed when saved into the database if C(encrypted) parameter is set, otherwise it will be save in plain text format.,When passing a hashed password it must be generated with the format C('str[\"md5\"] + md5[ password + username ]'), resulting in a total of 35 characters. An easy way to do this is C(echo \"md5$(echo -n 'verysecretpasswordJOE' | md5sum)\").,Note that if the provided password string is already in MD5-hashed format, then it is used as-is, regardless of C(encrypted) parameter.\n attribute :password\n validates :password, type: String\n\n # @return [String, nil] Name of database where permissions will be granted.\n attribute :db\n validates :db, type: String\n\n # @return [:yes, :no, nil] If C(yes), fail when user can't be removed. Otherwise just log and continue.\n attribute :fail_on_user\n validates :fail_on_user, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Database port to connect to.\n attribute :port\n validates :port, type: Integer\n\n # @return [String, nil] User (role) used to authenticate with PostgreSQL.\n attribute :login_user\n validates :login_user, type: String\n\n # @return [Object, nil] Password used to authenticate with PostgreSQL.\n attribute :login_password\n\n # @return [String, nil] Host running PostgreSQL.\n attribute :login_host\n validates :login_host, type: String\n\n # @return [Object, nil] Path to a Unix domain socket for local connections.\n attribute :login_unix_socket\n\n # @return [String, nil] PostgreSQL privileges string in the format: C(table:priv1,priv2).\n attribute :priv\n validates :priv, type: String\n\n # @return [:\"[NO]SUPERUSER\", :\"[NO]CREATEROLE\", :\"[NO]CREATEDB\", :\"[NO]INHERIT\", :\"[NO]LOGIN\", :\"[NO]REPLICATION\", :\"[NO]BYPASSRLS\", nil] PostgreSQL role attributes string in the format: CREATEDB,CREATEROLE,SUPERUSER.,Note that '[NO]CREATEUSER' is deprecated.\n attribute :role_attr_flags\n validates :role_attr_flags, expression_inclusion: {:in=>[:\"[NO]SUPERUSER\", :\"[NO]CREATEROLE\", :\"[NO]CREATEDB\", :\"[NO]INHERIT\", :\"[NO]LOGIN\", :\"[NO]REPLICATION\", :\"[NO]BYPASSRLS\"], :message=>\"%{value} needs to be :\\\"[NO]SUPERUSER\\\", :\\\"[NO]CREATEROLE\\\", :\\\"[NO]CREATEDB\\\", :\\\"[NO]INHERIT\\\", :\\\"[NO]LOGIN\\\", :\\\"[NO]REPLICATION\\\", :\\\"[NO]BYPASSRLS\\\"\"}, allow_nil: true\n\n # @return [:present, :absent, nil] The user (role) state.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Whether the password is stored hashed in the database. Passwords can be passed already hashed or unhashed, and postgresql ensures the stored password is hashed when C(encrypted) is set.,Note: Postgresql 10 and newer doesn't support unhashed passwords.,Previous to Ansible 2.6, this was C(no) by default.\n attribute :encrypted\n validates :encrypted, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] The date at which the user's password is to expire.,If set to C('infinity'), user's password never expire.,Note that this value should be a valid SQL date and time type.\n attribute :expires\n validates :expires, type: String\n\n # @return [:yes, :no, nil] If C(yes), don't inspect database for password changes. Effective when C(pg_authid) is not accessible (such as AWS RDS). Otherwise, make password changes as necessary.\n attribute :no_password_changes\n validates :no_password_changes, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:disable, :allow, :prefer, :require, :\"verify-ca\", :\"verify-full\", nil] Determines whether or with what priority a secure SSL TCP/IP connection will be negotiated with the server.,See U(https://www.postgresql.org/docs/current/static/libpq-ssl.html) for more information on the modes.,Default of C(prefer) matches libpq default.\n attribute :ssl_mode\n validates :ssl_mode, expression_inclusion: {:in=>[:disable, :allow, :prefer, :require, :\"verify-ca\", :\"verify-full\"], :message=>\"%{value} needs to be :disable, :allow, :prefer, :require, :\\\"verify-ca\\\", :\\\"verify-full\\\"\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the name of a file containing SSL certificate authority (CA) certificate(s). If the file exists, the server's certificate will be verified to be signed by one of these authorities.\n attribute :ssl_rootcert\n\n # @return [Object, nil] Specifies the user connection limit.\n attribute :conn_limit\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7126099467277527, "alphanum_fraction": 0.7126099467277527, "avg_line_length": 55.83333206176758, "blob_id": "0f7f40652d864a15398e9817d698d6dcaac02574", "content_id": "94d3c68ff16ca64c057c72a81978ef3bc3018762", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1364, "license_type": "permissive", "max_line_length": 330, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigiq_regkey_pool.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages registration key (regkey) pools on a BIG-IQ. These pools function as a container in-which you will add lists of registration keys. To add registration keys, use the C(bigiq_regkey_license) module.\n class Bigiq_regkey_pool < Base\n # @return [String] Specifies the name of the registration key pool.,You must be mindful to name your registration pools unique names. While BIG-IQ does not require this, this module does. If you do not do this, the behavior of the module is undefined and you may end up putting licenses in the wrong registration key pool.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] A description to attach to the pool.\n attribute :description\n\n # @return [:absent, :present, nil] The state of the regkey pool on the system.,When C(present), guarantees that the pool exists.,When C(absent), removes the pool, and the licenses it contains, from the system.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6642282605171204, "alphanum_fraction": 0.6681297421455383, "avg_line_length": 72.23213958740234, "blob_id": "6058e1320f2890abfa6c632ece9ab9b641685f18", "content_id": "628c97d8a2dfe4ef451dd594118dab131b82d8c0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4101, "license_type": "permissive", "max_line_length": 365, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/system/parted.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows configuring block device partition using the C(parted) command line tool. For a full description of the fields and the options check the GNU parted manual.\n class Parted < Base\n # @return [String] The block device (disk) where to operate.\n attribute :device\n validates :device, presence: true, type: String\n\n # @return [:none, :cylinder, :minimal, :optimal, nil] Set alignment for newly created partitions.\n attribute :align\n validates :align, expression_inclusion: {:in=>[:none, :cylinder, :minimal, :optimal], :message=>\"%{value} needs to be :none, :cylinder, :minimal, :optimal\"}, allow_nil: true\n\n # @return [Integer, String, nil] The number of the partition to work with or the number of the partition that will be created. Required when performing any action on the disk, except fetching information.\n attribute :number\n validates :number, type: MultipleTypes.new(Integer, String)\n\n # @return [:s, :B, :KB, :KiB, :MB, :MiB, :GB, :GiB, :TB, :TiB, :%, :cyl, :chs, :compact, nil] Selects the current default unit that Parted will use to display locations and capacities on the disk and to interpret those given by the user if they are not suffixed by an unit. When fetching information about a disk, it is always recommended to specify a unit.\n attribute :unit\n validates :unit, expression_inclusion: {:in=>[:s, :B, :KB, :KiB, :MB, :MiB, :GB, :GiB, :TB, :TiB, :%, :cyl, :chs, :compact], :message=>\"%{value} needs to be :s, :B, :KB, :KiB, :MB, :MiB, :GB, :GiB, :TB, :TiB, :%, :cyl, :chs, :compact\"}, allow_nil: true\n\n # @return [:aix, :amiga, :bsd, :dvh, :gpt, :loop, :mac, :msdos, :pc98, :sun, nil] Creates a new disk label.\n attribute :label\n validates :label, expression_inclusion: {:in=>[:aix, :amiga, :bsd, :dvh, :gpt, :loop, :mac, :msdos, :pc98, :sun], :message=>\"%{value} needs to be :aix, :amiga, :bsd, :dvh, :gpt, :loop, :mac, :msdos, :pc98, :sun\"}, allow_nil: true\n\n # @return [:primary, :extended, :logical, nil] Is one of 'primary', 'extended' or 'logical' and may be specified only with 'msdos' or 'dvh' partition tables. A name must be specified for a 'gpt' partition table. Neither part-type nor name may be used with a 'sun' partition table.\n attribute :part_type\n validates :part_type, expression_inclusion: {:in=>[:primary, :extended, :logical], :message=>\"%{value} needs to be :primary, :extended, :logical\"}, allow_nil: true\n\n # @return [String, nil] Where the partition will start as offset from the beginning of the disk, that is, the \"distance\" from the start of the disk. The distance can be specified with all the units supported by parted (except compat) and it is case sensitive. E.g. C(10GiB), C(15%).\n attribute :part_start\n validates :part_start, type: String\n\n # @return [String, nil] Where the partition will end as offset from the beginning of the disk, that is, the \"distance\" from the start of the disk. The distance can be specified with all the units supported by parted (except compat) and it is case sensitive. E.g. C(10GiB), C(15%).\n attribute :part_end\n validates :part_end, type: String\n\n # @return [Object, nil] Sets the name for the partition number (GPT, Mac, MIPS and PC98 only).\n attribute :name\n\n # @return [Array<String>, String, nil] A list of the flags that has to be set on the partition.\n attribute :flags\n validates :flags, type: TypeGeneric.new(String)\n\n # @return [:present, :absent, :info, nil] If to create or delete a partition. If set to C(info) the module will only return the device information.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :info], :message=>\"%{value} needs to be :present, :absent, :info\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7249146699905396, "alphanum_fraction": 0.7249146699905396, "avg_line_length": 60.04166793823242, "blob_id": "a2b7f8c484e99ccae16bfa8972161966376ba32c", "content_id": "388ad6f6b76e03d79ed7d1a36191c44a9ca0938d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1465, "license_type": "permissive", "max_line_length": 290, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/utilities/logic/set_fact.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows setting new variables. Variables are set on a host-by-host basis just like facts discovered by the setup module.\n # These variables will be available to subsequent plays during an ansible-playbook run, but will not be saved across executions even if you use a fact cache.\n # Per the standard Ansible variable precedence rules, many other types of variables have a higher priority, so this value may be overridden. See L(Variable Precedence Guide,../user_guide/playbooks_variables.html#variable-precedence-where-should-i-put-a-variable) for more information.\n # This module is also supported for Windows targets.\n class Set_fact < Base\n # @return [Object] The C(set_fact) module takes key=value pairs as variables to set in the playbook scope. Or alternatively, accepts complex arguments using the C(args:) statement.\n attribute :key_value\n validates :key_value, presence: true\n\n # @return [:yes, :no, nil] This boolean indicates if the facts set will also be added to the fact cache, if fact caching is enabled.\n attribute :cacheable\n validates :cacheable, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6722517609596252, "alphanum_fraction": 0.6722517609596252, "avg_line_length": 45.1698112487793, "blob_id": "577efabc957e9e4091af0ae19aa64b9d20308ffc", "content_id": "19d3c40c9a012c9ddc5279e3e7257f306cb75311", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2447, "license_type": "permissive", "max_line_length": 218, "num_lines": 53, "path": "/lib/ansible/ruby/modules/generated/clustering/consul_acl.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows the addition, modification and deletion of ACL keys and associated rules in a consul cluster via the agent. For more details on using and configuring ACLs, see https://www.consul.io/docs/guides/acl.html.\n class Consul_acl < Base\n # @return [String, nil] a management token is required to manipulate the acl lists\n attribute :mgmt_token\n validates :mgmt_token, type: String\n\n # @return [:present, :absent, nil] whether the ACL pair should be present or absent\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:client, :management, nil] the type of token that should be created, either management or client\n attribute :token_type\n validates :token_type, expression_inclusion: {:in=>[:client, :management], :message=>\"%{value} needs to be :client, :management\"}, allow_nil: true\n\n # @return [String, nil] the name that should be associated with the acl key, this is opaque to Consul\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] the token key indentifying an ACL rule set. If generated by consul this will be a UUID\n attribute :token\n validates :token, type: String\n\n # @return [Array<Hash>, Hash, nil] a list of the rules that should be associated with a given token\n attribute :rules\n validates :rules, type: TypeGeneric.new(Hash)\n\n # @return [String, nil] host of the consul agent defaults to localhost\n attribute :host\n validates :host, type: String\n\n # @return [Integer, nil] the port on which the consul agent is running\n attribute :port\n validates :port, type: Integer\n\n # @return [String, nil] the protocol scheme on which the consul agent is running\n attribute :scheme\n validates :scheme, type: String\n\n # @return [Boolean, nil] whether to verify the tls certificate of the consul agent\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7055050730705261, "alphanum_fraction": 0.7124532461166382, "avg_line_length": 55.69696807861328, "blob_id": "2a684504f4b020ab93d4d9a6c4253a8320255fc9", "content_id": "fa99584e245e475040f15dd7f0097f1a7075d239", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1871, "license_type": "permissive", "max_line_length": 262, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_rollback.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module offers the ability to set a configuration checkpoint file or rollback to a configuration checkpoint file on HUAWEI CloudEngine switches.\n class Ce_rollback < Base\n # @return [Integer, nil] Specifies the label of the configuration rollback point to which system configurations are expected to roll back. The value is an integer that the system generates automatically.\n attribute :commit_id\n validates :commit_id, type: Integer\n\n # @return [Object, nil] Specifies a user label for a configuration rollback point. The value is a string of 1 to 256 case-sensitive ASCII characters, spaces not supported. The value must start with a letter and cannot be presented in a single hyphen (-).\n attribute :label\n\n # @return [Object, nil] Specifies a configuration file for configuration rollback. The value is a string of 5 to 64 case-sensitive characters in the format of *.zip, *.cfg, or *.dat, spaces not supported.\n attribute :filename\n\n # @return [Object, nil] Specifies the number of configuration rollback points. The value is an integer that ranges from 1 to 80.\n attribute :last\n\n # @return [Object, nil] Specifies the number of configuration rollback points. The value is an integer that ranges from 1 to 80.\n attribute :oldest\n\n # @return [:rollback, :clear, :set, :display, :commit] The operation of configuration rollback.\n attribute :action\n validates :action, presence: true, expression_inclusion: {:in=>[:rollback, :clear, :set, :display, :commit], :message=>\"%{value} needs to be :rollback, :clear, :set, :display, :commit\"}\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6795841455459595, "alphanum_fraction": 0.6795841455459595, "avg_line_length": 34.266666412353516, "blob_id": "2c7575fdbc66181df1d8f3a9329335626666bd8b", "content_id": "b680cf09a5503f19fb83cce39f81ebdff8a2749e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1058, "license_type": "permissive", "max_line_length": 87, "num_lines": 30, "path": "/lib/ansible/ruby/modules/generated/network/panos/panos_admpwd.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Change the admin password of PAN-OS via SSH using a SSH key for authentication.\n # Useful for AWS instances where the first login should be done via SSH.\n class Panos_admpwd < Base\n # @return [String] IP address (or hostname) of PAN-OS device\n attribute :ip_address\n validates :ip_address, presence: true, type: String\n\n # @return [String, nil] username for initial authentication\n attribute :username\n validates :username, type: String\n\n # @return [String] filename of the SSH Key to use for authentication\n attribute :key_filename\n validates :key_filename, presence: true, type: String\n\n # @return [String] password to configure for admin on the PAN-OS device\n attribute :newpassword\n validates :newpassword, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6953339576721191, "alphanum_fraction": 0.6953339576721191, "avg_line_length": 44.54166793823242, "blob_id": "7cd4997cd06c7920557b0cd0286838f6e1d89a82", "content_id": "1ce3fb0f4756a5f4a4f219db22aeffd730cfd306", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1093, "license_type": "permissive", "max_line_length": 292, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_host_storage_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Retrieve facts about one or more oVirt/RHV HostStorages (applicable only for block storage).\n class Ovirt_host_storage_facts < Base\n # @return [String] Host to get device list from.\n attribute :host\n validates :host, presence: true, type: String\n\n # @return [Hash, nil] Dictionary with values for iSCSI storage type:,C(address) - Address of the iSCSI storage server.,C(target) - The target IQN for the storage device.,C(username) - A CHAP user name for logging into a target.,C(password) - A CHAP password for logging into a target.\n attribute :iscsi\n validates :iscsi, type: Hash\n\n # @return [Object, nil] Dictionary with values for fibre channel storage type:,C(address) - Address of the fibre channel storage server.,C(port) - Port of the fibre channel storage server.,C(lun_id) - LUN id.\n attribute :fcp\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7048766016960144, "alphanum_fraction": 0.7145910263061523, "avg_line_length": 72.52857208251953, "blob_id": "c9c066cc58bc1b11ee4c19d1919b069cf0855962", "content_id": "cc9c906ef98b495c8816d1bc6486c7655b580651", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5147, "license_type": "permissive", "max_line_length": 520, "num_lines": 70, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_monitor_snmp_dca.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The BIG-IP has an SNMP data collecting agent (DCA) that can query remote SNMP agents of various types, including the UC Davis agent (UCD) and the Windows 2000 Server agent (WIN2000).\n class Bigip_monitor_snmp_dca < Base\n # @return [String] Monitor name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Specifies descriptive text that identifies the monitor.\n attribute :description\n\n # @return [String, nil] The parent template of this monitor template. Once this value has been set, it cannot be changed. By default, this value is the C(snmp_dca) parent on the C(Common) partition.\n attribute :parent\n validates :parent, type: String\n\n # @return [Object, nil] Specifies, in seconds, the frequency at which the system issues the monitor check when either the resource is down or the status of the resource is unknown. When creating a new monitor, the default is C(10).\n attribute :interval\n\n # @return [Object, nil] Specifies the number of seconds the target has in which to respond to the monitor request. When creating a new monitor, the default is C(30) seconds. If the target responds within the set time period, it is considered 'up'. If the target does not respond within the set time period, it is considered 'down'. When this value is set to 0 (zero), the system uses the interval from the parent monitor. Note that C(timeout) and C(time_until_up) combine to control when a resource is set to up.\n attribute :timeout\n\n # @return [Object, nil] Specifies the number of seconds to wait after a resource first responds correctly to the monitor before setting the resource to 'up'. During the interval, all responses from the resource must be correct. When the interval expires, the resource is marked 'up'. A value of 0, means that the resource is marked up immediately upon receipt of the first correct response. When creating a new monitor, the default is C(0).\n attribute :time_until_up\n\n # @return [Object, nil] Specifies the community name that the system must use to authenticate with the host server through SNMP. When creating a new monitor, the default value is C(public). Note that this value is case sensitive.\n attribute :community\n\n # @return [:v1, :v2c, nil] Specifies the version of SNMP that the host server uses. When creating a new monitor, the default is C(v1). When C(v1), specifies that the host server uses SNMP version 1. When C(v2c), specifies that the host server uses SNMP version 2c.\n attribute :version\n validates :version, expression_inclusion: {:in=>[:v1, :v2c], :message=>\"%{value} needs to be :v1, :v2c\"}, allow_nil: true\n\n # @return [:UCD, :WIN2000, :GENERIC, nil] Specifies the SNMP agent running on the monitored server. When creating a new monitor, the default is C(UCD) (UC-Davis).\n attribute :agent_type\n validates :agent_type, expression_inclusion: {:in=>[:UCD, :WIN2000, :GENERIC], :message=>\"%{value} needs to be :UCD, :WIN2000, :GENERIC\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the coefficient that the system uses to calculate the weight of the CPU threshold in the dynamic ratio load balancing algorithm. When creating a new monitor, the default is C(1.5).\n attribute :cpu_coefficient\n\n # @return [Object, nil] Specifies the maximum acceptable CPU usage on the target server. When creating a new monitor, the default is C(80) percent.\n attribute :cpu_threshold\n\n # @return [Object, nil] Specifies the coefficient that the system uses to calculate the weight of the memory threshold in the dynamic ratio load balancing algorithm. When creating a new monitor, the default is C(1.0).\n attribute :memory_coefficient\n\n # @return [Object, nil] Specifies the maximum acceptable memory usage on the target server. When creating a new monitor, the default is C(70) percent.\n attribute :memory_threshold\n\n # @return [Object, nil] Specifies the coefficient that the system uses to calculate the weight of the disk threshold in the dynamic ratio load balancing algorithm. When creating a new monitor, the default is C(2.0).\n attribute :disk_coefficient\n\n # @return [Object, nil] Specifies the maximum acceptable disk usage on the target server. When creating a new monitor, the default is C(90) percent.\n attribute :disk_threshold\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [:present, :absent, nil] When C(present), ensures that the monitor exists.,When C(absent), ensures the monitor is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6951934099197388, "alphanum_fraction": 0.7045720815658569, "avg_line_length": 46.38888931274414, "blob_id": "d16988b45e55b3428f4d1f3af2af90fae400eb6d", "content_id": "d9e1140a5885a9f370e32eea9905dbc6c51164af", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1706, "license_type": "permissive", "max_line_length": 266, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/sts_assume_role.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Assume a role using AWS Security Token Service and obtain temporary credentials\n class Sts_assume_role < Base\n # @return [Object] The Amazon Resource Name (ARN) of the role that the caller is assuming (http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html#Identifiers_ARNs)\n attribute :role_arn\n validates :role_arn, presence: true\n\n # @return [Object] Name of the role's session - will be used by CloudTrail\n attribute :role_session_name\n validates :role_session_name, presence: true\n\n # @return [Object, nil] Supplemental policy to use in addition to assumed role's policies.\n attribute :policy\n\n # @return [Object, nil] The duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) to 43200 seconds (12 hours). The max dependis on the IAM role's sessions duration setting. By default, the value is set to 3600 seconds.s\n attribute :duration_seconds\n\n # @return [Object, nil] A unique identifier that is used by third parties to assume a role in their customers' accounts.\n attribute :external_id\n\n # @return [Object, nil] The identification number of the MFA device that is associated with the user who is making the AssumeRole call.\n attribute :mfa_serial_number\n\n # @return [Object, nil] The value provided by the MFA device, if the trust policy of the role being assumed requires MFA.\n attribute :mfa_token\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7416440844535828, "alphanum_fraction": 0.7429990768432617, "avg_line_length": 78.07142639160156, "blob_id": "756da2026a14ea59f2a2674207dae949c7a94f6e", "content_id": "6c21eea6ff7d5d882a77812242af3218934677f3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2214, "license_type": "permissive", "max_line_length": 941, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/windows/win_dsc.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configures a resource using PowerShell DSC.\n # Requires PowerShell version 5.0 or newer.\n # Most of the options for this module are dynamic and will vary depending on the DSC Resource specified in I(resource_name).\n # See :doc:`/user_guide/windows_dsc` for more information on how to use this module.\n class Win_dsc < Base\n # @return [String] The name of the DSC Resource to use.,Must be accessible to PowerShell using any of the default paths.\n attribute :resource_name\n validates :resource_name, presence: true, type: String\n\n # @return [String, nil] Can be used to configure the exact version of the DSC resource to be invoked.,Useful if the target node has multiple versions installed of the module containing the DSC resource.,If not specified, the module will follow standard PowerShell convention and use the highest version available.\n attribute :module_version\n validates :module_version, type: String\n\n # @return [Object] The M(win_dsc) module takes in multiple free form options based on the DSC resource being invoked by I(resource_name).,There is no option actually named C(free_form) so see the examples.,This module will try and convert the option to the correct type required by the DSC resource and throw a warning if it fails.,If the type of the DSC resource option is a C(CimInstance) or C(CimInstance[]), this means the value should be a dictionary or list of dictionaries based on the values required by that option.,If the type of the DSC resource option is a C(PSCredential) then there needs to be 2 options set in the Ansible task definition suffixed with C(_username) and C(_password).,If the type of the DSC resource option is an array, then a list should be provided but a comma separated string also work. Use a list where possible as no escaping is required and it works with more complex types list C(CimInstance[]).\n attribute :free_form\n validates :free_form, presence: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6782061457633972, "alphanum_fraction": 0.6782061457633972, "avg_line_length": 42.82758712768555, "blob_id": "cb7ce1d6a82b11e135285ceba43163c120a2d095", "content_id": "d37d71e5974c5f97b0fe823b9d5b00d1f4355f01", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1271, "license_type": "permissive", "max_line_length": 163, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/centurylink/clc_server_snapshot.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # An Ansible module to Create, Delete and Restore server snapshots in CenturyLink Cloud.\n class Clc_server_snapshot < Base\n # @return [Array<String>, String] The list of CLC server Ids.\n attribute :server_ids\n validates :server_ids, presence: true, type: TypeGeneric.new(String)\n\n # @return [Integer, nil] The number of days to keep the server snapshot before it expires.\n attribute :expiration_days\n validates :expiration_days, type: Integer\n\n # @return [:present, :absent, :restore, nil] The state to insure that the provided resources are in.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :restore], :message=>\"%{value} needs to be :present, :absent, :restore\"}, allow_nil: true\n\n # @return [Boolean, nil] Whether to wait for the provisioning tasks to finish before returning.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.666383683681488, "alphanum_fraction": 0.666383683681488, "avg_line_length": 39.620689392089844, "blob_id": "990c9b0de30eab9b2f9a9786abfe4d2e444174ac", "content_id": "f60ec71ba3a879100e8d3305dd21dfe122461dcc", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1178, "license_type": "permissive", "max_line_length": 163, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/iam_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage AWS IAM users\n class Iam_user < Base\n # @return [String] The name of the user to create.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Array<String>, String, nil] A list of managed policy ARNs or friendly names to attach to the user. To embed an inline policy, use M(iam_policy).\n attribute :managed_policy\n validates :managed_policy, type: TypeGeneric.new(String)\n\n # @return [:present, :absent] Create or remove the IAM user\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [Boolean, nil] Detach policies which are not included in managed_policy list\n attribute :purge_policy\n validates :purge_policy, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6498801112174988, "alphanum_fraction": 0.6498801112174988, "avg_line_length": 38.71428680419922, "blob_id": "61da9327238e9c459c20f012e6cb86038d56e222", "content_id": "e2f3583aa28d4427ccec70cc9b49c8adb5cd513d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1668, "license_type": "permissive", "max_line_length": 207, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_router.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Start, restart, stop and destroy routers.\n # C(state=present) is not able to create routers, use M(cs_network) instead.\n class Cs_router < Base\n # @return [String] Name of the router.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Name or id of the service offering of the router.\n attribute :service_offering\n validates :service_offering, type: String\n\n # @return [Object, nil] Domain the router is related to.\n attribute :domain\n\n # @return [Object, nil] Account the router is related to.\n attribute :account\n\n # @return [Object, nil] Name of the project the router is related to.\n attribute :project\n\n # @return [Object, nil] Name of the zone the router is deployed in.,If not set, all zones are used.\n attribute :zone\n\n # @return [:present, :absent, :started, :stopped, :restarted, nil] State of the router.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :started, :stopped, :restarted], :message=>\"%{value} needs to be :present, :absent, :started, :stopped, :restarted\"}, allow_nil: true\n\n # @return [Boolean, nil] Poll async jobs until job has finished.\n attribute :poll_async\n validates :poll_async, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6677389740943909, "alphanum_fraction": 0.6847426295280457, "avg_line_length": 47.35555648803711, "blob_id": "bd1cadc1a6bbcc7f3e223ea9689665d136571140", "content_id": "79221c690211d9a102ed69d0ca49bd46c0733d69", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2176, "license_type": "permissive", "max_line_length": 333, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_mlag_config.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages MLAG configuration on HUAWEI CloudEngine switches.\n class Ce_mlag_config < Base\n # @return [String, nil] ID of a DFS group. The value is 1.\n attribute :dfs_group_id\n validates :dfs_group_id, type: String\n\n # @return [Object, nil] The nickname bound to a DFS group. The value is an integer that ranges from 1 to 65471.\n attribute :nickname\n\n # @return [Object, nil] A pseudo nickname of a DFS group. The value is an integer that ranges from 1 to 65471.\n attribute :pseudo_nickname\n\n # @return [Object, nil] The priority of a pseudo nickname. The value is an integer that ranges from 128 to 255. The default value is 192. A larger value indicates a higher priority.\n attribute :pseudo_priority\n\n # @return [Object, nil] IP address bound to the DFS group. The value is in dotted decimal notation.\n attribute :ip_address\n\n # @return [Object, nil] Name of the VPN instance bound to the DFS group. The value is a string of 1 to 31 case-sensitive characters without spaces. If the character string is quoted by double quotation marks, the character string can contain spaces. The value _public_ is reserved and cannot be used as the VPN instance name.\n attribute :vpn_instance_name\n\n # @return [Object, nil] Priority of a DFS group. The value is an integer that ranges from 1 to 254. The default value is 100.\n attribute :priority_id\n\n # @return [Object, nil] Name of the peer-link interface. The value is in the range from 0 to 511.\n attribute :eth_trunk_id\n\n # @return [Object, nil] Number of the peer-link interface. The value is 1.\n attribute :peer_link_id\n\n # @return [:present, :absent, nil] Specify desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6622516512870789, "alphanum_fraction": 0.6622516512870789, "avg_line_length": 51.849998474121094, "blob_id": "52b2e9243051311c8264b35d54605eb56b08f1ce", "content_id": "58dfe77ce2c718d3a2e4afc033676e3946111847", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2114, "license_type": "permissive", "max_line_length": 263, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/network/opx/opx_cps.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Executes the given operation on the YANG object, using CPS API in the networking device running OpenSwitch (OPX). It uses the YANG models provided in https://github.com/open-switch/opx-base-model.\n class Opx_cps < Base\n # @return [String, nil] Yang path to be configured.\n attribute :module_name\n validates :module_name, type: String\n\n # @return [Object, nil] Attribute Yang type.\n attribute :attr_type\n\n # @return [Hash, nil] Attribute Yang path and their corresponding data.\n attribute :attr_data\n validates :attr_data, type: Hash\n\n # @return [:delete, :create, :set, :action, :get, nil] Operation to be performed on the object.\n attribute :operation\n validates :operation, expression_inclusion: {:in=>[:delete, :create, :set, :action, :get], :message=>\"%{value} needs to be :delete, :create, :set, :action, :get\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Queries/Writes the specified yang path from/to the db.\n attribute :db\n validates :db, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:target, :observed, :proposed, :realtime, :registration, :running, :startup, nil] A qualifier provides the type of object data to retrieve or act on.\n attribute :qualifier\n validates :qualifier, expression_inclusion: {:in=>[:target, :observed, :proposed, :realtime, :registration, :running, :startup], :message=>\"%{value} needs to be :target, :observed, :proposed, :realtime, :registration, :running, :startup\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Attempts to force the auto-commit event to the specified yang object.\n attribute :commit_event\n validates :commit_event, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.502636194229126, "alphanum_fraction": 0.5079085826873779, "avg_line_length": 26.095237731933594, "blob_id": "9dc83ec35846e7f7b7429b38efb5d35e6edfbbc0", "content_id": "2e57657415536e9b9bbb9d4e7036ac26546a2479", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1138, "license_type": "permissive", "max_line_length": 84, "num_lines": 42, "path": "/lib/ansible/ruby/models/inclusion_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# see LICENSE.txt in project root\nrequire 'spec_helper'\n\ndescribe Ansible::Ruby::Models::Inclusion do\n describe '#to_h' do\n subject(:hash) { instance.to_h }\n\n context 'basic' do\n let(:instance) { Ansible::Ruby::Models::Inclusion.new file: '/something.yml' }\n\n it { is_expected.to eq include: '/something.yml' }\n end\n\n context 'static with variables' do\n let(:instance) do\n Ansible::Ruby::Models::Inclusion.new file: '/something.yml',\n static: true,\n variables: { stuff: 123 }\n end\n\n it do\n is_expected.to eq include: '/something.yml',\n static: true,\n vars: { stuff: 123 }\n end\n end\n\n context 'static false' do\n let(:instance) do\n Ansible::Ruby::Models::Inclusion.new file: '/something.yml',\n static: false\n end\n\n it do\n is_expected.to eq include: '/something.yml',\n static: false\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6575742959976196, "alphanum_fraction": 0.6575742959976196, "avg_line_length": 41.77083206176758, "blob_id": "59d56653875d78b0372a7a715d88cf218595e1f0", "content_id": "4caf26a0e2e388cfe2c615e98afb44c110130797", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2053, "license_type": "permissive", "max_line_length": 185, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_ssm_parameter_store.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage key-value pairs in aws parameter store.\n class Aws_ssm_parameter_store < Base\n # @return [String] parameter key name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] parameter key desciption.\n attribute :description\n validates :description, type: String\n\n # @return [String, nil] Parameter value.\n attribute :value\n validates :value, type: String\n\n # @return [:present, :absent, nil] Creates or modifies an existing parameter,Deletes a parameter\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:String, :StringList, :SecureString, nil] Parameter String type\n attribute :string_type\n validates :string_type, expression_inclusion: {:in=>[:String, :StringList, :SecureString], :message=>\"%{value} needs to be :String, :StringList, :SecureString\"}, allow_nil: true\n\n # @return [Boolean, nil] Work with SecureString type to get plain text secrets,Boolean\n attribute :decryption\n validates :decryption, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] aws KMS key to decrypt the secrets.\n attribute :key_id\n validates :key_id, type: String\n\n # @return [:never, :changed, :always, nil] Option to overwrite an existing value if it already exists.,String\n attribute :overwrite_value\n validates :overwrite_value, expression_inclusion: {:in=>[:never, :changed, :always], :message=>\"%{value} needs to be :never, :changed, :always\"}, allow_nil: true\n\n # @return [Object, nil] region.\n attribute :region\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6353919506072998, "alphanum_fraction": 0.6353919506072998, "avg_line_length": 29.071428298950195, "blob_id": "55f0b8129a494ab68224980c829593179f44c1b5", "content_id": "6679cea8291e08a4911e847acf98e19e7c1f96d0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 842, "license_type": "permissive", "max_line_length": 143, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/monitoring/logentries.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Sends logs to LogEntries in realtime\n class Logentries < Base\n # @return [String] path to a log file\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [:present, :absent, nil] following state of the log\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] name of the log\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] type of the log\n attribute :logtype\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7260468602180481, "alphanum_fraction": 0.7260468602180481, "avg_line_length": 67.73170471191406, "blob_id": "7ef044ce3d5a0baf0bfd30666c8c4f02cbca0cae", "content_id": "15a0272a7b09a1268413df39a7d437009706ee04", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2818, "license_type": "permissive", "max_line_length": 451, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcpubsub.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create and Delete Topics/Subscriptions, Publish and pull messages on PubSub. See U(https://cloud.google.com/pubsub/docs) for an overview.\n class Gcpubsub < Base\n # @return [String] GCP pubsub topic name.,Only the name, not the full path, is required.\n attribute :topic\n validates :topic, presence: true, type: String\n\n # @return [Array<Hash>, Hash, nil] Dictionary containing a subscripton name associated with a topic (required), along with optional ack_deadline, push_endpoint and pull. For pulling from a subscription, message_ack (bool), max_messages (int) and return_immediate are available as subfields. See subfields name, push_endpoint and ack_deadline for more information.\n attribute :subscription\n validates :subscription, type: TypeGeneric.new(Hash)\n\n # @return [Object, nil] Subfield of subscription. Required if subscription is specified. See examples.\n attribute :name\n\n # @return [Object, nil] Subfield of subscription. Not required. Default deadline for subscriptions to ACK the message before it is resent. See examples.\n attribute :ack_deadline\n\n # @return [Object, nil] Subfield of subscription. Not required. If specified, messages will be retrieved from topic via the provided subscription name. max_messages (int; default None; max number of messages to pull), message_ack (bool; default False; acknowledge the message) and return_immediately (bool; default True, don't wait for messages to appear). If the messages are acknowledged, changed is set to True, otherwise, changed is False.\n attribute :pull\n\n # @return [Object, nil] Subfield of subscription. Not required. If specified, message will be sent to an endpoint. See U(https://cloud.google.com/pubsub/docs/advanced#push_endpoints) for more information.\n attribute :push_endpoint\n\n # @return [Array<Hash>, Hash, nil] List of dictionaries describing messages and attributes to be published. Dictionary is in message(str):attributes(dict) format. Only message is required.\n attribute :publish\n validates :publish, type: TypeGeneric.new(Hash)\n\n # @return [:absent, :present, nil] State of the topic or queue.,Applies to the most granular resource.,If subscription isspecified we remove it.,If only topic is specified, that is what is removed.,NOTE - A topic can be removed without first removing the subscription.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6907029747962952, "alphanum_fraction": 0.6975056529045105, "avg_line_length": 51.5, "blob_id": "0001f70ebb14c488f9a520034b5d29e7d664ed06", "content_id": "deb4ff0a17269f4089911ef3483290e72c4213bd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2205, "license_type": "permissive", "max_line_length": 375, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_compute_instance_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Represents an Instance Group resource. Instance groups are self-managed and can contain identical or different instances. Instance groups do not use an instance template. Unlike managed instance groups, you must create and add instances to an instance group manually.\n class Gcp_compute_instance_group < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] An optional description of this resource. Provide this property when you create the resource.\n attribute :description\n\n # @return [String, nil] The name of the instance group.,The name must be 1-63 characters long, and comply with RFC1035.\n attribute :name\n validates :name, type: String\n\n # @return [Array<Hash>, Hash, nil] Assigns a name to a port number.,For example: {name: \"http\", port: 80}.,This allows the system to reference ports by the assigned name instead of a port number. Named ports can also contain multiple ports.,For example: [{name: \"http\", port: 80},{name: \"http\", port: 8080}] Named ports apply to all instances in this instance group.\n attribute :named_ports\n validates :named_ports, type: TypeGeneric.new(Hash)\n\n # @return [String, nil] The network to which all instances in the instance group belong.\n attribute :network\n validates :network, type: String\n\n # @return [Object, nil] The region where the instance group is located (for regional resources).\n attribute :region\n\n # @return [Object, nil] The subnetwork to which all instances in the instance group belong.\n attribute :subnetwork\n\n # @return [String] A reference to the zone where the instance group resides.\n attribute :zone\n validates :zone, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7119008898735046, "alphanum_fraction": 0.7119008898735046, "avg_line_length": 55.272727966308594, "blob_id": "5f4720ff26550f73b457ae0d08731e0545c21359", "content_id": "8314bd09dbcfd8f4ec177db972969dcbe652b16c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1857, "license_type": "permissive", "max_line_length": 386, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/network/cli/cli_command.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Sends a command to a network device and returns the result read from the device.\n class Cli_command < Base\n # @return [String] The command to send to the remote network device. The resulting output from the command is returned, unless I(sendonly) is set.\n attribute :command\n validates :command, presence: true, type: String\n\n # @return [Array<String>, String, nil] A single regex pattern or a sequence of patterns to evaluate the expected prompt from I(command).\n attribute :prompt\n validates :prompt, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] The answer to reply with if I(prompt) is matched. The value can be a single answer or a list of answer for multiple prompts. In case the command execution results in multiple prompts the sequence of the prompt and excepted answer should be in same order.\n attribute :answer\n validates :answer, type: TypeGeneric.new(String)\n\n # @return [Symbol, nil] The boolean value, that when set to true will send I(command) to the device but not wait for a result.\n attribute :sendonly\n validates :sendonly, type: Symbol\n\n # @return [Symbol, nil] By default if any one of the prompts mentioned in C(prompt) option is matched it won't check for other prompts. This boolean flag, that when set to I(True) will check for all the prompts mentioned in C(prompt) option in the given order. If the option is set to I(True) all the prompts should be received from remote host if not it will result in timeout.\n attribute :check_all\n validates :check_all, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7118857502937317, "alphanum_fraction": 0.7118857502937317, "avg_line_length": 65.13888549804688, "blob_id": "87a55501a5f50bf3b8134000ad238d0c1b7e831e", "content_id": "b73f51be8ccbbab1543422f4b3a2d067fcdece3e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2381, "license_type": "permissive", "max_line_length": 552, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_storage_bucket_access_control.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The BucketAccessControls resource represents the Access Control Lists (ACLs) for buckets within Google Cloud Storage. ACLs let you specify who has access to your data and to what extent.\n # There are three roles that can be assigned to an entity: READERs can get the bucket, though no acl property will be returned, and list the bucket's objects. WRITERs are READERs, and they can insert objects into the bucket and delete the bucket's objects. OWNERs are WRITERs, and they can get the acl property of a bucket, update a bucket, and call all BucketAccessControls methods on the bucket. For more information, see Access Control, with the caveat that this API uses READER, WRITER, and OWNER instead of READ, WRITE, and FULL_CONTROL.\n class Gcp_storage_bucket_access_control < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The name of the bucket.\n attribute :bucket\n validates :bucket, presence: true, type: String\n\n # @return [String] The entity holding the permission, in one of the following forms: user-userId user-email group-groupId group-email domain-domain project-team-projectId allUsers allAuthenticatedUsers Examples: The user [email protected] would be [email protected].,The group [email protected] would be [email protected].,To refer to all members of the Google Apps for Business domain example.com, the entity would be domain-example.com.\n attribute :entity\n validates :entity, presence: true, type: String\n\n # @return [Object, nil] The ID for the entity.\n attribute :entity_id\n\n # @return [Object, nil] The project team associated with the entity.\n attribute :project_team\n\n # @return [:OWNER, :READER, :WRITER, nil] The access permission for the entity.\n attribute :role\n validates :role, expression_inclusion: {:in=>[:OWNER, :READER, :WRITER], :message=>\"%{value} needs to be :OWNER, :READER, :WRITER\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6973461508750916, "alphanum_fraction": 0.6973461508750916, "avg_line_length": 54.34375, "blob_id": "cf08981937981f81a370a771be847aca1339a675", "content_id": "1044368ac784cf782e3f607705e05f3162d97a38", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1771, "license_type": "permissive", "max_line_length": 257, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/netapp_e_lun_mapping.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, delete, or modify mappings between a volume and a targeted host/host+ group.\n class Netapp_e_lun_mapping < Base\n # @return [:present, :absent] Present will ensure the mapping exists, absent will remove the mapping.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String, nil] The name of host or hostgroup you wish to assign to the mapping,If omitted, the default hostgroup is used.,If the supplied I(volume_name) is associated with a different target, it will be updated to what is supplied here.\n attribute :target\n validates :target, type: String\n\n # @return [Object] The name of the volume you wish to include in the mapping.\n attribute :volume_name\n validates :volume_name, presence: true\n\n # @return [Object, nil] The LUN value you wish to give the mapping.,If the supplied I(volume_name) is associated with a different LUN, it will be updated to what is supplied here.,LUN value will be determine by the storage-system when not specified.\n attribute :lun\n\n # @return [:host, :group, nil] This option specifies the whether the target should be a host or a group of hosts,Only necessary when the target name is used for both a host and a group of hosts\n attribute :target_type\n validates :target_type, expression_inclusion: {:in=>[:host, :group], :message=>\"%{value} needs to be :host, :group\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6746506690979004, "alphanum_fraction": 0.6746506690979004, "avg_line_length": 40.75, "blob_id": "a134467571243b74cb5a205ca69321d6ac5bcb53", "content_id": "2ddd5b68bf629d8dea2d6413fedf881b58c627c8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2004, "license_type": "permissive", "max_line_length": 172, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/monitoring/newrelic_deployment.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Notify newrelic about app deployments (see https://docs.newrelic.com/docs/apm/new-relic-apm/maintenance/deployment-notifications#api)\n class Newrelic_deployment < Base\n # @return [String] API token, to place in the x-api-key header.\n attribute :token\n validates :token, presence: true, type: String\n\n # @return [String, nil] (one of app_name or application_id are required) The value of app_name in the newrelic.yml file used by the application\n attribute :app_name\n validates :app_name, type: String\n\n # @return [Object, nil] (one of app_name or application_id are required) The application id, found in the URL when viewing the application in RPM\n attribute :application_id\n\n # @return [Object, nil] A list of changes for this deployment\n attribute :changelog\n\n # @return [Object, nil] Text annotation for the deployment - notes for you\n attribute :description\n\n # @return [String, nil] A revision number (e.g., git commit SHA)\n attribute :revision\n validates :revision, type: String\n\n # @return [String, nil] The name of the user/process that triggered this deployment\n attribute :user\n validates :user, type: String\n\n # @return [Object, nil] Name of the application\n attribute :appname\n\n # @return [Object, nil] The environment for this deployment\n attribute :environment\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6619537472724915, "alphanum_fraction": 0.6619537472724915, "avg_line_length": 31.41666603088379, "blob_id": "4210221d4f9715f4ff7fc43cea3675b61be60238", "content_id": "8bdb80eca6e93948dfce164717bb4551cd8db2e6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 778, "license_type": "permissive", "max_line_length": 143, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_keystone_role.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage OpenStack Identity Roles.\n class Os_keystone_role < Base\n # @return [String] Role Name\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Should the resource be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.672703742980957, "alphanum_fraction": 0.672703742980957, "avg_line_length": 45.84848403930664, "blob_id": "d4815d20252ca5ac99f32eb9905e94a2f9aca0a1", "content_id": "2cf6cf59ab721725047efc25b07007dfbf0757fc", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1546, "license_type": "permissive", "max_line_length": 370, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/system/group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage presence of groups on a host.\n # For Windows targets, use the M(win_group) module instead.\n class Group < Base\n # @return [String] Name of the group to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Optional I(GID) to set for the group.\n attribute :gid\n\n # @return [:absent, :present, nil] Whether the group should be present or not on the remote host.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If I(yes), indicates that the group created is a system group.\n attribute :system\n validates :system, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Forces the use of \"local\" command alternatives on platforms that implement it. This is useful in environments that use centralized authentification when you want to manipulate the local groups. I.E. it uses `lgroupadd` instead of `useradd`.,This requires that these commands exist on the targeted host, otherwise it will be a fatal error.\n attribute :local\n validates :local, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7021013498306274, "alphanum_fraction": 0.7045735716819763, "avg_line_length": 37.52381134033203, "blob_id": "fd011e0c6a256d7de4c876d820441e6cf53a933c", "content_id": "31bd1f5c542a57860873c0815d0c77c8af9f4d68", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 809, "license_type": "permissive", "max_line_length": 234, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_vpc_igw_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gather facts about internet gateways in AWS.\n class Ec2_vpc_igw_facts < Base\n # @return [Hash, nil] A dict of filters to apply. Each dict item consists of a filter key and a filter value. See U(http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInternetGateways.html) for possible filters.\n attribute :filters\n validates :filters, type: Hash\n\n # @return [String, nil] Get details of specific Internet Gateway ID. Provide this value as a list.\n attribute :internet_gateway_ids\n validates :internet_gateway_ids, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6381404995918274, "alphanum_fraction": 0.6550449132919312, "avg_line_length": 41.06666564941406, "blob_id": "ab8595c970abee3158a5e5a64c6ed1748567d156", "content_id": "895a9382525395946d61f0f7e16e2f3a0516872c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1893, "license_type": "permissive", "max_line_length": 142, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/network/meraki/meraki_snmp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows for management of SNMP settings for Meraki.\n class Meraki_snmp < Base\n # @return [:query, :present, nil] Specifies whether SNMP information should be queried or modified.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:query, :present], :message=>\"%{value} needs to be :query, :present\"}, allow_nil: true\n\n # @return [Symbol, nil] Specifies whether SNMPv2c is enabled.\n attribute :v2c_enabled\n validates :v2c_enabled, type: Symbol\n\n # @return [Symbol, nil] Specifies whether SNMPv3 is enabled.\n attribute :v3_enabled\n validates :v3_enabled, type: Symbol\n\n # @return [:MD5, :SHA, nil] Sets authentication mode for SNMPv3.\n attribute :v3_auth_mode\n validates :v3_auth_mode, expression_inclusion: {:in=>[:MD5, :SHA], :message=>\"%{value} needs to be :MD5, :SHA\"}, allow_nil: true\n\n # @return [String, nil] Authentication password for SNMPv3.,Must be at least 8 characters long.\n attribute :v3_auth_pass\n validates :v3_auth_pass, type: String\n\n # @return [:DES, :AES128, nil] Specifies privacy mode for SNMPv3.\n attribute :v3_priv_mode\n validates :v3_priv_mode, expression_inclusion: {:in=>[:DES, :AES128], :message=>\"%{value} needs to be :DES, :AES128\"}, allow_nil: true\n\n # @return [String, nil] Privacy password for SNMPv3.,Must be at least 8 characters long.\n attribute :v3_priv_pass\n validates :v3_priv_pass, type: String\n\n # @return [String, nil] Semi-colon delimited IP addresses which can perform SNMP queries.\n attribute :peer_ips\n validates :peer_ips, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7309941649436951, "alphanum_fraction": 0.7456140518188477, "avg_line_length": 19.117647171020508, "blob_id": "62a0cbb3bc9c29621f0367e0920bcfa3ce19defb", "content_id": "d9af6c2f3a8ec765b52811c6afcda5ebe21eea53", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 342, "license_type": "permissive", "max_line_length": 66, "num_lines": 17, "path": "/lib/ansible/ruby/modules/custom/commands/raw.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# VALIDATED_CHECKSUM: z5clqX2YhgpxWUV4gzTzqCvTZgjlIrUje9KFJTYgHX4=\n# See LICENSE.txt for license\n\nrequire 'ansible/ruby/modules/free_form'\nrequire 'ansible/ruby/modules/generated/commands/raw'\n\nmodule Ansible\n module Ruby\n module Modules\n class Raw\n include FreeForm\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6374622583389282, "alphanum_fraction": 0.6435045599937439, "avg_line_length": 29.090909957885742, "blob_id": "c1b2f118a55af17509980206ff1b303746fb723e", "content_id": "3058a0e49385049654c8b0421ad3b6eca280b4ac", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 662, "license_type": "permissive", "max_line_length": 101, "num_lines": 22, "path": "/ansible-ruby.gemspec", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n$LOAD_PATH.unshift File.expand_path('lib', __dir__)\nrequire 'ansible/ruby/version'\n\nGem::Specification.new do |s|\n s.name = 'ansible-ruby'\n s.version = Ansible::Ruby::VERSION\n s.author = 'Brady Wied'\n s.email = '[email protected]'\n s.summary = 'A Ruby DSL for Ansible'\n s.description = 'Creates a Ruby DSL that compiles .rb files to Ansible YML on a file by file basis'\n s.homepage = 'https://github.com/wied03/ansible-ruby'\n\n s.files = Dir.glob('lib/**/*.rb')\n .reject { |file| file.end_with?('_spec.rb', '_test.rb') }\n\n s.require_paths = ['lib']\n\n s.add_dependency 'activemodel', '~> 5.0'\n s.add_dependency 'rake'\nend\n" }, { "alpha_fraction": 0.6821640133857727, "alphanum_fraction": 0.6821640133857727, "avg_line_length": 39.7931022644043, "blob_id": "6d568f8f35c572642d5bf47a55e71eb73d268acb", "content_id": "6f447e4c41b3e4d2d1283f742c20d4d538a9c102", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1183, "license_type": "permissive", "max_line_length": 147, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/crypto/openssl_dhparam.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows one to (re)generate OpenSSL DH-params. This module uses file common arguments to specify generated file permissions.\n class Openssl_dhparam < Base\n # @return [:present, :absent, nil] Whether the parameters should exist or not, taking action if the state is different from what is stated.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Integer, nil] Size (in bits) of the generated DH-params\n attribute :size\n validates :size, type: Integer\n\n # @return [Symbol, nil] Should the parameters be regenerated even it it already exists\n attribute :force\n validates :force, type: Symbol\n\n # @return [String] Name of the file in which the generated parameters will be saved.\n attribute :path\n validates :path, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.708710789680481, "alphanum_fraction": 0.708710789680481, "avg_line_length": 61.39130401611328, "blob_id": "f9ff0cc50860d53a44d575a624652d334d26b096", "content_id": "30ef04e3a82ad38224ce24c0a3952aa51273490f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1435, "license_type": "permissive", "max_line_length": 579, "num_lines": 23, "path": "/lib/ansible/ruby/modules/generated/windows/win_file.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates (empty) files, updates file modification stamps of existing files, and can create or remove directories.\n # Unlike M(file), does not modify ownership, permissions or manipulate links.\n # For non-Windows targets, use the M(file) module instead.\n class Win_file < Base\n # @return [String] Path to the file being managed.\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [:absent, :directory, :file, :touch, nil] If C(directory), all immediate subdirectories will be created if they do not exist.,If C(file), the file will NOT be created if it does not exist, see the M(copy) or M(template) module if you want that behavior. If C(absent), directories will be recursively deleted, and files will be removed.,If C(touch), an empty file will be created if the C(path) does not exist, while an existing file or directory will receive updated file access and modification times (similar to the way C(touch) works from the command line).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :directory, :file, :touch], :message=>\"%{value} needs to be :absent, :directory, :file, :touch\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6914153099060059, "alphanum_fraction": 0.692962110042572, "avg_line_length": 50.720001220703125, "blob_id": "c93df7655fb9498d2470042720c2e5f152acddba", "content_id": "b0fc7055ad89816564d601f12878c2206f7b5200", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2586, "license_type": "permissive", "max_line_length": 325, "num_lines": 50, "path": "/lib/ansible/ruby/modules/generated/clustering/openshift/oc.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows management of resources in an OpenShift cluster. The inventory host can be any host with network connectivity to the OpenShift cluster; the default port being 8443/TCP.\n # This module relies on a token to authenticate to OpenShift. This can either be a user or a service account.\n class Oc < Base\n # @return [String, nil] Hostname or address of the OpenShift API endpoint. By default, this is expected to be the current inventory host.\n attribute :host\n validates :host, type: String\n\n # @return [Integer, nil] The port number of the API endpoint.\n attribute :port\n validates :port, type: Integer\n\n # @return [Hash, nil] The inline definition of the resource. This is mutually exclusive with name, namespace and kind.\n attribute :inline\n validates :inline, type: Hash\n\n # @return [String] The kind of the resource upon which to take action.\n attribute :kind\n validates :kind, presence: true, type: String\n\n # @return [String, nil] The name of the resource on which to take action.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] The namespace of the resource upon which to take action.\n attribute :namespace\n validates :namespace, type: String\n\n # @return [String] The token with which to authenticate against the OpenShift cluster.\n attribute :token\n validates :token, presence: true, type: String\n\n # @return [Boolean, nil] If C(no), SSL certificates for the target url will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:present, :absent] If the state is present, and the resource doesn't exist, it shall be created using the inline definition. If the state is present and the resource exists, the definition will be updated, again using an inline definition. If the state is absent, the resource will be deleted if it exists.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6453900933265686, "alphanum_fraction": 0.6611505150794983, "avg_line_length": 38.65625, "blob_id": "4cfbd372f5a1ec3ff707d82f640253c3b851f4ca", "content_id": "cf89c3d340da70b1b8ed3676003d7e8c01be2291", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1269, "license_type": "permissive", "max_line_length": 157, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_mac_pools.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module manage MAC pools in oVirt/RHV.\n class Ovirt_mac_pool < Base\n # @return [String] Name of the MAC pool to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Description of the MAC pool.\n attribute :description\n\n # @return [:present, :absent, nil] Should the mac pool be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Symbol, nil] If I(true) allow a MAC address to be used multiple times in a pool.,Default value is set by oVirt/RHV engine to I(false).\n attribute :allow_duplicates\n validates :allow_duplicates, type: Symbol\n\n # @return [Array<String>, String, nil] List of MAC ranges. The from and to should be split by comma.,For example: 00:1a:4a:16:01:51,00:1a:4a:16:01:61\n attribute :ranges\n validates :ranges, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6835784912109375, "alphanum_fraction": 0.6841789484024048, "avg_line_length": 53.6065559387207, "blob_id": "bfbbc546176b47d16a2110245bbf9198c9f03c25", "content_id": "775e0a6d16dcf231d425fa283462f091eb4f02e9", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3331, "license_type": "permissive", "max_line_length": 191, "num_lines": 61, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_resource_pool.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to add/remove a resource pool to/from vCenter\n class Vmware_resource_pool < Base\n # @return [String] Name of the datacenter to add the host.\n attribute :datacenter\n validates :datacenter, presence: true, type: String\n\n # @return [String] Name of the cluster to add the host.\n attribute :cluster\n validates :cluster, presence: true, type: String\n\n # @return [String] Resource pool name to manage.\n attribute :resource_pool\n validates :resource_pool, presence: true, type: String\n\n # @return [Boolean, nil] In a resource pool with an expandable reservation, the reservation on a resource pool can grow beyond the specified value.\n attribute :cpu_expandable_reservations\n validates :cpu_expandable_reservations, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Integer, nil] Amount of resource that is guaranteed available to the virtual machine or resource pool.\n attribute :cpu_reservation\n validates :cpu_reservation, type: Integer\n\n # @return [Integer, nil] The utilization of a virtual machine/resource pool will not exceed this limit, even if there are available resources.,The default value -1 indicates no limit.\n attribute :cpu_limit\n validates :cpu_limit, type: Integer\n\n # @return [:high, :custom, :low, :normal, nil] Memory shares are used in case of resource contention.\n attribute :cpu_shares\n validates :cpu_shares, expression_inclusion: {:in=>[:high, :custom, :low, :normal], :message=>\"%{value} needs to be :high, :custom, :low, :normal\"}, allow_nil: true\n\n # @return [Boolean, nil] In a resource pool with an expandable reservation, the reservation on a resource pool can grow beyond the specified value.\n attribute :mem_expandable_reservations\n validates :mem_expandable_reservations, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Integer, nil] Amount of resource that is guaranteed available to the virtual machine or resource pool.\n attribute :mem_reservation\n validates :mem_reservation, type: Integer\n\n # @return [Integer, nil] The utilization of a virtual machine/resource pool will not exceed this limit, even if there are available resources.,The default value -1 indicates no limit.\n attribute :mem_limit\n validates :mem_limit, type: Integer\n\n # @return [:high, :custom, :low, :normal, nil] Memory shares are used in case of resource contention.\n attribute :mem_shares\n validates :mem_shares, expression_inclusion: {:in=>[:high, :custom, :low, :normal], :message=>\"%{value} needs to be :high, :custom, :low, :normal\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Add or remove the resource pool\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6255770921707153, "alphanum_fraction": 0.6315789222717285, "avg_line_length": 35.099998474121094, "blob_id": "27e886b6216c7bdad53f3407a64b31c0e7015dfe", "content_id": "09c8f40d4b16fd592b93e489e279158cb06ca3fa", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2166, "license_type": "permissive", "max_line_length": 185, "num_lines": 60, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_zone.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and remove zones.\n class Cs_zone < Base\n # @return [String] Name of the zone.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] uuid of the existing zone.\n attribute :id\n\n # @return [:present, :enabled, :disabled, :absent, nil] State of the zone.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :enabled, :disabled, :absent], :message=>\"%{value} needs to be :present, :enabled, :disabled, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Domain the zone is related to.,Zone is a public zone if not set.\n attribute :domain\n\n # @return [Object, nil] Network domain for the zone.\n attribute :network_domain\n\n # @return [:basic, :advanced, nil] Network type of the zone.\n attribute :network_type\n validates :network_type, expression_inclusion: {:in=>[:basic, :advanced], :message=>\"%{value} needs to be :basic, :advanced\"}, allow_nil: true\n\n # @return [String, nil] First DNS for the zone.,Required if C(state=present)\n attribute :dns1\n validates :dns1, type: String\n\n # @return [String, nil] Second DNS for the zone.\n attribute :dns2\n validates :dns2, type: String\n\n # @return [Object, nil] First internal DNS for the zone.,If not set C(dns1) will be used on C(state=present).\n attribute :internal_dns1\n\n # @return [Object, nil] Second internal DNS for the zone.\n attribute :internal_dns2\n\n # @return [Object, nil] First DNS for IPv6 for the zone.\n attribute :dns1_ipv6\n\n # @return [Object, nil] Second DNS for IPv6 for the zone.\n attribute :dns2_ipv6\n\n # @return [Object, nil] Guest CIDR address for the zone.\n attribute :guest_cidr_address\n\n # @return [Object, nil] DHCP provider for the Zone.\n attribute :dhcp_provider\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6969696879386902, "alphanum_fraction": 0.6969696879386902, "avg_line_length": 30.058822631835938, "blob_id": "82be7538e930c026f82af7414e4b969a6ca1a166", "content_id": "bf85cfa4d347cffae387c5ab8dee49c36bda1656", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 528, "license_type": "permissive", "max_line_length": 149, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_user_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Retrieve facts about one or more oVirt/RHV users.\n class Ovirt_user_facts < Base\n # @return [String, nil] Search term which is accepted by oVirt/RHV search backend.,For example to search user X use following pattern: name=X\n attribute :pattern\n validates :pattern, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6838955283164978, "alphanum_fraction": 0.6882480978965759, "avg_line_length": 51.514286041259766, "blob_id": "7586e54b234ad55363bb49fea8511b5c26972c00", "content_id": "e68ad74929c257014b362a9c0c314b0147808992", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3676, "license_type": "permissive", "max_line_length": 246, "num_lines": 70, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_poolgroup.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure PoolGroup object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_poolgroup < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Object, nil] Checksum of cloud configuration for poolgroup.,Internally set by cloud connector.\n attribute :cloud_config_cksum\n\n # @return [Object, nil] It is a reference to an object of type cloud.\n attribute :cloud_ref\n\n # @return [Object, nil] Name of the user who created the object.\n attribute :created_by\n\n # @return [Object, nil] When setup autoscale manager will automatically promote new pools into production when deployment goals are met.,It is a reference to an object of type poolgroupdeploymentpolicy.\n attribute :deployment_policy_ref\n\n # @return [Object, nil] Description of pool group.\n attribute :description\n\n # @return [Object, nil] Enable an action - close connection, http redirect, or local http response - when a pool group failure happens.,By default, a connection will be closed, in case the pool group experiences a failure.\n attribute :fail_action\n\n # @return [Symbol, nil] Whether an implicit set of priority labels is generated.,Field introduced in 17.1.9,17.2.3.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :implicit_priority_labels\n validates :implicit_priority_labels, type: Symbol\n\n # @return [Object, nil] List of pool group members object of type poolgroupmember.\n attribute :members\n\n # @return [Object, nil] The minimum number of servers to distribute traffic to.,Allowed values are 1-65535.,Special values are 0 - 'disable'.,Default value when not specified in API or module is interpreted by Avi Controller as 0.\n attribute :min_servers\n\n # @return [String] The name of the pool group.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Uuid of the priority labels.,If not provided, pool group member priority label will be interpreted as a number with a larger number considered higher priority.,It is a reference to an object of type prioritylabels.\n attribute :priority_labels_ref\n\n # @return [Object, nil] It is a reference to an object of type tenant.\n attribute :tenant_ref\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Uuid of the pool group.\n attribute :uuid\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6607393622398376, "alphanum_fraction": 0.6607393622398376, "avg_line_length": 42.61224365234375, "blob_id": "92a24832129698e76b6bd9641a9a29eee9b8067e", "content_id": "8998df08a2b048c82e36d869e5dce83d31843c69", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2137, "license_type": "permissive", "max_line_length": 207, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/lightsail.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates or instances in AWS Lightsail and optionally wait for it to be 'running'.\n class Lightsail < Base\n # @return [:present, :absent, :running, :restarted, :stopped, nil] Indicate desired state of the target.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :running, :restarted, :stopped], :message=>\"%{value} needs to be :present, :absent, :running, :restarted, :stopped\"}, allow_nil: true\n\n # @return [String] Name of the instance\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] AWS availability zone in which to launch the instance. Required when state='present'\n attribute :zone\n validates :zone, type: String\n\n # @return [String, nil] ID of the instance blueprint image. Required when state='present'\n attribute :blueprint_id\n validates :blueprint_id, type: String\n\n # @return [String, nil] Bundle of specification info for the instance. Required when state='present'\n attribute :bundle_id\n validates :bundle_id, type: String\n\n # @return [String, nil] Launch script that can configure the instance with additional data\n attribute :user_data\n validates :user_data, type: String\n\n # @return [String, nil] Name of the key pair to use with the instance\n attribute :key_pair_name\n validates :key_pair_name, type: String\n\n # @return [:yes, :no, nil] Wait for the instance to be in state 'running' before returning. If wait is \"no\" an ip_address may not be returned\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] How long before wait gives up, in seconds.\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6913580298423767, "alphanum_fraction": 0.6913580298423767, "avg_line_length": 27.58823585510254, "blob_id": "d41cc7768f58435c43140b2362b8ef0eb2608346", "content_id": "d55d54f30753cb607d3af6a8008daf7c00bf0d4e", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 486, "license_type": "permissive", "max_line_length": 107, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_command.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Run system-cli commands on ONTAP\n class Na_ontap_command < Base\n # @return [Array<String>, String, nil] a comma separated list containing the command and arguments.\n attribute :command\n validates :command, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.720708429813385, "alphanum_fraction": 0.7225250005722046, "avg_line_length": 65.7272720336914, "blob_id": "533ea01366a7a4a66abbb69459ccd7c89fda5c08", "content_id": "e5c03f7305d81dc32d9e3304b1c8f9308faaf4b3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2202, "license_type": "permissive", "max_line_length": 386, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_batch_job_queue.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows the management of AWS Batch Job Queues. It is idempotent and supports \"Check\" mode. Use module M(aws_batch_compute_environment) to manage the compute environment, M(aws_batch_job_queue) to manage job queues, M(aws_batch_job_definition) to manage job definitions.\n class Aws_batch_job_queue < Base\n # @return [Object] The name for the job queue\n attribute :job_queue_name\n validates :job_queue_name, presence: true\n\n # @return [:present, :absent] Describes the desired state.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [:ENABLED, :DISABLED, nil] The state of the job queue. If the job queue state is ENABLED , it is able to accept jobs.\n attribute :job_queue_state\n validates :job_queue_state, expression_inclusion: {:in=>[:ENABLED, :DISABLED], :message=>\"%{value} needs to be :ENABLED, :DISABLED\"}, allow_nil: true\n\n # @return [Object] The priority of the job queue. Job queues with a higher priority (or a lower integer value for the priority parameter) are evaluated first when associated with same compute environment. Priority is determined in ascending order, for example, a job queue with a priority value of 1 is given scheduling preference over a job queue with a priority value of 10.\n attribute :priority\n validates :priority, presence: true\n\n # @return [Object] The set of compute environments mapped to a job queue and their order relative to each other. The job scheduler uses this parameter to determine which compute environment should execute a given job. Compute environments must be in the VALID state before you can associate them with a job queue. You can associate up to 3 compute environments with a job queue.\n attribute :compute_environment_order\n validates :compute_environment_order, presence: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6906832456588745, "alphanum_fraction": 0.6919254660606384, "avg_line_length": 32.54166793823242, "blob_id": "2c65e2ae05367472446fd40e56446a934bf53762", "content_id": "9c98fae9fe4e05234c545c7c578e13d852687b4c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 805, "license_type": "permissive", "max_line_length": 184, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/storage/zfs/zpool_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gather facts from ZFS pool properties.\n class Zpool_facts < Base\n # @return [Object, nil] ZFS pool name.\n attribute :name\n\n # @return [Symbol, nil] Specifies if property values should be displayed in machine friendly format.\n attribute :parsable\n validates :parsable, type: Symbol\n\n # @return [String, nil] Specifies which dataset properties should be queried in comma-separated format. For more information about dataset properties, check zpool(1M) man page.\n attribute :properties\n validates :properties, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.674716591835022, "alphanum_fraction": 0.674716591835022, "avg_line_length": 41.27083206176758, "blob_id": "215ed91f6efc42dcdb9bc1b084671ac212af6935", "content_id": "30e7dcad0f2f5223d1da0f0b318543aeb2713431", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2029, "license_type": "permissive", "max_line_length": 161, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/packaging/language/yarn.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage node.js packages with the Yarn package manager (https://yarnpkg.com/)\n class Yarn < Base\n # @return [String, nil] The name of a node.js library to install,If omitted all packages in package.json are installed.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] The base path where Node.js libraries will be installed.,This is where the node_modules folder lives.\n attribute :path\n validates :path, type: String\n\n # @return [String, nil] The version of the library to be installed.,Must be in semver format. If \"latest\" is desired, use \"state\" arg instead\n attribute :version\n validates :version, type: String\n\n # @return [Symbol, nil] Install the node.js library globally\n attribute :global\n validates :global, type: Symbol\n\n # @return [Object, nil] The executable location for yarn.\n attribute :executable\n\n # @return [Symbol, nil] Use the --ignore-scripts flag when installing.\n attribute :ignore_scripts\n validates :ignore_scripts, type: Symbol\n\n # @return [Symbol, nil] Install dependencies in production mode.,Yarn will ignore any dependencies under devDependencies in package.json\n attribute :production\n validates :production, type: Symbol\n\n # @return [String, nil] The registry to install modules from.\n attribute :registry\n validates :registry, type: String\n\n # @return [:present, :absent, :latest, nil] Installation state of the named node.js library,If absent is selected, a name option must be provided\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :latest], :message=>\"%{value} needs to be :present, :absent, :latest\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6844861507415771, "alphanum_fraction": 0.6877591013908386, "avg_line_length": 60.106666564941406, "blob_id": "024d78183b15ac86a9e9b084da62d2e244022433", "content_id": "e296d890ad2bd6b6d490697416e0b6bb1f63689c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4583, "license_type": "permissive", "max_line_length": 388, "num_lines": 75, "path": "/lib/ansible/ruby/modules/generated/cloud/packet/packet_device.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage a bare metal server in the Packet Host (a \"device\" in the API terms).\n # When the machine is created it can optionally wait for public IP address, or for active state.\n # This module has a dependency on packet >= 1.0.\n # API is documented at U(https://www.packet.net/developers/api/devices).\n class Packet_device < Base\n # @return [Object, nil] Packet api token. You can also supply it in env var C(PACKET_API_TOKEN).\n attribute :auth_token\n\n # @return [Integer, nil] The number of devices to create. Count number can be included in hostname via the %d string formatter.\n attribute :count\n validates :count, type: Integer\n\n # @return [Integer, nil] From which number to start the count.\n attribute :count_offset\n validates :count_offset, type: Integer\n\n # @return [Object, nil] List of device IDs on which to operate.\n attribute :device_ids\n\n # @return [Object, nil] Facility slug for device creation. See Packet API for current list - U(https://www.packet.net/developers/api/facilities/).\n attribute :facility\n\n # @return [Object, nil] Dict with \"features\" for device creation. See Packet API docs for details.\n attribute :features\n\n # @return [Object, nil] A hostname of a device, or a list of hostnames.,If given string or one-item list, you can use the C(\"%d\") Python string format to expand numbers from I(count).,If only one hostname, it might be expanded to list if I(count)>1.\n attribute :hostnames\n\n # @return [Boolean, nil] Whether to lock a created device.\n attribute :locked\n validates :locked, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] OS slug for device creation. See Packet API for current list - U(https://www.packet.net/developers/api/operatingsystems/).\n attribute :operating_system\n\n # @return [Object, nil] Plan slug for device creation. See Packet API for current list - U(https://www.packet.net/developers/api/plans/).\n attribute :plan\n\n # @return [Object] ID of project of the device.\n attribute :project_id\n validates :project_id, presence: true\n\n # @return [:present, :absent, :active, :inactive, :rebooted, nil] Desired state of the device.,If set to C(present) (the default), the module call will return immediately after the device-creating HTTP request successfully returns.,If set to C(active), the module call will block until all the specified devices are in state active due to the Packet API, or until I(wait_timeout).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :active, :inactive, :rebooted], :message=>\"%{value} needs to be :present, :absent, :active, :inactive, :rebooted\"}, allow_nil: true\n\n # @return [Object, nil] Userdata blob made available to the machine\n attribute :user_data\n\n # @return [4, 6, nil] Whether to wait for the instance to be assigned a public IPv4/IPv6 address.,If set to 4, it will wait until IPv4 is assigned to the instance.,If set to 6, wait until public IPv6 is assigned to the instance.\n attribute :wait_for_public_IPv\n validates :wait_for_public_IPv, expression_inclusion: {:in=>[4, 6], :message=>\"%{value} needs to be 4, 6\"}, allow_nil: true\n\n # @return [Integer, nil] How long (seconds) to wait either for automatic IP address assignment, or for the device to reach the C(active) I(state).,If I(wait_for_public_IPv) is set and I(state) is C(active), the module will wait for both events consequently, applying the timeout twice.\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [Object, nil] URL of custom iPXE script for provisioning.,More about custome iPXE for Packet devices at U(https://help.packet.net/technical/infrastructure/custom-ipxe).\n attribute :ipxe_script_url\n\n # @return [Boolean, nil] Persist PXE as the first boot option.,Normally, the PXE process happens only on the first boot. Set this arg to have your device continuously boot to iPXE.\n attribute :always_pxe\n validates :always_pxe, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.659649133682251, "alphanum_fraction": 0.659649133682251, "avg_line_length": 40.5625, "blob_id": "4c7ad43f6e003f828a2187b2b5ba887ba5a160f7", "content_id": "377027bf40db8ba7d51a7e6bd0bfd05eb0ad7454", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1995, "license_type": "permissive", "max_line_length": 164, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_igroup.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # create, destroy or rename Igroups and add or remove initiator in igroups.\n class Na_ontap_igroup < Base\n # @return [:present, :absent, nil] Whether the specified Igroup should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The name of the igroup to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:fcp, :iscsi, :mixed, nil] Type of the initiator group.,Required when C(state=present).\n attribute :initiator_group_type\n validates :initiator_group_type, expression_inclusion: {:in=>[:fcp, :iscsi, :mixed], :message=>\"%{value} needs to be :fcp, :iscsi, :mixed\"}, allow_nil: true\n\n # @return [String, nil] Name of igroup to rename to name.\n attribute :from_name\n validates :from_name, type: String\n\n # @return [String, nil] OS type of the initiators within the group.\n attribute :ostype\n validates :ostype, type: String\n\n # @return [String, nil] WWPN, WWPN Alias, or iSCSI name of Initiator to add or remove.\n attribute :initiator\n validates :initiator, type: String\n\n # @return [Object, nil] Name of a current portset to bind to the newly created igroup.\n attribute :bind_portset\n\n # @return [Symbol, nil] Forcibly remove the initiator even if there are existing LUNs mapped to this initiator group.\n attribute :force_remove_initiator\n validates :force_remove_initiator, type: Symbol\n\n # @return [String] The name of the vserver to use.\n attribute :vserver\n validates :vserver, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6796759963035583, "alphanum_fraction": 0.6818851232528687, "avg_line_length": 40.15151596069336, "blob_id": "58dead33bd05f27b0319ee1204fbdfc43b7bae0a", "content_id": "71d7e58601909b1c5281868abc8a1fe93a39a12c", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1358, "license_type": "permissive", "max_line_length": 168, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_elementsw_admin_users.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, destroy, or update admin users on SolidFire\n class Na_elementsw_admin_users < Base\n # @return [:present, :absent] Whether the specified account should exist or not.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String] Unique username for this account. (May be 1 to 64 characters in length).\n attribute :element_username\n validates :element_username, presence: true, type: String\n\n # @return [String, nil] The password for the new admin account. Setting the password attribute will always reset your password, even if the password is the same\n attribute :element_password\n validates :element_password, type: String\n\n # @return [Symbol, nil] Boolean, true for accepting Eula, False Eula\n attribute :acceptEula\n validates :acceptEula, type: Symbol\n\n # @return [Array<String>, String, nil] A list of type the admin has access to\n attribute :access\n validates :access, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6678876876831055, "alphanum_fraction": 0.6678876876831055, "avg_line_length": 31.760000228881836, "blob_id": "cc1fb790709f0aacac404a1957edb9888c2883b2", "content_id": "fb74e269e47d3585982311523634ab6ca7884fc4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 819, "license_type": "permissive", "max_line_length": 111, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/net_tools/ipify_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # If behind NAT and need to know the public IP of your internet gateway.\n class Ipify_facts < Base\n # @return [String, nil] URL of the ipify.org API service.,C(?format=json) will be appended per default.\n attribute :api_url\n validates :api_url, type: String\n\n # @return [Integer, nil] HTTP connection timeout in seconds.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [String, nil] When set to C(NO), SSL certificates will not be validated.\n attribute :validate_certs\n validates :validate_certs, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6852540373802185, "alphanum_fraction": 0.6889715194702148, "avg_line_length": 52.79999923706055, "blob_id": "9d29ce495bf4a4c579cdaef7a2893ae04dda4b0e", "content_id": "0fdfa0fd944b6b90445b39e468b1f9ad24ec1d3d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2421, "license_type": "permissive", "max_line_length": 307, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/packaging/os/pkgng.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage binary packages for FreeBSD using 'pkgng' which is available in versions after 9.0.\n class Pkgng < Base\n # @return [Array<String>, String] Name or list of names of packages to install/remove.\n attribute :name\n validates :name, presence: true, type: TypeGeneric.new(String)\n\n # @return [:present, :latest, :absent, nil] State of the package.,Note: \"latest\" added in 2.7\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :latest, :absent], :message=>\"%{value} needs to be :present, :latest, :absent\"}, allow_nil: true\n\n # @return [Symbol, nil] Use local package base instead of fetching an updated one.\n attribute :cached\n validates :cached, type: Symbol\n\n # @return [Array<String>, String, nil] A comma-separated list of keyvalue-pairs of the form C(<+/-/:><key>[=<value>]). A C(+) denotes adding an annotation, a C(-) denotes removing an annotation, and C(:) denotes modifying an annotation. If setting or modifying annotations, a value must be provided.\n attribute :annotation\n validates :annotation, type: TypeGeneric.new(String)\n\n # @return [Object, nil] For pkgng versions before 1.1.4, specify packagesite to use for downloading packages. If not specified, use settings from C(/usr/local/etc/pkg.conf).,For newer pkgng versions, specify a the name of a repository configured in C(/usr/local/etc/pkg/repos).\n attribute :pkgsite\n\n # @return [Object, nil] For pkgng versions 1.5 and later, pkg will install all packages within the specified root directory.,Can not be used together with I(chroot) or I(jail) options.\n attribute :rootdir\n\n # @return [Object, nil] Pkg will chroot in the specified environment.,Can not be used together with I(rootdir) or I(jail) options.\n attribute :chroot\n\n # @return [Object, nil] Pkg will execute in the given jail name or id.,Can not be used together with I(chroot) or I(rootdir) options.\n attribute :jail\n\n # @return [Symbol, nil] Remove automatically installed packages which are no longer needed.\n attribute :autoremove\n validates :autoremove, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.669036328792572, "alphanum_fraction": 0.669036328792572, "avg_line_length": 37.3636360168457, "blob_id": "a6c25a4cb8d5aff8a49adfbcd2972362fe83bb2f", "content_id": "90685b1b305ca7c8518dba8238b52e41504ba2fb", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1266, "license_type": "permissive", "max_line_length": 200, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/storage/ibm/ibm_sa_host.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module adds hosts to or removes them from IBM Spectrum Accelerate storage systems.\n class Ibm_sa_host < Base\n # @return [String] Host name.\n attribute :host\n validates :host, presence: true, type: String\n\n # @return [:present, :absent] Host state.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [Object, nil] The name of the cluster to include the host.\n attribute :cluster\n\n # @return [Object, nil] The domains the cluster will be attached to. To include more than one domain, separate domain names with commas. To include all existing domains, use an asterisk (\"*\").\n attribute :domain\n\n # @return [Object, nil] The host's CHAP name identifier\n attribute :iscsi_chap_name\n\n # @return [Object, nil] The password of the initiator used to authenticate to the system when CHAP is enable\n attribute :iscsi_chap_secret\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7185473442077637, "alphanum_fraction": 0.7230868935585022, "avg_line_length": 52.17241287231445, "blob_id": "b75ed566a311bf0a072520ab3d1ea47532d763f1", "content_id": "b2dd393c531a7436728069b606788f6fe9b3013a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1542, "license_type": "permissive", "max_line_length": 402, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_compute_instance_template.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Defines an Instance Template resource that provides configuration settings for your virtual machine instances. Instance templates are not tied to the lifetime of an instance and can be used and reused as to deploy virtual machines. You can also use different templates to create different virtual machine configurations. Instance templates are required when you create a managed instance group.\n # Tip: Disks should be set to autoDelete=true so that leftover disks are not left behind on machine deletion.\n class Gcp_compute_instance_template < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] An optional description of this resource. Provide this property when you create the resource.\n attribute :description\n\n # @return [String] Name of the resource. The name is 1-63 characters long and complies with RFC1035.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Hash, nil] The instance properties for this instance template.\n attribute :properties\n validates :properties, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7030701637268066, "alphanum_fraction": 0.707456111907959, "avg_line_length": 54.60975646972656, "blob_id": "bb52849f71f85d29667a14121d501c3452c4b8c6", "content_id": "652eaac913d57a271a2e6dc9045f489933efe670", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2280, "license_type": "permissive", "max_line_length": 423, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_forwarding_rule.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, Update or Destroy a Forwarding_Rule. See U(https://cloud.google.com/compute/docs/load-balancing/http/target-proxies) for an overview. More details on the Global Forwarding_Rule API can be found at U(https://cloud.google.com/compute/docs/reference/latest/globalForwardingRules) More details on the Forwarding Rules API can be found at U(https://cloud.google.com/compute/docs/reference/latest/forwardingRules)\n class Gcp_forwarding_rule < Base\n # @return [String, nil] IPv4 or named IP address. Must be of the same scope (regional, global). Reserved addresses can (and probably should) be used for global forwarding rules. You may reserve IPs from the console or via the gce_eip module.\n attribute :address\n validates :address, type: String\n\n # @return [String] Name of the Forwarding_Rule.\n attribute :forwarding_rule_name\n validates :forwarding_rule_name, presence: true, type: String\n\n # @return [Integer, nil] For global forwarding rules, must be set to 80 or 8080 for TargetHttpProxy, and 443 for TargetHttpsProxy or TargetSslProxy.\n attribute :port_range\n validates :port_range, type: Integer\n\n # @return [String, nil] For global forwarding rules, TCP, UDP, ESP, AH, SCTP or ICMP. Default is TCP.\n attribute :protocol\n validates :protocol, type: String\n\n # @return [String, nil] The region for this forwarding rule. Currently, only 'global' is supported.\n attribute :region\n validates :region, type: String\n\n # @return [:present, :absent] The state of the Forwarding Rule. 'present' or 'absent'\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String, nil] Target resource for forwarding rule. For global proxy, this is a Global TargetProxy resource. Required for external load balancing (including Global load balancing)\n attribute :target\n validates :target, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7035425901412964, "alphanum_fraction": 0.7035425901412964, "avg_line_length": 56.46428680419922, "blob_id": "365c8089d611f40f716d4b548748264660a3eff6", "content_id": "b9bc5ef7315e80335432347969657b6c095c9186", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1609, "license_type": "permissive", "max_line_length": 375, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_cfg_backup.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to perform various operations related to backup, restore and reset of ESXi host configuration.\n class Vmware_cfg_backup < Base\n # @return [String, nil] Name of ESXi server. This is required only if authentication against a vCenter is done.\n attribute :esxi_hostname\n validates :esxi_hostname, type: String\n\n # @return [String, nil] The destination where the ESXi configuration bundle will be saved. The I(dest) can be a folder or a file.,If I(dest) is a folder, the backup file will be saved in the folder with the default filename generated from the ESXi server.,If I(dest) is a file, the backup file will be saved with that filename. The file extension will always be .tgz.\n attribute :dest\n validates :dest, type: String\n\n # @return [Object, nil] The file containing the ESXi configuration that will be restored.\n attribute :src\n\n # @return [:saved, :absent, :loaded, nil] If C(saved), the .tgz backup bundle will be saved in I(dest).,If C(absent), the host configuration will be reset to default values.,If C(loaded), the backup file in I(src) will be loaded to the ESXi host rewriting the hosts settings.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:saved, :absent, :loaded], :message=>\"%{value} needs to be :saved, :absent, :loaded\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6722143888473511, "alphanum_fraction": 0.6767277717590332, "avg_line_length": 47.5616455078125, "blob_id": "2a7c62a68bddb1f0b6e668182757697c651c20ce", "content_id": "031cefcb1d641cf454cd4b3bfa5954f0baa7ac5c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3545, "license_type": "permissive", "max_line_length": 362, "num_lines": 73, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_ipamdnsproviderprofile.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure IpamDnsProviderProfile object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_ipamdnsproviderprofile < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Symbol, nil] If this flag is set, only allocate ip from networks in the virtual service vrf.,Applicable for avi vantage ipam only.,Field introduced in 17.2.4.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :allocate_ip_in_vrf\n validates :allocate_ip_in_vrf, type: Symbol\n\n # @return [Object, nil] Provider details if type is aws.\n attribute :aws_profile\n\n # @return [Object, nil] Provider details if type is microsoft azure.,Field introduced in 17.2.1.\n attribute :azure_profile\n\n # @return [Object, nil] Provider details if type is custom.,Field introduced in 17.1.1.\n attribute :custom_profile\n\n # @return [Object, nil] Provider details if type is google cloud.\n attribute :gcp_profile\n\n # @return [Object, nil] Provider details if type is infoblox.\n attribute :infoblox_profile\n\n # @return [Hash, nil] Provider details if type is avi.\n attribute :internal_profile\n validates :internal_profile, type: Hash\n\n # @return [String] Name for the ipam/dns provider profile.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Provider details if type is openstack.\n attribute :openstack_profile\n\n # @return [Object, nil] Field introduced in 17.1.1.\n attribute :proxy_configuration\n\n # @return [String, nil] It is a reference to an object of type tenant.\n attribute :tenant_ref\n validates :tenant_ref, type: String\n\n # @return [String] Provider type for the ipam/dns provider profile.,Enum options - IPAMDNS_TYPE_INFOBLOX, IPAMDNS_TYPE_AWS, IPAMDNS_TYPE_OPENSTACK, IPAMDNS_TYPE_GCP, IPAMDNS_TYPE_INFOBLOX_DNS, IPAMDNS_TYPE_CUSTOM,,IPAMDNS_TYPE_CUSTOM_DNS, IPAMDNS_TYPE_AZURE, IPAMDNS_TYPE_INTERNAL, IPAMDNS_TYPE_INTERNAL_DNS, IPAMDNS_TYPE_AWS_DNS, IPAMDNS_TYPE_AZURE_DNS.\n attribute :type\n validates :type, presence: true, type: String\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Uuid of the ipam/dns provider profile.\n attribute :uuid\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5742092728614807, "alphanum_fraction": 0.5742092728614807, "avg_line_length": 23.176469802856445, "blob_id": "c09fe0e3bd158ab4a5470df8b839db24c2ff16de", "content_id": "9f3fa7f2779ac16d37dd12fb618ae4c5dcf72454", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1233, "license_type": "permissive", "max_line_length": 71, "num_lines": 51, "path": "/lib/ansible/ruby/dsl_builders/jinja_item_node_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# see LICENSE.txt in project root\nrequire 'spec_helper'\nrequire 'ansible/ruby/dsl_builders/jinja_item_node'\n\ndescribe Ansible::Ruby::DslBuilders::JinjaItemNode do\n let(:instance) { Ansible::Ruby::DslBuilders::JinjaItemNode.new }\n\n describe '#+' do\n subject { instance + something }\n\n context 'another item node' do\n let(:something) { Ansible::Ruby::DslBuilders::JinjaItemNode.new }\n\n it { is_expected.to eq '{{ item }}{{ item }}' }\n end\n\n context 'string' do\n let(:something) { ' foobar' }\n\n it { is_expected.to eq '{{ item }} foobar' }\n end\n end\n\n context 'string conversions' do\n %i[to_s to_str].each do |method|\n describe \"##{method}\" do\n subject { instance.send(method) }\n\n context 'dictionary' do\n context 'key' do\n subject { instance.key.send(method) }\n\n it { is_expected.to eq '{{ item.key }}' }\n end\n\n context 'nested' do\n subject { instance.key.stuff.send(method) }\n\n it { is_expected.to eq '{{ item.key.stuff }}' }\n end\n end\n\n context 'ref only' do\n it { is_expected.to eq '{{ item }}' }\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7017383575439453, "alphanum_fraction": 0.7017383575439453, "avg_line_length": 42.720001220703125, "blob_id": "57ccf720731a8cabb4c3e0a42d0d146351f4f8ca", "content_id": "26ba1b6b8679d775c0120c26136e176164465ef0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1093, "license_type": "permissive", "max_line_length": 301, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_target_proxy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, Update or Destroy a Target_Proxy. See U(https://cloud.google.com/compute/docs/load-balancing/http/target-proxies) for an overview. More details on the Target_Proxy API can be found at U(https://cloud.google.com/compute/docs/reference/latest/targetHttpProxies#resource-representations).\n class Gcp_target_proxy < Base\n # @return [String] Name of the Target_Proxy.\n attribute :target_proxy_name\n validates :target_proxy_name, presence: true, type: String\n\n # @return [String] Type of Target_Proxy. HTTP, HTTPS or SSL. Only HTTP is currently supported.\n attribute :target_proxy_type\n validates :target_proxy_type, presence: true, type: String\n\n # @return [String, nil] Name of the Url Map. Required if type is HTTP or HTTPS proxy.\n attribute :url_map_name\n validates :url_map_name, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7045454382896423, "alphanum_fraction": 0.7045454382896423, "avg_line_length": 46.14285659790039, "blob_id": "9e9e93cec09d980b082c84a07006ec82d431917a", "content_id": "77a9af44f609251dfcf7ef210f31165db5475c99", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1320, "license_type": "permissive", "max_line_length": 292, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/database/proxysql/proxysql_replication_hostgroups.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Each row in mysql_replication_hostgroups represent a pair of writer_hostgroup and reader_hostgroup. ProxySQL will monitor the value of read_only for all the servers in specified hostgroups, and based on the value of read_only will assign the server to the writer or reader hostgroups.\n class Proxysql_replication_hostgroups < Base\n # @return [Integer] Id of the writer hostgroup.\n attribute :writer_hostgroup\n validates :writer_hostgroup, presence: true, type: Integer\n\n # @return [Integer] Id of the reader hostgroup.\n attribute :reader_hostgroup\n validates :reader_hostgroup, presence: true, type: Integer\n\n # @return [Object, nil] Text field that can be used for any purposed defined by the user.\n attribute :comment\n\n # @return [:present, :absent, nil] When C(present) - adds the replication hostgroup, when C(absent) - removes the replication hostgroup.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7137864232063293, "alphanum_fraction": 0.7188349366188049, "avg_line_length": 63.375, "blob_id": "f6462a2cbe781afbfc0137c56b28f03f7bc4e122", "content_id": "806d292b7e38eeddc40c6d634443004f8b32ee23", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5150, "license_type": "permissive", "max_line_length": 306, "num_lines": 80, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_serverautoscalepolicy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure ServerAutoScalePolicy object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_serverautoscalepolicy < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Object, nil] User defined description for the object.\n attribute :description\n\n # @return [Symbol, nil] Use avi intelligent autoscale algorithm where autoscale is performed by comparing load on the pool against estimated capacity of all the servers.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :intelligent_autoscale\n validates :intelligent_autoscale, type: Symbol\n\n # @return [Object, nil] Maximum extra capacity as percentage of load used by the intelligent scheme.,Scalein is triggered when available capacity is more than this margin.,Allowed values are 1-99.,Default value when not specified in API or module is interpreted by Avi Controller as 40.\n attribute :intelligent_scalein_margin\n\n # @return [Object, nil] Minimum extra capacity as percentage of load used by the intelligent scheme.,Scaleout is triggered when available capacity is less than this margin.,Allowed values are 1-99.,Default value when not specified in API or module is interpreted by Avi Controller as 20.\n attribute :intelligent_scaleout_margin\n\n # @return [Object, nil] Maximum number of servers to scalein simultaneously.,The actual number of servers to scalein is chosen such that target number of servers is always more than or equal to the min_size.,Default value when not specified in API or module is interpreted by Avi Controller as 1.\n attribute :max_scalein_adjustment_step\n\n # @return [Object, nil] Maximum number of servers to scaleout simultaneously.,The actual number of servers to scaleout is chosen such that target number of servers is always less than or equal to the max_size.,Default value when not specified in API or module is interpreted by Avi Controller as 1.\n attribute :max_scaleout_adjustment_step\n\n # @return [Object, nil] Maximum number of servers after scaleout.,Allowed values are 0-400.\n attribute :max_size\n\n # @return [Object, nil] No scale-in happens once number of operationally up servers reach min_servers.,Allowed values are 0-400.\n attribute :min_size\n\n # @return [String] Name of the object.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Trigger scalein when alerts due to any of these alert configurations are raised.,It is a reference to an object of type alertconfig.\n attribute :scalein_alertconfig_refs\n\n # @return [Object, nil] Cooldown period during which no new scalein is triggered to allow previous scalein to successfully complete.,Default value when not specified in API or module is interpreted by Avi Controller as 300.,Units(SEC).\n attribute :scalein_cooldown\n\n # @return [Object, nil] Trigger scaleout when alerts due to any of these alert configurations are raised.,It is a reference to an object of type alertconfig.\n attribute :scaleout_alertconfig_refs\n\n # @return [Object, nil] Cooldown period during which no new scaleout is triggered to allow previous scaleout to successfully complete.,Default value when not specified in API or module is interpreted by Avi Controller as 300.,Units(SEC).\n attribute :scaleout_cooldown\n\n # @return [Object, nil] It is a reference to an object of type tenant.\n attribute :tenant_ref\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Symbol, nil] Use predicted load rather than current load.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :use_predicted_load\n validates :use_predicted_load, type: Symbol\n\n # @return [Object, nil] Unique object identifier of the object.\n attribute :uuid\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6769230961799622, "alphanum_fraction": 0.6769230961799622, "avg_line_length": 38, "blob_id": "a47b7388a10aac5dafc6bca6bcea4323b854eac0", "content_id": "ba140629447bb94f77e87ccf8b2f16163dba97cd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 975, "license_type": "permissive", "max_line_length": 209, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/storage/emc/emc_vnx_sg_member.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module manages the members of an existing storage group.\n class Emc_vnx_sg_member < Base\n # @return [String] Name of the Storage group to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Integer] Lun id to be added.\n attribute :lunid\n validates :lunid, presence: true, type: Integer\n\n # @return [:present, :absent, nil] Indicates the desired lunid state.,C(present) ensures specified lunid is present in the Storage Group.,C(absent) ensures specified lunid is absent from Storage Group.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6932325959205627, "alphanum_fraction": 0.6952937245368958, "avg_line_length": 65.15908813476562, "blob_id": "48526da2d70fe674aa3e27852899f80eadc1af41", "content_id": "5e581c60e5b2467928c7648f33cf43e922a9e472", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2911, "license_type": "permissive", "max_line_length": 375, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/remote_management/ucs/ucs_uuid_pool.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configures server UUID pools and UUID blocks on Cisco UCS Manager.\n # Examples can be used with the L(UCS Platform Emulator,https://communities.cisco.com/ucspe).\n class Ucs_uuid_pool < Base\n # @return [:present, :absent, nil] If C(present), will verify UUID pool is present and will create if needed.,If C(absent), will verify UUID pool is absent and will delete if needed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The name of the UUID pool.,This name can be between 1 and 32 alphanumeric characters.,You cannot use spaces or any special characters other than - (hyphen), \"_\" (underscore), : (colon), and . (period).,You cannot change this name after the UUID pool is created.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] The user-defined description of the UUID pool.,Enter up to 256 characters.,You can use any characters or spaces except the following:,` (accent mark), (backslash), ^ (carat), \" (double quote), = (equal sign), > (greater than), < (less than), or ' (single quote).\n attribute :description\n\n # @return [Object, nil] UUID prefix used for the range of server UUIDs.,If no value is provided, the system derived prefix will be used (equivalent to selecting 'derived' option in UI).,If the user provides a value, the user provided prefix will be used (equivalent to selecting 'other' option in UI).,A user provided value should be in the format XXXXXXXX-XXXX-XXXX.\n attribute :prefix\n\n # @return [:default, :sequential, nil] The Assignment Order field.,This can be one of the following:,default - Cisco UCS Manager selects a random identity from the pool.,sequential - Cisco UCS Manager selects the lowest available identity from the pool.\n attribute :order\n validates :order, expression_inclusion: {:in=>[:default, :sequential], :message=>\"%{value} needs to be :default, :sequential\"}, allow_nil: true\n\n # @return [String, nil] The first UUID in the block of UUIDs.,This is the From field in the UCS Manager UUID Blocks menu.\n attribute :first_uuid\n validates :first_uuid, type: String\n\n # @return [String, nil] The last UUID in the block of UUIDs.,This is the To field in the UCS Manager Add UUID Blocks menu.\n attribute :last_uuid\n validates :last_uuid, type: String\n\n # @return [String, nil] The distinguished name (dn) of the organization where the resource is assigned.\n attribute :org_dn\n validates :org_dn, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6741552352905273, "alphanum_fraction": 0.6828815340995789, "avg_line_length": 56.29787063598633, "blob_id": "43712242d96b329b3c0f05b50b59ad1c8f4ea0f6", "content_id": "438b53165f403819e2d701ac668cec5371ff2e23", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5386, "license_type": "permissive", "max_line_length": 397, "num_lines": 94, "path": "/lib/ansible/ruby/modules/generated/cloud/docker/docker_swarm.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create a new Swarm cluster.\n # Add/Remove nodes or managers to an existing cluster.\n class Docker_swarm < Base\n # @return [String, nil] Externally reachable address advertised to other nodes.,This can either be an address/port combination in the form C(192.168.1.1:4567), or an interface followed by a port number, like C(eth0:4567).,If the port number is omitted, the port number from the listen address is used.,If C(advertise_addr) is not specified, it will be automatically detected when possible.\n attribute :advertise_addr\n validates :advertise_addr, type: String\n\n # @return [String, nil] Listen address used for inter-manager communication.,This can either be an address/port combination in the form C(192.168.1.1:4567), or an interface followed by a port number, like C(eth0:4567).,If the port number is omitted, the default swarm listening port is used.\n attribute :listen_addr\n validates :listen_addr, type: String\n\n # @return [:yes, :no, nil] Use with state C(present) to force creating a new Swarm, even if already part of one.,Use with state C(absent) to Leave the swarm even if this node is a manager.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :join, :absent, :remove, :inspect] Set to C(present), to create/update a new cluster.,Set to C(join), to join an existing cluster.,Set to C(absent), to leave an existing cluster.,Set to C(remove), to remove an absent node from the cluster.,Set to C(inspect) to display swarm informations.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :join, :absent, :remove, :inspect], :message=>\"%{value} needs to be :present, :join, :absent, :remove, :inspect\"}\n\n # @return [String, nil] Swarm id of the node to remove.,Used with I(state=remove).\n attribute :node_id\n validates :node_id, type: String\n\n # @return [String, nil] Swarm token used to join a swarm cluster.,Used with I(state=join).\n attribute :join_token\n validates :join_token, type: String\n\n # @return [Array<String>, String, nil] Remote address of a manager to connect to.,Used with I(state=join).\n attribute :remote_addrs\n validates :remote_addrs, type: TypeGeneric.new(String)\n\n # @return [Object, nil] Maximum number of tasks history stored.,Docker default value is C(5).\n attribute :task_history_retention_limit\n\n # @return [Object, nil] Number of logs entries between snapshot.,Docker default value is C(10000).\n attribute :snapshot_interval\n\n # @return [Object, nil] Number of snapshots to keep beyond the current snapshot.,Docker default value is C(0).\n attribute :keep_old_snapshots\n\n # @return [Object, nil] Number of log entries to keep around to sync up slow followers after a snapshot is created.\n attribute :log_entries_for_slow_followers\n\n # @return [Object, nil] Amount of ticks (in seconds) between each heartbeat.,Docker default value is C(1s).\n attribute :heartbeat_tick\n\n # @return [Integer, nil] Amount of ticks (in seconds) needed without a leader to trigger a new election.,Docker default value is C(10s).\n attribute :election_tick\n validates :election_tick, type: Integer\n\n # @return [Object, nil] The delay for an agent to send a heartbeat to the dispatcher.,Docker default value is C(5s).\n attribute :dispatcher_heartbeat_period\n\n # @return [Object, nil] Automatic expiry for nodes certificates.,Docker default value is C(3months).\n attribute :node_cert_expiry\n\n # @return [Object, nil] The name of the swarm.\n attribute :name\n\n # @return [Object, nil] User-defined key/value metadata.\n attribute :labels\n\n # @return [Object, nil] The desired signing CA certificate for all swarm node TLS leaf certificates, in PEM format.\n attribute :signing_ca_cert\n\n # @return [Object, nil] The desired signing CA key for all swarm node TLS leaf certificates, in PEM format.\n attribute :signing_ca_key\n\n # @return [Object, nil] An integer whose purpose is to force swarm to generate a new signing CA certificate and key, if none have been specified.,Docker default value is C(0).\n attribute :ca_force_rotate\n\n # @return [Symbol, nil] If set, generate a key and use it to lock data stored on the managers.,Docker default value is C(no).\n attribute :autolock_managers\n validates :autolock_managers, type: Symbol\n\n # @return [:yes, :no, nil] Rotate the worker join token.\n attribute :rotate_worker_token\n validates :rotate_worker_token, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Rotate the manager join token.\n attribute :rotate_manager_token\n validates :rotate_manager_token, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6998567581176758, "alphanum_fraction": 0.6998567581176758, "avg_line_length": 47.98245620727539, "blob_id": "94db67c709fddcb42a98c6ebcecb9a7fde13eb3c", "content_id": "16b3d7c2ea065b2ae235f8db1b76059ed8755087", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2792, "license_type": "permissive", "max_line_length": 331, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_snapmirror.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create/Delete/Initialize/Modify SnapMirror volume/vserver relationships\n class Na_ontap_snapmirror < Base\n # @return [:present, :absent, nil] Whether the specified relationship should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Specifies the name of the source volume for the SnapMirror.\n attribute :source_volume\n validates :source_volume, type: String\n\n # @return [String, nil] Specifies the name of the destination volume for the SnapMirror.\n attribute :destination_volume\n validates :destination_volume, type: String\n\n # @return [String, nil] Name of the source vserver for the SnapMirror.\n attribute :source_vserver\n validates :source_vserver, type: String\n\n # @return [String, nil] Name of the destination vserver for the SnapMirror.\n attribute :destination_vserver\n validates :destination_vserver, type: String\n\n # @return [Object, nil] Specifies the source endpoint of the SnapMirror relationship.\n attribute :source_path\n\n # @return [String, nil] Specifies the destination endpoint of the SnapMirror relationship.\n attribute :destination_path\n validates :destination_path, type: String\n\n # @return [:data_protection, :load_sharing, :vault, :restore, :transition_data_protection, :extended_data_protection, nil] Specify the type of SnapMirror relationship.\n attribute :relationship_type\n validates :relationship_type, expression_inclusion: {:in=>[:data_protection, :load_sharing, :vault, :restore, :transition_data_protection, :extended_data_protection], :message=>\"%{value} needs to be :data_protection, :load_sharing, :vault, :restore, :transition_data_protection, :extended_data_protection\"}, allow_nil: true\n\n # @return [String, nil] Specify the name of the current schedule, which is used to update the SnapMirror relationship.,Optional for create, modifiable.\n attribute :schedule\n validates :schedule, type: String\n\n # @return [Object, nil] Source hostname or IP address.,Required for SnapMirror delete\n attribute :source_hostname\n\n # @return [Object, nil] Source username.,Optional if this is same as destination username.\n attribute :source_username\n\n # @return [Object, nil] Source password.,Optional if this is same as destination password.\n attribute :source_password\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6804341077804565, "alphanum_fraction": 0.6813385486602783, "avg_line_length": 48.50746154785156, "blob_id": "c1366feca846f3343567d1bd74052e434eca2104", "content_id": "63c925cbd90eab2a2c30970cd0f4a12556123665", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3317, "license_type": "permissive", "max_line_length": 241, "num_lines": 67, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_scheduler.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure Scheduler object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_scheduler < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Object, nil] Backup configuration to be executed by this scheduler.,It is a reference to an object of type backupconfiguration.\n attribute :backup_config_ref\n\n # @return [Symbol, nil] Boolean flag to set enabled.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :enabled\n validates :enabled, type: Symbol\n\n # @return [Object, nil] Scheduler end date and time.\n attribute :end_date_time\n\n # @return [Object, nil] Frequency at which custom scheduler will run.,Allowed values are 0-60.\n attribute :frequency\n\n # @return [Object, nil] Unit at which custom scheduler will run.,Enum options - SCHEDULER_FREQUENCY_UNIT_MIN, SCHEDULER_FREQUENCY_UNIT_HOUR, SCHEDULER_FREQUENCY_UNIT_DAY, SCHEDULER_FREQUENCY_UNIT_WEEK,,SCHEDULER_FREQUENCY_UNIT_MONTH.\n attribute :frequency_unit\n\n # @return [String] Name of scheduler.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Scheduler run mode.,Enum options - RUN_MODE_PERIODIC, RUN_MODE_AT, RUN_MODE_NOW.\n attribute :run_mode\n\n # @return [Object, nil] Control script to be executed by this scheduler.,It is a reference to an object of type alertscriptconfig.\n attribute :run_script_ref\n\n # @return [Object, nil] Define scheduler action.,Enum options - SCHEDULER_ACTION_RUN_A_SCRIPT, SCHEDULER_ACTION_BACKUP.,Default value when not specified in API or module is interpreted by Avi Controller as SCHEDULER_ACTION_BACKUP.\n attribute :scheduler_action\n\n # @return [Object, nil] Scheduler start date and time.\n attribute :start_date_time\n\n # @return [Object, nil] It is a reference to an object of type tenant.\n attribute :tenant_ref\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Unique object identifier of the object.\n attribute :uuid\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6510593891143799, "alphanum_fraction": 0.6800941824913025, "avg_line_length": 85.88636016845703, "blob_id": "7482c5e344533feacd7f02fbce8e2349a2567c86", "content_id": "9e73f14786c5fbd6084ee7edb25c98b363957547", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3823, "license_type": "permissive", "max_line_length": 669, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_domain.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage physical, virtual, bridged, routed or FC domain profiles on Cisco ACI fabrics.\n class Aci_domain < Base\n # @return [String, nil] Name of the physical, virtual, bridged routed or FC domain profile.\n attribute :domain\n validates :domain, type: String\n\n # @return [:fc, :l2dom, :l3dom, :phys, :vmm, nil] The type of domain profile.,C(fc): The FC domain profile is a policy pertaining to single FC Management domain,C(l2dom): The external bridged domain profile is a policy for managing L2 bridged infrastructure bridged outside the fabric.,C(l3dom): The external routed domain profile is a policy for managing L3 routed infrastructure outside the fabric.,C(phys): The physical domain profile stores the physical resources and encap resources that should be used for EPGs associated with this domain.,C(vmm): The VMM domain profile is a policy for grouping VM controllers with similar networking policy requirements.\n attribute :domain_type\n validates :domain_type, expression_inclusion: {:in=>[:fc, :l2dom, :l3dom, :phys, :vmm], :message=>\"%{value} needs to be :fc, :l2dom, :l3dom, :phys, :vmm\"}, allow_nil: true\n\n # @return [:AF11, :AF12, :AF13, :AF21, :AF22, :AF23, :AF31, :AF32, :AF33, :AF41, :AF42, :AF43, :CS0, :CS1, :CS2, :CS3, :CS4, :CS5, :CS6, :CS7, :EF, :VA, :unspecified, nil] The target Differentiated Service (DSCP) value.,The APIC defaults to C(unspecified) when unset during creation.\n attribute :dscp\n validates :dscp, expression_inclusion: {:in=>[:AF11, :AF12, :AF13, :AF21, :AF22, :AF23, :AF31, :AF32, :AF33, :AF41, :AF42, :AF43, :CS0, :CS1, :CS2, :CS3, :CS4, :CS5, :CS6, :CS7, :EF, :VA, :unspecified], :message=>\"%{value} needs to be :AF11, :AF12, :AF13, :AF21, :AF22, :AF23, :AF31, :AF32, :AF33, :AF41, :AF42, :AF43, :CS0, :CS1, :CS2, :CS3, :CS4, :CS5, :CS6, :CS7, :EF, :VA, :unspecified\"}, allow_nil: true\n\n # @return [:unknown, :vlan, :vxlan, nil] The layer 2 encapsulation protocol to use with the virtual switch.\n attribute :encap_mode\n validates :encap_mode, expression_inclusion: {:in=>[:unknown, :vlan, :vxlan], :message=>\"%{value} needs to be :unknown, :vlan, :vxlan\"}, allow_nil: true\n\n # @return [Object, nil] The muticast IP address to use for the virtual switch.\n attribute :multicast_address\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n\n # @return [:cloudfoundry, :kubernetes, :microsoft, :openshift, :openstack, :redhat, :vmware, nil] The VM platform for VMM Domains.,Support for Kubernetes was added in ACI v3.0.,Support for CloudFoundry, OpenShift and Red Hat was added in ACI v3.1.\n attribute :vm_provider\n validates :vm_provider, expression_inclusion: {:in=>[:cloudfoundry, :kubernetes, :microsoft, :openshift, :openstack, :redhat, :vmware], :message=>\"%{value} needs to be :cloudfoundry, :kubernetes, :microsoft, :openshift, :openstack, :redhat, :vmware\"}, allow_nil: true\n\n # @return [:avs, :default, :dvs, :unknown, nil] The virtual switch to use for vmm domains.,The APIC defaults to C(default) when unset during creation.\n attribute :vswitch\n validates :vswitch, expression_inclusion: {:in=>[:avs, :default, :dvs, :unknown], :message=>\"%{value} needs to be :avs, :default, :dvs, :unknown\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6884422302246094, "alphanum_fraction": 0.6884422302246094, "avg_line_length": 34.117645263671875, "blob_id": "72b7c9a6a55588ecbbc43849a1361649783afcd4", "content_id": "1b1b17d9571bb2c0c5f9bfc23028597c9dc09a22", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 597, "license_type": "permissive", "max_line_length": 133, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vca_fw.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Adds or removes firewall rules from a gateway in a vca environment\n class Vca_fw < Base\n # @return [Boolean] A list of firewall rules to be added to the gateway, Please see examples on valid entries\n attribute :fw_rules\n validates :fw_rules, presence: true, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7283950448036194, "alphanum_fraction": 0.7283950448036194, "avg_line_length": 46.64706039428711, "blob_id": "9101d06f87d31d2b733af04749de2661f99f835c", "content_id": "9a2041f83b35fcddf2db47914e4b63f0d52cd1f5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 810, "license_type": "permissive", "max_line_length": 395, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_pim.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages configuration of a Protocol Independent Multicast (PIM) instance.\n class Nxos_pim < Base\n # @return [String] Configure group ranges for Source Specific Multicast (SSM). Valid values are multicast addresses or the keyword C(none) or keyword C(default). C(none) removes all SSM group ranges. C(default) will set ssm_range to the default multicast address. If you set multicast address, please ensure that it is not the same as the C(default), otherwise use the C(default) option.\n attribute :ssm_range\n validates :ssm_range, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.680705726146698, "alphanum_fraction": 0.6809903383255005, "avg_line_length": 54.77777862548828, "blob_id": "638e9a1611a0315469c8c5d591ed51ed4de6698e", "content_id": "9905b348b83ed71d0fd4a48883ad62cdfa391f9c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3514, "license_type": "permissive", "max_line_length": 205, "num_lines": 63, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/iam.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows for the management of IAM users, user API keys, groups, roles.\n class Iam < Base\n # @return [:user, :group, :role, nil] Type of IAM resource\n attribute :iam_type\n validates :iam_type, expression_inclusion: {:in=>[:user, :group, :role], :message=>\"%{value} needs to be :user, :group, :role\"}, allow_nil: true\n\n # @return [String] Name of IAM resource to create or identify\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] When state is update, will replace name with new_name on IAM resource\n attribute :new_name\n\n # @return [Object, nil] When state is update, will replace the path with new_path on the IAM resource\n attribute :new_path\n\n # @return [:present, :absent, :update] Whether to create, delete or update the IAM resource. Note, roles cannot be updated.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent, :update], :message=>\"%{value} needs to be :present, :absent, :update\"}\n\n # @return [String, nil] When creating or updating, specify the desired path of the resource. If state is present, it will replace the current path to match what is passed in when they do not match.\n attribute :path\n validates :path, type: String\n\n # @return [Object, nil] The inline (JSON or YAML) trust policy document that grants an entity permission to assume the role. Mutually exclusive with C(trust_policy_filepath).\n attribute :trust_policy\n\n # @return [Object, nil] The path to the trust policy document that grants an entity permission to assume the role. Mutually exclusive with C(trust_policy).\n attribute :trust_policy_filepath\n\n # @return [:create, :remove, :active, :inactive, nil] When type is user, it creates, removes, deactivates or activates a user's access key(s). Note that actions apply only to keys specified.\n attribute :access_key_state\n validates :access_key_state, expression_inclusion: {:in=>[:create, :remove, :active, :inactive], :message=>\"%{value} needs to be :create, :remove, :active, :inactive\"}, allow_nil: true\n\n # @return [String, nil] When access_key_state is create it will ensure this quantity of keys are present. Defaults to 1.\n attribute :key_count\n validates :key_count, type: String\n\n # @return [Object, nil] A list of the keys that you want impacted by the access_key_state parameter.\n attribute :access_key_ids\n\n # @return [Object, nil] A list of groups the user should belong to. When update, will gracefully remove groups not listed.\n attribute :groups\n\n # @return [String, nil] When type is user and state is present, define the users login password. Also works with update. Note that always returns changed.\n attribute :password\n validates :password, type: String\n\n # @return [:always, :on_create, nil] C(always) will update passwords if they differ. C(on_create) will only set the password for newly created users.\n attribute :update_password\n validates :update_password, expression_inclusion: {:in=>[:always, :on_create], :message=>\"%{value} needs to be :always, :on_create\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6975040435791016, "alphanum_fraction": 0.6985892653465271, "avg_line_length": 56.59375, "blob_id": "4da5da877a3c123e9296a2a19ebb954eef00a928", "content_id": "23c4fb7e9ae9bc90870608a73c2a44f51dd293d0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3686, "license_type": "permissive", "max_line_length": 410, "num_lines": 64, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_pkiprofile.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure PKIProfile object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_pkiprofile < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Object, nil] List of certificate authorities (root and intermediate) trusted that is used for certificate validation.\n attribute :ca_certs\n\n # @return [Object, nil] Creator name.\n attribute :created_by\n\n # @return [Symbol, nil] When enabled, avi will verify via crl checks that certificates in the trust chain have not been revoked.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :crl_check\n validates :crl_check, type: Symbol\n\n # @return [Object, nil] Certificate revocation lists.\n attribute :crls\n\n # @return [Symbol, nil] When enabled, avi will not trust intermediate and root certs presented by a client.,Instead, only the chain certs configured in the certificate authority section will be used to verify trust of the client's cert.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :ignore_peer_chain\n validates :ignore_peer_chain, type: Symbol\n\n # @return [Symbol, nil] This field describes the object's replication scope.,If the field is set to false, then the object is visible within the controller-cluster and its associated service-engines.,If the field is set to true, then the object is replicated across the federation.,Field introduced in 17.1.3.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :is_federated\n validates :is_federated, type: Symbol\n\n # @return [String] Name of the pki profile.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] It is a reference to an object of type tenant.\n attribute :tenant_ref\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Unique object identifier of the object.\n attribute :uuid\n\n # @return [Symbol, nil] When enabled, avi will only validate the revocation status of the leaf certificate using crl.,To enable validation for the entire chain, disable this option and provide all the relevant crls.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :validate_only_leaf_crl\n validates :validate_only_leaf_crl, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6928487420082092, "alphanum_fraction": 0.6951934099197388, "avg_line_length": 46.38888931274414, "blob_id": "be224e1339f9eb69e96c505dba5f9e4d9d15042e", "content_id": "8c5d15accf134f79e410814770109fa6c96910fe", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 853, "license_type": "permissive", "max_line_length": 294, "num_lines": 18, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_vm_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Return basic facts pertaining to a vSphere virtual machine guest.\n # Cluster name as fact is added in version 2.7.\n class Vmware_vm_facts < Base\n # @return [:all, :vm, :template, nil] If set to C(vm), then facts are gathered for virtual machines only.,If set to C(template), then facts are gathered for virtual machine templates only.,If set to C(all), then facts are gathered for all virtual machines and virtual machine templates.\n attribute :vm_type\n validates :vm_type, expression_inclusion: {:in=>[:all, :vm, :template], :message=>\"%{value} needs to be :all, :vm, :template\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6721901893615723, "alphanum_fraction": 0.6721901893615723, "avg_line_length": 46.86206817626953, "blob_id": "b4f55985c0f142235e27d5e8139c20e7882e23f7", "content_id": "d9ba16dbbca3d61e577fce925d1e41d9c4e86100", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1388, "license_type": "permissive", "max_line_length": 203, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/network/junos/junos_scp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module transfers files via SCP from or to remote devices running Junos.\n class Junos_scp < Base\n # @return [String] The C(src) argument takes a single path, or a list of paths to be transfered. The argument C(recursive) must be C(true) to transfer directories.\n attribute :src\n validates :src, presence: true, type: String\n\n # @return [String, nil] The C(dest) argument specifies the path in which to receive the files.\n attribute :dest\n validates :dest, type: String\n\n # @return [:yes, :no, nil] The C(recursive) argument enables recursive transfer of files and directories.\n attribute :recursive\n validates :recursive, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] The C(remote_src) argument enables the download of files (I(scp get)) from the remote device. The default behavior is to upload files (I(scp put)) to the remote device.\n attribute :remote_src\n validates :remote_src, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6899999976158142, "alphanum_fraction": 0.6899999976158142, "avg_line_length": 20.428571701049805, "blob_id": "42dd00edfd3f30a85b34979ed71ef158d5513e48", "content_id": "c592281176174221ff7467b2bc7211105b0241bf", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 300, "license_type": "permissive", "max_line_length": 49, "num_lines": 14, "path": "/spec/support/matchers/have_errors.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nRSpec::Matchers.define :have_errors do |expected|\n match do |actual|\n actual.valid? # trigger validation\n errors = actual.errors.to_h\n @matcher = eq(expected)\n @matcher.matches? errors\n end\n\n failure_message do |_|\n @matcher.failure_message\n end\nend\n" }, { "alpha_fraction": 0.6566806435585022, "alphanum_fraction": 0.6656680703163147, "avg_line_length": 44.10810852050781, "blob_id": "559118bf9b0c72bb95021f6d707ba8b9a995c367", "content_id": "17cad9bad09f5d34e192ecf9d1e4ebf9413ce649", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1669, "license_type": "permissive", "max_line_length": 281, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_ntp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages core NTP configuration on HUAWEI CloudEngine switches.\n class Ce_ntp < Base\n # @return [Object, nil] Network address of NTP server.\n attribute :server\n\n # @return [Object, nil] Network address of NTP peer.\n attribute :peer\n\n # @return [Object, nil] Authentication key identifier to use with given NTP server or peer.\n attribute :key_id\n\n # @return [:enable, :disable, nil] Makes given NTP server or peer the preferred NTP server or peer for the device.\n attribute :is_preferred\n validates :is_preferred, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [String, nil] Makes the device communicate with the given NTP server or peer over a specific vpn.\n attribute :vpn_name\n validates :vpn_name, type: String\n\n # @return [Object, nil] Local source interface from which NTP messages are sent. Must be fully qualified interface name, i.e. C(40GE1/0/22), C(vlanif10). Interface types, such as C(10GE), C(40GE), C(100GE), C(Eth-Trunk), C(LoopBack), C(MEth), C(NULL), C(Tunnel), C(Vlanif).\n attribute :source_int\n\n # @return [:present, :absent, nil] Manage the state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6700528264045715, "alphanum_fraction": 0.6700528264045715, "avg_line_length": 53.68888854980469, "blob_id": "4644a84b942532027207ad4866265977b6834bb9", "content_id": "4b98209c8707604e3689499243ffa5ef5652acef", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2461, "license_type": "permissive", "max_line_length": 461, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_elementsw_volume_clone.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create volume clones on Element OS\n class Na_elementsw_volume_clone < Base\n # @return [String] The name of the clone.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Integer] The id of the src volume to clone. id may be a numeric identifier or a volume name.\n attribute :src_volume_id\n validates :src_volume_id, presence: true, type: Integer\n\n # @return [Integer, nil] The id of the snapshot to clone. id may be a numeric identifier or a snapshot name.\n attribute :src_snapshot_id\n validates :src_snapshot_id, type: Integer\n\n # @return [Integer] Account ID for the owner of this cloned volume. id may be a numeric identifier or an account name.\n attribute :account_id\n validates :account_id, presence: true, type: Integer\n\n # @return [Hash, nil] A YAML dictionary of attributes that you would like to apply on this cloned volume.\n attribute :attributes\n validates :attributes, type: Hash\n\n # @return [Integer, nil] The size of the cloned volume in (size_unit).\n attribute :size\n validates :size, type: Integer\n\n # @return [:bytes, :b, :kb, :mb, :gb, :tb, :pb, :eb, :zb, :yb, nil] The unit used to interpret the size parameter.\n attribute :size_unit\n validates :size_unit, expression_inclusion: {:in=>[:bytes, :b, :kb, :mb, :gb, :tb, :pb, :eb, :zb, :yb], :message=>\"%{value} needs to be :bytes, :b, :kb, :mb, :gb, :tb, :pb, :eb, :zb, :yb\"}, allow_nil: true\n\n # @return [:readOnly, :readWrite, :locked, :replicationTarget, nil] Access allowed for the volume.,If unspecified, the access settings of the clone will be the same as the source.,readOnly - Only read operations are allowed.,readWrite - Reads and writes are allowed.,locked - No reads or writes are allowed.,replicationTarget - Identify a volume as the target volume for a paired set of volumes. If the volume is not paired, the access status is locked.\n attribute :access\n validates :access, expression_inclusion: {:in=>[:readOnly, :readWrite, :locked, :replicationTarget], :message=>\"%{value} needs to be :readOnly, :readWrite, :locked, :replicationTarget\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6993716955184937, "alphanum_fraction": 0.6993716955184937, "avg_line_length": 52.0512809753418, "blob_id": "892380a1aea1dc92fcfd96bee7aaf4d88f5ad4dc", "content_id": "0683d71ab9590584582376a5662a84b855669b40", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2069, "license_type": "permissive", "max_line_length": 268, "num_lines": 39, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/netapp_e_host.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, remove hosts on NetApp E-series storage arrays\n class Netapp_e_host < Base\n # @return [String] If the host doesn't yet exist, the label/name to assign at creation time.,If the hosts already exists, this will be used to uniquely identify the host to make any required changes\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, nil] Set to absent to remove an existing host,Set to present to modify or create a new host definition\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [Integer, nil] The index that maps to host type you wish to create. It is recommended to use the M(netapp_e_facts) module to gather this information. Alternatively you can use the WSP portal to retrieve the information.,Required when C(state=present)\n attribute :host_type_index\n validates :host_type_index, type: Integer\n\n # @return [Array<Hash>, Hash, nil] A list of host ports you wish to associate with the host.,Host ports are uniquely identified by their WWN or IQN. Their assignments to a particular host are uniquely identified by a label and these must be unique.\n attribute :ports\n validates :ports, type: TypeGeneric.new(Hash)\n\n # @return [Symbol, nil] Allow ports that are already assigned to be re-assigned to your current host\n attribute :force_port\n validates :force_port, type: Symbol\n\n # @return [Object, nil] The unique identifier of the host-group you want the host to be a member of; this is used for clustering.\n attribute :group\n\n # @return [Object, nil] A local path to a file to be used for debug logging\n attribute :log_path\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6845238208770752, "alphanum_fraction": 0.6916666626930237, "avg_line_length": 48.411766052246094, "blob_id": "c8a4b95c57bf7cb5c8919703651308ead6018ef1", "content_id": "a8d35cee6bb2a6bf8160ef4528e976a003287161", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2520, "license_type": "permissive", "max_line_length": 293, "num_lines": 51, "path": "/lib/ansible/ruby/modules/generated/net_tools/nios/nios_srv_record.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Adds and/or removes instances of SRV record objects from Infoblox NIOS servers. This module manages NIOS C(record:srv) objects using the Infoblox WAPI interface over REST.\n class Nios_srv_record < Base\n # @return [String] Specifies the fully qualified hostname to add or remove from the system\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] Sets the DNS view to associate this a record with. The DNS view must already be configured on the system\n attribute :view\n validates :view, presence: true, type: String\n\n # @return [Integer] Configures the port (0-65535) of this SRV record.\n attribute :port\n validates :port, presence: true, type: Integer\n\n # @return [Integer] Configures the priority (0-65535) for this SRV record.\n attribute :priority\n validates :priority, presence: true, type: Integer\n\n # @return [String] Configures the target FQDN for this SRV record.\n attribute :target\n validates :target, presence: true, type: String\n\n # @return [Integer] Configures the weight (0-65535) for this SRV record.\n attribute :weight\n validates :weight, presence: true, type: Integer\n\n # @return [Object, nil] Configures the TTL to be associated with this host record\n attribute :ttl\n\n # @return [Object, nil] Allows for the configuration of Extensible Attributes on the instance of the object. This argument accepts a set of key / value pairs for configuration.\n attribute :extattrs\n\n # @return [String, nil] Configures a text string comment to be associated with the instance of this object. The provided text string will be configured on the object instance.\n attribute :comment\n validates :comment, type: String\n\n # @return [:present, :absent, nil] Configures the intended state of the instance of the object on the NIOS server. When this value is set to C(present), the object is configured on the device and when this value is set to C(absent) the value is removed (if necessary) from the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6857749223709106, "alphanum_fraction": 0.6857749223709106, "avg_line_length": 26.705883026123047, "blob_id": "4678e34711d4e958874754f241f70652ab818838", "content_id": "e1528a77c2e599bdd00db589e06baec7fb91b78c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 471, "license_type": "permissive", "max_line_length": 88, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/remote_management/oneview/oneview_fc_network_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Retrieve the facts about one or more of the Fibre Channel Networks from OneView.\n class Oneview_fc_network_facts < Base\n # @return [String, nil] Fibre Channel Network name.\n attribute :name\n validates :name, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.698051929473877, "alphanum_fraction": 0.6996753215789795, "avg_line_length": 46.38461685180664, "blob_id": "df8cfb942a37f2e6a06c3a0373c1deae45e65086", "content_id": "ba4e3d779c290d79f777db7c6688c2031af5ac51", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1232, "license_type": "permissive", "max_line_length": 249, "num_lines": 26, "path": "/lib/ansible/ruby/modules/generated/packaging/os/package.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Installs, upgrade and removes packages using the underlying OS package manager.\n # For Windows targets, use the M(win_package) module instead.\n class Package < Base\n # @return [String] Package name, or package specifier with version, like C(name-1.0).,Be aware that packages are not always named the same and this module will not 'translate' them per distro.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] Whether to install (C(present)), or remove (C(absent)) a package. Other states depend on the underlying package module, i.e C(latest).\n attribute :state\n validates :state, presence: true, type: String\n\n # @return [String, nil] The required package manager module to use (yum, apt, etc). The default 'auto' will use existing facts or try to autodetect it.,You should only use this field if the automatic selection is not working for some reason.\n attribute :use\n validates :use, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6904761791229248, "alphanum_fraction": 0.6904761791229248, "avg_line_length": 38.45454406738281, "blob_id": "bf1d266bf0ebcc2f2f8ff5fa12cff6bd56270a3b", "content_id": "c50ed0152ac4915af775b13c2a991eff23420d49", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1302, "license_type": "permissive", "max_line_length": 153, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/utilities/logic/wait_for_connection.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Waits for a total of C(timeout) seconds.\n # Retries the transport connection after a timeout of C(connect_timeout).\n # Tests the transport connection every C(sleep) seconds.\n # This module makes use of internal ansible transport (and configuration) and the ping/win_ping module to guarantee correct end-to-end functioning.\n # This module is also supported for Windows targets.\n class Wait_for_connection < Base\n # @return [Integer, nil] Maximum number of seconds to wait for a connection to happen before closing and retrying.\n attribute :connect_timeout\n validates :connect_timeout, type: Integer\n\n # @return [Integer, nil] Number of seconds to wait before starting to poll.\n attribute :delay\n validates :delay, type: Integer\n\n # @return [Integer, nil] Number of seconds to sleep between checks.\n attribute :sleep\n validates :sleep, type: Integer\n\n # @return [Integer, nil] Maximum number of seconds to wait for.\n attribute :timeout\n validates :timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6874695420265198, "alphanum_fraction": 0.6874695420265198, "avg_line_length": 50.275001525878906, "blob_id": "d0788b70b8b9477d164ff64dc32cf0a730cb6015", "content_id": "8940b7839da242d3b8ace991a6ce65afbb359bcf", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2051, "license_type": "permissive", "max_line_length": 276, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/network/aos/aos_blueprint.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Apstra AOS Blueprint module let you manage your Blueprint easily. You can create create and delete Blueprint by Name or ID. You can also use it to retrieve all data from a blueprint. This module is idempotent and support the I(check) mode. It's using the AOS REST API.\n class Aos_blueprint < Base\n # @return [String] An existing AOS session as obtained by M(aos_login) module.\n attribute :session\n validates :session, presence: true, type: String\n\n # @return [String, nil] Name of the Blueprint to manage. Only one of I(name) or I(id) can be set.\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] AOS Id of the IP Pool to manage (can't be used to create a new IP Pool). Only one of I(name) or I(id) can be set.\n attribute :id\n\n # @return [:present, :absent, :\"build-ready\", nil] Indicate what is the expected state of the Blueprint.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :\"build-ready\"], :message=>\"%{value} needs to be :present, :absent, :\\\"build-ready\\\"\"}, allow_nil: true\n\n # @return [Integer, nil] When I(state=build-ready), this timeout identifies timeout in seconds to wait before declaring a failure.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [String, nil] When creating a blueprint, this value identifies, by name, an existing engineering design template within the AOS-server.\n attribute :template\n validates :template, type: String\n\n # @return [String, nil] When creating a blueprint, this value identifies a known AOS reference architecture value. I(Refer to AOS-server documentation for available values).\n attribute :reference_arch\n validates :reference_arch, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6574816703796387, "alphanum_fraction": 0.6574816703796387, "avg_line_length": 41.791046142578125, "blob_id": "502df4766d9ce275ae9e1d02854768df916d8149", "content_id": "738832f4f0086a9110c1b7842330831a241bb37d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2867, "license_type": "permissive", "max_line_length": 177, "num_lines": 67, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_ipaddrgroup.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure IpAddrGroup object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_ipaddrgroup < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Object, nil] Configure ip address(es).\n attribute :addrs\n\n # @return [Object, nil] Populate ip addresses from members of this cisco apic epg.\n attribute :apic_epg_name\n\n # @return [Object, nil] Populate the ip address ranges from the geo database for this country.\n attribute :country_codes\n\n # @return [Object, nil] User defined description for the object.\n attribute :description\n\n # @return [Object, nil] Configure (ip address, port) tuple(s).\n attribute :ip_ports\n\n # @return [Object, nil] Populate ip addresses from tasks of this marathon app.\n attribute :marathon_app_name\n\n # @return [Object, nil] Task port associated with marathon service port.,If marathon app has multiple service ports, this is required.,Else, the first task port is used.\n attribute :marathon_service_port\n\n # @return [String] Name of the ip address group.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Array<Hash>, Hash, nil] Configure ip address prefix(es).\n attribute :prefixes\n validates :prefixes, type: TypeGeneric.new(Hash)\n\n # @return [Object, nil] Configure ip address range(s).\n attribute :ranges\n\n # @return [Object, nil] It is a reference to an object of type tenant.\n attribute :tenant_ref\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Uuid of the ip address group.\n attribute :uuid\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6990866661071777, "alphanum_fraction": 0.7003208994865417, "avg_line_length": 70.07017517089844, "blob_id": "d83bcee8ecfec412ee6dbabf91baa9ce8b6895c3", "content_id": "822f8ca7043461a2074d27b1e9e7be1576c22419", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4051, "license_type": "permissive", "max_line_length": 760, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/system/pamd.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Edit PAM service's type, control, module path and module arguments. In order for a PAM rule to be modified, the type, control and module_path must match an existing rule. See man(5) pam.d for details.\n class Pamd < Base\n # @return [String] The name generally refers to the PAM service file to change, for example system-auth.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] The type of the PAM rule being modified. The type, control and module_path all must match a rule to be modified.\n attribute :type\n validates :type, presence: true, type: String\n\n # @return [String] The control of the PAM rule being modified. This may be a complicated control with brackets. If this is the case, be sure to put \"[bracketed controls]\" in quotes. The type, control and module_path all must match a rule to be modified.\n attribute :control\n validates :control, presence: true, type: String\n\n # @return [String] The module path of the PAM rule being modified. The type, control and module_path all must match a rule to be modified.\n attribute :module_path\n validates :module_path, presence: true, type: String\n\n # @return [String, nil] The new type to assign to the new rule.\n attribute :new_type\n validates :new_type, type: String\n\n # @return [String, nil] The new control to assign to the new rule.\n attribute :new_control\n validates :new_control, type: String\n\n # @return [String, nil] The new module path to be assigned to the new rule.\n attribute :new_module_path\n validates :new_module_path, type: String\n\n # @return [Array<String>, String, nil] When state is 'updated', the module_arguments will replace existing module_arguments. When state is 'args_absent' args matching those listed in module_arguments will be removed. When state is 'args_present' any args listed in module_arguments are added if missing from the existing rule. Furthermore, if the module argument takes a value denoted by '=', the value will be changed to that specified in module_arguments. Note that module_arguments is a list. Please see the examples for usage.\n attribute :module_arguments\n validates :module_arguments, type: TypeGeneric.new(String)\n\n # @return [:updated, :before, :after, :args_present, :args_absent, :absent, nil] The default of 'updated' will modify an existing rule if type, control and module_path all match an existing rule. With 'before', the new rule will be inserted before a rule matching type, control and module_path. Similarly, with 'after', the new rule will be inserted after an existing rule matching type, control and module_path. With either 'before' or 'after' new_type, new_control, and new_module_path must all be specified. If state is 'args_absent' or 'args_present', new_type, new_control, and new_module_path will be ignored. State 'absent' will remove the rule. The 'absent' state was added in version 2.4 and is only available in Ansible versions >= 2.4.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:updated, :before, :after, :args_present, :args_absent, :absent], :message=>\"%{value} needs to be :updated, :before, :after, :args_present, :args_absent, :absent\"}, allow_nil: true\n\n # @return [String, nil] This is the path to the PAM service files\n attribute :path\n validates :path, type: String\n\n # @return [:yes, :no, nil] Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.\n attribute :backup\n validates :backup, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6653771996498108, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 38.769229888916016, "blob_id": "b86d36ca2cbead451e08a72d9d5f96c29e079d83", "content_id": "c944ca94528d1dbcac542dbb78217593de65cdd6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1551, "license_type": "permissive", "max_line_length": 142, "num_lines": 39, "path": "/lib/ansible/ruby/modules/generated/network/netvisor/pn_ospf.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Execute vrouter-ospf-add, vrouter-ospf-remove command.\n # This command adds/removes Open Shortest Path First(OSPF) routing protocol to a virtual router(vRouter) service.\n class Pn_ospf < Base\n # @return [Object, nil] Provide login username if user is not root.\n attribute :pn_cliusername\n\n # @return [Object, nil] Provide login password if user is not root.\n attribute :pn_clipassword\n\n # @return [Object, nil] Target switch to run the CLI on.\n attribute :pn_cliswitch\n\n # @return [:present, :absent] Assert the state of the ospf. Use 'present' to add ospf and 'absent' to remove ospf.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String] Specify the name of the vRouter.\n attribute :pn_vrouter_name\n validates :pn_vrouter_name, presence: true, type: String\n\n # @return [String] Specify the network IP (IPv4 or IPv6) address.\n attribute :pn_network_ip\n validates :pn_network_ip, presence: true, type: String\n\n # @return [String, nil] Stub area number for the configuration. Required for vrouter-ospf-add.\n attribute :pn_ospf_area\n validates :pn_ospf_area, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6813310980796814, "alphanum_fraction": 0.6835871338844299, "avg_line_length": 46.91891860961914, "blob_id": "d4fafc11a88b211f06bd7b6ea871674c0010a5ff", "content_id": "638a84e63e64e340ce4d71bae5076c314f5eded8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1773, "license_type": "permissive", "max_line_length": 268, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/crypto/openssl_publickey.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows one to (re)generate OpenSSL public keys from their private keys. It uses the pyOpenSSL python library to interact with openssl. Keys are generated in PEM format. This module works only if the version of PyOpenSSL is recent enough (> 16.0.0).\n class Openssl_publickey < Base\n # @return [:present, :absent, nil] Whether the public key should exist or not, taking action if the state is different from what is stated.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Symbol, nil] Should the key be regenerated even it it already exists\n attribute :force\n validates :force, type: Symbol\n\n # @return [:PEM, :OpenSSH, nil] The format of the public key.\n attribute :format\n validates :format, expression_inclusion: {:in=>[:PEM, :OpenSSH], :message=>\"%{value} needs to be :PEM, :OpenSSH\"}, allow_nil: true\n\n # @return [String] Name of the file in which the generated TLS/SSL public key will be written.\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [String] Path to the TLS/SSL private key from which to generate the public key.\n attribute :privatekey_path\n validates :privatekey_path, presence: true, type: String\n\n # @return [String, nil] The passphrase for the privatekey.\n attribute :privatekey_passphrase\n validates :privatekey_passphrase, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7360000014305115, "alphanum_fraction": 0.7546666860580444, "avg_line_length": 19.83333396911621, "blob_id": "530169482ec8866b2927f28554937d0fa6b83c24", "content_id": "b3c213b81be969ce70a4d0ee7ed64aa282f803e3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 375, "license_type": "permissive", "max_line_length": 66, "num_lines": 18, "path": "/lib/ansible/ruby/modules/custom/files/file.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# VALIDATED_CHECKSUM: Dz9MDnujKS00A1DPsWXKqLpdXm8Brg2cTM9hcPcdxKI=\n\n# see LICENSE.txt in project root\n\nrequire 'ansible/ruby/modules/generated/files/file'\nrequire 'ansible/ruby/modules/helpers/file_attributes'\n\nmodule Ansible\n module Ruby\n module Modules\n class File\n include Helpers::FileAttributes\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6381872296333313, "alphanum_fraction": 0.6419019103050232, "avg_line_length": 32.650001525878906, "blob_id": "9f1ed9308f5945d0c793647a4e8d43e38d465778", "content_id": "4eec6932a348e69994cefaead727954803e41c02", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1346, "license_type": "permissive", "max_line_length": 143, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/network/ovs/openvswitch_port.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage Open vSwitch ports\n class Openvswitch_port < Base\n # @return [String] Name of bridge to manage\n attribute :bridge\n validates :bridge, presence: true, type: String\n\n # @return [String] Name of port to manage on the bridge\n attribute :port\n validates :port, presence: true, type: String\n\n # @return [Integer, nil] VLAN tag for this port. Must be a value between 0 and 4095.\n attribute :tag\n validates :tag, type: Integer\n\n # @return [:present, :absent, nil] Whether the port should exist\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Integer, nil] How long to wait for ovs-vswitchd to respond\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [Object, nil] Dictionary of external_ids applied to a port.\n attribute :external_ids\n\n # @return [String, nil] Set a single property on a port.\n attribute :set\n validates :set, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6634777784347534, "alphanum_fraction": 0.6668542623519897, "avg_line_length": 49.056339263916016, "blob_id": "ad9024fb0c975098b731e1b210b9ea6fdc3d0d66", "content_id": "c84fcf2b1ede20812a67a75b4127111526e7b381", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3554, "license_type": "permissive", "max_line_length": 270, "num_lines": 71, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_vol.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # creates an EBS volume and optionally attaches it to an instance. If both an instance ID and a device name is given and the instance has a device at the device name, then no volume is created and no attachment is made. This module has a dependency on python-boto.\n class Ec2_vol < Base\n # @return [String, nil] instance ID if you wish to attach the volume. Since 1.9 you can set to None to detach.\n attribute :instance\n validates :instance, type: String\n\n # @return [String, nil] volume Name tag if you wish to attach an existing volume (requires instance)\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] volume id if you wish to attach an existing volume (requires instance) or remove an existing volume\n attribute :id\n validates :id, type: String\n\n # @return [Integer, nil] size of volume (in GB) to create.\n attribute :volume_size\n validates :volume_size, type: Integer\n\n # @return [String, nil] Type of EBS volume; standard (magnetic), gp2 (SSD), io1 (Provisioned IOPS), st1 (Throughput Optimized HDD), sc1 (Cold HDD). \"Standard\" is the old EBS default and continues to remain the Ansible default for backwards compatibility.\n attribute :volume_type\n validates :volume_type, type: String\n\n # @return [Integer, nil] the provisioned IOPs you want to associate with this volume (integer).\n attribute :iops\n validates :iops, type: Integer\n\n # @return [String, nil] Enable encryption at rest for this volume.\n attribute :encrypted\n validates :encrypted, type: String\n\n # @return [Object, nil] Specify the id of the KMS key to use.\n attribute :kms_key_id\n\n # @return [String, nil] device id to override device mapping. Assumes /dev/sdf for Linux/UNIX and /dev/xvdf for Windows.\n attribute :device_name\n validates :device_name, type: String\n\n # @return [:yes, :no, nil] When set to \"yes\", the volume will be deleted upon instance termination.\n attribute :delete_on_termination\n validates :delete_on_termination, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] zone in which to create the volume, if unset uses the zone the instance is in (if set)\n attribute :zone\n validates :zone, type: String\n\n # @return [String, nil] snapshot ID on which to base the volume\n attribute :snapshot\n validates :snapshot, type: String\n\n # @return [:yes, :no, nil] When set to \"no\", SSL certificates will not be validated for boto versions >= 2.6.0.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:absent, :present, :list, nil] whether to ensure the volume is present or absent, or to list existing volumes (The C(list) option was added in version 1.8).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :list], :message=>\"%{value} needs to be :absent, :present, :list\"}, allow_nil: true\n\n # @return [Object, nil] tag:value pairs to add to the volume after creation\n attribute :tags\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6718894243240356, "alphanum_fraction": 0.6718894243240356, "avg_line_length": 36.41379165649414, "blob_id": "412ec6b2c0ab74107eb53e7f5cfd3a99fdbf57d9", "content_id": "f018793654a4fed645fff6982102f667b9c71bfd", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1085, "license_type": "permissive", "max_line_length": 142, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_dvs_host.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage a host system from distributed virtual switch.\n class Vmware_dvs_host < Base\n # @return [String] The ESXi hostname.\n attribute :esxi_hostname\n validates :esxi_hostname, presence: true, type: String\n\n # @return [String] The name of the Distributed vSwitch.\n attribute :switch_name\n validates :switch_name, presence: true, type: String\n\n # @return [Array<String>, String] The ESXi hosts vmnics to use with the Distributed vSwitch.\n attribute :vmnics\n validates :vmnics, presence: true, type: TypeGeneric.new(String)\n\n # @return [:present, :absent] If the host should be present or absent attached to the vSwitch.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6539185047149658, "alphanum_fraction": 0.6583071947097778, "avg_line_length": 36.97618865966797, "blob_id": "8f29e096a31d6c6ae8d36c58c960a1c5674728c1", "content_id": "2f0e396f438711c41be6592f2be842716349893b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1595, "license_type": "permissive", "max_line_length": 143, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/network/junos/junos_vlan.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of VLANs on Juniper JUNOS network devices.\n class Junos_vlan < Base\n # @return [String] Name of the VLAN.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Integer] ID of the VLAN. Range 1-4094.\n attribute :vlan_id\n validates :vlan_id, presence: true, type: Integer\n\n # @return [Object, nil] Name of logical layer 3 interface.\n attribute :l3_interface\n\n # @return [Object, nil] Text description of VLANs.\n attribute :description\n\n # @return [Object, nil] List of interfaces to check the VLAN has been configured correctly.\n attribute :interfaces\n\n # @return [Array<Hash>, Hash, nil] List of VLANs definitions.\n attribute :aggregate\n validates :aggregate, type: TypeGeneric.new(Hash)\n\n # @return [:present, :absent, nil] State of the VLAN configuration.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Boolean, nil] Specifies whether or not the configuration is active or deactivated\n attribute :active\n validates :active, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7052553296089172, "alphanum_fraction": 0.7057511210441589, "avg_line_length": 63.03174591064453, "blob_id": "e04e905707ecf8f33212062b3d2906293b7ce908", "content_id": "10b36c1fc956865aa5885fbe854f98e44d006706", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4034, "license_type": "permissive", "max_line_length": 317, "num_lines": 63, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/elb_network_lb.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage an AWS Network Elastic Load Balancer. See U(https://aws.amazon.com/blogs/aws/new-network-load-balancer-effortless-scaling-to-millions-of-requests-per-second/) for details.\n class Elb_network_lb < Base\n # @return [Symbol, nil] Indicates whether cross-zone load balancing is enabled.\n attribute :cross_zone_load_balancing\n validates :cross_zone_load_balancing, type: Symbol\n\n # @return [Symbol, nil] Indicates whether deletion protection for the ELB is enabled.\n attribute :deletion_protection\n validates :deletion_protection, type: Symbol\n\n # @return [Array<Hash>, Hash, nil] A list of dicts containing listeners to attach to the ELB. See examples for detail of the dict required. Note that listener keys are CamelCased.\n attribute :listeners\n validates :listeners, type: TypeGeneric.new(Hash)\n\n # @return [String] The name of the load balancer. This name must be unique within your AWS account, can have a maximum of 32 characters, must contain only alphanumeric characters or hyphens, and must not begin or end with a hyphen.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Boolean, nil] If yes, existing listeners will be purged from the ELB to match exactly what is defined by I(listeners) parameter. If the I(listeners) parameter is not set then listeners will not be modified\n attribute :purge_listeners\n validates :purge_listeners, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] If yes, existing tags will be purged from the resource to match exactly what is defined by I(tags) parameter. If the I(tags) parameter is not set then tags will not be modified.\n attribute :purge_tags\n validates :purge_tags, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash, nil] A list of dicts containing the IDs of the subnets to attach to the load balancer. You can also specify the allocation ID of an Elastic IP to attach to the load balancer. You can specify one Elastic IP address per subnet. This parameter is mutually exclusive with I(subnets)\n attribute :subnet_mappings\n validates :subnet_mappings, type: TypeGeneric.new(Hash)\n\n # @return [Array<String>, String, nil] A list of the IDs of the subnets to attach to the load balancer. You can specify only one subnet per Availability Zone. You must specify subnets from at least two Availability Zones. Required if state=present. This parameter is mutually exclusive with I(subnet_mappings)\n attribute :subnets\n validates :subnets, type: TypeGeneric.new(String)\n\n # @return [:\"internet-facing\", :internal, nil] Internet-facing or internal load balancer. An ELB scheme can not be modified after creation.\n attribute :scheme\n validates :scheme, expression_inclusion: {:in=>[:\"internet-facing\", :internal], :message=>\"%{value} needs to be :\\\"internet-facing\\\", :internal\"}, allow_nil: true\n\n # @return [:present, :absent] Create or destroy the load balancer.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [Object, nil] A dictionary of one or more tags to assign to the load balancer.\n attribute :tags\n\n # @return [Symbol, nil] Whether or not to wait for the network load balancer to reach the desired state.\n attribute :wait\n validates :wait, type: Symbol\n\n # @return [Object, nil] The duration in seconds to wait, used in conjunction with I(wait).\n attribute :wait_timeout\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6709677577018738, "alphanum_fraction": 0.6709677577018738, "avg_line_length": 35.904762268066406, "blob_id": "c177648b3a40f3f23006d87251be31412973a7db", "content_id": "5788edd28c991b75acd28d844aea46b3a46831cc", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 775, "license_type": "permissive", "max_line_length": 182, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/packaging/os/dpkg_selections.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Change dpkg package selection state via --get-selections and --set-selections.\n class Dpkg_selections < Base\n # @return [String] Name of the package\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:install, :hold, :deinstall, :purge] The selection state to set the package to.\n attribute :selection\n validates :selection, presence: true, expression_inclusion: {:in=>[:install, :hold, :deinstall, :purge], :message=>\"%{value} needs to be :install, :hold, :deinstall, :purge\"}\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6730019450187683, "alphanum_fraction": 0.6759259104728699, "avg_line_length": 49.04878234863281, "blob_id": "787a1cc1a6ca7dcb3a43fd72a5b6f9a6943ac76b", "content_id": "81619a06bdb4b064815f837591c6e7a321a978eb", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2052, "license_type": "permissive", "max_line_length": 309, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/network/a10/a10_server.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage SLB (Server Load Balancer) server objects on A10 Networks devices via aXAPIv2.\n class A10_server < Base\n # @return [String, nil] set active-partition\n attribute :partition\n validates :partition, type: String\n\n # @return [Object] The SLB (Server Load Balancer) server name.\n attribute :server_name\n validates :server_name, presence: true\n\n # @return [String, nil] The SLB server IPv4 address.\n attribute :server_ip\n validates :server_ip, type: String\n\n # @return [:enabled, :disabled, nil] The SLB virtual server status.\n attribute :server_status\n validates :server_status, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash, nil] A list of ports to create for the server. Each list item should be a dictionary which specifies the C(port:) and C(protocol:), but can also optionally specify the C(status:). See the examples below for details. This parameter is required when C(state) is C(present).\n attribute :server_ports\n validates :server_ports, type: TypeGeneric.new(Hash)\n\n # @return [:present, :absent, nil] This is to specify the operation to create, update or remove SLB server.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated. This should only be used on personally controlled devices using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5341987013816833, "alphanum_fraction": 0.5351971983909607, "avg_line_length": 27.614286422729492, "blob_id": "c61ce32ad12926beefca98ff010c835b2034ee41", "content_id": "1ff08c518d03c9c5f7c7d73ab2d9c895b75045b1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4006, "license_type": "permissive", "max_line_length": 155, "num_lines": 140, "path": "/util/option_formatter_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# See LICENSE.txt for license\nrequire 'spec_helper'\nrequire_relative './option_formatter'\nrequire_relative './parser/option_data'\n\ndescribe Ansible::Ruby::OptionFormatter do\n describe '::format' do\n subject do\n # match the expected multiline string stuff\n Ansible::Ruby::OptionFormatter.format(option_data).join(\"\\n\") + \"\\n\"\n end\n\n let(:required) { false }\n let(:types) { [] }\n let(:choices) { nil }\n let(:attribute) { 'the_attribute' }\n\n let(:option_data) do\n Ansible::Ruby::Parser::OptionData.new name: attribute,\n description: %w[abc],\n required: required,\n types: types,\n choices: choices\n end\n\n context 'no validations' do\n it do\n is_expected.to eq <<~RUBY\n # @return [Object, nil] abc\n attribute :the_attribute\n RUBY\n end\n end\n\n context 'required' do\n let(:required) { true }\n\n it do\n is_expected.to eq <<~RUBY\n # @return [Object] abc\n attribute :the_attribute\n validates :the_attribute, presence: true\n RUBY\n end\n end\n\n context 'choices' do\n context 'required' do\n let(:required) { true }\n let(:types) { [String] }\n let(:choices) { %i[present absent] }\n\n it do\n is_expected.to eq <<~RUBY\n # @return [:present, :absent] abc\n attribute :the_attribute\n validates :the_attribute, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n RUBY\n end\n end\n\n context 'not required' do\n let(:required) { false }\n let(:types) { [String] }\n let(:choices) { %i[present absent] }\n\n it do\n is_expected.to eq <<~RUBY\n # @return [:present, :absent, nil] abc\n attribute :the_attribute\n validates :the_attribute, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n RUBY\n end\n end\n\n context 'boolean' do\n let(:types) { [TrueClass, FalseClass] }\n let(:choices) { [true, false] }\n\n it do\n is_expected.to eq <<~RUBY\n # @return [Boolean, nil] abc\n attribute :the_attribute\n validates :the_attribute, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n RUBY\n end\n end\n\n context 'different types' do\n let(:types) { [] }\n let(:choices) { [1, :abc] }\n\n it do\n is_expected.to eq <<~RUBY\n # @return [1, :abc, nil] abc\n attribute :the_attribute\n validates :the_attribute, expression_inclusion: {:in=>[1, :abc], :message=>\"%{value} needs to be 1, :abc\"}, allow_nil: true\n RUBY\n end\n end\n end\n\n context 'non symbol friendly attribute' do\n let(:attribute) { 'no-recommends' }\n\n it do\n is_expected.to eq <<~RUBY\n # @return [Object, nil] abc\n attribute :no_recommends, original_name: 'no-recommends'\n RUBY\n end\n end\n\n context 'array' do\n let(:types) { [TypeGeneric.new(Integer)] }\n\n it do\n is_expected.to eq <<~RUBY\n # @return [Array<Integer>, Integer, nil] abc\n attribute :the_attribute\n validates :the_attribute, type: TypeGeneric.new(Integer)\n RUBY\n end\n end\n\n context 'array with multiple types' do\n let(:types) { [TypeGeneric.new(String, Hash)] }\n\n it do\n is_expected.to eq <<~RUBY\n # @return [Array<String>, String, nil] abc\n attribute :the_attribute\n validates :the_attribute, type: TypeGeneric.new(String, Hash)\n RUBY\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6809391975402832, "alphanum_fraction": 0.6809391975402832, "avg_line_length": 44.25, "blob_id": "447b0556b8de4251ec6c318f5a6f47316e30ae82", "content_id": "e6df1783b47ebf94504563ac627e5ea654aded71", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1448, "license_type": "permissive", "max_line_length": 251, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_ssl_key.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module will import/delete SSL keys on a BIG-IP. Keys can be imported from key files on the local disk, in PEM format.\n class Bigip_ssl_key < Base\n # @return [String, nil] Sets the contents of a key directly to the specified value. This is used with lookup plugins or for anything with formatting or templating. This must be provided when C(state) is C(present).\n attribute :content\n validates :content, type: String\n\n # @return [:present, :absent, nil] When C(present), ensures that the key is uploaded to the device. When C(absent), ensures that the key is removed from the device. If the key is currently in use, the module will not be able to remove the key.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The name of the key.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Passphrase on key.\n attribute :passphrase\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6819338202476501, "alphanum_fraction": 0.6819338202476501, "avg_line_length": 36.42856979370117, "blob_id": "7cd4ec8f71eab0b3b8bfd7ca14df85d7550f1160", "content_id": "edd0fee4280de10bb4e469c991da034677777834", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 786, "license_type": "permissive", "max_line_length": 143, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_datacenter.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to manage (create, delete) VMware vSphere Datacenters.\n class Vmware_datacenter < Base\n # @return [String] The name of the datacenter the cluster will be created in.\n attribute :datacenter_name\n validates :datacenter_name, presence: true, type: String\n\n # @return [:present, :absent, nil] If the datacenter should be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.636845588684082, "alphanum_fraction": 0.6434724926948547, "avg_line_length": 39.783782958984375, "blob_id": "3fe356dc05025e9826ef49147c451929e80db6b0", "content_id": "062d7dab370187332a5c3833f3a4fcd5deeb2d54", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1509, "license_type": "permissive", "max_line_length": 203, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/cloud/scaleway/scaleway_volume.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module manages volumes on Scaleway account U(https://developer.scaleway.com)\n class Scaleway_volume < Base\n # @return [:present, :absent, nil] Indicate desired state of the volume.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:ams1, :\"EMEA-NL-EVS\", :par1, :\"EMEA-FR-PAR1\"] Scaleway region to use (for example par1).\n attribute :region\n validates :region, presence: true, expression_inclusion: {:in=>[:ams1, :\"EMEA-NL-EVS\", :par1, :\"EMEA-FR-PAR1\"], :message=>\"%{value} needs to be :ams1, :\\\"EMEA-NL-EVS\\\", :par1, :\\\"EMEA-FR-PAR1\\\"\"}\n\n # @return [String] Name used to identify the volume.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] ScaleWay organization ID to which volume belongs.\n attribute :organization\n validates :organization, type: String\n\n # @return [Integer, nil] Size of the volume in bytes.\n attribute :size\n validates :size, type: Integer\n\n # @return [String, nil] Type of the volume (for example 'l_ssd').\n attribute :volume_type\n validates :volume_type, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.686930775642395, "alphanum_fraction": 0.686930775642395, "avg_line_length": 52.56097412109375, "blob_id": "762ac4fcaa78af0327aeba735e1af24bf529a4c0", "content_id": "0f4033264fea2d07f34b379c30144d8c98b446c3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4392, "license_type": "permissive", "max_line_length": 292, "num_lines": 82, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_network_offering.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, enable, disable and remove network offerings.\n class Cs_network_offering < Base\n # @return [:enabled, :present, :disabled, :absent, nil] State of the network offering.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:enabled, :present, :disabled, :absent], :message=>\"%{value} needs to be :enabled, :present, :disabled, :absent\"}, allow_nil: true\n\n # @return [String, nil] Display text of the network offerings.\n attribute :display_text\n validates :display_text, type: String\n\n # @return [:Shared, :Isolated, nil] Guest type of the network offering.\n attribute :guest_ip_type\n validates :guest_ip_type, expression_inclusion: {:in=>[:Shared, :Isolated], :message=>\"%{value} needs to be :Shared, :Isolated\"}, allow_nil: true\n\n # @return [String] The name of the network offering.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:Dns, :PortForwarding, :Dhcp, :SourceNat, :UserData, :Firewall, :StaticNat, :Vpn, :Lb, nil] Services supported by the network offering.,One or more of the choices.\n attribute :supported_services\n validates :supported_services, expression_inclusion: {:in=>[:Dns, :PortForwarding, :Dhcp, :SourceNat, :UserData, :Firewall, :StaticNat, :Vpn, :Lb], :message=>\"%{value} needs to be :Dns, :PortForwarding, :Dhcp, :SourceNat, :UserData, :Firewall, :StaticNat, :Vpn, :Lb\"}, allow_nil: true\n\n # @return [String, nil] The traffic type for the network offering.\n attribute :traffic_type\n validates :traffic_type, type: String\n\n # @return [Object, nil] The availability of network offering. Default value is Optional\n attribute :availability\n\n # @return [Symbol, nil] Whether the network offering has IP conserve mode enabled.\n attribute :conserve_mode\n validates :conserve_mode, type: Symbol\n\n # @return [:internallbprovider, :publiclbprovider, nil] Network offering details in key/value pairs.,with service provider as a value\n attribute :details\n validates :details, expression_inclusion: {:in=>[:internallbprovider, :publiclbprovider], :message=>\"%{value} needs to be :internallbprovider, :publiclbprovider\"}, allow_nil: true\n\n # @return [:allow, :deny, nil] Whether the default egress policy is allow or to deny.\n attribute :egress_default_policy\n validates :egress_default_policy, expression_inclusion: {:in=>[:allow, :deny], :message=>\"%{value} needs to be :allow, :deny\"}, allow_nil: true\n\n # @return [Object, nil] True if network offering supports persistent networks,defaulted to false if not specified\n attribute :persistent\n\n # @return [Symbol, nil] If true keepalive will be turned on in the loadbalancer.,At the time of writing this has only an effect on haproxy.,the mode http and httpclose options are unset in the haproxy conf file.\n attribute :keepalive_enabled\n validates :keepalive_enabled, type: Symbol\n\n # @return [Object, nil] Maximum number of concurrent connections supported by the network offering.\n attribute :max_connections\n\n # @return [Object, nil] Data transfer rate in megabits per second allowed.\n attribute :network_rate\n\n # @return [Object, nil] Desired service capabilities as part of network offering.\n attribute :service_capabilities\n\n # @return [Object, nil] The service offering name or ID used by virtual router provider.\n attribute :service_offering\n\n # @return [Object, nil] Provider to service mapping.,If not specified, the provider for the service will be mapped to the default provider on the physical network.\n attribute :service_provider\n\n # @return [Symbol, nil] Wheter the network offering supports specifying IP ranges.,Defaulted to C(no) by the API if not specified.\n attribute :specify_ip_ranges\n validates :specify_ip_ranges, type: Symbol\n\n # @return [Symbol, nil] Whether the network offering supports vlans or not.\n attribute :specify_vlan\n validates :specify_vlan, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.634353756904602, "alphanum_fraction": 0.6354875564575195, "avg_line_length": 42.55555725097656, "blob_id": "d8b358132b3515ae08f5e14987638e8879bf3659", "content_id": "0653ecc5dde7a9dc44bb401b338a0ab6847e5140", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3528, "license_type": "permissive", "max_line_length": 182, "num_lines": 81, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_network_acl_rule.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add, update and remove network ACL rules.\n class Cs_network_acl_rule < Base\n # @return [String] Name of the network ACL.\n attribute :network_acl\n validates :network_acl, presence: true, type: String\n\n # @return [String, nil] CIDR of the rule.\n attribute :cidr\n validates :cidr, type: String\n\n # @return [Integer] CIDR of the rule.\n attribute :rule_position\n validates :rule_position, presence: true, type: Integer\n\n # @return [:tcp, :udp, :icmp, :all, :by_number, nil] Protocol of the rule\n attribute :protocol\n validates :protocol, expression_inclusion: {:in=>[:tcp, :udp, :icmp, :all, :by_number], :message=>\"%{value} needs to be :tcp, :udp, :icmp, :all, :by_number\"}, allow_nil: true\n\n # @return [Object, nil] Protocol number from 1 to 256 required if C(protocol=by_number).\n attribute :protocol_number\n\n # @return [Integer, nil] Start port for this rule.,Considered if C(protocol=tcp) or C(protocol=udp).\n attribute :start_port\n validates :start_port, type: Integer\n\n # @return [Integer, nil] End port for this rule.,Considered if C(protocol=tcp) or C(protocol=udp).,If not specified, equal C(start_port).\n attribute :end_port\n validates :end_port, type: Integer\n\n # @return [Object, nil] Type of the icmp message being sent.,Considered if C(protocol=icmp).\n attribute :icmp_type\n\n # @return [Object, nil] Error code for this icmp message.,Considered if C(protocol=icmp).\n attribute :icmp_code\n\n # @return [String] VPC the network ACL is related to.\n attribute :vpc\n validates :vpc, presence: true, type: String\n\n # @return [:ingress, :egress, nil] Traffic type of the rule.\n attribute :traffic_type\n validates :traffic_type, expression_inclusion: {:in=>[:ingress, :egress], :message=>\"%{value} needs to be :ingress, :egress\"}, allow_nil: true\n\n # @return [:allow, :deny, nil] Action policy of the rule.\n attribute :action_policy\n validates :action_policy, expression_inclusion: {:in=>[:allow, :deny], :message=>\"%{value} needs to be :allow, :deny\"}, allow_nil: true\n\n # @return [Object, nil] List of tags. Tags are a list of dictionaries having keys C(key) and C(value).,If you want to delete all tags, set a empty list e.g. C(tags: []).\n attribute :tags\n\n # @return [Object, nil] Domain the VPC is related to.\n attribute :domain\n\n # @return [Object, nil] Account the VPC is related to.\n attribute :account\n\n # @return [Object, nil] Name of the project the VPC is related to.\n attribute :project\n\n # @return [Object, nil] Name of the zone the VPC related to.,If not set, default zone is used.\n attribute :zone\n\n # @return [:present, :absent, nil] State of the network ACL rule.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Poll async jobs until job has finished.\n attribute :poll_async\n validates :poll_async, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.685512363910675, "alphanum_fraction": 0.685512363910675, "avg_line_length": 47.7931022644043, "blob_id": "380343b57df4113fadef810cfcf56f2f5c306e99", "content_id": "3fb85b910ce24502d5218254bfaa03a0812388c4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1415, "license_type": "permissive", "max_line_length": 245, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_resourcegroup.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and delete a resource group.\n class Azure_rm_resourcegroup < Base\n # @return [:yes, :no, nil] Remove a resource group and all associated resources. Use with state 'absent' to delete a resource group that contains resources.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Azure location for the resource group. Required when creating a new resource group. Cannot be changed once resource group is created.\n attribute :location\n validates :location, type: String\n\n # @return [String] Name of the resource group.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, nil] Assert the state of the resource group. Use 'present' to create or update and 'absent' to delete. When 'absent' a resource group containing resources will not be removed unless the force option is used.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6766554117202759, "alphanum_fraction": 0.6882551908493042, "avg_line_length": 49.46341323852539, "blob_id": "ce40fb7f97930ef714116f676a130ce4d8daae8a", "content_id": "c02f0f0ee00acdb8388ee208b12392f0a97bfcf4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2069, "license_type": "permissive", "max_line_length": 198, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/network/onyx/onyx_igmp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of IGMP protocol params on Mellanox ONYX network devices.\n class Onyx_igmp < Base\n # @return [:enabled, :disabled] IGMP state.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}\n\n # @return [Object, nil] Configure the last member query interval, range 1-25\n attribute :last_member_query_interval\n\n # @return [Object, nil] Configure the mrouter timeout, range 60-600\n attribute :mrouter_timeout\n\n # @return [Object, nil] Configure the host port purge timeout, range 130-1225\n attribute :port_purge_timeout\n\n # @return [:enabled, :disabled, nil] Configure ip igmp snooping proxy and enable reporting mode\n attribute :proxy_reporting\n validates :proxy_reporting, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [Object, nil] Configure the report suppression interval, range 1-25\n attribute :report_suppression_interval\n\n # @return [:flood, :\"forward-to-mrouter-ports\", nil] Configure the unregistered multicast mode Flood unregistered multicast Forward unregistered multicast to mrouter ports\n attribute :unregistered_multicast\n validates :unregistered_multicast, expression_inclusion: {:in=>[:flood, :\"forward-to-mrouter-ports\"], :message=>\"%{value} needs to be :flood, :\\\"forward-to-mrouter-ports\\\"\"}, allow_nil: true\n\n # @return [:V2, :V3, nil] Configure the default operating version of the IGMP snooping\n attribute :default_version\n validates :default_version, expression_inclusion: {:in=>[:V2, :V3], :message=>\"%{value} needs to be :V2, :V3\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7048280835151672, "alphanum_fraction": 0.7070226669311523, "avg_line_length": 67.3499984741211, "blob_id": "79f2bf5a702efdf653b3ea855f4a81f4fb7447c0", "content_id": "bf0ab13a6349c1c8d555105ab19a2ea738b47cc0", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2734, "license_type": "permissive", "max_line_length": 426, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/netapp_e_asup.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allow the auto-support settings to be configured for an individual E-Series storage-system\n class Netapp_e_asup < Base\n # @return [:enabled, :disabled, nil] Enable/disable the E-Series auto-support configuration.,When this option is enabled, configuration, logs, and other support-related information will be relayed to NetApp to help better support your system. No personally identifiable information, passwords, etc, will be collected.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [Boolean, nil] Enable active/proactive monitoring for ASUP. When a problem is detected by our monitoring systems, it's possible that the bundle did not contain all of the required information at the time of the event. Enabling this option allows NetApp support personnel to manually request transmission or re-transmission of support data in order ot resolve the problem.,Only applicable if I(state=enabled).\n attribute :active\n validates :active, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Integer, nil] A start hour may be specified in a range from 0 to 23 hours.,ASUP bundles will be sent daily between the provided start and end time (UTC).,I(start) must be less than I(end).\n attribute :start\n validates :start, type: Integer\n\n # @return [Integer, nil] An end hour may be specified in a range from 1 to 24 hours.,ASUP bundles will be sent daily between the provided start and end time (UTC).,I(start) must be less than I(end).\n attribute :end\n validates :end, type: Integer\n\n # @return [:monday, :tuesday, :wednesday, :thursday, :friday, :saturday, :sunday, nil] A list of days of the week that ASUP bundles will be sent. A larger, weekly bundle will be sent on one of the provided days.\n attribute :days\n validates :days, expression_inclusion: {:in=>[:monday, :tuesday, :wednesday, :thursday, :friday, :saturday, :sunday], :message=>\"%{value} needs to be :monday, :tuesday, :wednesday, :thursday, :friday, :saturday, :sunday\"}, allow_nil: true\n\n # @return [Symbol, nil] Provide the full ASUP configuration in the return.\n attribute :verbose\n validates :verbose, type: Symbol\n\n # @return [Object, nil] A local path to a file to be used for debug logging\n attribute :log_path\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.658450722694397, "alphanum_fraction": 0.658450722694397, "avg_line_length": 33.08000183105469, "blob_id": "b6562dd2a53a89f0429e6c7eec11cf90559d86d5", "content_id": "c3a28d19699a7fabef9c18d6d7bbce56061be7d8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 852, "license_type": "permissive", "max_line_length": 128, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/network/panos/panos_dag.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create a dynamic address group object in the firewall used for policy rules\n class Panos_dag < Base\n # @return [String] name of the dynamic address group\n attribute :dag_name\n validates :dag_name, presence: true, type: String\n\n # @return [String] dynamic filter user by the dynamic address group\n attribute :dag_filter\n validates :dag_filter, presence: true, type: String\n\n # @return [:yes, :no, nil] commit if changed\n attribute :commit\n validates :commit, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6876750588417053, "alphanum_fraction": 0.6876750588417053, "avg_line_length": 43.625, "blob_id": "30b16a8fecb1e2be65fe19bd88c6c94b9f343f8d", "content_id": "df36c5f847d7f7d8e9b000e92e997ddb0a73efd0", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1428, "license_type": "permissive", "max_line_length": 229, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_cli_script.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages CLI scripts on a BIG-IP. CLI scripts, otherwise known as tmshell scripts or TMSH scripts allow you to create custom scripts that can run to manage objects within a BIG-IP.\n class Bigip_cli_script < Base\n # @return [String] Specifies the name of the script.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The content of the script.,This parameter is typically used in conjunction with Ansible's C(file), or template lookup plugins. If this sounds foreign to you, see the examples in this documentation.\n attribute :content\n validates :content, type: String\n\n # @return [Object, nil] Description of the cli script.\n attribute :description\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [:present, :absent, nil] When C(present), ensures that the script exists.,When C(absent), ensures the script is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6975265145301819, "alphanum_fraction": 0.6975265145301819, "avg_line_length": 44.64516067504883, "blob_id": "14f69b3c4e4088ecda84b88f95ef77f59125de0c", "content_id": "f70bb50d08ffeba9b340be4679366ba2d0b925ad", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1415, "license_type": "permissive", "max_line_length": 366, "num_lines": 31, "path": "/lib/ansible/ruby/modules/generated/network/netscaler/netscaler_cs_action.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage content switching actions\n # This module is intended to run either on the ansible control node or a bastion (jumpserver) with access to the actual netscaler instance\n class Netscaler_cs_action < Base\n # @return [String, nil] Name for the content switching action. Must begin with an ASCII alphanumeric or underscore C(_) character, and must contain only ASCII alphanumeric, underscore C(_), hash C(#), period C(.), space C( ), colon C(:), at sign C(@), equal sign C(=), and hyphen C(-) characters. Can be changed after the content switching action is created.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] Name of the load balancing virtual server to which the content is switched.\n attribute :targetlbvserver\n validates :targetlbvserver, type: String\n\n # @return [Object, nil] Name of the VPN virtual server to which the content is switched.\n attribute :targetvserver\n\n # @return [Object, nil] Information about this content switching action.\n attribute :targetvserverexpr\n\n # @return [Object, nil] Comments associated with this cs action.\n attribute :comment\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7088137865066528, "alphanum_fraction": 0.713308572769165, "avg_line_length": 72.0999984741211, "blob_id": "4bf09c4b3cbe6a229d2b00513220aeb669d50581", "content_id": "cf647725b6ec76a23beab3ef8ff46ac7bbbe0df5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5117, "license_type": "permissive", "max_line_length": 468, "num_lines": 70, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_compute_backend_service.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates a BackendService resource in the specified project using the data included in the request.\n class Gcp_compute_backend_service < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Lifetime of cookies in seconds if session_affinity is GENERATED_COOKIE. If set to 0, the cookie is non-persistent and lasts only until the end of the browser session (or equivalent). The maximum allowed value for TTL is one day.,When the load balancing scheme is INTERNAL, this field is not used.\n attribute :affinity_cookie_ttl_sec\n\n # @return [Array<Hash>, Hash, nil] The list of backends that serve this BackendService.\n attribute :backends\n validates :backends, type: TypeGeneric.new(Hash)\n\n # @return [Object, nil] Cloud CDN configuration for this BackendService.\n attribute :cdn_policy\n\n # @return [Object, nil] Settings for connection draining.\n attribute :connection_draining\n\n # @return [Object, nil] An optional description of this resource.\n attribute :description\n\n # @return [Symbol, nil] If true, enable Cloud CDN for this BackendService.,When the load balancing scheme is INTERNAL, this field is not used.\n attribute :enable_cdn\n validates :enable_cdn, type: Symbol\n\n # @return [Array<String>, String, nil] The list of URLs to the HttpHealthCheck or HttpsHealthCheck resource for health checking this BackendService. Currently at most one health check can be specified, and a health check is required.,For internal load balancing, a URL to a HealthCheck resource must be specified instead.\n attribute :health_checks\n validates :health_checks, type: TypeGeneric.new(String)\n\n # @return [Object, nil] Settings for enabling Cloud Identity Aware Proxy.\n attribute :iap\n\n # @return [:INTERNAL, :EXTERNAL, nil] Indicates whether the backend service will be used with internal or external load balancing. A backend service created for one type of load balancing cannot be used with the other.\n attribute :load_balancing_scheme\n validates :load_balancing_scheme, expression_inclusion: {:in=>[:INTERNAL, :EXTERNAL], :message=>\"%{value} needs to be :INTERNAL, :EXTERNAL\"}, allow_nil: true\n\n # @return [String, nil] Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash.\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] Name of backend port. The same name should appear in the instance groups referenced by this service. Required when the load balancing scheme is EXTERNAL.,When the load balancing scheme is INTERNAL, this field is not used.\n attribute :port_name\n\n # @return [:HTTP, :HTTPS, :TCP, :SSL, nil] The protocol this BackendService uses to communicate with backends.,Possible values are HTTP, HTTPS, TCP, and SSL. The default is HTTP.,For internal load balancing, the possible values are TCP and UDP, and the default is TCP.\n attribute :protocol\n validates :protocol, expression_inclusion: {:in=>[:HTTP, :HTTPS, :TCP, :SSL], :message=>\"%{value} needs to be :HTTP, :HTTPS, :TCP, :SSL\"}, allow_nil: true\n\n # @return [Object, nil] The region where the regional backend service resides.,This field is not applicable to global backend services.\n attribute :region\n\n # @return [:NONE, :CLIENT_IP, :GENERATED_COOKIE, :CLIENT_IP_PROTO, :CLIENT_IP_PORT_PROTO, nil] Type of session affinity to use. The default is NONE.,When the load balancing scheme is EXTERNAL, can be NONE, CLIENT_IP, or GENERATED_COOKIE.,When the load balancing scheme is INTERNAL, can be NONE, CLIENT_IP, CLIENT_IP_PROTO, or CLIENT_IP_PORT_PROTO.,When the protocol is UDP, this field is not used.\n attribute :session_affinity\n validates :session_affinity, expression_inclusion: {:in=>[:NONE, :CLIENT_IP, :GENERATED_COOKIE, :CLIENT_IP_PROTO, :CLIENT_IP_PORT_PROTO], :message=>\"%{value} needs to be :NONE, :CLIENT_IP, :GENERATED_COOKIE, :CLIENT_IP_PROTO, :CLIENT_IP_PORT_PROTO\"}, allow_nil: true\n\n # @return [Integer, nil] How many seconds to wait for the backend before considering it a failed request. Default is 30 seconds. Valid range is [1, 86400].\n attribute :timeout_sec\n validates :timeout_sec, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6638349294662476, "alphanum_fraction": 0.6656553149223328, "avg_line_length": 39.19512176513672, "blob_id": "5ede2e9b08d38fadf087bacfd86ff65caa13c434", "content_id": "a9270cf861b75018187b00dad0698f56ad0695ae", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1648, "license_type": "permissive", "max_line_length": 220, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/rundeck_acl_policy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and remove Rundeck ACL policies through HTTP API.\n class Rundeck_acl_policy < Base\n # @return [:present, :absent, nil] Create or remove Rundeck project.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] Sets the project name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] Sets the rundeck instance URL.\n attribute :url\n validates :url, presence: true, type: String\n\n # @return [Integer, nil] Sets the API version used by module.,API version must be at least 14.\n attribute :api_version\n validates :api_version, type: Integer\n\n # @return [String] Sets the token to authenticate against Rundeck API.\n attribute :token\n validates :token, presence: true, type: String\n\n # @return [String, nil] Sets the project which receive the ACL policy.,If unset, it's a system ACL policy.\n attribute :project\n validates :project, type: String\n\n # @return [Hash, nil] Sets the ACL policy content.,ACL policy content is a YAML object as described in http://rundeck.org/docs/man5/aclpolicy.html.,It can be a YAML string or a pure Ansible inventory YAML object.\n attribute :policy\n validates :policy, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6642916798591614, "alphanum_fraction": 0.674350380897522, "avg_line_length": 48.70833206176758, "blob_id": "c209fe32083909f4148014dcf08e82f3be7555d1", "content_id": "cde33080209ae1dadd9465ec412aaf009e17023a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2386, "license_type": "permissive", "max_line_length": 192, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/cloud/rackspace/rax_scaling_policy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manipulate Rackspace Cloud Autoscale Scaling Policy\n class Rax_scaling_policy < Base\n # @return [Object, nil] The UTC time when this policy will be executed. The time must be formatted according to C(yyyy-MM-dd'T'HH:mm:ss.SSS) such as C(2013-05-19T08:07:08Z)\n attribute :at\n\n # @return [Object, nil] The change, either as a number of servers or as a percentage, to make in the scaling group. If this is a percentage, you must set I(is_percent) to C(true) also.\n attribute :change\n\n # @return [Object, nil] The time when the policy will be executed, as a cron entry. For example, if this is parameter is set to C(1 0 * * *)\n attribute :cron\n\n # @return [Object, nil] The period of time, in seconds, that must pass before any scaling can occur after the previous scaling. Must be an integer between 0 and 86400 (24 hrs).\n attribute :cooldown\n\n # @return [Object, nil] The desired server capacity of the scaling the group; that is, how many servers should be in the scaling group.\n attribute :desired_capacity\n\n # @return [Boolean, nil] Whether the value in I(change) is a percent value\n attribute :is_percent\n validates :is_percent, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object] Name to give the policy\n attribute :name\n validates :name, presence: true\n\n # @return [:webhook, :schedule] The type of policy that will be executed for the current release.\n attribute :policy_type\n validates :policy_type, presence: true, expression_inclusion: {:in=>[:webhook, :schedule], :message=>\"%{value} needs to be :webhook, :schedule\"}\n\n # @return [Object] Name of the scaling group that this policy will be added to\n attribute :scaling_group\n validates :scaling_group, presence: true\n\n # @return [:present, :absent, nil] Indicate desired state of the resource\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7514253258705139, "alphanum_fraction": 0.7514253258705139, "avg_line_length": 50.588233947753906, "blob_id": "a9c9166f13dd6aec637c2751c120a71e63c5d497", "content_id": "21b6df495985caf926e31e0c66b5a2ec4ba5a219", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 877, "license_type": "permissive", "max_line_length": 319, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/storage/purestorage/purefb_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Collect facts information from a Pure Storage FlashBlade running the Purity//FB operating system. By default, the module will collect basic fact information including hosts, host groups, protection groups and volume counts. Additional fact information can be collected based on the configured set of arguements.\n class Purefb_facts < Base\n # @return [String, nil] When supplied, this argument will define the facts to be collected. Possible values for this include all, minimum, config, performance, capacity, network, subnets, lags, filesystems and snapshots.\n attribute :gather_subset\n validates :gather_subset, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7247838377952576, "alphanum_fraction": 0.7348703145980835, "avg_line_length": 65.0952377319336, "blob_id": "0ebd21e9f45c5a6391aae5b51418edfdfcdaced2", "content_id": "31e9f3363d785171adff1dccb9e10f1a2a44fa7e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1388, "license_type": "permissive", "max_line_length": 405, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/network/junos/junos_netconf.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides an abstraction that enables and configures the netconf system service running on Junos devices. This module can be used to easily enable the Netconf API. Netconf provides a programmatic interface for working with configuration and state resources as defined in RFC 6242. If the C(netconf_port) is not mentioned in the task by default netconf will be enabled on port 830 only.\n class Junos_netconf < Base\n # @return [Integer, nil] This argument specifies the port the netconf service should listen on for SSH connections. The default port as defined in RFC 6242 is 830.\n attribute :netconf_port\n validates :netconf_port, type: Integer\n\n # @return [:present, :absent, nil] Specifies the state of the C(junos_netconf) resource on the remote device. If the I(state) argument is set to I(present) the netconf service will be configured. If the I(state) argument is set to I(absent) the netconf service will be removed from the configuration.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6471712589263916, "alphanum_fraction": 0.6471712589263916, "avg_line_length": 35.33333206176758, "blob_id": "02b6d0ca3e0964a5c50f5c38f5cdef8cd7ddeecb", "content_id": "bca2ceafcc4406976369c2b5b3ca3b8cba0a1720", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5232, "license_type": "permissive", "max_line_length": 164, "num_lines": 144, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_quota.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage OpenStack Quotas. Quotas can be created, updated or deleted using this module. A quota will be updated if matches an existing project and is present.\n class Os_quota < Base\n # @return [String] Name of the OpenStack Project to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] A value of present sets the quota and a value of absent resets the quota to system defaults.\n attribute :state\n validates :state, type: String\n\n # @return [String, nil] Maximum size of backups in GB's.\n attribute :backup_gigabytes\n validates :backup_gigabytes, type: String\n\n # @return [String, nil] Maximum number of backups allowed.\n attribute :backups\n validates :backups, type: String\n\n # @return [Integer, String, nil] Maximum number of CPU's per project.\n attribute :cores\n validates :cores, type: MultipleTypes.new(Integer, String)\n\n # @return [String, nil] Number of fixed IP's to allow.\n attribute :fixed_ips\n validates :fixed_ips, type: String\n\n # @return [String, nil] Number of floating IP's to allow in Compute.\n attribute :floating_ips\n validates :floating_ips, type: String\n\n # @return [String, nil] Number of floating IP's to allow in Network.\n attribute :floatingip\n validates :floatingip, type: String\n\n # @return [String, nil] Maximum volume storage allowed for project.\n attribute :gigabytes\n validates :gigabytes, type: String\n\n # @return [Object, nil] Maximum size in GB's of individual lvm volumes.\n attribute :gigabytes_lvm\n\n # @return [String, nil] Maximum file size in bytes.\n attribute :injected_file_size\n validates :injected_file_size, type: String\n\n # @return [String, nil] Number of injected files to allow.\n attribute :injected_files\n validates :injected_files, type: String\n\n # @return [String, nil] Maximum path size.\n attribute :injected_path_size\n validates :injected_path_size, type: String\n\n # @return [String, nil] Maximum number of instances allowed.\n attribute :instances\n validates :instances, type: String\n\n # @return [String, nil] Number of key pairs to allow.\n attribute :key_pairs\n validates :key_pairs, type: String\n\n # @return [String, nil] Number of load balancers to allow.\n attribute :loadbalancer\n validates :loadbalancer, type: String\n\n # @return [Object, nil] Number of networks to allow.\n attribute :network\n\n # @return [String, nil] Maximum size in GB's of individual volumes.\n attribute :per_volume_gigabytes\n validates :per_volume_gigabytes, type: String\n\n # @return [String, nil] Number of load balancer pools to allow.\n attribute :pool\n validates :pool, type: String\n\n # @return [String, nil] Number of Network ports to allow, this needs to be greater than the instances limit.\n attribute :port\n validates :port, type: String\n\n # @return [String, nil] Number of properties to allow.\n attribute :properties\n validates :properties, type: String\n\n # @return [String, nil] Maximum amount of ram in MB to allow.\n attribute :ram\n validates :ram, type: String\n\n # @return [Object, nil] Number of policies to allow.\n attribute :rbac_policy\n\n # @return [Object, nil] Number of routers to allow.\n attribute :router\n\n # @return [String, nil] Number of rules per security group to allow.\n attribute :security_group_rule\n validates :security_group_rule, type: String\n\n # @return [String, nil] Number of security groups to allow.\n attribute :security_group\n validates :security_group, type: String\n\n # @return [String, nil] Number of server group members to allow.\n attribute :server_group_members\n validates :server_group_members, type: String\n\n # @return [String, nil] Number of server groups to allow.\n attribute :server_groups\n validates :server_groups, type: String\n\n # @return [String, nil] Number of snapshots to allow.\n attribute :snapshots\n validates :snapshots, type: String\n\n # @return [Object, nil] Number of LVM snapshots to allow.\n attribute :snapshots_lvm\n\n # @return [Object, nil] Number of subnets to allow.\n attribute :subnet\n\n # @return [Object, nil] Number of subnet pools to allow.\n attribute :subnetpool\n\n # @return [Integer, String, nil] Number of volumes to allow.\n attribute :volumes\n validates :volumes, type: MultipleTypes.new(Integer, String)\n\n # @return [Object, nil] Number of LVM volumes to allow.\n attribute :volumes_lvm\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6809779405593872, "alphanum_fraction": 0.6863446831703186, "avg_line_length": 53.09677505493164, "blob_id": "1d25f3e802748be18fe445efc7b269dd883640d1", "content_id": "5850595b5117ad4c819a18f1db7e49715686fb62", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1677, "license_type": "permissive", "max_line_length": 309, "num_lines": 31, "path": "/lib/ansible/ruby/modules/generated/packaging/os/pkgutil.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages CSW packages (SVR4 format) on Solaris 10 and 11.\n # These were the native packages on Solaris <= 10 and are available as a legacy feature in Solaris 11.\n # Pkgutil is an advanced packaging system, which resolves dependency on installation. It is designed for CSW packages.\n class Pkgutil < Base\n # @return [String] Package name, e.g. (C(CSWnrpe))\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Specifies the repository path to install the package from.,Its global definition is done in C(/etc/opt/csw/pkgutil.conf).\n attribute :site\n validates :site, type: String\n\n # @return [:present, :absent, :latest] Whether to install (C(present)), or remove (C(absent)) a package.,The upgrade (C(latest)) operation will update/install the package to the latest version available.,Note: The module has a limitation that (C(latest)) only works for one package, not lists of them.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent, :latest], :message=>\"%{value} needs to be :present, :absent, :latest\"}\n\n # @return [Boolean, nil] If you want to refresh your catalog from the mirror, set this to (C(yes)).\n attribute :update_catalog\n validates :update_catalog, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6571949124336243, "alphanum_fraction": 0.6593806743621826, "avg_line_length": 38.78260803222656, "blob_id": "b71b8437eda5479effbbee18d8d3a7b45cb8241c", "content_id": "cacaba8f927cfcaf09097e369ff0b5d3823b9d93", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2745, "license_type": "permissive", "max_line_length": 350, "num_lines": 69, "path": "/lib/ansible/ruby/modules/generated/database/mysql/mysql_replication.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages MySQL server replication, slave, master status get and change master host.\n class Mysql_replication < Base\n # @return [:getslave, :getmaster, :changemaster, :stopslave, :startslave, :resetslave, :resetslaveall, nil] module operating mode. Could be getslave (SHOW SLAVE STATUS), getmaster (SHOW MASTER STATUS), changemaster (CHANGE MASTER TO), startslave (START SLAVE), stopslave (STOP SLAVE), resetslave (RESET SLAVE), resetslaveall (RESET SLAVE ALL)\n attribute :mode\n validates :mode, expression_inclusion: {:in=>[:getslave, :getmaster, :changemaster, :stopslave, :startslave, :resetslave, :resetslaveall], :message=>\"%{value} needs to be :getslave, :getmaster, :changemaster, :stopslave, :startslave, :resetslave, :resetslaveall\"}, allow_nil: true\n\n # @return [String, nil] same as mysql variable\n attribute :master_host\n validates :master_host, type: String\n\n # @return [Object, nil] same as mysql variable\n attribute :master_user\n\n # @return [Object, nil] same as mysql variable\n attribute :master_password\n\n # @return [Object, nil] same as mysql variable\n attribute :master_port\n\n # @return [Object, nil] same as mysql variable\n attribute :master_connect_retry\n\n # @return [String, nil] same as mysql variable\n attribute :master_log_file\n validates :master_log_file, type: String\n\n # @return [Integer, nil] same as mysql variable\n attribute :master_log_pos\n validates :master_log_pos, type: Integer\n\n # @return [Object, nil] same as mysql variable\n attribute :relay_log_file\n\n # @return [Object, nil] same as mysql variable\n attribute :relay_log_pos\n\n # @return [0, 1, nil] same as mysql variable\n attribute :master_ssl\n validates :master_ssl, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [Object, nil] same as mysql variable\n attribute :master_ssl_ca\n\n # @return [Object, nil] same as mysql variable\n attribute :master_ssl_capath\n\n # @return [Object, nil] same as mysql variable\n attribute :master_ssl_cert\n\n # @return [Object, nil] same as mysql variable\n attribute :master_ssl_key\n\n # @return [Object, nil] same as mysql variable\n attribute :master_ssl_cipher\n\n # @return [Object, nil] does the host uses GTID based replication or not\n attribute :master_auto_position\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.696044385433197, "alphanum_fraction": 0.6970853805541992, "avg_line_length": 63.0444450378418, "blob_id": "ca23d5c3d5e0bb71aaf2a09da13191e427096151", "content_id": "919726af1a44ad680329861a7b68923e99b8df47", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2882, "license_type": "permissive", "max_line_length": 731, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or destroy users.\n class Na_ontap_user < Base\n # @return [:present, :absent, nil] Whether the specified user should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The name of the user to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:console, :http, :ontapi, :rsh, :snmp, :\"service-processor\", :sp, :ssh, :telnet] Application to grant access to.\n attribute :application\n validates :application, presence: true, expression_inclusion: {:in=>[:console, :http, :ontapi, :rsh, :snmp, :\"service-processor\", :sp, :ssh, :telnet], :message=>\"%{value} needs to be :console, :http, :ontapi, :rsh, :snmp, :\\\"service-processor\\\", :sp, :ssh, :telnet\"}\n\n # @return [:community, :password, :publickey, :domain, :nsswitch, :usm] Authentication method for the application.,Not all authentication methods are valid for an application.,Valid authentication methods for each application are as denoted in I(authentication_choices_description).,Password for console application,Password, domain, nsswitch, cert for http application.,Password, domain, nsswitch, cert for ontapi application.,Community for snmp application (when creating SNMPv1 and SNMPv2 users).,The usm and community for snmp application (when creating SNMPv3 users).,Password for sp application.,Password for rsh application.,Password for telnet application.,Password, publickey, domain, nsswitch for ssh application.\n attribute :authentication_method\n validates :authentication_method, presence: true, expression_inclusion: {:in=>[:community, :password, :publickey, :domain, :nsswitch, :usm], :message=>\"%{value} needs to be :community, :password, :publickey, :domain, :nsswitch, :usm\"}\n\n # @return [String, nil] Password for the user account.,It is ignored for creating snmp users, but is required for creating non-snmp users.,For an existing user, this value will be used as the new password.\n attribute :set_password\n validates :set_password, type: String\n\n # @return [String, nil] The name of the role. Required when C(state=present)\n attribute :role_name\n validates :role_name, type: String\n\n # @return [Symbol, nil] Whether the specified user account is locked.\n attribute :lock_user\n validates :lock_user, type: Symbol\n\n # @return [String] The name of the vserver to use.\n attribute :vserver\n validates :vserver, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.681240439414978, "alphanum_fraction": 0.681240439414978, "avg_line_length": 43.70454406738281, "blob_id": "5ebe387c932dc3766430b54b95fb6186389e5e7a", "content_id": "7e1aba5df7e18a74ae13e4bd25693828b070f2ac", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1967, "license_type": "permissive", "max_line_length": 295, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/identity/ipa/ipa_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add, modify and delete group within IPA server\n class Ipa_group < Base\n # @return [Object] Canonical name.,Can not be changed as it is the unique identifier.\n attribute :cn\n validates :cn, presence: true\n\n # @return [Object, nil] Description of the group.\n attribute :description\n\n # @return [Symbol, nil] Allow adding external non-IPA members from trusted domains.\n attribute :external\n validates :external, type: Symbol\n\n # @return [Integer, nil] GID (use this option to set it manually).\n attribute :gidnumber\n validates :gidnumber, type: Integer\n\n # @return [Array<String>, String, nil] List of group names assigned to this group.,If an empty list is passed all groups will be removed from this group.,If option is omitted assigned groups will not be checked or changed.,Groups that are already assigned but not passed will be removed.\n attribute :group\n validates :group, type: TypeGeneric.new(String)\n\n # @return [Symbol, nil] Create as a non-POSIX group.\n attribute :nonposix\n validates :nonposix, type: Symbol\n\n # @return [Array<String>, String, nil] List of user names assigned to this group.,If an empty list is passed all users will be removed from this group.,If option is omitted assigned users will not be checked or changed.,Users that are already assigned but not passed will be removed.\n attribute :user\n validates :user, type: TypeGeneric.new(String)\n\n # @return [:present, :absent, nil] State to ensure\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7164592146873474, "alphanum_fraction": 0.7275242209434509, "avg_line_length": 39.16666793823242, "blob_id": "b97e52a1ab5dc02decc4042866d7f21745dacf36", "content_id": "3b9afe5dcb40c8cadb4b5355cddc227fa740c851", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 723, "license_type": "permissive", "max_line_length": 139, "num_lines": 18, "path": "/lib/ansible/ruby/modules/generated/windows/win_dotnet_ngen.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # After .NET framework is installed/updated, Windows will probably want to recompile things to optimise for the host.\n # This happens via scheduled task, usually at some inopportune time.\n # This module allows you to run this task on your own schedule, so you incur the CPU hit at some more convenient and controlled time.\n # U(http://blogs.msdn.com/b/dotnet/archive/2013/08/06/wondering-why-mscorsvw-exe-has-high-cpu-usage-you-can-speed-it-up.aspx)\n class Win_dotnet_ngen < Base\n\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.690115213394165, "alphanum_fraction": 0.6907216310501099, "avg_line_length": 52.19355010986328, "blob_id": "aa9f387f3b5222a5f682e04cbb4d729b82e6ecc4", "content_id": "7132b4859f3dc3441fe76333bc3a70f91bc9f0b7", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1649, "license_type": "permissive", "max_line_length": 307, "num_lines": 31, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_tag.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to create / delete / update VMware tags.\n # Tag feature is introduced in vSphere 6 version, so this module is not supported in the earlier versions of vSphere.\n # All variables and VMware object names are case sensitive.\n class Vmware_tag < Base\n # @return [String] The name of tag to manage.\n attribute :tag_name\n validates :tag_name, presence: true, type: String\n\n # @return [String, nil] The tag description.,This is required only if C(state) is set to C(present).,This parameter is ignored, when C(state) is set to C(absent).,Process of updating tag only allows description change.\n attribute :tag_description\n validates :tag_description, type: String\n\n # @return [String, nil] The unique ID generated by vCenter should be used to.,User can get this unique ID from facts module.\n attribute :category_id\n validates :category_id, type: String\n\n # @return [:present, :absent, nil] The state of tag.,If set to C(present) and tag does not exists, then tag is created.,If set to C(present) and tag exists, then tag is updated.,If set to C(absent) and tag exists, then tag is deleted.,If set to C(absent) and tag does not exists, no action is taken.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6658217310905457, "alphanum_fraction": 0.6692014932632446, "avg_line_length": 45.411766052246094, "blob_id": "545f6455708ef144d2c741373ad72895611fbe46", "content_id": "1d4ef386639b015574e4578c14b5398e843cb2f0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2367, "license_type": "permissive", "max_line_length": 232, "num_lines": 51, "path": "/lib/ansible/ruby/modules/generated/database/proxysql/proxysql_scheduler.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The M(proxysql_scheduler) module adds or removes schedules using the proxysql admin interface.\n class Proxysql_scheduler < Base\n # @return [Boolean, nil] A schedule with I(active) set to C(False) will be tracked in the database, but will be never loaded in the in-memory data structures.\n attribute :active\n validates :active, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Integer, nil] How often (in millisecond) the job will be started. The minimum value for I(interval_ms) is 100 milliseconds.\n attribute :interval_ms\n validates :interval_ms, type: Integer\n\n # @return [String] Full path of the executable to be executed.\n attribute :filename\n validates :filename, presence: true, type: String\n\n # @return [Object, nil] Argument that can be passed to the job.\n attribute :arg1\n\n # @return [Object, nil] Argument that can be passed to the job.\n attribute :arg2\n\n # @return [Object, nil] Argument that can be passed to the job.\n attribute :arg3\n\n # @return [Object, nil] Argument that can be passed to the job.\n attribute :arg4\n\n # @return [Object, nil] Argument that can be passed to the job.\n attribute :arg5\n\n # @return [Object, nil] Text field that can be used for any purposed defined by the user.\n attribute :comment\n\n # @return [:present, :absent, nil] When C(present) - adds the schedule, when C(absent) - removes the schedule.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Boolean, nil] By default we avoid deleting more than one schedule in a single batch, however if you need this behaviour and you're not concerned about the schedules deleted, you can set I(force_delete) to C(True).\n attribute :force_delete\n validates :force_delete, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7019931674003601, "alphanum_fraction": 0.7063685059547424, "avg_line_length": 56.13888931274414, "blob_id": "75b7da658b9172b667e19d02109c1e450afd5572", "content_id": "e365868a15d00ec9c9201fbdbe85e3e643d8dfc8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2057, "license_type": "permissive", "max_line_length": 340, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/packaging/language/easy_install.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Installs Python libraries, optionally in a I(virtualenv)\n class Easy_install < Base\n # @return [String] A Python library name\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] an optional I(virtualenv) directory path to install into. If the I(virtualenv) does not exist, it is created automatically\n attribute :virtualenv\n validates :virtualenv, type: String\n\n # @return [:yes, :no, nil] Whether the virtual environment will inherit packages from the global site-packages directory. Note that if this setting is changed on an already existing virtual environment it will not have any effect, the environment must be deleted and newly created.\n attribute :virtualenv_site_packages\n validates :virtualenv_site_packages, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] The command to create the virtual environment with. For example C(pyvenv), C(virtualenv), C(virtualenv2).\n attribute :virtualenv_command\n validates :virtualenv_command, type: String\n\n # @return [Object, nil] The explicit executable or a pathname to the executable to be used to run easy_install for a specific version of Python installed in the system. For example C(easy_install-3.3), if there are both Python 2.7 and 3.3 installations in the system and you want to run easy_install for the Python 3.3 installation.\n attribute :executable\n\n # @return [:present, :latest, nil] The desired state of the library. C(latest) ensures that the latest version is installed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :latest], :message=>\"%{value} needs to be :present, :latest\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6685006618499756, "alphanum_fraction": 0.6685006618499756, "avg_line_length": 44.4375, "blob_id": "3faf5c08ea998ee29ddb61975d8e4c273d51a747", "content_id": "b846759965149edf401befe886d5880e79475480", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1454, "license_type": "permissive", "max_line_length": 211, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_taboo_contract.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage taboo contracts on Cisco ACI fabrics.\n class Aci_taboo_contract < Base\n # @return [String] The name of the Taboo Contract.\n attribute :taboo_contract\n validates :taboo_contract, presence: true, type: String\n\n # @return [Object, nil] The description for the Taboo Contract.\n attribute :description\n\n # @return [String] The name of the tenant.\n attribute :tenant\n validates :tenant, presence: true, type: String\n\n # @return [:\"application-profile\", :context, :global, :tenant, nil] The scope of a service contract.,The APIC defaults to C(context) when unset during creation.\n attribute :scope\n validates :scope, expression_inclusion: {:in=>[:\"application-profile\", :context, :global, :tenant], :message=>\"%{value} needs to be :\\\"application-profile\\\", :context, :global, :tenant\"}, allow_nil: true\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7321937084197998, "alphanum_fraction": 0.7435897588729858, "avg_line_length": 18.5, "blob_id": "a539a17142998d1aec05ac4d6c9378353fee27a4", "content_id": "40269b6be78aae5e44a5fa57c55936fd60472d0d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 351, "license_type": "permissive", "max_line_length": 66, "num_lines": 18, "path": "/lib/ansible/ruby/modules/custom/commands/command.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# VALIDATED_CHECKSUM: bgYpmlgHHwir0nbxTr9jiOjGnTv/CI1XdBL3X/PJaak=\n\n# See LICENSE.txt for license\n\nrequire 'ansible/ruby/modules/free_form'\nrequire 'ansible/ruby/modules/generated/commands/command'\n\nmodule Ansible\n module Ruby\n module Modules\n class Command\n include FreeForm\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6831231117248535, "alphanum_fraction": 0.6874728202819824, "avg_line_length": 84.14814758300781, "blob_id": "a448a8f066f2cb4dd25a59c474cbf1b52fda7e85", "content_id": "61281c1e46e4700c1b02c53a58866db64518e8f1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4598, "license_type": "permissive", "max_line_length": 973, "num_lines": 54, "path": "/lib/ansible/ruby/modules/generated/cloud/rackspace/rax_mon_check.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or delete a Rackspace Cloud Monitoring check associated with an existing rax_mon_entity. A check is a specific test or measurement that is performed, possibly from different monitoring zones, on the systems you monitor. Rackspace monitoring module flow | rax_mon_entity -> *rax_mon_check* -> rax_mon_notification -> rax_mon_notification_plan -> rax_mon_alarm\n class Rax_mon_check < Base\n # @return [:present, :absent, nil] Ensure that a check with this C(label) exists or does not exist.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object] ID of the rax_mon_entity to target with this check.\n attribute :entity_id\n validates :entity_id, presence: true\n\n # @return [Object] Defines a label for this check, between 1 and 64 characters long.\n attribute :label\n validates :label, presence: true\n\n # @return [:\"remote.dns\", :\"remote.ftp-banner\", :\"remote.http\", :\"remote.imap-banner\", :\"remote.mssql-banner\", :\"remote.mysql-banner\", :\"remote.ping\", :\"remote.pop3-banner\", :\"remote.postgresql-banner\", :\"remote.smtp-banner\", :\"remote.smtp\", :\"remote.ssh\", :\"remote.tcp\", :\"remote.telnet-banner\", :\"agent.filesystem\", :\"agent.memory\", :\"agent.load_average\", :\"agent.cpu\", :\"agent.disk\", :\"agent.network\", :\"agent.plugin\"] The type of check to create. C(remote.) checks may be created on any rax_mon_entity. C(agent.) checks may only be created on rax_mon_entities that have a non-null C(agent_id).\n attribute :check_type\n validates :check_type, presence: true, expression_inclusion: {:in=>[:\"remote.dns\", :\"remote.ftp-banner\", :\"remote.http\", :\"remote.imap-banner\", :\"remote.mssql-banner\", :\"remote.mysql-banner\", :\"remote.ping\", :\"remote.pop3-banner\", :\"remote.postgresql-banner\", :\"remote.smtp-banner\", :\"remote.smtp\", :\"remote.ssh\", :\"remote.tcp\", :\"remote.telnet-banner\", :\"agent.filesystem\", :\"agent.memory\", :\"agent.load_average\", :\"agent.cpu\", :\"agent.disk\", :\"agent.network\", :\"agent.plugin\"], :message=>\"%{value} needs to be :\\\"remote.dns\\\", :\\\"remote.ftp-banner\\\", :\\\"remote.http\\\", :\\\"remote.imap-banner\\\", :\\\"remote.mssql-banner\\\", :\\\"remote.mysql-banner\\\", :\\\"remote.ping\\\", :\\\"remote.pop3-banner\\\", :\\\"remote.postgresql-banner\\\", :\\\"remote.smtp-banner\\\", :\\\"remote.smtp\\\", :\\\"remote.ssh\\\", :\\\"remote.tcp\\\", :\\\"remote.telnet-banner\\\", :\\\"agent.filesystem\\\", :\\\"agent.memory\\\", :\\\"agent.load_average\\\", :\\\"agent.cpu\\\", :\\\"agent.disk\\\", :\\\"agent.network\\\", :\\\"agent.plugin\\\"\"}\n\n # @return [Object, nil] Comma-separated list of the names of the monitoring zones the check should run from. Available monitoring zones include mzdfw, mzhkg, mziad, mzlon, mzord and mzsyd. Required for remote.* checks; prohibited for agent.* checks.\n attribute :monitoring_zones_poll\n\n # @return [Object, nil] One of `target_hostname` and `target_alias` is required for remote.* checks, but prohibited for agent.* checks. The hostname this check should target. Must be a valid IPv4, IPv6, or FQDN.\n attribute :target_hostname\n\n # @return [Object, nil] One of `target_alias` and `target_hostname` is required for remote.* checks, but prohibited for agent.* checks. Use the corresponding key in the entity's `ip_addresses` hash to resolve an IP address to target.\n attribute :target_alias\n\n # @return [Object, nil] Additional details specific to the check type. Must be a hash of strings between 1 and 255 characters long, or an array or object containing 0 to 256 items.\n attribute :details\n\n # @return [Symbol, nil] If \"yes\", ensure the check is created, but don't actually use it yet.\n attribute :disabled\n validates :disabled, type: Symbol\n\n # @return [Object, nil] Hash of arbitrary key-value pairs to accompany this check if it fires. Keys and values must be strings between 1 and 255 characters long.\n attribute :metadata\n\n # @return [Object, nil] The number of seconds between each time the check is performed. Must be greater than the minimum period set on your account.\n attribute :period\n\n # @return [Object, nil] The number of seconds this check will wait when attempting to collect results. Must be less than the period.\n attribute :timeout\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7045503854751587, "alphanum_fraction": 0.7058567404747009, "avg_line_length": 84.05555725097656, "blob_id": "f95294ae30303d37947557f9d95e196871bed87b", "content_id": "35e5afbce69c8606b0b3e1928a8941fcc1eea985", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4593, "license_type": "permissive", "max_line_length": 908, "num_lines": 54, "path": "/lib/ansible/ruby/modules/generated/files/file.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Sets attributes of files, symlinks, and directories, or removes files/symlinks/directories. Many other modules support the same options as the C(file) module - including M(copy), M(template), and M(assemble).\n # For Windows targets, use the M(win_file) module instead.\n class File < Base\n # @return [String] Path to the file being managed.\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [:absent, :directory, :file, :hard, :link, :touch, nil] If C(directory), all intermediate subdirectories will be created if they do not exist. Since Ansible 1.7 they will be created with the supplied permissions. If C(file), the file will NOT be created if it does not exist; see the C(touch) value or the M(copy) or M(template) module if you want that behavior. If C(link), the symbolic link will be created or changed. Use C(hard) for hardlinks. If C(absent), directories will be recursively deleted, and files or symlinks will be unlinked. Note that C(absent) will not cause C(file) to fail if the C(path) does not exist as the state did not change. If C(touch) (new in 1.4), an empty file will be created if the C(path) does not exist, while an existing file or directory will receive updated file access and modification times (similar to the way `touch` works from the command line).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :directory, :file, :hard, :link, :touch], :message=>\"%{value} needs to be :absent, :directory, :file, :hard, :link, :touch\"}, allow_nil: true\n\n # @return [String, nil] path of the file to link to (applies only to C(state=link) and C(state=hard)). Will accept absolute, relative and nonexisting paths. Relative paths are relative to the file being created (C(path)) which is how the UNIX command C(ln -s SRC DEST) treats relative paths.\n attribute :src\n validates :src, type: String\n\n # @return [:yes, :no, nil] recursively set the specified file attributes (applies only to directories)\n attribute :recurse\n validates :recurse, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] force the creation of the symlinks in two cases: the source file does not exist (but will appear later); the destination exists and is a file (so, we need to unlink the \"path\" file and create symlink to the \"src\" file in place of it).\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] This flag indicates that filesystem links, if they exist, should be followed.,Previous to Ansible 2.5, this was C(no) by default.\n attribute :follow\n validates :follow, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] This parameter indicates the time the file's modification time should be set to,Should be C(preserve) when no modification is required, C(YYYYMMDDHHMM.SS) when using default time format, or C(now),Default is None meaning that C(preserve) is the default for C(state=[file,directory,link,hard]) and C(now) is default for C(state=touch)\n attribute :modification_time\n validates :modification_time, type: String\n\n # @return [String, nil] When used with C(modification_time), indicates the time format that must be used.,Based on default Python format (see time.strftime doc)\n attribute :modification_time_format\n validates :modification_time_format, type: String\n\n # @return [String, nil] This parameter indicates the time the file's access time should be set to,Should be C(preserve) when no modification is required, C(YYYYMMDDHHMM.SS) when using default time format, or C(now),Default is None meaning that C(preserve) is the default for C(state=[file,directory,link,hard]) and C(now) is default for C(state=touch)\n attribute :access_time\n validates :access_time, type: String\n\n # @return [String, nil] When used with C(access_time), indicates the time format that must be used.,Based on default Python format (see time.strftime doc)\n attribute :access_time_format\n validates :access_time_format, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6850207448005676, "alphanum_fraction": 0.6850207448005676, "avg_line_length": 47.25714111328125, "blob_id": "685303f998efc03e5bf17ee7159f278ce74d776d", "content_id": "1273b041d5e982ff463fe5d2f79529261633ec50", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1689, "license_type": "permissive", "max_line_length": 267, "num_lines": 35, "path": "/lib/ansible/ruby/modules/generated/windows/win_command.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The C(win_command) module takes the command name followed by a list of space-delimited arguments.\n # The given command will be executed on all selected nodes. It will not be processed through the shell, so variables like C($env:HOME) and operations like C(\"<\"), C(\">\"), C(\"|\"), and C(\";\") will not work (use the M(win_shell) module if you need these features).\n # For non-Windows targets, use the M(command) module instead.\n class Win_command < Base\n # @return [Object] The C(win_command) module takes a free form command to run.,There is no parameter actually named 'free form'. See the examples!\n attribute :free_form\n validates :free_form, presence: true\n\n # @return [String, nil] A path or path filter pattern; when the referenced path exists on the target host, the task will be skipped.\n attribute :creates\n validates :creates, type: String\n\n # @return [String, nil] A path or path filter pattern; when the referenced path B(does not) exist on the target host, the task will be skipped.\n attribute :removes\n validates :removes, type: String\n\n # @return [String, nil] Set the specified path as the current working directory before executing a command.\n attribute :chdir\n validates :chdir, type: String\n\n # @return [String, nil] Set the stdin of the command directly to the specified value.\n attribute :stdin\n validates :stdin, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6564922332763672, "alphanum_fraction": 0.6574612259864807, "avg_line_length": 39.47058868408203, "blob_id": "74dab9a8d97220b027af0439714682c3e0db2f89", "content_id": "46e60c6966baeae4c847c230513b261bb97e123f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2064, "license_type": "permissive", "max_line_length": 187, "num_lines": 51, "path": "/lib/ansible/ruby/modules/generated/windows/win_iis_website.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates, Removes and configures a IIS Web site.\n class Win_iis_website < Base\n # @return [String] Names of web site.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Explicitly set the IIS numeric ID for a site.,Note that this value cannot be changed after the website has been created.\n attribute :site_id\n\n # @return [:absent, :started, :stopped, :restarted, nil] State of the web site\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :started, :stopped, :restarted], :message=>\"%{value} needs to be :absent, :started, :stopped, :restarted\"}, allow_nil: true\n\n # @return [String, nil] The physical path on the remote host to use for the new site.,The specified folder must already exist.\n attribute :physical_path\n validates :physical_path, type: String\n\n # @return [String, nil] The application pool in which the new site executes.\n attribute :application_pool\n validates :application_pool, type: String\n\n # @return [Integer, nil] The port to bind to / use for the new site.\n attribute :port\n validates :port, type: Integer\n\n # @return [String, nil] The IP address to bind to / use for the new site.\n attribute :ip\n validates :ip, type: String\n\n # @return [String, nil] The host header to bind to / use for the new site.\n attribute :hostname\n validates :hostname, type: String\n\n # @return [Object, nil] Enables HTTPS binding on the site..\n attribute :ssl\n\n # @return [String, nil] Custom site Parameters from string where properties are separated by a pipe and property name/values by colon Ex. \"foo:1|bar:2\"\n attribute :parameters\n validates :parameters, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6946211457252502, "alphanum_fraction": 0.6946211457252502, "avg_line_length": 41.17073059082031, "blob_id": "22f34ed2c44a1101e03b440056c5758b794315f5", "content_id": "a6b2622a1cbc3f8dea19bc21f108a67230e5a5f6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1729, "license_type": "permissive", "max_line_length": 143, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_vxlan_vtep.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages VXLAN Network Virtualization Endpoint (NVE) overlay interface that terminates VXLAN tunnels.\n class Nxos_vxlan_vtep < Base\n # @return [String] Interface name for the VXLAN Network Virtualization Endpoint.\n attribute :interface\n validates :interface, presence: true, type: String\n\n # @return [String, nil] Description of the NVE interface.\n attribute :description\n validates :description, type: String\n\n # @return [Symbol, nil] Specify mechanism for host reachability advertisement.\n attribute :host_reachability\n validates :host_reachability, type: Symbol\n\n # @return [Symbol, nil] Administratively shutdown the NVE interface.\n attribute :shutdown\n validates :shutdown, type: Symbol\n\n # @return [String, nil] Specify the loopback interface whose IP address should be used for the NVE interface.\n attribute :source_interface\n validates :source_interface, type: String\n\n # @return [Integer, nil] Suppresses advertisement of the NVE loopback address until the overlay has converged.\n attribute :source_interface_hold_down_time\n validates :source_interface_hold_down_time, type: Integer\n\n # @return [:present, :absent, nil] Determines whether the config should be present or not on the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.688511312007904, "alphanum_fraction": 0.688511312007904, "avg_line_length": 51.59574508666992, "blob_id": "a80a51038acb90ddd33260cd29c29c45ccdf9b08", "content_id": "84f092113ad16313bbd86e9019349e7f28c2ab82", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2472, "license_type": "permissive", "max_line_length": 235, "num_lines": 47, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_guest_boot_manager.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to manage boot options for the given virtual machine.\n class Vmware_guest_boot_manager < Base\n # @return [String, nil] Name of the VM to work with.,This is required if C(uuid) parameter is not supplied.\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] UUID of the instance to manage if known, this is VMware's BIOS UUID.,This is required if C(name) parameter is not supplied.\n attribute :uuid\n\n # @return [Object, nil] List of the boot devices.\n attribute :boot_order\n\n # @return [:first, :last, nil] If multiple virtual machines matching the name, use the first or last found.\n attribute :name_match\n validates :name_match, expression_inclusion: {:in=>[:first, :last], :message=>\"%{value} needs to be :first, :last\"}, allow_nil: true\n\n # @return [Integer, nil] Delay in milliseconds before starting the boot sequence.\n attribute :boot_delay\n validates :boot_delay, type: Integer\n\n # @return [Symbol, nil] If set to C(True), the virtual machine automatically enters BIOS setup the next time it boots.,The virtual machine resets this flag, so that the machine boots proceeds normally.\n attribute :enter_bios_setup\n validates :enter_bios_setup, type: Symbol\n\n # @return [Symbol, nil] If set to C(True), the virtual machine that fails to boot, will try to boot again after C(boot_retry_delay) is expired.,If set to C(False), the virtual machine waits indefinitely for user intervention.\n attribute :boot_retry_enabled\n validates :boot_retry_enabled, type: Symbol\n\n # @return [Integer, nil] Specify the time in milliseconds between virtual machine boot failure and subsequent attempt to boot again.,If set, will automatically set C(boot_retry_enabled) to C(True) as this parameter is required.\n attribute :boot_retry_delay\n validates :boot_retry_delay, type: Integer\n\n # @return [:bios, :efi, nil] Choose which firmware should be used to boot the virtual machine.\n attribute :boot_firmware\n validates :boot_firmware, expression_inclusion: {:in=>[:bios, :efi], :message=>\"%{value} needs to be :bios, :efi\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7150177955627441, "alphanum_fraction": 0.7222775816917419, "avg_line_length": 69.9595947265625, "blob_id": "c10620e33685b62be6ee6a5eae9a9185d52b2145", "content_id": "e643997400850897a25a190edfc998515c9f2ce1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 7025, "license_type": "permissive", "max_line_length": 623, "num_lines": 99, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_gslbservice.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure GslbService object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_gslbservice < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Object, nil] The federated application persistence associated with gslbservice site persistence functionality.,It is a reference to an object of type applicationpersistenceprofile.,Field introduced in 17.2.1.\n attribute :application_persistence_profile_ref\n\n # @return [Symbol, nil] Gs member's overall health status is derived based on a combination of controller and datapath health-status inputs.,Note that the datapath status is determined by the association of health monitor profiles.,Only the controller provided status is determined through this configuration.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :controller_health_status_enabled\n validates :controller_health_status_enabled, type: Symbol\n\n # @return [Object, nil] Creator name.,Field introduced in 17.1.2.\n attribute :created_by\n\n # @return [Object, nil] User defined description for the object.\n attribute :description\n\n # @return [Object, nil] Fully qualified domain name of the gslb service.\n attribute :domain_names\n\n # @return [Object, nil] Response to the client query when the gslb service is down.\n attribute :down_response\n\n # @return [Symbol, nil] Enable or disable the gslb service.,If the gslb service is enabled, then the vips are sent in the dns responses based on reachability and configured algorithm.,If the gslb service is disabled, then the vips are no longer available in the dns response.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :enabled\n validates :enabled, type: Symbol\n\n # @return [Object, nil] Select list of pools belonging to this gslb service.\n attribute :groups\n\n # @return [Object, nil] Verify vs health by applying one or more health monitors.,Active monitors generate synthetic traffic from dns service engine and to mark a vs up or down based on the response.,It is a reference to an object of type healthmonitor.\n attribute :health_monitor_refs\n\n # @return [Object, nil] Health monitor probe can be executed for all the members or it can be executed only for third-party members.,This operational mode is useful to reduce the number of health monitor probes in case of a hybrid scenario.,In such a case, avi members can have controller derived status while non-avi members can be probed by via health monitor probes in dataplane.,Enum options - GSLB_SERVICE_HEALTH_MONITOR_ALL_MEMBERS, GSLB_SERVICE_HEALTH_MONITOR_ONLY_NON_AVI_MEMBERS.,Default value when not specified in API or module is interpreted by Avi Controller as GSLB_SERVICE_HEALTH_MONITOR_ALL_MEMBERS.\n attribute :health_monitor_scope\n\n # @return [Symbol, nil] This field indicates that this object is replicated across gslb federation.,Field introduced in 17.1.3.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :is_federated\n validates :is_federated, type: Symbol\n\n # @return [Object, nil] The minimum number of members to distribute traffic to.,Allowed values are 1-65535.,Special values are 0 - 'disable'.,Field introduced in 17.2.4.,Default value when not specified in API or module is interpreted by Avi Controller as 0.\n attribute :min_members\n\n # @return [String] Name for the gslb service.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Number of ip addresses of this gslb service to be returned by the dns service.,Enter 0 to return all ip addresses.,Allowed values are 1-20.,Special values are 0- 'return all ip addresses'.\n attribute :num_dns_ip\n\n # @return [Object, nil] The load balancing algorithm will pick a gslb pool within the gslb service list of available pools.,Enum options - GSLB_SERVICE_ALGORITHM_PRIORITY, GSLB_SERVICE_ALGORITHM_GEO.,Field introduced in 17.2.3.,Default value when not specified in API or module is interpreted by Avi Controller as GSLB_SERVICE_ALGORITHM_PRIORITY.\n attribute :pool_algorithm\n\n # @return [Symbol, nil] Enable site-persistence for the gslbservice.,Field introduced in 17.2.1.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :site_persistence_enabled\n validates :site_persistence_enabled, type: Symbol\n\n # @return [Object, nil] It is a reference to an object of type tenant.\n attribute :tenant_ref\n\n # @return [Object, nil] Ttl value (in seconds) for records served for this gslb service by the dns service.,Allowed values are 1-86400.,Units(SEC).\n attribute :ttl\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Symbol, nil] Use the client ip subnet from the edns option as source ipaddress for client geo-location and consistent hash algorithm.,Default is true.,Field introduced in 17.1.1.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :use_edns_client_subnet\n validates :use_edns_client_subnet, type: Symbol\n\n # @return [Object, nil] Uuid of the gslb service.\n attribute :uuid\n\n # @return [Symbol, nil] Enable wild-card match of fqdn if an exact match is not found in the dns table, the longest match is chosen by wild-carding the fqdn in the dns,request.,Default is false.,Field introduced in 17.1.1.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :wildcard_match\n validates :wildcard_match, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.6730769276618958, "avg_line_length": 37.26415252685547, "blob_id": "6fada8f852924952554a1e1678247009e8568050", "content_id": "cfb39c10bf5be53dafb1bb7b2a119549dd319652", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2028, "license_type": "permissive", "max_line_length": 164, "num_lines": 53, "path": "/lib/ansible/ruby/modules/generated/identity/opendj/opendj_backendprop.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module will update settings for OpenDJ with the command set-backend-prop.\n # It will check first via de get-backend-prop if configuration needs to be applied.\n class Opendj_backendprop < Base\n # @return [String, nil] The path to the bin directory of OpenDJ.\n attribute :opendj_bindir\n validates :opendj_bindir, type: String\n\n # @return [String] The hostname of the OpenDJ server.\n attribute :hostname\n validates :hostname, presence: true, type: String\n\n # @return [String] The Admin port on which the OpenDJ instance is available.\n attribute :port\n validates :port, presence: true, type: String\n\n # @return [String, nil] The username to connect to.\n attribute :username\n validates :username, type: String\n\n # @return [String, nil] The password for the cn=Directory Manager user.,Either password or passwordfile is needed.\n attribute :password\n validates :password, type: String\n\n # @return [Object, nil] Location to the password file which holds the password for the cn=Directory Manager user.,Either password or passwordfile is needed.\n attribute :passwordfile\n\n # @return [String] The name of the backend on which the property needs to be updated.\n attribute :backend\n validates :backend, presence: true, type: String\n\n # @return [String] The configuration setting to update.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] The value for the configuration item.\n attribute :value\n validates :value, presence: true, type: String\n\n # @return [String, nil] If configuration needs to be added/updated\n attribute :state\n validates :state, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6780612468719482, "alphanum_fraction": 0.6780612468719482, "avg_line_length": 46.80487823486328, "blob_id": "1a112f0b465f228d01c4aa53032188fb80cb5d90", "content_id": "045832f96e01b9e5a48fb3c60de9a47805373617", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1960, "license_type": "permissive", "max_line_length": 257, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/network/aos/aos_external_router.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Apstra AOS External Router module let you manage your External Router easily. You can create create and delete External Router by Name, ID or by using a JSON File. This module is idempotent and support the I(check) mode. It's using the AOS REST API.\n class Aos_external_router < Base\n # @return [String] An existing AOS session as obtained by M(aos_login) module.\n attribute :session\n validates :session, presence: true, type: String\n\n # @return [String, nil] Name of the External Router to manage. Only one of I(name), I(id) or I(content) can be set.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] AOS Id of the External Router to manage (can't be used to create a new External Router), Only one of I(name), I(id) or I(content) can be set.\n attribute :id\n validates :id, type: String\n\n # @return [String, nil] Datastructure of the External Router to create. The format is defined by the I(content_format) parameter. It's the same datastructure that is returned on success in I(value).\n attribute :content\n validates :content, type: String\n\n # @return [:present, :absent, nil] Indicate what is the expected state of the External Router (present or not).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] IP address of the Loopback interface of the external_router.\n attribute :loopback\n validates :loopback, type: String\n\n # @return [Integer, nil] ASN id of the external_router.\n attribute :asn\n validates :asn, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6577540040016174, "alphanum_fraction": 0.6760886311531067, "avg_line_length": 42.63333511352539, "blob_id": "2753e902693c31e75ebe9cda4e3c334cbecc0345", "content_id": "9ae01b887da35d99982387694aa5b0503eff6e79", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1309, "license_type": "permissive", "max_line_length": 201, "num_lines": 30, "path": "/lib/ansible/ruby/modules/generated/remote_management/hpilo/hpilo_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module gathers facts for a specific system using its HP iLO interface. These facts include hardware and network related information useful for provisioning (e.g. macaddress, uuid).\n # This module requires the hpilo python module.\n class Hpilo_facts < Base\n # @return [String] The HP iLO hostname/address that is linked to the physical system.\n attribute :host\n validates :host, presence: true, type: String\n\n # @return [String, nil] The login name to authenticate to the HP iLO interface.\n attribute :login\n validates :login, type: String\n\n # @return [String, nil] The password to authenticate to the HP iLO interface.\n attribute :password\n validates :password, type: String\n\n # @return [:SSLv3, :SSLv23, :TLSv1, :TLSv1_1, :TLSv1_2, nil] Change the ssl_version used.\n attribute :ssl_version\n validates :ssl_version, expression_inclusion: {:in=>[:SSLv3, :SSLv23, :TLSv1, :TLSv1_1, :TLSv1_2], :message=>\"%{value} needs to be :SSLv3, :SSLv23, :TLSv1, :TLSv1_1, :TLSv1_2\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6558079719543457, "alphanum_fraction": 0.6558079719543457, "avg_line_length": 44.74509811401367, "blob_id": "9e77d7f0ea1497002b430dab11fa05921c594461", "content_id": "16322a40923a869b33bcee73ee880ec1d779b152", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2333, "license_type": "permissive", "max_line_length": 238, "num_lines": 51, "path": "/lib/ansible/ruby/modules/generated/network/netvisor/pn_ospfarea.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Execute vrouter-ospf-add, vrouter-ospf-remove command.\n # This command adds/removes Open Shortest Path First(OSPF) area to/from a virtual router(vRouter) service.\n class Pn_ospfarea < Base\n # @return [String] Login username.\n attribute :pn_cliusername\n validates :pn_cliusername, presence: true, type: String\n\n # @return [String] Login password.\n attribute :pn_clipassword\n validates :pn_clipassword, presence: true, type: String\n\n # @return [Object, nil] Target switch(es) to run the CLI on.\n attribute :pn_cliswitch\n\n # @return [:present, :absent, :update] State the action to perform. Use 'present' to add ospf-area, 'absent' to remove ospf-area and 'update' to modify ospf-area.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent, :update], :message=>\"%{value} needs to be :present, :absent, :update\"}\n\n # @return [String] Specify the name of the vRouter.\n attribute :pn_vrouter_name\n validates :pn_vrouter_name, presence: true, type: String\n\n # @return [String] Specify the OSPF area number.\n attribute :pn_ospf_area\n validates :pn_ospf_area, presence: true, type: String\n\n # @return [:none, :stub, :\"stub-no-summary\", :nssa, :\"nssa-no-summary\", nil] Specify the OSPF stub type.\n attribute :pn_stub_type\n validates :pn_stub_type, expression_inclusion: {:in=>[:none, :stub, :\"stub-no-summary\", :nssa, :\"nssa-no-summary\"], :message=>\"%{value} needs to be :none, :stub, :\\\"stub-no-summary\\\", :nssa, :\\\"nssa-no-summary\\\"\"}, allow_nil: true\n\n # @return [Object, nil] OSPF prefix list for filtering incoming packets.\n attribute :pn_prefix_listin\n\n # @return [Object, nil] OSPF prefix list for filtering outgoing packets.\n attribute :pn_prefix_listout\n\n # @return [Boolean, nil] Enable/disable system information.\n attribute :pn_quiet\n validates :pn_quiet, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6454810500144958, "alphanum_fraction": 0.6454810500144958, "avg_line_length": 45.35135269165039, "blob_id": "21740b84d87125a1baee628cb571e8235cfdc29a", "content_id": "5b5aaeb9ec844dfc5276f1881ce4ef37fc92efc8", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1715, "license_type": "permissive", "max_line_length": 143, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_cluster.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove VMware vSphere clusters.\n class Vmware_cluster < Base\n # @return [String] The name of the cluster that will be created.\n attribute :cluster_name\n validates :cluster_name, presence: true, type: String\n\n # @return [String] The name of the datacenter the cluster will be created in.\n attribute :datacenter_name\n validates :datacenter_name, presence: true, type: String\n\n # @return [:yes, :no, nil] If set to C(yes) will enable DRS when the cluster is created.\n attribute :enable_drs\n validates :enable_drs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If set to C(yes) will enable HA when the cluster is created.\n attribute :enable_ha\n validates :enable_ha, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If set to C(yes) will enable vSAN when the cluster is created.\n attribute :enable_vsan\n validates :enable_vsan, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:absent, :present, nil] Create (C(present)) or remove (C(absent)) a VMware vSphere cluster.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7864077687263489, "alphanum_fraction": 0.7864077687263489, "avg_line_length": 24.75, "blob_id": "d78e77da98f7588c4eeda091e48e3400c15a6a9d", "content_id": "fbfb00b95111934de78f482bcffbf8d259030b4b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 103, "license_type": "permissive", "max_line_length": 35, "num_lines": 4, "path": "/lib/ansible/ruby/rake/tasks.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'ansible/ruby/rake/compile'\nrequire 'ansible/ruby/rake/execute'\n" }, { "alpha_fraction": 0.6526839733123779, "alphanum_fraction": 0.660149335861206, "avg_line_length": 50.14545440673828, "blob_id": "cdd26e74906196e0a443016180e16969b85c42bc", "content_id": "1ce38d236649ba72aaa8c58a83e3ac22807fd337", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2813, "license_type": "permissive", "max_line_length": 217, "num_lines": 55, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_vpc_subnet.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage subnets in AWS virtual private clouds\n class Ec2_vpc_subnet < Base\n # @return [Object, nil] The availability zone for the subnet.\n attribute :az\n\n # @return [String, nil] The CIDR block for the subnet. E.g. 192.0.2.0/24.\n attribute :cidr\n validates :cidr, type: String\n\n # @return [String, nil] The IPv6 CIDR block for the subnet. The VPC must have a /56 block assigned and this value must be a valid IPv6 /64 that falls in the VPC range.,Required if I(assign_instances_ipv6=true)\n attribute :ipv6_cidr\n validates :ipv6_cidr, type: String\n\n # @return [Object, nil] A dict of tags to apply to the subnet. Any tags currently applied to the subnet and not present here will be removed.\n attribute :tags\n\n # @return [:present, :absent, nil] Create or remove the subnet\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] VPC ID of the VPC in which to create or delete the subnet.\n attribute :vpc_id\n validates :vpc_id, presence: true, type: String\n\n # @return [:yes, :no, nil] Specify C(yes) to indicate that instances launched into the subnet should be assigned public IP address by default.\n attribute :map_public\n validates :map_public, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Specify C(yes) to indicate that instances launched into the subnet should be automatically assigned an IPv6 address.\n attribute :assign_instances_ipv6\n validates :assign_instances_ipv6, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] When specified,I(state=present) module will wait for subnet to be in available state before continuing.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Number of seconds to wait for subnet to become available I(wait=True).\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [:yes, :no, nil] Whether or not to remove tags that do not appear in the I(tags) list.\n attribute :purge_tags\n validates :purge_tags, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7214764952659607, "alphanum_fraction": 0.7214764952659607, "avg_line_length": 55.761905670166016, "blob_id": "0dbe00a1fc97133c63665af3d62d9316ca90061f", "content_id": "527586f37981cb92c2aef48f78b99531bfa1c951", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1192, "license_type": "permissive", "max_line_length": 401, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_guest_custom_attribute_defs.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to add and remove custom attributes definitions for the given virtual machine from VMWare.\n class Vmware_guest_custom_attribute_defs < Base\n # @return [String, nil] Name of the custom attribute definition.,This is required parameter, if C(state) is set to C(present) or C(absent).\n attribute :attribute_key\n validates :attribute_key, type: String\n\n # @return [:present, :absent] Manage definition of custom attributes.,If set to C(present) and definition not present, then custom attribute definition is created.,If set to C(present) and definition is present, then no action taken.,If set to C(absent) and definition is present, then custom attribute definition is removed.,If set to C(absent) and definition is absent, then no action taken.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6824720501899719, "alphanum_fraction": 0.6853134632110596, "avg_line_length": 59.54838562011719, "blob_id": "837b1375aa20afcce54c428428bcfb2115ea064b", "content_id": "735eab3e48f561985cd905a48efae03b91d9f5c8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5631, "license_type": "permissive", "max_line_length": 234, "num_lines": 93, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_bd.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages Bridge Domains (BD) on Cisco ACI fabrics.\n class Aci_bd < Base\n # @return [Symbol, nil] Determines if the Bridge Domain should flood ARP traffic.,The APIC defaults to C(no) when unset during creation.\n attribute :arp_flooding\n validates :arp_flooding, type: Symbol\n\n # @return [String, nil] The name of the Bridge Domain.\n attribute :bd\n validates :bd, type: String\n\n # @return [:ethernet, :fc, nil] The type of traffic on the Bridge Domain.,The APIC defaults to C(ethernet) when unset during creation.\n attribute :bd_type\n validates :bd_type, expression_inclusion: {:in=>[:ethernet, :fc], :message=>\"%{value} needs to be :ethernet, :fc\"}, allow_nil: true\n\n # @return [Object, nil] Description for the Bridge Domain.\n attribute :description\n\n # @return [Symbol, nil] Determines if PIM is enabled.,The APIC defaults to C(no) when unset during creation.\n attribute :enable_multicast\n validates :enable_multicast, type: Symbol\n\n # @return [Symbol, nil] Determines if IP forwarding should be allowed.,The APIC defaults to C(yes) when unset during creation.\n attribute :enable_routing\n validates :enable_routing, type: Symbol\n\n # @return [Symbol, nil] Clears all End Points in all Leaves when C(yes).,The value is not reset to disabled once End Points have been cleared; that requires a second task.,The APIC defaults to C(no) when unset during creation.\n attribute :endpoint_clear\n validates :endpoint_clear, type: Symbol\n\n # @return [:default, :garp, nil] Determines if GARP should be enabled to detect when End Points move.,The APIC defaults to C(garp) when unset during creation.\n attribute :endpoint_move_detect\n validates :endpoint_move_detect, expression_inclusion: {:in=>[:default, :garp], :message=>\"%{value} needs to be :default, :garp\"}, allow_nil: true\n\n # @return [:inherit, :resolve, nil] Determines if the Bridge Domain should inherit or resolve the End Point Retention Policy.,The APIC defaults to C(resolve) when unset during creation.\n attribute :endpoint_retention_action\n validates :endpoint_retention_action, expression_inclusion: {:in=>[:inherit, :resolve], :message=>\"%{value} needs to be :inherit, :resolve\"}, allow_nil: true\n\n # @return [Object, nil] The name of the End Point Retention Policy the Bridge Domain should use when overriding the default End Point Retention Policy.\n attribute :endpoint_retention_policy\n\n # @return [Object, nil] The name of the IGMP Snooping Policy the Bridge Domain should use when overriding the default IGMP Snooping Policy.\n attribute :igmp_snoop_policy\n\n # @return [Symbol, nil] Determines if the Bridge Domain should learn End Point IPs.,The APIC defaults to C(yes) when unset during creation.\n attribute :ip_learning\n validates :ip_learning, type: Symbol\n\n # @return [Object, nil] The name of the IPv6 Neighbor Discovery Policy the Bridge Domain should use when overridding the default IPV6 ND Policy.\n attribute :ipv6_nd_policy\n\n # @return [:proxy, :flood, nil] Determines what forwarding method to use for unknown l2 destinations.,The APIC defaults to C(proxy) when unset during creation.\n attribute :l2_unknown_unicast\n validates :l2_unknown_unicast, expression_inclusion: {:in=>[:proxy, :flood], :message=>\"%{value} needs to be :proxy, :flood\"}, allow_nil: true\n\n # @return [:flood, :\"opt-flood\", nil] Determines the forwarding method to use for unknown multicast destinations.,The APIC defaults to C(flood) when unset during creation.\n attribute :l3_unknown_multicast\n validates :l3_unknown_multicast, expression_inclusion: {:in=>[:flood, :\"opt-flood\"], :message=>\"%{value} needs to be :flood, :\\\"opt-flood\\\"\"}, allow_nil: true\n\n # @return [Symbol, nil] Determines if the BD should limit IP learning to only subnets owned by the Bridge Domain.,The APIC defaults to C(yes) when unset during creation.\n attribute :limit_ip_learn\n validates :limit_ip_learn, type: Symbol\n\n # @return [String, nil] The MAC Address to assign to the C(bd) instead of using the default.,The APIC defaults to C(00:22:BD:F8:19:FF) when unset during creation.\n attribute :mac_address\n validates :mac_address, type: String\n\n # @return [:\"bd-flood\", :drop, :\"encap-flood\", nil] Determines the forwarding method for L2 multicast, broadcast, and link layer traffic.,The APIC defaults to C(bd-flood) when unset during creation.\n attribute :multi_dest\n validates :multi_dest, expression_inclusion: {:in=>[:\"bd-flood\", :drop, :\"encap-flood\"], :message=>\"%{value} needs to be :\\\"bd-flood\\\", :drop, :\\\"encap-flood\\\"\"}, allow_nil: true\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n\n # @return [String, nil] The name of the Tenant.\n attribute :tenant\n validates :tenant, type: String\n\n # @return [String, nil] The name of the VRF.\n attribute :vrf\n validates :vrf, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6805006861686707, "alphanum_fraction": 0.6805006861686707, "avg_line_length": 40.02702713012695, "blob_id": "f88be17cbe7d79052b8e1c4fa93eefaccf419ce9", "content_id": "55154a80b1dfc9046decb05333948f6d4d362e35", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1518, "license_type": "permissive", "max_line_length": 167, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_license.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove licenses on NetApp ONTAP.\n class Na_ontap_license < Base\n # @return [:present, :absent, nil] Whether the specified license should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Symbol, nil] Remove licenses that have no controller affiliation in the cluster.\n attribute :remove_unused\n validates :remove_unused, type: Symbol\n\n # @return [Symbol, nil] Remove licenses that have expired in the cluster.\n attribute :remove_expired\n validates :remove_expired, type: Symbol\n\n # @return [NilClass, nil] Serial number of the node associated with the license. This parameter is used primarily when removing license for a specific service.\n attribute :serial_number\n validates :serial_number, type: NilClass\n\n # @return [Array<String>, String, nil] List of license-names to delete.\n attribute :license_names\n validates :license_names, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] List of license codes to be added.\n attribute :license_codes\n validates :license_codes, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6851683259010315, "alphanum_fraction": 0.6851683259010315, "avg_line_length": 42.959999084472656, "blob_id": "e967f7c598681b449b29f326b1e7a41e446cfcea", "content_id": "fc45b0ce7b9fddf94ad0b57de823095976f442e5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1099, "license_type": "permissive", "max_line_length": 322, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/packaging/os/homebrew_tap.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Tap external Homebrew repositories.\n class Homebrew_tap < Base\n # @return [Array<String>, String] The GitHub user/organization repository to tap.\n attribute :name\n validates :name, presence: true, type: TypeGeneric.new(String)\n\n # @return [String, nil] The optional git URL of the repository to tap. The URL is not assumed to be on GitHub, and the protocol doesn't have to be HTTP. Any location and protocol that git can handle is fine.,I(name) option may not be a list of multiple taps (but a single tap instead) when this option is provided.\n attribute :url\n validates :url, type: String\n\n # @return [:present, :absent, nil] state of the repository.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7040690779685974, "alphanum_fraction": 0.7065351605415344, "avg_line_length": 37.619049072265625, "blob_id": "cbe969f16e876960f165e121b8ccd240e8176c85", "content_id": "c61233d25c202e878dc581452e1ecac4e500c537", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 811, "license_type": "permissive", "max_line_length": 239, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_vpc_peering_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gets various details related to AWS VPC Peers\n class Ec2_vpc_peering_facts < Base\n # @return [Array<String>, String, nil] Get details of specific vpc peer IDs\n attribute :peer_connection_ids\n validates :peer_connection_ids, type: TypeGeneric.new(String)\n\n # @return [Hash, nil] A dict of filters to apply. Each dict item consists of a filter key and a filter value. See U(http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeVpcPeeringConnections.html) for possible filters.\n attribute :filters\n validates :filters, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7285318374633789, "alphanum_fraction": 0.742382287979126, "avg_line_length": 19.05555534362793, "blob_id": "d6e6ad46c7f218e6c824502fa16734302fc8b876", "content_id": "1ab550ce8e68b26d0a0a692b6c8243355b073588", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 361, "license_type": "permissive", "max_line_length": 66, "num_lines": 18, "path": "/lib/ansible/ruby/modules/custom/cloud/core/amazon/ec2_ami.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# VALIDATED_CHECKSUM: RhqwUulWJitm2NvVAi5LBt2KlaAYFJGYjMdfixvzclM=\n\n# See LICENSE.txt for license\n\nrequire 'ansible/ruby/modules/generated/cloud/amazon/ec2_ami'\nrequire 'ansible/ruby/modules/helpers/aws'\n\nmodule Ansible\n module Ruby\n module Modules\n class Ec2_ami\n include Helpers::Aws\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7126984000205994, "alphanum_fraction": 0.7174603343009949, "avg_line_length": 59.967742919921875, "blob_id": "98b4c76f8da6dfe0a84d62be545f8e41db10c0fc", "content_id": "44b88decfe1d4eb6400eb514fcd28b08e1c6b141", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1890, "license_type": "permissive", "max_line_length": 456, "num_lines": 31, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/netapp_e_iscsi_target.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configure the settings of an E-Series iSCSI target\n class Netapp_e_iscsi_target < Base\n # @return [String, nil] The name/alias to assign to the iSCSI target.,This alias is often used by the initiator software in order to make an iSCSI target easier to identify.\n attribute :name\n validates :name, type: String\n\n # @return [Boolean, nil] Enable ICMP ping responses from the configured iSCSI ports.\n attribute :ping\n validates :ping, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] Enable Challenge-Handshake Authentication Protocol (CHAP), utilizing this value as the password.,When this value is specified, we will always trigger an update (changed=True). We have no way of verifying whether or not the password has changed.,The chap secret may only use ascii characters with values between 32 and 126 decimal.,The chap secret must be no less than 12 characters, but no more than 16 characters in length.\n attribute :chap_secret\n\n # @return [Boolean, nil] When an initiator initiates a discovery session to an initiator port, it is considered an unnamed discovery session if the iSCSI target iqn is not specified in the request.,This option may be disabled to increase security if desired.\n attribute :unnamed_discovery\n validates :unnamed_discovery, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] A local path (on the Ansible controller), to a file to be used for debug logging.\n attribute :log_path\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5219178199768066, "alphanum_fraction": 0.5223744511604309, "avg_line_length": 23.606740951538086, "blob_id": "b7b50ad039c04e42425723f499a14510ea01816e", "content_id": "e9f22c7cc4f5e1063b2602aa592fcc8b15e1638a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2190, "license_type": "permissive", "max_line_length": 79, "num_lines": 89, "path": "/lib/ansible/ruby/dsl_builders/tasks.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# See LICENSE.txt for license\nrequire 'ansible/ruby/dsl_builders/task'\nrequire 'ansible/ruby/models/handler'\nrequire 'ansible/ruby/models/inclusion'\n\nmodule Ansible\n module Ruby\n module DslBuilders\n class Tasks < Base\n def initialize(context)\n @context = context\n @task_builders = []\n @includes = []\n end\n\n def ansible_include(filename, &block)\n @includes << _ansible_include(filename, &block)\n end\n\n # allow multiple tasks, etc.\n def _result\n tasks = @task_builders.map(&:_result)\n Models::Tasks.new items: tasks,\n inclusions: @includes\n end\n\n class << self\n def context(context)\n contexts[context]\n end\n\n def contexts\n {\n tasks: {\n valid_methods: [:task],\n model: Models::Task\n },\n handlers: {\n valid_methods: [:handler],\n model: Models::Handler\n }\n }\n end\n end\n\n def respond_to_missing?(id, *)\n _valid_methods.include? id\n end\n\n private\n\n def _context\n self.class.context @context\n end\n\n def _valid_methods\n raise \"Unknown context #{@context}\" unless _context\n\n valid = _context[:valid_methods]\n raise \"Valid methods not configured for #{@context}!\" unless valid\n\n valid\n end\n\n def _process_method(id, *args, &block)\n valid = _valid_methods\n no_method_error id, \"Only #{valid} is valid\" unless valid.include? id\n _handle args[0], &block\n end\n\n def _handle(name, &block)\n model = _context[:model]\n raise \"Model not configured for #{@context}\" unless model\n\n task_builder = Task.new name, model\n task_builder.instance_eval(&block)\n @last_variable = task_builder._register\n @task_builders << task_builder\n end\n\n def method_missing_return(*)\n @last_variable\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6899934411048889, "alphanum_fraction": 0.6906474828720093, "avg_line_length": 51.72413635253906, "blob_id": "95cea9e7b69982f13173eabb095195ffd90dea46", "content_id": "0d5d418a8b81e2a0565b6dc55ed55ac7d19c74f0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1529, "license_type": "permissive", "max_line_length": 286, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/network/files/net_put.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides functionality to copy file from Ansible controller to network devices.\n class Net_put < Base\n # @return [String] Specifies the source file. The path to the source file can either be the full path on the Ansible control host or a relative path from the playbook or role root directory.\n attribute :src\n validates :src, presence: true, type: String\n\n # @return [:scp, :sftp, nil] Protocol used to transfer file.\n attribute :protocol\n validates :protocol, expression_inclusion: {:in=>[:scp, :sftp], :message=>\"%{value} needs to be :scp, :sftp\"}, allow_nil: true\n\n # @return [String, nil] Specifies the destination file. The path to destination file can either be the full path or relative path as supported by network_os.\n attribute :dest\n validates :dest, type: String\n\n # @return [:binary, :text, nil] Set the file transfer mode. If mode is set to I(template) then I(src) file will go through Jinja2 template engine to replace any vars if present in the src file. If mode is set to I(binary) then file will be copied as it is to destination device.\n attribute :mode\n validates :mode, expression_inclusion: {:in=>[:binary, :text], :message=>\"%{value} needs to be :binary, :text\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7579505443572998, "alphanum_fraction": 0.7579505443572998, "avg_line_length": 82.85185241699219, "blob_id": "dce318ebf546db8a729386f8042685f371ed30ad", "content_id": "4b052f5e0db05b74ff77950665ecb6e566d804c2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2264, "license_type": "permissive", "max_line_length": 447, "num_lines": 27, "path": "/lib/ansible/ruby/modules/generated/crypto/certificate_complete_chain.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module completes a given chain of certificates in PEM format by finding intermediate certificates from a given set of certificates, until it finds a root certificate in another given set of certificates.\n # This can for example be used to find the root certificate for a certificate chain returned by M(acme_certificate).\n # Note that this module does I(not) check for validity of the chains. It only checks that issuer and subject match, and that the signature is correct. It ignores validity dates and key usage completely. If you need to verify that a generated chain is valid, please use C(openssl verify ...).\n class Certificate_complete_chain < Base\n # @return [String] A concatenated set of certificates in PEM format forming a chain.,The module will try to complete this chain.\n attribute :input_chain\n validates :input_chain, presence: true, type: String\n\n # @return [Array<String>, String] A list of filenames or directories.,A filename is assumed to point to a file containing one or more certificates in PEM format. All certificates in this file will be added to the set of root certificates.,If a directory name is given, all files in the directory and its subdirectories will be scanned and tried to be parsed as concatenated certificates in PEM format.,Symbolic links will be followed.\n attribute :root_certificates\n validates :root_certificates, presence: true, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] A list of filenames or directories.,A filename is assumed to point to a file containing one or more certificates in PEM format. All certificates in this file will be added to the set of root certificates.,If a directory name is given, all files in the directory and its subdirectories will be scanned and tried to be parsed as concatenated certificates in PEM format.,Symbolic links will be followed.\n attribute :intermediate_certificates\n validates :intermediate_certificates, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7381792664527893, "alphanum_fraction": 0.7424135208129883, "avg_line_length": 66.47618865966797, "blob_id": "d63f6f0854d1830ff958d72ec63810affce5bb61", "content_id": "9faa2b8d9eafba66c33c5ad268137b55e69f4c40", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1417, "license_type": "permissive", "max_line_length": 536, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module fetches data from the metadata API in CloudStack. The module must be called from within the instance itself.\n class Cs_facts < Base\n # @return [:cloudstack_service_offering, :cloudstack_availability_zone, :cloudstack_public_hostname, :cloudstack_public_ipv4, :cloudstack_local_hostname, :cloudstack_local_ipv4, :cloudstack_instance_id, :cloudstack_user_data, nil] Filter for a specific fact.\n attribute :filter\n validates :filter, expression_inclusion: {:in=>[:cloudstack_service_offering, :cloudstack_availability_zone, :cloudstack_public_hostname, :cloudstack_public_ipv4, :cloudstack_local_hostname, :cloudstack_local_ipv4, :cloudstack_instance_id, :cloudstack_user_data], :message=>\"%{value} needs to be :cloudstack_service_offering, :cloudstack_availability_zone, :cloudstack_public_hostname, :cloudstack_public_ipv4, :cloudstack_local_hostname, :cloudstack_local_ipv4, :cloudstack_instance_id, :cloudstack_user_data\"}, allow_nil: true\n\n # @return [String, nil] Host or IP of the meta data API service.,If not set, determination by parsing the dhcp lease file.\n attribute :meta_data_host\n validates :meta_data_host, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5262107253074646, "alphanum_fraction": 0.5327267646789551, "avg_line_length": 63.04135513305664, "blob_id": "15292560925f7f86621568bcdad27f18b098e433", "content_id": "d5b663da8664a74eb886779610d6465668c3adb1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 17035, "license_type": "permissive", "max_line_length": 491, "num_lines": 266, "path": "/util/parser/yaml.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# See LICENSE.txt for license\nmodule Ansible\n module Ruby\n module Parser\n module Yaml\n class << self\n def parse(yaml_string, description, module_name = nil)\n File.write \"debug_#{description}_before.yml\", yaml_string if ENV['DEBUG']\n yaml_string = remove_line_continuation yaml_string\n yaml_string = fix_missing_hash_entry(yaml_string, module_name) if module_name\n yaml_string = remove_difficult_strings yaml_string\n File.write \"debug_#{description}_after.yml\", yaml_string if ENV['DEBUG']\n # For some reason, safe_load chokes on parsing modules\n # rubocop:disable Security/YAMLLoad\n YAML.load yaml_string\n # rubocop:enable Security/YAMLLoad\n rescue StandardError\n $stderr << \"Problem parsing #{description}!\"\n raise\n end\n\n private\n\n def remove_line_continuation(yaml)\n # code doesn't always indent these right\n yaml.gsub(/ \\\\\\n/, '')\n end\n\n def with_yaml_lines(yaml)\n yaml.split(\"\\n\").map do |line|\n yield line\n end.join \"\\n\"\n end\n\n # rubocop:disable Metrics/MethodLength\n def remove_difficult_strings(yaml)\n dirty_patterns = {\n ' azure_rm_networkinterface:' => ' azure_rm_networkinterface:',\n ' - name: Create a network interface with private IP address only (no Public IP)' => ' - name: Create a network interface with private IP address only (no Public IP)',\n \"- gc_storage: bucket=mybucket object=key.txt src=/usr/local/myfile.txt headers='{\\\"Content-Encoding\\\": \\\"gzip\\\"}'\" => \"- gc_storage: 'bucket=mybucket object=key.txt src=/usr/local/myfile.txt headers=''{\\\"Content-Encoding\\\": \\\"gzip\\\"}'''\",\n ' filters parameters are Not mutually exclusive)' => '# filters parameters are Not mutually exclusive)',\n # often before --- in YAML files but not commented out, throws off parser\n /^\\$\\s*ansible -i.*/ => '# non commented $ansible command removed',\n # often before --- in YAML files but not commented out, throws off parser\n /^\\s*ansible host.*/ => '# non commented $ansible command removed',\n # win_unzip\n 'C:\\\\Users\\\\Phil\\\\' => 'C:\\\\\\\\\\Users\\\\\\\\\\Phil\\\\\\\\\\\\',\n # win_iis_website\n /host.*^\\}/m => '# Removed invalid YAML',\n # win_acl indentation\n '- name: Remove FullControl AccessRule for IIS_IUSRS' => '- name: Remove FullControl AccessRule for IIS_IUSRS',\n # more win_acl\n '- name: Deny Deny' => '- name: Deny Deny',\n # ejabberd_user\n 'Example playbook entries using the ejabberd_user module to manage users state.' => '# Example playbook entries using the ejabberd_user module to manage users state.',\n # deploy_helper\n /General explanation, starting with an example folder structure.*The 'releases' folder.*during cleanup./m => '# text was not commented out',\n \"gluster_volume: state=present name=test1 options='{performance.cache-size: 256MB}'\" => \"gluster_volume: 'state=present name=test1 options=''{performance.cache-size: 256MB}'''\",\n # postgresql_user\n /\"When passing an encrypted password.*/ => 'When passing an encrypted password, the encrypted parameter must also be true, and it must be generated with the format in the Ansible docs',\n 'INSERT,UPDATE/table:SELECT/anothertable:ALL' => '- postgresql_user: priv=INSERT,UPDATE/table:SELECT/anothertable:ALL',\n # get_ent\n '- getent: database=shadow key=www-data split=:' => \"- getent: 'database=shadow key=www-data split=:'\",\n # crypttab\n \"when: '/dev/mapper/luks-' in {{ item.device }}\" => \"when: \\\"'/dev/mapper/luks-' in {{ item.device }}\\\"\",\n # npm\n /^description: .*package.*/ => '# npm description removed',\n # bower\n 'description: install bower locally and run from there' => '',\n # pushover\n /has exploded in flames,.*baa5fe97f2c5ab3ca8f0bb59/m => 'has exploded in flames, It is now time to panic\" app_token=wxfdksl user_key=baa5fe97f2c5ab3ca8f0bb59',\n # ha_proxy, invalid YAML hash with array\n 'author: \"Ravi Bhure (@ravibhure)\"' => '# author: \"Ravi Bhure (@ravibhure)\"',\n # dnsimple, missing colon\n '- local_action dnsimple' => '- local_action: dnsimple',\n # zabbix_hostmacro\n 'macro_name:Example macro' => 'macro_name: Example macro',\n 'macro_value:Example value' => 'macro_value: Example value',\n # pagerduty\n /- pagerduty_alert:\\n\\s+name: companyabc/ => \"- pagerduty_alert:\\n name=companyabc\",\n # datalog - not escaped properly\n 'query: \"datadog.agent.up\".over(\"host:host1\").last(2).count_by_status()\"' => 'query: \"datadog.agent.up\"',\n # influxdb_retention_policy - indentation\n ' influxdb_retention_policy:' => ' influxdb_retention_policy:',\n # influxdb_database - more indentation\n ' influxdb_database:' => ' influxdb_database:',\n # xenserver_facts - indentation, bad commenting\n ' xenserver:' => ' xenserver:',\n /TASK: \\[Print.*/m => '# commented out',\n # vmware_vswitch\n /^Example from Ansible playbook$/ => '# Example from Ansible playbook',\n # vmware_target_canonical_facts - indentation\n /- name: Get Canonical name.*local_action: \\>/m => \"- name: Get Canonical name\\n local_action: >\",\n # vmware_dvs_portgroup\n /name: Create Management portgroup.*local_action:/m => \"name: Create Management portgroup\\n local_action:\",\n # vmware_datacenter - indentation\n /- name: Create Datacenter.*local_action: \\>/m => \"- name: Create Datacenter\\n local_action: >\",\n # vmware_cluster - indentation\n /- name: Create Cluster.*local_action: \\>/m => \"- name: Create Cluster\\n local_action: >\",\n # vca_vapp\n 'vapp_name: tower' => 'vapp_name=tower',\n # os_user_facts and os_project_facts - dangling comment\n /# Gather facts about a previously created (user|project).*with filter/m => '# Gather facts about a previously created \\1 in a specific domain with filter',\n # virt - mixing hash and array\n '- virt: name=alpha state=running' => '',\n # cs_configuration, extra colon\n ' module: cs_configuration:' => ' module: cs_configuration',\n # clc_blueprint_package, indentation\n ' clc_blueprint_package:' => ' clc_blueprint_package:',\n # ops template, indentation\n ' ops_template:' => ' ops_template:',\n # junos_template\n /- name: replace config hierarchy\\n\\s+src: config.j2/ => \"- name: replace config hierarchy\\n src: config.j2\",\n /- name: overwrite the config\\n\\s+src: config.j2/ => \"- name: overwrite the config\\n src: config.j2\",\n # cl_interface_policy - incorrect comment\n /^Example playbook entries using the cl_interface_policy module\\.$/ => '# Example playbook entries using the cl_interface_policy module.',\n # synchronize - not commented\n /# Example .rsync-filter file in the source directory.*previously excluded/m => '# commented',\n # mysql_user - usage not commented properly\n 'mydb.*:INSERT,UPDATE/anotherdb.*:SELECT/yetanotherdb.*:ALL' => '- mysql_user: priv=mydb.*:INSERT,UPDATE/anotherdb.*:SELECT/yetanotherdb.*:ALL',\n /\\[client\\].*password=.*y/m => '# Commented out config file',\n # Vsphere guest, complex, pick 1 example\n /(- vsphere_guest:.*?)^-.*/m => '\\1',\n # os_server, complex, pick 1 example\n /(- os_server:.*?)^-.*/m => '\\1',\n # ec2_asg - bad comments\n /^# Rolling ASG Updates.*?launch configuration\\.$/m => '# comments',\n /^To only replace a couple of instances.*replace_instances\":/m => '# comments',\n # rollbar_deployment - trailing commas\n 'revision=4.2,' => 'revision=4.2',\n \"rollbar_user='admin',\" => \"rollbar_user='admin'\",\n # Synchronize - non parseable defaults\n 'default: Value of ansible_ssh_port for this host, remote_port config setting, or 22 if none of those are set' => 'default: 22',\n # rds - non parseable defaults\n 'default: 3306 for mysql, 1521 for Oracle, 1433 for SQL Server, 5432 for PostgreSQL.' => 'default: 5432',\n # datadog_monitor\n 'default: 2x timeframe for metric, 2 minutes for service' => 'default: 2',\n # bad spacing\n ' docker_image:' => ' docker_image:',\n # bad spacing\n ' dellos10_command:' => ' dellos10_command:',\n # forgot : on key\n 'provider \"{{ cli }}\"' => 'provider: \"{{ cli }}\"',\n # Forgot 'tasks' list\n /(?<=transport: cli).*?- name: run show version on remote devices.*?eos_command/m => \"\\ntasks:\\n- name: run show version on remote devices\\n eos_command\",\n # Spacing problem\n ' eos_command:' => ' eos_command:',\n ' sros_config:' => ' sros_config:',\n ' sros_command:' => ' sros_command:',\n # Vars/hash\n /vars:.*?- eos_config:/m => '- eos_config:',\n /vars:.*?- eos_facts:/m => '- eos_facts:',\n /vars:.*?- ios_facts:/m => '- ios_facts:',\n /vars:.*?- asa_config:/m => '- asa_config:',\n /vars:.*?- asa_command:/m => '- asa_command:',\n /vars:.*?- vyos_command:/m => '- vyos_command:',\n /vars:.*?- ops_command:/m => '- ops_command:',\n /vars:.*?- ops_facts:/m => '- ops_facts:',\n /vars:.*?- nxos_facts:/m => '- nxos_facts:',\n /vars:.*?- asa_acl:/m => '- asa_acl:',\n /vars:.*? eos_eapi:/m => \"- name: foo\\n eos_eapi:\",\n /vars:.*? ios_config:/m => \"- name: foo\\n ios_config:\",\n ' ios_command:' => ' ios_command:',\n ' iosxr_command:' => ' iosxr_command:',\n /vars:.*? iosxr_config:/m => \"- name: foo\\n iosxr_config:\",\n /vars:.*? junos_command:/m => \"- name: foo\\n junos_command:\",\n /vars:.*? junos_config:/m => \"- name: foo\\n junos_config:\",\n /vars:.*? junos_netconf:/m => \"- name: foo\\n junos_netconf:\",\n 'configure RR client' => '# configure RR client',\n /vars:.*? nxos_command:/m => \"- name: foo\\n nxos_command:\",\n ' nxos_command:' => ' nxos_command:',\n /vars:.*? nxos_config:/m => \"- name: foo\\n nxos_config:\",\n /vars:.*? vyos_facts:/m => \"- name: foo\\n vyos_facts:\",\n /vars:.*? vyos_config:/m => \"- name: foo\\n vyos_config:\",\n /vars:.*? sros_rollback:/m => \"- name: foo\\n sros_rollback:\",\n /vars:.*? sros_config:/m => \"- name: foo\\n sros_config:\",\n /vars:.*? ops_config:/m => \"- name: foo\\n ops_config:\",\n /vars:.*? nxos_nxapi:/m => \"- name: foo\\n nxos_nxapi:\",\n # quotes not closed\n 'src: \"C:\\\\\\\\DirectoryOne' => 'src: \"C:/DirectoryOne\"',\n # Not labeled correctly and not formatted right\n /# Create a DNS record on a UCS.*- udm_dns_zone:.*/m => \"- udm_dns_record:\\n name: www\\n zone: example.com\\n type: host_record\\n data: ['a': '192.0.2.1']\",\n 'api_url: \"{{ netapp_api_url }}\"/' => 'api_url: \"{{ netapp_api_url }}\"',\n # unquoted comment\n 'send a message to chat in playbook' => '# send a message to chat in playbook',\n # Incorrect YAML escaping in F5 example, this will result in strings anyways\n 'host: \"{{ ansible_default_ipv4[\"address\"] }}\"' => 'host: a string',\n ' context: customer_a' => ' context: customer_a',\n 'automation to stop the maintenance.' => '# automation to stop the maintenance.',\n # Lack of closing quotes\n '- \"server1.example.com' => '- \"server1.example.com\"',\n # markdown in the middle of the YAML example\n /^```/ => '',\n # this doesn't help much with how we're using this\n ' ---' => '',\n # unescaped colon\n 'Obtain SSO token with using username/password credentials:' => 'Obtain SSO token with using username/password credentials',\n # tasks/block interference\n /tasks:.*- block:/m => '',\n # Quotes left open\n /cluster: \"centos$/ => 'cluster: \"centos\"',\n # Invalig YAML\n /# Create a Redshift.*/m => '',\n # Example turns into JSON for some reason in cloudformation_facts\n /\"stack_outputs\": {.*/m => '',\n # unescaped command\n /ansible winhost.*/ => '# ansible winhost...',\n # unmatched quotes\n /'{{roleinput\\d}}\"/ => '\"{{roleinput2222}}\"',\n # not quoted properly\n '- include: {{hostvar}}.yml' => '- include: \"{{hostvar}}.yml\"',\n 'src: {{ inventory_hostname }}.cfg' => 'src: \"{{ inventory_hostname }}.cfg\"',\n # = should be colon in nxos_interface_ospf\n ' cost=default' => ' cost: default',\n # block\n /- block:.*name: Install OS/m => \"tasks:\\n - name: Install OS\",\n /transport: nxapi.*rescue.*/m => 'transport: nxapi',\n # win_acl spacing\n '- name: Remove FullControl AccessRule for IIS_IUSRS' => '- name: Remove FullControl AccessRule for IIS_IUSRS',\n '- name: Deny Deny' => '- name: Deny Deny',\n \"msg: '{{ inventory_hostname }} has exploded in flames, It is now time to panic\\\" app_token=wxfdksl user_key=baa5fe97f2c5ab3ca8f0bb59\" =>\n \"msg: '{{ inventory_hostname }} has exploded in flames, It is now time to panic'\\n app_token: wxfdksl\\n user_key: baa5fe97f2c5ab3ca8f0bb59\",\n # avi/avi_sslkeyandcertificate.py\n /key: \\|.*--END PRIVATE KEY-----/m => 'key: foo',\n /certificate: \\|.*--END CERTIFICATE-----/m => 'certificate: foo',\n # pagerduty\n ' name=companyabc' => ' name: companyabc',\n # vca_vapp\n 'vapp_name=tower' => 'vapp_name: tower',\n # gcp_compute_ssl_certificate\n /gcp_compute_ssl_certificate:.*state: present/m => \"gcp_compute_ssl_certificate:\\n name: \\\"test_object\\\"\\n description: A certificate for testing. Do not use this certificate in production\\n certificate: somecert\\n private_key: somekey\\n project: \\\"test_project\\\"\\n auth_kind: \\\"service_account\\\"\\n service_account_file: \\\"/tmp/auth.pem\\\"\\n state: present\",\n # pubnub_blocks\n '- \"User\\\\\\'s account will be used if value not set or empty.\"' => '- \"user account\"',\n 'admin.pubnub.com. Used only if block doesn\\\\\\'t exists and won\\\\\\'t change' => 'admin.pubnub.com',\n # avi_cloudconnectoruser\n /private_key:.*?BEGIN RSA PRIVATE KEY.*?END RSA PRIVATE KEY-----'/m => 'private_key: foo',\n # win_scheduled_task_stat.py\n 'default: name:' => \"default: foobar\\n name:\",\n # win_scheduled_task\n 'default: state:' => \"default: foobar\\n state:\",\n # java_keystore\n /private_key:.*?BEGIN RSA PRIVATE KEY.*?END RSA PRIVATE KEY-----/m => 'private_key: foo',\n # manageiq_provider\n /certificate_authority:.*?BEGIN CERTIFICATE.*?END CERTIFICATE-----/m => 'certificate_authority: cagoeshere'\n }\n dirty_patterns.inject(yaml) do |fixed_yaml, find_replace|\n fixed_yaml.gsub find_replace[0], find_replace[1]\n end\n end\n\n # rubocop:enable Metrics/MethodLength\n\n def fix_missing_hash_entry(yaml, module_name)\n # fix - svc : issues\n correct_usage = \"- #{module_name}:\"\n yaml = yaml.gsub \"- #{module_name} :\", correct_usage\n # missing colon entirely\n yaml.gsub(/- #{module_name}(?!\\:)/, correct_usage)\n end\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6746341586112976, "alphanum_fraction": 0.6746341586112976, "avg_line_length": 49, "blob_id": "5c4dd17ee1b232e43113f6b13c57f8a4699e73a8", "content_id": "69f56b3369171b497d39775fb6da07b25f97e4be", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2050, "license_type": "permissive", "max_line_length": 197, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/packaging/os/apt_repository.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove an APT repositories in Ubuntu and Debian.\n class Apt_repository < Base\n # @return [String] A source string for the repository.\n attribute :repo\n validates :repo, presence: true, type: String\n\n # @return [:absent, :present, nil] A source string state.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] The octal mode for newly created files in sources.list.d\n attribute :mode\n validates :mode, type: String\n\n # @return [:yes, :no, nil] Run the equivalent of C(apt-get update) when a change occurs. Cache updates are run after making changes.\n attribute :update_cache\n validates :update_cache, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), SSL certificates for the target repo will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Sets the name of the source list file in sources.list.d. Defaults to a file name based on the repository source url. The .list extension will be automatically added.\n attribute :filename\n validates :filename, type: String\n\n # @return [String, nil] Override the distribution codename to use for PPA repositories. Should usually only be set when working with a PPA on a non-Ubuntu target (e.g. Debian or Mint)\n attribute :codename\n validates :codename, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7023890614509583, "alphanum_fraction": 0.7044368386268616, "avg_line_length": 51.32143020629883, "blob_id": "3d15bb44c90071e0513f4f45c370742b401acfbb", "content_id": "138f9067d5bea302354f8438f90e9c11667261c5", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1465, "license_type": "permissive", "max_line_length": 246, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_remote_syslog.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manipulate remote syslog settings on a BIG-IP.\n class Bigip_remote_syslog < Base\n # @return [String] Specifies the IP address, or hostname, for the remote system to which the system sends log messages.\n attribute :remote_host\n validates :remote_host, presence: true, type: String\n\n # @return [Integer, nil] Specifies the port that the system uses to send messages to the remote logging server. When creating a remote syslog, if this parameter is not specified, the default value C(514) is used.\n attribute :remote_port\n validates :remote_port, type: Integer\n\n # @return [Object, nil] Specifies the local IP address of the system that is logging. To provide no local IP, specify the value C(none). When creating a remote syslog, if this parameter is not specified, the default value C(none) is used.\n attribute :local_ip\n\n # @return [:absent, :present, nil] When C(present), guarantees that the remote syslog exists with the provided attributes.,When C(absent), removes the remote syslog from the system.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6738805770874023, "alphanum_fraction": 0.6738805770874023, "avg_line_length": 39.60606002807617, "blob_id": "641d400c397530e51cd009a06a26323d2a04872d", "content_id": "3fb339633c866291a19caa06ab5b85fd23340239", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1340, "license_type": "permissive", "max_line_length": 143, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_affinity_labels.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module manage affinity labels in oVirt/RHV. It can also manage assignments of those labels to hosts and VMs.\n class Ovirt_affinity_label < Base\n # @return [String] Name of the affinity label to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Should the affinity label be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Name of the cluster where vms and hosts resides.\n attribute :cluster\n validates :cluster, type: String\n\n # @return [Array<String>, String, nil] List of the VMs names, which should have assigned this affinity label.\n attribute :vms\n validates :vms, type: TypeGeneric.new(String, NilClass)\n\n # @return [Array<String>, String, nil] List of the hosts names, which should have assigned this affinity label.\n attribute :hosts\n validates :hosts, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7112135291099548, "alphanum_fraction": 0.7147977352142334, "avg_line_length": 66.3448257446289, "blob_id": "0aab8ccc425dcdd23b65f2039d269da593dd1df7", "content_id": "149ff0fa68d3db578b8c280430a7a923529b5975", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1953, "license_type": "permissive", "max_line_length": 455, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_device_license.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage license installation and activation on a BIG-IP.\n class Bigip_device_license < Base\n # @return [String, nil] The registration key to use to license the BIG-IP.,This parameter is required if the C(state) is equal to C(present).,This parameter is not required when C(state) is C(absent) and will be ignored if it is provided.\n attribute :license_key\n validates :license_key, type: String\n\n # @return [String, nil] The F5 license server to use when getting a license and validating a dossier.,This parameter is required if the C(state) is equal to C(present).,This parameter is not required when C(state) is C(absent) and will be ignored if it is provided.\n attribute :license_server\n validates :license_server, type: String\n\n # @return [:absent, :present, nil] The state of the license on the system.,When C(present), only guarantees that a license is there.,When C(latest), ensures that the license is always valid.,When C(absent), removes the license on the system.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [Symbol, nil] Declares whether you accept the BIG-IP EULA or not. By default, this value is C(no). You must specifically declare that you have viewed and accepted the license. This module will not present you with that EULA though, so it is incumbent on you to read it.,The EULA can be found here; https://support.f5.com/csp/article/K12902.,This parameter is not required when C(state) is C(absent) and will be ignored if it is provided.\n attribute :accept_eula\n validates :accept_eula, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7009826898574829, "alphanum_fraction": 0.7056621313095093, "avg_line_length": 56.75675582885742, "blob_id": "7ceef4339a01008a168d6a77f83f808e389e1ee8", "content_id": "e56ee78a6c2d1550e31723e2a477d2051432a3e7", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2137, "license_type": "permissive", "max_line_length": 269, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/windows/win_say.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Uses .NET libraries to convert text to speech and optionally play .wav sounds. Audio Service needs to be running and some kind of speakers or headphones need to be attached to the windows target(s) for the speech to be audible.\n class Win_say < Base\n # @return [Array<String>, String, nil] The text to be spoken.,Use either C(msg) or C(msg_file).,Optional so that you can use this module just to play sounds.\n attribute :msg\n validates :msg, type: TypeGeneric.new(String)\n\n # @return [String, nil] Full path to a windows format text file containing the text to be spokend.,Use either C(msg) or C(msg_file).,Optional so that you can use this module just to play sounds.\n attribute :msg_file\n validates :msg_file, type: String\n\n # @return [String, nil] Which voice to use. See notes for how to discover installed voices.,If the requested voice is not available the default voice will be used. Example voice names from Windows 10 are C(Microsoft Zira Desktop) and C(Microsoft Hazel Desktop).\n attribute :voice\n validates :voice, type: String\n\n # @return [Integer, nil] How fast or slow to speak the text.,Must be an integer value in the range -10 to 10.,-10 is slowest, 10 is fastest.\n attribute :speech_speed\n validates :speech_speed, type: Integer\n\n # @return [String, nil] Full path to a C(.wav) file containing a sound to play before the text is spoken.,Useful on conference calls to alert other speakers that ansible has something to say.\n attribute :start_sound_path\n validates :start_sound_path, type: String\n\n # @return [String, nil] Full path to a C(.wav) file containing a sound to play after the text has been spoken.,Useful on conference calls to alert other speakers that ansible has finished speaking.\n attribute :end_sound_path\n validates :end_sound_path, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6899175643920898, "alphanum_fraction": 0.6899175643920898, "avg_line_length": 42.80555725097656, "blob_id": "8b8b22792db6e719e189eea3aefc13cc124441b4", "content_id": "08fba7188c2e6eb0030be5ca983b8be30640387a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1577, "license_type": "permissive", "max_line_length": 156, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/commands/script.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The C(script) module takes the script name followed by a list of space-delimited arguments.\n # The local script at path will be transferred to the remote node and then executed.\n # The given script will be processed through the shell environment on the remote node.\n # This module does not require python on the remote system, much like the M(raw) module.\n # This module is also supported for Windows targets.\n class Script < Base\n # @return [Object] Path to the local script file followed by optional arguments.,There is no parameter actually named 'free form', see the examples!\n attribute :free_form\n validates :free_form, presence: true\n\n # @return [String, nil] A filename on the remote node, when it already exists, this step will B(not) be run.\n attribute :creates\n validates :creates, type: String\n\n # @return [String, nil] A filename on the remote node, when it does not exist, this step will B(not) be run.\n attribute :removes\n validates :removes, type: String\n\n # @return [Object, nil] Change into this directory on the remote node before running the script.\n attribute :chdir\n\n # @return [String, nil] Name or path of a executable to invoke the script with.\n attribute :executable\n validates :executable, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6680923700332642, "alphanum_fraction": 0.6680923700332642, "avg_line_length": 34.42424392700195, "blob_id": "8133f9da47479aece64db8c0836d5ba850cb2b22", "content_id": "edecd646f6935ee7362cbbee4918e15707473707", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1169, "license_type": "permissive", "max_line_length": 110, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_dnsrecordset_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Get facts for a specific DNS Record Set in a Zone, or a specific type in all Zones or in one Zone etc.\n class Azure_rm_dnsrecordset_facts < Base\n # @return [String, nil] Only show results for a Record Set.\n attribute :relative_name\n validates :relative_name, type: String\n\n # @return [String, nil] Limit results by resource group. Required when filtering by name or type.\n attribute :resource_group\n validates :resource_group, type: String\n\n # @return [String, nil] Limit results by zones. Required when filtering by name or type.\n attribute :zone_name\n validates :zone_name, type: String\n\n # @return [String, nil] Limit record sets by record type.\n attribute :record_type\n validates :record_type, type: String\n\n # @return [Integer, nil] Limit the maximum number of record sets to return\n attribute :top\n validates :top, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6943065524101257, "alphanum_fraction": 0.6947445273399353, "avg_line_length": 62.425926208496094, "blob_id": "80f1844df6b3cb46071b9d769802ba29c4c97c06", "content_id": "d958d59237946e534c5ef6e2e01d261c9804eb78", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6850, "license_type": "permissive", "max_line_length": 666, "num_lines": 108, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_virtualmachine_scaleset.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create and update a virtual machine scale set.\n class Azure_rm_virtualmachine_scaleset < Base\n # @return [String] Name of the resource group containing the virtual machine scale set.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] Name of the virtual machine.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, nil] Assert the state of the virtual machine scale set.,State 'present' will check that the machine exists with the requested configuration. If the configuration of the existing machine does not match, the machine will be updated. state.,State 'absent' will remove the virtual machine scale set.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [Object, nil] Valid Azure location. Defaults to location of the resource group.\n attribute :location\n\n # @return [Object, nil] Short host name\n attribute :short_hostname\n\n # @return [String] A valid Azure VM size value. For example, 'Standard_D4'. The list of choices varies depending on the subscription and location. Check your subscription for available choices.\n attribute :vm_size\n validates :vm_size, presence: true, type: String\n\n # @return [Integer] Capacity of VMSS.\n attribute :capacity\n validates :capacity, presence: true, type: Integer\n\n # @return [:Basic, :Standard, nil] SKU Tier.\n attribute :tier\n validates :tier, expression_inclusion: {:in=>[:Basic, :Standard], :message=>\"%{value} needs to be :Basic, :Standard\"}, allow_nil: true\n\n # @return [:Manual, :Automatic, nil] Upgrade policy.\n attribute :upgrade_policy\n validates :upgrade_policy, expression_inclusion: {:in=>[:Manual, :Automatic], :message=>\"%{value} needs to be :Manual, :Automatic\"}, allow_nil: true\n\n # @return [String, nil] Admin username used to access the host after it is created. Required when creating a VM.\n attribute :admin_username\n validates :admin_username, type: String\n\n # @return [String, nil] Password for the admin username. Not required if the os_type is Linux and SSH password authentication is disabled by setting ssh_password_enabled to false.\n attribute :admin_password\n validates :admin_password, type: String\n\n # @return [Boolean, nil] When the os_type is Linux, setting ssh_password_enabled to false will disable SSH password authentication and require use of SSH keys.\n attribute :ssh_password_enabled\n validates :ssh_password_enabled, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash, nil] For os_type Linux provide a list of SSH keys. Each item in the list should be a dictionary where the dictionary contains two keys: path and key_data. Set the path to the default location of the authorized_keys files. On an Enterprise Linux host, for example, the path will be /home/<admin username>/.ssh/authorized_keys. Set key_data to the actual value of the public key.\n attribute :ssh_public_keys\n validates :ssh_public_keys, type: TypeGeneric.new(Hash)\n\n # @return [Hash, String] Specifies the image used to build the VM.,If a string, the image is sourced from a custom image based on the name.,If a dict with the keys C(publisher), C(offer), C(sku), and C(version), the image is sourced from a Marketplace image. NOTE: set image.version to C(latest) to get the most recent version of a given image.,If a dict with the keys C(name) and C(resource_group), the image is sourced from a custom image based on the C(name) and C(resource_group) set. NOTE: the key C(resource_group) is optional and if omitted, all images in the subscription will be searched for by C(name).,Custom image support was added in Ansible 2.5\n attribute :image\n validates :image, presence: true, type: MultipleTypes.new(Hash, String)\n\n # @return [:ReadOnly, :ReadWrite, nil] Type of OS disk caching.\n attribute :os_disk_caching\n validates :os_disk_caching, expression_inclusion: {:in=>[:ReadOnly, :ReadWrite], :message=>\"%{value} needs to be :ReadOnly, :ReadWrite\"}, allow_nil: true\n\n # @return [:Windows, :Linux, nil] Base type of operating system.\n attribute :os_type\n validates :os_type, expression_inclusion: {:in=>[:Windows, :Linux], :message=>\"%{value} needs to be :Windows, :Linux\"}, allow_nil: true\n\n # @return [:Standard_LRS, :Premium_LRS, nil] Managed disk type.\n attribute :managed_disk_type\n validates :managed_disk_type, expression_inclusion: {:in=>[:Standard_LRS, :Premium_LRS], :message=>\"%{value} needs to be :Standard_LRS, :Premium_LRS\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash, nil] Describes list of data disks.\n attribute :data_disks\n validates :data_disks, type: TypeGeneric.new(Hash)\n\n # @return [Object, nil] When creating a virtual machine, if a specific virtual network from another resource group should be used, use this parameter to specify the resource group to use.\n attribute :virtual_network_resource_group\n\n # @return [String, nil] Virtual Network name.\n attribute :virtual_network_name\n validates :virtual_network_name, type: String\n\n # @return [String, nil] Subnet name.\n attribute :subnet_name\n validates :subnet_name, type: String\n\n # @return [Object, nil] Load balancer name.\n attribute :load_balancer\n\n # @return [String, nil] When removing a VM using state 'absent', also remove associated resources.,It can be 'all' or a list with any of the following: ['network_interfaces', 'virtual_storage', 'public_ips'].,Any other input will be ignored.\n attribute :remove_on_absent\n validates :remove_on_absent, type: String\n\n # @return [Symbol, nil] Indicates whether user wants to allow accelerated networking for virtual machines in scaleset being created.\n attribute :enable_accelerated_networking\n validates :enable_accelerated_networking, type: Symbol\n\n # @return [Object, nil] Existing security group with which to associate the subnet.,It can be the security group name which is in the same resource group.,It can be the resource Id.,It can be a dict which contains C(name) and C(resource_group) of the security group.\n attribute :security_group\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7064873576164246, "alphanum_fraction": 0.7064873576164246, "avg_line_length": 42.58620834350586, "blob_id": "b09de362dcd08c4f0bd97d11b1bdc875aaeff348", "content_id": "7f94fdcf60c43923bf19f64b9ccdb1bfedafd9c0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1264, "license_type": "permissive", "max_line_length": 390, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/network/aos/aos_login.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Obtain the AOS server session token by providing the required username and password credentials. Upon successful authentication, this module will return the session-token that is required by all subsequent AOS module usage. On success the module will automatically populate ansible facts with the variable I(aos_session) This module is not idempotent and do not support check mode.\n class Aos_login < Base\n # @return [String] Address of the AOS Server on which you want to open a connection.\n attribute :server\n validates :server, presence: true, type: String\n\n # @return [Integer, nil] Port number to use when connecting to the AOS server.\n attribute :port\n validates :port, type: Integer\n\n # @return [String, nil] Login username to use when connecting to the AOS server.\n attribute :user\n validates :user, type: String\n\n # @return [String, nil] Password to use when connecting to the AOS server.\n attribute :passwd\n validates :passwd, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6623424291610718, "alphanum_fraction": 0.6632559895515442, "avg_line_length": 44.23140335083008, "blob_id": "f8267fc1a54189fbdae712c7a6dd2bb4c31363b8", "content_id": "fa4562e3da991c6d077c2f58ff9cbf261f1c3bf3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5473, "license_type": "permissive", "max_line_length": 259, "num_lines": 121, "path": "/lib/ansible/ruby/modules/generated/cloud/misc/proxmox.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # allows you to create/delete/stop instances in Proxmox VE cluster\n # Starting in Ansible 2.1, it automatically detects containerization type (lxc for PVE 4, openvz for older)\n class Proxmox < Base\n # @return [String] the host of the Proxmox VE cluster\n attribute :api_host\n validates :api_host, presence: true, type: String\n\n # @return [String] the user to authenticate with\n attribute :api_user\n validates :api_user, presence: true, type: String\n\n # @return [String, nil] the password to authenticate with,you can use PROXMOX_PASSWORD environment variable\n attribute :api_password\n validates :api_password, type: String\n\n # @return [Integer, nil] the instance id,if not set, the next available VM ID will be fetched from ProxmoxAPI.,if not set, will be fetched from PromoxAPI based on the hostname\n attribute :vmid\n validates :vmid, type: Integer\n\n # @return [:yes, :no, nil] enable / disable https certificate verification\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Proxmox VE node, when new VM will be created,required only for C(state=present),for another states will be autodiscovered\n attribute :node\n validates :node, type: String\n\n # @return [Object, nil] Proxmox VE resource pool\n attribute :pool\n\n # @return [Integer, String, nil] the instance root password,required only for C(state=present)\n attribute :password\n validates :password, type: MultipleTypes.new(Integer, String)\n\n # @return [String, nil] the instance hostname,required only for C(state=present),must be unique if vmid is not passed\n attribute :hostname\n validates :hostname, type: String\n\n # @return [String, nil] the template for VM creating,required only for C(state=present)\n attribute :ostemplate\n validates :ostemplate, type: String\n\n # @return [Integer, nil] hard disk size in GB for instance\n attribute :disk\n validates :disk, type: Integer\n\n # @return [Integer, nil] Specify number of cores per socket.\n attribute :cores\n validates :cores, type: Integer\n\n # @return [Integer, nil] numbers of allocated cpus for instance\n attribute :cpus\n validates :cpus, type: Integer\n\n # @return [Integer, nil] memory size in MB for instance\n attribute :memory\n validates :memory, type: Integer\n\n # @return [Integer, nil] swap memory size in MB for instance\n attribute :swap\n validates :swap, type: Integer\n\n # @return [Hash, nil] specifies network interfaces for the container. As a hash/dictionary defining interfaces.\n attribute :netif\n validates :netif, type: Hash\n\n # @return [Hash, nil] specifies additional mounts (separate disks) for the container. As a hash/dictionary defining mount points\n attribute :mounts\n validates :mounts, type: Hash\n\n # @return [Object, nil] specifies the address the container will be assigned\n attribute :ip_address\n\n # @return [:yes, :no, nil] specifies whether a VM will be started during system bootup\n attribute :onboot\n validates :onboot, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] target storage\n attribute :storage\n validates :storage, type: String\n\n # @return [Integer, nil] CPU weight for a VM\n attribute :cpuunits\n validates :cpuunits, type: Integer\n\n # @return [Object, nil] sets DNS server IP address for a container\n attribute :nameserver\n\n # @return [Object, nil] sets DNS search domain for a container\n attribute :searchdomain\n\n # @return [Integer, nil] timeout for operations\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [:yes, :no, nil] forcing operations,can be used only with states C(present), C(stopped), C(restarted),with C(state=present) force option allow to overwrite existing container,with states C(stopped) , C(restarted) allow to force stop instance\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :started, :absent, :stopped, :restarted, nil] Indicate desired state of the instance\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :started, :absent, :stopped, :restarted], :message=>\"%{value} needs to be :present, :started, :absent, :stopped, :restarted\"}, allow_nil: true\n\n # @return [Object, nil] Public key to add to /root/.ssh/authorized_keys. This was added on Proxmox 4.2, it is ignored for earlier versions\n attribute :pubkey\n\n # @return [:yes, :no, nil] Indicate if the container should be unprivileged\n attribute :unprivileged\n validates :unprivileged, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6573489904403687, "alphanum_fraction": 0.6609557867050171, "avg_line_length": 37.24137878417969, "blob_id": "619acbb152b623e05c0ff92e0277817ea4ebf456", "content_id": "c6980ec72f7873ed09c475b77f34c8cebdc615ca", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1109, "license_type": "permissive", "max_line_length": 143, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/windows/win_route.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove a static route.\n class Win_route < Base\n # @return [String] Destination IP address in CIDR format (ip address/prefix length)\n attribute :destination\n validates :destination, presence: true, type: String\n\n # @return [String, nil] The gateway used by the static route.,If C(gateway) is not provided it will be set to C(0.0.0.0).\n attribute :gateway\n validates :gateway, type: String\n\n # @return [Integer, nil] Metric used by the static route.\n attribute :metric\n validates :metric, type: Integer\n\n # @return [:absent, :present, nil] If C(absent), it removes a network static route.,If C(present), it adds a network static route.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.686165988445282, "alphanum_fraction": 0.686165988445282, "avg_line_length": 51.70833206176758, "blob_id": "8bfcbce2b0a229eb7a98ddf8bd6a511f07073d7b", "content_id": "0920407f3379a324c2937ced125ff01b8635231a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2530, "license_type": "permissive", "max_line_length": 279, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/cloud/misc/serverless.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Provides support for managing Serverless Framework (https://serverless.com/) project deployments and stacks.\n class Serverless < Base\n # @return [:present, :absent, nil] Goal state of given stage/project\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] The path of a serverless framework binary relative to the 'service_path' eg. node_module/.bin/serverless\n attribute :serverless_bin_path\n validates :serverless_bin_path, type: String\n\n # @return [String] The path to the root of the Serverless Service to be operated on.\n attribute :service_path\n validates :service_path, presence: true, type: String\n\n # @return [String, nil] The name of the serverless framework project stage to deploy to. This uses the serverless framework default \"dev\".\n attribute :stage\n validates :stage, type: String\n\n # @return [Object, nil] A list of specific functions to deploy. If this is not provided, all functions in the service will be deployed.\n attribute :functions\n\n # @return [String, nil] AWS region to deploy the service to\n attribute :region\n validates :region, type: String\n\n # @return [Boolean, nil] Whether or not to deploy artifacts after building them. When this option is `false` all the functions will be built, but no stack update will be run to send them out. This is mostly useful for generating artifacts to be stored/deployed elsewhere.\n attribute :deploy\n validates :deploy, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Whether or not to force full deployment, equivalent to serverless `--force` option.\n attribute :force\n validates :force, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Shows all stack events during deployment, and display any Stack Output.\n attribute :verbose\n validates :verbose, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6711635589599609, "alphanum_fraction": 0.6711635589599609, "avg_line_length": 27.238094329833984, "blob_id": "d06d2f44145637c2d8778b305bf4172a779d1341", "content_id": "7f597dbf79e9f78c51d39d9ef62debb8ceeabf47", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 593, "license_type": "permissive", "max_line_length": 78, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/net_tools/ipinfoio_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gather IP geolocation facts of a host's IP address using ipinfo.io API\n class Ipinfoio_facts < Base\n # @return [Integer, nil] HTTP connection timeout in seconds\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [String, nil] Set http user agent\n attribute :http_agent\n validates :http_agent, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6582964062690735, "alphanum_fraction": 0.66863614320755, "avg_line_length": 46.23255920410156, "blob_id": "2685929394fd4d1c1a40b53a53fc93e422258792", "content_id": "673b707f0681917f8cdd526f4ad5402793364bc7", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2031, "license_type": "permissive", "max_line_length": 162, "num_lines": 43, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_netstream_global.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages global parameters of NetStream on HUAWEI CloudEngine switches.\n class Ce_netstream_global < Base\n # @return [:ip, :vxlan, nil] Specifies the type of netstream global.\n attribute :type\n validates :type, expression_inclusion: {:in=>[:ip, :vxlan], :message=>\"%{value} needs to be :ip, :vxlan\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Specify desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object] Netstream global interface.\n attribute :interface\n validates :interface, presence: true\n\n # @return [Object, nil] Specifies the netstream sampler interval, length is 1 - 65535.\n attribute :sampler_interval\n\n # @return [:inbound, :outbound, nil] Specifies the netstream sampler direction.\n attribute :sampler_direction\n validates :sampler_direction, expression_inclusion: {:in=>[:inbound, :outbound], :message=>\"%{value} needs to be :inbound, :outbound\"}, allow_nil: true\n\n # @return [:inbound, :outbound, nil] Specifies the netstream statistic direction.\n attribute :statistics_direction\n validates :statistics_direction, expression_inclusion: {:in=>[:inbound, :outbound], :message=>\"%{value} needs to be :inbound, :outbound\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the flexible netstream statistic record, length is 1 - 32.\n attribute :statistics_record\n\n # @return [16, 32, nil] Specifies the netstream index-switch.\n attribute :index_switch\n validates :index_switch, expression_inclusion: {:in=>[16, 32], :message=>\"%{value} needs to be 16, 32\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7061086893081665, "alphanum_fraction": 0.7065896987915039, "avg_line_length": 58.400001525878906, "blob_id": "cd946325f2923a0e2a3f86185473d74b6cb00904", "content_id": "34e8538ab91fdce43864445e5de00a31e75ae887", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2079, "license_type": "permissive", "max_line_length": 414, "num_lines": 35, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_category.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to create / delete / update VMware categories.\n # Tag feature is introduced in vSphere 6 version, so this module is not supported in the earlier versions of vSphere.\n # All variables and VMware object names are case sensitive.\n class Vmware_category < Base\n # @return [String] The name of category to manage.\n attribute :category_name\n validates :category_name, presence: true, type: String\n\n # @return [String, nil] The category description.,This is required only if C(state) is set to C(present).,This parameter is ignored, when C(state) is set to C(absent).\n attribute :category_description\n validates :category_description, type: String\n\n # @return [:multiple, :single, nil] The category cardinality.,This parameter is ignored, when updating existing category.\n attribute :category_cardinality\n validates :category_cardinality, expression_inclusion: {:in=>[:multiple, :single], :message=>\"%{value} needs to be :multiple, :single\"}, allow_nil: true\n\n # @return [String, nil] The new name for an existing category.,This value is used while updating an existing category.\n attribute :new_category_name\n validates :new_category_name, type: String\n\n # @return [:present, :absent, nil] The state of category.,If set to C(present) and category does not exists, then category is created.,If set to C(present) and category exists, then category is updated.,If set to C(absent) and category exists, then category is deleted.,If set to C(absent) and category does not exists, no action is taken.,Process of updating category only allows name, description change.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6772152185440063, "alphanum_fraction": 0.6772152185440063, "avg_line_length": 43.093021392822266, "blob_id": "d1067a00f6ba3c549cbb9943eaae7519d4f83d41", "content_id": "b38b25e5090fc7ec134c5e62dc56ada13a61245e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1896, "license_type": "permissive", "max_line_length": 185, "num_lines": 43, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_vpc_offering.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, enable, disable and remove CloudStack VPC offerings.\n class Cs_vpc_offering < Base\n # @return [String] The name of the vpc offering\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:enabled, :present, :disabled, :absent, nil] State of the vpc offering.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:enabled, :present, :disabled, :absent], :message=>\"%{value} needs to be :enabled, :present, :disabled, :absent\"}, allow_nil: true\n\n # @return [String, nil] Display text of the vpc offerings\n attribute :display_text\n validates :display_text, type: String\n\n # @return [Object, nil] Desired service capabilities as part of vpc offering.\n attribute :service_capabilities\n\n # @return [Object, nil] The name or ID of the service offering for the VPC router appliance.\n attribute :service_offering\n\n # @return [Array<String>, String, nil] Services supported by the vpc offering\n attribute :supported_services\n validates :supported_services, type: TypeGeneric.new(String)\n\n # @return [Array<Hash>, Hash, nil] provider to service mapping. If not specified, the provider for the service will be mapped to the default provider on the physical network\n attribute :service_providers\n validates :service_providers, type: TypeGeneric.new(Hash)\n\n # @return [Boolean, nil] Poll async jobs until job has finished.\n attribute :poll_async\n validates :poll_async, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6459739208221436, "alphanum_fraction": 0.6459739208221436, "avg_line_length": 38, "blob_id": "86a24009cb044156acbca34f63098200dd026b5f", "content_id": "45a5eb747abe3b9518cbef5acfb827695ade81e0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2223, "license_type": "permissive", "max_line_length": 173, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/source_control/github_release.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Fetch metadata about GitHub Releases\n class Github_release < Base\n # @return [String, nil] GitHub Personal Access Token for authenticating\n attribute :token\n validates :token, type: String\n\n # @return [String] The GitHub account that owns the repository\n attribute :user\n validates :user, presence: true, type: String\n\n # @return [String, nil] The GitHub account password for the user\n attribute :password\n validates :password, type: String\n\n # @return [String] Repository name\n attribute :repo\n validates :repo, presence: true, type: String\n\n # @return [:latest_release, :create_release] Action to perform\n attribute :action\n validates :action, presence: true, expression_inclusion: {:in=>[:latest_release, :create_release], :message=>\"%{value} needs to be :latest_release, :create_release\"}\n\n # @return [String, nil] Tag name when creating a release. Required when using action is set to C(create_release).\n attribute :tag\n validates :tag, type: String\n\n # @return [String, nil] Target of release when creating a release\n attribute :target\n validates :target, type: String\n\n # @return [String, nil] Name of release when creating a release\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] Description of the release when creating a release\n attribute :body\n validates :body, type: String\n\n # @return [:yes, :no, nil] Sets if the release is a draft or not. (boolean)\n attribute :draft\n validates :draft, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Sets if the release is a prerelease or not. (boolean)\n attribute :prerelease\n validates :prerelease, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.676186203956604, "alphanum_fraction": 0.6847313046455383, "avg_line_length": 53.9012336730957, "blob_id": "0d5e81cc1728629158d5b5a8c89b0917d0aebb02", "content_id": "4b1bee7a258c49f58690c1654bede8b91e603238", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4447, "license_type": "permissive", "max_line_length": 301, "num_lines": 81, "path": "/lib/ansible/ruby/modules/generated/remote_management/ucs/ucs_ip_pool.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configures IP address pools and blocks of IP addresses on Cisco UCS Manager.\n # Examples can be used with the UCS Platform Emulator U(https://communities.cisco.com/ucspe).\n class Ucs_ip_pool < Base\n # @return [:present, :absent, nil] If C(present), will verify IP pool is present and will create if needed.,If C(absent), will verify IP pool is absent and will delete if needed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The name of the IP address pool.,This name can be between 1 and 32 alphanumeric characters.,You cannot use spaces or any special characters other than - (hyphen), \"_\" (underscore), : (colon), and . (period).,You cannot change this name after the IP address pool is created.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] The user-defined description of the IP address pool.,Enter up to 256 characters.,You can use any characters or spaces except the following:,` (accent mark), (backslash), ^ (carat), \" (double quote), = (equal sign), > (greater than), < (less than), or ' (single quote).\n attribute :descrption\n\n # @return [:default, :sequential, nil] The Assignment Order field.,This can be one of the following:,default - Cisco UCS Manager selects a random identity from the pool.,sequential - Cisco UCS Manager selects the lowest available identity from the pool.\n attribute :order\n validates :order, expression_inclusion: {:in=>[:default, :sequential], :message=>\"%{value} needs to be :default, :sequential\"}, allow_nil: true\n\n # @return [String, nil] The first IPv4 address in the IPv4 addresses block.,This is the From field in the UCS Manager Add IPv4 Blocks menu.\n attribute :first_addr\n validates :first_addr, type: String\n\n # @return [String, nil] The last IPv4 address in the IPv4 addresses block.,This is the To field in the UCS Manager Add IPv4 Blocks menu.\n attribute :last_addr\n validates :last_addr, type: String\n\n # @return [String, nil] The subnet mask associated with the IPv4 addresses in the block.\n attribute :subnet_mask\n validates :subnet_mask, type: String\n\n # @return [String, nil] The default gateway associated with the IPv4 addresses in the block.\n attribute :default_gw\n validates :default_gw, type: String\n\n # @return [String, nil] The primary DNS server that this block of IPv4 addresses should access.\n attribute :primary_dns\n validates :primary_dns, type: String\n\n # @return [String, nil] The secondary DNS server that this block of IPv4 addresses should access.\n attribute :secondary_dns\n validates :secondary_dns, type: String\n\n # @return [String, nil] The first IPv6 address in the IPv6 addresses block.,This is the From field in the UCS Manager Add IPv6 Blocks menu.\n attribute :ipv6_first_addr\n validates :ipv6_first_addr, type: String\n\n # @return [String, nil] The last IPv6 address in the IPv6 addresses block.,This is the To field in the UCS Manager Add IPv6 Blocks menu.\n attribute :ipv6_last_addr\n validates :ipv6_last_addr, type: String\n\n # @return [String, nil] The network address prefix associated with the IPv6 addresses in the block.\n attribute :ipv6_prefix\n validates :ipv6_prefix, type: String\n\n # @return [String, nil] The default gateway associated with the IPv6 addresses in the block.\n attribute :ipv6_default_gw\n validates :ipv6_default_gw, type: String\n\n # @return [String, nil] The primary DNS server that this block of IPv6 addresses should access.\n attribute :ipv6_primary_dns\n validates :ipv6_primary_dns, type: String\n\n # @return [String, nil] The secondary DNS server that this block of IPv6 addresses should access.\n attribute :ipv6_secondary_dns\n validates :ipv6_secondary_dns, type: String\n\n # @return [String, nil] Org dn (distinguished name)\n attribute :org_dn\n validates :org_dn, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6554622054100037, "alphanum_fraction": 0.6554622054100037, "avg_line_length": 37.80434799194336, "blob_id": "87f13a26616e671c450a6595a062c7e3d85cc916", "content_id": "d291fa4e3abfb033db8d62759d0a5f8069717454", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1785, "license_type": "permissive", "max_line_length": 143, "num_lines": 46, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_vpn_connection.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create and remove VPN connections.\n class Cs_vpn_connection < Base\n # @return [String] Name of the VPC the VPN connection is related to.\n attribute :vpc\n validates :vpc, presence: true, type: String\n\n # @return [String] Name of the VPN customer gateway.\n attribute :vpn_customer_gateway\n validates :vpn_customer_gateway, presence: true, type: String\n\n # @return [Symbol, nil] State of the VPN connection.,Only considered when C(state=present).\n attribute :passive\n validates :passive, type: Symbol\n\n # @return [Symbol, nil] Activate the VPN gateway if not already activated on C(state=present).,Also see M(cs_vpn_gateway).\n attribute :force\n validates :force, type: Symbol\n\n # @return [:present, :absent, nil] State of the VPN connection.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Domain the VPN connection is related to.\n attribute :domain\n\n # @return [Object, nil] Account the VPN connection is related to.\n attribute :account\n\n # @return [Object, nil] Name of the project the VPN connection is related to.\n attribute :project\n\n # @return [Boolean, nil] Poll async jobs until job has finished.\n attribute :poll_async\n validates :poll_async, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6530612111091614, "alphanum_fraction": 0.6544686555862427, "avg_line_length": 42.06060791015625, "blob_id": "b36fb228f43aa1b539f4641b2a02ad7460ef7c79", "content_id": "8c2ac444519572ea476c8edb692a84bd05259174", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1421, "license_type": "permissive", "max_line_length": 299, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/system/debconf.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configure a .deb package using debconf-set-selections. Or just query existing selections.\n class Debconf < Base\n # @return [String] Name of package to configure.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] A debconf configuration setting.\n attribute :question\n validates :question, type: String\n\n # @return [:boolean, :error, :multiselect, :note, :password, :seen, :select, :string, :text, :title, :text, nil] The type of the value supplied.,C(seen) was added in 2.2.\n attribute :vtype\n validates :vtype, expression_inclusion: {:in=>[:boolean, :error, :multiselect, :note, :password, :seen, :select, :string, :text, :title, :text], :message=>\"%{value} needs to be :boolean, :error, :multiselect, :note, :password, :seen, :select, :string, :text, :title, :text\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] Value to set the configuration to.\n attribute :value\n validates :value, type: TypeGeneric.new(String)\n\n # @return [Symbol, nil] Do not set 'seen' flag when pre-seeding.\n attribute :unseen\n validates :unseen, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6566104888916016, "alphanum_fraction": 0.6583850979804993, "avg_line_length": 37.86206817626953, "blob_id": "419825ec195c01277d41ac244c7a477126026ed1", "content_id": "d27dc18fb53184807f7681e051936ad25579ef8e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1127, "license_type": "permissive", "max_line_length": 146, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_acl_interface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages applying ACLs to interfaces.\n class Nxos_acl_interface < Base\n # @return [String] Case sensitive name of the access list (ACL).\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] Full name of interface, e.g. I(Ethernet1/1).\n attribute :interface\n validates :interface, presence: true, type: String\n\n # @return [:ingress, :egress] Direction ACL to be applied in on the interface.\n attribute :direction\n validates :direction, presence: true, expression_inclusion: {:in=>[:ingress, :egress], :message=>\"%{value} needs to be :ingress, :egress\"}\n\n # @return [:present, :absent, nil] Specify desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6869439482688904, "alphanum_fraction": 0.6874248385429382, "avg_line_length": 51.64556884765625, "blob_id": "0a01b8e68b312a9d6aa6cdf98c28bd553933be4b", "content_id": "4d7a2c59cee1732fdddf62b6c5a0015dc11367c2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4159, "license_type": "permissive", "max_line_length": 212, "num_lines": 79, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_interface_policy_leaf_policy_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage fabric interface policy leaf policy groups on Cisco ACI fabrics.\n class Aci_interface_policy_leaf_policy_group < Base\n # @return [String, nil] Name of the leaf policy group to be added/deleted.\n attribute :policy_group\n validates :policy_group, type: String\n\n # @return [String, nil] Description for the leaf policy group to be created.\n attribute :description\n validates :description, type: String\n\n # @return [:leaf, :link, :node] Selector for the type of leaf policy group we want to create.,C(leaf) for Leaf Access Port Policy Group,C(link) for Port Channel (PC),C(node) for Virtual Port Channel (VPC)\n attribute :lag_type\n validates :lag_type, presence: true, expression_inclusion: {:in=>[:leaf, :link, :node], :message=>\"%{value} needs to be :leaf, :link, :node\"}\n\n # @return [String, nil] Choice of link_level_policy to be used as part of the leaf policy group to be created.\n attribute :link_level_policy\n validates :link_level_policy, type: String\n\n # @return [Object, nil] Choice of cdp_policy to be used as part of the leaf policy group to be created.\n attribute :cdp_policy\n\n # @return [Object, nil] Choice of mcp_policy to be used as part of the leaf policy group to be created.\n attribute :mcp_policy\n\n # @return [Object, nil] Choice of lldp_policy to be used as part of the leaf policy group to be created.\n attribute :lldp_policy\n\n # @return [Object, nil] Choice of stp_interface_policy to be used as part of the leaf policy group to be created.\n attribute :stp_interface_policy\n\n # @return [Object, nil] Choice of egress_data_plane_policing_policy to be used as part of the leaf policy group to be created.\n attribute :egress_data_plane_policing_policy\n\n # @return [Object, nil] Choice of ingress_data_plane_policing_policy to be used as part of the leaf policy group to be created.\n attribute :ingress_data_plane_policing_policy\n\n # @return [Object, nil] Choice of priority_flow_control_policy to be used as part of the leaf policy group to be created.\n attribute :priority_flow_control_policy\n\n # @return [String, nil] Choice of fibre_channel_interface_policy to be used as part of the leaf policy group to be created.\n attribute :fibre_channel_interface_policy\n validates :fibre_channel_interface_policy, type: String\n\n # @return [Object, nil] Choice of slow_drain_policy to be used as part of the leaf policy group to be created.\n attribute :slow_drain_policy\n\n # @return [Object, nil] Choice of port_channel_policy to be used as part of the leaf policy group to be created.\n attribute :port_channel_policy\n\n # @return [Object, nil] Choice of monitoring_policy to be used as part of the leaf policy group to be created.\n attribute :monitoring_policy\n\n # @return [Object, nil] Choice of storm_control_interface_policy to be used as part of the leaf policy group to be created.\n attribute :storm_control_interface_policy\n\n # @return [Object, nil] Choice of l2_interface_policy to be used as part of the leaf policy group to be created.\n attribute :l2_interface_policy\n\n # @return [Object, nil] Choice of port_security_policy to be used as part of the leaf policy group to be created.\n attribute :port_security_policy\n\n # @return [Object, nil] Choice of attached_entity_profile (AEP) to be used as part of the leaf policy group to be created.\n attribute :aep\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6941747665405273, "alphanum_fraction": 0.6941747665405273, "avg_line_length": 24.75, "blob_id": "f9b24515bcf0d0347797df6366da5d174afe8b9d", "content_id": "fb7e83b1f28833d3996a0aa9f64be24d4d43a0ad", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 412, "license_type": "permissive", "max_line_length": 76, "num_lines": 16, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_auth.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Retrieve an auth token from an OpenStack Cloud\n class Os_auth < Base\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6489493250846863, "alphanum_fraction": 0.6489493250846863, "avg_line_length": 31.360000610351562, "blob_id": "6a75a41b80453e4ddb55c705e4b8c5e50470b418", "content_id": "f846844c77b525549c9b3ed50944ec7ffb66b638", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 809, "license_type": "permissive", "max_line_length": 132, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/system/seboolean.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Toggles SELinux booleans.\n class Seboolean < Base\n # @return [String] Name of the boolean to configure.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:yes, :no, nil] Set to C(yes) if the boolean setting should survive a reboot.\n attribute :persistent\n validates :persistent, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Symbol] Desired boolean value\n attribute :state\n validates :state, presence: true, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.634357750415802, "alphanum_fraction": 0.634357750415802, "avg_line_length": 43.52631759643555, "blob_id": "3892f8c24f11416ed76c5850e1b2fb217fe47342", "content_id": "dabd8a47bc37f622157c38d49ae38d58a5c5c56b", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2538, "license_type": "permissive", "max_line_length": 213, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_cdot_volume.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or destroy volumes on NetApp cDOT\n class Na_cdot_volume < Base\n # @return [:present, :absent] Whether the specified volume should exist or not.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String] The name of the volume to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:yes, :no, nil] Set True if the volume is an Infinite Volume.\n attribute :infinite\n validates :infinite, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Whether the specified volume is online, or not.\n attribute :online\n validates :online, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] The name of the aggregate the flexvol should exist on. Required when C(state=present).\n attribute :aggregate_name\n validates :aggregate_name, type: String\n\n # @return [Integer, nil] The size of the volume in (size_unit). Required when C(state=present).\n attribute :size\n validates :size, type: Integer\n\n # @return [:bytes, :b, :kb, :mb, :gb, :tb, :pb, :eb, :zb, :yb, nil] The unit used to interpret the size parameter.\n attribute :size_unit\n validates :size_unit, expression_inclusion: {:in=>[:bytes, :b, :kb, :mb, :gb, :tb, :pb, :eb, :zb, :yb], :message=>\"%{value} needs to be :bytes, :b, :kb, :mb, :gb, :tb, :pb, :eb, :zb, :yb\"}, allow_nil: true\n\n # @return [String] Name of the vserver to use.\n attribute :vserver\n validates :vserver, presence: true, type: String\n\n # @return [String, nil] Junction path where to mount the volume\n attribute :junction_path\n validates :junction_path, type: String\n\n # @return [String, nil] Export policy to set for the specified junction path.\n attribute :export_policy\n validates :export_policy, type: String\n\n # @return [String, nil] Snapshot policy to set for the specified volume.\n attribute :snapshot_policy\n validates :snapshot_policy, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6629629731178284, "alphanum_fraction": 0.6629629731178284, "avg_line_length": 42.783782958984375, "blob_id": "1083d53266d9c91eaf0be7fb3907eb44b8e9a2b3", "content_id": "e1e33fb81ca98baaaa64241cebfc8e1b52e601bc", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1620, "license_type": "permissive", "max_line_length": 279, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_irule.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage iRules across different modules on a BIG-IP.\n class Bigip_irule < Base\n # @return [String, nil] When used instead of 'src', sets the contents of an iRule directly to the specified value. This is for simple values, but can be used with lookup plugins for anything complex or with formatting. Either one of C(src) or C(content) must be provided.\n attribute :content\n validates :content, type: String\n\n # @return [:ltm, :gtm] The BIG-IP module to add the iRule to.\n attribute :module\n validates :module, presence: true, expression_inclusion: {:in=>[:ltm, :gtm], :message=>\"%{value} needs to be :ltm, :gtm\"}\n\n # @return [String] The name of the iRule.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] The iRule file to interpret and upload to the BIG-IP. Either one of C(src) or C(content) must be provided.\n attribute :src\n validates :src, presence: true, type: String\n\n # @return [:present, :absent, nil] Whether the iRule should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7112810611724854, "alphanum_fraction": 0.7112810611724854, "avg_line_length": 20.79166603088379, "blob_id": "55686e4bbdfe7fec079e6e53f2e73e4aaf6ba72e", "content_id": "159bceee71da7b4aff0ad6134c83455246a1a1b8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 523, "license_type": "permissive", "max_line_length": 51, "num_lines": 24, "path": "/examples/Rakefile", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'ansible/ruby/rake/tasks'\n\ndesc 'named ansible task'\nAnsible::Ruby::Rake::Execute.new do |task|\n task.playbooks = 'webservers.rb'\nend\n\ndesc 'AMI test'\nAnsible::Ruby::Rake::Execute.new :ami do |task|\n task.playbooks = 'image_copy.rb'\nend\n\ndesc 'Command test'\nAnsible::Ruby::Rake::Execute.new :command do |task|\n task.playbooks = 'command.rb'\nend\n\ndesc 'Block test'\nAnsible::Ruby::Rake::Execute.new :block do |task|\n task.playbooks = 'block.rb'\n task.options = '-e stuff=true'\nend\n" }, { "alpha_fraction": 0.6419125199317932, "alphanum_fraction": 0.6561546325683594, "avg_line_length": 49.844825744628906, "blob_id": "a52e772ddf4dd3b179f08d8e0b09d3443cf338eb", "content_id": "2d17078921bb11ecb896cc3e643df942df6bc15a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2949, "license_type": "permissive", "max_line_length": 235, "num_lines": 58, "path": "/lib/ansible/ruby/modules/generated/network/onyx/onyx_interface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of Interfaces on Mellanox ONYX network devices.\n class Onyx_interface < Base\n # @return [String] Name of the Interface.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Description of Interface.\n attribute :description\n validates :description, type: String\n\n # @return [Symbol, nil] Interface link status.\n attribute :enabled\n validates :enabled, type: Symbol\n\n # @return [:\"1G\", :\"10G\", :\"25G\", :\"40G\", :\"50G\", :\"56G\", :\"100G\", nil] Interface link speed.\n attribute :speed\n validates :speed, expression_inclusion: {:in=>[:\"1G\", :\"10G\", :\"25G\", :\"40G\", :\"50G\", :\"56G\", :\"100G\"], :message=>\"%{value} needs to be :\\\"1G\\\", :\\\"10G\\\", :\\\"25G\\\", :\\\"40G\\\", :\\\"50G\\\", :\\\"56G\\\", :\\\"100G\\\"\"}, allow_nil: true\n\n # @return [Integer, nil] Maximum size of transmit packet.\n attribute :mtu\n validates :mtu, type: Integer\n\n # @return [Object, nil] List of Interfaces definitions.\n attribute :aggregate\n\n # @return [:full, :half, :auto, nil] Interface link status\n attribute :duplex\n validates :duplex, expression_inclusion: {:in=>[:full, :half, :auto], :message=>\"%{value} needs to be :full, :half, :auto\"}, allow_nil: true\n\n # @return [Object, nil] Transmit rate in bits per second (bps).,This is state check parameter only.,Supports conditionals, see L(Conditionals in Networking Modules,../network/user_guide/network_working_with_command_output.html)\n attribute :tx_rate\n\n # @return [Object, nil] Receiver rate in bits per second (bps).,This is state check parameter only.,Supports conditionals, see L(Conditionals in Networking Modules,../network/user_guide/network_working_with_command_output.html)\n attribute :rx_rate\n\n # @return [Integer, nil] Time in seconds to wait before checking for the operational state on remote device. This wait is applicable for operational state argument which are I(state) with values C(up)/C(down).\n attribute :delay\n validates :delay, type: Integer\n\n # @return [Symbol, nil] Purge Interfaces not defined in the aggregate parameter. This applies only for logical interface.\n attribute :purge\n validates :purge, type: Symbol\n\n # @return [:present, :absent, :up, :down, nil] State of the Interface configuration, C(up) means present and operationally up and C(down) means present and operationally C(down)\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :up, :down], :message=>\"%{value} needs to be :present, :absent, :up, :down\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6652835607528687, "alphanum_fraction": 0.6652835607528687, "avg_line_length": 47.20000076293945, "blob_id": "7df3ebece0b19f5da1df8ba539e3905956629d37", "content_id": "122207176ea117cc5df2cff762171d96c81fa51f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2169, "license_type": "permissive", "max_line_length": 169, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_linkagg.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of link aggregation groups on Cisco NXOS devices.\n class Nxos_linkagg < Base\n # @return [Integer] Channel-group number for the port-channel Link aggregation group.\n attribute :group\n validates :group, presence: true, type: Integer\n\n # @return [:active, :on, :passive, nil] Mode for the link aggregation group.\n attribute :mode\n validates :mode, expression_inclusion: {:in=>[:active, :on, :passive], :message=>\"%{value} needs to be :active, :on, :passive\"}, allow_nil: true\n\n # @return [Integer, nil] Minimum number of ports required up before bringing up the link aggregation group.\n attribute :min_links\n validates :min_links, type: Integer\n\n # @return [Array<String>, String, nil] List of interfaces that will be managed in the link aggregation group.\n attribute :members\n validates :members, type: TypeGeneric.new(String)\n\n # @return [:yes, :no, nil] When true it forces link aggregation group members to match what is declared in the members param. This can be used to remove members.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash, nil] List of link aggregation definitions.\n attribute :aggregate\n validates :aggregate, type: TypeGeneric.new(Hash)\n\n # @return [:present, :absent, nil] State of the link aggregation group.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Purge links not defined in the I(aggregate) parameter.\n attribute :purge\n validates :purge, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.691310465335846, "alphanum_fraction": 0.6965662240982056, "avg_line_length": 54.960784912109375, "blob_id": "fd79ce05cef681ca4db9624c9183fb7d6cd65a40", "content_id": "d91c2ac2e44e995230f0b6737f5aac8a169de9e9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2854, "license_type": "permissive", "max_line_length": 214, "num_lines": 51, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_useraccountprofile.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure UserAccountProfile object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_useraccountprofile < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Object, nil] Lock timeout period (in minutes).,Default is 30 minutes.,Default value when not specified in API or module is interpreted by Avi Controller as 30.,Units(MIN).\n attribute :account_lock_timeout\n\n # @return [Object, nil] The time period after which credentials expire.,Default is 180 days.,Default value when not specified in API or module is interpreted by Avi Controller as 180.,Units(DAYS).\n attribute :credentials_timeout_threshold\n\n # @return [Object, nil] Maximum number of concurrent sessions allowed.,There are unlimited sessions by default.,Default value when not specified in API or module is interpreted by Avi Controller as 0.\n attribute :max_concurrent_sessions\n\n # @return [Object, nil] Number of login attempts before lockout.,Default is 3 attempts.,Default value when not specified in API or module is interpreted by Avi Controller as 3.\n attribute :max_login_failure_count\n\n # @return [Object, nil] Maximum number of passwords to be maintained in the password history.,Default is 4 passwords.,Default value when not specified in API or module is interpreted by Avi Controller as 4.\n attribute :max_password_history_count\n\n # @return [String] Name of the object.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Unique object identifier of the object.\n attribute :uuid\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6346153616905212, "alphanum_fraction": 0.6346153616905212, "avg_line_length": 34.069766998291016, "blob_id": "009f7dff46a391126038276e3f3b438e69780599", "content_id": "3f0d179c57e5e86df93ef75449d53ee5fe4f4b20", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1508, "license_type": "permissive", "max_line_length": 185, "num_lines": 43, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_pod.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, delete pods.\n class Cs_pod < Base\n # @return [String] Name of the pod.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] uuid of the existing pod.\n attribute :id\n\n # @return [String, nil] Starting IP address for the Pod.,Required on C(state=present)\n attribute :start_ip\n validates :start_ip, type: String\n\n # @return [Object, nil] Ending IP address for the Pod.\n attribute :end_ip\n\n # @return [String, nil] Netmask for the Pod.,Required on C(state=present)\n attribute :netmask\n validates :netmask, type: String\n\n # @return [String, nil] Gateway for the Pod.,Required on C(state=present)\n attribute :gateway\n validates :gateway, type: String\n\n # @return [String, nil] Name of the zone in which the pod belongs to.,If not set, default zone is used.\n attribute :zone\n validates :zone, type: String\n\n # @return [:present, :enabled, :disabled, :absent, nil] State of the pod.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :enabled, :disabled, :absent], :message=>\"%{value} needs to be :present, :enabled, :disabled, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6857379674911499, "alphanum_fraction": 0.6857379674911499, "avg_line_length": 45.38461685180664, "blob_id": "c4e374734a31c4fc9a57be27ebed07605615c08a", "content_id": "8eb05ef4a8d3950a5f5b7d79d525efb7bac16694", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1206, "license_type": "permissive", "max_line_length": 144, "num_lines": 26, "path": "/lib/ansible/ruby/modules/generated/utilities/logic/set_stats.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows setting/accumulating stats on the current ansible run, either per host or for all hosts in the run.\n # This module is also supported for Windows targets.\n class Set_stats < Base\n # @return [Hash] A dictionary of which each key represents a stat (or variable) you want to keep track of\n attribute :data\n validates :data, presence: true, type: Hash\n\n # @return [Boolean, nil] boolean that indicates if the stats is per host or for all hosts in the run.\n attribute :per_host\n validates :per_host, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] boolean that indicates if the provided value is aggregated to the existing stat C(yes) or will replace it C(no)\n attribute :aggregate\n validates :aggregate, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7370210289955139, "alphanum_fraction": 0.738875150680542, "avg_line_length": 86.45945739746094, "blob_id": "17e8bdb124b00c72330f9e68fb93edc86e147fa5", "content_id": "27f6e2d4a5366789bc6bb7f5c2116bc8735d24f9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3236, "license_type": "permissive", "max_line_length": 570, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_gir.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Trigger a graceful removal or insertion (GIR) of the switch.\n class Nxos_gir < Base\n # @return [Symbol, nil] When C(system_mode_maintenance=true) it puts all enabled protocols in maintenance mode (using the isolate command). When C(system_mode_maintenance=false) it puts all enabled protocols in normal mode (using the no isolate command).\n attribute :system_mode_maintenance\n validates :system_mode_maintenance, type: Symbol\n\n # @return [Symbol, nil] When C(system_mode_maintenance_dont_generate_profile=true) it prevents the dynamic searching of enabled protocols and executes commands configured in a maintenance-mode profile. Use this option if you want the system to use a maintenance-mode profile that you have created. When C(system_mode_maintenance_dont_generate_profile=false) it prevents the dynamic searching of enabled protocols and executes commands configured in a normal-mode profile. Use this option if you want the system to use a normal-mode profile that you have created.\n attribute :system_mode_maintenance_dont_generate_profile\n validates :system_mode_maintenance_dont_generate_profile, type: Symbol\n\n # @return [Integer, nil] Keeps the switch in maintenance mode for a specified number of minutes. Range is 5-65535.\n attribute :system_mode_maintenance_timeout\n validates :system_mode_maintenance_timeout, type: Integer\n\n # @return [Symbol, nil] Shuts down all protocols, vPC domains, and interfaces except the management interface (using the shutdown command). This option is disruptive while C(system_mode_maintenance) (which uses the isolate command) is not.\n attribute :system_mode_maintenance_shutdown\n validates :system_mode_maintenance_shutdown, type: Symbol\n\n # @return [:hw_error, :svc_failure, :kern_failure, :wdog_timeout, :fatal_error, :lc_failure, :match_any, :manual_reload, :any_other, :maintenance, nil] Boots the switch into maintenance mode automatically in the event of a specified system crash. Note that not all reset reasons are applicable for all platforms. Also if reset reason is set to match_any, it is not idempotent as it turns on all reset reasons. If reset reason is match_any and state is absent, it turns off all the reset reasons.\n attribute :system_mode_maintenance_on_reload_reset_reason\n validates :system_mode_maintenance_on_reload_reset_reason, expression_inclusion: {:in=>[:hw_error, :svc_failure, :kern_failure, :wdog_timeout, :fatal_error, :lc_failure, :match_any, :manual_reload, :any_other, :maintenance], :message=>\"%{value} needs to be :hw_error, :svc_failure, :kern_failure, :wdog_timeout, :fatal_error, :lc_failure, :match_any, :manual_reload, :any_other, :maintenance\"}, allow_nil: true\n\n # @return [:present, :absent] Specify desired state of the resource.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6900504231452942, "alphanum_fraction": 0.6914259791374207, "avg_line_length": 61.31428527832031, "blob_id": "4740e79c2bae5bd17d485483b0409cd78a9cff96", "content_id": "068747f2d3907e86682b1a6d3ccafb1f1abab85f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2181, "license_type": "permissive", "max_line_length": 584, "num_lines": 35, "path": "/lib/ansible/ruby/modules/generated/system/known_hosts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The C(known_hosts) module lets you add or remove a host keys from the C(known_hosts) file.\n # Starting at Ansible 2.2, multiple entries per host are allowed, but only one for each key type supported by ssh. This is useful if you're going to want to use the M(git) module over ssh, for example.\n # If you have a very large number of host keys to manage, you will find the M(template) module more useful.\n class Known_hosts < Base\n # @return [String] The host to add or remove (must match a host specified in key). It will be converted to lowercase so that ssh-keygen can find it.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The SSH public host key, as a string (required if state=present, optional when state=absent, in which case all keys for the host are removed). The key must be in the right format for ssh (see sshd(8), section \"SSH_KNOWN_HOSTS FILE FORMAT\").\\r\\nSpecifically, the key should not match the format that is found in an SSH pubkey file, but should rather have the hostname prepended to a line that includes the pubkey, the same way that it would appear in the known_hosts file. The value prepended to the line must also match the value of the name parameter.\n attribute :key\n validates :key, type: String\n\n # @return [String, nil] The known_hosts file to edit\n attribute :path\n validates :path, type: String\n\n # @return [:yes, :no, nil] Hash the hostname in the known_hosts file\n attribute :hash_host\n validates :hash_host, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, nil] I(present) to add the host key, I(absent) to remove it.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6350102424621582, "alphanum_fraction": 0.6350102424621582, "avg_line_length": 42.28888702392578, "blob_id": "3af04685136f1cc318a9b9f2ef24fc8e27203761", "content_id": "213d110a57089c94fde2940be379488720e48c52", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1948, "license_type": "permissive", "max_line_length": 309, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/cloud/vultr/vr_dns_record.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and remove DNS records.\n class Vultr_dns_record < Base\n # @return [String, nil] The record name (subrecord).\n attribute :name\n validates :name, type: String\n\n # @return [String] The domain the record is related to.\n attribute :domain\n validates :domain, presence: true, type: String\n\n # @return [:A, :AAAA, :CNAME, :MX, :SRV, :CAA, :TXT, :NS, :SSHFP, nil] Type of the record.\n attribute :record_type\n validates :record_type, expression_inclusion: {:in=>[:A, :AAAA, :CNAME, :MX, :SRV, :CAA, :TXT, :NS, :SSHFP], :message=>\"%{value} needs to be :A, :AAAA, :CNAME, :MX, :SRV, :CAA, :TXT, :NS, :SSHFP\"}, allow_nil: true\n\n # @return [String, nil] Data of the record.,Required if C(state=present) or C(multiple=yes).\n attribute :data\n validates :data, type: String\n\n # @return [Integer, nil] TTL of the record.\n attribute :ttl\n validates :ttl, type: Integer\n\n # @return [Symbol, nil] Whether to use more than one record with similar C(name) including no name and C(record_type).,Only allowed for a few record types, e.g. C(record_type=A), C(record_type=NS) or C(record_type=MX).,C(data) will not be updated, instead it is used as a key to find existing records.\n attribute :multiple\n validates :multiple, type: Symbol\n\n # @return [Integer, nil] Priority of the record.\n attribute :priority\n validates :priority, type: Integer\n\n # @return [:present, :absent, nil] State of the DNS record.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6853932738304138, "alphanum_fraction": 0.6853932738304138, "avg_line_length": 39.13725662231445, "blob_id": "45882263f3943bbfbe62ddd753a221e0e979f838", "content_id": "0fd58d134e5db19b63cf938ba81603bad53c7af7", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2047, "license_type": "permissive", "max_line_length": 312, "num_lines": 51, "path": "/lib/ansible/ruby/modules/generated/system/open_iscsi.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Discover targets on given portal, (dis)connect targets, mark targets to manually or auto start, return device nodes of connected targets.\n class Open_iscsi < Base\n # @return [String, nil] the ip address of the iscsi target\n attribute :portal\n validates :portal, type: String\n\n # @return [Integer, nil] the port on which the iscsi target process listens\n attribute :port\n validates :port, type: Integer\n\n # @return [String, nil] the iscsi target name\n attribute :target\n validates :target, type: String\n\n # @return [Symbol, nil] whether the target node should be connected\n attribute :login\n validates :login, type: Symbol\n\n # @return [String, nil] discovery.sendtargets.auth.authmethod\n attribute :node_auth\n validates :node_auth, type: String\n\n # @return [Object, nil] discovery.sendtargets.auth.username\n attribute :node_user\n\n # @return [Object, nil] discovery.sendtargets.auth.password\n attribute :node_pass\n\n # @return [Symbol, nil] whether the target node should be automatically connected at startup\n attribute :auto_node_startup\n validates :auto_node_startup, type: Symbol\n\n # @return [Symbol, nil] whether the list of target nodes on the portal should be (re)discovered and added to the persistent iscsi database. Keep in mind that iscsiadm discovery resets configurtion, like node.startup to manual, hence combined with auto_node_startup=yes will always return a changed state.\n attribute :discover\n validates :discover, type: Symbol\n\n # @return [Symbol, nil] whether the list of nodes in the persistent iscsi database should be returned by the module\n attribute :show_nodes\n validates :show_nodes, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.717175304889679, "alphanum_fraction": 0.7241564393043518, "avg_line_length": 69.93968200683594, "blob_id": "a4b92c7aa9a25177010f7b4a04c64b67fd19bda1", "content_id": "116e53a5ee2bb64c3aba545a053d72e0c45b1a02", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 22346, "license_type": "permissive", "max_line_length": 877, "num_lines": 315, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_virtualservice.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure VirtualService object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_virtualservice < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Object, nil] This configuration only applies if the virtualservice is in legacy active standby ha mode and load distribution among active standby is enabled.,This field is used to tag the virtualservice so that virtualservices with the same tag will share the same active serviceengine.,Virtualservices with different tags will have different active serviceengines.,If one of the serviceengine's in the serviceenginegroup fails, all virtualservices will end up using the same active serviceengine.,Redistribution of the virtualservices can be either manual or automated when the failed serviceengine recovers.,Redistribution is based on the auto redistribute property of the serviceenginegroup.,Enum options - ACTIVE_STANDBY_SE_1, ACTIVE_STANDBY_SE_2.,Default value when not specified in API or module is interpreted by Avi Controller as ACTIVE_STANDBY_SE_1.\n attribute :active_standby_se_tag\n\n # @return [Object, nil] Determines analytics settings for the application.\n attribute :analytics_policy\n\n # @return [Object, nil] Specifies settings related to analytics.,It is a reference to an object of type analyticsprofile.\n attribute :analytics_profile_ref\n\n # @return [String, nil] Enable application layer specific features for the virtual service.,It is a reference to an object of type applicationprofile.\n attribute :application_profile_ref\n validates :application_profile_ref, type: String\n\n # @return [Symbol, nil] Auto-allocate floating/elastic ip from the cloud infrastructure.,Field deprecated in 17.1.1.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :auto_allocate_floating_ip\n validates :auto_allocate_floating_ip, type: Symbol\n\n # @return [Symbol, nil] Auto-allocate vip from the provided subnet.,Field deprecated in 17.1.1.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :auto_allocate_ip\n validates :auto_allocate_ip, type: Symbol\n\n # @return [Object, nil] Availability-zone to place the virtual service.,Field deprecated in 17.1.1.\n attribute :availability_zone\n\n # @return [Symbol, nil] (internal-use) fip allocated by avi in the cloud infrastructure.,Field deprecated in 17.1.1.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :avi_allocated_fip\n validates :avi_allocated_fip, type: Symbol\n\n # @return [Symbol, nil] (internal-use) vip allocated by avi in the cloud infrastructure.,Field deprecated in 17.1.1.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :avi_allocated_vip\n validates :avi_allocated_vip, type: Symbol\n\n # @return [Symbol, nil] (this is a beta feature).,Sync key-value cache to the new ses when vs is scaled out.,For ex ssl sessions are stored using vs's key-value cache.,When the vs is scaled out, the ssl session information is synced to the new se, allowing existing ssl sessions to be reused on the new se.,Field introduced in 17.2.7, 18.1.1.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :bulk_sync_kvcache\n validates :bulk_sync_kvcache, type: Symbol\n\n # @return [Object, nil] Http authentication configuration for protected resources.\n attribute :client_auth\n\n # @return [Symbol, nil] Close client connection on vs config update.,Field introduced in 17.2.4.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :close_client_conn_on_config_update\n validates :close_client_conn_on_config_update, type: Symbol\n\n # @return [Object, nil] Checksum of cloud configuration for vs.,Internally set by cloud connector.\n attribute :cloud_config_cksum\n\n # @return [Object, nil] It is a reference to an object of type cloud.\n attribute :cloud_ref\n\n # @return [Object, nil] Enum options - cloud_none, cloud_vcenter, cloud_openstack, cloud_aws, cloud_vca, cloud_apic, cloud_mesos, cloud_linuxserver, cloud_docker_ucp,,cloud_rancher, cloud_oshift_k8s, cloud_azure.,Default value when not specified in API or module is interpreted by Avi Controller as CLOUD_NONE.\n attribute :cloud_type\n\n # @return [Object, nil] Rate limit the incoming connections to this virtual service.\n attribute :connections_rate_limit\n\n # @return [Object, nil] Profile used to match and rewrite strings in request and/or response body.\n attribute :content_rewrite\n\n # @return [Object, nil] Creator name.\n attribute :created_by\n\n # @return [Symbol, nil] Select the algorithm for qos fairness.,This determines how multiple virtual services sharing the same service engines will prioritize traffic over a congested network.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :delay_fairness\n validates :delay_fairness, type: Symbol\n\n # @return [Object, nil] User defined description for the object.\n attribute :description\n\n # @return [Object, nil] (internal-use) discovered networks providing reachability for client facing virtual service ip.,This field is deprecated.,It is a reference to an object of type network.,Field deprecated in 17.1.1.\n attribute :discovered_network_ref\n\n # @return [Object, nil] (internal-use) discovered networks providing reachability for client facing virtual service ip.,This field is used internally by avi, not editable by the user.,Field deprecated in 17.1.1.\n attribute :discovered_networks\n\n # @return [Object, nil] (internal-use) discovered subnets providing reachability for client facing virtual service ip.,This field is deprecated.,Field deprecated in 17.1.1.\n attribute :discovered_subnet\n\n # @return [Object, nil] Service discovery specific data including fully qualified domain name, type and time-to-live of the dns record.,Note that only one of fqdn and dns_info setting is allowed.\n attribute :dns_info\n\n # @return [Object, nil] Dns policies applied on the dns traffic of the virtual service.,Field introduced in 17.1.1.\n attribute :dns_policies\n\n # @return [Symbol, nil] Force placement on all se's in service group (mesos mode only).,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :east_west_placement\n validates :east_west_placement, type: Symbol\n\n # @return [Symbol, nil] Response traffic to clients will be sent back to the source mac address of the connection, rather than statically sent to a default gateway.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :enable_autogw\n validates :enable_autogw, type: Symbol\n\n # @return [Symbol, nil] Enable route health injection using the bgp config in the vrf context.\n attribute :enable_rhi\n validates :enable_rhi, type: Symbol\n\n # @return [Symbol, nil] Enable route health injection for source nat'ted floating ip address using the bgp config in the vrf context.\n attribute :enable_rhi_snat\n validates :enable_rhi_snat, type: Symbol\n\n # @return [Symbol, nil] Enable or disable the virtual service.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :enabled\n validates :enabled, type: Symbol\n\n # @return [Object, nil] Error page profile to be used for this virtualservice.this profile is used to send the custom error page to the client generated by the proxy.,It is a reference to an object of type errorpageprofile.,Field introduced in 17.2.4.\n attribute :error_page_profile_ref\n\n # @return [Object, nil] Floating ip to associate with this virtual service.,Field deprecated in 17.1.1.\n attribute :floating_ip\n\n # @return [Object, nil] If auto_allocate_floating_ip is true and more than one floating-ip subnets exist, then the subnet for the floating ip address allocation.,This field is applicable only if the virtualservice belongs to an openstack or aws cloud.,In openstack or aws cloud it is required when auto_allocate_floating_ip is selected.,Field deprecated in 17.1.1.\n attribute :floating_subnet_uuid\n\n # @return [Object, nil] Criteria for flow distribution among ses.,Enum options - LOAD_AWARE, CONSISTENT_HASH_SOURCE_IP_ADDRESS, CONSISTENT_HASH_SOURCE_IP_ADDRESS_AND_PORT.,Default value when not specified in API or module is interpreted by Avi Controller as LOAD_AWARE.\n attribute :flow_dist\n\n # @return [Object, nil] Criteria for flow labelling.,Enum options - NO_LABEL, APPLICATION_LABEL, SERVICE_LABEL.,Default value when not specified in API or module is interpreted by Avi Controller as NO_LABEL.\n attribute :flow_label_type\n\n # @return [Object, nil] Dns resolvable, fully qualified domain name of the virtualservice.,Only one of 'fqdn' and 'dns_info' configuration is allowed.\n attribute :fqdn\n\n # @return [Object, nil] Translate the host name sent to the servers to this value.,Translate the host name sent from servers back to the value used by the client.\n attribute :host_name_xlate\n\n # @return [Object, nil] Http policies applied on the data traffic of the virtual service.\n attribute :http_policies\n\n # @return [Symbol, nil] Ignore pool servers network reachability constraints for virtual service placement.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :ign_pool_net_reach\n validates :ign_pool_net_reach, type: Symbol\n\n # @return [NilClass, nil] Ip address of the virtual service.,Field deprecated in 17.1.1.\n attribute :ip_address\n validates :ip_address, type: NilClass\n\n # @return [Object, nil] Subnet and/or network for allocating virtualservice ip by ipam provider module.,Field deprecated in 17.1.1.\n attribute :ipam_network_subnet\n\n # @return [Object, nil] L4 policies applied to the data traffic of the virtual service.,Field introduced in 17.2.7.\n attribute :l4_policies\n\n # @return [Symbol, nil] Limit potential dos attackers who exceed max_cps_per_client significantly to a fraction of max_cps_per_client for a while.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :limit_doser\n validates :limit_doser, type: Symbol\n\n # @return [Object, nil] Maximum connections per second per client ip.,Allowed values are 10-1000.,Special values are 0- 'unlimited'.,Default value when not specified in API or module is interpreted by Avi Controller as 0.\n attribute :max_cps_per_client\n\n # @return [Object, nil] Microservice representing the virtual service.,It is a reference to an object of type microservice.\n attribute :microservice_ref\n\n # @return [String] Name for the virtual service.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Determines network settings such as protocol, tcp or udp, and related options for the protocol.,It is a reference to an object of type networkprofile.\n attribute :network_profile_ref\n\n # @return [Object, nil] Manually override the network on which the virtual service is placed.,It is a reference to an object of type network.,Field deprecated in 17.1.1.\n attribute :network_ref\n\n # @return [Object, nil] Network security policies for the virtual service.,It is a reference to an object of type networksecuritypolicy.\n attribute :network_security_policy_ref\n\n # @return [Object, nil] A list of nsx service groups representing the clients which can access the virtual ip of the virtual service.,Field introduced in 17.1.1.\n attribute :nsx_securitygroup\n\n # @return [NilClass, nil] Optional settings that determine performance limits like max connections or bandwdith etc.\n attribute :performance_limits\n validates :performance_limits, type: NilClass\n\n # @return [Object, nil] The pool group is an object that contains pools.,It is a reference to an object of type poolgroup.\n attribute :pool_group_ref\n\n # @return [String, nil] The pool is an object that contains destination servers and related attributes such as load-balancing and persistence.,It is a reference to an object of type pool.\n attribute :pool_ref\n validates :pool_ref, type: String\n\n # @return [Object, nil] (internal-use) network port assigned to the virtual service ip address.,Field deprecated in 17.1.1.\n attribute :port_uuid\n\n # @return [Symbol, nil] Remove listening port if virtualservice is down.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :remove_listening_port_on_vs_down\n validates :remove_listening_port_on_vs_down, type: Symbol\n\n # @return [Object, nil] Rate limit the incoming requests to this virtual service.\n attribute :requests_rate_limit\n\n # @return [Symbol, nil] Disable re-distribution of flows across service engines for a virtual service.,Enable if the network itself performs flow hashing with ecmp in environments such as gcp.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :scaleout_ecmp\n validates :scaleout_ecmp, type: Symbol\n\n # @return [Object, nil] The service engine group to use for this virtual service.,Moving to a new se group is disruptive to existing connections for this vs.,It is a reference to an object of type serviceenginegroup.\n attribute :se_group_ref\n\n # @return [Object, nil] Determines the network settings profile for the server side of tcp proxied connections.,Leave blank to use the same settings as the client to vs side of the connection.,It is a reference to an object of type networkprofile.\n attribute :server_network_profile_ref\n\n # @return [Object, nil] Metadata pertaining to the service provided by this virtual service.,In openshift/kubernetes environments, egress pod info is stored.,Any user input to this field will be overwritten by avi vantage.\n attribute :service_metadata\n\n # @return [Object, nil] Select pool based on destination port.\n attribute :service_pool_select\n\n # @return [Array<Hash>, Hash, nil] List of services defined for this virtual service.\n attribute :services\n validates :services, type: TypeGeneric.new(Hash)\n\n # @return [Object, nil] Sideband configuration to be used for this virtualservice.it can be used for sending traffic to sideband vips for external inspection etc.\n attribute :sideband_profile\n\n # @return [Object, nil] Nat'ted floating source ip address(es) for upstream connection to servers.\n attribute :snat_ip\n\n # @return [Object, nil] Gslb pools used to manage site-persistence functionality.,Each site-persistence pool contains the virtualservices in all the other sites, that is auto-generated by the gslb manager.,This is a read-only field for the user.,It is a reference to an object of type pool.,Field introduced in 17.2.2.\n attribute :sp_pool_refs\n\n # @return [Array<String>, String, nil] Select or create one or two certificates, ec and/or rsa, that will be presented to ssl/tls terminated connections.,It is a reference to an object of type sslkeyandcertificate.\n attribute :ssl_key_and_certificate_refs\n validates :ssl_key_and_certificate_refs, type: TypeGeneric.new(String)\n\n # @return [String, nil] Determines the set of ssl versions and ciphers to accept for ssl/tls terminated connections.,It is a reference to an object of type sslprofile.\n attribute :ssl_profile_ref\n validates :ssl_profile_ref, type: String\n\n # @return [Object, nil] Expected number of ssl session cache entries (may be exceeded).,Allowed values are 1024-16383.,Default value when not specified in API or module is interpreted by Avi Controller as 1024.\n attribute :ssl_sess_cache_avg_size\n\n # @return [Object, nil] List of static dns records applied to this virtual service.,These are static entries and no health monitoring is performed against the ip addresses.\n attribute :static_dns_records\n\n # @return [Object, nil] Subnet providing reachability for client facing virtual service ip.,Field deprecated in 17.1.1.\n attribute :subnet\n\n # @return [Object, nil] It represents subnet for the virtual service ip address allocation when auto_allocate_ip is true.it is only applicable in openstack or aws cloud.,This field is required if auto_allocate_ip is true.,Field deprecated in 17.1.1.\n attribute :subnet_uuid\n\n # @return [Object, nil] It is a reference to an object of type tenant.\n attribute :tenant_ref\n\n # @return [Object, nil] Server network or list of servers for cloning traffic.,It is a reference to an object of type trafficcloneprofile.,Field introduced in 17.1.1.\n attribute :traffic_clone_profile_ref\n\n # @return [Symbol, nil] Knob to enable the virtual service traffic on its assigned service engines.,This setting is effective only when the enabled flag is set to true.,Field introduced in 17.2.8.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :traffic_enabled\n validates :traffic_enabled, type: Symbol\n\n # @return [String, nil] Specify if this is a normal virtual service, or if it is the parent or child of an sni-enabled virtual hosted virtual service.,Enum options - VS_TYPE_NORMAL, VS_TYPE_VH_PARENT, VS_TYPE_VH_CHILD.,Default value when not specified in API or module is interpreted by Avi Controller as VS_TYPE_NORMAL.\n attribute :type\n validates :type, type: String\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Symbol, nil] Use bridge ip as vip on each host in mesos deployments.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :use_bridge_ip_as_vip\n validates :use_bridge_ip_as_vip, type: Symbol\n\n # @return [Symbol, nil] Use the virtual ip as the snat ip for health monitoring and sending traffic to the backend servers instead of the service engine interface ip.,The caveat of enabling this option is that the virtualservice cannot be configued in an active-active ha mode.,Dns based multi vip solution has to be used for ha & non-disruptive upgrade purposes.,Field introduced in 17.1.9,17.2.3.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :use_vip_as_snat\n validates :use_vip_as_snat, type: Symbol\n\n # @return [Object, nil] Uuid of the virtualservice.\n attribute :uuid\n\n # @return [Object, nil] The exact name requested from the client's sni-enabled tls hello domain name field.,If this is a match, the parent vs will forward the connection to this child vs.\n attribute :vh_domain_name\n\n # @return [Object, nil] Specifies the virtual service acting as virtual hosting (sni) parent.\n attribute :vh_parent_vs_uuid\n\n # @return [Object, nil] List of virtual service ips.,While creating a 'shared vs',please use vsvip_ref to point to the shared entities.,Field introduced in 17.1.1.\n attribute :vip\n\n # @return [Object, nil] Virtual routing context that the virtual service is bound to.,This is used to provide the isolation of the set of networks the application is attached to.,It is a reference to an object of type vrfcontext.\n attribute :vrf_context_ref\n\n # @return [Object, nil] Datascripts applied on the data traffic of the virtual service.\n attribute :vs_datascripts\n\n # @return [Object, nil] Mostly used during the creation of shared vs, this field refers to entities that can be shared across virtual services.,It is a reference to an object of type vsvip.,Field introduced in 17.1.1.\n attribute :vsvip_ref\n\n # @return [Object, nil] Waf policy for the virtual service.,It is a reference to an object of type wafpolicy.,Field introduced in 17.2.1.\n attribute :waf_policy_ref\n\n # @return [Object, nil] The quality of service weight to assign to traffic transmitted from this virtual service.,A higher weight will prioritize traffic versus other virtual services sharing the same service engines.,Allowed values are 1-128.,Default value when not specified in API or module is interpreted by Avi Controller as 1.\n attribute :weight\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6793286204338074, "alphanum_fraction": 0.6810954213142395, "avg_line_length": 38.034481048583984, "blob_id": "9836e2e95f108b65a7c7b05104491052dac448b7", "content_id": "1b1816c70dee693dcb7eb27a6a9b1a539d403171", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1132, "license_type": "permissive", "max_line_length": 145, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_igmp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages IGMP global configuration configuration settings.\n class Nxos_igmp < Base\n # @return [Symbol, nil] Removes routes when the IGMP process is restarted. By default, routes are not flushed.\n attribute :flush_routes\n validates :flush_routes, type: Symbol\n\n # @return [Symbol, nil] Enables or disables the enforce router alert option check for IGMPv2 and IGMPv3 packets.\n attribute :enforce_rtr_alert\n validates :enforce_rtr_alert, type: Symbol\n\n # @return [Symbol, nil] Restarts the igmp process (using an exec config command).\n attribute :restart\n validates :restart, type: Symbol\n\n # @return [:present, :default, nil] Manages desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :default], :message=>\"%{value} needs to be :present, :default\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7214235067367554, "alphanum_fraction": 0.7242704629898071, "avg_line_length": 73.73403930664062, "blob_id": "99644766346c394c5b7006da42fa6bf59f1ab0d4", "content_id": "3b931286368464776a5790a889bb5f582d9d8057", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 7025, "license_type": "permissive", "max_line_length": 647, "num_lines": 94, "path": "/lib/ansible/ruby/modules/generated/commands/psexec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Runs a remote command from a Linux host to a Windows host without WinRM being set up.\n # Can be run on the Ansible controller to bootstrap Windows hosts to get them ready for WinRM.\n class Psexec < Base\n # @return [String] The remote Windows host to connect to, can be either an IP address or a hostname.\n attribute :hostname\n validates :hostname, presence: true, type: String\n\n # @return [String, nil] The username to use when connecting to the remote Windows host.,This user must be a member of the C(Administrators) group of the Windows host.,Required if the Kerberos requirements are not installed or the username is a local account to the Windows host.,Can be omitted to use the default Kerberos principal ticket in the local credential cache if the Kerberos library is installed.,If I(process_username) is not specified, then the remote process will run under a Network Logon under this account.\n attribute :connection_username\n validates :connection_username, type: String\n\n # @return [String, nil] The password for I(connection_user).,Required if the Kerberos requirements are not installed or the username is a local account to the Windows host.,Can be omitted to use a Kerberos principal ticket for the principal set by I(connection_user) if the Kerberos library is installed and the ticket has already been retrieved with the C(kinit) command before.\n attribute :connection_password\n validates :connection_password, type: String\n\n # @return [Integer, nil] The port that the remote SMB service is listening on.\n attribute :port\n validates :port, type: Integer\n\n # @return [Boolean, nil] Will use SMB encryption to encrypt the SMB messages sent to and from the host.,This requires the SMB 3 protocol which is only supported from Windows Server 2012 or Windows 8, older versions like Windows 7 or Windows Server 2008 (R2) must set this to C(no) and use no encryption.,When setting to C(no), the packets are in plaintext and can be seen by anyone sniffing the network, any process options are included in this.\n attribute :encrypt\n validates :encrypt, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] The timeout in seconds to wait when receiving the initial SMB negotiate response from the server.\n attribute :connection_timeout\n validates :connection_timeout, type: String\n\n # @return [String] The executable to run on the Windows host.\n attribute :executable\n validates :executable, presence: true, type: String\n\n # @return [String, nil] Any arguments as a single string to use when running the executable.\n attribute :arguments\n validates :arguments, type: String\n\n # @return [String, nil] Changes the working directory set when starting the process.\n attribute :working_directory\n validates :working_directory, type: String\n\n # @return [Symbol, nil] Will run the command as a detached process and the module returns immediately after starting the processs while the process continues to run in the background.,The I(stdout) and I(stderr) return values will be null when this is set to C(yes).,The I(stdin) option does not work with this type of process.,The I(rc) return value is not set when this is C(yes)\n attribute :asynchronous\n validates :asynchronous, type: Symbol\n\n # @return [Boolean, nil] Runs the remote command with the user's profile loaded.\n attribute :load_profile\n validates :load_profile, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] The user to run the process as.,This can be set to run the process under an Interactive logon of the specified account which bypasses limitations of a Network logon used when this isn't specified.,If omitted then the process is run under the same account as I(connection_username) with a Network logon.,Set to C(System) to run as the builtin SYSTEM account, no password is required with this account.,If I(encrypt) is C(no), the username and password are sent as a simple XOR scrambled byte string that is not encrypted. No special tools are required to get the username and password just knowledge of the protocol.\n attribute :process_username\n validates :process_username, type: String\n\n # @return [String, nil] The password for I(process_username).,Required if I(process_username) is defined and not C(System).\n attribute :process_password\n validates :process_password, type: String\n\n # @return [String, nil] The integrity level of the process when I(process_username) is defined and is not equal to C(System).,When C(default), the default integrity level based on the system setup.,When C(elevated), the command will be run with Administrative rights.,When C(limited), the command will be forced to run with non-Administrative rights.\n attribute :integrity_level\n validates :integrity_level, type: String\n\n # @return [Symbol, nil] Will run the process as an interactive process that shows a process Window of the Windows session specified by I(interactive_session).,The I(stdout) and I(stderr) return values will be null when this is set to C(yes).,The I(stdin) option does not work with this type of process.\n attribute :interactive\n validates :interactive, type: Symbol\n\n # @return [Integer, nil] The Windows session ID to use when displaying the interactive process on the remote Windows host.,This is only valid when I(interactive) is C(yes).,The default is C(0) which is the console session of the Windows host.\n attribute :interactive_session\n validates :interactive_session, type: Integer\n\n # @return [String, nil] Set the command's priority on the Windows host.,See U(https://msdn.microsoft.com/en-us/library/windows/desktop/ms683211.aspx) for more details.\n attribute :priority\n validates :priority, type: String\n\n # @return [Symbol, nil] Shows the process UI on the Winlogon secure desktop when I(process_username) is C(System).\n attribute :show_ui_on_logon_screen\n validates :show_ui_on_logon_screen, type: Symbol\n\n # @return [Integer, nil] The timeout in seconds that is placed upon the running process.,A value of C(0) means no timeout.\n attribute :process_timeout\n validates :process_timeout, type: Integer\n\n # @return [String, nil] Data to send on the stdin pipe once the process has started.,This option has no effect when I(interactive) or I(asynchronous) is C(yes).\n attribute :stdin\n validates :stdin, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6721311211585999, "alphanum_fraction": 0.6727166175842285, "avg_line_length": 46.44444274902344, "blob_id": "9648aa322eb01a16bc06660291f096f72379bfb5", "content_id": "e1bafa7936d190f6cb2311ba4a9fc818b7456b70", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1708, "license_type": "permissive", "max_line_length": 204, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/storage/zfs/zfs_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gather facts from ZFS dataset properties.\n class Zfs_facts < Base\n # @return [String] ZFS dataset name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:yes, :no, nil] Specifies if properties for any children should be recursively displayed.\n attribute :recurse\n validates :recurse, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Specifies if property values should be displayed in machine friendly format.\n attribute :parsable\n validates :parsable, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Specifies which dataset properties should be queried in comma-separated format. For more information about dataset properties, check zfs(1M) man page.\n attribute :properties\n validates :properties, type: String\n\n # @return [:all, :filesystem, :volume, :snapshot, :bookmark, nil] Specifies which datasets types to display. Multiple values have to be provided in comma-separated form.\n attribute :type\n validates :type, expression_inclusion: {:in=>[:all, :filesystem, :volume, :snapshot, :bookmark], :message=>\"%{value} needs to be :all, :filesystem, :volume, :snapshot, :bookmark\"}, allow_nil: true\n\n # @return [Object, nil] Specifiies recurion depth.\n attribute :depth\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6815038323402405, "alphanum_fraction": 0.7057989239692688, "avg_line_length": 65.34117889404297, "blob_id": "0aa4a5889522876ecb8d8b7779450f53d26e87c0", "content_id": "0d3376688ea34359b385c3062b0a8c27de9d38e0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5639, "license_type": "permissive", "max_line_length": 344, "num_lines": 85, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_ospf_vrf.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages configuration of an OSPF VPN instance on HUAWEI CloudEngine switches.\n class Ce_ospf_vrf < Base\n # @return [Object] The ID of the ospf process. Valid values are an integer, 1 - 4294967295, the default value is 1.\n attribute :ospf\n validates :ospf, presence: true\n\n # @return [Object, nil] Specifies the ospf private route id,. Valid values are a string, formatted as an IP address (i.e. \"10.1.1.1\") the length is 0 - 20.\n attribute :route_id\n\n # @return [String, nil] Specifies the vpn instance which use ospf,length is 1 - 31. Valid values are a string.\n attribute :vrf\n validates :vrf, type: String\n\n # @return [Object, nil] Specifies the description information of ospf process.\n attribute :description\n\n # @return [Object, nil] Specifies the reference bandwidth used to assign ospf cost. Valid values are an integer, in Mbps, 1 - 2147483648, the default value is 100.\n attribute :bandwidth\n\n # @return [:yes, :no, nil] Specifies the mode of timer to calculate interval of arrive LSA. If set the parameter but not specifies value, the default will be used. If true use general timer. If false use intelligent timer.\n attribute :lsaalflag\n validates :lsaalflag, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the interval of arrive LSA when use the general timer. Valid value is an integer, in millisecond, from 0 to 10000.\n attribute :lsaainterval\n\n # @return [Object, nil] Specifies the max interval of arrive LSA when use the intelligent timer. Valid value is an integer, in millisecond, from 0 to 10000, the default value is 1000.\n attribute :lsaamaxinterval\n\n # @return [Object, nil] Specifies the start interval of arrive LSA when use the intelligent timer. Valid value is an integer, in millisecond, from 0 to 10000, the default value is 500.\n attribute :lsaastartinterval\n\n # @return [Object, nil] Specifies the hold interval of arrive LSA when use the intelligent timer. Valid value is an integer, in millisecond, from 0 to 10000, the default value is 500.\n attribute :lsaaholdinterval\n\n # @return [:yes, :no, nil] Specifies whether cancel the interval of LSA originate or not. If set the parameter but noe specifies value, the default will be used. true:cancel the interval of LSA originate, the interval is 0. false:do not cancel the interval of LSA originate.\n attribute :lsaointervalflag\n validates :lsaointervalflag, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the interval of originate LSA . Valid value is an integer, in second, from 0 to 10, the default value is 5.\n attribute :lsaointerval\n\n # @return [Object, nil] Specifies the max interval of originate LSA . Valid value is an integer, in millisecond, from 1 to 10000, the default value is 5000.\n attribute :lsaomaxinterval\n\n # @return [Object, nil] Specifies the start interval of originate LSA . Valid value is an integer, in millisecond, from 0 to 1000, the default value is 500.\n attribute :lsaostartinterval\n\n # @return [Object, nil] Specifies the hold interval of originate LSA . Valid value is an integer, in millisecond, from 0 to 5000, the default value is 1000.\n attribute :lsaoholdinterval\n\n # @return [:\"intelligent-timer\", :timer, :millisecond, nil] Specifies the mode of timer which used to calculate SPF. If set the parameter but noe specifies value, the default will be used. If is intelligent-timer, then use intelligent timer. If is timer, then use second level timer. If is millisecond, then use millisecond level timer.\n attribute :spfintervaltype\n validates :spfintervaltype, expression_inclusion: {:in=>[:\"intelligent-timer\", :timer, :millisecond], :message=>\"%{value} needs to be :\\\"intelligent-timer\\\", :timer, :millisecond\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the interval to calculate SPF when use second level timer. Valid value is an integer, in second, from 1 to 10.\n attribute :spfinterval\n\n # @return [Object, nil] Specifies the interval to calculate SPF when use millisecond level timer. Valid value is an integer, in millisecond, from 1 to 10000.\n attribute :spfintervalmi\n\n # @return [Object, nil] Specifies the max interval to calculate SPF when use intelligent timer. Valid value is an integer, in millisecond, from 1 to 20000, the default value is 5000.\n attribute :spfmaxinterval\n\n # @return [Object, nil] Specifies the start interval to calculate SPF when use intelligent timer. Valid value is an integer, in millisecond, from 1 to 1000, the default value is 50.\n attribute :spfstartinterval\n\n # @return [Object, nil] Specifies the hold interval to calculate SPF when use intelligent timer. Valid value is an integer, in millisecond, from 1 to 5000, the default value is 200.\n attribute :spfholdinterval\n\n # @return [:present, :absent, nil] Specify desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6769822835922241, "alphanum_fraction": 0.6769822835922241, "avg_line_length": 56.480770111083984, "blob_id": "f9d74b814eff0bd7f34db7e53b365c210c18a5b5", "content_id": "ccca19807595f0d6379230a5f7bb3371ada1825e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5978, "license_type": "permissive", "max_line_length": 619, "num_lines": 104, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gce_instance_template.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates or destroy Google instance templates of Compute Engine of Google Cloud Platform.\n class Gce_instance_template < Base\n # @return [:present, :absent, nil] The desired state for the instance template.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] The name of the GCE instance template.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] The desired machine type for the instance template.\n attribute :size\n validates :size, type: String\n\n # @return [Object, nil] A source disk to attach to the instance. Cannot specify both I(image) and I(source).\n attribute :source\n\n # @return [Object, nil] The image to use to create the instance. Cannot specify both both I(image) and I(source).\n attribute :image\n\n # @return [String, nil] The image family to use to create the instance. If I(image) has been used I(image_family) is ignored. Cannot specify both I(image) and I(source).\n attribute :image_family\n validates :image_family, type: String\n\n # @return [String, nil] Specify a C(pd-standard) disk or C(pd-ssd) for an SSD disk.\n attribute :disk_type\n validates :disk_type, type: String\n\n # @return [Boolean, nil] Indicate that the boot disk should be deleted when the Node is deleted.\n attribute :disk_auto_delete\n validates :disk_auto_delete, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] The network to associate with the instance.\n attribute :network\n validates :network, type: String\n\n # @return [Object, nil] The Subnetwork resource name for this instance.\n attribute :subnetwork\n\n # @return [:yes, :no, nil] Set to C(yes) to allow instance to send/receive non-matching src/dst packets.\n attribute :can_ip_forward\n validates :can_ip_forward, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] The external IP address to use. If C(ephemeral), a new non-static address will be used. If C(None), then no external address will be used. To use an existing static IP address specify address name.\n attribute :external_ip\n validates :external_ip, type: String\n\n # @return [String, nil] service account email\n attribute :service_account_email\n validates :service_account_email, type: String\n\n # @return [:bigquery, :\"cloud-platform\", :\"compute-ro\", :\"compute-rw\", :\"useraccounts-ro\", :\"useraccounts-rw\", :datastore, :\"logging-write\", :monitoring, :\"sql-admin\", :\"storage-full\", :\"storage-ro\", :\"storage-rw\", :taskqueue, :\"userinfo-email\", nil] service account permissions (see U(https://cloud.google.com/sdk/gcloud/reference/compute/instances/create), --scopes section for detailed information)\n attribute :service_account_permissions\n validates :service_account_permissions, expression_inclusion: {:in=>[:bigquery, :\"cloud-platform\", :\"compute-ro\", :\"compute-rw\", :\"useraccounts-ro\", :\"useraccounts-rw\", :datastore, :\"logging-write\", :monitoring, :\"sql-admin\", :\"storage-full\", :\"storage-ro\", :\"storage-rw\", :taskqueue, :\"userinfo-email\"], :message=>\"%{value} needs to be :bigquery, :\\\"cloud-platform\\\", :\\\"compute-ro\\\", :\\\"compute-rw\\\", :\\\"useraccounts-ro\\\", :\\\"useraccounts-rw\\\", :datastore, :\\\"logging-write\\\", :monitoring, :\\\"sql-admin\\\", :\\\"storage-full\\\", :\\\"storage-ro\\\", :\\\"storage-rw\\\", :taskqueue, :\\\"userinfo-email\\\"\"}, allow_nil: true\n\n # @return [Object, nil] Defines whether the instance should be automatically restarted when it is terminated by Compute Engine.\n attribute :automatic_restart\n\n # @return [Object, nil] Defines whether the instance is preemptible.\n attribute :preemptible\n\n # @return [Object, nil] a comma-separated list of tags to associate with the instance\n attribute :tags\n\n # @return [Object, nil] a hash/dictionary of custom data for the instance; '{\"key\":\"value\", ...}'\n attribute :metadata\n\n # @return [Object, nil] description of instance template\n attribute :description\n\n # @return [Object, nil] a list of persistent disks to attach to the instance; a string value gives the name of the disk; alternatively, a dictionary value can define 'name' and 'mode' ('READ_ONLY' or 'READ_WRITE'). The first entry will be the boot disk (which must be READ_WRITE).\n attribute :disks\n\n # @return [Object, nil] Support passing in the GCE-specific formatted networkInterfaces[] structure.\n attribute :nic_gce_struct\n\n # @return [Object, nil] Support passing in the GCE-specific formatted formatted disks[] structure. Case sensitive. see U(https://cloud.google.com/compute/docs/reference/latest/instanceTemplates#resource) for detailed information\n attribute :disks_gce_struct\n\n # @return [String, nil] your GCE project ID\n attribute :project_id\n validates :project_id, type: String\n\n # @return [Object, nil] path to the pem file associated with the service account email This option is deprecated. Use 'credentials_file'.\n attribute :pem_file\n\n # @return [String, nil] path to the JSON file associated with the service account email\n attribute :credentials_file\n validates :credentials_file, type: String\n\n # @return [Object, nil] Region that subnetwork resides in. (Required for subnetwork to successfully complete)\n attribute :subnetwork_region\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.707789957523346, "alphanum_fraction": 0.7107069492340088, "avg_line_length": 55.582523345947266, "blob_id": "888fa0139d915b7e1280e9c416d8320d91c1ad4e", "content_id": "a01fb2af10ba63d1ad7c038a90aa532e411649e7", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5828, "license_type": "permissive", "max_line_length": 381, "num_lines": 103, "path": "/lib/ansible/ruby/modules/generated/crypto/openssl_csr.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows one to (re)generate OpenSSL certificate signing requests. It uses the pyOpenSSL python library to interact with openssl. This module supports the subjectAltName, keyUsage, extendedKeyUsage, basicConstraints and OCSP Must Staple extensions.\n class Openssl_csr < Base\n # @return [:present, :absent, nil] Whether the certificate signing request should exist or not, taking action if the state is different from what is stated.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Digest used when signing the certificate signing request with the private key\n attribute :digest\n validates :digest, type: String\n\n # @return [String] Path to the privatekey to use when signing the certificate signing request\n attribute :privatekey_path\n validates :privatekey_path, presence: true, type: String\n\n # @return [String, nil] The passphrase for the privatekey.\n attribute :privatekey_passphrase\n validates :privatekey_passphrase, type: String\n\n # @return [Integer, nil] Version of the certificate signing request\n attribute :version\n validates :version, type: Integer\n\n # @return [Symbol, nil] Should the certificate signing request be forced regenerated by this ansible module\n attribute :force\n validates :force, type: Symbol\n\n # @return [String] Name of the file into which the generated OpenSSL certificate signing request will be written\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [Object, nil] Key/value pairs that will be present in the subject name field of the certificate signing request.,If you need to specify more than one value with the same key, use a list as value.\n attribute :subject\n\n # @return [String, nil] countryName field of the certificate signing request subject\n attribute :country_name\n validates :country_name, type: String\n\n # @return [Object, nil] stateOrProvinceName field of the certificate signing request subject\n attribute :state_or_province_name\n\n # @return [Object, nil] localityName field of the certificate signing request subject\n attribute :locality_name\n\n # @return [String, nil] organizationName field of the certificate signing request subject\n attribute :organization_name\n validates :organization_name, type: String\n\n # @return [Object, nil] organizationalUnitName field of the certificate signing request subject\n attribute :organizational_unit_name\n\n # @return [String, nil] commonName field of the certificate signing request subject\n attribute :common_name\n validates :common_name, type: String\n\n # @return [String, nil] emailAddress field of the certificate signing request subject\n attribute :email_address\n validates :email_address, type: String\n\n # @return [Array<String>, String, nil] SAN extension to attach to the certificate signing request,This can either be a 'comma separated string' or a YAML list.,Values should be prefixed by their options. (i.e., C(email), C(URI), C(DNS), C(RID), C(IP), C(dirName), C(otherName) and the ones specific to your CA),More at U(https://tools.ietf.org/html/rfc5280#section-4.2.1.6)\n attribute :subject_alt_name\n validates :subject_alt_name, type: TypeGeneric.new(String)\n\n # @return [Object, nil] Should the subjectAltName extension be considered as critical\n attribute :subject_alt_name_critical\n\n # @return [Array<String>, String, nil] This defines the purpose (e.g. encipherment, signature, certificate signing) of the key contained in the certificate.,This can either be a 'comma separated string' or a YAML list.\n attribute :key_usage\n validates :key_usage, type: TypeGeneric.new(String)\n\n # @return [Object, nil] Should the keyUsage extension be considered as critical\n attribute :key_usage_critical\n\n # @return [Array<String>, String, nil] Additional restrictions (e.g. client authentication, server authentication) on the allowed purposes for which the public key may be used.,This can either be a 'comma separated string' or a YAML list.\n attribute :extended_key_usage\n validates :extended_key_usage, type: TypeGeneric.new(String)\n\n # @return [Object, nil] Should the extkeyUsage extension be considered as critical\n attribute :extended_key_usage_critical\n\n # @return [Object, nil] Indicates basic constraints, such as if the certificate is a CA.\n attribute :basic_constraints\n\n # @return [Object, nil] Should the basicConstraints extension be considered as critical\n attribute :basic_constraints_critical\n\n # @return [Boolean, nil] Indicates that the certificate should contain the OCSP Must Staple extension (U(https://tools.ietf.org/html/rfc7633)).\n attribute :ocsp_must_staple\n validates :ocsp_must_staple, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] Should the OCSP Must Staple extension be considered as critical,Warning: according to the RFC, this extension should not be marked as critical, as old clients not knowing about OCSP Must Staple are required to reject such certificates (see U(https://tools.ietf.org/html/rfc7633#section-4)).\n attribute :ocsp_must_staple_critical\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6418250799179077, "alphanum_fraction": 0.6418250799179077, "avg_line_length": 25.299999237060547, "blob_id": "4420609b9382f51cc6512842b52da2adde90d8b6", "content_id": "63dc5f2db4aa959a0c1391c60584c36b42e6ebeb", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1315, "license_type": "permissive", "max_line_length": 124, "num_lines": 50, "path": "/lib/ansible/ruby/models/expression_inclusion_validator_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# See LICENSE.txt for license\nrequire 'spec_helper'\nrequire 'ansible/ruby/models/base'\n\ndescribe ExpressionInclusionValidator do\n before { stub_const 'Ansible::Ruby::TypeValTestModel', klass }\n\n subject { instance }\n\n let(:klass) do\n Class.new(Ansible::Ruby::Models::Base) do\n attribute :foo\n validates :foo, expression_inclusion: { in: %i[yes no] }, allow_nil: true\n end\n end\n\n context 'passes' do\n let(:instance) { klass.new foo: :yes }\n\n it { is_expected.to be_valid }\n end\n\n context 'fails' do\n let(:instance) { klass.new foo: :nope }\n\n it { is_expected.to_not be_valid }\n it { is_expected.to have_errors foo: 'nope needs to be [:yes, :no]' }\n end\n\n context 'custom error' do\n let(:klass) do\n Class.new(Ansible::Ruby::Models::Base) do\n attribute :foo\n validates :foo, expression_inclusion: { in: %i[yes no], message: '%{value} needs to be :yes, :no' }, allow_nil: true\n end\n end\n let(:instance) { klass.new foo: :nope }\n\n it { is_expected.to_not be_valid }\n it { is_expected.to have_errors foo: 'nope needs to be :yes, :no' }\n end\n\n context 'Jinja expression' do\n let(:instance) { klass.new foo: Ansible::Ruby::Models::JinjaExpression.new('howdy') }\n\n it { is_expected.to be_valid }\n end\nend\n" }, { "alpha_fraction": 0.6797829270362854, "alphanum_fraction": 0.6797829270362854, "avg_line_length": 53.592594146728516, "blob_id": "d3d24a46e15a33548a041053032970ce365b8893", "content_id": "ec141bfc94a71fe29e4e415ad9fdf680f8442295", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2948, "license_type": "permissive", "max_line_length": 194, "num_lines": 54, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_ironic_node.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Deploy to nodes controlled by Ironic.\n class Os_ironic_node < Base\n # @return [:present, :absent, nil] Indicates desired state of the resource\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Indicates if the resource should be deployed. Allows for deployment logic to be disengaged and control of the node power or maintenance state to be changed.\n attribute :deploy\n validates :deploy, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] globally unique identifier (UUID) to be given to the resource.\n attribute :uuid\n\n # @return [Object, nil] If noauth mode is utilized, this is required to be set to the endpoint URL for the Ironic API. Use with \"auth\" and \"auth_type\" settings set to None.\n attribute :ironic_url\n\n # @return [Object, nil] A configdrive file or HTTP(S) URL that will be passed along to the node.\n attribute :config_drive\n\n # @return [Object, nil] Definition of the instance information which is used to deploy the node. This information is only required when an instance is set to present.\n attribute :instance_info\n\n # @return [:present, :absent, nil] A setting to allow power state to be asserted allowing nodes that are not yet deployed to be powered on, and nodes that are deployed to be powered off.\n attribute :power\n validates :power, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:yes, :no, nil] A setting to allow the direct control if a node is in maintenance mode.\n attribute :maintenance\n validates :maintenance, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] A string expression regarding the reason a node is in a maintenance mode.\n attribute :maintenance_reason\n\n # @return [:yes, :no, nil] A boolean value instructing the module to wait for node activation or deactivation to complete before returning.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] An integer value representing the number of seconds to wait for the node activation or deactivation to complete.\n attribute :timeout\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6572504639625549, "alphanum_fraction": 0.674199640750885, "avg_line_length": 41.47999954223633, "blob_id": "60c9ec1430d8f619460c414f94c084a348b7a5ba", "content_id": "3189cb7419af17117b04ccfbb08d5b608e4e11ec", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1062, "license_type": "permissive", "max_line_length": 216, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_vrf_interface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages interface specific VPN configuration of HUAWEI CloudEngine switches.\n class Ce_vrf_interface < Base\n # @return [Object] VPN instance, the length of vrf name is 1 ~ 31, i.e. \"test\", but can not be C(_public_).\n attribute :vrf\n validates :vrf, presence: true\n\n # @return [Object] An interface that can binding VPN instance, i.e. 40GE1/0/22, Vlanif10. Must be fully qualified interface name. Interface types, such as 10GE, 40GE, 100GE, LoopBack, MEth, Tunnel, Vlanif....\n attribute :vpn_interface\n validates :vpn_interface, presence: true\n\n # @return [:present, :absent, nil] Manage the state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.653513491153717, "alphanum_fraction": 0.653513491153717, "avg_line_length": 38.36170196533203, "blob_id": "5926c539b7bc4daf7fcfa172bfe1b8ed86f9ccf0", "content_id": "9f9fd90bbb7d018557c2b1942a12eda87994e2b4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1850, "license_type": "permissive", "max_line_length": 143, "num_lines": 47, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_member.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or Remove a member for a pool from the OpenStack load-balancer service.\n class Os_member < Base\n # @return [String] Name that has to be given to the member\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Should the resource be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The name or id of the pool that this member belongs to.\n attribute :pool\n validates :pool, presence: true, type: String\n\n # @return [Integer, nil] The protocol port number for the member.\n attribute :protocol_port\n validates :protocol_port, type: Integer\n\n # @return [String, nil] The IP address of the member.\n attribute :address\n validates :address, type: String\n\n # @return [Object, nil] The subnet ID the member service is accessible from.\n attribute :subnet_id\n\n # @return [:yes, :no, nil] If the module should wait for the load balancer to be ACTIVE.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] The amount of time the module should wait for the load balancer to get into ACTIVE state.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.657731294631958, "alphanum_fraction": 0.6583850979804993, "avg_line_length": 61.42856979370117, "blob_id": "988a0cc0af445f1be80ed764384648b81f7ea0b5", "content_id": "3a9b68d30b5bd3cfc2e269fc984f6e2d8228d41a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3059, "license_type": "permissive", "max_line_length": 447, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/system/pam_limits.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The C(pam_limits) module modifies PAM limits. The default file is C(/etc/security/limits.conf). For the full documentation, see C(man 5 limits.conf).\n class Pam_limits < Base\n # @return [String] A username, @groupname, wildcard, uid/gid range.\n attribute :domain\n validates :domain, presence: true, type: String\n\n # @return [:hard, :soft, :-] Limit type, see C(man 5 limits.conf) for an explanation\n attribute :limit_type\n validates :limit_type, presence: true, expression_inclusion: {:in=>[:hard, :soft, :-], :message=>\"%{value} needs to be :hard, :soft, :-\"}\n\n # @return [:core, :data, :fsize, :memlock, :nofile, :rss, :stack, :cpu, :nproc, :as, :maxlogins, :maxsyslogins, :priority, :locks, :sigpending, :msgqueue, :nice, :rtprio, :chroot] The limit to be set\n attribute :limit_item\n validates :limit_item, presence: true, expression_inclusion: {:in=>[:core, :data, :fsize, :memlock, :nofile, :rss, :stack, :cpu, :nproc, :as, :maxlogins, :maxsyslogins, :priority, :locks, :sigpending, :msgqueue, :nice, :rtprio, :chroot], :message=>\"%{value} needs to be :core, :data, :fsize, :memlock, :nofile, :rss, :stack, :cpu, :nproc, :as, :maxlogins, :maxsyslogins, :priority, :locks, :sigpending, :msgqueue, :nice, :rtprio, :chroot\"}\n\n # @return [Integer, String] The value of the limit.\n attribute :value\n validates :value, presence: true, type: MultipleTypes.new(Integer, String)\n\n # @return [:yes, :no, nil] Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.\n attribute :backup\n validates :backup, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If set to C(yes), the minimal value will be used or conserved. If the specified value is inferior to the value in the file, file content is replaced with the new value, else content is not modified.\n attribute :use_min\n validates :use_min, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If set to C(yes), the maximal value will be used or conserved. If the specified value is superior to the value in the file, file content is replaced with the new value, else content is not modified.\n attribute :use_max\n validates :use_max, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Modify the limits.conf path.\n attribute :dest\n validates :dest, type: String\n\n # @return [String, nil] Comment associated with the limit.\n attribute :comment\n validates :comment, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6590189933776855, "alphanum_fraction": 0.6606012582778931, "avg_line_length": 38.5, "blob_id": "7fa7aae62484c27decf8889b72d5a3df2af662f9", "content_id": "7ab13178632d3076d2efde461e5df95086cc20da", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1264, "license_type": "permissive", "max_line_length": 145, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/source_control/bzr.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage I(bzr) branches to deploy files or software.\n class Bzr < Base\n # @return [String] SSH or HTTP protocol address of the parent branch.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] Absolute path of where the branch should be cloned to.\n attribute :dest\n validates :dest, presence: true, type: String\n\n # @return [String, nil] What version of the branch to clone. This can be the bzr revno or revid.\n attribute :version\n validates :version, type: String\n\n # @return [:yes, :no, nil] If C(yes), any modified files in the working tree will be discarded. Before 1.9 the default value was C(yes).\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Path to bzr executable to use. If not supplied, the normal mechanism for resolving binary paths will be used.\n attribute :executable\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7063062787055969, "alphanum_fraction": 0.7095094919204712, "avg_line_length": 67.4246597290039, "blob_id": "d4c3731718c489997eea6db922ca67cdb12a159b", "content_id": "7649ab7fb3bfcadbb4d9f6bc0482fc6aa13f269b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4995, "license_type": "permissive", "max_line_length": 330, "num_lines": 73, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/s3_lifecycle.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage s3 bucket lifecycle rules in AWS\n class S3_lifecycle < Base\n # @return [String] Name of the s3 bucket\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Indicates the lifetime of the objects that are subject to the rule by the date they will expire. The value must be ISO-8601 format, the time must be midnight and a GMT timezone must be specified.\\r\\n\n attribute :expiration_date\n validates :expiration_date, type: String\n\n # @return [Integer, nil] Indicates the lifetime, in days, of the objects that are subject to the rule. The value must be a non-zero positive integer.\n attribute :expiration_days\n validates :expiration_days, type: Integer\n\n # @return [String, nil] Prefix identifying one or more objects to which the rule applies. If no prefix is specified, the rule will apply to the whole bucket.\n attribute :prefix\n validates :prefix, type: String\n\n # @return [Boolean, nil] \"Whether to replace all the current transition(s) with the new transition(s). When false, the provided transition(s) will be added, replacing transitions with the same storage_class. When true, existing transitions will be removed and replaced with the new transition(s)\\r\\n\n attribute :purge_transitions\n validates :purge_transitions, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] Delete noncurrent versions this many days after they become noncurrent\n attribute :noncurrent_version_expiration_days\n\n # @return [:glacier, :onezone_ia, :standard_ia, nil] Transition noncurrent versions to this storage class\n attribute :noncurrent_version_storage_class\n validates :noncurrent_version_storage_class, expression_inclusion: {:in=>[:glacier, :onezone_ia, :standard_ia], :message=>\"%{value} needs to be :glacier, :onezone_ia, :standard_ia\"}, allow_nil: true\n\n # @return [Object, nil] Transition noncurrent versions this many days after they become noncurrent\n attribute :noncurrent_version_transition_days\n\n # @return [Object, nil] A list of transition behaviors to be applied to noncurrent versions for the rule. Each storage class may be used only once. Each transition behavior contains these elements\\r\\n I(transition_days)\\r\\n I(storage_class)\\r\\n\n attribute :noncurrent_version_transitions\n\n # @return [Object, nil] Unique identifier for the rule. The value cannot be longer than 255 characters. A unique value for the rule will be generated if no value is provided.\n attribute :rule_id\n\n # @return [:present, :absent, nil] Create or remove the lifecycle rule\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] If 'enabled', the rule is currently being applied. If 'disabled', the rule is not currently being applied.\n attribute :status\n validates :status, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:glacier, :onezone_ia, :standard_ia, nil] The storage class to transition to. Currently there are two supported values - 'glacier', 'onezone_ia', or 'standard_ia'.,The 'standard_ia' class is only being available from Ansible version 2.2.\n attribute :storage_class\n validates :storage_class, expression_inclusion: {:in=>[:glacier, :onezone_ia, :standard_ia], :message=>\"%{value} needs to be :glacier, :onezone_ia, :standard_ia\"}, allow_nil: true\n\n # @return [String, nil] Indicates the lifetime of the objects that are subject to the rule by the date they will transition to a different storage class. The value must be ISO-8601 format, the time must be midnight and a GMT timezone must be specified. If transition_days is not specified, this parameter is required.\"\\r\\n\n attribute :transition_date\n validates :transition_date, type: String\n\n # @return [Integer, nil] Indicates when, in days, an object transitions to a different storage class. If transition_date is not specified, this parameter is required.\n attribute :transition_days\n validates :transition_days, type: Integer\n\n # @return [Array<Hash>, Hash, nil] A list of transition behaviors to be applied to the rule. Each storage class may be used only once. Each transition behavior may contain these elements I(transition_days) I(transition_date) I(storage_class)\n attribute :transitions\n validates :transitions, type: TypeGeneric.new(Hash)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.666347086429596, "alphanum_fraction": 0.668264627456665, "avg_line_length": 49.878047943115234, "blob_id": "d36d0768473d2ecde3768a54d5c25224a9325600", "content_id": "e681d59218e91bc26ebb503a73d1a2cddc9eaea2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2086, "license_type": "permissive", "max_line_length": 266, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/commands/command.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The C(command) module takes the command name followed by a list of space-delimited arguments.\n # The given command will be executed on all selected nodes. It will not be processed through the shell, so variables like C($HOME) and operations like C(\"<\"), C(\">\"), C(\"|\"), C(\";\") and C(\"&\") will not work (use the M(shell) module if you need these features).\n # For Windows targets, use the M(win_command) module instead.\n class Command < Base\n # @return [Object] The command module takes a free form command to run. There is no parameter actually named 'free form'. See the examples!\n attribute :free_form\n validates :free_form, presence: true\n\n # @return [Array<String>, String, nil] Allows the user to provide the command as a list vs. a string. Only the string or the list form can be provided, not both. One or the other must be provided.\n attribute :argv\n validates :argv, type: TypeGeneric.new(String)\n\n # @return [String, nil] A filename or (since 2.0) glob pattern. If it already exists, this step B(won't) be run.\n attribute :creates\n validates :creates, type: String\n\n # @return [Object, nil] A filename or (since 2.0) glob pattern. If it already exists, this step B(will) be run.\n attribute :removes\n\n # @return [String, nil] Change into this directory before running the command.\n attribute :chdir\n validates :chdir, type: String\n\n # @return [:yes, :no, nil] If command_warnings are on in ansible.cfg, do not warn about this particular line if set to C(no).\n attribute :warn\n validates :warn, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Set the stdin of the command directly to the specified value.\n attribute :stdin\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6901535391807556, "alphanum_fraction": 0.6943691372871399, "avg_line_length": 58.30356979370117, "blob_id": "919bbf3fafdff7349cc6910af44b3f25cd60b7b9", "content_id": "219f1f43aa1e60c419fc9729657523485eda3fbf", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3321, "license_type": "permissive", "max_line_length": 553, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # maintains ec2 security groups. This module has a dependency on python-boto >= 2.5\n class Ec2_group < Base\n # @return [String, nil] Name of the security group.,One of and only one of I(name) or I(group_id) is required.,Required if I(state=present).\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] Id of group to delete (works only with absent).,One of and only one of I(name) or I(group_id) is required.\n attribute :group_id\n validates :group_id, type: String\n\n # @return [String, nil] Description of the security group. Required when C(state) is C(present).\n attribute :description\n validates :description, type: String\n\n # @return [String, Integer, nil] ID of the VPC to create the group in.\n attribute :vpc_id\n validates :vpc_id, type: MultipleTypes.new(String, Integer)\n\n # @return [Array<Hash>, Hash, nil] List of firewall inbound rules to enforce in this group (see example). If none are supplied, no inbound rules will be enabled. Rules list may include its own name in `group_name`. This allows idempotent loopback additions (e.g. allow group to access itself). Rule sources list support was added in version 2.4. This allows to define multiple sources per source type as well as multiple source types per rule. Prior to 2.4 an individual source is allowed. In version 2.5 support for rule descriptions was added.\n attribute :rules\n validates :rules, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash, nil] List of firewall outbound rules to enforce in this group (see example). If none are supplied, a default all-out rule is assumed. If an empty list is supplied, no outbound rules will be enabled. Rule Egress sources list support was added in version 2.4. In version 2.5 support for rule descriptions was added.\n attribute :rules_egress\n validates :rules_egress, type: TypeGeneric.new(Hash)\n\n # @return [:present, :absent, nil] Create or delete a security group\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Purge existing rules on security group that are not found in rules\n attribute :purge_rules\n validates :purge_rules, type: String\n\n # @return [String, nil] Purge existing rules_egress on security group that are not found in rules_egress\n attribute :purge_rules_egress\n validates :purge_rules_egress, type: String\n\n # @return [Object, nil] A dictionary of one or more tags to assign to the security group.\n attribute :tags\n\n # @return [Boolean, nil] If yes, existing tags will be purged from the resource to match exactly what is defined by I(tags) parameter. If the I(tags) parameter is not set then tags will not be modified.\n attribute :purge_tags\n validates :purge_tags, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6836518049240112, "alphanum_fraction": 0.6850672364234924, "avg_line_length": 54.05194854736328, "blob_id": "154af32f96b838108ab7f0c13255e26053cffee8", "content_id": "d1a82342f0416b27b2b2c05af500dffcf5d7e5f6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4239, "license_type": "permissive", "max_line_length": 537, "num_lines": 77, "path": "/lib/ansible/ruby/modules/generated/notification/mail.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is useful for sending emails from playbooks.\n # One may wonder why automate sending emails? In complex environments there are from time to time processes that cannot be automated, either because you lack the authority to make it so, or because not everyone agrees to a common approach.\n # If you cannot automate a specific step, but the step is non-blocking, sending out an email to the responsible party to make them perform their part of the bargain is an elegant way to put the responsibility in someone else's lap.\n # Of course sending out a mail can be equally useful as a way to notify one or more people in a team that a specific action has been (successfully) taken.\n class Mail < Base\n # @return [String, nil] The email-address the mail is sent from. May contain address and phrase.\n attribute :from\n validates :from, type: String\n\n # @return [String, nil] The email-address(es) the mail is being sent to.,This is a list, which may contain address and phrase portions.\n attribute :to\n validates :to, type: String\n\n # @return [String, nil] The email-address(es) the mail is being copied to.,This is a list, which may contain address and phrase portions.\n attribute :cc\n validates :cc, type: String\n\n # @return [Object, nil] The email-address(es) the mail is being 'blind' copied to.,This is a list, which may contain address and phrase portions.\n attribute :bcc\n\n # @return [String] The subject of the email being sent.\n attribute :subject\n validates :subject, presence: true, type: String\n\n # @return [String, nil] The body of the email being sent.\n attribute :body\n validates :body, type: String\n\n # @return [String, nil] If SMTP requires username.\n attribute :username\n validates :username, type: String\n\n # @return [String, nil] If SMTP requires password.\n attribute :password\n validates :password, type: String\n\n # @return [String, nil] The mail server.\n attribute :host\n validates :host, type: String\n\n # @return [Integer, nil] The mail server port.,This must be a valid integer between 1 and 65534\n attribute :port\n validates :port, type: Integer\n\n # @return [Object, nil] A list of pathnames of files to attach to the message.,Attached files will have their content-type set to C(application/octet-stream).\n attribute :attach\n\n # @return [Object, nil] A list of headers which should be added to the message.,Each individual header is specified as C(header=value) (see example below).\n attribute :headers\n\n # @return [String, nil] The character set of email being sent.\n attribute :charset\n validates :charset, type: String\n\n # @return [:html, :plain, nil] The minor mime type, can be either C(plain) or C(html).,The major type is always C(text).\n attribute :subtype\n validates :subtype, expression_inclusion: {:in=>[:html, :plain], :message=>\"%{value} needs to be :html, :plain\"}, allow_nil: true\n\n # @return [:always, :never, :starttls, :try, nil] If C(always), the connection will only send email if the connection is Encrypted. If the server doesn't accept the encrypted connection it will fail.,If C(try), the connection will attempt to setup a secure SSL/TLS session, before trying to send.,If C(never), the connection will not attempt to setup a secure SSL/TLS session, before sending,If C(starttls), the connection will try to upgrade to a secure SSL/TLS connection, before sending. If it is unable to do so it will fail.\n attribute :secure\n validates :secure, expression_inclusion: {:in=>[:always, :never, :starttls, :try], :message=>\"%{value} needs to be :always, :never, :starttls, :try\"}, allow_nil: true\n\n # @return [Integer, nil] Sets the timeout in seconds for connection attempts.\n attribute :timeout\n validates :timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6871249675750732, "alphanum_fraction": 0.6901779174804688, "avg_line_length": 62.751678466796875, "blob_id": "9e4da46a6df6ad27f72b2a91a835fc8fdc74ffef", "content_id": "2d8effcc92fdaf01d81e19c9c36b18840fb2fc1e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 9499, "license_type": "permissive", "max_line_length": 500, "num_lines": 149, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates or terminates ec2 instances.\n class Ec2 < Base\n # @return [String, nil] key pair to use on the instance\n attribute :key_name\n validates :key_name, type: String\n\n # @return [Object, nil] identifier for this instance or set of instances, so that the module will be idempotent with respect to EC2 instances. This identifier is valid for at least 24 hours after the termination of the instance, and should not be reused for another call later on. For details, see the description of client token at U(http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Run_Instance_Idempotency.html).\n attribute :id\n\n # @return [Array<String>, String, nil] security group (or list of groups) to use with the instance\n attribute :group\n validates :group, type: TypeGeneric.new(String)\n\n # @return [String, nil] security group id (or list of ids) to use with the instance\n attribute :group_id\n validates :group_id, type: String\n\n # @return [String, nil] The AWS region to use. Must be specified if ec2_url is not used. If not specified then the value of the EC2_REGION environment variable, if any, is used. See U(http://docs.aws.amazon.com/general/latest/gr/rande.html#ec2_region)\n attribute :region\n validates :region, type: String\n\n # @return [Object, nil] AWS availability zone in which to launch the instance\n attribute :zone\n\n # @return [String] instance type to use for the instance, see U(http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html)\n attribute :instance_type\n validates :instance_type, presence: true, type: String\n\n # @return [:default, :dedicated, nil] An instance with a tenancy of \"dedicated\" runs on single-tenant hardware and can only be launched into a VPC. Note that to use dedicated tenancy you MUST specify a vpc_subnet_id as well. Dedicated tenancy is not available for EC2 \"micro\" instances.\n attribute :tenancy\n validates :tenancy, expression_inclusion: {:in=>[:default, :dedicated], :message=>\"%{value} needs to be :default, :dedicated\"}, allow_nil: true\n\n # @return [Float, nil] Maximum spot price to bid, If not set a regular on-demand instance is requested. A spot request is made with this maximum bid. When it is filled, the instance is started.\n attribute :spot_price\n validates :spot_price, type: Float\n\n # @return [:\"one-time\", :persistent, nil] Type of spot request; one of \"one-time\" or \"persistent\". Defaults to \"one-time\" if not supplied.\n attribute :spot_type\n validates :spot_type, expression_inclusion: {:in=>[:\"one-time\", :persistent], :message=>\"%{value} needs to be :\\\"one-time\\\", :persistent\"}, allow_nil: true\n\n # @return [String] I(ami) ID to use for the instance\n attribute :image\n validates :image, presence: true, type: String\n\n # @return [Object, nil] kernel I(eki) to use for the instance\n attribute :kernel\n\n # @return [Object, nil] ramdisk I(eri) to use for the instance\n attribute :ramdisk\n\n # @return [:yes, :no, nil] wait for the instance to reach its desired state before returning. Does not wait for SSH, see 'wait_for_connection' example for details.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] how long before wait gives up, in seconds\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [Integer, nil] how long to wait for the spot instance request to be fulfilled\n attribute :spot_wait_timeout\n validates :spot_wait_timeout, type: Integer\n\n # @return [Integer, nil] number of instances to launch\n attribute :count\n validates :count, type: Integer\n\n # @return [:yes, :no, nil] enable detailed monitoring (CloudWatch) for instance\n attribute :monitoring\n validates :monitoring, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] opaque blob of data which is made available to the ec2 instance\n attribute :user_data\n\n # @return [Hash, nil] a hash/dictionary of tags to add to the new instance or for starting/stopping instance by tag; '{\"key\":\"value\"}' and '{\"key\":\"value\",\"key\":\"value\"}'\n attribute :instance_tags\n validates :instance_tags, type: Hash\n\n # @return [Object, nil] placement group for the instance when using EC2 Clustered Compute\n attribute :placement_group\n\n # @return [String, nil] the subnet ID in which to launch the instance (VPC)\n attribute :vpc_subnet_id\n validates :vpc_subnet_id, type: String\n\n # @return [Symbol, nil] when provisioning within vpc, assign a public IP address. Boto library must be 2.13.0+\n attribute :assign_public_ip\n validates :assign_public_ip, type: Symbol\n\n # @return [Object, nil] the private ip address to assign the instance (from the vpc subnet)\n attribute :private_ip\n\n # @return [Object, nil] Name of the IAM instance profile (i.e. what the EC2 console refers to as an \"IAM Role\") to use. Boto library must be 2.5.0+\n attribute :instance_profile_name\n\n # @return [Array<String>, String, nil] list of instance ids, currently used for states: absent, running, stopped\n attribute :instance_ids\n validates :instance_ids, type: TypeGeneric.new(String)\n\n # @return [Symbol, nil] Enable or Disable the Source/Destination checks (for NAT instances and Virtual Routers). When initially creating an instance the EC2 API defaults this to True.\n attribute :source_dest_check\n validates :source_dest_check, type: Symbol\n\n # @return [:yes, :no, nil] Enable or Disable the Termination Protection\n attribute :termination_protection\n validates :termination_protection, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:stop, :terminate, nil] Set whether AWS will Stop or Terminate an instance on shutdown. This parameter is ignored when using instance-store images (which require termination on shutdown).\n attribute :instance_initiated_shutdown_behavior\n validates :instance_initiated_shutdown_behavior, expression_inclusion: {:in=>[:stop, :terminate], :message=>\"%{value} needs to be :stop, :terminate\"}, allow_nil: true\n\n # @return [:present, :absent, :running, :restarted, :stopped, nil] create, terminate, start, stop or restart instances. The state 'restarted' was added in 2.2\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :running, :restarted, :stopped], :message=>\"%{value} needs to be :present, :absent, :running, :restarted, :stopped\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash, nil] a list of hash/dictionaries of volumes to add to the new instance; '[{\"key\":\"value\", \"key\":\"value\"}]'; keys allowed are - device_name (str; required), delete_on_termination (bool; False), device_type (deprecated), ephemeral (str), encrypted (bool; False), snapshot (str), volume_type (str), volume_size (int, GB), iops (int) - device_type is deprecated use volume_type, iops must be set when volume_type='io1', ephemeral and snapshot are mutually exclusive.\n attribute :volumes\n validates :volumes, type: TypeGeneric.new(Hash)\n\n # @return [String, nil] whether instance is using optimized EBS volumes, see U(http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSOptimized.html)\n attribute :ebs_optimized\n validates :ebs_optimized, type: String\n\n # @return [Integer, nil] An integer value which indicates how many instances that match the 'count_tag' parameter should be running. Instances are either created or terminated based on this value.\n attribute :exact_count\n validates :exact_count, type: Integer\n\n # @return [Hash, Array<String>, String, nil] Used with 'exact_count' to determine how many nodes based on a specific tag criteria should be running. This can be expressed in multiple ways and is shown in the EXAMPLES section. For instance, one can request 25 servers that are tagged with \"class=webserver\". The specified tag must already exist or be passed in as the 'instance_tags' option.\n attribute :count_tag\n validates :count_tag, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] A list of existing network interfaces to attach to the instance at launch. When specifying existing network interfaces, none of the assign_public_ip, private_ip, vpc_subnet_id, group, or group_id parameters may be used. (Those parameters are for creating a new network interface at launch.)\n attribute :network_interfaces\n validates :network_interfaces, type: TypeGeneric.new(String)\n\n # @return [String, nil] Launch group for spot request, see U(http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/how-spot-instances-work.html#spot-launch-group)\n attribute :spot_launch_group\n validates :spot_launch_group, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6526054739952087, "alphanum_fraction": 0.6526054739952087, "avg_line_length": 31.675676345825195, "blob_id": "9b45f5756b235408ed2293f443a6a495bf2de5cd", "content_id": "4dfadac9a7a9ae37c711af4264a64a06901e33d2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1209, "license_type": "permissive", "max_line_length": 138, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/packaging/os/rhn_channel.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Adds or removes Red Hat software channels.\n class Rhn_channel < Base\n # @return [String] Name of the software channel.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] Name of the system as it is known in RHN/Satellite.\n attribute :sysname\n validates :sysname, presence: true, type: String\n\n # @return [String, nil] Whether the channel should be present or not, taking action if the state is different from what is stated.\n attribute :state\n validates :state, type: String\n\n # @return [String] The full URL to the RHN/Satellite API.\n attribute :url\n validates :url, presence: true, type: String\n\n # @return [String] RHN/Satellite login.\n attribute :user\n validates :user, presence: true, type: String\n\n # @return [String] RHN/Satellite password.\n attribute :password\n validates :password, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6834692358970642, "alphanum_fraction": 0.6834692358970642, "avg_line_length": 39.878787994384766, "blob_id": "81ccbb5fd46fbb71eba0f0370b5bfa49b2846c40", "content_id": "de9fff0ec6a922d723194fddff41f554f86d523f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1349, "license_type": "permissive", "max_line_length": 151, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/windows/win_iis_virtualdirectory.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates, Removes and configures a virtual directory in IIS.\n class Win_iis_virtualdirectory < Base\n # @return [String] The name of the virtual directory to create or remove.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, nil] Whether to add or remove the specified virtual directory.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String] The site name under which the virtual directory is created or exists.\n attribute :site\n validates :site, presence: true, type: String\n\n # @return [String, nil] The application under which the virtual directory is created or exists.\n attribute :application\n validates :application, type: String\n\n # @return [String, nil] The physical path to the folder in which the new virtual directory is created.,The specified folder must already exist.\n attribute :physical_path\n validates :physical_path, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6818956732749939, "alphanum_fraction": 0.6818956732749939, "avg_line_length": 47.081966400146484, "blob_id": "b4b261d10970b95d892182e3a270b51fb4a32a04", "content_id": "c15d95278b757be57efda7da2c13b1569bdd7a57", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2933, "license_type": "permissive", "max_line_length": 210, "num_lines": 61, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/netapp_e_snapshot_volume.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, remove snapshot volumes for NetApp E/EF-Series storage arrays.\n class Netapp_e_snapshot_volume < Base\n # @return [String] The username to authenticate with the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_username\n validates :api_username, presence: true, type: String\n\n # @return [String] The password to authenticate with the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_password\n validates :api_password, presence: true, type: String\n\n # @return [String] The url to the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_url\n validates :api_url, presence: true, type: String\n\n # @return [Boolean, nil] Should https certificates be validated?\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String] storage array ID\n attribute :ssid\n validates :ssid, presence: true, type: String\n\n # @return [String] The identifier of the snapshot image used to create the new snapshot volume.,Note: You'll likely want to use the M(netapp_e_facts) module to find the ID of the image you want.\n attribute :snapshot_image_id\n validates :snapshot_image_id, presence: true, type: String\n\n # @return [Integer, nil] The repository utilization warning threshold percentage\n attribute :full_threshold\n validates :full_threshold, type: Integer\n\n # @return [String] The name you wish to give the snapshot volume\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:modeUnknown, :readWrite, :readOnly, :__UNDEFINED] The snapshot volume access mode\n attribute :view_mode\n validates :view_mode, presence: true, expression_inclusion: {:in=>[:modeUnknown, :readWrite, :readOnly, :__UNDEFINED], :message=>\"%{value} needs to be :modeUnknown, :readWrite, :readOnly, :__UNDEFINED\"}\n\n # @return [Integer, nil] The size of the view in relation to the size of the base volume\n attribute :repo_percentage\n validates :repo_percentage, type: Integer\n\n # @return [String] Name of the storage pool on which to allocate the repository volume.\n attribute :storage_pool_name\n validates :storage_pool_name, presence: true, type: String\n\n # @return [:absent, :present] Whether to create or remove the snapshot volume\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.699999988079071, "avg_line_length": 19, "blob_id": "ee8cf2a1493501d5c63c8bf234739015bd9b579a", "content_id": "565079b69386c790d5656434fb7afcb6754afa1c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 300, "license_type": "permissive", "max_line_length": 45, "num_lines": 15, "path": "/lib/ansible/ruby/modules/generated/windows/win_product_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Provides Windows product information.\n class Win_product_facts < Base\n\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6560062170028687, "alphanum_fraction": 0.6560062170028687, "avg_line_length": 35.628570556640625, "blob_id": "dfde4f25b5a5857df8e63dd3555b7772423accd5", "content_id": "4cd68cde24eec63d213baec01a1a5aef3d71cc95", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1282, "license_type": "permissive", "max_line_length": 172, "num_lines": 35, "path": "/lib/ansible/ruby/modules/generated/notification/grove.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The C(grove) module sends a message for a service to a Grove.io channel.\n class Grove < Base\n # @return [String] Token of the channel to post to.\n attribute :channel_token\n validates :channel_token, presence: true, type: String\n\n # @return [String, nil] Name of the service (displayed as the \"user\" in the message)\n attribute :service\n validates :service, type: String\n\n # @return [String] Message content\n attribute :message\n validates :message, presence: true, type: String\n\n # @return [Object, nil] Service URL for the web client\n attribute :url\n\n # @return [Object, nil] Icon for the service\n attribute :icon_url\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.684380054473877, "alphanum_fraction": 0.684380054473877, "avg_line_length": 63.24137878417969, "blob_id": "cf0e9f36db45af7be26700d6e0b0dbece9171788", "content_id": "e62779b1456368e35beb15b34a9bcbbd0052eb49", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1863, "license_type": "permissive", "max_line_length": 428, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/remote_management/manageiq/manageiq_policies.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The manageiq_policies module supports adding and deleting policy_profiles in ManageIQ.\n class Manageiq_policies < Base\n # @return [:absent, :present, :list, nil] absent - policy_profiles should not exist,,present - policy_profiles should exist,,list - list current policy_profiles and policies.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :list], :message=>\"%{value} needs to be :absent, :present, :list\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash, nil] list of dictionaries, each includes the policy_profile 'name' key.,required if state is present or absent.\n attribute :policy_profiles\n validates :policy_profiles, type: TypeGeneric.new(Hash)\n\n # @return [:provider, :host, :vm, :blueprint, :category, :cluster, :\"data store\", :group, :\"resource pool\", :service, :\"service template\", :template, :tenant, :user] the type of the resource to which the profile should be [un]assigned\n attribute :resource_type\n validates :resource_type, presence: true, expression_inclusion: {:in=>[:provider, :host, :vm, :blueprint, :category, :cluster, :\"data store\", :group, :\"resource pool\", :service, :\"service template\", :template, :tenant, :user], :message=>\"%{value} needs to be :provider, :host, :vm, :blueprint, :category, :cluster, :\\\"data store\\\", :group, :\\\"resource pool\\\", :service, :\\\"service template\\\", :template, :tenant, :user\"}\n\n # @return [String] the name of the resource to which the profile should be [un]assigned\n attribute :resource_name\n validates :resource_name, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6633249521255493, "alphanum_fraction": 0.664160430431366, "avg_line_length": 35.272727966308594, "blob_id": "6b982ff7c7c1da224899810ca59fc738b6512c24", "content_id": "b51f26a0b506bb3d9bf341f0187fccccfbcd38bb", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1197, "license_type": "permissive", "max_line_length": 204, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/cloud/rackspace/rax_cdb_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # create / delete a database in the Cloud Databases.\n class Rax_cdb_user < Base\n # @return [Object, nil] The databases server UUID\n attribute :cdb_id\n\n # @return [Object, nil] Name of the database user\n attribute :db_username\n\n # @return [Object, nil] Database user password\n attribute :db_password\n\n # @return [Object, nil] Name of the databases that the user can access\n attribute :databases\n\n # @return [String, nil] Specifies the host from which a user is allowed to connect to the database. Possible values are a string containing an IPv4 address or \"%\" to allow connecting from any host\n attribute :host\n validates :host, type: String\n\n # @return [:present, :absent, nil] Indicate desired state of the resource\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.675000011920929, "alphanum_fraction": 0.675000011920929, "avg_line_length": 36.57575607299805, "blob_id": "586e2679495465631d5480c2c69e4556a02299bf", "content_id": "12ac4d1593faf7c5e25aca84cefcd006e330276d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1240, "license_type": "permissive", "max_line_length": 143, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/cloud/webfaction/webfaction_mailbox.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove mailboxes on a Webfaction account. Further documentation at https://github.com/quentinsf/ansible-webfaction.\n class Webfaction_mailbox < Base\n # @return [String] The name of the mailbox\n attribute :mailbox_name\n validates :mailbox_name, presence: true, type: String\n\n # @return [String] The password for the mailbox\n attribute :mailbox_password\n validates :mailbox_password, presence: true, type: String\n\n # @return [:present, :absent, nil] Whether the mailbox should exist\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The webfaction account to use\n attribute :login_name\n validates :login_name, presence: true, type: String\n\n # @return [String] The webfaction password to use\n attribute :login_password\n validates :login_password, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6591276526451111, "alphanum_fraction": 0.6591276526451111, "avg_line_length": 28.4761905670166, "blob_id": "1fa83d2117c11f0892b09b9cdee2d43e815dcc07", "content_id": "21296e2fffcd307cfe93536a6f22394be2b777ae", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 619, "license_type": "permissive", "max_line_length": 119, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_node.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Rename an ONTAP node.\n class Na_ontap_node < Base\n # @return [String] The new name for the node\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] The name of the node to be renamed. If I(name) already exists, no action will be performed.\n attribute :from_name\n validates :from_name, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6587344408035278, "alphanum_fraction": 0.6592752933502197, "avg_line_length": 39.19565200805664, "blob_id": "43acbea1225cc557bcbb76cf68ea771eead5632a", "content_id": "7ea2b3edcde8c82ee03ecbb38986fc34891a942c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1849, "license_type": "permissive", "max_line_length": 198, "num_lines": 46, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_snmp_community.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages SNMP community configuration on HUAWEI CloudEngine switches.\n class Ce_snmp_community < Base\n # @return [Object, nil] Access control list number.\n attribute :acl_number\n\n # @return [Object, nil] Unique name to identify the community.\n attribute :community_name\n\n # @return [:read, :write, nil] Access right read or write.\n attribute :access_right\n validates :access_right, expression_inclusion: {:in=>[:read, :write], :message=>\"%{value} needs to be :read, :write\"}, allow_nil: true\n\n # @return [Object, nil] Mib view name.\n attribute :community_mib_view\n\n # @return [Object, nil] Unique name to identify the SNMPv3 group.\n attribute :group_name\n\n # @return [:noAuthNoPriv, :authentication, :privacy, nil] Security level indicating whether to use authentication and encryption.\n attribute :security_level\n validates :security_level, expression_inclusion: {:in=>[:noAuthNoPriv, :authentication, :privacy], :message=>\"%{value} needs to be :noAuthNoPriv, :authentication, :privacy\"}, allow_nil: true\n\n # @return [Object, nil] Mib view name for read.\n attribute :read_view\n\n # @return [Object, nil] Mib view name for write.\n attribute :write_view\n\n # @return [Object, nil] Mib view name for notification.\n attribute :notify_view\n\n # @return [:present, :absent, nil] Manage the state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7184535264968872, "alphanum_fraction": 0.7206013798713684, "avg_line_length": 65.51190185546875, "blob_id": "ec72bf0d0bf706f5ac5ebd6ff7465cb52ed90576", "content_id": "5afb055b9e1e9c43d07acadd800fb028c9d5ec34", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5587, "license_type": "permissive", "max_line_length": 312, "num_lines": 84, "path": "/lib/ansible/ruby/modules/generated/network/ios/ios_vrf.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of VRF definitions on Cisco IOS devices. It allows playbooks to manage individual or the entire VRF collection. It also supports purging VRF definitions from the configuration that are not explicitly defined.\n class Ios_vrf < Base\n # @return [Array<String>, String, nil] The set of VRF definition objects to be configured on the remote IOS device. Ths list entries can either be the VRF name or a hash of VRF definitions and attributes. This argument is mutually exclusive with the C(name) argument.\n attribute :vrfs\n validates :vrfs, type: TypeGeneric.new(String)\n\n # @return [String, nil] The name of the VRF definition to be managed on the remote IOS device. The VRF definition name is an ASCII string name used to uniquely identify the VRF. This argument is mutually exclusive with the C(vrfs) argument\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] Provides a short description of the VRF definition in the current active configuration. The VRF definition value accepts alphanumeric characters used to provide additional information about the VRF.\n attribute :description\n validates :description, type: String\n\n # @return [String, nil] The router-distinguisher value uniquely identifies the VRF to routing processes on the remote IOS system. The RD value takes the form of C(A:B) where C(A) and C(B) are both numeric values.\n attribute :rd\n validates :rd, type: String\n\n # @return [Array<String>, String, nil] Identifies the set of interfaces that should be configured in the VRF. Interfaces must be routed interfaces in order to be placed into a VRF.\n attribute :interfaces\n validates :interfaces, type: TypeGeneric.new(String)\n\n # @return [Object, nil] This is a intent option and checks the operational state of the for given vrf C(name) for associated interfaces. If the value in the C(associated_interfaces) does not match with the operational state of vrf interfaces on device it will result in failure.\n attribute :associated_interfaces\n\n # @return [Integer, nil] Time in seconds to wait before checking for the operational state on remote device.\n attribute :delay\n validates :delay, type: Integer\n\n # @return [Boolean, nil] Instructs the module to consider the VRF definition absolute. It will remove any previously configured VRFs on the device.\n attribute :purge\n validates :purge, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Configures the state of the VRF definition as it relates to the device operational configuration. When set to I(present), the VRF should be configured in the device active configuration and when set to I(absent) the VRF should not be in the device active configuration\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] Adds an export and import list of extended route target communities to the VRF.\n attribute :route_both\n validates :route_both, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] Adds an export list of extended route target communities to the VRF.\n attribute :route_export\n validates :route_export, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] Adds an import list of extended route target communities to the VRF.\n attribute :route_import\n validates :route_import, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] Adds an export and import list of extended route target communities in address-family configuration submode to the VRF.\n attribute :route_both_ipv4\n validates :route_both_ipv4, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] Adds an export list of extended route target communities in address-family configuration submode to the VRF.\n attribute :route_export_ipv4\n validates :route_export_ipv4, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] Adds an import list of extended route target communities in address-family configuration submode to the VRF.\n attribute :route_import_ipv4\n validates :route_import_ipv4, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] Adds an export and import list of extended route target communities in address-family configuration submode to the VRF.\n attribute :route_both_ipv6\n validates :route_both_ipv6, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] Adds an export list of extended route target communities in address-family configuration submode to the VRF.\n attribute :route_export_ipv6\n validates :route_export_ipv6, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] Adds an import list of extended route target communities in address-family configuration submode to the VRF.\n attribute :route_import_ipv6\n validates :route_import_ipv6, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6582506895065308, "alphanum_fraction": 0.6609557867050171, "avg_line_length": 43.36000061035156, "blob_id": "e40910155a7fae4c26b59d7abbc7df384a6d8553", "content_id": "3d17f912ea33a4cbc46a1bec042e980650c1f18c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1109, "license_type": "permissive", "max_line_length": 161, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/packaging/os/pkg5.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # IPS packages are the native packages in Solaris 11 and higher.\n class Pkg5 < Base\n # @return [Array<String>, String] An FRMI of the package(s) to be installed/removed/updated.,Multiple packages may be specified, separated by C(,).\n attribute :name\n validates :name, presence: true, type: TypeGeneric.new(String)\n\n # @return [:absent, :latest, :present, nil] Whether to install (I(present), I(latest)), or remove (I(absent)) a package.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :latest, :present], :message=>\"%{value} needs to be :absent, :latest, :present\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Accept any licences.\n attribute :accept_licenses\n validates :accept_licenses, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6841822862625122, "alphanum_fraction": 0.6873994469642639, "avg_line_length": 55.51515197753906, "blob_id": "77f73bab8629e5c30f72e4d9a8aff07ce5f64e40", "content_id": "4f4c6262dc5de2d60a260011603727e5baf93833", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1865, "license_type": "permissive", "max_line_length": 301, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/remote_management/ucs/ucs_storage_profile.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configures storage profiles on Cisco UCS Manager.\n # Examples can be used with the L(UCS Platform Emulator,https://communities.cisco.com/ucspe).\n class Ucs_storage_profile < Base\n # @return [:absent, :present, nil] If C(present), will verify that the storage profile is present and will create if needed.,If C(absent), will verify that the storage profile is absent and will delete if needed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String] The name of the storage profile.,This name can be between 1 and 16 alphanumeric characters.,You cannot use spaces or any special characters other than - (hyphen), \"_\" (underscore), : (colon), and . (period).,You cannot change this name after profile is created.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] The user-defined description of the storage profile.,Enter up to 256 characters.,You can use any characters or spaces except the following:,` (accent mark), (backslash), ^ (carat), \" (double quote), = (equal sign), > (greater than), < (less than), or ' (single quote).\n attribute :description\n\n # @return [Array<Hash>, Hash, nil] List of Local LUNs used by the storage profile.\n attribute :local_luns\n validates :local_luns, type: TypeGeneric.new(Hash)\n\n # @return [String, nil] The distinguished name (dn) of the organization where the resource is assigned.\n attribute :org_dn\n validates :org_dn, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6743922829627991, "alphanum_fraction": 0.6743922829627991, "avg_line_length": 46.81081008911133, "blob_id": "21c222f1586e061e307066a6bd0e9d4f5f4cc979", "content_id": "140625e36ad453ec879199761ee0488531c655ae", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1769, "license_type": "permissive", "max_line_length": 173, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_vrf.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage contexts or VRFs on Cisco ACI fabrics.\n # Each context is a private network associated to a tenant, i.e. VRF.\n class Aci_vrf < Base\n # @return [String, nil] The name of the Tenant the VRF should belong to.\n attribute :tenant\n validates :tenant, type: String\n\n # @return [String, nil] The name of the VRF.\n attribute :vrf\n validates :vrf, type: String\n\n # @return [:egress, :ingress, nil] Determines if the policy should be enforced by the fabric on ingress or egress.\n attribute :policy_control_direction\n validates :policy_control_direction, expression_inclusion: {:in=>[:egress, :ingress], :message=>\"%{value} needs to be :egress, :ingress\"}, allow_nil: true\n\n # @return [:enforced, :unenforced, nil] Determines if the fabric should enforce contract policies to allow routing and packet forwarding.\n attribute :policy_control_preference\n validates :policy_control_preference, expression_inclusion: {:in=>[:enforced, :unenforced], :message=>\"%{value} needs to be :enforced, :unenforced\"}, allow_nil: true\n\n # @return [Object, nil] The description for the VRF.\n attribute :description\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6669512987136841, "alphanum_fraction": 0.6690862774848938, "avg_line_length": 41.581817626953125, "blob_id": "0e06d33c5e3553be30dfc6fa7d763d8137479545", "content_id": "7e5c58b1f5e21d6952ebc093b7d7303db423569c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2342, "license_type": "permissive", "max_line_length": 179, "num_lines": 55, "path": "/lib/ansible/ruby/modules/generated/network/meraki/meraki_vlan.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, edit, query, or delete VLANs in a Meraki environment.\n class Meraki_vlan < Base\n # @return [:absent, :present, :query, nil] Specifies whether object should be queried, created/modified, or removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n\n # @return [String, nil] Name of network which VLAN is in or should be in.\n attribute :net_name\n validates :net_name, type: String\n\n # @return [Object, nil] ID of network which VLAN is in or should be in.\n attribute :net_id\n\n # @return [Integer, nil] ID number of VLAN.,ID should be between 1-4096.\n attribute :vlan_id\n validates :vlan_id, type: Integer\n\n # @return [String, nil] Name of VLAN.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] CIDR notation of network subnet.\n attribute :subnet\n validates :subnet, type: String\n\n # @return [String, nil] IP address of appliance.,Address must be within subnet specified in C(subnet) parameter.\n attribute :appliance_ip\n validates :appliance_ip, type: String\n\n # @return [String, nil] Semi-colon delimited list of DNS IP addresses.,Specify one of the following options for preprogrammed DNS entries opendns, google_dns, upstream_dns\n attribute :dns_nameservers\n validates :dns_nameservers, type: String\n\n # @return [Array<Hash>, Hash, nil] IP address ranges which should be reserve and not distributed via DHCP.\n attribute :reserved_ip_range\n validates :reserved_ip_range, type: TypeGeneric.new(Hash)\n\n # @return [Object, nil] The translated VPN subnet if VPN and VPN subnet translation are enabled on the VLAN.\n attribute :vpn_nat_subnet\n\n # @return [Array<Hash>, Hash, nil] Static IP address assignements to be distributed via DHCP by MAC address.\n attribute :fixed_ip_assignments\n validates :fixed_ip_assignments, type: TypeGeneric.new(Hash)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6818609237670898, "alphanum_fraction": 0.6818609237670898, "avg_line_length": 56.513511657714844, "blob_id": "bd2319f8afca1baffa7e767e2a6df3716d1a6099", "content_id": "4d6f9f70dacd73a31a9f420906ade964bfb2dd7f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2128, "license_type": "permissive", "max_line_length": 259, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/packaging/os/openbsd_pkg.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage packages on OpenBSD using the pkg tools.\n class Openbsd_pkg < Base\n # @return [String] A name or a list of names of the packages.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :latest, :present, nil] C(present) will make sure the package is installed. C(latest) will make sure the latest version of the package is installed. C(absent) will make sure the specified package is not installed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :latest, :present], :message=>\"%{value} needs to be :absent, :latest, :present\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Build the package from source instead of downloading and installing a binary. Requires that the port source tree is already installed. Automatically builds and installs the 'sqlports' package, if it is not already installed.\n attribute :build\n validates :build, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] When used in combination with the C(build) option, allows overriding the default ports source directory.\n attribute :ports_dir\n validates :ports_dir, type: String\n\n # @return [:yes, :no, nil] When updating or removing packages, delete the extra configuration file(s) in the old packages which are annotated with @extra in the packaging-list.\n attribute :clean\n validates :clean, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Replace or delete packages quickly; do not bother with checksums before removing normal files.\n attribute :quick\n validates :quick, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.74481201171875, "alphanum_fraction": 0.7460448145866394, "avg_line_length": 92.59615325927734, "blob_id": "430d39aa9a38e78d3af77e67984cf98d21cbd275", "content_id": "29c929ac99af3b0dfd599fc112bd47b8fde082e7", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4867, "license_type": "permissive", "max_line_length": 489, "num_lines": 52, "path": "/lib/ansible/ruby/modules/generated/network/iosxr/iosxr_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of the local usernames configured on network devices. It allows playbooks to manage either individual usernames or the aggregate of usernames in the current running config. It also supports purging usernames from the configuration that are not explicitly defined.\n class Iosxr_user < Base\n # @return [Array<Hash>, Hash, nil] The set of username objects to be configured on the remote Cisco IOS XR device. The list entries can either be the username or a hash of username and properties. This argument is mutually exclusive with the C(name) argument.\n attribute :aggregate\n validates :aggregate, type: TypeGeneric.new(Hash)\n\n # @return [String, nil] The username to be configured on the Cisco IOS XR device. This argument accepts a string value and is mutually exclusive with the C(aggregate) argument. Please note that this option is not same as C(provider username).\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] The password to be configured on the Cisco IOS XR device. The password needs to be provided in clear text. Password is encrypted on the device when used with I(cli) and by Ansible when used with I(netconf) using the same MD5 hash technique with salt size of 3. Please note that this option is not same as C(provider password).\n attribute :configured_password\n validates :configured_password, type: String\n\n # @return [:on_create, :always, nil] Since passwords are encrypted in the device running config, this argument will instruct the module when to change the password. When set to C(always), the password will always be updated in the device and when set to C(on_create) the password will be updated only if the username is created.\n attribute :update_password\n validates :update_password, expression_inclusion: {:in=>[:on_create, :always], :message=>\"%{value} needs to be :on_create, :always\"}, allow_nil: true\n\n # @return [String, nil] Configures the group for the username in the device running configuration. The argument accepts a string value defining the group name. This argument does not check if the group has been configured on the device.\n attribute :group\n validates :group, type: String\n\n # @return [Array<String>, String, nil] Configures the groups for the username in the device running configuration. The argument accepts a list of group names. This argument does not check if the group has been configured on the device. It is similar to the aggregrate command for usernames, but lets you configure multiple groups for the user(s).\n attribute :groups\n validates :groups, type: TypeGeneric.new(String)\n\n # @return [Symbol, nil] Instructs the module to consider the resource definition absolute. It will remove any previously configured usernames on the device with the exception of the `admin` user and the current defined set of users.\n attribute :purge\n validates :purge, type: Symbol\n\n # @return [:present, :absent, nil] Configures the state of the username definition as it relates to the device operational configuration. When set to I(present), the username(s) should be configured in the device active configuration and when set to I(absent) the username(s) should not be in the device active configuration\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Configures the contents of the public keyfile to upload to the IOS-XR node. This enables users to login using the accompanying private key. IOS-XR only accepts base64 decoded files, so this will be decoded and uploaded to the node. Do note that this requires an OpenSSL public key file, PuTTy generated files will not work! Mutually exclusive with public_key_contents. If used with multiple users in aggregates, then the same key file is used for all users.\n attribute :public_key\n\n # @return [String, nil] Configures the contents of the public keyfile to upload to the IOS-XR node. This enables users to login using the accompanying private key. IOS-XR only accepts base64 decoded files, so this will be decoded and uploaded to the node. Do note that this requires an OpenSSL public key file, PuTTy generated files will not work! Mutually exclusive with public_key.If used with multiple users in aggregates, then the same key file is used for all users.\n attribute :public_key_contents\n validates :public_key_contents, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6864367723464966, "alphanum_fraction": 0.6864367723464966, "avg_line_length": 60.26760482788086, "blob_id": "3d1066cba7c3bb6307bd516a2e1b8749d556d84f", "content_id": "48928f8e05150f987fa008ad88b1c67df28d5329", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4350, "license_type": "permissive", "max_line_length": 265, "num_lines": 71, "path": "/lib/ansible/ruby/modules/generated/network/radware/vdirect_commit.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Commits pending configuration changes on one or more Radware devices via vDirect server.\n # For Alteon ADC device, apply, sync and save actions will be performed by default. Skipping of an action is possible by explicit parameter specifying.\n # For Alteon VX Container device, no sync operation will be performed since sync action is only relevant for Alteon ADC devices.\n # For DefensePro and AppWall devices, a bulk commit action will be performed. Explicit apply, sync and save actions specifying is not relevant.\n class Vdirect_commit < Base\n # @return [String] Primary vDirect server IP address, may be set as C(VDIRECT_IP) environment variable.\n attribute :vdirect_ip\n validates :vdirect_ip, presence: true, type: String\n\n # @return [String] vDirect server username, may be set as C(VDIRECT_USER) environment variable.\n attribute :vdirect_user\n validates :vdirect_user, presence: true, type: String\n\n # @return [String] vDirect server password, may be set as C(VDIRECT_PASSWORD) environment variable.\n attribute :vdirect_password\n validates :vdirect_password, presence: true, type: String\n\n # @return [Object, nil] Secondary vDirect server IP address, may be set as C(VDIRECT_SECONDARY_IP) environment variable.\n attribute :vdirect_secondary_ip\n\n # @return [:yes, :no, nil] Wait for async operation to complete, may be set as C(VDIRECT_WAIT) environment variable.\n attribute :vdirect_wait\n validates :vdirect_wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] vDirect server HTTPS port number, may be set as C(VDIRECT_HTTPS_PORT) environment variable.\n attribute :vdirect_https_port\n validates :vdirect_https_port, type: Integer\n\n # @return [Integer, nil] vDirect server HTTP port number, may be set as C(VDIRECT_HTTP_PORT) environment variable.\n attribute :vdirect_http_port\n validates :vdirect_http_port, type: Integer\n\n # @return [Integer, nil] Amount of time to wait for async operation completion [seconds],,may be set as C(VDIRECT_TIMEOUT) environment variable.\n attribute :vdirect_timeout\n validates :vdirect_timeout, type: Integer\n\n # @return [:yes, :no, nil] If C(no), an HTTP connection will be used instead of the default HTTPS connection,,may be set as C(VDIRECT_HTTPS) or C(VDIRECT_USE_SSL) environment variable.\n attribute :vdirect_use_ssl\n validates :vdirect_use_ssl, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated,,may be set as C(VDIRECT_VALIDATE_CERTS) or C(VDIRECT_VERIFY) environment variable.,This should only set to C(no) used on personally controlled sites using self-signed certificates.\n attribute :vdirect_validate_certs\n validates :vdirect_validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Array<String>, String] List of Radware Alteon device names for commit operations.\n attribute :devices\n validates :devices, presence: true, type: TypeGeneric.new(String)\n\n # @return [:yes, :no, nil] If C(no), apply action will not be performed. Relevant for ADC devices only.\n attribute :apply\n validates :apply, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), save action will not be performed. Relevant for ADC devices only.\n attribute :save\n validates :save, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), sync action will not be performed. Relevant for ADC devices only.\n attribute :sync\n validates :sync, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6530003547668457, "alphanum_fraction": 0.6530003547668457, "avg_line_length": 44.47457504272461, "blob_id": "82dd74658c4dbffa2e43210af8c2241ac73fb54e", "content_id": "3c330ed856f9e39526f6e4a21bd9ce12fc4da0d9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2683, "license_type": "permissive", "max_line_length": 225, "num_lines": 59, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_account.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, disable, lock, enable and remove accounts.\n class Cs_account < Base\n # @return [String] Name of account.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Username of the user to be created if account did not exist.,Required on C(state=present).\n attribute :username\n validates :username, type: String\n\n # @return [String, nil] Password of the user to be created if account did not exist.,Required on C(state=present).\n attribute :password\n validates :password, type: String\n\n # @return [String, nil] First name of the user to be created if account did not exist.,Required on C(state=present).\n attribute :first_name\n validates :first_name, type: String\n\n # @return [String, nil] Last name of the user to be created if account did not exist.,Required on C(state=present).\n attribute :last_name\n validates :last_name, type: String\n\n # @return [String, nil] Email of the user to be created if account did not exist.,Required on C(state=present).\n attribute :email\n validates :email, type: String\n\n # @return [Object, nil] Timezone of the user to be created if account did not exist.\n attribute :timezone\n\n # @return [Object, nil] Network domain of the account.\n attribute :network_domain\n\n # @return [:user, :root_admin, :domain_admin, nil] Type of the account.\n attribute :account_type\n validates :account_type, expression_inclusion: {:in=>[:user, :root_admin, :domain_admin], :message=>\"%{value} needs to be :user, :root_admin, :domain_admin\"}, allow_nil: true\n\n # @return [String, nil] Domain the account is related to.\n attribute :domain\n validates :domain, type: String\n\n # @return [:present, :absent, :enabled, :disabled, :locked, :unlocked, nil] State of the account.,C(unlocked) is an alias for C(enabled).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :enabled, :disabled, :locked, :unlocked], :message=>\"%{value} needs to be :present, :absent, :enabled, :disabled, :locked, :unlocked\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Poll async jobs until job has finished.\n attribute :poll_async\n validates :poll_async, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6357560753822327, "alphanum_fraction": 0.6357560753822327, "avg_line_length": 28.924999237060547, "blob_id": "3a4bf5f15b4c47f0f34d0974a25ef6661f4da61c", "content_id": "699c99d77018a6d772c66304c9b4a2912ccedee9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1197, "license_type": "permissive", "max_line_length": 106, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/notification/jabber.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Send a message to jabber\n class Jabber < Base\n # @return [String] User as which to connect\n attribute :user\n validates :user, presence: true, type: String\n\n # @return [String] password for user to connect\n attribute :password\n validates :password, presence: true, type: String\n\n # @return [String] user ID or name of the room, when using room use a slash to indicate your nick.\n attribute :to\n validates :to, presence: true, type: String\n\n # @return [String] The message body.\n attribute :msg\n validates :msg, presence: true, type: String\n\n # @return [String, nil] host to connect, overrides user info\n attribute :host\n validates :host, type: String\n\n # @return [Integer, nil] port to connect to, overrides default\n attribute :port\n validates :port, type: Integer\n\n # @return [Object, nil] message encoding\n attribute :encoding\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6747182011604309, "alphanum_fraction": 0.6747182011604309, "avg_line_length": 28.571428298950195, "blob_id": "723bd147fa55440c7bfe50c31e2d0d8f571f5767", "content_id": "ada498eb631419f925db7170acc89d92f19fd9f5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 621, "license_type": "permissive", "max_line_length": 103, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/network/nso/nso_show.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides support for displaying data from Cisco NSO.\n class Nso_show < Base\n # @return [String] Path to NSO data.\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [Symbol, nil] Controls whether or not operational data is included in the result.\\r\\n\n attribute :operational\n validates :operational, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6911885738372803, "alphanum_fraction": 0.6917375922203064, "avg_line_length": 56.82539749145508, "blob_id": "ad3b15cf85b52c5812be50af5560cc42998e919c", "content_id": "8cba4b5089e2287639d56fc8e5e9f6594a675451", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3643, "license_type": "permissive", "max_line_length": 489, "num_lines": 63, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gc_storage.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows users to manage their objects/buckets in Google Cloud Storage. It allows upload and download operations and can set some canned permissions. It also allows retrieval of URLs for objects for use in playbooks, and retrieval of string contents of objects. This module requires setting the default project in GCS prior to playbook usage. See U(https://developers.google.com/storage/docs/reference/v1/apiversion1) for information about setting the default project.\n class Gc_storage < Base\n # @return [String] Bucket name.\n attribute :bucket\n validates :bucket, presence: true, type: String\n\n # @return [String, nil] Keyname of the object inside the bucket. Can be also be used to create \"virtual directories\" (see examples).\n attribute :object\n validates :object, type: String\n\n # @return [String, nil] The source file path when performing a PUT operation.\n attribute :src\n validates :src, type: String\n\n # @return [String, nil] The destination file path when downloading an object/key with a GET operation.\n attribute :dest\n validates :dest, type: String\n\n # @return [:yes, :no, nil] Forces an overwrite either locally on the filesystem or remotely with the object/key. Used with PUT and GET operations.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] This option let's the user set the canned permissions on the object/bucket that are created. The permissions that can be set are 'private', 'public-read', 'authenticated-read'.\n attribute :permission\n validates :permission, type: String\n\n # @return [Object, nil] Headers to attach to object.\n attribute :headers\n\n # @return [Object, nil] Time limit (in seconds) for the URL generated and returned by GCA when performing a mode=put or mode=get_url operation. This url is only available when public-read is the acl for the object.\n attribute :expiration\n\n # @return [:get, :put, :get_url, :get_str, :delete, :create] Switches the module behaviour between upload, download, get_url (return download url) , get_str (download object as string), create (bucket) and delete (bucket).\n attribute :mode\n validates :mode, presence: true, expression_inclusion: {:in=>[:get, :put, :get_url, :get_str, :delete, :create], :message=>\"%{value} needs to be :get, :put, :get_url, :get_str, :delete, :create\"}\n\n # @return [Object] GS secret key. If not set then the value of the GS_SECRET_ACCESS_KEY environment variable is used.\n attribute :gs_secret_key\n validates :gs_secret_key, presence: true\n\n # @return [Object] GS access key. If not set then the value of the GS_ACCESS_KEY_ID environment variable is used.\n attribute :gs_access_key\n validates :gs_access_key, presence: true\n\n # @return [String, nil] The gs region to use. If not defined then the value 'US' will be used. See U(https://cloud.google.com/storage/docs/bucket-locations)\n attribute :region\n validates :region, type: String\n\n # @return [Symbol, nil] Whether versioning is enabled or disabled (note that once versioning is enabled, it can only be suspended)\n attribute :versioning\n validates :versioning, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7119113802909851, "alphanum_fraction": 0.7368420958518982, "avg_line_length": 19.05555534362793, "blob_id": "b44f86c54902a31316d9ec8e177595178749379c", "content_id": "895289ddfa4204728a99958bb6e4de50632c5a75", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 361, "license_type": "permissive", "max_line_length": 66, "num_lines": 18, "path": "/lib/ansible/ruby/modules/custom/cloud/core/amazon/ec2_eip.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# VALIDATED_CHECKSUM: PgorX84TOr33FZPvvP+HbMuVbykJ25rKDOAd+T4dCfc=\n\n# See LICENSE.txt for license\n\nrequire 'ansible/ruby/modules/generated/cloud/amazon/ec2_eip'\nrequire 'ansible/ruby/modules/helpers/aws'\n\nmodule Ansible\n module Ruby\n module Modules\n class Ec2_eip\n include Helpers::Aws\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6699314117431641, "alphanum_fraction": 0.6699314117431641, "avg_line_length": 34.2068977355957, "blob_id": "ccba59dc147d2294cee887c705e39a02ffc22b27", "content_id": "a22f457026e0812c9d532f10a9fdcd74631bb405", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1021, "license_type": "permissive", "max_line_length": 129, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/ansible_tower/tower_job_wait.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Wait for Ansible Tower job to finish and report success or failure. See U(https://www.ansible.com/tower) for an overview.\n class Tower_job_wait < Base\n # @return [String] ID of the job to monitor.\n attribute :job_id\n validates :job_id, presence: true, type: String\n\n # @return [Integer, nil] Minimum interval in seconds, to request an update from Tower.\n attribute :min_interval\n validates :min_interval, type: Integer\n\n # @return [Integer, nil] Maximum interval in seconds, to request an update from Tower.\n attribute :max_interval\n validates :max_interval, type: Integer\n\n # @return [Integer, nil] Maximum time in seconds to wait for a job to finish.\n attribute :timeout\n validates :timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6687058806419373, "alphanum_fraction": 0.6844705939292908, "avg_line_length": 56.43243408203125, "blob_id": "fdb5c88149e947ea5e65bd6db7fbcedee593a7ca", "content_id": "9a056089247d3e52d78ca71a70877ec79c26d6bf", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4250, "license_type": "permissive", "max_line_length": 491, "num_lines": 74, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_elementsw_network_interfaces.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configure Element SW Node Network Interfaces for Bond 1G and 10G IP address.\n class Na_elementsw_network_interfaces < Base\n # @return [:loopback, :manual, :dhcp, :static] Type of Method used to configure the interface.,method depends on other settings such as the use of a static IP address, which will change the method to static.,loopback - Used to define the IPv4 loopback interface.,manual - Used to define interfaces for which no configuration is done by default.,dhcp - May be used to obtain an IP address via DHCP.,static - Used to define Ethernet interfaces with statically allocated IPv4 addresses.\n attribute :method\n validates :method, presence: true, expression_inclusion: {:in=>[:loopback, :manual, :dhcp, :static], :message=>\"%{value} needs to be :loopback, :manual, :dhcp, :static\"}\n\n # @return [String] IP address for the 1G network.\n attribute :ip_address_1g\n validates :ip_address_1g, presence: true, type: String\n\n # @return [String] IP address for the 10G network.\n attribute :ip_address_10g\n validates :ip_address_10g, presence: true, type: String\n\n # @return [String] 1GbE Subnet Mask.\n attribute :subnet_1g\n validates :subnet_1g, presence: true, type: String\n\n # @return [String] 10GbE Subnet Mask.\n attribute :subnet_10g\n validates :subnet_10g, presence: true, type: String\n\n # @return [String] Router network address to send packets out of the local network.\n attribute :gateway_address_1g\n validates :gateway_address_1g, presence: true, type: String\n\n # @return [String] Router network address to send packets out of the local network.\n attribute :gateway_address_10g\n validates :gateway_address_10g, presence: true, type: String\n\n # @return [String, nil] Maximum Transmission Unit for 1GbE, Largest packet size that a network protocol can transmit.,Must be greater than or equal to 1500 bytes.\n attribute :mtu_1g\n validates :mtu_1g, type: String\n\n # @return [String, nil] Maximum Transmission Unit for 10GbE, Largest packet size that a network protocol can transmit.,Must be greater than or equal to 1500 bytes.\n attribute :mtu_10g\n validates :mtu_10g, type: String\n\n # @return [Object, nil] List of addresses for domain name servers.\n attribute :dns_nameservers\n\n # @return [Object, nil] List of DNS search domains.\n attribute :dns_search_domains\n\n # @return [:ActivePassive, :ALB, :LACP, nil] Bond mode for 1GbE configuration.\n attribute :bond_mode_1g\n validates :bond_mode_1g, expression_inclusion: {:in=>[:ActivePassive, :ALB, :LACP], :message=>\"%{value} needs to be :ActivePassive, :ALB, :LACP\"}, allow_nil: true\n\n # @return [:ActivePassive, :ALB, :LACP, nil] Bond mode for 10GbE configuration.\n attribute :bond_mode_10g\n validates :bond_mode_10g, expression_inclusion: {:in=>[:ActivePassive, :ALB, :LACP], :message=>\"%{value} needs to be :ActivePassive, :ALB, :LACP\"}, allow_nil: true\n\n # @return [:Fast, :Slow, nil] Link Aggregation Control Protocol useful only if LACP is selected as the Bond Mode.,Slow - Packets are transmitted at 30 second intervals.,Fast - Packets are transmitted in 1 second intervals.\n attribute :lacp_1g\n validates :lacp_1g, expression_inclusion: {:in=>[:Fast, :Slow], :message=>\"%{value} needs to be :Fast, :Slow\"}, allow_nil: true\n\n # @return [:Fast, :Slow, nil] Link Aggregation Control Protocol useful only if LACP is selected as the Bond Mode.,Slow - Packets are transmitted at 30 second intervals.,Fast - Packets are transmitted in 1 second intervals.\n attribute :lacp_10g\n validates :lacp_10g, expression_inclusion: {:in=>[:Fast, :Slow], :message=>\"%{value} needs to be :Fast, :Slow\"}, allow_nil: true\n\n # @return [Object, nil] This is the primary network tag. All nodes in a cluster have the same VLAN tag.\n attribute :virtual_network_tag\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7038664221763611, "alphanum_fraction": 0.7056239247322083, "avg_line_length": 44.52000045776367, "blob_id": "373759e1374b3ec25ebcbc926f0c53cca0b2d229", "content_id": "096e2cbbeeff7540c149952c49f0138fce913f73", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1138, "license_type": "permissive", "max_line_length": 200, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_target_canonical_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to gather facts about canonical (NAA) from an ESXi host based on SCSI target ID.\n class Vmware_target_canonical_facts < Base\n # @return [Integer, nil] The target id based on order of scsi device.,version 2.6 onwards, this parameter is optional.\n attribute :target_id\n validates :target_id, type: Integer\n\n # @return [String, nil] Name of the cluster.,Facts about all SCSI devices for all host system in the given cluster is returned.,This parameter is required, if C(esxi_hostname) is not provided.\n attribute :cluster_name\n validates :cluster_name, type: String\n\n # @return [String, nil] Name of the ESXi host system.,Facts about all SCSI devices for the given ESXi host system is returned.,This parameter is required, if C(cluster_name) is not provided.\n attribute :esxi_hostname\n validates :esxi_hostname, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6925902962684631, "alphanum_fraction": 0.6925902962684631, "avg_line_length": 76.76190185546875, "blob_id": "498cbe42bfb92d52d1c2d965ecc3671a4b6bf917", "content_id": "b00897d6cd078aa48ce6813ba7c75b5246d4843e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3266, "license_type": "permissive", "max_line_length": 532, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/windows/win_copy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The C(win_copy) module copies a file on the local box to remote windows locations.\n # For non-Windows targets, use the M(copy) module instead.\n class Win_copy < Base\n # @return [String, nil] When used instead of C(src), sets the contents of a file directly to the specified value. This is for simple values, for anything complex or with formatting please switch to the template module.\n attribute :content\n validates :content, type: String\n\n # @return [:yes, :no, nil] This option controls the autodecryption of source files using vault.\n attribute :decrypt\n validates :decrypt, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String] Remote absolute path where the file should be copied to. If src is a directory, this must be a directory too.,Use \\ for path separators or \\\\ when in \"double quotes\".,If C(dest) ends with \\ then source or the contents of source will be copied to the directory without renaming.,If C(dest) is a nonexistent path, it will only be created if C(dest) ends with \"/\" or \"\\\", or C(src) is a directory.,If C(src) and C(dest) are files and if the parent directory of C(dest) doesn't exist, then the task will fail.\n attribute :dest\n validates :dest, presence: true, type: String\n\n # @return [:yes, :no, nil] If set to C(yes), the file will only be transferred if the content is different than destination.,If set to C(no), the file will only be transferred if the destination does not exist.,If set to C(no), no checksuming of the content is performed which can help improve performance on larger files.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] This flag indicates that filesystem links in the source tree, if they exist, should be followed.\n attribute :local_follow\n validates :local_follow, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), it will search for src at originating/master machine.,If C(yes), it will go to the remote/target machine for the src.\n attribute :remote_src\n validates :remote_src, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String] Local path to a file to copy to the remote server; can be absolute or relative.,If path is a directory, it is copied (including the source folder name) recursively to C(dest).,If path is a directory and ends with \"/\", only the inside contents of that directory are copied to the destination. Otherwise, if it does not end with \"/\", the directory itself with all contents is copied.,If path is a file and dest ends with \"\\\", the file is copied to the folder with the same filename.\n attribute :src\n validates :src, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5383023023605347, "alphanum_fraction": 0.5383023023605347, "avg_line_length": 16.88888931274414, "blob_id": "d80003da9a471ce7bd97682c9e51ab0613cd62a0", "content_id": "e6b85c9785d73222a1be8866150253f3cdba5754", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 483, "license_type": "permissive", "max_line_length": 82, "num_lines": 27, "path": "/lib/ansible/ruby/models/jinja_expression.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nmodule Ansible\n module Ruby\n module Models\n class JinjaExpression\n attr_reader :expression\n\n def initialize(expression)\n @expression = expression\n end\n\n def to_s\n \"{{ #{@expression} }}\"\n end\n\n def to_str\n to_s\n end\n\n def ===(other_node)\n other_node.is_a?(JinjaExpression) && expression == other_node.expression\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6805828809738159, "alphanum_fraction": 0.6805828809738159, "avg_line_length": 48.7843132019043, "blob_id": "d057d37d7208a17c2ec4f6e9e6e3a117dded9954", "content_id": "a785447755b0d7582b88c814dcb4dcaad8513330", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2539, "license_type": "permissive", "max_line_length": 473, "num_lines": 51, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_vmpool.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Module to manage VM pools in oVirt/RHV.\n class Ovirt_vmpool < Base\n # @return [String] Name of the VM pool to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Comment of the Virtual Machine pool.\n attribute :comment\n\n # @return [:present, :absent, nil] Should the VM pool be present/absent.,Note that when C(state) is I(absent) all VMs in VM pool are stopped and removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Name of the template, which will be used to create VM pool.\n attribute :template\n validates :template, type: String\n\n # @return [Object, nil] Description of the VM pool.\n attribute :description\n\n # @return [String, nil] Name of the cluster, where VM pool should be created.\n attribute :cluster\n validates :cluster, type: String\n\n # @return [:manual, :automatic, nil] Type of the VM pool. Either manual or automatic.,C(manual) - The administrator is responsible for explicitly returning the virtual machine to the pool. The virtual machine reverts to the original base image after the administrator returns it to the pool.,C(Automatic) - When the virtual machine is shut down, it automatically reverts to its base image and is returned to the virtual machine pool.,Default value is set by engine.\n attribute :type\n validates :type, expression_inclusion: {:in=>[:manual, :automatic], :message=>\"%{value} needs to be :manual, :automatic\"}, allow_nil: true\n\n # @return [Integer, nil] Maximum number of VMs a single user can attach to from this pool.,Default value is set by engine.\n attribute :vm_per_user\n validates :vm_per_user, type: Integer\n\n # @return [Integer, nil] Number of pre-started VMs defines the number of VMs in run state, that are waiting to be attached to Users.,Default value is set by engine.\n attribute :prestarted\n validates :prestarted, type: Integer\n\n # @return [Integer, nil] Number of VMs in the pool.,Default value is set by engine.\n attribute :vm_count\n validates :vm_count, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5509950518608093, "alphanum_fraction": 0.5708954930305481, "avg_line_length": 15.408163070678711, "blob_id": "e054f4be18560f10982b968552147d56900f1da9", "content_id": "bb3e7b11202d37c25f3cf296e9427f0eaa6249b1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 804, "license_type": "permissive", "max_line_length": 56, "num_lines": 49, "path": "/examples/roles/dummy/tasks/main.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\ntask 'say hello' do\n with_items(%w[a b c]) do |item|\n result = shell \"ls #{item} || true\" do\n chdir '/tmp'\n end\n\n changed_when \"'No such file' in #{result.stderr}\"\n\n notify 'reboot'\n end\nend\n\ntask 'array input' do\n with_items(%w[a b c]) do |item|\n apt do\n name [item, item]\n end\n end\nend\n\ntask 'middle' do\n debug { msg 'foo' }\nend\n\ntask 'and goodbye' do\n stuff = {\n cmd1: {\n foobar: '123'\n },\n cmd2: {\n foobar: '456'\n }\n }\n\n with_dict(stuff) do |key, value|\n # will run ls cmd1 123 and ls cmd2 456\n result = command \"ls #{key} #{value.foobar}\" do\n chdir '/tmp'\n end\n\n changed_when \"'No such filesss' in #{result.stderr}\"\n end\nend\n\ntask 'do some failure' do\n ansible_fail { msg 'write this' }\nend\n" }, { "alpha_fraction": 0.6747289299964905, "alphanum_fraction": 0.6818181872367859, "avg_line_length": 52.28888702392578, "blob_id": "7fd521c0699d940cca894a3574b677fe9e0b6a8d", "content_id": "dd9f3d11df0f1294877216d3ca39f682618d32f7", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2398, "license_type": "permissive", "max_line_length": 187, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_netstream_export.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configure NetStream flow statistics exporting and versions for exported packets on HUAWEI CloudEngine switches.\n class Ce_netstream_export < Base\n # @return [:ip, :vxlan] Specifies NetStream feature.\n attribute :type\n validates :type, presence: true, expression_inclusion: {:in=>[:ip, :vxlan], :message=>\"%{value} needs to be :ip, :vxlan\"}\n\n # @return [Object, nil] Specifies source address which can be IPv6 or IPv4 of the exported NetStream packet.\n attribute :source_ip\n\n # @return [Object, nil] Specifies destination address which can be IPv6 or IPv4 of the exported NetStream packet.\n attribute :host_ip\n\n # @return [Object, nil] Specifies the destination UDP port number of the exported packets. The value is an integer that ranges from 1 to 65535.\n attribute :host_port\n\n # @return [Object, nil] Specifies the VPN instance of the exported packets carrying flow statistics. Ensure the VPN instance has been created on the device.\n attribute :host_vpn\n\n # @return [5, 9, nil] Sets the version of exported packets.\n attribute :version\n validates :version, expression_inclusion: {:in=>[5, 9], :message=>\"%{value} needs to be 5, 9\"}, allow_nil: true\n\n # @return [:origin, :peer, nil] Specifies the AS number recorded in the statistics as the original or the peer AS number.\n attribute :as_option\n validates :as_option, expression_inclusion: {:in=>[:origin, :peer], :message=>\"%{value} needs to be :origin, :peer\"}, allow_nil: true\n\n # @return [:enable, :disable, nil] Configures the statistics to carry BGP next hop information. Currently, only V9 supports the exported packets carrying BGP next hop information.\n attribute :bgp_nexthop\n validates :bgp_nexthop, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Manage the state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7057449817657471, "alphanum_fraction": 0.7085474133491516, "avg_line_length": 55.342105865478516, "blob_id": "0583343dfcc57f79d53ac1fb74e41a24cbf74f89", "content_id": "f59dde4d3c7b1a7afb8c5918f5cbd1a80ca5c5e7", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2141, "license_type": "permissive", "max_line_length": 293, "num_lines": 38, "path": "/lib/ansible/ruby/modules/generated/net_tools/nios/nios_txt_record.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Adds and/or removes instances of txt record objects from Infoblox NIOS servers. This module manages NIOS C(record:txt) objects using the Infoblox WAPI interface over REST.\n class Nios_txt_record < Base\n # @return [String] Specifies the fully qualified hostname to add or remove from the system\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] Sets the DNS view to associate this tst record with. The DNS view must already be configured on the system\n attribute :view\n validates :view, presence: true, type: String\n\n # @return [String, nil] Text associated with the record. It can contain up to 255 bytes per substring, up to a total of 512 bytes. To enter leading, trailing, or embedded spaces in the text, add quotes around the text to preserve the spaces.\n attribute :text\n validates :text, type: String\n\n # @return [Object, nil] Configures the TTL to be associated with this tst record\n attribute :ttl\n\n # @return [Object, nil] Allows for the configuration of Extensible Attributes on the instance of the object. This argument accepts a set of key / value pairs for configuration.\n attribute :extattrs\n\n # @return [Object, nil] Configures a text string comment to be associated with the instance of this object. The provided text string will be configured on the object instance.\n attribute :comment\n\n # @return [:present, :absent, nil] Configures the intended state of the instance of the object on the NIOS server. When this value is set to C(present), the object is configured on the device and when this value is set to C(absent) the value is removed (if necessary) from the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6828047037124634, "alphanum_fraction": 0.6844741106033325, "avg_line_length": 43.92499923706055, "blob_id": "7cd194c8f1fa85cb68524074614b778adefd0c7f", "content_id": "a032b9371919769ccb81914db425839d5cfbcf9c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1797, "license_type": "permissive", "max_line_length": 159, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/clustering/k8s/k8s_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Use the OpenShift Python client to perform read operations on K8s objects.\n # Access to the full range of K8s APIs.\n # Authenticate using either a config file, certificates, password or token.\n # Supports check mode.\n class K8s_facts < Base\n # @return [String, nil] Use to specify the API version. in conjunction with I(kind), I(name), and I(namespace) to identify a specific object.\n attribute :api_version\n validates :api_version, type: String\n\n # @return [String] Use to specify an object model. Use in conjunction with I(api_version), I(name), and I(namespace) to identify a specific object.\n attribute :kind\n validates :kind, presence: true, type: String\n\n # @return [String, nil] Use to specify an object name. Use in conjunction with I(api_version), I(kind) and I(namespace) to identify a specific object.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] Use to specify an object namespace. Use in conjunction with I(api_version), I(kind), and I(name) to identify a specfic object.\n attribute :namespace\n validates :namespace, type: String\n\n # @return [Array<String>, String, nil] List of label selectors to use to filter results\n attribute :label_selectors\n validates :label_selectors, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] List of field selectors to use to filter results\n attribute :field_selectors\n validates :field_selectors, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.709594190120697, "alphanum_fraction": 0.7119399309158325, "avg_line_length": 53.653846740722656, "blob_id": "eb8e8692470117e07798e83789863c817a40f396", "content_id": "266323e2a54e49db1766c5667e05089ebed1e018", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4263, "license_type": "permissive", "max_line_length": 338, "num_lines": 78, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_systemconfiguration.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure SystemConfiguration object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_systemconfiguration < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Object, nil] Adminauthconfiguration settings for systemconfiguration.\n attribute :admin_auth_configuration\n\n # @return [Object, nil] Specifies the default license tier which would be used by new clouds.,Enum options - ENTERPRISE_16, ENTERPRISE_18.,Field introduced in 17.2.5.,Default value when not specified in API or module is interpreted by Avi Controller as ENTERPRISE_18.\n attribute :default_license_tier\n\n # @return [Object, nil] Dnsconfiguration settings for systemconfiguration.\n attribute :dns_configuration\n\n # @return [Object, nil] Dns virtualservices hosting fqdn records for applications across avi vantage.,If no virtualservices are provided, avi vantage will provide dns services for configured applications.,Switching back to avi vantage from dns virtualservices is not allowed.,It is a reference to an object of type virtualservice.\n attribute :dns_virtualservice_refs\n\n # @return [Symbol, nil] Boolean flag to set docker_mode.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :docker_mode\n validates :docker_mode, type: Symbol\n\n # @return [Object, nil] Emailconfiguration settings for systemconfiguration.\n attribute :email_configuration\n\n # @return [Object, nil] Tenantconfiguration settings for systemconfiguration.\n attribute :global_tenant_config\n\n # @return [Object, nil] Linuxconfiguration settings for systemconfiguration.\n attribute :linux_configuration\n\n # @return [Object, nil] Configure ip access control for controller to restrict open access.\n attribute :mgmt_ip_access_control\n\n # @return [Object, nil] Ntpconfiguration settings for systemconfiguration.\n attribute :ntp_configuration\n\n # @return [Object, nil] Portalconfiguration settings for systemconfiguration.\n attribute :portal_configuration\n\n # @return [Object, nil] Proxyconfiguration settings for systemconfiguration.\n attribute :proxy_configuration\n\n # @return [Object, nil] Snmpconfiguration settings for systemconfiguration.\n attribute :snmp_configuration\n\n # @return [Object, nil] Allowed ciphers list for ssh to the management interface on the controller and service engines.,If this is not specified, all the default ciphers are allowed.,Ssh -q cipher provides the list of default ciphers supported.\n attribute :ssh_ciphers\n\n # @return [Object, nil] Allowed hmac list for ssh to the management interface on the controller and service engines.,If this is not specified, all the default hmacs are allowed.,Ssh -q mac provides the list of default hmacs supported.\n attribute :ssh_hmacs\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Unique object identifier of the object.\n attribute :uuid\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6158612370491028, "alphanum_fraction": 0.6158612370491028, "avg_line_length": 25.899999618530273, "blob_id": "0a50022fb68d23ce75235bae4f667cf4355828a0", "content_id": "a6fe76aac426c4cf842761a2d3d22fc2ebf508bd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 807, "license_type": "permissive", "max_line_length": 80, "num_lines": 30, "path": "/lib/ansible/ruby/models/unit.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# see LICENSE.txt in project root\nmodule Ansible\n module Ruby\n module Models\n class Unit < Base\n attribute :register\n validates :register, type: String\n attribute :become\n validates :become, type: MultipleTypes.new(TrueClass, FalseClass)\n attribute :become_user\n validates :become_user, type: String\n attribute :when\n validates :when, type: String\n attribute :ignore_errors\n validates :ignore_errors, type: MultipleTypes.new(TrueClass, FalseClass)\n attribute :vars\n validates :vars, type: Hash\n\n def to_h\n result = super\n notify = result.delete :notify\n result[:notify] = [*notify] if notify\n result\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6953582167625427, "alphanum_fraction": 0.7021190524101257, "avg_line_length": 69.78571319580078, "blob_id": "453746d555b7a101973944bcefad95d923962290", "content_id": "c6370acd0c2090ff3c7a9183a1f33dab5e158c6c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 9910, "license_type": "permissive", "max_line_length": 690, "num_lines": 140, "path": "/lib/ansible/ruby/modules/generated/windows/win_scheduled_task.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates/modified or removes Windows scheduled tasks.\n class Win_scheduled_task < Base\n # @return [String] The name of the scheduled task without the path.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Task folder in which this task will be stored.,Will create the folder when C(state=present) and the folder does not already exist.,Will remove the folder when C(state=absent) and there are no tasks left in the folder.\n attribute :path\n validates :path, type: String\n\n # @return [:absent, :present, nil] When C(state=present) will ensure the task exists.,When C(state=absent) will ensure the task does not exist.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] A list of action to configure for the task.,See suboptions for details on how to construct each list entry.,When creating a task there MUST be at least one action but when deleting a task this can be a null or an empty list.,The ordering of this list is important, the module will ensure the order is kept when modifying the task.,This module only supports the C(ExecAction) type but can still delete the older legacy types.\n attribute :actions\n validates :actions, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] A list of triggers to configure for the task.,See suboptions for details on how to construct each list entry.,The ordering of this list is important, the module will ensure the order is kept when modifying the task.,There are multiple types of triggers, see U(https://msdn.microsoft.com/en-us/library/windows/desktop/aa383868.aspx) for a list of trigger types and their options.,The suboption options listed below are not required for all trigger types, read the description for more details.\n attribute :triggers\n validates :triggers, type: TypeGeneric.new(String)\n\n # @return [Object, nil] The name of the user/group that is displayed in the Task Scheduler UI.\n attribute :display_name\n\n # @return [Object, nil] The group that will run the task.,C(group) and C(username) are exclusive to each other and cannot be set at the same time.,C(logon_type) can either be not set or equal C(group).\n attribute :group\n\n # @return [:none, :password, :s4u, :interactive_token, :group, :service_account, :token_or_password, nil] The logon method that the task will run with.,C(password) means the password will be stored and the task has access to network resources.,C(s4u) means the existing token will be used to run the task and no password will be stored with the task. Means no network or encrypted files access.,C(interactive_token) means the user must already be logged on interactively and will run in an existing interactive session.,C(group) means that the task will run as a group.,C(service_account) means that a service account like System, Local Service or Network Service will run the task.\n attribute :logon_type\n validates :logon_type, expression_inclusion: {:in=>[:none, :password, :s4u, :interactive_token, :group, :service_account, :token_or_password], :message=>\"%{value} needs to be :none, :password, :s4u, :interactive_token, :group, :service_account, :token_or_password\"}, allow_nil: true\n\n # @return [:limited, :highest, nil] The level of user rights used to run the task.,If not specified the task will be created with limited rights.\n attribute :run_level\n validates :run_level, expression_inclusion: {:in=>[:limited, :highest], :message=>\"%{value} needs to be :limited, :highest\"}, allow_nil: true\n\n # @return [String, nil] The user to run the scheduled task as.,Will default to the current user under an interactive token if not specified during creation.\n attribute :username\n validates :username, type: String\n\n # @return [String, nil] The password for the user account to run the scheduled task as.,This is required when running a task without the user being logged in, excluding the builtin service accounts.,If set, will always result in a change unless C(update_password) is set to C(no) and no othr changes are required for the service.\n attribute :password\n validates :password, type: String\n\n # @return [:yes, :no, nil] Whether to update the password even when not other changes have occured.,When C(yes) will always result in a change when executing the module.\n attribute :update_password\n validates :update_password, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] The author of the task.\n attribute :author\n\n # @return [Object, nil] The date when the task was registered.\n attribute :date\n\n # @return [String, nil] The description of the task.\n attribute :description\n validates :description, type: String\n\n # @return [Object, nil] The source of the task.\n attribute :source\n\n # @return [Object, nil] The version number of the task.\n attribute :version\n\n # @return [Symbol, nil] Whether the task can be started by using either the Run command or the Context menu.\n attribute :allow_demand_start\n validates :allow_demand_start, type: Symbol\n\n # @return [Symbol, nil] Whether the task can be terminated by using TerminateProcess.\n attribute :allow_hard_terminate\n validates :allow_hard_terminate, type: Symbol\n\n # @return [0, 1, 2, nil] The integer value with indicates which version of Task Scheduler a task is compatible with.,C(0) means the task is compatible with the AT command.,C(1) means the task is compatible with Task Scheduler 1.0.,C(2) means the task is compatible with Task Scheduler 2.0.\n attribute :compatibility\n validates :compatibility, expression_inclusion: {:in=>[0, 1, 2], :message=>\"%{value} needs to be 0, 1, 2\"}, allow_nil: true\n\n # @return [Object, nil] The amount of time that the Task Scheduler will wait before deleting the task after it expires.,A task expires after the end_boundary has been exceeded for all triggers associated with the task.,This is in the ISO 8601 Duration format C(P[n]Y[n]M[n]DT[n]H[n]M[n]S).\n attribute :delete_expired_task_after\n\n # @return [Symbol, nil] Whether the task will not be started if the computer is running on battery power.\n attribute :disallow_start_if_on_batteries\n validates :disallow_start_if_on_batteries, type: Symbol\n\n # @return [Symbol, nil] Whether the task is enabled, the task can only run when C(yes).\n attribute :enabled\n validates :enabled, type: Symbol\n\n # @return [Object, nil] The amount of time allowed to complete the task.,When not set, the time limit is infinite.,This is in the ISO 8601 Duration format C(P[n]Y[n]M[n]DT[n]H[n]M[n]S).\n attribute :execution_time_limit\n\n # @return [Symbol, nil] Whether the task will be hidden in the UI.\n attribute :hidden\n validates :hidden, type: Symbol\n\n # @return [0, 1, 2, 3, nil] An integer that indicates the behaviour when starting a task that is already running.,C(0) will start a new instance in parallel with existing instances of that task.,C(1) will wait until other instances of that task to finish running before starting itself.,C(2) will not start a new instance if another is running.,C(3) will stop other instances of the task and start the new one.\n attribute :multiple_instances\n validates :multiple_instances, expression_inclusion: {:in=>[0, 1, 2, 3], :message=>\"%{value} needs to be 0, 1, 2, 3\"}, allow_nil: true\n\n # @return [Integer, nil] The priority level (0-10) of the task.,When creating a new task the default if C(7).,See U(https://msdn.microsoft.com/en-us/library/windows/desktop/aa383512.aspx) for details on the priority levels.\n attribute :priority\n validates :priority, type: Integer\n\n # @return [Integer, nil] The number of times that the Task Scheduler will attempt to restart the task.\n attribute :restart_count\n validates :restart_count, type: Integer\n\n # @return [Object, nil] How long the Task Scheduler will attempt to restart the task.,If this is set then C(restart_count) must also be set.,The maximum allowed time is 31 days.,The minimum allowed time is 1 minute.,This is in the ISO 8601 Duration format C(P[n]Y[n]M[n]DT[n]H[n]M[n]S).\n attribute :restart_interval\n\n # @return [Symbol, nil] Whether the task will run the task only if the computer is in an idle state.\n attribute :run_only_if_idle\n validates :run_only_if_idle, type: Symbol\n\n # @return [Symbol, nil] Whether the task will run only when a network is available.\n attribute :run_only_if_network_available\n validates :run_only_if_network_available, type: Symbol\n\n # @return [Symbol, nil] Whether the task can start at any time after its scheduled time has passed.\n attribute :start_when_available\n validates :start_when_available, type: Symbol\n\n # @return [Symbol, nil] Whether the task will be stopped if the computer begins to run on battery power.\n attribute :stop_if_going_on_batteries\n validates :stop_if_going_on_batteries, type: Symbol\n\n # @return [Symbol, nil] Whether the task will wake the computer when it is time to run the task.\n attribute :wake_to_run\n validates :wake_to_run, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6410092115402222, "alphanum_fraction": 0.6414368152618408, "avg_line_length": 43.971153259277344, "blob_id": "b1efcff595cc82d7243256452781e76fb8a5d7ea", "content_id": "5c4515bec9feb86c7da7273d6b1659f9eab14afc", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4677, "license_type": "permissive", "max_line_length": 229, "num_lines": 104, "path": "/lib/ansible/ruby/modules/generated/cloud/misc/rhevm.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module only supports oVirt/RHEV version 3. A newer module M(ovirt_vms) supports oVirt/RHV version 4.\n # Allows you to create/remove/update or powermanage virtual machines on a RHEV/oVirt platform.\n class Rhevm < Base\n # @return [String, nil] The user to authenticate with.\n attribute :user\n validates :user, type: String\n\n # @return [String, nil] The name/ip of your RHEV-m/oVirt instance.\n attribute :server\n validates :server, type: String\n\n # @return [String, nil] The port on which the API is reacheable.\n attribute :port\n validates :port, type: String\n\n # @return [:yes, :no, nil] A boolean switch to make a secure or insecure connection to the server.\n attribute :insecure_api\n validates :insecure_api, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] The name of the VM.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] The rhev/ovirt cluster in which you want you VM to start.\n attribute :cluster\n validates :cluster, type: String\n\n # @return [String, nil] The rhev/ovirt datacenter in which you want you VM to start.\n attribute :datacenter\n validates :datacenter, type: String\n\n # @return [:ping, :present, :absent, :up, :down, :restarted, :cd, :info, nil] This serves to create/remove/update or powermanage your VM.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:ping, :present, :absent, :up, :down, :restarted, :cd, :info], :message=>\"%{value} needs to be :ping, :present, :absent, :up, :down, :restarted, :cd, :info\"}, allow_nil: true\n\n # @return [String, nil] The template to use for the VM.\n attribute :image\n validates :image, type: String\n\n # @return [:server, :desktop, :host, nil] To define if the VM is a server or desktop.\n attribute :type\n validates :type, expression_inclusion: {:in=>[:server, :desktop, :host], :message=>\"%{value} needs to be :server, :desktop, :host\"}, allow_nil: true\n\n # @return [Object, nil] The host you wish your VM to run on.\n attribute :vmhost\n\n # @return [String, nil] The number of CPUs you want in your VM.\n attribute :vmcpu\n validates :vmcpu, type: String\n\n # @return [String, nil] This parameter is used to configure the cpu share.\n attribute :cpu_share\n validates :cpu_share, type: String\n\n # @return [String, nil] The amount of memory you want your VM to use (in GB).\n attribute :vmmem\n validates :vmmem, type: String\n\n # @return [String, nil] The operationsystem option in RHEV/oVirt.\n attribute :osver\n validates :osver, type: String\n\n # @return [String, nil] The minimum amount of memory you wish to reserve for this system.\n attribute :mempol\n validates :mempol, type: String\n\n # @return [:yes, :no, nil] To make your VM High Available.\n attribute :vm_ha\n validates :vm_ha, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash, nil] This option uses complex arguments and is a list of disks with the options name, size and domain.\n attribute :disks\n validates :disks, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash, nil] This option uses complex arguments and is a list of interfaces with the options name and vlan.\n attribute :ifaces\n validates :ifaces, type: TypeGeneric.new(Hash)\n\n # @return [String, nil] This option uses complex arguments and is a list of items that specify the bootorder.\n attribute :boot_order\n validates :boot_order, type: String\n\n # @return [Boolean, nil] This option sets the delete protection checkbox.\n attribute :del_prot\n validates :del_prot, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] The CD you wish to have mounted on the VM when I(state = 'CD').\n attribute :cd_drive\n validates :cd_drive, type: String\n\n # @return [Object, nil] The timeout you wish to define for power actions.,When I(state = 'up'),When I(state = 'down'),When I(state = 'restarted')\n attribute :timeout\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6758393049240112, "alphanum_fraction": 0.6763896346092224, "avg_line_length": 55.78125, "blob_id": "0cf5ed2262be2b35d977cf7730e194b9e61a1cdc", "content_id": "9e6c6239fea340c0609523ea2d4c4eddd9d01811", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3634, "license_type": "permissive", "max_line_length": 303, "num_lines": 64, "path": "/lib/ansible/ruby/modules/generated/windows/win_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages local Windows user accounts.\n # For non-Windows targets, use the M(user) module instead.\n class Win_user < Base\n # @return [String] Name of the user to create, remove or modify.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Full name of the user.\n attribute :fullname\n\n # @return [Object, nil] Description of the user.\n attribute :description\n\n # @return [String, nil] Optionally set the user's password to this (plain text) value.\n attribute :password\n validates :password, type: String\n\n # @return [:always, :on_create, nil] C(always) will update passwords if they differ. C(on_create) will only set the password for newly created users.\n attribute :update_password\n validates :update_password, expression_inclusion: {:in=>[:always, :on_create], :message=>\"%{value} needs to be :always, :on_create\"}, allow_nil: true\n\n # @return [Symbol, nil] C(yes) will require the user to change their password at next login.,C(no) will clear the expired password flag.\n attribute :password_expired\n validates :password_expired, type: Symbol\n\n # @return [Symbol, nil] C(yes) will set the password to never expire.,C(no) will allow the password to expire.\n attribute :password_never_expires\n validates :password_never_expires, type: Symbol\n\n # @return [Symbol, nil] C(yes) will prevent the user from changing their password.,C(no) will allow the user to change their password.\n attribute :user_cannot_change_password\n validates :user_cannot_change_password, type: Symbol\n\n # @return [Symbol, nil] C(yes) will disable the user account.,C(no) will clear the disabled flag.\n attribute :account_disabled\n validates :account_disabled, type: Symbol\n\n # @return [:no, nil] C(no) will unlock the user account if locked.\n attribute :account_locked\n validates :account_locked, expression_inclusion: {:in=>[:no], :message=>\"%{value} needs to be :no\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] Adds or removes the user from this comma-separated lis of groups, depending on the value of I(groups_action). When I(groups_action) is C(replace) and I(groups) is set to the empty string ('groups='), the user is removed from all groups.\n attribute :groups\n validates :groups, type: TypeGeneric.new(String)\n\n # @return [:add, :replace, :remove, nil] If C(add), the user is added to each group in I(groups) where not already a member.,If C(replace), the user is added as a member of each group in I(groups) and removed from any other groups.,If C(remove), the user is removed from each group in I(groups).\n attribute :groups_action\n validates :groups_action, expression_inclusion: {:in=>[:add, :replace, :remove], :message=>\"%{value} needs to be :add, :replace, :remove\"}, allow_nil: true\n\n # @return [:absent, :present, :query, nil] When C(absent), removes the user account if it exists.,When C(present), creates or updates the user account.,When C(query) (new in 1.9), retrieves the user account details without making any changes.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6501976251602173, "alphanum_fraction": 0.6531620621681213, "avg_line_length": 31.645160675048828, "blob_id": "f2c01dab8d6b848890adf4879f352558d8ad6d12", "content_id": "b8d5df36ec15364ff61bf8655b54c10717f9b931", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1012, "license_type": "permissive", "max_line_length": 143, "num_lines": 31, "path": "/lib/ansible/ruby/modules/generated/cloud/rackspace/rax_dns.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage domains on Rackspace Cloud DNS\n class Rax_dns < Base\n # @return [Object, nil] Brief description of the domain. Maximum length of 160 characters\n attribute :comment\n\n # @return [Object, nil] Email address of the domain administrator\n attribute :email\n\n # @return [String, nil] Domain name to create\n attribute :name\n validates :name, type: String\n\n # @return [:present, :absent, nil] Indicate desired state of the resource\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Integer, nil] Time to live of domain in seconds\n attribute :ttl\n validates :ttl, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6609124541282654, "alphanum_fraction": 0.6609124541282654, "avg_line_length": 35.8636360168457, "blob_id": "102c3f4ec3e9a7ac7c3489f39109dba3810c16fb", "content_id": "44a6da4db45f0a9546d9440fc04c372d7a60b52d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1622, "license_type": "permissive", "max_line_length": 158, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_recordset.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage OpenStack DNS recordsets. Recordsets can be created, deleted or updated. Only the I(records), I(description), and I(ttl) values can be updated.\n class Os_recordset < Base\n # @return [String] Zone managing the recordset\n attribute :zone\n validates :zone, presence: true, type: String\n\n # @return [String] Name of the recordset\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] Recordset type\n attribute :recordset_type\n validates :recordset_type, presence: true, type: String\n\n # @return [Array<String>, String] List of recordset definitions\n attribute :records\n validates :records, presence: true, type: TypeGeneric.new(String)\n\n # @return [String, nil] Description of the recordset\n attribute :description\n validates :description, type: String\n\n # @return [Integer, nil] TTL (Time To Live) value in seconds\n attribute :ttl\n validates :ttl, type: Integer\n\n # @return [:present, :absent, nil] Should the resource be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6410861611366272, "alphanum_fraction": 0.649350643157959, "avg_line_length": 34.29166793823242, "blob_id": "d268bbd34e2d30461a49db6dfb929af3516f55bf", "content_id": "771430ed639538e3ef5fd8398193c454a8ac4fe4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 847, "license_type": "permissive", "max_line_length": 143, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_vrf.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages VPN instance of HUAWEI CloudEngine switches.\n class Ce_vrf < Base\n # @return [Object] VPN instance, the length of vrf name is 1 - 31, i.e. \"test\", but can not be C(_public_).\n attribute :vrf\n validates :vrf, presence: true\n\n # @return [Object, nil] Description of the vrf, the string length is 1 - 242 .\n attribute :description\n\n # @return [:present, :absent, nil] Manage the state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6677050590515137, "alphanum_fraction": 0.6677050590515137, "avg_line_length": 37.52000045776367, "blob_id": "b26b7e25bfa475c174ea21ac9b990b73fdbed13c", "content_id": "9b976d01c12d5f6aae0c05c37d49745c629b3928", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 963, "license_type": "permissive", "max_line_length": 143, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/packaging/os/portinstall.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage packages for FreeBSD using 'portinstall'.\n class Portinstall < Base\n # @return [Array<String>, String] name of package to install/remove\n attribute :name\n validates :name, presence: true, type: TypeGeneric.new(String)\n\n # @return [:present, :absent, nil] state of the package\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Boolean, nil] use packages instead of ports whenever available\n attribute :use_packages\n validates :use_packages, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6579563021659851, "alphanum_fraction": 0.6585413217544556, "avg_line_length": 50.279998779296875, "blob_id": "a547c24149715b8646794aa88434b30406bc913a", "content_id": "fa8928dadebeb8b9cd521d2d65e791f544296b2b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5128, "license_type": "permissive", "max_line_length": 362, "num_lines": 100, "path": "/lib/ansible/ruby/modules/generated/cloud/lxc/lxc_container.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Management of LXC containers\n class Lxc_container < Base\n # @return [String] Name of a container.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:dir, :lvm, :loop, :btrfs, :overlayfs, :zfs, nil] Backend storage type for the container.\n attribute :backing_store\n validates :backing_store, expression_inclusion: {:in=>[:dir, :lvm, :loop, :btrfs, :overlayfs, :zfs], :message=>\"%{value} needs to be :dir, :lvm, :loop, :btrfs, :overlayfs, :zfs\"}, allow_nil: true\n\n # @return [String, nil] Name of the template to use within an LXC create.\n attribute :template\n validates :template, type: String\n\n # @return [String, nil] Template options when building the container.\n attribute :template_options\n validates :template_options, type: String\n\n # @return [Object, nil] Path to the LXC configuration file.\n attribute :config\n\n # @return [String, nil] Name of the logical volume, defaults to the container name.\n attribute :lv_name\n validates :lv_name, type: String\n\n # @return [String, nil] If Backend store is lvm, specify the name of the volume group.\n attribute :vg_name\n validates :vg_name, type: String\n\n # @return [Object, nil] Use LVM thin pool called TP.\n attribute :thinpool\n\n # @return [String, nil] Create fstype TYPE.\n attribute :fs_type\n validates :fs_type, type: String\n\n # @return [String, nil] File system Size.\n attribute :fs_size\n validates :fs_size, type: String\n\n # @return [Object, nil] Place rootfs directory under DIR.\n attribute :directory\n\n # @return [Object, nil] Create zfs under given zfsroot.\n attribute :zfs_root\n\n # @return [String, nil] Run a command within a container.\n attribute :container_command\n validates :container_command, type: String\n\n # @return [Object, nil] Place container under PATH\n attribute :lxc_path\n\n # @return [:yes, :no, nil] Enable a container log for host actions to the container.\n attribute :container_log\n validates :container_log, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:INFO, :ERROR, :DEBUG, nil] Set the log level for a container where *container_log* was set.\n attribute :container_log_level\n validates :container_log_level, expression_inclusion: {:in=>[:INFO, :ERROR, :DEBUG], :message=>\"%{value} needs to be :INFO, :ERROR, :DEBUG\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Name of the new cloned server. This is only used when state is clone.\n attribute :clone_name\n validates :clone_name, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Create a snapshot a container when cloning. This is not supported by all container storage backends. Enabling this may fail if the backing store does not support snapshots.\n attribute :clone_snapshot\n validates :clone_snapshot, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Create an archive of a container. This will create a tarball of the running container.\n attribute :archive\n validates :archive, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Path the save the archived container. If the path does not exist the archive method will attempt to create it.\n attribute :archive_path\n validates :archive_path, type: String\n\n # @return [:gzip, :bzip2, :none, nil] Type of compression to use when creating an archive of a running container.\n attribute :archive_compression\n validates :archive_compression, expression_inclusion: {:in=>[:gzip, :bzip2, :none], :message=>\"%{value} needs to be :gzip, :bzip2, :none\"}, allow_nil: true\n\n # @return [:started, :stopped, :restarted, :absent, :frozen, nil] Define the state of a container. If you clone a container using `clone_name` the newly cloned container created in a stopped state. The running container will be stopped while the clone operation is happening and upon completion of the clone the original container state will be restored.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:started, :stopped, :restarted, :absent, :frozen], :message=>\"%{value} needs to be :started, :stopped, :restarted, :absent, :frozen\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] list of 'key=value' options to use when configuring a container.\n attribute :container_config\n validates :container_config, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6971830725669861, "alphanum_fraction": 0.6983568072319031, "avg_line_length": 53.967742919921875, "blob_id": "7880adc9d45112e1b8f7255f9de176c0df0f482b", "content_id": "95ab1bd15dfd0e669d55f50f91b93c2d00bc95a9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1704, "license_type": "permissive", "max_line_length": 355, "num_lines": 31, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_waf_rule.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Read the AWS documentation for WAF U(https://aws.amazon.com/documentation/waf/)\n class Aws_waf_rule < Base\n # @return [String] Name of the Web Application Firewall rule\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] A friendly name or description for the metrics for the rule,The name can contain only alphanumeric characters (A-Z, a-z, 0-9); the name can't contain whitespace.,You can't change metric_name after you create the rule,Defaults to the same as name with disallowed characters removed\n attribute :metric_name\n\n # @return [:present, :absent, nil] whether the rule should be present or absent\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash, nil] list of conditions used in the rule. Each condition should contain I(type): which is one of [C(byte), C(geo), C(ip), C(size), C(sql) or C(xss)] I(negated): whether the condition should be negated, and C(condition), the name of the existing condition. M(aws_waf_condition) can be used to create new conditions\\r\\n\n attribute :conditions\n validates :conditions, type: TypeGeneric.new(Hash)\n\n # @return [Object, nil] Whether or not to remove conditions that are not passed when updating `conditions`. Defaults to false.\n attribute :purge_conditions\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6738241314888, "alphanum_fraction": 0.6738241314888, "avg_line_length": 46.32258224487305, "blob_id": "4a874db01acc43adc1d25c4d576af8014a9dde34", "content_id": "53a8ce591f5edf23ba9f29dd06fc07b93204bab9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2934, "license_type": "permissive", "max_line_length": 241, "num_lines": 62, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_loadbalancer_rule.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add, update and remove load balancer rules.\n class Cs_loadbalancer_rule < Base\n # @return [String] The name of the load balancer rule.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] The description of the load balancer rule.\n attribute :description\n\n # @return [:source, :roundrobin, :leastconn, nil] Load balancer algorithm,Required when using C(state=present).\n attribute :algorithm\n validates :algorithm, expression_inclusion: {:in=>[:source, :roundrobin, :leastconn], :message=>\"%{value} needs to be :source, :roundrobin, :leastconn\"}, allow_nil: true\n\n # @return [Integer, nil] The private port of the private ip address/virtual machine where the network traffic will be load balanced to.,Required when using C(state=present).,Can not be changed once the rule exists due API limitation.\n attribute :private_port\n validates :private_port, type: Integer\n\n # @return [Integer] The public port from where the network traffic will be load balanced from.,Required when using C(state=present).,Can not be changed once the rule exists due API limitation.\n attribute :public_port\n validates :public_port, presence: true, type: Integer\n\n # @return [Object] Public IP address from where the network traffic will be load balanced from.\n attribute :ip_address\n validates :ip_address, presence: true\n\n # @return [:yes, :no, nil] Whether the firewall rule for public port should be created, while creating the new rule.,Use M(cs_firewall) for managing firewall rules.\n attribute :open_firewall\n validates :open_firewall, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] CIDR (full notation) to be used for firewall rule if required.\n attribute :cidr\n\n # @return [Object, nil] The protocol to be used on the load balancer\n attribute :protocol\n\n # @return [Object, nil] Name of the project the load balancer IP address is related to.\n attribute :project\n\n # @return [:present, :absent, nil] State of the rule.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Domain the rule is related to.\n attribute :domain\n\n # @return [Object, nil] Account the rule is related to.\n attribute :account\n\n # @return [Object, nil] Name of the zone in which the rule should be created.,If not set, default zone is used.\n attribute :zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6930917501449585, "alphanum_fraction": 0.6930917501449585, "avg_line_length": 41.0476188659668, "blob_id": "0fd31ca18e1a799e10718fdb3c7123fa34b3a8e6", "content_id": "fad7cea8f7686bb494827962b9c777bf5b01d3df", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 883, "license_type": "permissive", "max_line_length": 254, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_acm_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Retrieve facts for ACM certificates\n class Aws_acm_facts < Base\n # @return [String, nil] The domain name of an ACM certificate to limit the search to\n attribute :domain_name\n validates :domain_name, type: String\n\n # @return [:PENDING_VALIDATION, :ISSUED, :INACTIVE, :EXPIRED, :VALIDATION_TIMED_OUT, nil] Status to filter the certificate results\n attribute :status\n validates :status, expression_inclusion: {:in=>[:PENDING_VALIDATION, :ISSUED, :INACTIVE, :EXPIRED, :VALIDATION_TIMED_OUT], :message=>\"%{value} needs to be :PENDING_VALIDATION, :ISSUED, :INACTIVE, :EXPIRED, :VALIDATION_TIMED_OUT\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6585366129875183, "alphanum_fraction": 0.6585366129875183, "avg_line_length": 31, "blob_id": "b20b5f10f62ce5f0cc88990b20c1e80374a2db4d", "content_id": "279dab9cec96c004483393d92326aa919d6854bb", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1312, "license_type": "permissive", "max_line_length": 131, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/monitoring/circonus_annotation.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create an annotation event with a given category, title and description. Optionally start, end or durations can be provided\n class Circonus_annotation < Base\n # @return [String] Circonus API key\n attribute :api_key\n validates :api_key, presence: true, type: String\n\n # @return [String] Annotation Category\n attribute :category\n validates :category, presence: true, type: String\n\n # @return [String] Description of annotation\n attribute :description\n validates :description, presence: true, type: String\n\n # @return [String] Title of annotation\n attribute :title\n validates :title, presence: true, type: String\n\n # @return [String, nil] Unix timestamp of event start\n attribute :start\n validates :start, type: String\n\n # @return [String, nil] Unix timestamp of event end\n attribute :stop\n validates :stop, type: String\n\n # @return [Integer, nil] Duration in seconds of annotation\n attribute :duration\n validates :duration, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7179871201515198, "alphanum_fraction": 0.7301428914070129, "avg_line_length": 77.81101989746094, "blob_id": "e2f1349d22e2b4dc727b8fe13b57a310435d495b", "content_id": "6bb8f6620a99dfc9b157e89e6b2ea6e20f679f37", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 30027, "license_type": "permissive", "max_line_length": 696, "num_lines": 381, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_serviceenginegroup.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure ServiceEngineGroup object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_serviceenginegroup < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Symbol, nil] Service engines in active/standby mode for ha failover.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :active_standby\n validates :active_standby, type: Symbol\n\n # @return [Symbol, nil] Advertise reach-ability of backend server networks via adc through bgp for default gateway feature.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :advertise_backend_networks\n validates :advertise_backend_networks, type: Symbol\n\n # @return [Symbol, nil] Enable aggressive failover configuration for ha.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :aggressive_failure_detection\n validates :aggressive_failure_detection, type: Symbol\n\n # @return [Object, nil] In compact placement, virtual services are placed on existing ses until max_vs_per_se limit is reached.,Enum options - PLACEMENT_ALGO_PACKED, PLACEMENT_ALGO_DISTRIBUTED.,Default value when not specified in API or module is interpreted by Avi Controller as PLACEMENT_ALGO_PACKED.\n attribute :algo\n\n # @return [Symbol, nil] Allow ses to be created using burst license.,Field introduced in 17.2.5.\n attribute :allow_burst\n validates :allow_burst, type: Symbol\n\n # @return [Object, nil] Amount of se memory in gb until which shared memory is collected in core archive.,Field introduced in 17.1.3.,Default value when not specified in API or module is interpreted by Avi Controller as 8.,Units(GB).\n attribute :archive_shm_limit\n\n # @return [Symbol, nil] Ssl handshakes will be handled by dedicated ssl threads.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :async_ssl\n validates :async_ssl, type: Symbol\n\n # @return [Object, nil] Number of async ssl threads per se_dp.,Allowed values are 1-16.,Default value when not specified in API or module is interpreted by Avi Controller as 1.\n attribute :async_ssl_threads\n\n # @return [Symbol, nil] If set, virtual services will be automatically migrated when load on an se is less than minimum or more than maximum thresholds.,Only alerts are generated when the auto_rebalance is not set.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :auto_rebalance\n validates :auto_rebalance, type: Symbol\n\n # @return [Object, nil] Capacities of se for auto rebalance for each criteria.,Field introduced in 17.2.4.\n attribute :auto_rebalance_capacity_per_se\n\n # @return [Object, nil] Set of criteria for se auto rebalance.,Enum options - SE_AUTO_REBALANCE_CPU, SE_AUTO_REBALANCE_PPS, SE_AUTO_REBALANCE_MBPS, SE_AUTO_REBALANCE_OPEN_CONNS, SE_AUTO_REBALANCE_CPS.,Field introduced in 17.2.3.\n attribute :auto_rebalance_criteria\n\n # @return [Object, nil] Frequency of rebalance, if 'auto rebalance' is enabled.,Default value when not specified in API or module is interpreted by Avi Controller as 300.,Units(SEC).\n attribute :auto_rebalance_interval\n\n # @return [Symbol, nil] Redistribution of virtual services from the takeover se to the replacement se can cause momentary traffic loss.,If the auto-redistribute load option is left in its default off state, any desired rebalancing requires calls to rest api.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :auto_redistribute_active_standby_load\n validates :auto_redistribute_active_standby_load, type: Symbol\n\n # @return [Object, nil] Excess service engine capacity provisioned for ha failover.,Default value when not specified in API or module is interpreted by Avi Controller as 1.\n attribute :buffer_se\n\n # @return [Object, nil] It is a reference to an object of type cloud.\n attribute :cloud_ref\n\n # @return [Object, nil] Percentage of memory for connection state.,This will come at the expense of memory used for http in-memory cache.,Allowed values are 10-90.,Default value when not specified in API or module is interpreted by Avi Controller as 50.,Units(PERCENT).\n attribute :connection_memory_percentage\n\n # @return [Symbol, nil] Boolean flag to set cpu_reserve.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :cpu_reserve\n validates :cpu_reserve, type: Symbol\n\n # @return [Symbol, nil] Allocate all the cpu cores for the service engine virtual machines on the same cpu socket.,Applicable only for vcenter cloud.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :cpu_socket_affinity\n validates :cpu_socket_affinity, type: Symbol\n\n # @return [Object, nil] Custom security groups to be associated with data vnics for se instances in openstack and aws clouds.,Field introduced in 17.1.3.\n attribute :custom_securitygroups_data\n\n # @return [Object, nil] Custom security groups to be associated with management vnic for se instances in openstack and aws clouds.,Field introduced in 17.1.3.\n attribute :custom_securitygroups_mgmt\n\n # @return [Object, nil] Custom tag will be used to create the tags for se instance in aws.,Note this is not the same as the prefix for se name.\n attribute :custom_tag\n\n # @return [Symbol, nil] Dedicate the core that handles packet receive/transmit from the network to just the dispatching function.,Don't use it for tcp/ip and ssl functions.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :dedicated_dispatcher_core\n validates :dedicated_dispatcher_core, type: Symbol\n\n # @return [Object, nil] User defined description for the object.\n attribute :description\n\n # @return [Symbol, nil] Stop using tcp/udp and ip checksum offload features of nics.,Field introduced in 17.1.14, 17.2.5.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :disable_csum_offloads\n validates :disable_csum_offloads, type: Symbol\n\n # @return [Symbol, nil] Disable generic receive offload (gro) in dpdk poll-mode driver packet receive path.,Gro is on by default on nics that do not support lro (large receive offload) or do not gain performance boost from lro.,Field introduced in 17.2.5.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :disable_gro\n validates :disable_gro, type: Symbol\n\n # @return [Symbol, nil] Disable tcp segmentation offload (tso) in dpdk poll-mode driver packet transmit path.,Tso is on by default on nics that support it.,Field introduced in 17.2.5.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :disable_tso\n validates :disable_tso, type: Symbol\n\n # @return [Object, nil] Amount of disk space for each of the service engine virtual machines.,Default value when not specified in API or module is interpreted by Avi Controller as 10.,Units(GB).\n attribute :disk_per_se\n\n # @return [Symbol, nil] Use both the active and standby service engines for virtual service placement in the legacy active standby ha mode.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :distribute_load_active_standby\n validates :distribute_load_active_standby, type: Symbol\n\n # @return [Symbol, nil] (this is a beta feature).,Enable hsm key priming.,If enabled, key handles on the hsm will be synced to se before processing client connections.,Field introduced in 17.2.7.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :enable_hsm_priming\n validates :enable_hsm_priming, type: Symbol\n\n # @return [Symbol, nil] Enable routing for this serviceenginegroup .,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :enable_routing\n validates :enable_routing, type: Symbol\n\n # @return [Symbol, nil] Enable vip on all interfaces of se.,Field introduced in 17.1.1.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :enable_vip_on_all_interfaces\n validates :enable_vip_on_all_interfaces, type: Symbol\n\n # @return [Symbol, nil] Use virtual mac address for interfaces on which floating interface ips are placed.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :enable_vmac\n validates :enable_vmac, type: Symbol\n\n # @return [Object, nil] Multiplier for extra config to support large vs/pool config.,Default value when not specified in API or module is interpreted by Avi Controller as 0.0.\n attribute :extra_config_multiplier\n\n # @return [Object, nil] Extra config memory to support large geo db configuration.,Field introduced in 17.1.1.,Default value when not specified in API or module is interpreted by Avi Controller as 0.,Units(MB).\n attribute :extra_shared_config_memory\n\n # @return [Object, nil] If serviceenginegroup is configured for legacy 1+1 active standby ha mode, floating ip's will be advertised only by the active se in the pair.,Virtual services in this group must be disabled/enabled for any changes to the floating ip's to take effect.,Only active se hosting vs tagged with active standby se 1 tag will advertise this floating ip when manual load distribution is enabled.\n attribute :floating_intf_ip\n\n # @return [Object, nil] If serviceenginegroup is configured for legacy 1+1 active standby ha mode, floating ip's will be advertised only by the active se in the pair.,Virtual services in this group must be disabled/enabled for any changes to the floating ip's to take effect.,Only active se hosting vs tagged with active standby se 2 tag will advertise this floating ip when manual load distribution is enabled.\n attribute :floating_intf_ip_se_2\n\n # @return [Object, nil] Maximum number of flow table entries that have not completed tcp three-way handshake yet.,Field introduced in 17.2.5.,Default value when not specified in API or module is interpreted by Avi Controller as 0.\n attribute :flow_table_new_syn_max_entries\n\n # @return [Object, nil] High availability mode for all the virtual services using this service engine group.,Enum options - HA_MODE_SHARED_PAIR, HA_MODE_SHARED, HA_MODE_LEGACY_ACTIVE_STANDBY.,Default value when not specified in API or module is interpreted by Avi Controller as HA_MODE_SHARED.\n attribute :ha_mode\n\n # @return [Object, nil] It is a reference to an object of type hardwaresecuritymodulegroup.\n attribute :hardwaresecuritymodulegroup_ref\n\n # @return [Symbol, nil] Enable active health monitoring from the standby se for all placed virtual services.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :hm_on_standby\n validates :hm_on_standby, type: Symbol\n\n # @return [Object, nil] Key of a (key, value) pair identifying a label for a set of nodes usually in container clouds.,Needs to be specified together with host_attribute_value.,Ses can be configured differently including ha modes across different se groups.,May also be used for isolation between different classes of virtualservices.,Virtualservices' se group may be specified via annotations/labels.,A openshift/kubernetes namespace maybe annotated with a matching se group label as openshift.io/node-selector apptype=prod.,When multiple se groups are used in a cloud with host attributes specified,just a single se group can exist as a match-all se group without a,host_attribute_key.\n attribute :host_attribute_key\n\n # @return [Object, nil] Value of a (key, value) pair identifying a label for a set of nodes usually in container clouds.,Needs to be specified together with host_attribute_key.\n attribute :host_attribute_value\n\n # @return [Symbol, nil] Enable the host gateway monitor when service engine is deployed as docker container.,Disabled by default.,Field introduced in 17.2.4.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :host_gateway_monitor\n validates :host_gateway_monitor, type: Symbol\n\n # @return [Object, nil] Override default hypervisor.,Enum options - DEFAULT, VMWARE_ESX, KVM, VMWARE_VSAN, XEN.\n attribute :hypervisor\n\n # @return [Object, nil] Ignore rtt samples if it is above threshold.,Field introduced in 17.1.6,17.2.2.,Default value when not specified in API or module is interpreted by Avi Controller as 5000.,Units(MILLISECONDS).\n attribute :ignore_rtt_threshold\n\n # @return [Object, nil] Program se security group ingress rules to allow vip data access from remote cidr type.,Enum options - SG_INGRESS_ACCESS_NONE, SG_INGRESS_ACCESS_ALL, SG_INGRESS_ACCESS_VPC.,Field introduced in 17.1.5.,Default value when not specified in API or module is interpreted by Avi Controller as SG_INGRESS_ACCESS_ALL.\n attribute :ingress_access_data\n\n # @return [Object, nil] Program se security group ingress rules to allow ssh/icmp management access from remote cidr type.,Enum options - SG_INGRESS_ACCESS_NONE, SG_INGRESS_ACCESS_ALL, SG_INGRESS_ACCESS_VPC.,Field introduced in 17.1.5.,Default value when not specified in API or module is interpreted by Avi Controller as SG_INGRESS_ACCESS_ALL.\n attribute :ingress_access_mgmt\n\n # @return [Object, nil] Instance/flavor type for se instance.\n attribute :instance_flavor\n\n # @return [Object, nil] Iptable rules.\n attribute :iptables\n\n # @return [Symbol, nil] Select core with least load for new flow.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :least_load_core_selection\n validates :least_load_core_selection, type: Symbol\n\n # @return [Object, nil] Specifies the license tier which would be used.,This field by default inherits the value from cloud.,Enum options - ENTERPRISE_16, ENTERPRISE_18.,Field introduced in 17.2.5.\n attribute :license_tier\n\n # @return [Object, nil] If no license type is specified then default license enforcement for the cloud type is chosen.,Enum options - LIC_BACKEND_SERVERS, LIC_SOCKETS, LIC_CORES, LIC_HOSTS, LIC_SE_BANDWIDTH.,Field introduced in 17.2.5.\n attribute :license_type\n\n # @return [Object, nil] Maximum disk capacity (in mb) to be allocated to an se.,This is exclusively used for debug and log data.,Default value when not specified in API or module is interpreted by Avi Controller as 10000.,Units(MB).\n attribute :log_disksz\n\n # @return [Object, nil] When cpu usage on an se exceeds this threshold, virtual services hosted on this se may be rebalanced to other ses to reduce load.,A new se may be created as part of this process.,Allowed values are 40-90.,Default value when not specified in API or module is interpreted by Avi Controller as 80.,Units(PERCENT).\n attribute :max_cpu_usage\n\n # @return [Object, nil] Maximum number of active service engines for the virtual service.,Allowed values are 1-64.,Default value when not specified in API or module is interpreted by Avi Controller as 4.\n attribute :max_scaleout_per_vs\n\n # @return [Object, nil] Maximum number of services engines in this group.,Allowed values are 0-1000.,Default value when not specified in API or module is interpreted by Avi Controller as 10.\n attribute :max_se\n\n # @return [Object, nil] Maximum number of virtual services that can be placed on a single service engine.,East west virtual services are excluded from this limit.,Allowed values are 1-1000.,Default value when not specified in API or module is interpreted by Avi Controller as 10.\n attribute :max_vs_per_se\n\n # @return [Symbol, nil] Boolean flag to set mem_reserve.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :mem_reserve\n validates :mem_reserve, type: Symbol\n\n # @return [Object, nil] Amount of memory for each of the service engine virtual machines.,Default value when not specified in API or module is interpreted by Avi Controller as 2048.\n attribute :memory_per_se\n\n # @return [Object, nil] Management network to use for avi service engines.,It is a reference to an object of type network.\n attribute :mgmt_network_ref\n\n # @return [Object, nil] Management subnet to use for avi service engines.\n attribute :mgmt_subnet\n\n # @return [Object, nil] When cpu usage on an se falls below the minimum threshold, virtual services hosted on the se may be consolidated onto other underutilized ses.,After consolidation, unused service engines may then be eligible for deletion.,Allowed values are 20-60.,Default value when not specified in API or module is interpreted by Avi Controller as 30.,Units(PERCENT).\n attribute :min_cpu_usage\n\n # @return [Object, nil] Minimum number of active service engines for the virtual service.,Allowed values are 1-64.,Default value when not specified in API or module is interpreted by Avi Controller as 1.\n attribute :min_scaleout_per_vs\n\n # @return [String] Name of the object.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] This setting limits the number of non-significant logs generated per second per core on this se.,Default is 100 logs per second.,Set it to zero (0) to disable throttling.,Field introduced in 17.1.3.,Default value when not specified in API or module is interpreted by Avi Controller as 100.,Units(PER_SECOND).\n attribute :non_significant_log_throttle\n\n # @return [Object, nil] Number of changes in num flow cores sum to ignore.,Default value when not specified in API or module is interpreted by Avi Controller as 8.\n attribute :num_flow_cores_sum_changes_to_ignore\n\n # @return [Object, nil] Field deprecated in 17.1.1.\n attribute :openstack_availability_zone\n\n # @return [Object, nil] Field introduced in 17.1.1.\n attribute :openstack_availability_zones\n\n # @return [Object, nil] Avi management network name.\n attribute :openstack_mgmt_network_name\n\n # @return [Object, nil] Management network uuid.\n attribute :openstack_mgmt_network_uuid\n\n # @return [Object, nil] Amount of extra memory to be reserved for use by the operating system on a service engine.,Default value when not specified in API or module is interpreted by Avi Controller as 0.\n attribute :os_reserved_memory\n\n # @return [Symbol, nil] Per-app se mode is designed for deploying dedicated load balancers per app (vs).,In this mode, each se is limited to a max of 2 vss.,Vcpus in per-app ses count towards licensing usage at 25% rate.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :per_app\n validates :per_app, type: Symbol\n\n # @return [Object, nil] If placement mode is 'auto', virtual services are automatically placed on service engines.,Enum options - PLACEMENT_MODE_AUTO.,Default value when not specified in API or module is interpreted by Avi Controller as PLACEMENT_MODE_AUTO.\n attribute :placement_mode\n\n # @return [Object, nil] Enable or disable real time se metrics.\n attribute :realtime_se_metrics\n\n # @return [Object, nil] Select the se bandwidth for the bandwidth license.,Enum options - SE_BANDWIDTH_UNLIMITED, SE_BANDWIDTH_25M, SE_BANDWIDTH_200M, SE_BANDWIDTH_1000M, SE_BANDWIDTH_10000M.,Field introduced in 17.2.5.\n attribute :se_bandwidth_type\n\n # @return [Object, nil] Duration to preserve unused service engine virtual machines before deleting them.,If traffic to a virtual service were to spike up abruptly, this se would still be available to be utilized again rather than creating a new se.,If this value is set to 0, controller will never delete any ses and administrator has to manually cleanup unused ses.,Allowed values are 0-525600.,Default value when not specified in API or module is interpreted by Avi Controller as 120.,Units(MIN).\n attribute :se_deprovision_delay\n\n # @return [Object, nil] Dosthresholdprofile settings for serviceenginegroup.\n attribute :se_dos_profile\n\n # @return [Object, nil] Udp port for se_dp ipc in docker bridge mode.,Field introduced in 17.1.2.,Default value when not specified in API or module is interpreted by Avi Controller as 1500.\n attribute :se_ipc_udp_port\n\n # @return [Object, nil] Prefix to use for virtual machine name of service engines.,Default value when not specified in API or module is interpreted by Avi Controller as Avi.\n attribute :se_name_prefix\n\n # @return [Object, nil] Tcp port on se where echo service will be run.,Field introduced in 17.2.2.,Default value when not specified in API or module is interpreted by Avi Controller as 7.\n attribute :se_probe_port\n\n # @return [Object, nil] Udp port for punted packets in docker bridge mode.,Field introduced in 17.1.2.,Default value when not specified in API or module is interpreted by Avi Controller as 1501.\n attribute :se_remote_punt_udp_port\n\n # @return [Symbol, nil] Sideband traffic will be handled by a dedicated core.,Field introduced in 16.5.2, 17.1.9, 17.2.3.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :se_sb_dedicated_core\n validates :se_sb_dedicated_core, type: Symbol\n\n # @return [Object, nil] Number of sideband threads per se.,Allowed values are 1-128.,Field introduced in 16.5.2, 17.1.9, 17.2.3.,Default value when not specified in API or module is interpreted by Avi Controller as 1.\n attribute :se_sb_threads\n\n # @return [Object, nil] Multiplier for se threads based on vcpu.,Allowed values are 1-10.,Default value when not specified in API or module is interpreted by Avi Controller as 1.\n attribute :se_thread_multiplier\n\n # @return [Object, nil] Determines if dsr from secondary se is active or not 0 automatically determine based on hypervisor type.,1 disable dsr unconditionally.,~[0,1] enable dsr unconditionally.,Field introduced in 17.1.1.,Default value when not specified in API or module is interpreted by Avi Controller as 0.\n attribute :se_tunnel_mode\n\n # @return [Object, nil] Udp port for tunneled packets from secondary to primary se in docker bridge mode.,Field introduced in 17.1.3.,Default value when not specified in API or module is interpreted by Avi Controller as 1550.\n attribute :se_tunnel_udp_port\n\n # @return [Object, nil] Determines if se-se ipc messages are encapsulated in an udp header 0 automatically determine based on hypervisor type.,1 use udp encap unconditionally.,~[0,1] don't use udp encap.,Field introduced in 17.1.2.,Default value when not specified in API or module is interpreted by Avi Controller as 0.\n attribute :se_udp_encap_ipc\n\n # @return [Object, nil] Maximum number of aggregated vs heartbeat packets to send in a batch.,Allowed values are 1-256.,Field introduced in 17.1.1.,Default value when not specified in API or module is interpreted by Avi Controller as 8.\n attribute :se_vs_hb_max_pkts_in_batch\n\n # @return [Object, nil] Maximum number of virtualservices for which heartbeat messages are aggregated in one packet.,Allowed values are 1-1024.,Field introduced in 17.1.1.,Default value when not specified in API or module is interpreted by Avi Controller as 256.\n attribute :se_vs_hb_max_vs_in_pkt\n\n # @return [Object, nil] Subnets assigned to the se group.,Required for vs group placement.,Field introduced in 17.1.1.\n attribute :service_ip_subnets\n\n # @return [Object, nil] This setting limits the number of significant logs generated per second per core on this se.,Default is 100 logs per second.,Set it to zero (0) to disable throttling.,Field introduced in 17.1.3.,Default value when not specified in API or module is interpreted by Avi Controller as 100.,Units(PER_SECOND).\n attribute :significant_log_throttle\n\n # @return [Object, nil] It is a reference to an object of type tenant.\n attribute :tenant_ref\n\n # @return [Object, nil] This setting limits the number of udf logs generated per second per core on this se.,Udf logs are generated due to the configured client log filters or the rules with logging enabled.,Default is 100 logs per second.,Set it to zero (0) to disable throttling.,Field introduced in 17.1.3.,Default value when not specified in API or module is interpreted by Avi Controller as 100.,Units(PER_SECOND).\n attribute :udf_log_throttle\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Unique object identifier of the object.\n attribute :uuid\n\n # @return [Object, nil] Vcenterclusters settings for serviceenginegroup.\n attribute :vcenter_clusters\n\n # @return [Object, nil] Enum options - vcenter_datastore_any, vcenter_datastore_local, vcenter_datastore_shared.,Default value when not specified in API or module is interpreted by Avi Controller as VCENTER_DATASTORE_ANY.\n attribute :vcenter_datastore_mode\n\n # @return [Object, nil] List of vcenterdatastore.\n attribute :vcenter_datastores\n\n # @return [Symbol, nil] Boolean flag to set vcenter_datastores_include.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :vcenter_datastores_include\n validates :vcenter_datastores_include, type: Symbol\n\n # @return [Object, nil] Folder to place all the service engine virtual machines in vcenter.,Default value when not specified in API or module is interpreted by Avi Controller as AviSeFolder.\n attribute :vcenter_folder\n\n # @return [Object, nil] Vcenterhosts settings for serviceenginegroup.\n attribute :vcenter_hosts\n\n # @return [Object, nil] Number of vcpus for each of the service engine virtual machines.,Default value when not specified in API or module is interpreted by Avi Controller as 1.\n attribute :vcpus_per_se\n\n # @return [Symbol, nil] Ensure primary and secondary service engines are deployed on different physical hosts.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :vs_host_redundancy\n validates :vs_host_redundancy, type: Symbol\n\n # @return [Object, nil] Time to wait for the scaled in se to drain existing flows before marking the scalein done.,Default value when not specified in API or module is interpreted by Avi Controller as 30.,Units(SEC).\n attribute :vs_scalein_timeout\n\n # @return [Object, nil] During se upgrade, time to wait for the scaled-in se to drain existing flows before marking the scalein done.,Default value when not specified in API or module is interpreted by Avi Controller as 30.,Units(SEC).\n attribute :vs_scalein_timeout_for_upgrade\n\n # @return [Object, nil] Time to wait for the scaled out se to become ready before marking the scaleout done.,Default value when not specified in API or module is interpreted by Avi Controller as 30.,Units(SEC).\n attribute :vs_scaleout_timeout\n\n # @return [Object, nil] If set, virtual services will be placed on only a subset of the cores of an se.,Field introduced in 17.2.5.\n attribute :vss_placement\n\n # @return [Symbol, nil] Enable memory pool for waf.,Field introduced in 17.2.3.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :waf_mempool\n validates :waf_mempool, type: Symbol\n\n # @return [Object, nil] Memory pool size used for waf.,Field introduced in 17.2.3.,Default value when not specified in API or module is interpreted by Avi Controller as 64.,Units(KB).\n attribute :waf_mempool_size\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6610932350158691, "alphanum_fraction": 0.6610932350158691, "avg_line_length": 41.02702713012695, "blob_id": "aad3f8d4fb31e3811e2109587779b0577abd1703", "content_id": "2eac29008928e1a5cefbbcc18f4f6f40537552f9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1555, "license_type": "permissive", "max_line_length": 161, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/windows/win_xml.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Adds XML fragments formatted as strings to existing XML on remote servers.\n class Win_xml < Base\n # @return [String] The path of remote servers XML.\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [Array<String>, String] The string representation of the XML fragment to be added.\n attribute :fragment\n validates :fragment, presence: true, type: TypeGeneric.new(String)\n\n # @return [String] The node of the remote server XML where the fragment will go.\n attribute :xpath\n validates :xpath, presence: true, type: String\n\n # @return [:yes, :no, nil] Whether to backup the remote server's XML before applying the change.\n attribute :backup\n validates :backup, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:element, :attribute, :text] The type of XML you are working with.\n attribute :type\n validates :type, presence: true, expression_inclusion: {:in=>[:element, :attribute, :text], :message=>\"%{value} needs to be :element, :attribute, :text\"}\n\n # @return [String, nil] The attribute name if the type is 'attribute'. Required if C(type=attribute).\n attribute :attribute\n validates :attribute, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6814263463020325, "alphanum_fraction": 0.6837774515151978, "avg_line_length": 52.16666793823242, "blob_id": "759d17634efbd0571b80f51c544338c5030bb487", "content_id": "9eb12c73ed467937e9c7cb1d10ee8cff20a92648", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2552, "license_type": "permissive", "max_line_length": 198, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/iam_cert.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows for the management of server certificates\n class Iam_cert < Base\n # @return [String] Name of certificate to add, update or remove.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] When state is present, this will update the name of the cert.,The cert, key and cert_chain parameters will be ignored if this is defined.\n attribute :new_name\n validates :new_name, type: String\n\n # @return [Object, nil] When state is present, this will update the path of the cert.,The cert, key and cert_chain parameters will be ignored if this is defined.\n attribute :new_path\n\n # @return [:present, :absent] Whether to create(or update) or delete certificate.,If new_path or new_name is defined, specifying present will attempt to make an update these.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String, nil] When creating or updating, specify the desired path of the certificate.\n attribute :path\n validates :path, type: String\n\n # @return [String, nil] The path to, or content of the CA certificate chain in PEM encoded format. As of 2.4 content is accepted. If the parameter is not a file, it is assumed to be content.\n attribute :cert_chain\n validates :cert_chain, type: String\n\n # @return [String, nil] The path to, or content of the certificate body in PEM encoded format. As of 2.4 content is accepted. If the parameter is not a file, it is assumed to be content.\n attribute :cert\n validates :cert, type: String\n\n # @return [String, nil] The path to, or content of the private key in PEM encoded format. As of 2.4 content is accepted. If the parameter is not a file, it is assumed to be content.\n attribute :key\n validates :key, type: String\n\n # @return [Boolean, nil] By default the module will not upload a certificate that is already uploaded into AWS. If set to True, it will upload the certificate as long as the name is unique.\n attribute :dup_ok\n validates :dup_ok, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7211685180664062, "alphanum_fraction": 0.7222585678100586, "avg_line_length": 75.44999694824219, "blob_id": "c8c64a7b69f1a03aedf4abc8f4359c0b24d23909", "content_id": "55af5faceedddfe472202443398c66fcf1ffe66d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4587, "license_type": "permissive", "max_line_length": 629, "num_lines": 60, "path": "/lib/ansible/ruby/modules/generated/network/cloudvision/cv_server_provision.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows a server team to provision server network ports for new servers without having to access Arista CVP or asking the network team to do it for them. Provide the information for connecting to CVP, switch rack, port the new server is connected to, optional vlan, and an action and the module will apply the configuration to the switch port via CVP. Actions are add (applies template config to port), remove (defaults the interface config) and show (returns the current port config).\n class Cv_server_provision < Base\n # @return [String] The hostname or IP address of the CVP node being connected to.\n attribute :host\n validates :host, presence: true, type: String\n\n # @return [Object, nil] The port number to use when making API calls to the CVP node. This will default to the default port for the specified protocol. Port 80 for http and port 443 for https.\n attribute :port\n\n # @return [:https, :http, nil] The protocol to use when making API calls to CVP. CVP defaults to https and newer versions of CVP no longer support http.\n attribute :protocol\n validates :protocol, expression_inclusion: {:in=>[:https, :http], :message=>\"%{value} needs to be :https, :http\"}, allow_nil: true\n\n # @return [String] The user that will be used to connect to CVP for making API calls.\n attribute :username\n validates :username, presence: true, type: String\n\n # @return [String] The password of the user that will be used to connect to CVP for API calls.\n attribute :password\n validates :password, presence: true, type: String\n\n # @return [String] The hostname or identifier for the server that is having it's switch port provisioned.\n attribute :server_name\n validates :server_name, presence: true, type: String\n\n # @return [String] The hostname of the switch is being configured for the server being provisioned.\n attribute :switch_name\n validates :switch_name, presence: true, type: String\n\n # @return [Integer] The physical port number on the switch that the new server is connected to.\n attribute :switch_port\n validates :switch_port, presence: true, type: Integer\n\n # @return [Integer, nil] The vlan that should be applied to the port for this server. This parameter is dependent on a proper template that supports single vlan provisioning with it. If a port vlan is specified by the template specified does not support this the module will exit out with no changes. If a template is specified that requires a port vlan but no port vlan is specified the module will exit out with no changes.\n attribute :port_vlan\n validates :port_vlan, type: Integer\n\n # @return [String] A path to a Jinja formatted template file that contains the configuration block that will be applied to the specified switch port. This template will have variable fields replaced by the module before being applied to the switch configuration.\n attribute :template\n validates :template, presence: true, type: String\n\n # @return [:show, :add, :remove, nil] The action for the module to take. The actions are add, which applies the specified template config to port, remove, which defaults the specified interface configuration, and show, which will return the current port configuration with no changes.\n attribute :action\n validates :action, expression_inclusion: {:in=>[:show, :add, :remove], :message=>\"%{value} needs to be :show, :add, :remove\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Flag that determines whether or not the module will execute the CVP task spawned as a result of changes to a switch configlet. When an add or remove action is taken which results in a change to a switch configlet, CVP will spawn a task that needs to be executed for the configuration to be applied to the switch. If this option is True then the module will determined the task number created by the configuration change, execute it and wait for the task to complete. If the option is False then the task will remain in the Pending state in CVP for a network administrator to review and execute.\n attribute :auto_run\n validates :auto_run, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7088174819946289, "alphanum_fraction": 0.7190703749656677, "avg_line_length": 59.95833206176758, "blob_id": "dd4d06478294221676925d75482df1316f5bcb81", "content_id": "3273a21f46ae0c428817d13c95aac4d7c43e403a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1463, "license_type": "permissive", "max_line_length": 619, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_file_copy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Copy a file to a remote cloudengine device over SCP on HUAWEI CloudEngine switches.\n class Ce_file_copy < Base\n # @return [Object] Path to local file. Local directory must exist. The maximum length of I(local_file) is C(4096).\n attribute :local_file\n validates :local_file, presence: true\n\n # @return [Object, nil] Remote file path of the copy. Remote directories must exist. If omitted, the name of the local file will be used. The maximum length of I(remote_file) is C(4096).\n attribute :remote_file\n\n # @return [String, nil] The remote file system of the device. If omitted, devices that support a I(file_system) parameter will use their default values. File system indicates the storage medium and can be set to as follows, 1) C(flash) is root directory of the flash memory on the master MPU. 2) C(slave#flash) is root directory of the flash memory on the slave MPU. If no slave MPU exists, this drive is unavailable. 3) C(chassis ID/slot number#flash) is root directory of the flash memory on a device in a stack. For example, C(1/5#flash) indicates the flash memory whose chassis ID is 1 and slot number is 5.\n attribute :file_system\n validates :file_system, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6549502015113831, "alphanum_fraction": 0.6572934985160828, "avg_line_length": 45.135135650634766, "blob_id": "2157d77a7506352bcea09779c5f6459ac2ec36af", "content_id": "7119ae68c958b6651ffa565dd9c09fa3859948db", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1707, "license_type": "permissive", "max_line_length": 170, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_ntp_auth.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages NTP authentication.\n class Nxos_ntp_auth < Base\n # @return [Integer, nil] Authentication key identifier (numeric).\n attribute :key_id\n validates :key_id, type: Integer\n\n # @return [String, nil] MD5 String.\n attribute :md5string\n validates :md5string, type: String\n\n # @return [:text, :encrypt, nil] Whether the given md5string is in cleartext or has been encrypted. If in cleartext, the device will encrypt it before storing it.\n attribute :auth_type\n validates :auth_type, expression_inclusion: {:in=>[:text, :encrypt], :message=>\"%{value} needs to be :text, :encrypt\"}, allow_nil: true\n\n # @return [:false, :true, nil] Whether the given key is required to be supplied by a time source for the device to synchronize to the time source.\n attribute :trusted_key\n validates :trusted_key, expression_inclusion: {:in=>[:false, :true], :message=>\"%{value} needs to be :false, :true\"}, allow_nil: true\n\n # @return [:on, :off, nil] Turns NTP authentication on or off.\n attribute :authentication\n validates :authentication, expression_inclusion: {:in=>[:on, :off], :message=>\"%{value} needs to be :on, :off\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Manage the state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6559366583824158, "alphanum_fraction": 0.6559366583824158, "avg_line_length": 34.75471878051758, "blob_id": "b8934dabac2eec9bf76dd2d0bd30604902fad8d9", "content_id": "2a80e8d8176baf5541cf8561c3afba63f1414b49", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1895, "license_type": "permissive", "max_line_length": 142, "num_lines": 53, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_vpc.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages global VPC configuration\n class Nxos_vpc < Base\n # @return [Integer] VPC domain\n attribute :domain\n validates :domain, presence: true, type: Integer\n\n # @return [Integer, nil] Role priority for device. Remember lower is better.\n attribute :role_priority\n validates :role_priority, type: Integer\n\n # @return [Integer, nil] System priority device. Remember they must match between peers.\n attribute :system_priority\n validates :system_priority, type: Integer\n\n # @return [String, nil] Source IP address used for peer keepalive link\n attribute :pkl_src\n validates :pkl_src, type: String\n\n # @return [String, nil] Destination (remote) IP address used for peer keepalive link\n attribute :pkl_dest\n validates :pkl_dest, type: String\n\n # @return [String, nil] VRF used for peer keepalive link\n attribute :pkl_vrf\n validates :pkl_vrf, type: String\n\n # @return [Symbol, nil] Enables/Disables peer gateway\n attribute :peer_gw\n validates :peer_gw, type: Symbol\n\n # @return [Symbol, nil] Enables/Disables auto recovery\n attribute :auto_recovery\n validates :auto_recovery, type: Symbol\n\n # @return [Symbol, nil] manages delay restore command and config value in seconds\n attribute :delay_restore\n validates :delay_restore, type: Symbol\n\n # @return [:present, :absent] Manages desired state of the resource\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6507061719894409, "alphanum_fraction": 0.672063410282135, "avg_line_length": 68.11904907226562, "blob_id": "f7b82ad09beae88350bbadb05f93d8599c8295e9", "content_id": "7d7da7dde8f748dc87727afd29f43012f32e82bf", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2903, "license_type": "permissive", "max_line_length": 419, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/files/stat.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Retrieves facts for a file similar to the linux/unix 'stat' command.\n # For Windows targets, use the M(win_stat) module instead.\n class Stat < Base\n # @return [String] The full path of the file/object to get the facts of.\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [:yes, :no, nil] Whether to follow symlinks.\n attribute :follow\n validates :follow, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Whether to return the md5 sum of the file.,Will return None if not a regular file or if we're unable to use md5 (Common for FIPS-140 compliant systems).,The default of this option changed from C(yes) to C(no) in Ansible 2.5 and will be removed altogether in Ansible 2.9.,Use C(get_checksum=true) with C(checksum_algorithm=md5) to return an md5 hash under the C(checksum) return value.\n attribute :get_md5\n validates :get_md5, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Whether to return a checksum of the file (default sha1).\n attribute :get_checksum\n validates :get_checksum, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:md5, :sha1, :sha224, :sha256, :sha384, :sha512, nil] Algorithm to determine checksum of file. Will throw an error if the host is unable to use specified algorithm.,The remote host has to support the hashing method specified, C(md5) can be unavailable if the host is FIPS-140 compliant.\n attribute :checksum_algorithm\n validates :checksum_algorithm, expression_inclusion: {:in=>[:md5, :sha1, :sha224, :sha256, :sha384, :sha512], :message=>\"%{value} needs to be :md5, :sha1, :sha224, :sha256, :sha384, :sha512\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Use file magic and return data about the nature of the file. this uses the 'file' utility found on most Linux/Unix systems.,This will add both `mime_type` and 'charset' fields to the return, if possible.,In 2.3 this option changed from 'mime' to 'get_mime' and the default changed to 'Yes'.\n attribute :get_mime\n validates :get_mime, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Get file attributes using lsattr tool if present.\n attribute :get_attributes\n validates :get_attributes, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6962485909461975, "alphanum_fraction": 0.6990481615066528, "avg_line_length": 53.9538459777832, "blob_id": "2cb3f0663be952b3dfd833e5eea983e2bb489337", "content_id": "12b92d3abf154a8b8f0d8e3e82cc014ad26e3a14", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3572, "license_type": "permissive", "max_line_length": 338, "num_lines": 65, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_trafficmanagerendpoint.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and delete Azure Traffic Manager endpoint.\n class Azure_rm_trafficmanagerendpoint < Base\n # @return [String] Name of a resource group where the Traffic Manager endpoint exists or will be created.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] The name of the endpoint.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] Name of Traffic Manager profile where this endpoints attaches to.\n attribute :profile_name\n validates :profile_name, presence: true, type: String\n\n # @return [:azure_endpoints, :external_endpoints, :nested_endpoints] The type of the endpoint.\n attribute :type\n validates :type, presence: true, expression_inclusion: {:in=>[:azure_endpoints, :external_endpoints, :nested_endpoints], :message=>\"%{value} needs to be :azure_endpoints, :external_endpoints, :nested_endpoints\"}\n\n # @return [String, nil] The Azure Resource URI of the of the endpoint.,Not applicable to endpoints of I(type) C(external_endpoints).\n attribute :target_resource_id\n validates :target_resource_id, type: String\n\n # @return [String, nil] The fully-qualified DNS name of the endpoint.\n attribute :target\n validates :target, type: String\n\n # @return [Boolean, nil] The status of the endpoint.\n attribute :enabled\n validates :enabled, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Integer, nil] The weight of this endpoint when traffic manager profile has routing_method of C(weighted).,Possible values are from 1 to 1000.\n attribute :weight\n validates :weight, type: Integer\n\n # @return [Integer, nil] The priority of this endpoint when traffic manager profile has routing_method of C(priority).,Possible values are from 1 to 1000, lower values represent higher priority.,This is an optional parameter. If specified, it must be specified on all endpoints.,No two endpoints can share the same priority value.\n attribute :priority\n validates :priority, type: Integer\n\n # @return [String, nil] Specifies the location of the external or nested endpoints when using the 'Performance' traffic routing method.\n attribute :location\n validates :location, type: String\n\n # @return [Integer, nil] The minimum number of endpoints that must be available in the child profile in order for the parent profile to be considered available.,Only applicable to endpoint of I(type) (nested_endpoints).\n attribute :min_child_endpoints\n validates :min_child_endpoints, type: Integer\n\n # @return [String, nil] The list of countries/regions mapped to this endpoint when traffic manager profile has routing_method of C(geographic).\n attribute :geo_mapping\n validates :geo_mapping, type: String\n\n # @return [:absent, :present, nil] Assert the state of the Traffic Manager endpoint. Use C(present) to create or update a Traffic Manager endpoint and C(absent) to delete it.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6676452159881592, "alphanum_fraction": 0.6795973777770996, "avg_line_length": 53.193180084228516, "blob_id": "8967220b91a5adfa82c6dba0bd1840de4a78d474", "content_id": "7d41d4686ecc643e37b5bcf63059c875b35d346c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4769, "license_type": "permissive", "max_line_length": 230, "num_lines": 88, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_aaa_server_host.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages AAA server host configuration on HUAWEI CloudEngine switches.\n class Ce_aaa_server_host < Base\n # @return [:present, :absent, nil] Specify desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Name of a local user. The value is a string of 1 to 253 characters.\n attribute :local_user_name\n\n # @return [Object, nil] Login password of a user. The password can contain letters, numbers, and special characters. The value is a string of 1 to 255 characters.\n attribute :local_password\n\n # @return [Object, nil] The type of local user login through, such as ftp ssh snmp telnet.\n attribute :local_service_type\n\n # @return [Object, nil] FTP user directory. The value is a string of 1 to 255 characters.\n attribute :local_ftp_dir\n\n # @return [Object, nil] Login level of a local user. The value is an integer ranging from 0 to 15.\n attribute :local_user_level\n\n # @return [Object, nil] Name of the user group where the user belongs. The user inherits all the rights of the user group. The value is a string of 1 to 32 characters.\n attribute :local_user_group\n\n # @return [Object, nil] RADIUS server group's name. The value is a string of 1 to 32 case-insensitive characters.\n attribute :radius_group_name\n\n # @return [:Authentication, :Accounting, nil] Type of Radius Server.\n attribute :radius_server_type\n validates :radius_server_type, expression_inclusion: {:in=>[:Authentication, :Accounting], :message=>\"%{value} needs to be :Authentication, :Accounting\"}, allow_nil: true\n\n # @return [Object, nil] IPv4 address of configured server. The value is a string of 0 to 255 characters, in dotted decimal notation.\n attribute :radius_server_ip\n\n # @return [Object, nil] IPv6 address of configured server. The total length is 128 bits.\n attribute :radius_server_ipv6\n\n # @return [Object, nil] Configured server port for a particular server. The value is an integer ranging from 1 to 65535.\n attribute :radius_server_port\n\n # @return [:\"Secondary-server\", :\"Primary-server\", nil] Configured primary or secondary server for a particular server.\n attribute :radius_server_mode\n validates :radius_server_mode, expression_inclusion: {:in=>[:\"Secondary-server\", :\"Primary-server\"], :message=>\"%{value} needs to be :\\\"Secondary-server\\\", :\\\"Primary-server\\\"\"}, allow_nil: true\n\n # @return [Object, nil] Set VPN instance. The value is a string of 1 to 31 case-sensitive characters.\n attribute :radius_vpn_name\n\n # @return [Object, nil] Hostname of configured server. The value is a string of 0 to 255 case-sensitive characters.\n attribute :radius_server_name\n\n # @return [Object, nil] Name of a HWTACACS template. The value is a string of 1 to 32 case-insensitive characters.\n attribute :hwtacacs_template\n\n # @return [Object, nil] Server IPv4 address. Must be a valid unicast IP address. The value is a string of 0 to 255 characters, in dotted decimal notation.\n attribute :hwtacacs_server_ip\n\n # @return [Object, nil] Server IPv6 address. Must be a valid unicast IP address. The total length is 128 bits.\n attribute :hwtacacs_server_ipv6\n\n # @return [:Authentication, :Authorization, :Accounting, :Common, nil] Hwtacacs server type.\n attribute :hwtacacs_server_type\n validates :hwtacacs_server_type, expression_inclusion: {:in=>[:Authentication, :Authorization, :Accounting, :Common], :message=>\"%{value} needs to be :Authentication, :Authorization, :Accounting, :Common\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Whether the server is secondary.\n attribute :hwtacacs_is_secondary_server\n validates :hwtacacs_is_secondary_server, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] VPN instance name.\n attribute :hwtacacs_vpn_name\n\n # @return [:yes, :no, nil] Set the public-net.\n attribute :hwtacacs_is_public_net\n validates :hwtacacs_is_public_net, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Hwtacacs server host name.\n attribute :hwtacacs_server_host_name\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6565030813217163, "alphanum_fraction": 0.661743700504303, "avg_line_length": 42.72916793823242, "blob_id": "e72bc9004210d5a7ea5ac12c9cab7d1e6962411b", "content_id": "493aff31b1b5567eaaf3fd73975a0fa8b3634657", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2099, "license_type": "permissive", "max_line_length": 152, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_aaa_server_host.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages AAA server host-specific configuration.\n class Nxos_aaa_server_host < Base\n # @return [:radius, :tacacs] The server type is either radius or tacacs.\n attribute :server_type\n validates :server_type, presence: true, expression_inclusion: {:in=>[:radius, :tacacs], :message=>\"%{value} needs to be :radius, :tacacs\"}\n\n # @return [String] Address or name of the radius or tacacs host.\n attribute :address\n validates :address, presence: true, type: String\n\n # @return [String, nil] Shared secret for the specified host or keyword 'default'.\n attribute :key\n validates :key, type: String\n\n # @return [0, 7, nil] The state of encryption applied to the entered key. O for clear text, 7 for encrypted. Type-6 encryption is not supported.\n attribute :encrypt_type\n validates :encrypt_type, expression_inclusion: {:in=>[0, 7], :message=>\"%{value} needs to be 0, 7\"}, allow_nil: true\n\n # @return [Integer, nil] Timeout period for specified host, in seconds or keyword 'default. Range is 1-60.\n attribute :host_timeout\n validates :host_timeout, type: Integer\n\n # @return [Object, nil] Alternate UDP port for RADIUS authentication or keyword 'default'.\n attribute :auth_port\n\n # @return [Integer, nil] Alternate UDP port for RADIUS accounting or keyword 'default'.\n attribute :acct_port\n validates :acct_port, type: Integer\n\n # @return [Integer, nil] Alternate TCP port TACACS Server or keyword 'default'.\n attribute :tacacs_port\n validates :tacacs_port, type: Integer\n\n # @return [:present, :absent, nil] Manage the state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6460122466087341, "alphanum_fraction": 0.6460122466087341, "avg_line_length": 34.434783935546875, "blob_id": "fd038d352f504351b27fe25751c18406320ee81d", "content_id": "c5d7961cd16a037043c0bffaef527a4c5bc1fe58", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1630, "license_type": "permissive", "max_line_length": 127, "num_lines": 46, "path": "/lib/ansible/ruby/modules/generated/system/java_keystore.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or delete a Java keystore in JKS format for a given certificate.\n class Java_keystore < Base\n # @return [String] Name of the certificate.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Certificate that should be used to create the key store.\n attribute :certificate\n validates :certificate, type: String\n\n # @return [String, nil] Private key that should be used to create the key store.\n attribute :private_key\n validates :private_key, type: String\n\n # @return [String, nil] Password that should be used to secure the key store.\n attribute :password\n validates :password, type: String\n\n # @return [String] Absolute path where the jks should be generated.\n attribute :dest\n validates :dest, presence: true, type: String\n\n # @return [Object, nil] Name of the user that should own jks file.\n attribute :owner\n\n # @return [Object, nil] Name of the group that should own jks file.\n attribute :group\n\n # @return [Object, nil] Mode the file should be.\n attribute :mode\n\n # @return [:yes, :no, nil] Key store will be created even if it already exists.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6509971618652344, "alphanum_fraction": 0.6566951274871826, "avg_line_length": 41.54545593261719, "blob_id": "56f23c96b50741382d5679121dcf0c58c3792631", "content_id": "05565ff831d6d38722c10a8b9c3b7ebc3e8c69fb", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1404, "license_type": "permissive", "max_line_length": 147, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_vrf_af.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages VRF AF\n class Nxos_vrf_af < Base\n # @return [String] Name of the VRF.\n attribute :vrf\n validates :vrf, presence: true, type: String\n\n # @return [:ipv4, :ipv6] Address-Family Identifier (AFI).\n attribute :afi\n validates :afi, presence: true, expression_inclusion: {:in=>[:ipv4, :ipv6], :message=>\"%{value} needs to be :ipv4, :ipv6\"}\n\n # @return [:unicast, :multicast] Sub Address-Family Identifier (SAFI).,Deprecated in 2.4\n attribute :safi\n validates :safi, presence: true, expression_inclusion: {:in=>[:unicast, :multicast], :message=>\"%{value} needs to be :unicast, :multicast\"}\n\n # @return [Symbol, nil] Enable/Disable the EVPN route-target 'auto' setting for both import and export target communities.\n attribute :route_target_both_auto_evpn\n validates :route_target_both_auto_evpn, type: Symbol\n\n # @return [:present, :absent, nil] Determines whether the config should be present or not on the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7326202988624573, "alphanum_fraction": 0.7326202988624573, "avg_line_length": 19.77777862548828, "blob_id": "542deb29cdd7fe3ebf7c9d62504b6e93b108a0a9", "content_id": "9e0558e055f297bf916f5474ce5bb1ec9e90e663", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 374, "license_type": "permissive", "max_line_length": 57, "num_lines": 18, "path": "/spec/spec_helper.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'pathname'\n\nif ENV['TRAVIS']\n require 'simplecov'\n SimpleCov.start\nend\n\nspec_dir = Pathname.new('spec')\nDir['spec/support/**/*.rb'].each do |file|\n require Pathname.new(file).relative_path_from(spec_dir)\nend\n\nRSpec.configure do |config|\n config.filter_run_including focus: true\n config.run_all_when_everything_filtered = true\nend\n" }, { "alpha_fraction": 0.689130425453186, "alphanum_fraction": 0.6913043260574341, "avg_line_length": 42.125, "blob_id": "5e1630d4ace3d39412288b012348e8eed48587ab", "content_id": "60b1b7702f8997aa957230bd0eb9ab0d4878c1ca", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1380, "license_type": "permissive", "max_line_length": 269, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_ami_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gather facts about ec2 AMIs\n class Ec2_ami_facts < Base\n # @return [String, nil] One or more image IDs.\n attribute :image_ids\n validates :image_ids, type: String\n\n # @return [Hash, nil] A dict of filters to apply. Each dict item consists of a filter key and a filter value.,See U(https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeImages.html) for possible filters.,Filter names and values are case sensitive.\n attribute :filters\n validates :filters, type: Hash\n\n # @return [String, nil] Filter the images by the owner. Valid options are an AWS account ID, self,,or an AWS owner alias ( amazon | aws-marketplace | microsoft ).\n attribute :owners\n validates :owners, type: String\n\n # @return [Object, nil] Filter images by users with explicit launch permissions. Valid options are an AWS account ID, self, or all (public AMIs).\n attribute :executable_users\n\n # @return [Symbol, nil] Describe attributes (like launchPermission) of the images found.\n attribute :describe_image_attributes\n validates :describe_image_attributes, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6725417375564575, "alphanum_fraction": 0.6725417375564575, "avg_line_length": 36.17241287231445, "blob_id": "8fda23a08f7c6245270ba14b0bee3fb9d492ee56", "content_id": "ff462b742773a0c17e6732e395bfaee86354735a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1078, "license_type": "permissive", "max_line_length": 140, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/source_control/github_issue.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # View GitHub issue for a given repository.\n class Github_issue < Base\n # @return [String] Name of repository from which issue needs to be retrieved.\n attribute :repo\n validates :repo, presence: true, type: String\n\n # @return [String] Name of the GitHub organization in which the repository is hosted.\n attribute :organization\n validates :organization, presence: true, type: String\n\n # @return [Integer] Issue number for which information is required.\n attribute :issue\n validates :issue, presence: true, type: Integer\n\n # @return [get_status, nil] Get various details about issue depending upon action specified.\n attribute :action\n validates :action, expression_inclusion: {:in=>[[\"get_status\"]], :message=>\"%{value} needs to be [\\\"get_status\\\"]\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.709022581577301, "alphanum_fraction": 0.709022581577301, "avg_line_length": 59.45454406738281, "blob_id": "162ec059afc327bba0b27eb5192dfde4bb18c896", "content_id": "669a0ba5faba626db66cf0692f9e566697f98d0f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2660, "license_type": "permissive", "max_line_length": 409, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/system/service.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Controls services on remote hosts. Supported init systems include BSD init, OpenRC, SysV, Solaris SMF, systemd, upstart.\n # For Windows targets, use the M(win_service) module instead.\n class Service < Base\n # @return [String] Name of the service.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:reloaded, :restarted, :started, :stopped, nil] C(started)/C(stopped) are idempotent actions that will not run commands unless necessary. C(restarted) will always bounce the service. C(reloaded) will always reload. B(At least one of state and enabled are required.) Note that reloaded will start the service if it is not already started, even if your chosen init system wouldn't normally.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:reloaded, :restarted, :started, :stopped], :message=>\"%{value} needs to be :reloaded, :restarted, :started, :stopped\"}, allow_nil: true\n\n # @return [Object, nil] If the service is being C(restarted) then sleep this many seconds between the stop and start command. This helps to workaround badly behaving init scripts that exit immediately after signaling a process to stop.\n attribute :sleep\n\n # @return [String, nil] If the service does not respond to the status command, name a substring to look for as would be found in the output of the I(ps) command as a stand-in for a status result. If the string is found, the service will be assumed to be started.\n attribute :pattern\n validates :pattern, type: String\n\n # @return [Symbol, nil] Whether the service should start on boot. B(At least one of state and enabled are required.)\n attribute :enabled\n validates :enabled, type: Symbol\n\n # @return [String, nil] For OpenRC init scripts (ex: Gentoo) only. The runlevel that this service belongs to.\n attribute :runlevel\n validates :runlevel, type: String\n\n # @return [Object, nil] Additional arguments provided on the command line\n attribute :arguments\n\n # @return [String, nil] The service module actually uses system specific modules, normally through auto detection, this setting can force a specific module.,Normally it uses the value of the 'ansible_service_mgr' fact and falls back to the old 'service' module when none matching is found.\n attribute :use\n validates :use, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6606043577194214, "alphanum_fraction": 0.6606043577194214, "avg_line_length": 41.04705810546875, "blob_id": "dfd7c1157dc894fdb348e721dfa66be0d7fb6c6e", "content_id": "d65b35dfdb78b4c1103d06af4dfb38acf7c4c344", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3574, "license_type": "permissive", "max_line_length": 323, "num_lines": 85, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/jira.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create and modify issues in a JIRA instance.\n class Jira < Base\n # @return [String] Base URI for the JIRA instance.\n attribute :uri\n validates :uri, presence: true, type: String\n\n # @return [:create, :comment, :edit, :fetch, :transition, :link] The operation to perform.\n attribute :operation\n validates :operation, presence: true, expression_inclusion: {:in=>[:create, :comment, :edit, :fetch, :transition, :link], :message=>\"%{value} needs to be :create, :comment, :edit, :fetch, :transition, :link\"}\n\n # @return [String] The username to log-in with.\n attribute :username\n validates :username, presence: true, type: String\n\n # @return [String] The password to log-in with.\n attribute :password\n validates :password, presence: true, type: String\n\n # @return [String, nil] The project for this operation. Required for issue creation.\n attribute :project\n validates :project, type: String\n\n # @return [String, nil] The issue summary, where appropriate.\n attribute :summary\n validates :summary, type: String\n\n # @return [String, nil] The issue description, where appropriate.\n attribute :description\n validates :description, type: String\n\n # @return [String, nil] The issue type, for issue creation.\n attribute :issuetype\n validates :issuetype, type: String\n\n # @return [String, nil] An existing issue key to operate on.\n attribute :issue\n validates :issue, type: String\n\n # @return [String, nil] The comment text to add.\n attribute :comment\n validates :comment, type: String\n\n # @return [String, nil] The desired status; only relevant for the transition operation.\n attribute :status\n validates :status, type: String\n\n # @return [String, nil] Sets the assignee on create or transition operations. Note not all transitions will allow this.\n attribute :assignee\n validates :assignee, type: String\n\n # @return [String, nil] Set type of link, when action 'link' selected.\n attribute :linktype\n validates :linktype, type: String\n\n # @return [String, nil] Set issue from which link will be created.\n attribute :inwardissue\n validates :inwardissue, type: String\n\n # @return [String, nil] Set issue to which link will be created.\n attribute :outwardissue\n validates :outwardissue, type: String\n\n # @return [Hash, nil] This is a free-form data structure that can contain arbitrary data. This is passed directly to the JIRA REST API (possibly after merging with other required data, as when passed to create). See examples for more information, and the JIRA REST API for the structure required for various fields.\n attribute :fields\n validates :fields, type: Hash\n\n # @return [Integer, nil] Set timeout, in seconds, on requests to JIRA API.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [Boolean, nil] Require valid SSL certificates (set to `false` if you'd like to use self-signed certificates)\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7088906168937683, "alphanum_fraction": 0.7088906168937683, "avg_line_length": 49.84000015258789, "blob_id": "4a3631a1d36e24ad3ae122387959ea7c27ae19bd", "content_id": "46ee82015d1f7affd954ae683136d4f4ff79bd70", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1271, "license_type": "permissive", "max_line_length": 388, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/windows/win_group_membership.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows the addition and removal of local, service and domain users, and domain groups from a local group.\n class Win_group_membership < Base\n # @return [String] Name of the local group to manage membership on.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Array<String>, String] A list of members to ensure are present/absent from the group.,Accepts local users as .\\username, and SERVERNAME\\username.,Accepts domain users and groups as DOMAIN\\username and username@DOMAIN.,Accepts service users as NT AUTHORITY\\username.,Accepts all local, domain and service user types as username, favoring domain lookups when in a domain.\n attribute :members\n validates :members, presence: true, type: TypeGeneric.new(String)\n\n # @return [:absent, :present, nil] Desired state of the members in the group.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6550230383872986, "alphanum_fraction": 0.6612510085105896, "avg_line_length": 46.96104049682617, "blob_id": "523baf9c2b21621dfee9f3aed925f7203dcc048a", "content_id": "1f9f187b547ad19832c5c3aadd7317c9336a3a82", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3693, "license_type": "permissive", "max_line_length": 184, "num_lines": 77, "path": "/lib/ansible/ruby/modules/generated/cloud/profitbricks/profitbricks_volume.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows you to create or remove a volume from a ProfitBricks datacenter. This module has a dependency on profitbricks >= 1.0.0\n class Profitbricks_volume < Base\n # @return [String] The datacenter in which to create the volumes.\n attribute :datacenter\n validates :datacenter, presence: true, type: String\n\n # @return [String] The name of the volumes. You can enumerate the names using auto_increment.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Integer, nil] The size of the volume.\n attribute :size\n validates :size, type: Integer\n\n # @return [:IDE, :VIRTIO, nil] The bus type.\n attribute :bus\n validates :bus, expression_inclusion: {:in=>[:IDE, :VIRTIO], :message=>\"%{value} needs to be :IDE, :VIRTIO\"}, allow_nil: true\n\n # @return [Object] The system image ID for the volume, e.g. a3eae284-a2fe-11e4-b187-5f1f641608c8. This can also be a snapshot image ID.\n attribute :image\n validates :image, presence: true\n\n # @return [Object, nil] Password set for the administrative user.\n attribute :image_password\n\n # @return [Object, nil] Public SSH keys allowing access to the virtual machine.\n attribute :ssh_keys\n\n # @return [:HDD, :SSD, nil] The disk type of the volume.\n attribute :disk_type\n validates :disk_type, expression_inclusion: {:in=>[:HDD, :SSD], :message=>\"%{value} needs to be :HDD, :SSD\"}, allow_nil: true\n\n # @return [:LINUX, :WINDOWS, :UNKNOWN, :OTHER, nil] The licence type for the volume. This is used when the image is non-standard.\n attribute :licence_type\n validates :licence_type, expression_inclusion: {:in=>[:LINUX, :WINDOWS, :UNKNOWN, :OTHER], :message=>\"%{value} needs to be :LINUX, :WINDOWS, :UNKNOWN, :OTHER\"}, allow_nil: true\n\n # @return [Integer, nil] The number of volumes you wish to create.\n attribute :count\n validates :count, type: Integer\n\n # @return [Boolean, nil] Whether or not to increment a single number in the name for created virtual machines.\n attribute :auto_increment\n validates :auto_increment, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] list of instance ids, currently only used when state='absent' to remove instances.\n attribute :instance_ids\n validates :instance_ids, type: TypeGeneric.new(String)\n\n # @return [Object, nil] The ProfitBricks username. Overrides the PB_SUBSCRIPTION_ID environment variable.\n attribute :subscription_user\n\n # @return [Object, nil] THe ProfitBricks password. Overrides the PB_PASSWORD environment variable.\n attribute :subscription_password\n\n # @return [:yes, :no, nil] wait for the datacenter to be created before returning\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] how long before wait gives up, in seconds\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [:present, :absent, nil] create or terminate datacenters\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6450116038322449, "alphanum_fraction": 0.6450116038322449, "avg_line_length": 39.093021392822266, "blob_id": "b1d0e292b7d7605d46763b61ddcb628b7fc31326", "content_id": "a9bfad0ad406d3a611ca2c6ce191e158605c7b4a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1724, "license_type": "permissive", "max_line_length": 150, "num_lines": 43, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/ansible_tower/tower_job_launch.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Launch an Ansible Tower jobs. See U(https://www.ansible.com/tower) for an overview.\n class Tower_job_launch < Base\n # @return [String] Name of the job template to use.\n attribute :job_template\n validates :job_template, presence: true, type: String\n\n # @return [Object, nil] Job explanation field.\n attribute :job_explanation\n\n # @return [:run, :check, :scan, nil] Job_type to use for the job, only used if prompt for job_type is set.\n attribute :job_type\n validates :job_type, expression_inclusion: {:in=>[:run, :check, :scan], :message=>\"%{value} needs to be :run, :check, :scan\"}, allow_nil: true\n\n # @return [Object, nil] Inventory to use for the job, only used if prompt for inventory is set.\n attribute :inventory\n\n # @return [Object, nil] Credential to use for job, only used if prompt for credential is set.\n attribute :credential\n\n # @return [Object, nil] Extra_vars to use for the job_template. Prepend C(@) if a file.\n attribute :extra_vars\n\n # @return [Object, nil] Limit to use for the I(job_template).\n attribute :limit\n\n # @return [Object, nil] Specific tags to use for from playbook.\n attribute :tags\n\n # @return [:yes, :no, nil] Disable launching jobs from job template.\n attribute :use_job_endpoint\n validates :use_job_endpoint, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.695838451385498, "alphanum_fraction": 0.6970624327659607, "avg_line_length": 48.51515197753906, "blob_id": "1222eeb443e65da31ad06e191f326979a27c51d8", "content_id": "f3d744f7121afd4bbb5f1e4094b17a095b02f782", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1634, "license_type": "permissive", "max_line_length": 564, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gce_labels.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, Update or Destroy GCE Labels on instances, disks, snapshots, etc. When specifying the GCE resource, users may specifiy the full URL for the resource (its 'self_link'), or the individual parameters of the resource (type, location, name). Examples for the two options can be seen in the documentaion. See U(https://cloud.google.com/compute/docs/label-or-tag-resources) for more information about GCE Labels. Labels are gradually being added to more GCE resources, so this module will need to be updated as new resources are added to the GCE (v1) API.\n class Gce_labels < Base\n # @return [Hash, nil] A list of labels (key/value pairs) to add or remove for the resource.\n attribute :labels\n validates :labels, type: Hash\n\n # @return [String, nil] The 'self_link' for the resource (instance, disk, snapshot, etc)\n attribute :resource_url\n validates :resource_url, type: String\n\n # @return [String, nil] The type of resource (instances, disks, snapshots, images)\n attribute :resource_type\n validates :resource_type, type: String\n\n # @return [String, nil] The location of resource (global, us-central1-f, etc.)\n attribute :resource_location\n validates :resource_location, type: String\n\n # @return [String, nil] The name of resource.\n attribute :resource_name\n validates :resource_name, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6906474828720093, "alphanum_fraction": 0.6906474828720093, "avg_line_length": 25.0625, "blob_id": "8e56837ca3725820c005378b42108046c8208d69", "content_id": "08d62f6dcaa5037a9618c82e6e2599b853d80949", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 417, "license_type": "permissive", "max_line_length": 76, "num_lines": 16, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_vsan_cluster.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to configure VSAN clustering on an ESXi host\n class Vmware_vsan_cluster < Base\n # @return [Object, nil] Desired cluster UUID\n attribute :cluster_uuid\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.671832263469696, "alphanum_fraction": 0.6724399924278259, "avg_line_length": 61.09434127807617, "blob_id": "ae64fabf1a6e2d5034f8e8f50f9dfa3cf72f3de7", "content_id": "24dbb49ba68a0602d4b7c329017add06c252398f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3291, "license_type": "permissive", "max_line_length": 365, "num_lines": 53, "path": "/lib/ansible/ruby/modules/generated/files/acl.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Sets and retrieves file ACL information.\n class Acl < Base\n # @return [String] The full path of the file or object.\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [:absent, :present, :query, nil] defines whether the ACL should be present or not. The C(query) state gets the current acl without changing it, for use in 'register' operations.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n\n # @return [:yes, :no, nil] whether to follow symlinks on the path if a symlink is encountered.\n attribute :follow\n validates :follow, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] if the target is a directory, setting this to yes will make it the default acl for entities created inside the directory. It causes an error if path is a file.\n attribute :default\n validates :default, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] actual user or group that the ACL applies to when matching entity types user or group are selected.\n attribute :entity\n validates :entity, type: String\n\n # @return [:group, :mask, :other, :user, nil] the entity type of the ACL to apply, see setfacl documentation for more info.\n attribute :etype\n validates :etype, expression_inclusion: {:in=>[:group, :mask, :other, :user], :message=>\"%{value} needs to be :group, :mask, :other, :user\"}, allow_nil: true\n\n # @return [String, nil] Permissions to apply/remove can be any combination of r, w and x (read, write and execute respectively)\n attribute :permissions\n validates :permissions, type: String\n\n # @return [String, nil] DEPRECATED. The acl to set or remove. This must always be quoted in the form of '<etype>:<qualifier>:<perms>'. The qualifier may be empty for some types, but the type and perms are always required. '-' can be used as placeholder when you do not care about permissions. This is now superseded by entity, type and permissions fields.\n attribute :entry\n validates :entry, type: String\n\n # @return [:yes, :no, nil] Recursively sets the specified ACL (added in Ansible 2.0). Incompatible with C(state=query).\n attribute :recursive\n validates :recursive, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:default, :mask, :no_mask, nil] Select if and when to recalculate the effective right masks of the files, see setfacl documentation for more info. Incompatible with C(state=query).\n attribute :recalculate_mask\n validates :recalculate_mask, expression_inclusion: {:in=>[:default, :mask, :no_mask], :message=>\"%{value} needs to be :default, :mask, :no_mask\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6871062517166138, "alphanum_fraction": 0.6887862086296082, "avg_line_length": 50.760868072509766, "blob_id": "96b381740a6354c6ae28145a10debe590e7692c8", "content_id": "9bdfdb49711036f9972004fc713bce2d8c360a1c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2381, "license_type": "permissive", "max_line_length": 360, "num_lines": 46, "path": "/lib/ansible/ruby/modules/generated/network/junos/junos_linkagg.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of link aggregation groups on Juniper JUNOS network devices.\n class Junos_linkagg < Base\n # @return [String] Name of the link aggregation group.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Boolean, nil] Mode of the link aggregation group. A value of C(on) will enable LACP in C(passive) mode. C(active) configures the link to actively information about the state of the link, or it can be configured in C(passive) mode ie. send link state information only when received them from another link. A value of C(off) will disable LACP.\n attribute :mode\n validates :mode, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Array<String>, String] List of members interfaces of the link aggregation group. The value can be single interface or list of interfaces.\n attribute :members\n validates :members, presence: true, type: TypeGeneric.new(String)\n\n # @return [Object, nil] Minimum members that should be up before bringing up the link aggregation group.\n attribute :min_links\n\n # @return [Integer, nil] Number of aggregated ethernet devices that can be configured. Acceptable integer value is between 1 and 128.\n attribute :device_count\n validates :device_count, type: Integer\n\n # @return [Object, nil] Description of Interface.\n attribute :description\n\n # @return [Object, nil] List of link aggregation definitions.\n attribute :aggregate\n\n # @return [:present, :absent, :up, :down, nil] State of the link aggregation group.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :up, :down], :message=>\"%{value} needs to be :present, :absent, :up, :down\"}, allow_nil: true\n\n # @return [Boolean, nil] Specifies whether or not the configuration is active or deactivated\n attribute :active\n validates :active, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6727706789970398, "alphanum_fraction": 0.6727706789970398, "avg_line_length": 37.06060791015625, "blob_id": "e2b4c6a3d02ca41560b02456bb1911453d2b44db", "content_id": "fc58f4dc82eb564c94a56c3c3f1469d1f5eb334d", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1256, "license_type": "permissive", "max_line_length": 143, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_software_update.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Update ONTAP software\n class Na_ontap_software_update < Base\n # @return [:present, :absent, nil] Whether the specified ONTAP package should update or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] List of nodes to be updated, the nodes have to be a part of a HA Pair.\n attribute :node\n validates :node, type: String\n\n # @return [String] Specifies the package version.\n attribute :package_version\n validates :package_version, presence: true, type: String\n\n # @return [String] Specifies the package URL.\n attribute :package_url\n validates :package_url, presence: true, type: String\n\n # @return [Symbol, nil] Allows the update to continue if warnings are encountered during the validation phase.\n attribute :ignore_validation_warning\n validates :ignore_validation_warning, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6986272931098938, "alphanum_fraction": 0.7015390992164612, "avg_line_length": 63.106666564941406, "blob_id": "eb6549a06e4aede0453876bcde31900d30f36c97", "content_id": "e8b1553dd79b67ef8f9d3b88ae7b845f0331628f", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4808, "license_type": "permissive", "max_line_length": 344, "num_lines": 75, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/netapp_e_mgmt_interface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configure the E-Series management interfaces\n class Netapp_e_mgmt_interface < Base\n # @return [:enable, :disable, nil] Enable or disable IPv4 network interface configuration.,Either IPv4 or IPv6 must be enabled otherwise error will occur.,Only required when enabling or disabling IPv4 network interface\n attribute :state\n validates :state, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:A, :B] The controller that owns the port you want to configure.,Controller names are represented alphabetically, with the first controller as A, the second as B, and so on.,Current hardware models have either 1 or 2 available controllers, but that is not a guaranteed hard limitation and could change in the future.\n attribute :controller\n validates :controller, presence: true, expression_inclusion: {:in=>[:A, :B], :message=>\"%{value} needs to be :A, :B\"}\n\n # @return [String, nil] The port to modify the configuration for.,The list of choices is not necessarily comprehensive. It depends on the number of ports that are present in the system.,The name represents the port number (typically from left to right on the controller), beginning with a value of 1.,Mutually exclusive with I(channel).\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] The port to modify the configuration for.,The channel represents the port number (typically from left to right on the controller), beginning with a value of 1.,Mutually exclusive with I(name).\n attribute :channel\n\n # @return [String, nil] The IPv4 address to assign to the interface.,Should be specified in xx.xx.xx.xx form.,Mutually exclusive with I(config_method=dhcp)\n attribute :address\n validates :address, type: String\n\n # @return [String, nil] The subnet mask to utilize for the interface.,Should be specified in xx.xx.xx.xx form.,Mutually exclusive with I(config_method=dhcp)\n attribute :subnet_mask\n validates :subnet_mask, type: String\n\n # @return [String, nil] The IPv4 gateway address to utilize for the interface.,Should be specified in xx.xx.xx.xx form.,Mutually exclusive with I(config_method=dhcp)\n attribute :gateway\n validates :gateway, type: String\n\n # @return [:dhcp, :static, nil] The configuration method type to use for network interface ports.,dhcp is mutually exclusive with I(address), I(subnet_mask), and I(gateway).\n attribute :config_method\n validates :config_method, expression_inclusion: {:in=>[:dhcp, :static], :message=>\"%{value} needs to be :dhcp, :static\"}, allow_nil: true\n\n # @return [:dhcp, :static, nil] The configuration method type to use for DNS services.,dhcp is mutually exclusive with I(dns_address), and I(dns_address_backup).\n attribute :dns_config_method\n validates :dns_config_method, expression_inclusion: {:in=>[:dhcp, :static], :message=>\"%{value} needs to be :dhcp, :static\"}, allow_nil: true\n\n # @return [String, nil] Primary IPv4 DNS server address\n attribute :dns_address\n validates :dns_address, type: String\n\n # @return [String, nil] Backup IPv4 DNS server address,Queried when primary DNS server fails\n attribute :dns_address_backup\n validates :dns_address_backup, type: String\n\n # @return [:disable, :dhcp, :static, nil] The configuration method type to use for NTP services.,disable is mutually exclusive with I(ntp_address) and I(ntp_address_backup).,dhcp is mutually exclusive with I(ntp_address) and I(ntp_address_backup).\n attribute :ntp_config_method\n validates :ntp_config_method, expression_inclusion: {:in=>[:disable, :dhcp, :static], :message=>\"%{value} needs to be :disable, :dhcp, :static\"}, allow_nil: true\n\n # @return [String, nil] Primary IPv4 NTP server address\n attribute :ntp_address\n validates :ntp_address, type: String\n\n # @return [String, nil] Backup IPv4 NTP server address,Queried when primary NTP server fails\n attribute :ntp_address_backup\n validates :ntp_address_backup, type: String\n\n # @return [Symbol, nil] Enable ssh access to the controller for debug purposes.,This is a controller-level setting.,rlogin/telnet will be enabled for ancient equipment where ssh is not available.\n attribute :ssh\n validates :ssh, type: Symbol\n\n # @return [Object, nil] A local path to a file to be used for debug logging\n attribute :log_path\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6756183505058289, "alphanum_fraction": 0.6777384877204895, "avg_line_length": 47.7931022644043, "blob_id": "f0dc98025be8cf599e51d908b623024748ac0766", "content_id": "cacbe061e77a3e529013bade8bc91a2f32a10456", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1415, "license_type": "permissive", "max_line_length": 214, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_tag.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates, removes and lists tags for any EC2 resource. The resource is referenced by its resource id (e.g. an instance being i-XXXXXXX). It is designed to be used with complex args (tags), see the examples.\n class Ec2_tag < Base\n # @return [String] The EC2 resource id.\n attribute :resource\n validates :resource, presence: true, type: String\n\n # @return [:present, :absent, :list, nil] Whether the tags should be present or absent on the resource. Use list to interrogate the tags of an instance.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :list], :message=>\"%{value} needs to be :present, :absent, :list\"}, allow_nil: true\n\n # @return [Hash] a hash/dictionary of tags to add to the resource; '{\"key\":\"value\"}' and '{\"key\":\"value\",\"key\":\"value\"}'\n attribute :tags\n validates :tags, presence: true, type: Hash\n\n # @return [Symbol, nil] Whether unspecified tags should be removed from the resource.,Note that when combined with C(state: absent), specified tags with non-matching values are not purged.\n attribute :purge_tags\n validates :purge_tags, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6689655184745789, "alphanum_fraction": 0.6689655184745789, "avg_line_length": 35.25, "blob_id": "81a0db71551f49b796b2676f8ac7fcc7c165254e", "content_id": "0a67b29b3f1b48454ee15274c63df02b0e0d4194", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1160, "license_type": "permissive", "max_line_length": 143, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/cloud/webfaction/webfaction_domain.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove domains or subdomains on a Webfaction host. Further documentation at https://github.com/quentinsf/ansible-webfaction.\n class Webfaction_domain < Base\n # @return [String] The name of the domain\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Whether the domain should exist\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Any subdomains to create.\n attribute :subdomains\n\n # @return [String] The webfaction account to use\n attribute :login_name\n validates :login_name, presence: true, type: String\n\n # @return [String] The webfaction password to use\n attribute :login_password\n validates :login_password, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6971285939216614, "alphanum_fraction": 0.6978776454925537, "avg_line_length": 54.625, "blob_id": "c48749b151fb3df37cd52a08cce59a6619455eac", "content_id": "33a8fb283052941dfe2a1ad1b94b557b4824f1e3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4005, "license_type": "permissive", "max_line_length": 330, "num_lines": 72, "path": "/lib/ansible/ruby/modules/generated/monitoring/sensu_client.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages Sensu client configuration.\n # For more information, refer to the Sensu documentation: U(https://sensuapp.org/docs/latest/reference/clients.html)\n class Sensu_client < Base\n # @return [:present, :absent, nil] Whether the client should be present or not\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] A unique name for the client. The name cannot contain special characters or spaces.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] An address to help identify and reach the client. This is only informational, usually an IP address or hostname.\n attribute :address\n validates :address, type: String\n\n # @return [Array<String>, String] An array of client subscriptions, a list of roles and/or responsibilities assigned to the system (e.g. webserver).,These subscriptions determine which monitoring checks are executed by the client, as check requests are sent to subscriptions.,The subscriptions array items must be strings.\n attribute :subscriptions\n validates :subscriptions, presence: true, type: TypeGeneric.new(String)\n\n # @return [:yes, :no, nil] If safe mode is enabled for the client. Safe mode requires local check definitions in order to accept a check request and execute the check.\n attribute :safe_mode\n validates :safe_mode, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] Client definition attributes to redact (values) when logging and sending client keepalives.\n attribute :redact\n validates :redact, type: TypeGeneric.new(String)\n\n # @return [Hash, nil] The socket definition scope, used to configure the Sensu client socket.\n attribute :socket\n validates :socket, type: Hash\n\n # @return [:yes, :no, nil] If Sensu should monitor keepalives for this client.\n attribute :keepalives\n validates :keepalives, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Hash, nil] The keepalive definition scope, used to configure Sensu client keepalives behavior (e.g. keepalive thresholds, etc).\n attribute :keepalive\n validates :keepalive, type: Hash\n\n # @return [Object, nil] The registration definition scope, used to configure Sensu registration event handlers.\n attribute :registration\n\n # @return [:yes, :no, nil] If a deregistration event should be created upon Sensu client process stop.\n attribute :deregister\n validates :deregister, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] The deregistration definition scope, used to configure automated Sensu client de-registration.\n attribute :deregistration\n\n # @return [Object, nil] The ec2 definition scope, used to configure the Sensu Enterprise AWS EC2 integration (Sensu Enterprise users only).\n attribute :ec2\n\n # @return [Object, nil] The chef definition scope, used to configure the Sensu Enterprise Chef integration (Sensu Enterprise users only).\n attribute :chef\n\n # @return [Object, nil] The puppet definition scope, used to configure the Sensu Enterprise Puppet integration (Sensu Enterprise users only).\n attribute :puppet\n\n # @return [Object, nil] The servicenow definition scope, used to configure the Sensu Enterprise ServiceNow integration (Sensu Enterprise users only).\n attribute :servicenow\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6994701027870178, "alphanum_fraction": 0.7129279375076294, "avg_line_length": 65.41899108886719, "blob_id": "1b20877598750c4e95428f7225e6ec25900c6148", "content_id": "273299e1e13705c6bb0350dc85e32d016040921a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 11889, "license_type": "permissive", "max_line_length": 271, "num_lines": 179, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_controllerproperties.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure ControllerProperties object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_controllerproperties < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Symbol, nil] Field introduced in 17.1.1.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :allow_ip_forwarding\n validates :allow_ip_forwarding, type: Symbol\n\n # @return [Symbol, nil] Allow unauthenticated access for special apis.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :allow_unauthenticated_apis\n validates :allow_unauthenticated_apis, type: Symbol\n\n # @return [Symbol, nil] Boolean flag to set allow_unauthenticated_nodes.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :allow_unauthenticated_nodes\n validates :allow_unauthenticated_nodes, type: Symbol\n\n # @return [Object, nil] Allowed values are 0-1440.,Default value when not specified in API or module is interpreted by Avi Controller as 15.,Units(MIN).\n attribute :api_idle_timeout\n\n # @return [Symbol, nil] Export configuration in appviewx compatibility mode.,Field introduced in 17.1.1.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :appviewx_compat_mode\n validates :appviewx_compat_mode, type: Symbol\n\n # @return [Object, nil] Number of attach_ip_retry_interval.,Default value when not specified in API or module is interpreted by Avi Controller as 360.,Units(SEC).\n attribute :attach_ip_retry_interval\n\n # @return [Object, nil] Number of attach_ip_retry_limit.,Default value when not specified in API or module is interpreted by Avi Controller as 4.\n attribute :attach_ip_retry_limit\n\n # @return [Symbol, nil] Use ansible for se creation in baremetal.,Field introduced in 17.2.2.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :bm_use_ansible\n validates :bm_use_ansible, type: Symbol\n\n # @return [Object, nil] Number of cluster_ip_gratuitous_arp_period.,Default value when not specified in API or module is interpreted by Avi Controller as 60.,Units(MIN).\n attribute :cluster_ip_gratuitous_arp_period\n\n # @return [Object, nil] Number of crashed_se_reboot.,Default value when not specified in API or module is interpreted by Avi Controller as 900.,Units(SEC).\n attribute :crashed_se_reboot\n\n # @return [Object, nil] Number of dead_se_detection_timer.,Default value when not specified in API or module is interpreted by Avi Controller as 360.,Units(SEC).\n attribute :dead_se_detection_timer\n\n # @return [Object, nil] Number of dns_refresh_period.,Default value when not specified in API or module is interpreted by Avi Controller as 60.,Units(MIN).\n attribute :dns_refresh_period\n\n # @return [Object, nil] Number of dummy.\n attribute :dummy\n\n # @return [Symbol, nil] Enable/disable memory balancer.,Field introduced in 17.2.8.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :enable_memory_balancer\n validates :enable_memory_balancer, type: Symbol\n\n # @return [Object, nil] Number of fatal_error_lease_time.,Default value when not specified in API or module is interpreted by Avi Controller as 120.,Units(SEC).\n attribute :fatal_error_lease_time\n\n # @return [Object, nil] Number of max_dead_se_in_grp.,Default value when not specified in API or module is interpreted by Avi Controller as 1.\n attribute :max_dead_se_in_grp\n\n # @return [Object, nil] Maximum number of pcap files stored per tenant.,Default value when not specified in API or module is interpreted by Avi Controller as 4.\n attribute :max_pcap_per_tenant\n\n # @return [Object, nil] Maximum number of consecutive attach ip failures that halts vs placement.,Field introduced in 17.2.2.,Default value when not specified in API or module is interpreted by Avi Controller as 3.\n attribute :max_seq_attach_ip_failures\n\n # @return [Object, nil] Number of max_seq_vnic_failures.,Default value when not specified in API or module is interpreted by Avi Controller as 3.\n attribute :max_seq_vnic_failures\n\n # @return [Object, nil] Allowed values are 1-1051200.,Special values are 0 - 'disabled'.,Default value when not specified in API or module is interpreted by Avi Controller as 60.,Units(MIN).\n attribute :persistence_key_rotate_period\n\n # @return [Object, nil] Token used for uploading tech-support to portal.,Field introduced in 16.4.6,17.1.2.\n attribute :portal_token\n\n # @return [Object, nil] Number of query_host_fail.,Default value when not specified in API or module is interpreted by Avi Controller as 180.,Units(SEC).\n attribute :query_host_fail\n\n # @return [Object, nil] Version of the safenet package installed on the controller.,Field introduced in 16.5.2,17.2.3.\n attribute :safenet_hsm_version\n\n # @return [Object, nil] Number of se_create_timeout.,Default value when not specified in API or module is interpreted by Avi Controller as 900.,Units(SEC).\n attribute :se_create_timeout\n\n # @return [Object, nil] Interval between attempting failovers to an se.,Default value when not specified in API or module is interpreted by Avi Controller as 300.,Units(SEC).\n attribute :se_failover_attempt_interval\n\n # @return [Object, nil] Number of se_offline_del.,Default value when not specified in API or module is interpreted by Avi Controller as 172000.,Units(SEC).\n attribute :se_offline_del\n\n # @return [Object, nil] Number of se_vnic_cooldown.,Default value when not specified in API or module is interpreted by Avi Controller as 120.,Units(SEC).\n attribute :se_vnic_cooldown\n\n # @return [Object, nil] Number of secure_channel_cleanup_timeout.,Default value when not specified in API or module is interpreted by Avi Controller as 60.,Units(MIN).\n attribute :secure_channel_cleanup_timeout\n\n # @return [Object, nil] Number of secure_channel_controller_token_timeout.,Default value when not specified in API or module is interpreted by Avi Controller as 60.,Units(MIN).\n attribute :secure_channel_controller_token_timeout\n\n # @return [Object, nil] Number of secure_channel_se_token_timeout.,Default value when not specified in API or module is interpreted by Avi Controller as 60.,Units(MIN).\n attribute :secure_channel_se_token_timeout\n\n # @return [Object, nil] Pool size used for all fabric commands during se upgrade.,Default value when not specified in API or module is interpreted by Avi Controller as 20.\n attribute :seupgrade_fabric_pool_size\n\n # @return [Object, nil] Time to wait before marking segroup upgrade as stuck.,Default value when not specified in API or module is interpreted by Avi Controller as 360.,Units(SEC).\n attribute :seupgrade_segroup_min_dead_timeout\n\n # @return [Object, nil] Number of days for ssl certificate expiry warning.,Units(DAYS).\n attribute :ssl_certificate_expiry_warning_days\n\n # @return [Object, nil] Number of unresponsive_se_reboot.,Default value when not specified in API or module is interpreted by Avi Controller as 300.,Units(SEC).\n attribute :unresponsive_se_reboot\n\n # @return [Object, nil] Time to account for dns ttl during upgrade.,This is in addition to vs_scalein_timeout_for_upgrade in se_group.,Field introduced in 17.1.1.,Default value when not specified in API or module is interpreted by Avi Controller as 5.,Units(SEC).\n attribute :upgrade_dns_ttl\n\n # @return [Object, nil] Number of upgrade_lease_time.,Default value when not specified in API or module is interpreted by Avi Controller as 360.,Units(SEC).\n attribute :upgrade_lease_time\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Unique object identifier of the object.\n attribute :uuid\n\n # @return [Object, nil] Number of vnic_op_fail_time.,Default value when not specified in API or module is interpreted by Avi Controller as 180.,Units(SEC).\n attribute :vnic_op_fail_time\n\n # @return [Object, nil] Time to wait for the scaled out se to become ready before marking the scaleout done, applies to apic configuration only.,Default value when not specified in API or module is interpreted by Avi Controller as 360.,Units(SEC).\n attribute :vs_apic_scaleout_timeout\n\n # @return [Object, nil] Number of vs_awaiting_se_timeout.,Default value when not specified in API or module is interpreted by Avi Controller as 60.,Units(SEC).\n attribute :vs_awaiting_se_timeout\n\n # @return [Object, nil] Allowed values are 1-1051200.,Special values are 0 - 'disabled'.,Default value when not specified in API or module is interpreted by Avi Controller as 60.,Units(MIN).\n attribute :vs_key_rotate_period\n\n # @return [Object, nil] Time to wait before marking attach ip operation on an se as failed.,Field introduced in 17.2.2.,Default value when not specified in API or module is interpreted by Avi Controller as 3600.,Units(SEC).\n attribute :vs_se_attach_ip_fail\n\n # @return [Object, nil] Number of vs_se_bootup_fail.,Default value when not specified in API or module is interpreted by Avi Controller as 480.,Units(SEC).\n attribute :vs_se_bootup_fail\n\n # @return [Object, nil] Number of vs_se_create_fail.,Default value when not specified in API or module is interpreted by Avi Controller as 1500.,Units(SEC).\n attribute :vs_se_create_fail\n\n # @return [Object, nil] Number of vs_se_ping_fail.,Default value when not specified in API or module is interpreted by Avi Controller as 60.,Units(SEC).\n attribute :vs_se_ping_fail\n\n # @return [Object, nil] Number of vs_se_vnic_fail.,Default value when not specified in API or module is interpreted by Avi Controller as 300.,Units(SEC).\n attribute :vs_se_vnic_fail\n\n # @return [Object, nil] Number of vs_se_vnic_ip_fail.,Default value when not specified in API or module is interpreted by Avi Controller as 120.,Units(SEC).\n attribute :vs_se_vnic_ip_fail\n\n # @return [Object, nil] Number of warmstart_se_reconnect_wait_time.,Default value when not specified in API or module is interpreted by Avi Controller as 300.,Units(SEC).\n attribute :warmstart_se_reconnect_wait_time\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.655810534954071, "alphanum_fraction": 0.6565507054328918, "avg_line_length": 54.14285659790039, "blob_id": "8d35568ffb8ba3697a3dff4ca1a3d0edbaac7e84", "content_id": "fdbc24ff67927aead3fa01ea83cf0765b8eaad42", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2702, "license_type": "permissive", "max_line_length": 271, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_cdot_lun.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, destroy, resize luns on NetApp cDOT.\n class Na_cdot_lun < Base\n # @return [:present, :absent] Whether the specified lun should exist or not.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String] The name of the lun to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The name of the FlexVol the lun should exist on.,Required when C(state=present).\n attribute :flexvol_name\n validates :flexvol_name, type: String\n\n # @return [Integer, nil] The size of the lun in C(size_unit).,Required when C(state=present).\n attribute :size\n validates :size, type: Integer\n\n # @return [:bytes, :b, :kb, :mb, :gb, :tb, :pb, :eb, :zb, :yb, nil] The unit used to interpret the size parameter.\n attribute :size_unit\n validates :size_unit, expression_inclusion: {:in=>[:bytes, :b, :kb, :mb, :gb, :tb, :pb, :eb, :zb, :yb], :message=>\"%{value} needs to be :bytes, :b, :kb, :mb, :gb, :tb, :pb, :eb, :zb, :yb\"}, allow_nil: true\n\n # @return [Boolean, nil] Forcibly reduce the size. This is required for reducing the size of the LUN to avoid accidentally reducing the LUN size.\n attribute :force_resize\n validates :force_resize, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] If \"true\", override checks that prevent a LUN from being destroyed if it is online and mapped.,If \"false\", destroying an online and mapped LUN will fail.\n attribute :force_remove\n validates :force_remove, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] If \"true\", override checks that prevent a LUN from being destroyed while it is fenced.,If \"false\", attempting to destroy a fenced LUN will fail.,The default if not specified is \"false\". This field is available in Data ONTAP 8.2 and later.\n attribute :force_remove_fenced\n validates :force_remove_fenced, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String] The name of the vserver to use.\n attribute :vserver\n validates :vserver, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7002743482589722, "alphanum_fraction": 0.7002743482589722, "avg_line_length": 40.657142639160156, "blob_id": "6e9563f7c15186602bda0bcf6f90f8cbf0ae0973", "content_id": "6270e6bf74b272319433a2c882d771ca738feb69", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1458, "license_type": "permissive", "max_line_length": 256, "num_lines": 35, "path": "/lib/ansible/ruby/modules/generated/network/fortios/fortios_webfilter.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is able to configure a FortiGate or FortiOS by allowing the user to configure webfilter feature. For now it is able to handle url and content filtering capabilities. The module uses FortiGate REST API internally to configure the device.\n class Fortios_webfilter < Base\n # @return [String] FortiOS or FortiGate ip adress.\n attribute :host\n validates :host, presence: true, type: String\n\n # @return [String] FortiOS or FortiGate username.\n attribute :username\n validates :username, presence: true, type: String\n\n # @return [String, nil] FortiOS or FortiGate password.\n attribute :password\n validates :password, type: String\n\n # @return [String, nil] Virtual domain, among those defined previously. A vdom is a virtual instance of the FortiGate that can be configured and used as a different unit.\n attribute :vdom\n validates :vdom, type: String\n\n # @return [Object, nil] Container for a group of url entries that the FortiGate must act upon\n attribute :webfilter_url\n\n # @return [Object, nil] Container for a group of content-filtering entries that the FortiGate must act upon\n attribute :webfilter_content\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6961678862571716, "alphanum_fraction": 0.6979926824569702, "avg_line_length": 51.19047546386719, "blob_id": "9655cfd4fbf8d374cc4a49bc840e136b01697a66", "content_id": "724bba74964fa39c93c54e4e0316fcacc01af867", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2192, "license_type": "permissive", "max_line_length": 211, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_api_gateway.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows for the management of API Gateway APIs\n # Normally you should give the api_id since there is no other stable guaranteed unique identifier for the API. If you do not give api_id then a new API will be create each time this is run.\n # Beware that there are very hard limits on the rate that you can call API Gateway's REST API. You may need to patch your boto. See https://github.com/boto/boto3/issues/876 and discuss with your AWS rep.\n # swagger_file and swagger_text are passed directly on to AWS transparently whilst swagger_dict is an ansible dict which is converted to JSON before the API definitions are uploaded.\n class Aws_api_gateway < Base\n # @return [String, nil] The ID of the API you want to manage.\n attribute :api_id\n validates :api_id, type: String\n\n # @return [:present, :absent, nil] NOT IMPLEMENTED Create or delete API - currently we always create.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] JSON or YAML file containing swagger definitions for API. Exactly one of swagger_file, swagger_text or swagger_dict must be present.\n attribute :swagger_file\n validates :swagger_file, type: String\n\n # @return [Object, nil] Swagger definitions for API in JSON or YAML as a string direct from playbook.\n attribute :swagger_text\n\n # @return [Object, nil] Swagger definitions API ansible dictionary which will be converted to JSON and uploaded.\n attribute :swagger_dict\n\n # @return [String, nil] The name of the stage the API should be deployed to.\n attribute :stage\n validates :stage, type: String\n\n # @return [String, nil] Description of the deployment - recorded and visible in the AWS console.\n attribute :deploy_desc\n validates :deploy_desc, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7087531089782715, "alphanum_fraction": 0.7099306583404541, "avg_line_length": 61.13821029663086, "blob_id": "33947ee4236788d4403d6424e95153073cc3e17a", "content_id": "25aff7c5bab9b1f8b70bc9eba601a6ade48439c2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 7643, "license_type": "permissive", "max_line_length": 436, "num_lines": 123, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_asg.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Can create or delete AWS Autoscaling Groups\n # Works with the ec2_lc module to manage Launch Configurations\n class Ec2_asg < Base\n # @return [:present, :absent, nil] register or deregister the instance\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] Unique name for group to be created or deleted\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Array<String>, String, nil] List of ELB names to use for the group. Use for classic load balancers.\n attribute :load_balancers\n validates :load_balancers, type: TypeGeneric.new(String)\n\n # @return [Object, nil] List of target group ARNs to use for the group. Use for application load balancers.\n attribute :target_group_arns\n\n # @return [Array<String>, String, nil] List of availability zone names in which to create the group. Defaults to all the availability zones in the region if vpc_zone_identifier is not set.\n attribute :availability_zones\n validates :availability_zones, type: TypeGeneric.new(String)\n\n # @return [String] Name of the Launch configuration to use for the group. See the ec2_lc module for managing these. If unspecified then the current group value will be used.\n attribute :launch_config_name\n validates :launch_config_name, presence: true, type: String\n\n # @return [Integer, nil] Minimum number of instances in group, if unspecified then the current group value will be used.\n attribute :min_size\n validates :min_size, type: Integer\n\n # @return [Integer, nil] Maximum number of instances in group, if unspecified then the current group value will be used.\n attribute :max_size\n validates :max_size, type: Integer\n\n # @return [Object, nil] Physical location of your cluster placement group created in Amazon EC2.\n attribute :placement_group\n\n # @return [Integer, nil] Desired number of instances in group, if unspecified then the current group value will be used.\n attribute :desired_capacity\n validates :desired_capacity, type: Integer\n\n # @return [String, nil] In a rolling fashion, replace all instances with an old launch configuration with one from the current launch configuration.\n attribute :replace_all_instances\n validates :replace_all_instances, type: String\n\n # @return [Integer, nil] Number of instances you'd like to replace at a time. Used with replace_all_instances.\n attribute :replace_batch_size\n validates :replace_batch_size, type: Integer\n\n # @return [Array<String>, String, nil] List of instance_ids belonging to the named ASG that you would like to terminate and be replaced with instances matching the current launch configuration.\n attribute :replace_instances\n validates :replace_instances, type: TypeGeneric.new(String)\n\n # @return [String, nil] Check to make sure instances that are being replaced with replace_instances do not already have the current launch_config.\n attribute :lc_check\n validates :lc_check, type: String\n\n # @return [Array<String>, String, nil] List of VPC subnets to use\n attribute :vpc_zone_identifier\n validates :vpc_zone_identifier, type: TypeGeneric.new(String)\n\n # @return [Array<Hash>, Hash, nil] A list of tags to add to the Auto Scale Group. Optional key is 'propagate_at_launch', which defaults to true.\n attribute :tags\n validates :tags, type: TypeGeneric.new(Hash)\n\n # @return [String, nil] Length of time in seconds after a new EC2 instance comes into service that Auto Scaling starts checking its health.\n attribute :health_check_period\n validates :health_check_period, type: String\n\n # @return [:EC2, :ELB, nil] The service you want the health status from, Amazon EC2 or Elastic Load Balancer.\n attribute :health_check_type\n validates :health_check_type, expression_inclusion: {:in=>[:EC2, :ELB], :message=>\"%{value} needs to be :EC2, :ELB\"}, allow_nil: true\n\n # @return [String, nil] The number of seconds after a scaling activity completes before another can begin.\n attribute :default_cooldown\n validates :default_cooldown, type: String\n\n # @return [Integer, nil] How long to wait for instances to become viable when replaced. If you experience the error \"Waited too long for ELB instances to be healthy\", try increasing this value.\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [String, nil] Wait for the ASG instances to be in a ready state before exiting. If instances are behind an ELB, it will wait until the ELB determines all instances have a lifecycle_state of \"InService\" and a health_status of \"Healthy\".\n attribute :wait_for_instances\n validates :wait_for_instances, type: String\n\n # @return [:OldestInstance, :NewestInstance, :OldestLaunchConfiguration, :ClosestToNextInstanceHour, :Default, nil] An ordered list of criteria used for selecting instances to be removed from the Auto Scaling group when reducing capacity.,For 'Default', when used to create a new autoscaling group, the \"Default\"i value is used. When used to change an existent autoscaling group, the current termination policies are maintained.\n attribute :termination_policies\n validates :termination_policies, expression_inclusion: {:in=>[:OldestInstance, :NewestInstance, :OldestLaunchConfiguration, :ClosestToNextInstanceHour, :Default], :message=>\"%{value} needs to be :OldestInstance, :NewestInstance, :OldestLaunchConfiguration, :ClosestToNextInstanceHour, :Default\"}, allow_nil: true\n\n # @return [Object, nil] A SNS topic ARN to send auto scaling notifications to.\n attribute :notification_topic\n\n # @return [String, nil] A list of auto scaling events to trigger notifications on.\n attribute :notification_types\n validates :notification_types, type: String\n\n # @return [:Launch, :Terminate, :HealthCheck, :ReplaceUnhealthy, :AZRebalance, :AlarmNotification, :ScheduledActions, :AddToLoadBalancer, nil] A list of scaling processes to suspend.\n attribute :suspend_processes\n validates :suspend_processes, expression_inclusion: {:in=>[:Launch, :Terminate, :HealthCheck, :ReplaceUnhealthy, :AZRebalance, :AlarmNotification, :ScheduledActions, :AddToLoadBalancer], :message=>\"%{value} needs to be :Launch, :Terminate, :HealthCheck, :ReplaceUnhealthy, :AZRebalance, :AlarmNotification, :ScheduledActions, :AddToLoadBalancer\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Enable ASG metrics collection\n attribute :metrics_collection\n validates :metrics_collection, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] When metrics_collection is enabled this will determine granularity of metrics collected by CloudWatch\n attribute :metrics_granularity\n validates :metrics_granularity, type: String\n\n # @return [String, nil] List of autoscaling metrics to collect when enabling metrics_collection\n attribute :metrics_list\n validates :metrics_list, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7130329608917236, "alphanum_fraction": 0.7130329608917236, "avg_line_length": 74.15908813476562, "blob_id": "96528ad3b51d0afcfdf6f65c882709683769e644", "content_id": "c90a36a5f4f6bc5a2c6de5899bb5aa8cac4242b8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3307, "license_type": "permissive", "max_line_length": 338, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/network/junos/junos_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module manages locally configured user accounts on remote network devices running the JUNOS operating system. It provides a set of arguments for creating, removing and updating locally defined accounts\n class Junos_user < Base\n # @return [Array<Hash>, Hash, nil] The C(aggregate) argument defines a list of users to be configured on the remote device. The list of users will be compared against the current users and only changes will be added or removed from the device configuration. This argument is mutually exclusive with the name argument.\n attribute :aggregate\n validates :aggregate, type: TypeGeneric.new(Hash)\n\n # @return [String, nil] The C(name) argument defines the username of the user to be created on the system. This argument must follow appropriate usernaming conventions for the target device running JUNOS. This argument is mutually exclusive with the C(aggregate) argument.\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] The C(full_name) argument provides the full name of the user account to be created on the remote device. This argument accepts any text string value.\n attribute :full_name\n\n # @return [:operator, :\"read-only\", :\"super-user\", :unauthorized, nil] The C(role) argument defines the role of the user account on the remote system. User accounts can have more than one role configured.\n attribute :role\n validates :role, expression_inclusion: {:in=>[:operator, :\"read-only\", :\"super-user\", :unauthorized], :message=>\"%{value} needs to be :operator, :\\\"read-only\\\", :\\\"super-user\\\", :unauthorized\"}, allow_nil: true\n\n # @return [String, nil] The C(sshkey) argument defines the public SSH key to be configured for the user account on the remote system. This argument must be a valid SSH key\n attribute :sshkey\n validates :sshkey, type: String\n\n # @return [:yes, :no, nil] The C(purge) argument instructs the module to consider the users definition absolute. It will remove any previously configured users on the device with the exception of the current defined set of aggregate.\n attribute :purge\n validates :purge, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, nil] The C(state) argument configures the state of the user definitions as it relates to the device operational configuration. When set to I(present), the user should be configured in the device active configuration and when set to I(absent) the user should not be in the device active configuration\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Specifies whether or not the configuration is active or deactivated\n attribute :active\n validates :active, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6841972470283508, "alphanum_fraction": 0.6849557757377625, "avg_line_length": 47.8271598815918, "blob_id": "830b786c2926dbef5a4944acd4088291f6103c1b", "content_id": "aa51fca97eb4e44223dabd3328b5e64e2ce4a3ef", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3955, "license_type": "permissive", "max_line_length": 268, "num_lines": 81, "path": "/lib/ansible/ruby/modules/generated/cloud/opennebula/one_service.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage OpenNebula services\n class One_service < Base\n # @return [Object, nil] URL of the OpenNebula OneFlow API server.,It is recommended to use HTTPS so that the username/password are not transferred over the network unencrypted.,If not set then the value of the ONEFLOW_URL environment variable is used.\n attribute :api_url\n\n # @return [Object, nil] Name of the user to login into the OpenNebula OneFlow API server. If not set then the value of the C(ONEFLOW_USERNAME) environment variable is used.\n attribute :api_username\n\n # @return [Object, nil] Password of the user to login into OpenNebula OneFlow API server. If not set then the value of the C(ONEFLOW_PASSWORD) environment variable is used.\n attribute :api_password\n\n # @return [String, nil] Name of service template to use to create a new instace of a service\n attribute :template_name\n validates :template_name, type: String\n\n # @return [Integer, nil] ID of a service template to use to create a new instance of a service\n attribute :template_id\n validates :template_id, type: Integer\n\n # @return [Integer, nil] ID of a service instance that you would like to manage\n attribute :service_id\n validates :service_id, type: Integer\n\n # @return [String, nil] Name of a service instance that you would like to manage\n attribute :service_name\n validates :service_name, type: String\n\n # @return [Symbol, nil] Setting C(unique=yes) will make sure that there is only one service instance running with a name set with C(service_name) when,instantiating a service from a template specified with C(template_id)/C(template_name). Check examples below.\n attribute :unique\n validates :unique, type: Symbol\n\n # @return [:present, :absent, nil] C(present) - instantiate a service from a template specified with C(template_id)/C(template_name).,C(absent) - terminate an instance of a service specified with C(service_id)/C(service_name).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Set permission mode of a service instance in octet format, e.g. C(600) to give owner C(use) and C(manage) and nothing to group and others.\n attribute :mode\n validates :mode, type: String\n\n # @return [Integer, nil] ID of the user which will be set as the owner of the service\n attribute :owner_id\n validates :owner_id, type: Integer\n\n # @return [Integer, nil] ID of the group which will be set as the group of the service\n attribute :group_id\n validates :group_id, type: Integer\n\n # @return [Symbol, nil] Wait for the instance to reach RUNNING state after DEPLOYING or COOLDOWN state after SCALING\n attribute :wait\n validates :wait, type: Symbol\n\n # @return [Integer, nil] How long before wait gives up, in seconds\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [Object, nil] Dictionary of key/value custom attributes which will be used when instantiating a new service.\n attribute :custom_attrs\n\n # @return [String, nil] Name of the role whose cardinality should be changed\n attribute :role\n validates :role, type: String\n\n # @return [Integer, nil] Number of VMs for the specified role\n attribute :cardinality\n validates :cardinality, type: Integer\n\n # @return [Symbol, nil] Force the new cardinality even if it is outside the limits\n attribute :force\n validates :force, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7341279983520508, "alphanum_fraction": 0.7359419465065002, "avg_line_length": 79.39583587646484, "blob_id": "9d2992617e3370b0d1f190dc9dbe810ed56b56b8", "content_id": "c33e9e2297745e5240979fb080c855dcd076309d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3859, "license_type": "permissive", "max_line_length": 538, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/lambda_policy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows the management of AWS Lambda policy statements. It is idempotent and supports \"Check\" mode. Use module M(lambda) to manage the lambda function itself, M(lambda_alias) to manage function aliases, M(lambda_event) to manage event source mappings such as Kinesis streams, M(execute_lambda) to execute a lambda function and M(lambda_facts) to gather facts relating to one or more lambda functions.\n class Lambda_policy < Base\n # @return [Object] Name of the Lambda function whose resource policy you are updating by adding a new permission.,You can specify a function name (for example, Thumbnail ) or you can specify Amazon Resource Name (ARN) of the,function (for example, arn:aws:lambda:us-west-2:account-id:function:ThumbNail ). AWS Lambda also allows you to,specify partial ARN (for example, account-id:Thumbnail ). Note that the length constraint applies only to the,ARN. If you specify only the function name, it is limited to 64 character in length.\n attribute :function_name\n validates :function_name, presence: true\n\n # @return [:present, :absent] Describes the desired state.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [Object, nil] Name of the function alias. Mutually exclusive with C(version).\n attribute :alias\n\n # @return [Object, nil] Version of the Lambda function. Mutually exclusive with C(alias).\n attribute :version\n\n # @return [Object] A unique statement identifier.\n attribute :statement_id\n validates :statement_id, presence: true\n\n # @return [Object] The AWS Lambda action you want to allow in this statement. Each Lambda action is a string starting with lambda: followed by the API name (see Operations ). For example, lambda:CreateFunction . You can use wildcard (lambda:* ) to grant permission for all AWS Lambda actions.\n attribute :action\n validates :action, presence: true\n\n # @return [Object] The principal who is getting this permission. It can be Amazon S3 service Principal (s3.amazonaws.com ) if you want Amazon S3 to invoke the function, an AWS account ID if you are granting cross-account permission, or any valid AWS service principal such as sns.amazonaws.com . For example, you might want to allow a custom application in another AWS account to push events to AWS Lambda by invoking your function.\n attribute :principal\n validates :principal, presence: true\n\n # @return [Object, nil] This is optional; however, when granting Amazon S3 permission to invoke your function, you should specify this field with the bucket Amazon Resource Name (ARN) as its value. This ensures that only events generated from the specified bucket can invoke the function.\n attribute :source_arn\n\n # @return [Object, nil] The AWS account ID (without a hyphen) of the source owner. For example, if the SourceArn identifies a bucket, then this is the bucket owner's account ID. You can use this additional condition to ensure the bucket you specify is owned by a specific account (it is possible the bucket owner deleted the bucket and some other AWS account created the bucket). You can also use this condition to specify all sources (that is, you don't specify the SourceArn ) owned by a specific account.\n attribute :source_account\n\n # @return [Object, nil] Token string representing source ARN or account. Mutually exclusive with C(source_arn) or C(source_account).\n attribute :event_source_token\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6887725591659546, "alphanum_fraction": 0.6899359822273254, "avg_line_length": 48.11428451538086, "blob_id": "00e03ce58315f709662cb4f2a083e49c7ae091e3", "content_id": "106fe3dfccac88199e9688a414f17998e568402a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1719, "license_type": "permissive", "max_line_length": 221, "num_lines": 35, "path": "/lib/ansible/ruby/modules/generated/files/iso_extract.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module has two possible ways of operation.\n # If 7zip is installed on the system, this module extracts files from an ISO into a temporary directory and copies files to a given destination, if needed.\n # If the user has mount-capabilities (CAP_SYS_ADMIN on Linux) this module mounts the ISO image to a temporary location, and copies files to a given destination, if needed.\n class Iso_extract < Base\n # @return [String] The ISO image to extract files from.\n attribute :image\n validates :image, presence: true, type: String\n\n # @return [String] The destination directory to extract files to.\n attribute :dest\n validates :dest, presence: true, type: String\n\n # @return [Array<String>, String] A list of files to extract from the image.,Extracting directories does not work.\n attribute :files\n validates :files, presence: true, type: TypeGeneric.new(String)\n\n # @return [:yes, :no, nil] If C(yes), which will replace the remote file when contents are different than the source.,If C(no), the file will only be extracted and copied if the destination does not already exist.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] The path to the C(7z) executable to use for extracting files from the ISO.\n attribute :executable\n validates :executable, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6506768465042114, "alphanum_fraction": 0.6506768465042114, "avg_line_length": 43.71052551269531, "blob_id": "8953c733db2781c3b8c39f2e84c0a370eb735ca0", "content_id": "73a19bb41902d1cbbe87bbae8a6ba12f7e230c22", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3398, "license_type": "permissive", "max_line_length": 170, "num_lines": 76, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_portforward.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and remove port forwarding rules.\n class Cs_portforward < Base\n # @return [String] Public IP address the rule is assigned to.\n attribute :ip_address\n validates :ip_address, presence: true, type: String\n\n # @return [String, nil] Name of virtual machine which we make the port forwarding rule for.,Required if C(state=present).\n attribute :vm\n validates :vm, type: String\n\n # @return [:present, :absent, nil] State of the port forwarding rule.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:tcp, :udp, nil] Protocol of the port forwarding rule.\n attribute :protocol\n validates :protocol, expression_inclusion: {:in=>[:tcp, :udp], :message=>\"%{value} needs to be :tcp, :udp\"}, allow_nil: true\n\n # @return [Integer, String] Start public port for this rule.\n attribute :public_port\n validates :public_port, presence: true, type: MultipleTypes.new(Integer, String)\n\n # @return [Object, nil] End public port for this rule.,If not specified equal C(public_port).\n attribute :public_end_port\n\n # @return [Integer] Start private port for this rule.\n attribute :private_port\n validates :private_port, presence: true, type: Integer\n\n # @return [Object, nil] End private port for this rule.,If not specified equal C(private_port).\n attribute :private_end_port\n\n # @return [Boolean, nil] Whether the firewall rule for public port should be created, while creating the new rule.,Use M(cs_firewall) for managing firewall rules.\n attribute :open_firewall\n validates :open_firewall, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] VM guest NIC secondary IP address for the port forwarding rule.\n attribute :vm_guest_ip\n validates :vm_guest_ip, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] Name of the network.\n attribute :network\n\n # @return [Object, nil] Name of the VPC.\n attribute :vpc\n\n # @return [Object, nil] Domain the C(vm) is related to.\n attribute :domain\n\n # @return [Object, nil] Account the C(vm) is related to.\n attribute :account\n\n # @return [Object, nil] Name of the project the C(vm) is located in.\n attribute :project\n\n # @return [Object, nil] Name of the zone in which the virtual machine is in.,If not set, default zone is used.\n attribute :zone\n\n # @return [Boolean, nil] Poll async jobs until job has finished.\n attribute :poll_async\n validates :poll_async, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] List of tags. Tags are a list of dictionaries having keys C(key) and C(value).,To delete all tags, set a empty list e.g. C(tags: []).\n attribute :tags\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6772108674049377, "alphanum_fraction": 0.6792517304420471, "avg_line_length": 57.79999923706055, "blob_id": "eb9e2519caf9e7824784d9f459e8d9a65f9eba6b", "content_id": "4b2394230a8319cccf49f6086b06ede82e7995ef", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2940, "license_type": "permissive", "max_line_length": 457, "num_lines": 50, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/sf_volume_manager.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, destroy, or update volumes on SolidFire\n class Sf_volume_manager < Base\n # @return [:present, :absent] Whether the specified volume should exist or not.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String] The name of the volume to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Integer] Account ID for the owner of this volume.\n attribute :account_id\n validates :account_id, presence: true, type: Integer\n\n # @return [Object, nil] Should the volume provide 512-byte sector emulation?,Required when C(state=present)\n attribute :\"512emulation\"\n\n # @return [Hash, nil] Initial quality of service settings for this volume. Configure as dict in playbooks.\n attribute :qos\n validates :qos, type: Hash\n\n # @return [Object, nil] A YAML dictionary of attributes that you would like to apply on this volume.\n attribute :attributes\n\n # @return [Object, nil] The ID of the volume to manage or update.,In order to create multiple volumes with the same name, but different volume_ids, please declare the I(volume_id) parameter with an arbitrary value. However, the specified volume_id will not be assigned to the newly created volume (since it's an auto-generated property).\n attribute :volume_id\n\n # @return [Integer, nil] The size of the volume in (size_unit).,Required when C(state = present).\n attribute :size\n validates :size, type: Integer\n\n # @return [:bytes, :b, :kb, :mb, :gb, :tb, :pb, :eb, :zb, :yb, nil] The unit used to interpret the size parameter.\n attribute :size_unit\n validates :size_unit, expression_inclusion: {:in=>[:bytes, :b, :kb, :mb, :gb, :tb, :pb, :eb, :zb, :yb], :message=>\"%{value} needs to be :bytes, :b, :kb, :mb, :gb, :tb, :pb, :eb, :zb, :yb\"}, allow_nil: true\n\n # @return [:readOnly, :readWrite, :locked, :replicationTarget, nil] Access allowed for the volume.,readOnly: Only read operations are allowed.,readWrite: Reads and writes are allowed.,locked: No reads or writes are allowed.,replicationTarget: Identify a volume as the target volume for a paired set of volumes. If the volume is not paired, the access status is locked.,If unspecified, the access settings of the clone will be the same as the source.\n attribute :access\n validates :access, expression_inclusion: {:in=>[:readOnly, :readWrite, :locked, :replicationTarget], :message=>\"%{value} needs to be :readOnly, :readWrite, :locked, :replicationTarget\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6887221932411194, "alphanum_fraction": 0.6989017128944397, "avg_line_length": 62.27118682861328, "blob_id": "46eb0df1b692b361b54dccf59ae9db749a1ba829", "content_id": "b8463d8eccf41d2e28e8c1757d178fc0677d3232", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3733, "license_type": "permissive", "max_line_length": 313, "num_lines": 59, "path": "/lib/ansible/ruby/modules/generated/network/iosxr/iosxr_interface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of Interfaces on Cisco IOS XR network devices.\n class Iosxr_interface < Base\n # @return [String] Name of the interface to configure in C(type + path) format. e.g. C(GigabitEthernet0/0/0/0)\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Description of Interface being configured.\n attribute :description\n validates :description, type: String\n\n # @return [Boolean, nil] Removes the shutdown configuration, which removes the forced administrative down on the interface, enabling it to move to an up or down state.\n attribute :enabled\n validates :enabled, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:active, :preconfigure, nil] Whether the interface is C(active) or C(preconfigured). Preconfiguration allows you to configure modular services cards before they are inserted into the router. When the cards are inserted, they are instantly configured. Active cards are the ones already inserted.\n attribute :active\n validates :active, expression_inclusion: {:in=>[:active, :preconfigure], :message=>\"%{value} needs to be :active, :preconfigure\"}, allow_nil: true\n\n # @return [10, 100, 1000, nil] Configure the speed for an interface. Default is auto-negotiation when not configured.\n attribute :speed\n validates :speed, expression_inclusion: {:in=>[10, 100, 1000], :message=>\"%{value} needs to be 10, 100, 1000\"}, allow_nil: true\n\n # @return [Integer, nil] Sets the MTU value for the interface. Range is between 64 and 65535'\n attribute :mtu\n validates :mtu, type: Integer\n\n # @return [:full, :half, nil] Configures the interface duplex mode. Default is auto-negotiation when not configured.\n attribute :duplex\n validates :duplex, expression_inclusion: {:in=>[:full, :half], :message=>\"%{value} needs to be :full, :half\"}, allow_nil: true\n\n # @return [Object, nil] Transmit rate in bits per second (bps).,This is state check parameter only.,Supports conditionals, see L(Conditionals in Networking Modules,../network/user_guide/network_working_with_command_output.html)\n attribute :tx_rate\n\n # @return [Object, nil] Receiver rate in bits per second (bps).,This is state check parameter only.,Supports conditionals, see L(Conditionals in Networking Modules,../network/user_guide/network_working_with_command_output.html)\n attribute :rx_rate\n\n # @return [Array<Hash>, Hash, nil] List of Interface definitions. Include multiple interface configurations together, one each on a separate line\n attribute :aggregate\n validates :aggregate, type: TypeGeneric.new(Hash)\n\n # @return [Integer, nil] Time in seconds to wait before checking for the operational state on remote device. This wait is applicable for operational state argument which are I(state) with values C(up)/C(down), I(tx_rate) and I(rx_rate).\n attribute :delay\n validates :delay, type: Integer\n\n # @return [:present, :absent, :up, :down, nil] State of the Interface configuration, C(up) means present and operationally up and C(down) means present and operationally C(down)\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :up, :down], :message=>\"%{value} needs to be :present, :absent, :up, :down\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6980137825012207, "alphanum_fraction": 0.7020673155784607, "avg_line_length": 65.67567443847656, "blob_id": "9f4a90389a94a0c95ca912f5e0bbcacb9edaff1d", "content_id": "344c93fd3ca59e9c38b3447bfa7cbf0ce7a411eb", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2467, "license_type": "permissive", "max_line_length": 333, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/apache2_mod_proxy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Set and/or get members' attributes of an Apache httpd 2.4 mod_proxy balancer pool, using HTTP POST and GET requests. The httpd mod_proxy balancer-member status page has to be enabled and accessible, as this module relies on parsing this page. This module supports ansible check_mode, and requires BeautifulSoup python module.\n class Apache2_mod_proxy < Base\n # @return [String, nil] Suffix of the balancer pool url required to access the balancer pool status page (e.g. balancer_vhost[:port]/balancer_url_suffix).\n attribute :balancer_url_suffix\n validates :balancer_url_suffix, type: String\n\n # @return [String] (ipv4|ipv6|fqdn):port of the Apache httpd 2.4 mod_proxy balancer pool.\n attribute :balancer_vhost\n validates :balancer_vhost, presence: true, type: String\n\n # @return [String, nil] (ipv4|ipv6|fqdn) of the balancer member to get or to set attributes to. Port number is autodetected and should not be specified here. If undefined, apache2_mod_proxy module will return a members list of dictionaries of all the current balancer pool members' attributes.\n attribute :member_host\n validates :member_host, type: String\n\n # @return [:present, :absent, :enabled, :disabled, :drained, :hot_standby, :ignore_errors, nil] Desired state of the member host. (absent|disabled),drained,hot_standby,ignore_errors can be simultaneously invoked by separating them with a comma (e.g. state=drained,ignore_errors).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :enabled, :disabled, :drained, :hot_standby, :ignore_errors], :message=>\"%{value} needs to be :present, :absent, :enabled, :disabled, :drained, :hot_standby, :ignore_errors\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Use https to access balancer management page.\n attribute :tls\n validates :tls, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Validate ssl/tls certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.694065511226654, "alphanum_fraction": 0.6964529156684875, "avg_line_length": 51.35714340209961, "blob_id": "a1dc75907efb8d6e0a87290f93538a667cb3b82a", "content_id": "efbcf6ae19f4f02b23f1cff78dbed5cb8e7532ea", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2932, "license_type": "permissive", "max_line_length": 387, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_static_route.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manipulate static routes on a BIG-IP.\n class Bigip_static_route < Base\n # @return [String] Name of the static route.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Descriptive text that identifies the route.\n attribute :description\n\n # @return [String, nil] Specifies an IP address for the static entry in the routing table. When creating a new static route, this value is required.,This value cannot be changed once it is set.\n attribute :destination\n validates :destination, type: String\n\n # @return [String, nil] The netmask for the static route. When creating a new static route, this value is required.,This value can be in either IP or CIDR format.,This value cannot be changed once it is set.\n attribute :netmask\n validates :netmask, type: String\n\n # @return [String, nil] Specifies the router for the system to use when forwarding packets to the destination host or network. Also known as the next-hop router address. This can be either an IPv4 or IPv6 address. When it is an IPv6 address that starts with C(FE80:), the address will be treated as a link-local address. This requires that the C(vlan) parameter also be supplied.\n attribute :gateway_address\n validates :gateway_address, type: String\n\n # @return [Object, nil] Specifies the VLAN or Tunnel through which the system forwards packets to the destination. When C(gateway_address) is a link-local IPv6 address, this value is required\n attribute :vlan\n\n # @return [Object, nil] Specifies the pool through which the system forwards packets to the destination.\n attribute :pool\n\n # @return [Symbol, nil] Specifies that the system drops packets sent to the destination.\n attribute :reject\n validates :reject, type: Symbol\n\n # @return [Object, nil] Specifies a specific maximum transmission unit (MTU).\n attribute :mtu\n\n # @return [Object, nil] The route domain id of the system. When creating a new static route, if this value is not specified, a default value of C(0) will be used.,This value cannot be changed once it is set.\n attribute :route_domain\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [:present, :absent, nil] When C(present), ensures that the static route exists.,When C(absent), ensures that the static does not exist.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6978609561920166, "alphanum_fraction": 0.6978609561920166, "avg_line_length": 50.58620834350586, "blob_id": "72b11b86a8f16ac22ba76aeb3f2df0d6b41ee40c", "content_id": "af8c0907fd1756da019ae8683e4d78c31a69d950", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1496, "license_type": "permissive", "max_line_length": 219, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/net_tools/ldap/ldap_entry.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove LDAP entries. This module only asserts the existence or non-existence of an LDAP entry, not its attributes. To assert the attribute values of an entry, see M(ldap_attr).\n class Ldap_entry < Base\n # @return [Hash, nil] If I(state=present), attributes necessary to create an entry. Existing entries are never modified. To assert specific attribute values on an existing entry, use M(ldap_attr) module instead.\n attribute :attributes\n validates :attributes, type: Hash\n\n # @return [Array<String>, String, nil] If I(state=present), value or list of values to use when creating the entry. It can either be a string or an actual list of strings.\n attribute :objectClass\n validates :objectClass, type: TypeGeneric.new(String)\n\n # @return [String, nil] List of options which allows to overwrite any of the task or the I(attributes) options. To remove an option, set the value of the option to C(null).\n attribute :params\n validates :params, type: String\n\n # @return [:present, :absent, nil] The target state of the entry.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6625882387161255, "alphanum_fraction": 0.6630588173866272, "avg_line_length": 43.27083206176758, "blob_id": "35147822008715f749103016d9a68fbb5caf1045", "content_id": "531a01b8ca37e2d5f913b159b2aa8acb9cef7969", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4250, "license_type": "permissive", "max_line_length": 501, "num_lines": 96, "path": "/lib/ansible/ruby/modules/generated/network/fortios/fortios_ipv4_policy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides management of firewall IPv4 policies on FortiOS devices.\n class Fortios_ipv4_policy < Base\n # @return [Integer] Policy ID. Warning: policy ID number is different than Policy sequence number. The policy ID is the number assigned at policy creation. The sequence number represents the order in which the Fortigate will evaluate the rule for policy enforcement, and also the order in which rules are listed in the GUI and CLI. These two numbers do not necessarily correlate: this module is based off policy ID. TIP: policy ID can be viewed in the GUI by adding 'ID' to the display columns\n attribute :id\n validates :id, presence: true, type: Integer\n\n # @return [:present, :absent, nil] Specifies if policy I(id) need to be added or deleted.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Specifies source interface name(s).\n attribute :src_intf\n validates :src_intf, type: String\n\n # @return [String, nil] Specifies destination interface name(s).\n attribute :dst_intf\n validates :dst_intf, type: String\n\n # @return [Array<String>, String, nil] Specifies source address (or group) object name(s). Required when I(state=present).\n attribute :src_addr\n validates :src_addr, type: TypeGeneric.new(String)\n\n # @return [Symbol, nil] Negate source address param.\n attribute :src_addr_negate\n validates :src_addr_negate, type: Symbol\n\n # @return [String, nil] Specifies destination address (or group) object name(s). Required when I(state=present).\n attribute :dst_addr\n validates :dst_addr, type: String\n\n # @return [Symbol, nil] Negate destination address param.\n attribute :dst_addr_negate\n validates :dst_addr_negate, type: Symbol\n\n # @return [:accept, :deny, nil] Specifies accept or deny action policy. Required when I(state=present).\n attribute :policy_action\n validates :policy_action, expression_inclusion: {:in=>[:accept, :deny], :message=>\"%{value} needs to be :accept, :deny\"}, allow_nil: true\n\n # @return [String, nil] Specifies policy service(s), could be a list (ex: ['MAIL','DNS']). Required when I(state=present).\n attribute :service\n validates :service, type: String\n\n # @return [Symbol, nil] Negate policy service(s) defined in service value.\n attribute :service_negate\n validates :service_negate, type: Symbol\n\n # @return [String, nil] defines policy schedule.\n attribute :schedule\n validates :schedule, type: String\n\n # @return [Symbol, nil] Enable or disable Nat.\n attribute :nat\n validates :nat, type: Symbol\n\n # @return [Symbol, nil] Use fixed port for nat.\n attribute :fixedport\n validates :fixedport, type: Symbol\n\n # @return [Object, nil] Specifies NAT pool name.\n attribute :poolname\n\n # @return [Object, nil] Specifies Antivirus profile name.\n attribute :av_profile\n\n # @return [Object, nil] Specifies Webfilter profile name.\n attribute :webfilter_profile\n\n # @return [Object, nil] Specifies IPS Sensor profile name.\n attribute :ips_sensor\n\n # @return [Object, nil] Specifies Application Control name.\n attribute :application_list\n\n # @return [:disable, :utm, :all, nil] Logs sessions that matched policy.\n attribute :logtraffic\n validates :logtraffic, expression_inclusion: {:in=>[:disable, :utm, :all], :message=>\"%{value} needs to be :disable, :utm, :all\"}, allow_nil: true\n\n # @return [Symbol, nil] Logs beginning of session as well.\n attribute :logtraffic_start\n validates :logtraffic_start, type: Symbol\n\n # @return [String, nil] free text to describe policy.\n attribute :comment\n validates :comment, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7132701277732849, "alphanum_fraction": 0.7168246507644653, "avg_line_length": 41.20000076293945, "blob_id": "047963befe52fb6175c0c479d8d5f0649e188d7a", "content_id": "7c50d29a13045e95b125d1a43c0d19db2db33786", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 844, "license_type": "permissive", "max_line_length": 273, "num_lines": 20, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_instance_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gather facts about ec2 instances in AWS\n class Ec2_instance_facts < Base\n # @return [Array<String>, String, nil] If you specify one or more instance IDs, only instances that have the specified IDs are returned.\n attribute :instance_ids\n validates :instance_ids, type: TypeGeneric.new(String)\n\n # @return [Object, nil] A dict of filters to apply. Each dict item consists of a filter key and a filter value. See U(http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances.html) for possible filters. Filter names and values are case sensitive.\n attribute :filters\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6586638689041138, "alphanum_fraction": 0.6586638689041138, "avg_line_length": 33.21428680419922, "blob_id": "21f126cd2f65fb07f06415b2af0e9204402a5531", "content_id": "960fb442d1b8fdc3860044dcad745ffeb7162cf3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 958, "license_type": "permissive", "max_line_length": 136, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/network/panos/panos_admin.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # PanOS module that allows changes to the user account passwords by doing API calls to the Firewall using pan-api as the protocol.\n class Panos_admin < Base\n # @return [String, nil] username for admin user\n attribute :admin_username\n validates :admin_username, type: String\n\n # @return [String] password for admin user\n attribute :admin_password\n validates :admin_password, presence: true, type: String\n\n # @return [Object, nil] role for admin user\n attribute :role\n\n # @return [:yes, :no, nil] commit if changed\n attribute :commit\n validates :commit, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.659903883934021, "alphanum_fraction": 0.6641750931739807, "avg_line_length": 40.622222900390625, "blob_id": "cc9494d76213f84abe417ad7243e6205eef594f2", "content_id": "cc3cc9b41383c0c5b698cbe374cc26bd840c9f82", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1873, "license_type": "permissive", "max_line_length": 181, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_eks_cluster.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage Elastic Kubernetes Service Clusters\n class Aws_eks_cluster < Base\n # @return [String] Name of EKS cluster\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Kubernetes version - defaults to latest\n attribute :version\n validates :version, type: String\n\n # @return [String, nil] ARN of IAM role used by the EKS cluster\n attribute :role_arn\n validates :role_arn, type: String\n\n # @return [Array<String>, String, nil] list of subnet IDs for the Kubernetes cluster\n attribute :subnets\n validates :subnets, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] list of security group names or IDs\n attribute :security_groups\n validates :security_groups, type: TypeGeneric.new(String)\n\n # @return [:absent, :present, nil] desired state of the EKS cluster\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Specifies whether the module waits until the cluster becomes active after creation. It takes \"usually less than 10 minutes\" per AWS documentation.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] The duration in seconds to wait for the cluster to become active. Defaults to 1200 seconds (20 minutes).\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5205005407333374, "alphanum_fraction": 0.5212992429733276, "avg_line_length": 29.04800033569336, "blob_id": "63f54a34a52a34ea2a8f7dfdb3dfdda49a9a2ebc", "content_id": "aa48daad9cf5452b8b26ad053ff1d53085382047", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3756, "license_type": "permissive", "max_line_length": 76, "num_lines": 125, "path": "/lib/ansible/ruby/models/base.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'active_model'\nrequire 'ansible/ruby/models/type_generic'\nrequire 'ansible/ruby/models/multiple_types'\nrequire 'ansible/ruby/models/type_validator'\nrequire 'ansible/ruby/models/expression_inclusion_validator'\nrequire 'ansible/ruby/models/jinja_expression'\n\nmodule Ansible\n module Ruby\n module Models\n class Base\n include ActiveModel::Model\n include ActiveModel::Validations\n\n def initialize(args = {})\n @set_vars = {}\n super\n end\n\n class << self\n def remove_existing_validations(attr)\n options = attr_option(attr) || []\n options.clear\n _validators.delete attr\n callbacks = send(:get_callbacks, :validate)\n for_this_att = callbacks.select do |callback|\n filter = callback.filter\n filter.respond_to?(:attributes) && filter.attributes == [attr]\n end\n for_this_att.each { |callback| callbacks.delete callback }\n end\n\n def attr_options\n @attr_options ||= begin\n # need parent attribute info\n hash = Base > self ? superclass.attr_options : {}\n hash.clone\n end\n end\n\n def attribute(name, options = {})\n attr_reader name\n # Want to keep track of what we set (avoid default issues)\n ivar = \"@#{name}\".to_sym\n define_method(\"#{name}=\".to_sym) do |value|\n @set_vars[name] = true\n instance_variable_set ivar, value\n end\n for_name = attr_options[name] ||= {}\n for_name.merge! options\n end\n\n def attr_option(name)\n attr_options[name]\n end\n\n def fix_inclusion(attributes)\n inclusion_in = attributes[:inclusion][:in]\n inclusion_in << Ansible::Ruby::Models::JinjaExpression\n end\n\n def validates(*attributes)\n hash = attributes.find { |a| a.is_a?(Hash) }\n fix_inclusion(hash) if hash&.dig(:inclusion, :in)\n super\n # avoid having to dupe this in the :attribute call\n hash = attributes.length > 1 && attributes[1]\n type_validator = hash && hash[:type]\n return unless type_validator&.is_a?(TypeGeneric)\n\n name = attributes[0]\n for_name = attr_options[name] ||= {}\n for_name[:generic] = type_validator.klasses\n end\n end\n\n def to_h\n validate!\n Hash[\n @set_vars.map do |key, _|\n value = send key\n options = self.class.attr_option(key)\n value = hashify value\n generic_types = options[:generic]\n value = convert_generic generic_types, value if generic_types\n key = options[:original_name] || key\n [key, value]\n end.compact]\n end\n\n private\n\n def hashify(value)\n case value\n when Array\n value.map { |val| hashify(val) }\n when Base\n value.to_h\n when Ansible::Ruby::Models::JinjaExpression\n value.to_s\n when Hash\n Hash[\n value.map do |key, inner_value|\n [key, hashify(inner_value)]\n end\n ]\n else\n !value.nil? && value.respond_to?(:to_h) ? value.to_h : value\n end\n end\n\n def convert_generic(generic_types, value)\n # hash friendly of [*value]\n if generic_types.any? { |type| value.is_a? type }\n [value]\n else\n value\n end\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6829477548599243, "alphanum_fraction": 0.6829477548599243, "avg_line_length": 39.24137878417969, "blob_id": "0f128d86cfb21069645ddd5920a008b4cbd6ba82", "content_id": "53683fea153d69a804f0804d3fb34db69785bd62", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1167, "license_type": "permissive", "max_line_length": 143, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_elementsw_cluster_pair.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, delete cluster pair\n class Na_elementsw_cluster_pair < Base\n # @return [:present, :absent, nil] Whether the specified cluster pair should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] Destination IP address of the cluster to be paired.\n attribute :dest_mvip\n validates :dest_mvip, presence: true, type: String\n\n # @return [String, nil] Destination username for the cluster to be paired.,Optional if this is same as source cluster username.\n attribute :dest_username\n validates :dest_username, type: String\n\n # @return [String, nil] Destination password for the cluster to be paired.,Optional if this is same as source cluster password.\n attribute :dest_password\n validates :dest_password, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6643747091293335, "alphanum_fraction": 0.6643747091293335, "avg_line_length": 48.51063919067383, "blob_id": "3627f070e9eed58b839da1c31bbc1efaadcf797f", "content_id": "5568d87c2cdb5fa2de1e055fc4543c498f38c4ea", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2327, "license_type": "permissive", "max_line_length": 204, "num_lines": 47, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_pool.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or Remove a pool from the OpenStack load-balancer service.\n class Os_pool < Base\n # @return [String] Name that has to be given to the pool\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Should the resource be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] The name or id of the load balancer that this pool belongs to. Either loadbalancer or listener must be specified for pool creation.\n attribute :loadbalancer\n validates :loadbalancer, type: String\n\n # @return [Object, nil] The name or id of the listener that this pool belongs to. Either loadbalancer or listener must be specified for pool creation.\n attribute :listener\n\n # @return [:HTTP, :HTTPS, :PROXY, :TCP, :UDP, nil] The protocol for the pool.\n attribute :protocol\n validates :protocol, expression_inclusion: {:in=>[:HTTP, :HTTPS, :PROXY, :TCP, :UDP], :message=>\"%{value} needs to be :HTTP, :HTTPS, :PROXY, :TCP, :UDP\"}, allow_nil: true\n\n # @return [:LEAST_CONNECTIONS, :ROUND_ROBIN, :SOURCE_IP, nil] The load balancing algorithm for the pool.\n attribute :lb_algorithm\n validates :lb_algorithm, expression_inclusion: {:in=>[:LEAST_CONNECTIONS, :ROUND_ROBIN, :SOURCE_IP], :message=>\"%{value} needs to be :LEAST_CONNECTIONS, :ROUND_ROBIN, :SOURCE_IP\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If the module should wait for the pool to be ACTIVE.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] The amount of time the module should wait for the pool to get into ACTIVE state.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.674578845500946, "alphanum_fraction": 0.674578845500946, "avg_line_length": 36.31428527832031, "blob_id": "63b5fdf3c9333043933fc10447d5e668f29344f1", "content_id": "ce95e9f042101c8bf3684eeb275d829b7b6f6a11", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1306, "license_type": "permissive", "max_line_length": 143, "num_lines": 35, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_direct_connect_gateway.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates AWS Direct Connect Gateway\n # Deletes AWS Direct Connect Gateway\n # Attaches Virtual Gateways to Direct Connect Gateway\n # Detaches Virtual Gateways to Direct Connect Gateway\n class Aws_direct_connect_gateway < Base\n # @return [:present, :absent, nil] present to ensure resource is created.,absent to remove resource\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] name of the dxgw to be created or deleted\n attribute :name\n validates :name, type: String\n\n # @return [Integer] amazon side asn\n attribute :amazon_asn\n validates :amazon_asn, presence: true, type: Integer\n\n # @return [Object, nil] id of an existing direct connect gateway\n attribute :direct_connect_gateway_id\n\n # @return [String, nil] vpn gateway id of an existing virtual gateway\n attribute :virtual_gateway_id\n validates :virtual_gateway_id, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.642988383769989, "alphanum_fraction": 0.6484996676445007, "avg_line_length": 39.82500076293945, "blob_id": "c9229f01be0149908874d4d8f5bbc48487b82c4c", "content_id": "03bb9aff91a4a3cfefceb224aa426813b49ace44", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1633, "license_type": "permissive", "max_line_length": 173, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_switchport.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages Layer 2 interfaces\n class Nxos_switchport < Base\n # @return [String, nil] Full name of the interface, i.e. Ethernet1/1.\n attribute :interface\n validates :interface, type: String\n\n # @return [:access, :trunk, nil] Mode for the Layer 2 port.\n attribute :mode\n validates :mode, expression_inclusion: {:in=>[:access, :trunk], :message=>\"%{value} needs to be :access, :trunk\"}, allow_nil: true\n\n # @return [Integer, nil] If C(mode=access), used as the access VLAN ID.\n attribute :access_vlan\n validates :access_vlan, type: Integer\n\n # @return [Integer, nil] If C(mode=trunk), used as the trunk native VLAN ID.\n attribute :native_vlan\n validates :native_vlan, type: Integer\n\n # @return [String, nil] If C(mode=trunk), used as the VLAN range to ADD or REMOVE from the trunk.\n attribute :trunk_vlans\n validates :trunk_vlans, type: String\n\n # @return [:present, :absent, :unconfigured, nil] Manage the state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :unconfigured], :message=>\"%{value} needs to be :present, :absent, :unconfigured\"}, allow_nil: true\n\n # @return [Object, nil] if C(mode=trunk), these are the only VLANs that will be configured on the trunk, i.e. \"2-10,15\".\n attribute :trunk_allowed_vlans\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6769706606864929, "alphanum_fraction": 0.6769706606864929, "avg_line_length": 29.809524536132812, "blob_id": "532d3f9531805c1dd035ae6393a499592b24dd5c", "content_id": "65cea16ebd3bf9430bf06ed332797c074f532ee8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 647, "license_type": "permissive", "max_line_length": 118, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/iam_role_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gathers information about IAM roles\n class Iam_role_facts < Base\n # @return [String, nil] Name of a role to search for,Mutually exclusive with C(prefix)\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] Prefix of role I(path) to restrict IAM role search for,Mutually exclusive with C(name)\n attribute :path_prefix\n validates :path_prefix, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.669511616230011, "alphanum_fraction": 0.669511616230011, "avg_line_length": 45.86666488647461, "blob_id": "cf4673c26249d042bc1618857ea156ece771f865", "content_id": "937881feda96d328a67288e8fac90d762a94c0c9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2109, "license_type": "permissive", "max_line_length": 346, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/packaging/os/apt_key.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove an I(apt) key, optionally downloading it.\n class Apt_key < Base\n # @return [String, Integer, nil] The identifier of the key.,Including this allows check mode to correctly report the changed state.,If specifying a subkey's id be aware that apt-key does not understand how to remove keys via a subkey id. Specify the primary key's id instead.,This parameter is required when C(state) is set to C(absent).\n attribute :id\n validates :id, type: MultipleTypes.new(String, Integer)\n\n # @return [String, nil] The keyfile contents to add to the keyring.\n attribute :data\n validates :data, type: String\n\n # @return [String, nil] The path to a keyfile on the remote server to add to the keyring.\n attribute :file\n validates :file, type: String\n\n # @return [String, nil] The full path to specific keyring file in /etc/apt/trusted.gpg.d/\n attribute :keyring\n validates :keyring, type: String\n\n # @return [String, nil] The URL to retrieve key from.\n attribute :url\n validates :url, type: String\n\n # @return [String, nil] The keyserver to retrieve key from.\n attribute :keyserver\n validates :keyserver, type: String\n\n # @return [:absent, :present, nil] Ensures that the key is present (added) or absent (revoked).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), SSL certificates for the target url will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6595127582550049, "alphanum_fraction": 0.6595127582550049, "avg_line_length": 37.31111145019531, "blob_id": "f2989c1879ea906a1a8b79471f1d782989222101", "content_id": "8237fde35c74814f1eb150222d8b3e9a4d218aaf", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1724, "license_type": "permissive", "max_line_length": 191, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/monitoring/rollbar_deployment.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Notify Rollbar about app deployments (see https://rollbar.com/docs/deploys_other/)\n class Rollbar_deployment < Base\n # @return [String] Your project access token.\n attribute :token\n validates :token, presence: true, type: String\n\n # @return [String] Name of the environment being deployed, e.g. 'production'.\n attribute :environment\n validates :environment, presence: true, type: String\n\n # @return [String] Revision number/sha being deployed.\n attribute :revision\n validates :revision, presence: true, type: String\n\n # @return [String, nil] User who deployed.\n attribute :user\n validates :user, type: String\n\n # @return [String, nil] Rollbar username of the user who deployed.\n attribute :rollbar_user\n validates :rollbar_user, type: String\n\n # @return [String, nil] Deploy comment (e.g. what is being deployed).\n attribute :comment\n validates :comment, type: String\n\n # @return [String, nil] Optional URL to submit the notification to.\n attribute :url\n validates :url, type: String\n\n # @return [:yes, :no, nil] If C(no), SSL certificates for the target url will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6871795058250427, "alphanum_fraction": 0.692307710647583, "avg_line_length": 38, "blob_id": "e9ff7b32f51444c6cd2e9f13e8193a6455f7c16e", "content_id": "65c5f76b1926831b76ce48d772bd23852b4c5c8b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 780, "license_type": "permissive", "max_line_length": 198, "num_lines": 20, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/redshift_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gather facts about Redshift cluster(s)\n class Redshift_facts < Base\n # @return [Object, nil] The prefix of cluster identifier of the Redshift cluster you are searching for.,This is a regular expression match with implicit '^'. Append '$' for a complete match.\n attribute :cluster_identifier\n\n # @return [Hash, nil] A dictionary/hash of tags in the format { tag1_name: 'tag1_value', tag2_name: 'tag2_value' } to match against the security group(s) you are searching for.\n attribute :tags\n validates :tags, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6772326231002808, "alphanum_fraction": 0.6893605589866638, "avg_line_length": 54.81538391113281, "blob_id": "937573b77a6a4704adc586a05583a367749b7962", "content_id": "1178cf20a1e31481db8d81758d53acc1f9d74df5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3628, "license_type": "permissive", "max_line_length": 378, "num_lines": 65, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_wafpolicy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure WafPolicy object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_wafpolicy < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Object, nil] Creator name.,Field introduced in 17.2.4.\n attribute :created_by\n\n # @return [Object, nil] Waf rules are categorized in to groups based on their characterization.,These groups are system created with crs groups.,Field introduced in 17.2.1.\n attribute :crs_groups\n\n # @return [Object, nil] Field introduced in 17.2.1.\n attribute :description\n\n # @return [Object] Waf policy mode.,This can be detection or enforcement.,Enum options - WAF_MODE_DETECTION_ONLY, WAF_MODE_ENFORCEMENT.,Field introduced in 17.2.1.,Default value when not specified in API or module is interpreted by Avi Controller as WAF_MODE_DETECTION_ONLY.\n attribute :mode\n validates :mode, presence: true\n\n # @return [String] Field introduced in 17.2.1.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Waf ruleset paranoia mode.,This is used to select rules based on the paranoia-level tag.,Enum options - WAF_PARANOIA_LEVEL_LOW, WAF_PARANOIA_LEVEL_MEDIUM, WAF_PARANOIA_LEVEL_HIGH, WAF_PARANOIA_LEVEL_EXTREME.,Field introduced in 17.2.1.,Default value when not specified in API or module is interpreted by Avi Controller as WAF_PARANOIA_LEVEL_LOW.\n attribute :paranoia_level\n\n # @return [Object, nil] Waf rules are categorized in to groups based on their characterization.,These groups are created by the user and will be enforced after the crs groups.,Field introduced in 17.2.1.\n attribute :post_crs_groups\n\n # @return [Object, nil] Waf rules are categorized in to groups based on their characterization.,These groups are created by the user and will be enforced before the crs groups.,Field introduced in 17.2.1.\n attribute :pre_crs_groups\n\n # @return [Object, nil] It is a reference to an object of type tenant.,Field introduced in 17.2.1.\n attribute :tenant_ref\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Field introduced in 17.2.1.\n attribute :uuid\n\n # @return [Object] Waf profile for waf policy.,It is a reference to an object of type wafprofile.,Field introduced in 17.2.1.\n attribute :waf_profile_ref\n validates :waf_profile_ref, presence: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6715789437294006, "alphanum_fraction": 0.6763157844543457, "avg_line_length": 45.34146499633789, "blob_id": "6f1f430e32fff2593ea102386b476b3507280700", "content_id": "37cb33973decfb4ad8e194b984a525df48880f0d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1900, "license_type": "permissive", "max_line_length": 322, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_appserviceplan.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and delete instance of App Service Plan.\n class Azure_rm_appserviceplan < Base\n # @return [String] Name of the resource group to which the resource belongs.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] Unique name of the app service plan to create or update.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Resource location. If not set, location from the resource group will be used as default.\n attribute :location\n validates :location, type: String\n\n # @return [String, nil] The pricing tiers, e.g., F1, D1, B1, B2, B3, S1, P1, P1V2 etc.,Please see U(https://azure.microsoft.com/en-us/pricing/details/app-service/plans/) for more detail.,For linux app service plan, please see U(https://azure.microsoft.com/en-us/pricing/details/app-service/linux/) for more detail.\n attribute :sku\n validates :sku, type: String\n\n # @return [Symbol, nil] Describe whether to host webapp on Linux worker.\n attribute :is_linux\n validates :is_linux, type: Symbol\n\n # @return [Integer, nil] Describe number of workers to be allocated.\n attribute :number_of_workers\n validates :number_of_workers, type: Integer\n\n # @return [:absent, :present, nil] Assert the state of the app service plan.,Use 'present' to create or update an app service plan and 'absent' to delete it.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6682134866714478, "alphanum_fraction": 0.6689868569374084, "avg_line_length": 37.02941131591797, "blob_id": "b5fbb9ec9ed1927d524ad477f4507486fbba6d69", "content_id": "d1d889fbc405a2bb7bc1f31ee762d857a4930024", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1293, "license_type": "permissive", "max_line_length": 157, "num_lines": 34, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/elasticache_snapshot.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage cache snapshots in Amazon Elasticache.\n # Returns information about the specified snapshot.\n class Elasticache_snapshot < Base\n # @return [String] The name of the snapshot we want to create, copy, delete\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, :copy, nil] Actions that will create, destroy, or copy a snapshot.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :copy], :message=>\"%{value} needs to be :present, :absent, :copy\"}, allow_nil: true\n\n # @return [Object, nil] The name of the existing replication group to make the snapshot.\n attribute :replication_id\n\n # @return [Object, nil] The name of an existing cache cluster in the replication group to make the snapshot.\n attribute :cluster_id\n\n # @return [Object, nil] The name of a snapshot copy\n attribute :target\n\n # @return [Object, nil] The s3 bucket to which the snapshot is exported\n attribute :bucket\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6966879963874817, "alphanum_fraction": 0.6966879963874817, "avg_line_length": 52.78125, "blob_id": "cd41c49f30d5e1717afd3b4d46dd9c9832662808", "content_id": "901089452665375f02187e6356d9e7fcda5c4729", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1721, "license_type": "permissive", "max_line_length": 321, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/remote_management/manageiq/manageiq_alert_profiles.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The manageiq_alert_profiles module supports adding, updating and deleting alert profiles in ManageIQ.\n class Manageiq_alert_profiles < Base\n # @return [:absent, :present, nil] absent - alert profile should not exist,,present - alert profile should exist,\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] The unique alert profile name in ManageIQ.,Required when state is \"absent\" or \"present\".\n attribute :name\n validates :name, type: String\n\n # @return [:Vm, :ContainerNode, :MiqServer, :Host, :Storage, :EmsCluster, :ExtManagementSystem, :MiddlewareServer, nil] The resource type for the alert profile in ManageIQ. Required when state is \"present\".\n attribute :resource_type\n validates :resource_type, expression_inclusion: {:in=>[:Vm, :ContainerNode, :MiqServer, :Host, :Storage, :EmsCluster, :ExtManagementSystem, :MiddlewareServer], :message=>\"%{value} needs to be :Vm, :ContainerNode, :MiqServer, :Host, :Storage, :EmsCluster, :ExtManagementSystem, :MiddlewareServer\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] List of alert descriptions to assign to this profile.,Required if state is \"present\"\n attribute :alerts\n validates :alerts, type: TypeGeneric.new(String)\n\n # @return [Object, nil] Optional notes for this profile\n attribute :notes\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6530366539955139, "alphanum_fraction": 0.6530366539955139, "avg_line_length": 37.67441940307617, "blob_id": "8569d3279c87e68289f94c9681d7f7a8d16c7536", "content_id": "ee14433912060572a11d3040a0574bbaba0adcac", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1663, "license_type": "permissive", "max_line_length": 157, "num_lines": 43, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_zone.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage OpenStack DNS zones. Zones can be created, deleted or updated. Only the I(email), I(description), I(ttl) and I(masters) values can be updated.\n class Os_zone < Base\n # @return [String] Zone name\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:primary, :secondary, nil] Zone type\n attribute :zone_type\n validates :zone_type, expression_inclusion: {:in=>[:primary, :secondary], :message=>\"%{value} needs to be :primary, :secondary\"}, allow_nil: true\n\n # @return [String, nil] Email of the zone owner (only applies if zone_type is primary)\n attribute :email\n validates :email, type: String\n\n # @return [String, nil] Zone description\n attribute :description\n validates :description, type: String\n\n # @return [Integer, nil] TTL (Time To Live) value in seconds\n attribute :ttl\n validates :ttl, type: Integer\n\n # @return [Object, nil] Master nameservers (only applies if zone_type is secondary)\n attribute :masters\n\n # @return [:present, :absent, nil] Should the resource be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7239024639129639, "alphanum_fraction": 0.7248780727386475, "avg_line_length": 59.29411697387695, "blob_id": "3256339da5d5720ed549b1f3e67a3ad0cef9a3e9", "content_id": "59d6010149f2d34fd050ba343163bf26467ce113", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1025, "license_type": "permissive", "max_line_length": 574, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/monitoring/zabbix/zabbix_screen.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows you to create, modify and delete Zabbix screens and associated graph data.\n class Zabbix_screen < Base\n # @return [Array<Hash>, Hash] List of screens to be created/updated/deleted(see example).,If the screen(s) already been added, the screen(s) name won't be updated.,When creating or updating screen(s), C(screen_name), C(host_group) are required.,When deleting screen(s), the C(screen_name) is required.,Option C(graphs_in_row) will limit columns of screen and make multiple rows (default 3),The available states are: C(present) (default) and C(absent). If the screen(s) already exists, and the state is not C(absent), the screen(s) will just be updated as needed.\\r\\n\n attribute :screens\n validates :screens, presence: true, type: TypeGeneric.new(Hash)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6621838212013245, "alphanum_fraction": 0.6634646058082581, "avg_line_length": 50.196720123291016, "blob_id": "6e61039bf2b6b18a7dc5057367ce6ba838f86243", "content_id": "5bcb7ab971ace46880582b9b3d98252d75cecbde", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3123, "license_type": "permissive", "max_line_length": 356, "num_lines": 61, "path": "/lib/ansible/ruby/modules/generated/system/lvol.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module creates, removes or resizes logical volumes.\n class Lvol < Base\n # @return [String, nil] The volume group this logical volume is part of.\n attribute :vg\n validates :vg, type: String\n\n # @return [String, nil] The name of the logical volume.\n attribute :lv\n validates :lv, type: String\n\n # @return [Integer, String, nil] The size of the logical volume, according to lvcreate(8) --size, by default in megabytes or optionally with one of [bBsSkKmMgGtTpPeE] units; or according to lvcreate(8) --extents as a percentage of [VG|PVS|FREE]; Float values must begin with a digit. Resizing using percentage values was not supported prior to 2.1.\n attribute :size\n validates :size, type: MultipleTypes.new(Integer, String)\n\n # @return [:absent, :present, nil] Control if the logical volume exists. If C(present) and the volume does not already exist then the C(size) option is required.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Whether the volume is activate and visible to the host.\n attribute :active\n validates :active, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Shrink or remove operations of volumes requires this switch. Ensures that that filesystems get never corrupted/destroyed by mistake.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Free-form options to be passed to the lvcreate command.\n attribute :opts\n validates :opts, type: String\n\n # @return [String, nil] The name of the snapshot volume\n attribute :snapshot\n validates :snapshot, type: String\n\n # @return [Array<String>, String, nil] Comma separated list of physical volumes (e.g. /dev/sda,/dev/sdb).\n attribute :pvs\n validates :pvs, type: TypeGeneric.new(String)\n\n # @return [String, nil] The thin pool volume name. When you want to create a thin provisioned volume, specify a thin pool volume name.\n attribute :thinpool\n validates :thinpool, type: String\n\n # @return [:yes, :no, nil] Shrink if current size is higher than size requested.\n attribute :shrink\n validates :shrink, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Resize the underlying filesystem together with the logical volume.\n attribute :resizefs\n validates :resizefs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6913875341415405, "alphanum_fraction": 0.6913875341415405, "avg_line_length": 38.80952453613281, "blob_id": "a7118704770b811fc320bcb6ef1d89bcbebd76e0", "content_id": "ff8ae93d5099d6a7749d7e281aa45d771849d3e6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 836, "license_type": "permissive", "max_line_length": 150, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/elb_target_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module will search through every target group in a region to find which ones have registered a given instance ID or IP.\n class Elb_target_facts < Base\n # @return [String] What instance ID to get facts for.\n attribute :instance_id\n validates :instance_id, presence: true, type: String\n\n # @return [Boolean, nil] Whether or not to get target groups not used by any load balancers.\n attribute :get_unused_target_groups\n validates :get_unused_target_groups, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6855765581130981, "alphanum_fraction": 0.6855765581130981, "avg_line_length": 48.94444274902344, "blob_id": "80ecb19fce53dbfa860a77b3d7890c71507ef9ed", "content_id": "2798c7177180dc8b8bc3bdddddbb13dc32091517", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2697, "license_type": "permissive", "max_line_length": 193, "num_lines": 54, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/netapp_e_storage_system.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage the arrays accessible via a NetApp Web Services Proxy for NetApp E-series storage arrays.\n class Netapp_e_storage_system < Base\n # @return [String] The username to authenticate with the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_username\n validates :api_username, presence: true, type: String\n\n # @return [String] The password to authenticate with the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_password\n validates :api_password, presence: true, type: String\n\n # @return [String] The url to the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_url\n validates :api_url, presence: true, type: String\n\n # @return [:yes, :no, nil] Should https certificates be validated?\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String] The ID of the array to manage. This value must be unique for each array.\n attribute :ssid\n validates :ssid, presence: true, type: String\n\n # @return [:present, :absent] Whether the specified array should be configured on the Web Services Proxy or not.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [Array<String>, String] The list addresses for the out-of-band management adapter or the agent host. Mutually exclusive of array_wwn parameter.\n attribute :controller_addresses\n validates :controller_addresses, presence: true, type: TypeGeneric.new(String)\n\n # @return [Object, nil] The WWN of the array to manage. Only necessary if in-band managing multiple arrays on the same agent host. Mutually exclusive of controller_addresses parameter.\n attribute :array_wwn\n\n # @return [Object, nil] The management password of the array to manage, if set.\n attribute :array_password\n\n # @return [:yes, :no, nil] Enable trace logging for SYMbol calls to the storage system.\n attribute :enable_trace\n validates :enable_trace, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Optional meta tags to associate to this storage system\n attribute :meta_tags\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6905339956283569, "alphanum_fraction": 0.6905339956283569, "avg_line_length": 53.93333435058594, "blob_id": "cb1162317b5d08024ac177b80c04b8b3b73d0fed", "content_id": "b5cfb0986ceeb58e556c67c94d6d7a12e1fc9dd1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1648, "license_type": "permissive", "max_line_length": 278, "num_lines": 30, "path": "/lib/ansible/ruby/modules/generated/windows/win_environment.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Uses .net Environment to set or remove environment variables and can set at User, Machine or Process level.\n # User level environment variables will be set, but not available until the user has logged off and on again.\n class Win_environment < Base\n # @return [:absent, :present, nil] Set to C(present) to ensure environment variable is set.,Set to C(absent) to ensure it is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String] The name of the environment variable.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The value to store in the environment variable.,Must be set when C(state=present) and cannot be an empty string.,Can be omitted for C(state=absent).\n attribute :value\n validates :value, type: String\n\n # @return [:machine, :user, :process] The level at which to set the environment variable.,Use C(machine) to set for all users.,Use C(user) to set for the current user that ansible is connected as.,Use C(process) to set for the current process. Probably not that useful.\n attribute :level\n validates :level, presence: true, expression_inclusion: {:in=>[:machine, :user, :process], :message=>\"%{value} needs to be :machine, :user, :process\"}\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6879588961601257, "alphanum_fraction": 0.6879588961601257, "avg_line_length": 40.272727966308594, "blob_id": "0575fc6f654b6ef2c0f9cb4498acae2da81d3c4a", "content_id": "44f483083a89a41ee81c7c6e6f3317676c49877e", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1362, "license_type": "permissive", "max_line_length": 140, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/netapp_e_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Return various information about NetApp E-Series storage arrays (eg, configuration, disks)\n class Netapp_e_facts < Base\n # @return [String] The username to authenticate with the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_username\n validates :api_username, presence: true, type: String\n\n # @return [String] The password to authenticate with the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_password\n validates :api_password, presence: true, type: String\n\n # @return [String] The url to the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_url\n validates :api_url, presence: true, type: String\n\n # @return [Boolean, nil] Should https certificates be validated?\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object] The ID of the array to manage. This value must be unique for each array.\n attribute :ssid\n validates :ssid, presence: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6889386177062988, "alphanum_fraction": 0.6937339901924133, "avg_line_length": 60.33333206176758, "blob_id": "809bb6a9dd7dbdc7dfc65f11b85280f7e17ca61b", "content_id": "f6b2950ec2c8bec45fc56ea89150069288326891", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3128, "license_type": "permissive", "max_line_length": 583, "num_lines": 51, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_guest_file_operation.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Module to copy a file to a VM, fetch a file from a VM and create or delete a directory in the guest OS.\n class Vmware_guest_file_operation < Base\n # @return [String, nil] The datacenter hosting the virtual machine.,If set, it will help to speed up virtual machine search.\n attribute :datacenter\n validates :datacenter, type: String\n\n # @return [Object, nil] The cluster hosting the virtual machine.,If set, it will help to speed up virtual machine search.\n attribute :cluster\n\n # @return [Object, nil] Destination folder, absolute path to find an existing guest or create the new guest.,The folder should include the datacenter. ESX's datacenter is ha-datacenter,Used only if C(vm_id_type) is C(inventory_path).,Examples:, folder: /ha-datacenter/vm, folder: ha-datacenter/vm, folder: /datacenter1/vm, folder: datacenter1/vm, folder: /datacenter1/vm/folder1, folder: datacenter1/vm/folder1, folder: /folder1/datacenter1/vm, folder: folder1/datacenter1/vm, folder: /folder1/datacenter1/vm/folder2, folder: vm/folder2, folder: folder2\n attribute :folder\n\n # @return [String] Name of the virtual machine to work with.\n attribute :vm_id\n validates :vm_id, presence: true, type: String\n\n # @return [:uuid, :dns_name, :inventory_path, :vm_name, nil] The VMware identification method by which the virtual machine will be identified.\n attribute :vm_id_type\n validates :vm_id_type, expression_inclusion: {:in=>[:uuid, :dns_name, :inventory_path, :vm_name], :message=>\"%{value} needs to be :uuid, :dns_name, :inventory_path, :vm_name\"}, allow_nil: true\n\n # @return [String] The user to login in to the virtual machine.\n attribute :vm_username\n validates :vm_username, presence: true, type: String\n\n # @return [String] The password used to login-in to the virtual machine.\n attribute :vm_password\n validates :vm_password, presence: true, type: String\n\n # @return [Hash, nil] Create or delete directory.,Valid attributes are:, path: directory path to create or remove, operation: Valid values are create, delete, recurse (boolean): Not required, default (false)\n attribute :directory\n validates :directory, type: Hash\n\n # @return [Hash, nil] Copy file to vm without requiring network.,Valid attributes are:, src: file source absolute or relative, dest: file destination, path must be exist, overwrite: False or True (not required, default False)\n attribute :copy\n validates :copy, type: Hash\n\n # @return [Hash, nil] Get file from virtual machine without requiring network.,Valid attributes are:, src: The file on the remote system to fetch. This I(must) be a file, not a directory, dest: file destination on localhost, path must be exist\n attribute :fetch\n validates :fetch, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6583629846572876, "alphanum_fraction": 0.6583629846572876, "avg_line_length": 16.5625, "blob_id": "75597155a3868667f68bcac9304398a5d88e742c", "content_id": "8cb419dae89337d61eebdad9a477f046f50fb6ca", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 281, "license_type": "permissive", "max_line_length": 44, "num_lines": 16, "path": "/lib/ansible/ruby/modules/custom/utilities/include_vars.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'ansible/ruby/modules/free_form'\n\nmodule Ansible\n module Ruby\n module Modules\n class Include_vars < Base\n attribute :free_form\n validates :free_form, presence: true\n\n include FreeForm\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6786484718322754, "alphanum_fraction": 0.6793673634529114, "avg_line_length": 46.965518951416016, "blob_id": "94a695b999eb67881fa1099e4ec90525a3a78e8b", "content_id": "4978013f86ed09d31142372dd3aa4b0fdffae44f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1391, "license_type": "permissive", "max_line_length": 144, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_sgw_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Fetch AWS Storage Gateway facts\n class Aws_sgw_facts < Base\n # @return [Boolean, nil] Gather local disks attached to the storage gateway.\n attribute :gather_local_disks\n validates :gather_local_disks, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Gather tape information for storage gateways in tape mode.\n attribute :gather_tapes\n validates :gather_tapes, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Gather file share information for storage gateways in s3 mode.\n attribute :gather_file_shares\n validates :gather_file_shares, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Gather volume information for storage gateways in iSCSI (cached & stored) modes.\n attribute :gather_volumes\n validates :gather_volumes, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6511744260787964, "alphanum_fraction": 0.6511744260787964, "avg_line_length": 39.836734771728516, "blob_id": "1850cc7a16a45df2a6eb03d0a04ee92a1d54d4d7", "content_id": "7f3ee9f579dc06830307f4e13dd6fb1e29d0fa75", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2001, "license_type": "permissive", "max_line_length": 187, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_vrrp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages VRRP configuration on NX-OS switches.\n class Nxos_vrrp < Base\n # @return [Integer] VRRP group number.\n attribute :group\n validates :group, presence: true, type: Integer\n\n # @return [String] Full name of interface that is being managed for VRRP.\n attribute :interface\n validates :interface, presence: true, type: String\n\n # @return [Integer, nil] Time interval between advertisement or 'default' keyword\n attribute :interval\n validates :interval, type: Integer\n\n # @return [Integer, nil] VRRP priority or 'default' keyword\n attribute :priority\n validates :priority, type: Integer\n\n # @return [:yes, :no, nil] Enable/Disable preempt.\n attribute :preempt\n validates :preempt, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] VRRP virtual IP address or 'default' keyword\n attribute :vip\n validates :vip, type: String\n\n # @return [String, nil] Clear text authentication string or 'default' keyword\n attribute :authentication\n validates :authentication, type: String\n\n # @return [:shutdown, :\"no shutdown\", :default, nil] Used to enable or disable the VRRP process.\n attribute :admin_state\n validates :admin_state, expression_inclusion: {:in=>[:shutdown, :\"no shutdown\", :default], :message=>\"%{value} needs to be :shutdown, :\\\"no shutdown\\\", :default\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Specify desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6635379195213318, "alphanum_fraction": 0.6657039523124695, "avg_line_length": 42.28125, "blob_id": "1613e467ae6ea36074fd2ec9ba7514185ef0fe7c", "content_id": "a88a14e304d056281406dd28880dad4c5fc1c402", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1385, "license_type": "permissive", "max_line_length": 159, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_aaa_user_certificate.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage AAA user certificates on Cisco ACI fabrics.\n class Aci_aaa_user_certificate < Base\n # @return [String] The name of the user to add a certificate to.\n attribute :aaa_user\n validates :aaa_user, presence: true, type: String\n\n # @return [:appuser, :user, nil] Whether this is a normal user or an appuser.\n attribute :aaa_user_type\n validates :aaa_user_type, expression_inclusion: {:in=>[:appuser, :user], :message=>\"%{value} needs to be :appuser, :user\"}, allow_nil: true\n\n # @return [Object, nil] The PEM format public key extracted from the X.509 certificate.\n attribute :certificate\n\n # @return [String, nil] The name of the user certificate entry in ACI.\n attribute :certificate_name\n validates :certificate_name, type: String\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7207792401313782, "alphanum_fraction": 0.7207792401313782, "avg_line_length": 35.235294342041016, "blob_id": "8e7927e9ad8e59304c1271a60e149f5032807c27", "content_id": "c03f4608bd4d2168e7675fd30fc39637e1a5923f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 616, "license_type": "permissive", "max_line_length": 192, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/cloud/digital_ocean/digital_ocean_volume_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to gather facts about DigitalOcean provided volumes.\n class Digital_ocean_volume_facts < Base\n # @return [String, nil] Name of region to restrict results to volumes available in a specific region.,Please use M(digital_ocean_region_facts) for getting valid values related regions.\n attribute :region_name\n validates :region_name, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 27.428571701049805, "blob_id": "e59fc4cf1129b60e8744dfe3d6ee2215a4287e76", "content_id": "d36aa021791cc37f9c378562b948e75b4973b948", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 597, "license_type": "permissive", "max_line_length": 75, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/nginx_status_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gathers facts from nginx from an URL having C(stub_status) enabled.\n class Nginx_status_facts < Base\n # @return [String] URL of the nginx status.\n attribute :url\n validates :url, presence: true, type: String\n\n # @return [Integer, nil] HTTP connection timeout in seconds.\n attribute :timeout\n validates :timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.69487065076828, "alphanum_fraction": 0.69487065076828, "avg_line_length": 56.025001525878906, "blob_id": "717e6a7f11ca7fef3881443ff885416859fbc313", "content_id": "3ecf417dc5f1c9c984f34e10f6fff36874e4ae27", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4562, "license_type": "permissive", "max_line_length": 773, "num_lines": 80, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_webapp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and delete instance of Web App.\n class Azure_rm_webapp < Base\n # @return [String] Name of the resource group to which the resource belongs.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] Unique name of the app to create or update. To create or update a deployment slot, use the {slot} parameter.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Resource location. If not set, location from the resource group will be used as default.\n attribute :location\n\n # @return [Hash, String, nil] App service plan. Required for creation.,It can be name of existing app service plan in same resource group as web app.,It can be resource id of existing app service plan. eg., /subscriptions/<subs_id>/resourceGroups/<resource_group>/providers/Microsoft.Web/serverFarms/<plan_name>,It can be a dict which contains C(name), C(resource_group), C(sku), C(is_linux) and C(number_of_workers).,C(name). Name of app service plan.,C(resource_group). Resource group name of app service plan.,C(sku). SKU of app service plan. For allowed sku, please refer to U(https://azure.microsoft.com/en-us/pricing/details/app-service/linux/).,C(is_linux). Indicates Linux app service plan. type bool. default False.,C(number_of_workers). Number of workers.\n attribute :plan\n validates :plan, type: MultipleTypes.new(Hash, String)\n\n # @return [Array<Hash>, Hash, nil] Set of run time framework settings. Each setting is a dictionary.,See U(https://docs.microsoft.com/en-us/azure/app-service/app-service-web-overview) for more info.\n attribute :frameworks\n validates :frameworks, type: TypeGeneric.new(Hash)\n\n # @return [Hash, nil] Web app container settings.\n attribute :container_settings\n validates :container_settings, type: Hash\n\n # @return [Object, nil] Repository type of deployment source. Eg. LocalGit, GitHub.,Please see U(https://docs.microsoft.com/en-us/rest/api/appservice/webapps/createorupdate#scmtype) for more info.\n attribute :scm_type\n\n # @return [Object, nil] Deployment source for git\n attribute :deployment_source\n\n # @return [Object, nil] The web's startup file.,This only applies for linux web app.\n attribute :startup_file\n\n # @return [Boolean, nil] True to enable client affinity; False to stop sending session affinity cookies, which route client requests in the same session to the same instance.\n attribute :client_affinity_enabled\n validates :client_affinity_enabled, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Symbol, nil] Configures web site to accept only https requests.\n attribute :https_only\n validates :https_only, type: Symbol\n\n # @return [Symbol, nil] If true web app hostname is not registered with DNS on creation.\n attribute :dns_registration\n validates :dns_registration, type: Symbol\n\n # @return [Symbol, nil] If true, custom (non *.azurewebsites.net) domains associated with web app are not verified.\n attribute :skip_custom_domain_verification\n validates :skip_custom_domain_verification, type: Symbol\n\n # @return [Object, nil] Time to live in seconds for web app default domain name.\n attribute :ttl_in_seconds\n\n # @return [Hash, nil] Configure web app application settings. Suboptions are in key value pair format.\n attribute :app_settings\n validates :app_settings, type: Hash\n\n # @return [Symbol, nil] Purge any existing application settings. Replace web app application settings with app_settings.\n attribute :purge_app_settings\n validates :purge_app_settings, type: Symbol\n\n # @return [String, nil] Start/Stop/Restart the web app.\n attribute :app_state\n validates :app_state, type: String\n\n # @return [:absent, :present, nil] Assert the state of the Web App.,Use 'present' to create or update a Web App and 'absent' to delete it.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6746177077293396, "alphanum_fraction": 0.6758409738540649, "avg_line_length": 39.875, "blob_id": "069462bd77f01839421ad47cb839a5860b9c5e2b", "content_id": "91b812b7ca66479039a4b5e25ae62dacae6b30aa", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1635, "license_type": "permissive", "max_line_length": 215, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/supervisorctl.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage the state of a program or group of programs running via supervisord\n class Supervisorctl < Base\n # @return [String] The name of the supervisord program or group to manage.,The name will be taken as group name when it ends with a colon I(:),Group support is only available in Ansible version 1.6 or later.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The supervisor configuration file path\n attribute :config\n validates :config, type: String\n\n # @return [String, nil] URL on which supervisord server is listening\n attribute :server_url\n validates :server_url, type: String\n\n # @return [String, nil] username to use for authentication\n attribute :username\n validates :username, type: String\n\n # @return [String, nil] password to use for authentication\n attribute :password\n validates :password, type: String\n\n # @return [:present, :started, :stopped, :restarted, :absent] The desired state of program/group.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :started, :stopped, :restarted, :absent], :message=>\"%{value} needs to be :present, :started, :stopped, :restarted, :absent\"}\n\n # @return [Object, nil] path to supervisorctl executable\n attribute :supervisorctl_path\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7170283794403076, "alphanum_fraction": 0.7186978459358215, "avg_line_length": 48.91666793823242, "blob_id": "2d551f56b251bb023ce5c81011bbdce6efedce6a", "content_id": "f9282daeabf415e8b53e16ae3cd4176ef19d02ad", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1198, "license_type": "permissive", "max_line_length": 189, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_host_vmnic_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to gather facts about vmnics available on the given ESXi host.\n # If C(cluster_name) is provided, then vmnic facts about all hosts from given cluster will be returned.\n # If C(esxi_hostname) is provided, then vmnic facts about given host system will be returned.\n # Additional details about vswitch and dvswitch with respective vmnic is also provided which is added in 2.7 version.\n class Vmware_host_vmnic_facts < Base\n # @return [String, nil] Name of the cluster.,Vmnic facts about each ESXi server will be returned for the given cluster.,If C(esxi_hostname) is not given, this parameter is required.\n attribute :cluster_name\n validates :cluster_name, type: String\n\n # @return [String, nil] ESXi hostname.,Vmnic facts about this ESXi server will be returned.,If C(cluster_name) is not given, this parameter is required.\n attribute :esxi_hostname\n validates :esxi_hostname, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6553713083267212, "alphanum_fraction": 0.6553713083267212, "avg_line_length": 41.030303955078125, "blob_id": "0c80969451d0eda8e8e5bfa121c71f5bec49babe", "content_id": "344c2baf01afddc6e04958c18acc72c9ae4691af", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1387, "license_type": "permissive", "max_line_length": 143, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_domain.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and remove domains.\n class Cs_domain < Base\n # @return [String] Path of the domain.,Prefix C(ROOT/) or C(/ROOT/) in path is optional.\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [String, nil] Network domain for networks in the domain.\n attribute :network_domain\n validates :network_domain, type: String\n\n # @return [Boolean, nil] Clean up all domain resources like child domains and accounts.,Considered on C(state=absent).\n attribute :clean_up\n validates :clean_up, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:present, :absent, nil] State of the domain.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Boolean, nil] Poll async jobs until job has finished.\n attribute :poll_async\n validates :poll_async, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6851562261581421, "alphanum_fraction": 0.6859375238418579, "avg_line_length": 37.787879943847656, "blob_id": "ff4a7457116e9319d008eba66a3cc2ece61951ee", "content_id": "cbc15b44eaf8c52d368db9725d150792df3ae7e7", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1280, "license_type": "permissive", "max_line_length": 192, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_virtualmachineimage_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Get facts for virtual machine images.\n class Azure_rm_virtualmachineimage_facts < Base\n # @return [String] Azure location value (ie. westus, eastus, eastus2, northcentralus, etc.). Supplying only a location value will yield a list of available publishers for the location.\n attribute :location\n validates :location, presence: true, type: String\n\n # @return [String, nil] Name of an image publisher. List image offerings associated with a particular publisher.\n attribute :publisher\n validates :publisher, type: String\n\n # @return [String, nil] Name of an image offering. Combine with sku to see a list of available image versions.\n attribute :offer\n validates :offer, type: String\n\n # @return [String, nil] Image offering SKU. Combine with offer to see a list of available versions.\n attribute :sku\n validates :sku, type: String\n\n # @return [String, nil] Specific version number of an image.\n attribute :version\n validates :version, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.64987713098526, "alphanum_fraction": 0.64987713098526, "avg_line_length": 31.559999465942383, "blob_id": "7a1c52f0be4fb82d68b260227afbb9809841131c", "content_id": "856300d0ee759fa4ed3eab237d75cdec9fb59253", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 814, "license_type": "permissive", "max_line_length": 129, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/windows/win_owner.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Set owner of files or directories\n class Win_owner < Base\n # @return [String] Path to be used for changing owner\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [String] Name to be used for changing owner\n attribute :user\n validates :user, presence: true, type: String\n\n # @return [:yes, :no, nil] Indicates if the owner should be changed recursively\n attribute :recurse\n validates :recurse, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5920976400375366, "alphanum_fraction": 0.6008135080337524, "avg_line_length": 22.90277862548828, "blob_id": "21fae133cefd445d8c93ca45384a6e67c226a5dd", "content_id": "a65c2274eab04c0a7901eeeae0cdb7e0ae68097c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1721, "license_type": "permissive", "max_line_length": 126, "num_lines": 72, "path": "/lib/ansible/ruby/modules/free_form_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# See LICENSE.txt for license\n\nrequire 'spec_helper'\nrequire 'ansible/ruby/modules/free_form'\n\ndescribe Ansible::Ruby::Modules::FreeForm do\n before { stub_const 'Ansible::Ruby::Modules::SomeModule', klass }\n\n subject { instance }\n\n let(:klass) do\n Class.new(Ansible::Ruby::Modules::Base) do\n attribute :free_form\n validates :free_form, presence: true\n attribute :foo\n end\n end\n\n before do\n # simulate monkey patching existing\n klass.class_eval do\n include Ansible::Ruby::Modules::FreeForm\n end\n end\n\n describe 'validation' do\n context 'missing required value' do\n let(:instance) { klass.new {} }\n\n it { is_expected.to_not be_valid }\n it { is_expected.to have_errors free_form: 'Argument directly after some_module e.g. some_module(arg) cannot be blank' }\n end\n\n context 'not string' do\n let(:instance) { klass.new free_form: 123 }\n\n it { is_expected.to_not be_valid }\n it { is_expected.to have_errors free_form: 'some_module(123), 123 is expected to be a String but was a Integer' }\n end\n\n context 'valid' do\n let(:instance) { klass.new free_form: 'howdy' }\n\n it { is_expected.to be_valid }\n end\n end\n\n describe '#to_h' do\n subject { instance.to_h }\n\n context 'args' do\n let(:instance) { klass.new free_form: 'howdy', foo: 123 }\n\n it do\n is_expected.to eq(some_module: 'howdy',\n args: {\n foo: 123\n })\n end\n end\n\n context 'no args' do\n let(:instance) { klass.new free_form: 'howdy' }\n\n it do\n is_expected.to eq(some_module: 'howdy')\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6719653010368347, "alphanum_fraction": 0.6719653010368347, "avg_line_length": 31.952381134033203, "blob_id": "8072cf49569c95319201402ef0dc6f95ddb2ea17", "content_id": "fe0d386aef70c56ad83dda4d07e1b40eb9c05298", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 692, "license_type": "permissive", "max_line_length": 143, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_snmp_contact.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages SNMP contact configurations on HUAWEI CloudEngine switches.\n class Ce_snmp_contact < Base\n # @return [Object] Contact information.\n attribute :contact\n validates :contact, presence: true\n\n # @return [:present, :absent, nil] Manage the state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6607773900032043, "alphanum_fraction": 0.6607773900032043, "avg_line_length": 25.952381134033203, "blob_id": "e82a146ca8733957a42ffc56f96ddf7a475b18d7", "content_id": "a3bdba8532788d9234e81ce5e524d7532f77edd1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 566, "license_type": "permissive", "max_line_length": 62, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/database/influxdb/influxdb_query.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Query data points from InfluxDB.\n class Influxdb_query < Base\n # @return [String] Query to be executed.\n attribute :query\n validates :query, presence: true, type: String\n\n # @return [String] Name of the database.\n attribute :database_name\n validates :database_name, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6419108510017395, "alphanum_fraction": 0.6635889410972595, "avg_line_length": 49.836734771728516, "blob_id": "0800d1b8554be46dc58aa3c807512d68db7330ce", "content_id": "009350312c0acb0e8d82d99802503a4d67c4ac62", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2491, "license_type": "permissive", "max_line_length": 251, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/cloud/centurylink/clc_firewall_policy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or delete or update firewall polices on Centurylink Cloud\n class Clc_firewall_policy < Base\n # @return [Object] Target datacenter for the firewall policy\n attribute :location\n validates :location, presence: true\n\n # @return [:present, :absent, nil] Whether to create or delete the firewall policy\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] The list of source addresses for traffic on the originating firewall. This is required when state is 'present'\n attribute :source\n\n # @return [Object, nil] The list of destination addresses for traffic on the terminating firewall. This is required when state is 'present'\n attribute :destination\n\n # @return [:any, :icmp, :\"TCP/123\", :\"UDP/123\", :\"TCP/123-456\", :\"UDP/123-456\", nil] The list of ports associated with the policy. TCP and UDP can take in single ports or port ranges.\n attribute :ports\n validates :ports, expression_inclusion: {:in=>[:any, :icmp, :\"TCP/123\", :\"UDP/123\", :\"TCP/123-456\", :\"UDP/123-456\"], :message=>\"%{value} needs to be :any, :icmp, :\\\"TCP/123\\\", :\\\"UDP/123\\\", :\\\"TCP/123-456\\\", :\\\"UDP/123-456\\\"\"}, allow_nil: true\n\n # @return [Object, nil] Id of the firewall policy. This is required to update or delete an existing firewall policy\n attribute :firewall_policy_id\n\n # @return [Object] CLC alias for the source account\n attribute :source_account_alias\n validates :source_account_alias, presence: true\n\n # @return [Object, nil] CLC alias for the destination account\n attribute :destination_account_alias\n\n # @return [:yes, :no, nil] Whether to wait for the provisioning tasks to finish before returning.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Boolean, nil] Whether the firewall policy is enabled or disabled\n attribute :enabled\n validates :enabled, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7288811206817627, "alphanum_fraction": 0.7293795347213745, "avg_line_length": 84.38298034667969, "blob_id": "7a0ae38735d95200dd004911ba5ff62327a1e3d2", "content_id": "091aff7c1f01198554a1d58ef175fd1c295e92b7", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4013, "license_type": "permissive", "max_line_length": 529, "num_lines": 47, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_command.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Sends an arbitrary command to an BIG-IP node and returns the results read from the device. This module includes an argument that will cause the module to wait for a specific condition before returning or timing out if the condition is not met.\n # This module is B(not) idempotent, nor will it ever be. It is intended as a stop-gap measure to satisfy automation requirements until such a time as a real module has been developed to configure in the way you need.\n # If you are using this module, you should probably also be filing an issue to have a B(real) module created for your needs.\n class Bigip_command < Base\n # @return [Array<String>, String] The commands to send to the remote BIG-IP device over the configured provider. The resulting output from the command is returned. If the I(wait_for) argument is provided, the module is not returned until the condition is satisfied or the number of retries as expired.,Only C(tmsh) commands are supported. If you are piping or adding additional logic that is outside of C(tmsh) (such as grep'ing, awk'ing or other shell related things that are not C(tmsh), this behavior is not supported.\n attribute :commands\n validates :commands, presence: true, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] Specifies what to evaluate from the output of the command and what conditionals to apply. This argument will cause the task to wait for a particular conditional to be true before moving forward. If the conditional is not true by the configured retries, the task fails. See examples.\n attribute :wait_for\n validates :wait_for, type: TypeGeneric.new(String)\n\n # @return [:any, :all, nil] The I(match) argument is used in conjunction with the I(wait_for) argument to specify the match policy. Valid values are C(all) or C(any). If the value is set to C(all) then all conditionals in the I(wait_for) must be satisfied. If the value is set to C(any) then only one of the values must be satisfied.\n attribute :match\n validates :match, expression_inclusion: {:in=>[:any, :all], :message=>\"%{value} needs to be :any, :all\"}, allow_nil: true\n\n # @return [Integer, nil] Specifies the number of retries a command should by tried before it is considered failed. The command is run on the target device every retry and evaluated against the I(wait_for) conditionals.\n attribute :retries\n validates :retries, type: Integer\n\n # @return [Integer, nil] Configures the interval in seconds to wait between retries of the command. If the command does not pass the specified conditional, the interval indicates how to long to wait before trying the command again.\n attribute :interval\n validates :interval, type: Integer\n\n # @return [:rest, :cli] Configures the transport connection to use when connecting to the remote device. The transport argument supports connectivity to the device over cli (ssh) or rest.\n attribute :transport\n validates :transport, presence: true, expression_inclusion: {:in=>[:rest, :cli], :message=>\"%{value} needs to be :rest, :cli\"}\n\n # @return [Boolean, nil] Whether the module should raise warnings related to command idempotency or not.,Note that the F5 Ansible developers specifically leave this on to make you aware that your usage of this module may be better served by official F5 Ansible modules. This module should always be used as a last resort.\n attribute :warn\n validates :warn, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] Change into this directory before running the command.\n attribute :chdir\n validates :chdir, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6850116848945618, "alphanum_fraction": 0.6850116848945618, "avg_line_length": 39.66666793823242, "blob_id": "71f0e6d9dcaeb0c7070469c8e869bf75bc49cacc", "content_id": "0990bf53c359b63b024e85ecf9b220ec302c7b2f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 854, "license_type": "permissive", "max_line_length": 147, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/windows/win_chocolatey_feature.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Used to enable or disable features in Chocolatey.\n class Win_chocolatey_feature < Base\n # @return [String] The name of the feature to manage.,Run C(choco.exe feature list) to get a list of features that can be managed.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:disabled, :enabled, nil] When C(disabled) then the feature will be disabled.,When C(enabled) then the feature will be enabled.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:disabled, :enabled], :message=>\"%{value} needs to be :disabled, :enabled\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.678077220916748, "alphanum_fraction": 0.685724675655365, "avg_line_length": 62.86046600341797, "blob_id": "7ec4fa191303cadbdd75b78b75f43db6dfc33ee6", "content_id": "f9030ad389571df49714600080351e2062f799ad", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2746, "license_type": "permissive", "max_line_length": 506, "num_lines": 43, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_vpc_nacl.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Read the AWS documentation for Network ACLS U(http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_ACLs.html)\n class Ec2_vpc_nacl < Base\n # @return [String, nil] Tagged name identifying a network ACL.,One and only one of the I(name) or I(nacl_id) is required.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] NACL id identifying a network ACL.,One and only one of the I(name) or I(nacl_id) is required.\n attribute :nacl_id\n validates :nacl_id, type: String\n\n # @return [String, nil] VPC id of the requesting VPC.,Required when state present.\n attribute :vpc_id\n validates :vpc_id, type: String\n\n # @return [Array<String>, String, nil] The list of subnets that should be associated with the network ACL.,Must be specified as a list,Each subnet can be specified as subnet ID, or its tagged name.\n attribute :subnets\n validates :subnets, type: TypeGeneric.new(String)\n\n # @return [Object, nil] A list of rules for outgoing traffic. Each rule must be specified as a list. Each rule may contain the rule number (integer 1-32766), protocol (one of ['tcp', 'udp', 'icmp', '-1', 'all']), the rule action ('allow' or 'deny') the CIDR of the IPv4 network range to allow or deny, the ICMP type (-1 means all types), the ICMP code (-1 means all codes), the last port in the range for TCP or UDP protocols, and the first port in the range for TCP or UDP protocols. See examples.\n attribute :egress\n\n # @return [Object, nil] List of rules for incoming traffic. Each rule must be specified as a list. Each rule may contain the rule number (integer 1-32766), protocol (one of ['tcp', 'udp', 'icmp', '-1', 'all']), the rule action ('allow' or 'deny') the CIDR of the IPv4 network range to allow or deny, the ICMP type (-1 means all types), the ICMP code (-1 means all codes), the last port in the range for TCP or UDP protocols, and the first port in the range for TCP or UDP protocols. See examples.\n attribute :ingress\n\n # @return [Hash, nil] Dictionary of tags to look for and apply when creating a network ACL.\n attribute :tags\n validates :tags, type: Hash\n\n # @return [:present, :absent, nil] Creates or modifies an existing NACL,Deletes a NACL and reassociates subnets to the default NACL\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.640694260597229, "alphanum_fraction": 0.642171323299408, "avg_line_length": 33.71794891357422, "blob_id": "4ca40e3a31982ee091a2060a9523434d3f3090a7", "content_id": "41eccc4dc338135cd3dade0bd6b5d14448ecb5c4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2708, "license_type": "permissive", "max_line_length": 114, "num_lines": 78, "path": "/lib/ansible/ruby/modules/generated/network/panos/panos_match_rule.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Security policies allow you to enforce rules and take action, and can be as general or specific as needed.\n class Panos_match_rule < Base\n # @return [String] IP address (or hostname) of PAN-OS device being configured.\n attribute :ip_address\n validates :ip_address, presence: true, type: String\n\n # @return [String, nil] Username credentials to use for auth unless I(api_key) is set.\n attribute :username\n validates :username, type: String\n\n # @return [String] Password credentials to use for auth unless I(api_key) is set.\n attribute :password\n validates :password, presence: true, type: String\n\n # @return [Object, nil] API key that can be used instead of I(username)/I(password) credentials.\n attribute :api_key\n\n # @return [String, nil] Type of rule. Valid types are I(security) or I(nat).\n attribute :rule_type\n validates :rule_type, type: String\n\n # @return [String, nil] The source zone.\n attribute :source_zone\n validates :source_zone, type: String\n\n # @return [String] The source IP address.\n attribute :source_ip\n validates :source_ip, presence: true, type: String\n\n # @return [Object, nil] The source port.\n attribute :source_port\n\n # @return [String, nil] The source user or group.\n attribute :source_user\n validates :source_user, type: String\n\n # @return [String, nil] The inbound interface in a NAT rule.\n attribute :to_interface\n validates :to_interface, type: String\n\n # @return [String, nil] The destination zone.\n attribute :destination_zone\n validates :destination_zone, type: String\n\n # @return [String, nil] The destination IP address.\n attribute :destination_ip\n validates :destination_ip, type: String\n\n # @return [String, nil] The destination port.\n attribute :destination_port\n validates :destination_port, type: String\n\n # @return [String, nil] The application.\n attribute :application\n validates :application, type: String\n\n # @return [String, nil] The IP protocol number from 1 to 255.\n attribute :protocol\n validates :protocol, type: String\n\n # @return [Object, nil] URL category\n attribute :category\n\n # @return [String] ID of the VSYS object.\n attribute :vsys_id\n validates :vsys_id, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5258718729019165, "alphanum_fraction": 0.5276954770088196, "avg_line_length": 31.257352828979492, "blob_id": "4605c85ebbfa38843e28f1b27b2007186e2eaea1", "content_id": "381917368d8c443402c8bd6a6b0e769314bfc5a5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4387, "license_type": "permissive", "max_line_length": 106, "num_lines": 136, "path": "/util/option_formatter.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# See LICENSE.txt for license\nmodule Ansible\n module Ruby\n module OptionFormatter\n BOOLEAN_OPTIONS = [true, false].freeze\n\n class << self\n def format(option_data)\n lines = []\n formatted_type = format_yard_return_types(option_data)\n flat_desc = option_data.description.join ','\n lines << \"# #{formatted_type} #{flat_desc}\"\n attribute_args = {}\n name = option_data.name\n attribute_args[:original_name] = \"'#{name}'\" if track_original_name?(name)\n flat_attr_args = attribute_args.map do |key, value|\n \"#{key}: #{value}\"\n end.join ', '\n symbol = symbolize_attribute(name)\n lines << \"attribute #{symbol}#{flat_attr_args.empty? ? '' : \", #{flat_attr_args}\"}\"\n lines << format_validations(option_data)\n lines.compact\n rescue StandardError\n $stderr << \"Problem formatting option #{name}!\"\n raise\n end\n\n private\n\n def track_original_name?(name)\n name.include? '-'\n end\n\n def symbolize_attribute(name)\n name.tr('-', '_').to_sym.inspect\n end\n\n def format_yard_return_types(option_data)\n types = if (choices = option_data.choices)\n if (BOOLEAN_OPTIONS - choices).empty?\n choices -= BOOLEAN_OPTIONS\n choices << 'Boolean'\n else\n choices\n end\n else\n option_data.types\n end.clone # no mutating\n # Want to at least show something\n types << Object if types.empty?\n types << nil unless option_data.required?\n formatted = types.map { |type| format_yard_type type }.join ', '\n \"@return [#{formatted}]\"\n end\n\n def format_yard_type(type)\n # we let user use an array or single value\n case type\n when TypeGeneric\n # Only using 1 of the generic/union-ish types right now\n klass_name = type.klasses[0].name\n \"Array<#{klass_name}>, #{klass_name}\"\n when Class\n type.name\n when Symbol\n type.inspect\n when NilClass\n 'nil'\n else\n type\n end\n end\n\n def format_validations(option_data)\n validations = {}\n required = option_data.required?\n types = option_data.types\n # keep code lighter if not required\n validations[:presence] = true if required\n generics = locate_generics types\n if (choices = option_data.choices)\n choices_validation validations, choices\n validations[:allow_nil] = true unless required\n else\n type = validation_type(generics, types)\n validations[:type] = type if type\n end\n\n return nil unless validations.any?\n\n symbol = symbolize_attribute(option_data.name)\n \"validates #{symbol}, #{validations.map { |key, value| \"#{key}: #{value}\" }.join(', ')}\"\n end\n\n def locate_generics(types)\n generics = types.select { |type| type.is_a?(TypeGeneric) }.uniq\n raise \"Only know how to deal with 1 generic type, found #{generics}\" unless generics.length <= 1\n\n generics\n end\n\n def choices_validation(validations, choices)\n validations[:expression_inclusion] = {\n in: choices,\n message: \"%{value} needs to be #{choices.map { |sym| sym.inspect.to_s }.join(', ')}\"\n }\n end\n\n def validation_type(generics, types)\n if generics.any?\n generic = generics[0]\n \"TypeGeneric.new(#{generic.klasses.map(&:name).join ', '})\"\n elsif types.length > 1\n \"MultipleTypes.new(#{types.map { |type| format_single_validation type }.join ', '})\"\n elsif types.length == 1\n format_single_validation types[0]\n end\n end\n\n def format_single_validation(type)\n case type\n when TypeGeneric\n \"TypeGeneric.new(#{type.klass.name})\"\n when String\n # Boolean for YARD\n type\n else\n type.name\n end\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5232876539230347, "alphanum_fraction": 0.5232876539230347, "avg_line_length": 20.47058868408203, "blob_id": "c2d09af38376461b9043860b882d0d422cdbb923", "content_id": "0e68c25692880b34b7535dc75e0a803a2e068d6d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 730, "license_type": "permissive", "max_line_length": 72, "num_lines": 34, "path": "/lib/ansible/ruby/dsl_builders/result.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nmodule Ansible\n module Ruby\n module DslBuilders\n class Result\n def initialize(name_fetcher)\n @name_fetcher = name_fetcher\n end\n\n # we need to respond to everything, don't want super\n def method_missing(id, *args)\n flat_args = args.map(&:inspect).map(&:to_s).join ', '\n \"#{name}.#{id}#{flat_args.empty? ? '' : \"(#{flat_args})\"}\"\n end\n\n def respond_to_missing?(*)\n true\n end\n\n def to_s\n name\n end\n\n private\n\n def name\n # Don't want to assign a name until we actually use a variable\n @name ||= @name_fetcher.call\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5961484909057617, "alphanum_fraction": 0.5964275598526001, "avg_line_length": 35.191917419433594, "blob_id": "54920e991d170d17887459162a3322c7c3ed30b2", "content_id": "911bebe9d77789b039bdc12d91162a5afe1697bd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3583, "license_type": "permissive", "max_line_length": 148, "num_lines": 99, "path": "/lib/ansible/ruby/models/task.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'ansible/ruby/models/unit'\nrequire 'ansible/ruby/models/inclusion'\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Models\n class Task < Unit\n attribute :name\n validates :name, presence: true, type: String\n attribute :module\n validates :module, type: Ansible::Ruby::Modules::Base\n attribute :block\n attribute :rescue\n attribute :always\n attribute :inclusion\n validates :inclusion, type: Inclusion\n validate :inclusion_module_block\n attribute :changed_when\n validates :changed_when, type: String\n attribute :failed_when\n validates :failed_when, type: String\n attribute :with_dict\n validates :with_dict, type: MultipleTypes.new(String, Hash)\n attribute :no_log\n validates :no_log, type: MultipleTypes.new(TrueClass, FalseClass)\n attribute :with_items\n validates :with_items, type: MultipleTypes.new(String, Array)\n validate :loop_and_dict\n attribute :notify\n validates :notify, type: TypeGeneric.new(String)\n attribute :async\n validates :async, type: Integer\n attribute :poll\n validates :poll, type: Integer\n attribute :connection\n validates :connection,\n allow_nil: true,\n inclusion: { in: %i[local docker ssh], message: '%{value} needs to be :local, :docker, or :ssh' }\n # :reek:Attribute - This is a simple flag\n attr_accessor :local_action\n attribute :delegate_to\n validates :delegate_to, type: String\n attribute :delegate_facts\n validates :delegate_facts, type: MultipleTypes.new(TrueClass, FalseClass)\n attribute :remote_user\n validates :remote_user, type: String\n\n def to_h\n result = super\n # Module gets referenced by name, may not have a module though\n mod_or_include = @inclusion ? :inclusion : :module\n flatten = result.delete(mod_or_include) || {}\n # Module traditionally goes right after name, so rebuilding hash\n new_result = {\n name: result.delete(:name)\n }\n if @local_action\n module_name = flatten.keys.first\n flatten = {\n local_action: {\n module: module_name.to_s\n }.merge(flatten[module_name])\n }\n end\n new_result.merge! flatten\n result.each do |key, value|\n new_result[key] = value\n end\n collapse_block = lambda do |which|\n new_result[which] = new_result[which][:block] if new_result[which]\n end\n # If we have a block at this level, get rid of the duplicate {block: block{}}, we'e reusing playbook blocks here\n collapse_block[:block]\n collapse_block[:rescue]\n collapse_block[:always]\n new_result\n end\n\n private\n\n # :reek:NilCheck - ^ doesn't work with falsey, you would have to overload the operator\n def inclusion_module_block\n options = [@inclusion, @module, @block].compact\n return if options.size == 1\n\n errors.add :module,\n \"You must either use an include or a module/block but not both! module: #{@module}, inclusion: #{@inclusion}, block: #{@block}\"\n end\n\n def loop_and_dict\n errors.add :with_items, 'Cannot use both with_items and with_dict!' if with_items && with_dict\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7134460210800171, "alphanum_fraction": 0.7134460210800171, "avg_line_length": 74.61111450195312, "blob_id": "0dcdb49e81c4030b4592568ceb1b14420d452db0", "content_id": "aa74392ebad8ec18a89bdaa0fcb32a3e62f89dfc", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2722, "license_type": "permissive", "max_line_length": 320, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/network/junos/junos_package.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can install new and updated packages on remote devices running Junos. The module will compare the specified package with the one running on the remote device and install the specified version if there is a mismatch\n class Junos_package < Base\n # @return [String] The I(src) argument specifies the path to the source package to be installed on the remote device in the advent of a version mismatch. The I(src) argument can be either a localized path or a full path to the package file to install.\n attribute :src\n validates :src, presence: true, type: String\n\n # @return [Object, nil] The I(version) argument can be used to explicitly specify the version of the package that should be installed on the remote device. If the I(version) argument is not specified, then the version is extracts from the I(src) filename.\n attribute :version\n\n # @return [:yes, :no] In order for a package to take effect, the remote device must be restarted. When enabled, this argument will instruct the module to reboot the device once the updated package has been installed. If disabled or the remote package does not need to be changed, the device will not be started.\n attribute :reboot\n validates :reboot, presence: true, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}\n\n # @return [:yes, :no, nil] The I(no_copy) argument is responsible for instructing the remote device on where to install the package from. When enabled, the package is transferred to the remote device prior to installing.\n attribute :no_copy\n validates :no_copy, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] The I(validate) argument is responsible for instructing the remote device to skip checking the current device configuration compatibility with the package being installed. When set to false validation is not performed.\n attribute :validate\n validates :validate, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no] The I(force) argument instructs the module to bypass the package version check and install the packaged identified in I(src) on the remote device.\n attribute :force\n validates :force, presence: true, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6961079835891724, "alphanum_fraction": 0.716550886631012, "avg_line_length": 70.31775665283203, "blob_id": "d6983e4415d42785bb54263197b5472a23c6b37c", "content_id": "26819293877c6096c8975c06873b0ff63175771f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 7631, "license_type": "permissive", "max_line_length": 653, "num_lines": 107, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_template.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Module to manage virtual machine templates in oVirt/RHV.\n class Ovirt_template < Base\n # @return [String, nil] Name of the template to manage.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] ID of the template to be registered.\n attribute :id\n validates :id, type: String\n\n # @return [:present, :absent, :exported, :imported, :registered, nil] Should the template be present/absent/exported/imported/registered. When C(state) is I(registered) and the unregistered template's name belongs to an already registered in engine template in the same DC then we fail to register the unregistered template.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :exported, :imported, :registered], :message=>\"%{value} needs to be :present, :absent, :exported, :imported, :registered\"}, allow_nil: true\n\n # @return [String, nil] Name of the VM, which will be used to create template.\n attribute :vm\n validates :vm, type: String\n\n # @return [String, nil] Description of the template.\n attribute :description\n validates :description, type: String\n\n # @return [String, nil] CPU profile to be set to template.\n attribute :cpu_profile\n validates :cpu_profile, type: String\n\n # @return [String, nil] Name of the cluster, where template should be created/imported.\n attribute :cluster\n validates :cluster, type: String\n\n # @return [Symbol, nil] Boolean indication whether to allow partial registration of a template when C(state) is registered.\n attribute :allow_partial_import\n validates :allow_partial_import, type: Symbol\n\n # @return [Array<Hash>, Hash, nil] Mapper which maps an external virtual NIC profile to one that exists in the engine when C(state) is registered. vnic_profile is described by the following dictionary:,C(source_network_name): The network name of the source network.,C(source_profile_name): The profile name related to the source network.,C(target_profile_id): The id of the target profile id to be mapped to in the engine.\n attribute :vnic_profile_mappings\n validates :vnic_profile_mappings, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash, nil] Mapper which maps cluster name between Template's OVF and the destination cluster this Template should be registered to, relevant when C(state) is registered. Cluster mapping is described by the following dictionary:,C(source_name): The name of the source cluster.,C(dest_name): The name of the destination cluster.\n attribute :cluster_mappings\n validates :cluster_mappings, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash, nil] Mapper which maps role name between Template's OVF and the destination role this Template should be registered to, relevant when C(state) is registered. Role mapping is described by the following dictionary:,C(source_name): The name of the source role.,C(dest_name): The name of the destination role.\n attribute :role_mappings\n validates :role_mappings, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash, nil] Mapper which maps aaa domain name between Template's OVF and the destination aaa domain this Template should be registered to, relevant when C(state) is registered. The aaa domain mapping is described by the following dictionary:,C(source_name): The name of the source aaa domain.,C(dest_name): The name of the destination aaa domain.\n attribute :domain_mappings\n validates :domain_mappings, type: TypeGeneric.new(Hash)\n\n # @return [Symbol, nil] When C(state) is I(exported) this parameter indicates if the existing templates with the same name should be overwritten.\n attribute :exclusive\n validates :exclusive, type: Symbol\n\n # @return [Object, nil] When C(state) is I(exported) or I(imported) this parameter specifies the name of the export storage domain.\n attribute :export_domain\n\n # @return [String, nil] When C(state) is I(imported) this parameter specifies the name of the image provider to be used.\n attribute :image_provider\n validates :image_provider, type: String\n\n # @return [String, nil] When C(state) is I(imported) and C(image_provider) is used this parameter specifies the name of disk to be imported as template.\n attribute :image_disk\n validates :image_disk, type: String\n\n # @return [Object, nil] Number of IO threads used by virtual machine. I(0) means IO threading disabled.\n attribute :io_threads\n\n # @return [String, nil] When C(state) is I(imported) and C(image_provider) is used this parameter specifies the new name for imported disk, if omitted then I(image_disk) name is used by default. This parameter is used only in case of importing disk image from Glance domain.\n attribute :template_image_disk_name\n validates :template_image_disk_name, type: String\n\n # @return [String, nil] When C(state) is I(imported) this parameter specifies the name of the destination data storage domain. When C(state) is I(registered) this parameter specifies the name of the data storage domain of the unregistered template.\n attribute :storage_domain\n validates :storage_domain, type: String\n\n # @return [Symbol, nil] If I(True) then the permissions of the VM (only the direct ones, not the inherited ones) will be copied to the created template.,This parameter is used only when C(state) I(present).\n attribute :clone_permissions\n validates :clone_permissions, type: Symbol\n\n # @return [Symbol, nil] 'Sealing' is an operation that erases all machine-specific configurations from a filesystem: This includes SSH keys, UDEV rules, MAC addresses, system ID, hostname, etc. If I(true) subsequent virtual machines made from this template will avoid configuration inheritance.,This parameter is used only when C(state) I(present).\n attribute :seal\n validates :seal, type: Symbol\n\n # @return [Object, nil] Operating system of the template.,Default value is set by oVirt/RHV engine.,Possible values are: debian_7, freebsd, freebsdx64, other, other_linux, other_linux_ppc64, other_ppc64, rhel_3, rhel_4, rhel_4x64, rhel_5, rhel_5x64, rhel_6, rhel_6x64, rhel_6_ppc64, rhel_7x64, rhel_7_ppc64, sles_11, sles_11_ppc64, ubuntu_12_04, ubuntu_12_10, ubuntu_13_04, ubuntu_13_10, ubuntu_14_04, ubuntu_14_04_ppc64, windows_10, windows_10x64, windows_2003, windows_2003x64, windows_2008, windows_2008x64, windows_2008r2x64, windows_2008R2x64, windows_2012x64, windows_2012R2x64, windows_7, windows_7x64, windows_8, windows_8x64, windows_xp\n attribute :operating_system\n\n # @return [Object, nil] Amount of memory of the template. Prefix uses IEC 60027-2 standard (for example 1GiB, 1024MiB).\n attribute :memory\n\n # @return [Object, nil] Amount of minimal guaranteed memory of the template. Prefix uses IEC 60027-2 standard (for example 1GiB, 1024MiB).,C(memory_guaranteed) parameter can't be lower than C(memory) parameter.\n attribute :memory_guaranteed\n\n # @return [Object, nil] Upper bound of template memory up to which memory hot-plug can be performed. Prefix uses IEC 60027-2 standard (for example 1GiB, 1024MiB).\n attribute :memory_max\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6480186581611633, "alphanum_fraction": 0.6561771631240845, "avg_line_length": 40.85365676879883, "blob_id": "b8facede131638f403d4e27ee960ee79784a1f61", "content_id": "c7789f8b9fce4d0304d7c8849d6efe51abe0869e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1716, "license_type": "permissive", "max_line_length": 190, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/network/ios/ios_logging.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of logging on Cisco Ios devices.\n class Ios_logging < Base\n # @return [:on, :host, :console, :monitor, :buffered, nil] Destination of the logs.\n attribute :dest\n validates :dest, expression_inclusion: {:in=>[:on, :host, :console, :monitor, :buffered], :message=>\"%{value} needs to be :on, :host, :console, :monitor, :buffered\"}, allow_nil: true\n\n # @return [String, nil] If value of C(dest) is I(file) it indicates file-name, for I(user) it indicates username and for I(host) indicates the host name to be notified.\n attribute :name\n validates :name, type: String\n\n # @return [Integer, nil] Size of buffer. The acceptable value is in range from 4096 to 4294967295 bytes.\n attribute :size\n validates :size, type: Integer\n\n # @return [String, nil] Set logging facility.\n attribute :facility\n validates :facility, type: String\n\n # @return [String, nil] Set logging severity levels.\n attribute :level\n validates :level, type: String\n\n # @return [Array<Hash>, Hash, nil] List of logging definitions.\n attribute :aggregate\n validates :aggregate, type: TypeGeneric.new(Hash)\n\n # @return [:present, :absent, nil] State of the logging configuration.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6910530924797058, "alphanum_fraction": 0.6910530924797058, "avg_line_length": 47.772727966308594, "blob_id": "34ea8e3ad2cea3ad85868cff563c77ead52f9384", "content_id": "baf37efbc8598ac33fd8d631b4a68c1e055a37bb", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2146, "license_type": "permissive", "max_line_length": 286, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/network/eos/eos_vrf.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of VRFs on Arista EOS network devices.\n class Eos_vrf < Base\n # @return [String] Name of the VRF.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Route distinguisher of the VRF\n attribute :rd\n validates :rd, type: String\n\n # @return [Array<String>, String, nil] Identifies the set of interfaces that should be configured in the VRF. Interfaces must be routed interfaces in order to be placed into a VRF. The name of interface should be in expanded format and not abbreviated.\n attribute :interfaces\n validates :interfaces, type: TypeGeneric.new(String)\n\n # @return [Object, nil] This is a intent option and checks the operational state of the for given vrf C(name) for associated interfaces. If the value in the C(associated_interfaces) does not match with the operational state of vrf interfaces on device it will result in failure.\n attribute :associated_interfaces\n\n # @return [Array<Hash>, Hash, nil] List of VRFs definitions\n attribute :aggregate\n validates :aggregate, type: TypeGeneric.new(Hash)\n\n # @return [Boolean, nil] Purge VRFs not defined in the I(aggregate) parameter.\n attribute :purge\n validates :purge, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Integer, nil] Time in seconds to wait before checking for the operational state on remote device. This wait is applicable for operational state arguments.\n attribute :delay\n validates :delay, type: Integer\n\n # @return [:present, :absent, nil] State of the VRF configuration.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6615384817123413, "alphanum_fraction": 0.6615384817123413, "avg_line_length": 41.25, "blob_id": "9185eb96b20d34081537444b2028e161c3eee249", "content_id": "28cb827d1e46ebb85e1bc302fcc65a8c8f35a49e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2535, "license_type": "permissive", "max_line_length": 185, "num_lines": 60, "path": "/lib/ansible/ruby/modules/generated/messaging/rabbitmq_exchange.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module uses rabbitMQ Rest API to create/delete exchanges\n class Rabbitmq_exchange < Base\n # @return [String] Name of the exchange to create\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Whether the exchange should be present or absent,Only present implemented atm\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] rabbitMQ user for connection\n attribute :login_user\n validates :login_user, type: String\n\n # @return [Boolean, nil] rabbitMQ password for connection\n attribute :login_password\n validates :login_password, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] rabbitMQ host for connection\n attribute :login_host\n validates :login_host, type: String\n\n # @return [Integer, nil] rabbitMQ management api port\n attribute :login_port\n validates :login_port, type: Integer\n\n # @return [String, nil] rabbitMQ virtual host\n attribute :vhost\n validates :vhost, type: String\n\n # @return [Boolean, nil] whether exchange is durable or not\n attribute :durable\n validates :durable, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:fanout, :direct, :headers, :topic, nil] type for the exchange\n attribute :exchange_type\n validates :exchange_type, expression_inclusion: {:in=>[:fanout, :direct, :headers, :topic], :message=>\"%{value} needs to be :fanout, :direct, :headers, :topic\"}, allow_nil: true\n\n # @return [Symbol, nil] if the exchange should delete itself after all queues/exchanges unbound from it\n attribute :auto_delete\n validates :auto_delete, type: Symbol\n\n # @return [Symbol, nil] exchange is available only for other exchanges\n attribute :internal\n validates :internal, type: Symbol\n\n # @return [Object, nil] extra arguments for exchange. If defined this argument is a key/value dictionary\n attribute :arguments\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7081151604652405, "alphanum_fraction": 0.7081151604652405, "avg_line_length": 35.380950927734375, "blob_id": "c8078e127a9cf87cdd317692f714e5213e156a75", "content_id": "a1dfd092f5aaa85c2f3febf152540f7580efc926", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 764, "license_type": "permissive", "max_line_length": 210, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/remote_management/oneview/oneview_ethernet_network_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Retrieve the facts about one or more of the Ethernet Networks from OneView.\n class Oneview_ethernet_network_facts < Base\n # @return [String, nil] Ethernet Network name.\n attribute :name\n validates :name, type: String\n\n # @return [Array<String>, String, nil] List with options to gather additional facts about an Ethernet Network and related resources. Options allowed: C(associatedProfiles) and C(associatedUplinkGroups).\n attribute :options\n validates :options, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6729248762130737, "alphanum_fraction": 0.6758893132209778, "avg_line_length": 39.47999954223633, "blob_id": "bc716f48f7bbc7374523f5653daf260e0ec8f788", "content_id": "20db53df55b0ba01ed53fe92a6fcb9a658c3caf5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1012, "license_type": "permissive", "max_line_length": 161, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/packaging/os/slackpkg.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage binary packages for Slackware using 'slackpkg' which is available in versions after 12.2.\n class Slackpkg < Base\n # @return [Array<String>, String] name of package to install/remove\n attribute :name\n validates :name, presence: true, type: TypeGeneric.new(String)\n\n # @return [:present, :absent, :latest, nil] state of the package, you can use \"installed\" as an alias for C(present) and removed as one for C(absent).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :latest], :message=>\"%{value} needs to be :present, :absent, :latest\"}, allow_nil: true\n\n # @return [Symbol, nil] update the package database first\n attribute :update_cache\n validates :update_cache, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6828283071517944, "alphanum_fraction": 0.6828283071517944, "avg_line_length": 35.66666793823242, "blob_id": "5dd00243ac85c2ee86561d3fc5a662d27accfca8", "content_id": "dc537877e622f2967f9a577ab17ba117bc850f8a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 990, "license_type": "permissive", "max_line_length": 163, "num_lines": 27, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_permissions_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Retrieve facts about one or more oVirt/RHV permissions.\n class Ovirt_permission_facts < Base\n # @return [String, nil] Username of the user to manage. In most LDAPs it's I(uid) of the user, but in Active Directory you must specify I(UPN) of the user.\n attribute :user_name\n validates :user_name, type: String\n\n # @return [Object, nil] Name of the group to manage.\n attribute :group_name\n\n # @return [String] Authorization provider of the user/group. In previous versions of oVirt/RHV known as domain.\n attribute :authz_name\n validates :authz_name, presence: true, type: String\n\n # @return [Object, nil] Namespace of the authorization provider, where user/group resides.\n attribute :namespace\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6908397078514099, "alphanum_fraction": 0.6957470178604126, "avg_line_length": 49.94444274902344, "blob_id": "7b7382cb71d3c0cde42443b2655260ecb02c295d", "content_id": "8419b24b6d545779924caa2ddf0d56d09e7f03b0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1834, "license_type": "permissive", "max_line_length": 335, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/s3_website.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configure an s3 bucket as a website\n class S3_website < Base\n # @return [String] Name of the s3 bucket\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The object key name to use when a 4XX class error occurs. To remove an error key, set to None.\n attribute :error_key\n validates :error_key, type: String\n\n # @return [String, nil] Describes the redirect behavior for every request to this s3 bucket website endpoint\n attribute :redirect_all_requests\n validates :redirect_all_requests, type: String\n\n # @return [Object, nil] AWS region to create the bucket in. If not set then the value of the AWS_REGION and EC2_REGION environment variables are checked, followed by the aws_region and ec2_region settings in the Boto config file. If none of those are set the region defaults to the S3 Location: US Standard.\\r\\n\n attribute :region\n\n # @return [:present, :absent, nil] Add or remove s3 website configuration\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Suffix that is appended to a request that is for a directory on the website endpoint (e.g. if the suffix is index.html and you make a request to samplebucket/images/ the data that is returned will be for the object with the key name images/index.html). The suffix must not include a slash character.\\r\\n\n attribute :suffix\n validates :suffix, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6548430919647217, "alphanum_fraction": 0.6582537293434143, "avg_line_length": 35.650001525878906, "blob_id": "0c0784e5a99f45f9b779b1db3fc606ffb641be66", "content_id": "3fa4fae1671503f5e74c2d03f145724c3aca1697", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1466, "license_type": "permissive", "max_line_length": 143, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/network/slxos/slxos_vlan.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of VLANs on Extreme SLX-OS network devices.\n class Slxos_vlan < Base\n # @return [String, nil] Name of the VLAN.\n attribute :name\n validates :name, type: String\n\n # @return [Integer] ID of the VLAN. Range 1-4094.\n attribute :vlan_id\n validates :vlan_id, presence: true, type: Integer\n\n # @return [Array<String>, String] List of interfaces that should be associated to the VLAN.\n attribute :interfaces\n validates :interfaces, presence: true, type: TypeGeneric.new(String)\n\n # @return [Integer, nil] Delay the play should wait to check for declarative intent params values.\n attribute :delay\n validates :delay, type: Integer\n\n # @return [Object, nil] List of VLANs definitions.\n attribute :aggregate\n\n # @return [Symbol, nil] Purge VLANs not defined in the I(aggregate) parameter.\n attribute :purge\n validates :purge, type: Symbol\n\n # @return [:present, :absent, nil] State of the VLAN configuration.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6691604256629944, "alphanum_fraction": 0.6691604256629944, "avg_line_length": 36.59375, "blob_id": "26ab290dbdf7dbd0c153221a8a9a6bc7148f02ce", "content_id": "e0771489dfccc15834e05e6ae1218ba2a230abc0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1203, "license_type": "permissive", "max_line_length": 143, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/windows/win_iis_webapplication.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates, removes, and configures IIS web applications.\n class Win_iis_webapplication < Base\n # @return [String] Name of the web application.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] Name of the site on which the application is created.\n attribute :site\n validates :site, presence: true, type: String\n\n # @return [:absent, :present, nil] State of the web application.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] The physical path on the remote host to use for the new application.,The specified folder must already exist.\n attribute :physical_path\n validates :physical_path, type: String\n\n # @return [Object, nil] The application pool in which the new site executes.\n attribute :application_pool\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.661512017250061, "alphanum_fraction": 0.661512017250061, "avg_line_length": 37.79999923706055, "blob_id": "76a12e211a08da61866759b77c88f959f2ecd894", "content_id": "c152f664f74a785c6675c37fb644ad0f45b8b155", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1746, "license_type": "permissive", "max_line_length": 146, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vsphere_copy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Upload files to a vCenter datastore\n class Vsphere_copy < Base\n # @return [String] The vCenter server on which the datastore is available.\n attribute :host\n validates :host, presence: true, type: String\n\n # @return [String] The login name to authenticate on the vCenter server.\n attribute :login\n validates :login, presence: true, type: String\n\n # @return [String] The password to authenticate on the vCenter server.\n attribute :password\n validates :password, presence: true, type: String\n\n # @return [String] The file to push to vCenter\n attribute :src\n validates :src, presence: true, type: String\n\n # @return [String] The datacenter on the vCenter server that holds the datastore.\n attribute :datacenter\n validates :datacenter, presence: true, type: String\n\n # @return [String] The datastore on the vCenter server to push files to.\n attribute :datastore\n validates :datastore, presence: true, type: String\n\n # @return [String] The file to push to the datastore on the vCenter server.\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated. This should only be set to C(no) when no other option exists.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6600630283355713, "alphanum_fraction": 0.6767221689224243, "avg_line_length": 55.9487190246582, "blob_id": "ced18cd46c89ad4703b5ee1d4ba24c43ff5eed82", "content_id": "7c53c479c0528709725772b8d363200165d31923", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2221, "license_type": "permissive", "max_line_length": 347, "num_lines": 39, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_device_sshd.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage the SSHD settings of a BIG-IP.\n class Bigip_device_sshd < Base\n # @return [Object, nil] Specifies, if you have enabled SSH access, the IP address or address range for other systems that can use SSH to communicate with this system.,To specify all addresses, use the value C(all).,IP address can be specified, such as 172.27.1.10.,IP rangees can be specified, such as 172.27.*.* or 172.27.0.0/255.255.0.0.\n attribute :allow\n\n # @return [:enabled, :disabled, nil] Whether to enable the banner or not.\n attribute :banner\n validates :banner, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [String, nil] Specifies the text to include on the pre-login banner that displays when a user attempts to login to the system using SSH.\n attribute :banner_text\n validates :banner_text, type: String\n\n # @return [Object, nil] Specifies the number of seconds before inactivity causes an SSH session to log out.\n attribute :inactivity_timeout\n\n # @return [:debug, :debug1, :debug2, :debug3, :error, :fatal, :info, :quiet, :verbose, nil] Specifies the minimum SSHD message level to include in the system log.\n attribute :log_level\n validates :log_level, expression_inclusion: {:in=>[:debug, :debug1, :debug2, :debug3, :error, :fatal, :info, :quiet, :verbose], :message=>\"%{value} needs to be :debug, :debug1, :debug2, :debug3, :error, :fatal, :info, :quiet, :verbose\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] Specifies, when checked C(enabled), that the system accepts SSH communications.\n attribute :login\n validates :login, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [Integer, nil] Port that you want the SSH daemon to run on.\n attribute :port\n validates :port, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6963793635368347, "alphanum_fraction": 0.7026761174201965, "avg_line_length": 56.75, "blob_id": "939e99cb572b7af06fc885729106acc28cf9ea0c", "content_id": "834d2b1c58d52fdfabab3cb79ff46194a0d27544", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5082, "license_type": "permissive", "max_line_length": 410, "num_lines": 88, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_healthmonitor.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure HealthMonitor object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_healthmonitor < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Object, nil] User defined description for the object.\n attribute :description\n\n # @return [Object, nil] Healthmonitordns settings for healthmonitor.\n attribute :dns_monitor\n\n # @return [Object, nil] Healthmonitorexternal settings for healthmonitor.\n attribute :external_monitor\n\n # @return [Integer, nil] Number of continuous failed health checks before the server is marked down.,Allowed values are 1-50.,Default value when not specified in API or module is interpreted by Avi Controller as 2.\n attribute :failed_checks\n validates :failed_checks, type: Integer\n\n # @return [Object, nil] Healthmonitorhttp settings for healthmonitor.\n attribute :http_monitor\n\n # @return [Hash, nil] Healthmonitorhttp settings for healthmonitor.\n attribute :https_monitor\n validates :https_monitor, type: Hash\n\n # @return [Symbol, nil] This field describes the object's replication scope.,If the field is set to false, then the object is visible within the controller-cluster and its associated service-engines.,If the field is set to true, then the object is replicated across the federation.,Field introduced in 17.1.3.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :is_federated\n validates :is_federated, type: Symbol\n\n # @return [Object, nil] Use this port instead of the port defined for the server in the pool.,If the monitor succeeds to this port, the load balanced traffic will still be sent to the port of the server defined within the pool.,Allowed values are 1-65535.,Special values are 0 - 'use server port'.\n attribute :monitor_port\n\n # @return [String] A user friendly name for this health monitor.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Integer, nil] A valid response from the server is expected within the receive timeout window.,This timeout must be less than the send interval.,If server status is regularly flapping up and down, consider increasing this value.,Allowed values are 1-2400.,Default value when not specified in API or module is interpreted by Avi Controller as 4.,Units(SEC).\n attribute :receive_timeout\n validates :receive_timeout, type: Integer\n\n # @return [Integer, nil] Frequency, in seconds, that monitors are sent to a server.,Allowed values are 1-3600.,Default value when not specified in API or module is interpreted by Avi Controller as 10.,Units(SEC).\n attribute :send_interval\n validates :send_interval, type: Integer\n\n # @return [Integer, nil] Number of continuous successful health checks before server is marked up.,Allowed values are 1-50.,Default value when not specified in API or module is interpreted by Avi Controller as 2.\n attribute :successful_checks\n validates :successful_checks, type: Integer\n\n # @return [Object, nil] Healthmonitortcp settings for healthmonitor.\n attribute :tcp_monitor\n\n # @return [Object, nil] It is a reference to an object of type tenant.\n attribute :tenant_ref\n\n # @return [String] Type of the health monitor.,Enum options - HEALTH_MONITOR_PING, HEALTH_MONITOR_TCP, HEALTH_MONITOR_HTTP, HEALTH_MONITOR_HTTPS, HEALTH_MONITOR_EXTERNAL, HEALTH_MONITOR_UDP,,HEALTH_MONITOR_DNS, HEALTH_MONITOR_GSLB.\n attribute :type\n validates :type, presence: true, type: String\n\n # @return [Object, nil] Healthmonitorudp settings for healthmonitor.\n attribute :udp_monitor\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Uuid of the health monitor.\n attribute :uuid\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6534552574157715, "alphanum_fraction": 0.6534552574157715, "avg_line_length": 32.931034088134766, "blob_id": "078304a9d82cf6b9fcf2a1a56df760f4920c0095", "content_id": "6355ff0892be2833b930403ebb7ca2783bf4fde0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 984, "license_type": "permissive", "max_line_length": 143, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/storage/infinidat/infini_host.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module creates, deletes or modifies hosts on Infinibox.\n class Infini_host < Base\n # @return [String] Host Name\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Creates/Modifies Host when present or removes when absent\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] List of wwns of the host\n attribute :wwns\n validates :wwns, type: TypeGeneric.new(String)\n\n # @return [String, nil] Volume name to map to the host\n attribute :volume\n validates :volume, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6434699892997742, "alphanum_fraction": 0.6434699892997742, "avg_line_length": 35.17241287231445, "blob_id": "baea244a94702322f1b54981fca883cdd2874181", "content_id": "7afc66d473ad4a59a17c579add4f4bc6c0a58161", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1049, "license_type": "permissive", "max_line_length": 143, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/messaging/rabbitmq_vhost.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage the state of a virtual host in RabbitMQ\n class Rabbitmq_vhost < Base\n # @return [String] The name of the vhost to manage\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] erlang node name of the rabbit we wish to configure\n attribute :node\n validates :node, type: String\n\n # @return [:yes, :no, nil] Enable/disable tracing for a vhost\n attribute :tracing\n validates :tracing, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, nil] The state of vhost\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6661828756332397, "alphanum_fraction": 0.6748911738395691, "avg_line_length": 49.414634704589844, "blob_id": "3f2776b2d00f042e26ec54a7f28d56c472289297", "content_id": "058042d63b40cf81940a6558c187a5ee7b23b2b2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2067, "license_type": "permissive", "max_line_length": 160, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_aaa_server.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages AAA server global configuration\n class Nxos_aaa_server < Base\n # @return [:radius, :tacacs] The server type is either radius or tacacs.\n attribute :server_type\n validates :server_type, presence: true, expression_inclusion: {:in=>[:radius, :tacacs], :message=>\"%{value} needs to be :radius, :tacacs\"}\n\n # @return [String, nil] Global AAA shared secret or keyword 'default'.\n attribute :global_key\n validates :global_key, type: String\n\n # @return [0, 7, nil] The state of encryption applied to the entered global key. O clear text, 7 encrypted. Type-6 encryption is not supported.\n attribute :encrypt_type\n validates :encrypt_type, expression_inclusion: {:in=>[0, 7], :message=>\"%{value} needs to be 0, 7\"}, allow_nil: true\n\n # @return [Integer, nil] Duration for which a non-reachable AAA server is skipped, in minutes or keyword 'default. Range is 1-1440. Device default is 0.\n attribute :deadtime\n validates :deadtime, type: Integer\n\n # @return [Integer, nil] Global AAA server timeout period, in seconds or keyword 'default. Range is 1-60. Device default is 5.\n attribute :server_timeout\n validates :server_timeout, type: Integer\n\n # @return [:enabled, :disabled, nil] Enables direct authentication requests to AAA server or keyword 'default' Device default is disabled.\n attribute :directed_request\n validates :directed_request, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:present, :default, nil] Manage the state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :default], :message=>\"%{value} needs to be :present, :default\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6377068758010864, "alphanum_fraction": 0.63947993516922, "avg_line_length": 36.599998474121094, "blob_id": "f5465f623e55c1810e110a1a8747280af79f2780", "content_id": "f8543766b1d36fdc33c469bb7235d6f1c389ed97", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1692, "license_type": "permissive", "max_line_length": 162, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/messaging/rabbitmq_policy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage the state of a policy in RabbitMQ.\n class Rabbitmq_policy < Base\n # @return [String] The name of the policy to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The name of the vhost to apply to.\n attribute :vhost\n validates :vhost, type: String\n\n # @return [:all, :exchanges, :queues, nil] What the policy applies to. Requires RabbitMQ 3.2.0 or later.\n attribute :apply_to\n validates :apply_to, expression_inclusion: {:in=>[:all, :exchanges, :queues], :message=>\"%{value} needs to be :all, :exchanges, :queues\"}, allow_nil: true\n\n # @return [String] A regex of queues to apply the policy to.\n attribute :pattern\n validates :pattern, presence: true, type: String\n\n # @return [Hash] A dict or string describing the policy.\n attribute :tags\n validates :tags, presence: true, type: Hash\n\n # @return [Integer, nil] The priority of the policy.\n attribute :priority\n validates :priority, type: Integer\n\n # @return [String, nil] Erlang node name of the rabbit we wish to configure.\n attribute :node\n validates :node, type: String\n\n # @return [:present, :absent, nil] The state of the policy.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6719675660133362, "alphanum_fraction": 0.6719675660133362, "avg_line_length": 54.2931022644043, "blob_id": "9846b8d65a6bf8fa388bbabae0c0943e6e1cc8e3", "content_id": "1faf0591c429adc56d25581649f3b7a012b6e768", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3207, "license_type": "permissive", "max_line_length": 203, "num_lines": 58, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_managed_disk.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and delete an Azure Managed Disk\n class Azure_rm_managed_disk < Base\n # @return [String] Name of a resource group where the managed disk exists or will be created.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] Name of the managed disk.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, nil] Assert the state of the managed disk. Use C(present) to create or update a managed disk and 'absent' to delete a managed disk.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] Valid Azure location. Defaults to location of the resource group.\n attribute :location\n validates :location, type: String\n\n # @return [:Standard_LRS, :Premium_LRS, nil] Type of storage for the managed disk: C(Standard_LRS) or C(Premium_LRS). If not specified the disk is created C(Standard_LRS).\n attribute :storage_account_type\n validates :storage_account_type, expression_inclusion: {:in=>[:Standard_LRS, :Premium_LRS], :message=>\"%{value} needs to be :Standard_LRS, :Premium_LRS\"}, allow_nil: true\n\n # @return [:empty, :import, :copy, nil] Allowed values: empty, import, copy. C(import) from a VHD file in I(source_uri) and C(copy) from previous managed disk I(source_resource_uri).\n attribute :create_option\n validates :create_option, expression_inclusion: {:in=>[:empty, :import, :copy], :message=>\"%{value} needs to be :empty, :import, :copy\"}, allow_nil: true\n\n # @return [Object, nil] URI to a valid VHD file to be used when I(create_option) is C(import).\n attribute :source_uri\n\n # @return [Object, nil] The resource ID of the managed disk to copy when I(create_option) is C(copy).\n attribute :source_resource_uri\n\n # @return [:linux, :windows, nil] Type of Operating System: C(linux) or C(windows). Used when I(create_option) is either C(copy) or C(import) and the source is an OS disk.\n attribute :os_type\n validates :os_type, expression_inclusion: {:in=>[:linux, :windows], :message=>\"%{value} needs to be :linux, :windows\"}, allow_nil: true\n\n # @return [Integer, nil] Size in GB of the managed disk to be created. If I(create_option) is C(copy) then the value must be greater than or equal to the source's size.\n attribute :disk_size_gb\n validates :disk_size_gb, type: Integer\n\n # @return [String, nil] Name of an existing virtual machine with which the disk is or will be associated, this VM should be in the same resource group.,To detach a disk from a vm, keep undefined.\n attribute :managed_by\n validates :managed_by, type: String\n\n # @return [Object, nil] Tags to assign to the managed disk.\n attribute :tags\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7043478488922119, "alphanum_fraction": 0.7057970762252808, "avg_line_length": 39.588233947753906, "blob_id": "ebf4fc8c33a1f464d6abd34213ffe3b66da030dc", "content_id": "779a20f5d4c6a793b45fda713e098150ea844f42", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 690, "license_type": "permissive", "max_line_length": 255, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/cloud/smartos/smartos_image_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Retrieve facts about all installed images on SmartOS. Facts will be inserted to the ansible_facts key.\n class Smartos_image_facts < Base\n # @return [String, nil] Criteria for selecting image. Can be any value from image manifest and 'published_date', 'published', 'source', 'clones', and 'size'. More informaton can be found at U(https://smartos.org/man/1m/imgadm) under 'imgadm list'.\n attribute :filters\n validates :filters, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6559013724327087, "alphanum_fraction": 0.6559013724327087, "avg_line_length": 45.02702713012695, "blob_id": "4face4f4f51dce2bf47c2d0fefac3301b57f3a78", "content_id": "e057d13ab6b249b5a2cf8f78d9c118ef626064bd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1703, "license_type": "permissive", "max_line_length": 170, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/system/at.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Use this module to schedule a command or script file to run once in the future.\n # All jobs are executed in the 'a' queue.\n class At < Base\n # @return [String, nil] A command to be executed in the future.\n attribute :command\n validates :command, type: String\n\n # @return [Object, nil] An existing script file to be executed in the future.\n attribute :script_file\n\n # @return [Integer] The count of units in the future to execute the command or script file.\n attribute :count\n validates :count, presence: true, type: Integer\n\n # @return [:minutes, :hours, :days, :weeks] The type of units in the future to execute the command or script file.\n attribute :units\n validates :units, presence: true, expression_inclusion: {:in=>[:minutes, :hours, :days, :weeks], :message=>\"%{value} needs to be :minutes, :hours, :days, :weeks\"}\n\n # @return [:absent, :present, nil] The state dictates if the command or script file should be evaluated as present(added) or absent(deleted).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If a matching job is present a new job will not be added.\n attribute :unique\n validates :unique, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6769869327545166, "alphanum_fraction": 0.6769869327545166, "avg_line_length": 47.953125, "blob_id": "41e821228a3241916eb0ede4ee16a80c7d9132c0", "content_id": "8347f9ee28256f47dc07b8f8914fca4bd377788d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3133, "license_type": "permissive", "max_line_length": 235, "num_lines": 64, "path": "/lib/ansible/ruby/modules/generated/identity/cyberark/cyberark_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # CyberArk User Management using PAS Web Services SDK. It currently supports the following actions Get User Details, Add User, Update User, Delete User.\n class Cyberark_user < Base\n # @return [String] The name of the user who will be queried (for details), added, updated or deleted.\n attribute :username\n validates :username, presence: true, type: String\n\n # @return [:present, :absent, nil] Specifies the state needed for the user present for create user, absent for delete user.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] Dictionary set by a CyberArk authentication containing the different values to perform actions on a logged-on CyberArk session, please see M(cyberark_authentication) module for an example of cyberark_session.\n attribute :cyberark_session\n validates :cyberark_session, presence: true, type: String\n\n # @return [String, nil] The password that the new user will use to log on the first time. This password must meet the password policy requirements. this parameter is required when state is present -- Add User.\n attribute :initial_password\n validates :initial_password, type: String\n\n # @return [String, nil] The user updated password. Make sure that this password meets the password policy requirements.\n attribute :new_password\n validates :new_password, type: String\n\n # @return [Object, nil] The user email address.\n attribute :email\n\n # @return [Object, nil] The user first name.\n attribute :first_name\n\n # @return [Object, nil] The user last name.\n attribute :last_name\n\n # @return [:yes, :no, nil] Whether or not the user must change their password in their next logon. Valid values = true/false.\n attribute :change_password_on_the_next_logon\n validates :change_password_on_the_next_logon, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] The date and time when the user account will expire and become disabled.\n attribute :expiry_date\n\n # @return [String, nil] The type of user.\n attribute :user_type_name\n validates :user_type_name, type: String\n\n # @return [:yes, :no, nil] Whether or not the user will be disabled. Valid values = true/false.\n attribute :disabled\n validates :disabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] The Vault Location for the user.\n attribute :location\n\n # @return [String, nil] The name of the group the user will be added to.\n attribute :group_name\n validates :group_name, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7024999856948853, "alphanum_fraction": 0.7085000276565552, "avg_line_length": 53.054054260253906, "blob_id": "0ecee6447af3dfb283b94e7d44bb09d416a9b330", "content_id": "504a151b850d830b5b73f1120871ca1736779f87", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2000, "license_type": "permissive", "max_line_length": 294, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/netapp_e_auditlog.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows an e-series storage system owner to set audit-log configuration parameters.\n class Netapp_e_auditlog < Base\n # @return [Integer, nil] The maximum number log messages audit-log will retain.,Max records must be between and including 100 and 50000.\n attribute :max_records\n validates :max_records, type: Integer\n\n # @return [:all, :writeOnly, nil] Filters the log messages according to the specified log level selection.\n attribute :log_level\n validates :log_level, expression_inclusion: {:in=>[:all, :writeOnly], :message=>\"%{value} needs to be :all, :writeOnly\"}, allow_nil: true\n\n # @return [:overWrite, :preventSystemAccess, nil] Specifies what audit-log should do once the number of entries approach the record limit.\n attribute :full_policy\n validates :full_policy, expression_inclusion: {:in=>[:overWrite, :preventSystemAccess], :message=>\"%{value} needs to be :overWrite, :preventSystemAccess\"}, allow_nil: true\n\n # @return [Integer, nil] This is the memory full percent threshold that audit-log will start issuing warning messages.,Percent range must be between and including 60 and 90.\n attribute :threshold\n validates :threshold, type: Integer\n\n # @return [Symbol, nil] Forces the audit-log configuration to delete log history when log messages fullness cause immediate warning or full condition.,Warning! This will cause any existing audit-log messages to be deleted.,This is only applicable for I(full_policy=preventSystemAccess).\n attribute :force\n validates :force, type: Symbol\n\n # @return [String, nil] A local path to a file to be used for debug logging.\n attribute :log_path\n validates :log_path, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7768147587776184, "alphanum_fraction": 0.7789815664291382, "avg_line_length": 60.53333282470703, "blob_id": "2de3a074d9bfe427ec1fa444f1ace9428ada20e2", "content_id": "038f79e74725903cd8918f4a0112bc5923be3dd8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 923, "license_type": "permissive", "max_line_length": 673, "num_lines": 15, "path": "/lib/ansible/ruby/modules/generated/network/cnos/cnos_showrun.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows you to view the switch running configuration. It executes the display running-config CLI command on a switch and returns a file containing the current running configuration of the target network device. This module uses SSH to manage network device configuration. The results of the operation will be placed in a directory named 'results' that must be created by the user in their local directory to where the playbook is run. For more information about this module from Lenovo and customizing it usage for your use cases, please visit U(http://systemx.lenovofiles.com/help/index.jsp?topic=%2Fcom.lenovo.switchmgt.ansible.doc%2Fcnos_showrun.html)\n class Cnos_showrun < Base\n\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6938169002532959, "alphanum_fraction": 0.6950059533119202, "avg_line_length": 58.01754379272461, "blob_id": "ce782f46f7d45ef331690b834ce541221ee5c56c", "content_id": "6576593a5a8fa30ae63e026e3e519635ba258e51", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3364, "license_type": "permissive", "max_line_length": 416, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/windows/win_wait_for.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # You can wait for a set amount of time C(timeout), this is the default if nothing is specified.\n # Waiting for a port to become available is useful for when services are not immediately available after their init scripts return which is true of certain Java application servers.\n # You can wait for a file to exist or not exist on the filesystem.\n # This module can also be used to wait for a regex match string to be present in a file.\n # You can wait for active connections to be closed before continuing on a local port.\n class Win_wait_for < Base\n # @return [Integer, nil] The maximum number of seconds to wait for a connection to happen before closing and retrying.\n attribute :connect_timeout\n validates :connect_timeout, type: Integer\n\n # @return [Integer, nil] The number of seconds to wait before starting to poll.\n attribute :delay\n validates :delay, type: Integer\n\n # @return [Array<String>, String, nil] The list of hosts or IPs to ignore when looking for active TCP connections when C(state=drained).\n attribute :exclude_hosts\n validates :exclude_hosts, type: TypeGeneric.new(String)\n\n # @return [String, nil] A resolvable hostname or IP address to wait for.,If C(state=drained) then it will only check for connections on the IP specified, you can use '0.0.0.0' to use all host IPs.\n attribute :host\n validates :host, type: String\n\n # @return [String, nil] The path to a file on the filesystem to check.,If C(state) is present or started then it will wait until the file exists.,If C(state) is absent then it will wait until the file does not exist.\n attribute :path\n validates :path, type: String\n\n # @return [Integer, nil] The port number to poll on C(host).\n attribute :port\n validates :port, type: Integer\n\n # @return [String, nil] Can be used to match a string in a file.,If C(state) is present or started then it will wait until the regex matches.,If C(state) is absent then it will wait until the regex does not match.,Defaults to a multiline regex.\n attribute :search_regex\n validates :search_regex, type: String\n\n # @return [Integer, nil] Number of seconds to sleep between checks.\n attribute :sleep\n validates :sleep, type: Integer\n\n # @return [:absent, :drained, :present, :started, :stopped, nil] When checking a port, C(started) will ensure the port is open, C(stopped) will check that is it closed and C(drained) will check for active connections.,When checking for a file or a search string C(present) or C(started) will ensure that the file or string is present, C(absent) will check that the file or search string is absent or removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :drained, :present, :started, :stopped], :message=>\"%{value} needs to be :absent, :drained, :present, :started, :stopped\"}, allow_nil: true\n\n # @return [Integer, nil] The maximum number of seconds to wait for.\n attribute :timeout\n validates :timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6614497303962708, "alphanum_fraction": 0.6614497303962708, "avg_line_length": 35.787879943847656, "blob_id": "51965a85710342b437f196a1678202d4658ad01c", "content_id": "1bf382ad2a140b2deceee858cd66cffc477b3a62", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1214, "license_type": "permissive", "max_line_length": 143, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/network/onyx/onyx_bgp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of BGP router and neighbors on Mellanox ONYX network devices.\n class Onyx_bgp < Base\n # @return [Integer] Local AS number.\n attribute :as_number\n validates :as_number, presence: true, type: Integer\n\n # @return [String, nil] Router IP address. Required if I(state=present).\n attribute :router_id\n validates :router_id, type: String\n\n # @return [Array<Hash>, Hash, nil] List of neighbors. Required if I(state=present).\n attribute :neighbors\n validates :neighbors, type: TypeGeneric.new(Hash)\n\n # @return [Array<String>, String, nil] List of advertised networks.\n attribute :networks\n validates :networks, type: TypeGeneric.new(String)\n\n # @return [:present, :absent, nil] BGP state.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7228959202766418, "alphanum_fraction": 0.7247058749198914, "avg_line_length": 70.75325012207031, "blob_id": "9d268649f94944436f0ca13ea4824df1ed1a0f1f", "content_id": "98139e28fbdc7b144204e29b2e6f86ab9b4e342c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5525, "license_type": "permissive", "max_line_length": 526, "num_lines": 77, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_batch_job_definition.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows the management of AWS Batch Job Definitions. It is idempotent and supports \"Check\" mode. Use module M(aws_batch_compute_environment) to manage the compute environment, M(aws_batch_job_queue) to manage job queues, M(aws_batch_job_definition) to manage job definitions.\n class Aws_batch_job_definition < Base\n # @return [Object, nil] The arn for the job definition\n attribute :job_definition_arn\n\n # @return [String] The name for the job definition\n attribute :job_definition_name\n validates :job_definition_name, presence: true, type: String\n\n # @return [:present, :absent] Describes the desired state.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String] The type of job definition\n attribute :type\n validates :type, presence: true, type: String\n\n # @return [Hash, nil] Default parameter substitution placeholders to set in the job definition. Parameters are specified as a key-value pair mapping. Parameters in a SubmitJob request override any corresponding parameter defaults from the job definition.\n attribute :parameters\n validates :parameters, type: Hash\n\n # @return [String, nil] The image used to start a container. This string is passed directly to the Docker daemon. Images in the Docker Hub registry are available by default. Other repositories are specified with `` repository-url /image <colon>tag ``. Up to 255 letters (uppercase and lowercase), numbers, hyphens, underscores, colons, periods, forward slashes, and number signs are allowed. This parameter maps to Image in the Create a container section of the Docker Remote API and the IMAGE parameter of docker run.\n attribute :image\n validates :image, type: String\n\n # @return [Integer, nil] The number of vCPUs reserved for the container. This parameter maps to CpuShares in the Create a container section of the Docker Remote API and the --cpu-shares option to docker run. Each vCPU is equivalent to 1,024 CPU shares.\n attribute :vcpus\n validates :vcpus, type: Integer\n\n # @return [Integer, nil] The hard limit (in MiB) of memory to present to the container. If your container attempts to exceed the memory specified here, the container is killed. This parameter maps to Memory in the Create a container section of the Docker Remote API and the --memory option to docker run.\n attribute :memory\n validates :memory, type: Integer\n\n # @return [Array<String>, String, nil] The command that is passed to the container. This parameter maps to Cmd in the Create a container section of the Docker Remote API and the COMMAND parameter to docker run. For more information, see https://docs.docker.com/engine/reference/builder/#cmd.\n attribute :command\n validates :command, type: TypeGeneric.new(String)\n\n # @return [String, nil] The Amazon Resource Name (ARN) of the IAM role that the container can assume for AWS permissions.\n attribute :job_role_arn\n validates :job_role_arn, type: String\n\n # @return [Object, nil] A list of data volumes used in a job. List of dictionaries.\n attribute :volumes\n\n # @return [Object, nil] The environment variables to pass to a container. This parameter maps to Env in the Create a container section of the Docker Remote API and the --env option to docker run. List of dictionaries.\n attribute :environment\n\n # @return [Object, nil] The mount points for data volumes in your container. This parameter maps to Volumes in the Create a container section of the Docker Remote API and the --volume option to docker run. List of dictionaries.\n attribute :mount_points\n\n # @return [Object, nil] When this parameter is true, the container is given read-only access to its root file system. This parameter maps to ReadonlyRootfs in the Create a container section of the Docker Remote API and the --read-only option to docker run.\n attribute :readonly_root_filesystem\n\n # @return [Object, nil] When this parameter is true, the container is given elevated privileges on the host container instance (similar to the root user). This parameter maps to Privileged in the Create a container section of the Docker Remote API and the --privileged option to docker run.\n attribute :privileged\n\n # @return [Object, nil] A list of ulimits to set in the container. This parameter maps to Ulimits in the Create a container section of the Docker Remote API and the --ulimit option to docker run. List of dictionaries.\n attribute :ulimits\n\n # @return [Object, nil] The user name to use inside the container. This parameter maps to User in the Create a container section of the Docker Remote API and the --user option to docker run.\n attribute :user\n\n # @return [Integer, nil] Retry strategy - The number of times to move a job to the RUNNABLE status. You may specify between 1 and 10 attempts. If attempts is greater than one, the job is retried if it fails until it has moved to RUNNABLE that many times.\n attribute :attempts\n validates :attempts, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.52913498878479, "alphanum_fraction": 0.52913498878479, "avg_line_length": 23.891891479492188, "blob_id": "57ea6b883d3dec895875b638ad78692423201826", "content_id": "fc9d98862e33d8abde3539f12e326cba3e44f46f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2763, "license_type": "permissive", "max_line_length": 178, "num_lines": 111, "path": "/lib/ansible/ruby/dsl_builders/play.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'ansible/ruby/models/play'\nrequire 'ansible/ruby/dsl_builders/tasks'\nrequire 'ansible/ruby/dsl_builders/block'\n\nmodule Ansible\n module Ruby\n module DslBuilders\n class Play < Tasks\n def initialize(name = nil)\n super :tasks\n @play_args = {}\n @play_args[:name] = name if name\n end\n\n def hosts(value)\n @play_args[:hosts] = value\n end\n\n def vars(value)\n @play_args[:vars] = value\n end\n\n def no_log(value)\n @play_args[:no_log] = value\n end\n\n def roles(value)\n @play_args[:roles] = value\n end\n\n def tags(*value)\n @play_args[:tags] = [*value]\n end\n\n def role(name,\n optional_stuff = {})\n roles = @play_args[:roles] ||= []\n tag = optional_stuff[:tag] || optional_stuff[:tags]\n our_role_result = { role: name }\n our_role_result[:tags] = [*tag] if tag\n ansible_when = optional_stuff[:when]\n our_role_result[:when] = ansible_when if ansible_when\n roles << our_role_result\n end\n\n def connection(value)\n @play_args[:connection] = value\n end\n\n def user(value)\n @play_args[:user] = value\n end\n\n def serial(value)\n @play_args[:serial] = value\n end\n\n def gather_facts(value)\n @play_args[:gather_facts] = value\n end\n\n def become(*args)\n value = _implicit_bool args\n @play_args[:become] = value\n end\n\n def become_user(value)\n @play_args[:become_user] = value\n end\n\n def ignore_errors(*args)\n value = _implicit_bool args\n @play_args[:ignore_errors] = value\n end\n\n def local_host\n hosts 'localhost'\n connection :local\n end\n\n def block(&block)\n builder = Block.new\n builder.instance_eval(&block)\n @task_builders << builder\n end\n\n # allow any order\n def _result\n tasks = super\n raise 'Includes cannot be used in a play using a role. They can only be used in task files or in plays with a task list.' if tasks.inclusions.any? && @play_args[:roles]\n\n args = @play_args.merge({})\n # Don't want to trigger validation\n args[:tasks] = tasks if tasks.items.any?\n Models::Play.new args\n end\n\n private\n\n def _process_method(id, *args, &block)\n return super if respond_to_missing?(id, *args, &block)\n\n valid = _valid_attributes << :task\n no_method_error id, \"Only valid options are #{valid}\"\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7264583110809326, "alphanum_fraction": 0.7300000190734863, "avg_line_length": 79, "blob_id": "f30929944e765b0cedbe18244e823d7402e11099", "content_id": "1069e9fd3f4c8427b0270c334dda46437511f018", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4800, "license_type": "permissive", "max_line_length": 568, "num_lines": 60, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_gtm_monitor_tcp_half_open.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages F5 BIG-IP GTM tcp half-open monitors.\n class Bigip_gtm_monitor_tcp_half_open < Base\n # @return [String] Monitor name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The parent template of this monitor template. Once this value has been set, it cannot be changed. By default, this value is the C(tcp_half_open) parent on the C(Common) partition.\n attribute :parent\n validates :parent, type: String\n\n # @return [String, nil] IP address part of the IP/port definition. If this parameter is not provided when creating a new monitor, then the default value will be '*'.\n attribute :ip\n validates :ip, type: String\n\n # @return [Integer, nil] Port address part of the IP/port definition. If this parameter is not provided when creating a new monitor, then the default value will be '*'. Note that if specifying an IP address, a value between 1 and 65535 must be specified\n attribute :port\n validates :port, type: Integer\n\n # @return [Object, nil] Specifies, in seconds, the frequency at which the system issues the monitor check when either the resource is down or the status of the resource is unknown.,When creating a new monitor, if this parameter is not provided, then the default value will be C(30). This value B(must) be less than the C(timeout) value.\n attribute :interval\n\n # @return [Object, nil] Specifies the number of seconds the target has in which to respond to the monitor request.,If the target responds within the set time period, it is considered up.,If the target does not respond within the set time period, it is considered down.,When this value is set to 0 (zero), the system uses the interval from the parent monitor.,When creating a new monitor, if this parameter is not provided, then the default value will be C(120).\n attribute :timeout\n\n # @return [Object, nil] Specifies the number of seconds the big3d process waits before sending out a subsequent probe attempt when a probe fails and multiple probe attempts have been requested.,When creating a new monitor, if this parameter is not provided, then the default value will be C(1).\n attribute :probe_interval\n\n # @return [Object, nil] Specifies the number of seconds after which the system times out the probe request to the system.,When creating a new monitor, if this parameter is not provided, then the default value will be C(5).\n attribute :probe_timeout\n\n # @return [Object, nil] Specifies the number of times the system attempts to probe the host server, after which the system considers the host server down or unavailable.,When creating a new monitor, if this parameter is not provided, then the default value will be C(3).\n attribute :probe_attempts\n\n # @return [Symbol, nil] Specifies that the monitor allows more than one probe attempt per interval.,When C(yes), specifies that the monitor ignores down responses for the duration of the monitor timeout. Once the monitor timeout is reached without the system receiving an up response, the system marks the object down.,When C(no), specifies that the monitor immediately marks an object down when it receives a down response.,When creating a new monitor, if this parameter is not provided, then the default value will be C(no).\n attribute :ignore_down_response\n validates :ignore_down_response, type: Symbol\n\n # @return [Symbol, nil] Specifies whether the monitor operates in transparent mode.,A monitor in transparent mode directs traffic through the associated pool members or nodes (usually a router or firewall) to the aliased destination (that is, it probes the C(ip)-C(port) combination specified in the monitor).,If the monitor cannot successfully reach the aliased destination, the pool member or node through which the monitor traffic was sent is marked down.,When creating a new monitor, if this parameter is not provided, then the default value will be C(no).\n attribute :transparent\n validates :transparent, type: Symbol\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [:present, :absent, nil] When C(present), ensures that the monitor exists.,When C(absent), ensures the monitor is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7020974159240723, "alphanum_fraction": 0.7028083801269531, "avg_line_length": 57.60416793823242, "blob_id": "7f83509bf44ad8e6187bcb824651581e37de6afb", "content_id": "cab7b407a5c3e158d0db6e6d70d85e36867bde14", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2813, "license_type": "permissive", "max_line_length": 485, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/iam_role.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage AWS IAM roles\n class Iam_role < Base\n # @return [String, nil] The path to the role. For more information about paths, see U(http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html).\n attribute :path\n validates :path, type: String\n\n # @return [String] The name of the role to create.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Provide a description of the new role\n attribute :description\n validates :description, type: String\n\n # @return [Object, nil] Add the ARN of an IAM managed policy to restrict the permissions this role can pass on to IAM roles/users that it creates.,Boundaries cannot be set on Instance Profiles, so if this option is specified then C(create_instance_profile) must be false.,This is intended for roles/users that have permissions to create new IAM objects.,For more information on boundaries, see U(https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html)\n attribute :boundary\n\n # @return [String, nil] The trust relationship policy document that grants an entity permission to assume the role.,This parameter is required when C(state=present).\n attribute :assume_role_policy_document\n validates :assume_role_policy_document, type: String\n\n # @return [Array<String>, String, nil] A list of managed policy ARNs or, since Ansible 2.4, a list of either managed policy ARNs or friendly names. To embed an inline policy, use M(iam_policy). To remove existing policies, use an empty list item.\n attribute :managed_policy\n validates :managed_policy, type: TypeGeneric.new(String, NilClass)\n\n # @return [Boolean, nil] Detaches any managed policies not listed in the \"managed_policy\" option. Set to false if you want to attach policies elsewhere.\n attribute :purge_policies\n validates :purge_policies, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Create or remove the IAM role\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Boolean, nil] Creates an IAM instance profile along with the role\n attribute :create_instance_profile\n validates :create_instance_profile, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6656728982925415, "alphanum_fraction": 0.6675233840942383, "avg_line_length": 46.916255950927734, "blob_id": "633183d2530e35bf1645ad1bfb1199ee18c2deae", "content_id": "fbe3363df0043e50952935939c9aa3d2327c1aa7", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 9727, "license_type": "permissive", "max_line_length": 443, "num_lines": 203, "path": "/lib/ansible/ruby/modules/generated/cloud/smartos/vmadm.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage SmartOS virtual machines through vmadm(1M).\n class Vmadm < Base\n # @return [Object, nil] When enabled, the zone dataset will be mounted on C(/zones/archive) upon removal.\n attribute :archive_on_delete\n\n # @return [Object, nil] Whether or not a VM is booted when the system is rebooted.\n attribute :autoboot\n\n # @return [:joyent, :\"joyent-minimal\", :kvm, :lx] Type of virtual machine.\n attribute :brand\n validates :brand, presence: true, expression_inclusion: {:in=>[:joyent, :\"joyent-minimal\", :kvm, :lx], :message=>\"%{value} needs to be :joyent, :\\\"joyent-minimal\\\", :kvm, :lx\"}\n\n # @return [Object, nil] Set the boot order for KVM VMs.\n attribute :boot\n\n # @return [Object, nil] Sets a limit on the amount of CPU time that can be used by a VM. Use C(0) for no cap.\n attribute :cpu_cap\n\n # @return [Object, nil] Sets a limit on the number of fair share scheduler (FSS) CPU shares for a VM. This limit is relative to all other VMs on the system.\n attribute :cpu_shares\n\n # @return [:qemu64, :host, nil] Control the type of virtual CPU exposed to KVM VMs.\n attribute :cpu_type\n validates :cpu_type, expression_inclusion: {:in=>[:qemu64, :host], :message=>\"%{value} needs to be :qemu64, :host\"}, allow_nil: true\n\n # @return [Object, nil] Metadata to be set and associated with this VM, this contain customer modifiable keys.\n attribute :customer_metadata\n\n # @return [Object, nil] Whether to delegate a ZFS dataset to an OS VM.\n attribute :delegate_dataset\n\n # @return [Object, nil] Default value for a virtual disk model for KVM guests.\n attribute :disk_driver\n\n # @return [Object, nil] A list of disks to add, valid properties are documented in vmadm(1M).\n attribute :disks\n\n # @return [Object, nil] Domain value for C(/etc/hosts).\n attribute :dns_domain\n\n # @return [Object, nil] Docker images need this flag enabled along with the I(brand) set to C(lx).\n attribute :docker\n\n # @return [Object, nil] Mount additional filesystems into an OS VM.\n attribute :filesystems\n\n # @return [Boolean, nil] Enables the firewall, allowing fwadm(1M) rules to be applied.\n attribute :firewall_enabled\n validates :firewall_enabled, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] Force a particular action (i.e. stop or delete a VM).\n attribute :force\n\n # @return [Object, nil] Comma separated list of filesystem types this zone is allowed to mount.\n attribute :fs_allowed\n\n # @return [Object, nil] Zone/VM hostname.\n attribute :hostname\n\n # @return [String, nil] Image UUID.\n attribute :image_uuid\n validates :image_uuid, type: String\n\n # @return [Object, nil] Adds an C(@indestructible) snapshot to delegated datasets.\n attribute :indestructible_delegated\n\n # @return [Boolean, nil] Adds an C(@indestructible) snapshot to zoneroot.\n attribute :indestructible_zoneroot\n validates :indestructible_zoneroot, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Hash, nil] Metadata to be set and associated with this VM, this contains operator generated keys.\n attribute :internal_metadata\n validates :internal_metadata, type: Hash\n\n # @return [Object, nil] List of namespaces to be set as I(internal_metadata-only); these namespaces will come from I(internal_metadata) rather than I(customer_metadata).\n attribute :internal_metadata_namespace\n\n # @return [Object, nil] Kernel version to emulate for LX VMs.\n attribute :kernel_version\n\n # @return [Object, nil] Set (comma separated) list of privileges the zone is allowed to use.\n attribute :limit_priv\n\n # @return [Object, nil] Resolvers in C(/etc/resolv.conf) will be updated when updating the I(resolvers) property.\n attribute :maintain_resolvers\n\n # @return [Object, nil] Total amount of memory (in MiBs) on the host that can be locked by this VM.\n attribute :max_locked_memory\n\n # @return [Object, nil] Maximum number of lightweight processes this VM is allowed to have running.\n attribute :max_lwps\n\n # @return [Object, nil] Maximum amount of memory (in MiBs) on the host that the VM is allowed to use.\n attribute :max_physical_memory\n\n # @return [Object, nil] Maximum amount of virtual memory (in MiBs) the VM is allowed to use.\n attribute :max_swap\n\n # @return [Object, nil] Timeout in seconds (or 0 to disable) for the C(svc:/smartdc/mdata:execute) service that runs user-scripts in the zone.\n attribute :mdata_exec_timeout\n\n # @return [Object, nil] Name of the VM. vmadm(1M) uses this as an optional name.\n attribute :name\n\n # @return [Object, nil] Default value for a virtual NIC model for KVM guests.\n attribute :nic_driver\n\n # @return [Array<Hash>, Hash, nil] A list of nics to add, valid properties are documented in vmadm(1M).\n attribute :nics\n validates :nics, type: TypeGeneric.new(Hash)\n\n # @return [Object, nil] Consider the provisioning complete when the VM first starts, rather than when the VM has rebooted.\n attribute :nowait\n\n # @return [Object, nil] Additional qemu arguments for KVM guests. This overwrites the default arguments provided by vmadm(1M) and should only be used for debugging.\n attribute :qemu_opts\n\n # @return [Object, nil] Additional qemu cmdline arguments for KVM guests.\n attribute :qemu_extra_opts\n\n # @return [Integer, nil] Quota on zone filesystems (in MiBs).\n attribute :quota\n validates :quota, type: Integer\n\n # @return [Object, nil] Amount of virtual RAM for a KVM guest (in MiBs).\n attribute :ram\n\n # @return [Object, nil] List of resolvers to be put into C(/etc/resolv.conf).\n attribute :resolvers\n\n # @return [Object, nil] Dictionary that maps destinations to gateways, these will be set as static routes in the VM.\n attribute :routes\n\n # @return [Object, nil] Addition options for SPICE-enabled KVM VMs.\n attribute :spice_opts\n\n # @return [Object, nil] Password required to connect to SPICE. By default no password is set. Please note this can be read from the Global Zone.\n attribute :spice_password\n\n # @return [:present, :absent, :stopped, :restarted] States for the VM to be in. Please note that C(present), C(stopped) and C(restarted) operate on a VM that is currently provisioned. C(present) means that the VM will be created if it was absent, and that it will be in a running state. C(absent) will shutdown the zone before removing it. C(stopped) means the zone will be created if it doesn't exist already, before shutting it down.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent, :stopped, :restarted], :message=>\"%{value} needs to be :present, :absent, :stopped, :restarted\"}\n\n # @return [Object, nil] Amount of memory (in MiBs) that will be available in the VM for the C(/tmp) filesystem.\n attribute :tmpfs\n\n # @return [String, nil] UUID of the VM. Can either be a full UUID or C(*) for all VMs.\n attribute :uuid\n validates :uuid, type: String\n\n # @return [Object, nil] Number of virtual CPUs for a KVM guest.\n attribute :vcpus\n\n # @return [Object, nil] Specify VGA emulation used by KVM VMs.\n attribute :vga\n\n # @return [Object, nil] Number of packets that can be sent in a single flush of the tx queue of virtio NICs.\n attribute :virtio_txburst\n\n # @return [Object, nil] Timeout (in nanoseconds) for the TX timer of virtio NICs.\n attribute :virtio_txtimer\n\n # @return [Object, nil] Password required to connect to VNC. By default no password is set. Please note this can be read from the Global Zone.\n attribute :vnc_password\n\n # @return [Object, nil] TCP port to listen of the VNC server. Or set C(0) for random, or C(-1) to disable.\n attribute :vnc_port\n\n # @return [Object, nil] Specifies compression algorithm used for this VMs data dataset. This option only has effect on delegated datasets.\n attribute :zfs_data_compression\n\n # @return [Object, nil] Suggested block size (power of 2) for files in the delegated dataset's filesystem.\n attribute :zfs_data_recsize\n\n # @return [Object, nil] Maximum number of filesystems the VM can have.\n attribute :zfs_filesystem_limit\n\n # @return [Object, nil] IO throttle priority value relative to other VMs.\n attribute :zfs_io_priority\n\n # @return [Object, nil] Specifies compression algorithm used for this VMs root dataset. This option only has effect on the zoneroot dataset.\n attribute :zfs_root_compression\n\n # @return [Object, nil] Suggested block size (power of 2) for files in the zoneroot dataset's filesystem.\n attribute :zfs_root_recsize\n\n # @return [Object, nil] Number of snapshots the VM can have.\n attribute :zfs_snapshot_limit\n\n # @return [Object, nil] ZFS pool the VM's zone dataset will be created in.\n attribute :zpool\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6625880599021912, "alphanum_fraction": 0.6722283959388733, "avg_line_length": 40.4923095703125, "blob_id": "ac50e2f5504b7ee0f0774178a00e7b054d22bcb7", "content_id": "9807ce8b9ab6f04b7fa9cdab33ee7ea69a685fe3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2697, "license_type": "permissive", "max_line_length": 239, "num_lines": 65, "path": "/lib/ansible/ruby/modules/generated/identity/ipa/ipa_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add, modify and delete user within IPA server\n class Ipa_user < Base\n # @return [Object, nil] Display name\n attribute :displayname\n\n # @return [String, nil] First name\n attribute :givenname\n validates :givenname, type: String\n\n # @return [Integer, nil] Date at which the user password will expire,In the format YYYYMMddHHmmss,e.g. 20180121182022 will expire on 21 January 2018 at 18:20:22\n attribute :krbpasswordexpiration\n validates :krbpasswordexpiration, type: Integer\n\n # @return [Object, nil] Login shell\n attribute :loginshell\n\n # @return [Array<String>, String, nil] List of mail addresses assigned to the user.,If an empty list is passed all assigned email addresses will be deleted.,If None is passed email addresses will not be checked or changed.\n attribute :mail\n validates :mail, type: TypeGeneric.new(String)\n\n # @return [Object, nil] Password for new user\n attribute :password\n\n # @return [String, nil] Surname\n attribute :sn\n validates :sn, type: String\n\n # @return [Array<String>, String, nil] List of public SSH key.,If an empty list is passed all assigned public keys will be deleted.,If None is passed SSH public keys will not be checked or changed.\n attribute :sshpubkey\n validates :sshpubkey, type: TypeGeneric.new(String)\n\n # @return [:present, :absent, :enabled, :disabled, nil] State to ensure\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :enabled, :disabled], :message=>\"%{value} needs to be :present, :absent, :enabled, :disabled\"}, allow_nil: true\n\n # @return [Array<Integer>, Integer, nil] List of telephone numbers assigned to the user.,If an empty list is passed all assigned telephone numbers will be deleted.,If None is passed telephone numbers will not be checked or changed.\n attribute :telephonenumber\n validates :telephonenumber, type: TypeGeneric.new(Integer)\n\n # @return [Object, nil] Title\n attribute :title\n\n # @return [Object] uid of the user\n attribute :uid\n validates :uid, presence: true\n\n # @return [Integer, nil] Account Settings UID/Posix User ID number\n attribute :uidnumber\n validates :uidnumber, type: Integer\n\n # @return [Integer, nil] Posix Group ID\n attribute :gidnumber\n validates :gidnumber, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5875826478004456, "alphanum_fraction": 0.6008026599884033, "avg_line_length": 25.148147583007812, "blob_id": "4f6b82a891c0b60d5cb479ff4a8554061ae7c804", "content_id": "6b6311c159a178b77b57e8066d73732f36537edd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4236, "license_type": "permissive", "max_line_length": 116, "num_lines": 162, "path": "/lib/ansible/ruby/models/type_validator_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# See LICENSE.txt for license\nrequire 'spec_helper'\nrequire 'ansible/ruby/models/base'\n\ndescribe TypeValidator do\n before { stub_const 'Ansible::Ruby::TypeValTestModel', klass }\n\n subject { instance }\n\n let(:klass) do\n Class.new(Ansible::Ruby::Models::Base) do\n attribute :foo\n validates :foo, presence: true, allow_nil: true, type: Integer\n attribute :bar\n validates :bar, type: TypeGeneric.new(Float)\n attribute :toodles\n validates :toodles, presence: true, type: TypeGeneric.new(Float)\n end\n end\n\n context 'attribute present' do\n let(:instance) { klass.new foo: 'howdy', toodles: 40.4 }\n\n it { is_expected.to_not be_valid }\n it { is_expected.to have_errors foo: 'Attribute foo expected to be a Integer but was a String' }\n end\n\n context 'Jinja expression' do\n let(:instance) { klass.new foo: Ansible::Ruby::Models::JinjaExpression.new('howdy'), toodles: 40.4 }\n\n it { is_expected.to be_valid }\n end\n\n context 'multiple' do\n let(:klass) do\n Class.new(Ansible::Ruby::Models::Base) do\n attribute :foo\n validates :foo, presence: true, allow_nil: true, type: MultipleTypes.new(Float, Integer)\n end\n end\n\n let(:instance) { klass.new foo: foo_value }\n\n context 'passes' do\n [45.44, 33].each do |value|\n context value.class do\n let(:foo_value) { value }\n\n it { is_expected.to be_valid }\n end\n end\n end\n\n context 'fails' do\n let(:foo_value) { 'howdy' }\n\n it { is_expected.to_not be_valid }\n it { is_expected.to have_errors foo: 'Attribute foo expected to be one of [Float, Integer] but was a String' }\n end\n end\n\n context 'bar attribute not present' do\n let(:instance) { klass.new foo: 123, toodles: 40.4 }\n\n it { is_expected.to be_valid }\n end\n\n context 'nil value' do\n let(:instance) { klass.new foo: nil, toodles: 40.4 }\n\n it { is_expected.to be_valid }\n end\n\n context 'original name was not attr friendly' do\n let(:klass) do\n Class.new(Ansible::Ruby::Models::Base) do\n attribute :foo_bar, original_name: 'foo-bar'\n end\n end\n\n let(:instance) { klass.new foo_bar: 'howdy' }\n\n it { is_expected.to be_valid }\n it { is_expected.to have_hash 'foo-bar' => 'howdy' }\n end\n\n context 'generic type' do\n context 'single value' do\n context 'correct type' do\n let(:instance) { klass.new foo: nil, bar: 45.44, toodles: 40.4 }\n\n it { is_expected.to be_valid }\n end\n\n context 'incorrect type' do\n let(:instance) { klass.new foo: nil, bar: 'howdy', toodles: 40.4 }\n\n it { is_expected.to_not be_valid }\n end\n\n context 'nil' do\n let(:instance) { klass.new foo: nil, bar: nil, toodles: 40.4 }\n\n it { is_expected.to be_valid }\n end\n\n context 'nil not allowed' do\n let(:instance) { klass.new foo: nil, bar: nil, toodles: nil }\n\n it { is_expected.to_not be_valid }\n it { is_expected.to have_errors toodles: \"can't be blank\" }\n end\n end\n\n context 'mult value' do\n context 'correct type' do\n let(:instance) { klass.new foo: nil, bar: [45.44], toodles: 40.4 }\n\n it { is_expected.to be_valid }\n end\n\n context 'empty array' do\n let(:instance) { klass.new foo: nil, bar: [], toodles: 40.4 }\n\n it { is_expected.to be_valid }\n end\n\n context 'incorrect type' do\n let(:instance) { klass.new foo: nil, bar: ['howdy'], toodles: 40.4 }\n\n it { is_expected.to_not be_valid }\n end\n end\n end\n\n context 'custom message' do\n let(:klass) do\n Class.new(Ansible::Ruby::Models::Base) do\n attribute :foo\n validates :foo, type: {\n type: String,\n message: 'stuff (%{value}), %{value} is expected to be a String but was a %{type}'\n }\n end\n end\n\n context 'invalid' do\n let(:instance) { klass.new foo: 123 }\n\n it { is_expected.to_not be_valid }\n it { is_expected.to have_errors foo: 'stuff (123), 123 is expected to be a String but was a Integer' }\n end\n\n context 'valid' do\n let(:instance) { klass.new foo: 'abc' }\n\n it { is_expected.to be_valid }\n end\n end\nend\n" }, { "alpha_fraction": 0.7001304030418396, "alphanum_fraction": 0.7001304030418396, "avg_line_length": 64.74285888671875, "blob_id": "ac031e947d6e326a4377edf2f861858e70d70207", "content_id": "1694b267056b39094001f153e496adebd9e44b7b", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2301, "license_type": "permissive", "max_line_length": 316, "num_lines": 35, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_host_service_manager.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to manage (start, stop, restart) services on a given ESXi host.\n # If cluster_name is provided, specified service will be managed on all ESXi host belonging to that cluster.\n # If specific esxi_hostname is provided, then specified service will be managed on given ESXi host only.\n class Vmware_host_service_manager < Base\n # @return [String, nil] Name of the cluster.,Service settings are applied to every ESXi host system/s in given cluster.,If C(esxi_hostname) is not given, this parameter is required.\n attribute :cluster_name\n validates :cluster_name, type: String\n\n # @return [String, nil] ESXi hostname.,Service settings are applied to this ESXi host system.,If C(cluster_name) is not given, this parameter is required.\n attribute :esxi_hostname\n validates :esxi_hostname, type: String\n\n # @return [:absent, :present, :restart, :start, :stop, nil] Desired state of service.,State value 'start' and 'present' has same effect.,State value 'stop' and 'absent' has same effect.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :restart, :start, :stop], :message=>\"%{value} needs to be :absent, :present, :restart, :start, :stop\"}, allow_nil: true\n\n # @return [:automatic, :off, :on, nil] Set of valid service policy strings.,If set C(on), then service should be started when the host starts up.,If set C(automatic), then service should run if and only if it has open firewall ports.,If set C(off), then Service should not be started when the host starts up.\n attribute :service_policy\n validates :service_policy, expression_inclusion: {:in=>[:automatic, :off, :on], :message=>\"%{value} needs to be :automatic, :off, :on\"}, allow_nil: true\n\n # @return [String] Name of Service to be managed. This is brief identifier for the service, for example, ntpd, vxsyslogd etc.,This value should be a valid ESXi service name.\n attribute :service_name\n validates :service_name, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6591084003448486, "alphanum_fraction": 0.6591084003448486, "avg_line_length": 41.655738830566406, "blob_id": "3159886b8c32c5a39aa47ef3bb5777b7d59a8950", "content_id": "bdc0572da6e4a87a5077d9d8b4e7e2e6c2a063ef", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2602, "license_type": "permissive", "max_line_length": 172, "num_lines": 61, "path": "/lib/ansible/ruby/modules/generated/notification/flowdock.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Send a message to a flowdock team inbox or chat using the push API (see https://www.flowdock.com/api/team-inbox and https://www.flowdock.com/api/chat)\n class Flowdock < Base\n # @return [String] API token.\n attribute :token\n validates :token, presence: true, type: String\n\n # @return [:inbox, :chat] Whether to post to 'inbox' or 'chat'\n attribute :type\n validates :type, presence: true, expression_inclusion: {:in=>[:inbox, :chat], :message=>\"%{value} needs to be :inbox, :chat\"}\n\n # @return [String] Content of the message\n attribute :msg\n validates :msg, presence: true, type: String\n\n # @return [Array<String>, String, nil] tags of the message, separated by commas\n attribute :tags\n validates :tags, type: TypeGeneric.new(String)\n\n # @return [String, nil] (chat only - required) Name of the \"user\" sending the message\n attribute :external_user_name\n validates :external_user_name, type: String\n\n # @return [String, nil] (inbox only - required) Email address of the message sender\n attribute :from_address\n validates :from_address, type: String\n\n # @return [String, nil] (inbox only - required) Human readable identifier of the application that uses the Flowdock API\n attribute :source\n validates :source, type: String\n\n # @return [String, nil] (inbox only - required) Subject line of the message\n attribute :subject\n validates :subject, type: String\n\n # @return [Object, nil] (inbox only) Name of the message sender\n attribute :from_name\n\n # @return [Object, nil] (inbox only) Email address for replies\n attribute :reply_to\n\n # @return [Object, nil] (inbox only) Human readable identifier for more detailed message categorization\n attribute :project\n\n # @return [Object, nil] (inbox only) Link associated with the message. This will be used to link the message subject in Team Inbox.\n attribute :link\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.68825763463974, "alphanum_fraction": 0.6903391480445862, "avg_line_length": 59.05147171020508, "blob_id": "11f7e984db4abd1682412afbc16bde29c4b441d9", "content_id": "281ca7661110b4a8944ad758fe02b4e1925bb97d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 8167, "license_type": "permissive", "max_line_length": 372, "num_lines": 136, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_bgp_neighbor_af.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages BGP address-family's neighbors configurations on NX-OS switches.\n class Nxos_bgp_neighbor_af < Base\n # @return [Integer] BGP autonomous system number. Valid values are String, Integer in ASPLAIN or ASDOT notation.\n attribute :asn\n validates :asn, presence: true, type: Integer\n\n # @return [String, nil] Name of the VRF. The name 'default' is a valid VRF representing the global bgp.\n attribute :vrf\n validates :vrf, type: String\n\n # @return [String] Neighbor Identifier. Valid values are string. Neighbors may use IPv4 or IPv6 notation, with or without prefix length.\n attribute :neighbor\n validates :neighbor, presence: true, type: String\n\n # @return [:ipv4, :ipv6, :vpnv4, :vpnv6, :l2vpn] Address Family Identifier.\n attribute :afi\n validates :afi, presence: true, expression_inclusion: {:in=>[:ipv4, :ipv6, :vpnv4, :vpnv6, :l2vpn], :message=>\"%{value} needs to be :ipv4, :ipv6, :vpnv4, :vpnv6, :l2vpn\"}\n\n # @return [:unicast, :multicast, :evpn] Sub Address Family Identifier.\n attribute :safi\n validates :safi, presence: true, expression_inclusion: {:in=>[:unicast, :multicast, :evpn], :message=>\"%{value} needs to be :unicast, :multicast, :evpn\"}\n\n # @return [:enable, :disable, :inherit, nil] Valid values are enable for basic command enablement; disable for disabling the command at the neighbor af level (it adds the disable keyword to the basic command); and inherit to remove the command at this level (the command value is inherited from a higher BGP layer).\n attribute :additional_paths_receive\n validates :additional_paths_receive, expression_inclusion: {:in=>[:enable, :disable, :inherit], :message=>\"%{value} needs to be :enable, :disable, :inherit\"}, allow_nil: true\n\n # @return [:enable, :disable, :inherit, nil] Valid values are enable for basic command enablement; disable for disabling the command at the neighbor af level (it adds the disable keyword to the basic command); and inherit to remove the command at this level (the command value is inherited from a higher BGP layer).\n attribute :additional_paths_send\n validates :additional_paths_send, expression_inclusion: {:in=>[:enable, :disable, :inherit], :message=>\"%{value} needs to be :enable, :disable, :inherit\"}, allow_nil: true\n\n # @return [Object, nil] Conditional route advertisement. This property requires two route maps, an advertise-map and an exist-map. Valid values are an array specifying both the advertise-map name and the exist-map name, or simply 'default' e.g. ['my_advertise_map', 'my_exist_map']. This command is mutually exclusive with the advertise_map_non_exist property.\n attribute :advertise_map_exist\n\n # @return [Object, nil] Conditional route advertisement. This property requires two route maps, an advertise-map and an exist-map. Valid values are an array specifying both the advertise-map name and the non-exist-map name, or simply 'default' e.g. ['my_advertise_map', 'my_non_exist_map']. This command is mutually exclusive with the advertise_map_exist property.\n attribute :advertise_map_non_exist\n\n # @return [Object, nil] Activate allowas-in property\n attribute :allowas_in\n\n # @return [Object, nil] Max-occurrences value for allowas_in. Valid values are an integer value or 'default'. This is mutually exclusive with allowas_in.\n attribute :allowas_in_max\n\n # @return [Symbol, nil] Activate the as-override feature.\n attribute :as_override\n validates :as_override, type: Symbol\n\n # @return [Symbol, nil] Activate the default-originate feature.\n attribute :default_originate\n validates :default_originate, type: Symbol\n\n # @return [Object, nil] Route-map for the default_originate property. Valid values are a string defining a route-map name, or 'default'. This is mutually exclusive with default_originate.\n attribute :default_originate_route_map\n\n # @return [Symbol, nil] Disable checking of peer AS-number while advertising\n attribute :disable_peer_as_check\n validates :disable_peer_as_check, type: Symbol\n\n # @return [Object, nil] Valid values are a string defining a filter-list name, or 'default'.\n attribute :filter_list_in\n\n # @return [Object, nil] Valid values are a string defining a filter-list name, or 'default'.\n attribute :filter_list_out\n\n # @return [Object, nil] maximum-prefix limit value. Valid values are an integer value or 'default'.\n attribute :max_prefix_limit\n\n # @return [Object, nil] Optional restart interval. Valid values are an integer. Requires max_prefix_limit. May not be combined with max_prefix_warning.\n attribute :max_prefix_interval\n\n # @return [Object, nil] Optional threshold percentage at which to generate a warning. Valid values are an integer value. Requires max_prefix_limit.\n attribute :max_prefix_threshold\n\n # @return [Symbol, nil] Optional warning-only keyword. Requires max_prefix_limit. May not be combined with max_prefix_interval.\n attribute :max_prefix_warning\n validates :max_prefix_warning, type: Symbol\n\n # @return [Symbol, nil] Activate the next-hop-self feature.\n attribute :next_hop_self\n validates :next_hop_self, type: Symbol\n\n # @return [Symbol, nil] Activate the next-hop-third-party feature.\n attribute :next_hop_third_party\n validates :next_hop_third_party, type: Symbol\n\n # @return [Object, nil] Valid values are a string defining a prefix-list name, or 'default'.\n attribute :prefix_list_in\n\n # @return [Object, nil] Valid values are a string defining a prefix-list name, or 'default'.\n attribute :prefix_list_out\n\n # @return [Object, nil] Valid values are a string defining a route-map name, or 'default'.\n attribute :route_map_in\n\n # @return [Object, nil] Valid values are a string defining a route-map name, or 'default'.\n attribute :route_map_out\n\n # @return [Symbol, nil] Router reflector client.\n attribute :route_reflector_client\n validates :route_reflector_client, type: Symbol\n\n # @return [:none, :both, :extended, :standard, :default, nil] send-community attribute.\n attribute :send_community\n validates :send_community, expression_inclusion: {:in=>[:none, :both, :extended, :standard, :default], :message=>\"%{value} needs to be :none, :both, :extended, :standard, :default\"}, allow_nil: true\n\n # @return [:enable, :always, :inherit, nil] Valid values are 'enable' for basic command enablement; 'always' to add the always keyword to the basic command; and 'inherit' to remove the command at this level (the command value is inherited from a higher BGP layer).\n attribute :soft_reconfiguration_in\n validates :soft_reconfiguration_in, expression_inclusion: {:in=>[:enable, :always, :inherit], :message=>\"%{value} needs to be :enable, :always, :inherit\"}, allow_nil: true\n\n # @return [Object, nil] Site-of-origin. Valid values are a string defining a VPN extcommunity or 'default'.\n attribute :soo\n\n # @return [Symbol, nil] suppress-inactive feature.\n attribute :suppress_inactive\n validates :suppress_inactive, type: Symbol\n\n # @return [Object, nil] unsuppress-map. Valid values are a string defining a route-map name or 'default'.\n attribute :unsuppress_map\n\n # @return [Object, nil] Weight value. Valid values are an integer value or 'default'.\n attribute :weight\n\n # @return [:present, :absent, nil] Determines whether the config should be present or not on the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.698762059211731, "alphanum_fraction": 0.6996790170669556, "avg_line_length": 53.525001525878906, "blob_id": "81a279ba1ee1e0483a11fad19735304067f83636", "content_id": "00a440fc3dc530fcd46b492dc649656fd02a6360", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2181, "license_type": "permissive", "max_line_length": 330, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/netapp_e_syslog.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allow the syslog settings to be configured for an individual E-Series storage-system\n class Netapp_e_syslog < Base\n # @return [:present, :absent, nil] Add or remove the syslog server configuration for E-Series storage array.,Existing syslog server configuration will be removed or updated when its address matches I(address).,Fully qualified hostname that resolve to an IPv4 address that matches I(address) will not be treated as a match.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] The syslog server's IPv4 address or a fully qualified hostname.,All existing syslog configurations will be removed when I(state=absent) and I(address=None).\n attribute :address\n validates :address, type: String\n\n # @return [Integer, nil] This is the port the syslog server is using.\n attribute :port\n validates :port, type: Integer\n\n # @return [:udp, :tcp, :tls, nil] This is the transmission protocol the syslog server's using to receive syslog messages.\n attribute :protocol\n validates :protocol, expression_inclusion: {:in=>[:udp, :tcp, :tls], :message=>\"%{value} needs to be :udp, :tcp, :tls\"}, allow_nil: true\n\n # @return [String, nil] The e-series logging components define the specific logs to transfer to the syslog server.,At the time of writing, 'auditLog' is the only logging component but more may become available.\n attribute :components\n validates :components, type: String\n\n # @return [Symbol, nil] This forces a test syslog message to be sent to the stated syslog server.,Only attempts transmission when I(state=present).\n attribute :test\n validates :test, type: Symbol\n\n # @return [Object, nil] This argument specifies a local path for logging purposes.\n attribute :log_path\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6413177847862244, "alphanum_fraction": 0.6420609354972839, "avg_line_length": 41.49473571777344, "blob_id": "fb4690305d0a3f37c6630d4cc07774e17f6344bd", "content_id": "3a6346c567e830a2fad69d0958f4d81df77e7b82", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4037, "license_type": "permissive", "max_line_length": 345, "num_lines": 95, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/ansible_tower/tower_credential.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, or destroy Ansible Tower credentials. See U(https://www.ansible.com/tower) for an overview.\n class Tower_credential < Base\n # @return [String] The name to use for the credential.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The description to use for the credential.\n attribute :description\n validates :description, type: String\n\n # @return [Object, nil] User that should own this credential.\n attribute :user\n\n # @return [Object, nil] Team that should own this credential.\n attribute :team\n\n # @return [Object, nil] Project that should for this credential.\n attribute :project\n\n # @return [String, nil] Organization that should own the credential.\n attribute :organization\n validates :organization, type: String\n\n # @return [:ssh, :vault, :net, :scm, :aws, :vmware, :satellite6, :cloudforms, :gce, :azure_rm, :openstack, :rhv, :insights, :tower] Type of credential being added.\n attribute :kind\n validates :kind, presence: true, expression_inclusion: {:in=>[:ssh, :vault, :net, :scm, :aws, :vmware, :satellite6, :cloudforms, :gce, :azure_rm, :openstack, :rhv, :insights, :tower], :message=>\"%{value} needs to be :ssh, :vault, :net, :scm, :aws, :vmware, :satellite6, :cloudforms, :gce, :azure_rm, :openstack, :rhv, :insights, :tower\"}\n\n # @return [Object, nil] Host for this credential.\n attribute :host\n\n # @return [Object, nil] Username for this credential. access_key for AWS.\n attribute :username\n\n # @return [Object, nil] Password for this credential. Use ASK for prompting. secret_key for AWS. api_key for RAX.\n attribute :password\n\n # @return [Object, nil] Path to SSH private key.\n attribute :ssh_key_data\n\n # @return [Object, nil] Unlock password for ssh_key. Use ASK for prompting.\n attribute :ssh_key_unlock\n\n # @return [:yes, :no, nil] Should use authorize for net type.\n attribute :authorize\n validates :authorize, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Password for net credentials that require authorize.\n attribute :authorize_password\n\n # @return [Object, nil] Client or application ID for azure_rm type.\n attribute :client\n\n # @return [Object, nil] STS token for aws type.\n attribute :security_token\n\n # @return [Object, nil] Secret token for azure_rm type.\n attribute :secret\n\n # @return [Object, nil] Subscription ID for azure_rm type.\n attribute :subscription\n\n # @return [Object, nil] Tenant ID for azure_rm type.\n attribute :tenant\n\n # @return [Object, nil] Domain for openstack type.\n attribute :domain\n\n # @return [:None, :sudo, :su, :pbrun, :pfexec, :pmrun, nil] Become method to Use for privledge escalation.\n attribute :become_method\n validates :become_method, expression_inclusion: {:in=>[:None, :sudo, :su, :pbrun, :pfexec, :pmrun], :message=>\"%{value} needs to be :None, :sudo, :su, :pbrun, :pfexec, :pmrun\"}, allow_nil: true\n\n # @return [Object, nil] Become username. Use ASK for prompting.\n attribute :become_username\n\n # @return [Object, nil] Become password. Use ASK for prompting.\n attribute :become_password\n\n # @return [Object, nil] Vault password. Use ASK for prompting.\n attribute :vault_password\n\n # @return [:present, :absent, nil] Desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6905721426010132, "alphanum_fraction": 0.6933923959732056, "avg_line_length": 50.70833206176758, "blob_id": "86d6c50caaa88d4160ea862361363fdf436efe93", "content_id": "eb39b506a73c53666437ef00e08dc9b49279a4d4", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2482, "license_type": "permissive", "max_line_length": 225, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/netapp_e_auth.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Sets or updates the password for a storage array. When the password is updated on the storage array, it must be updated on the SANtricity Web Services proxy. Note, all storage arrays do not have a Monitor or RO role.\n class Netapp_e_auth < Base\n # @return [Boolean, nil] Should https certificates be validated?\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] The name of the storage array. Note that if more than one storage array with this name is detected, the task will fail and you'll have to use the ID instead.\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] the identifier of the storage array in the Web Services Proxy.\n attribute :ssid\n\n # @return [Boolean, nil] Boolean value on whether to update the admin password. If set to false then the RO account is updated.\n attribute :set_admin\n validates :set_admin, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] The current admin password. This is not required if the password hasn't been set before.\n attribute :current_password\n validates :current_password, type: String\n\n # @return [String] The password you would like to set. Cannot be more than 30 characters.\n attribute :new_password\n validates :new_password, presence: true, type: String\n\n # @return [String, nil] The full API url.,Example: http://ENDPOINT:8080/devmgr/v2,This can optionally be set via an environment variable, API_URL\n attribute :api_url\n validates :api_url, type: String\n\n # @return [String, nil] The username used to authenticate against the API,This can optionally be set via an environment variable, API_USERNAME\n attribute :api_username\n validates :api_username, type: String\n\n # @return [String, nil] The password used to authenticate against the API,This can optionally be set via an environment variable, API_PASSWORD\n attribute :api_password\n validates :api_password, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6260162591934204, "alphanum_fraction": 0.642276406288147, "avg_line_length": 15.399999618530273, "blob_id": "cd279a3503201730e1f2adb7c9908832d7649015", "content_id": "cfc3d1209db80f0351ae557cd0d28ac75e22c8b5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 246, "license_type": "permissive", "max_line_length": 37, "num_lines": 15, "path": "/spec/rake/no_nested_tasks/playbook1_test.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nplay 'the play name' do\n hosts %w[host1 host2]\n\n ansible_include 'included_file.yml'\n task 'Copy something over' do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n end\n\n user 'centos'\nend\n" }, { "alpha_fraction": 0.6925418376922607, "alphanum_fraction": 0.6925418376922607, "avg_line_length": 33.578948974609375, "blob_id": "f8c65881fc8696257c56687ee4c6b3270a7a5eab", "content_id": "fd4a702e0b3dc356fb5b381ab90a7c20ad185f0e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 657, "license_type": "permissive", "max_line_length": 135, "num_lines": 19, "path": "/lib/ansible/ruby/modules/generated/system/hostname.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Set system's hostname, supports most OSs/Distributions, including those using systemd.\n # Note, this module does *NOT* modify C(/etc/hosts). You need to modify it yourself using other modules like template or replace.\n # Windows, HP-UX and AIX are not currently supported.\n class Hostname < Base\n # @return [String] Name of the host\n attribute :name\n validates :name, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6832695007324219, "alphanum_fraction": 0.6845465898513794, "avg_line_length": 34.59090805053711, "blob_id": "5fa1a8acc8b005665865849f60acf2643586dea9", "content_id": "4aec2a5b3a2a892f7ecfbfb140148b0ef01588f4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 783, "license_type": "permissive", "max_line_length": 172, "num_lines": 22, "path": "/lib/ansible/ruby/modules/generated/windows/win_pester.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Run Pester tests on Windows hosts.\n # Test files have to be available on the remote host.\n class Win_pester < Base\n # @return [String] Path to a pester test file or a folder where tests can be found.,If the path is a folder, the module will consider all ps1 files as Pester tests.\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [String, nil] Minimum version of the pester module that has to be available on the remote host.\n attribute :version\n validates :version, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.699558436870575, "alphanum_fraction": 0.699558436870575, "avg_line_length": 65.90908813476562, "blob_id": "5eed5c25bf5556b95976f0b4f86a5ad183497adb", "content_id": "b3b67b76db2c67184960be3bb7f3f3d1d16fd89a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5888, "license_type": "permissive", "max_line_length": 222, "num_lines": 88, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/cloudfront_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gets information about an AWS CloudFront distribution\n class Cloudfront_facts < Base\n # @return [String, nil] The id of the CloudFront distribution. Used with I(distribution), I(distribution_config), I(invalidation), I(streaming_distribution), I(streaming_distribution_config), I(list_invalidations).\n attribute :distribution_id\n validates :distribution_id, type: String\n\n # @return [String, nil] The id of the invalidation to get information about. Used with I(invalidation).\n attribute :invalidation_id\n validates :invalidation_id, type: String\n\n # @return [String, nil] The id of the cloudfront origin access identity to get information about.\n attribute :origin_access_identity_id\n validates :origin_access_identity_id, type: String\n\n # @return [Object, nil] Used with I(list_distributions_by_web_acl_id).\n attribute :web_acl_id\n\n # @return [String, nil] Can be used instead of I(distribution_id) - uses the aliased CNAME for the cloudfront distribution to get the distribution id where required.\n attribute :domain_name_alias\n validates :domain_name_alias, type: String\n\n # @return [Boolean, nil] Get all cloudfront lists that do not require parameters.\n attribute :all_lists\n validates :all_lists, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Get information about an origin access identity. Requires I(origin_access_identity_id) to be specified.\n attribute :origin_access_identity\n validates :origin_access_identity, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Get the configuration information about an origin access identity. Requires I(origin_access_identity_id) to be specified.\n attribute :origin_access_identity_config\n validates :origin_access_identity_config, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Get information about a distribution. Requires I(distribution_id) or I(domain_name_alias) to be specified.\n attribute :distribution\n validates :distribution, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Get the configuration information about a distribution. Requires I(distribution_id) or I(domain_name_alias) to be specified.\n attribute :distribution_config\n validates :distribution_config, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Get information about an invalidation. Requires I(invalidation_id) to be specified.\n attribute :invalidation\n validates :invalidation, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Get information about a specified RTMP distribution. Requires I(distribution_id) or I(domain_name_alias) to be specified.\n attribute :streaming_distribution\n validates :streaming_distribution, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Get the configuration information about a specified RTMP distribution. Requires I(distribution_id) or I(domain_name_alias) to be specified.\n attribute :streaming_distribution_config\n validates :streaming_distribution_config, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Get a list of cloudfront origin access identities. Requires I(origin_access_identity_id) to be set.\n attribute :list_origin_access_identities\n validates :list_origin_access_identities, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Get a list of cloudfront distributions.\n attribute :list_distributions\n validates :list_distributions, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Get a list of distributions using web acl id as a filter. Requires I(web_acl_id) to be set.\n attribute :list_distributions_by_web_acl_id\n validates :list_distributions_by_web_acl_id, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Get a list of invalidations. Requires I(distribution_id) or I(domain_name_alias) to be specified.\n attribute :list_invalidations\n validates :list_invalidations, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Get a list of streaming distributions.\n attribute :list_streaming_distributions\n validates :list_streaming_distributions, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Returns a summary of all distributions, streaming distributions and origin_access_identities. This is the default behaviour if no option is selected.\n attribute :summary\n validates :summary, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6510862112045288, "alphanum_fraction": 0.6530612111091614, "avg_line_length": 45.738460540771484, "blob_id": "d97fe5395d47a96efffe3cb469f2eb7e8b3eaf3f", "content_id": "965752ca494adf6c0f563287fa6e6fe778e34495", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3038, "license_type": "permissive", "max_line_length": 324, "num_lines": 65, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/ansible_tower/tower_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, or destroy Ansible Tower groups. See U(https://www.ansible.com/tower) for an overview.\n class Tower_group < Base\n # @return [String] The name to use for the group.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The description to use for the group.\n attribute :description\n validates :description, type: String\n\n # @return [String] Inventory the group should be made a member of.\n attribute :inventory\n validates :inventory, presence: true, type: String\n\n # @return [Object, nil] Variables to use for the group, use C(@) for a file.\n attribute :variables\n\n # @return [Object, nil] Credential to use for the group.\n attribute :credential\n\n # @return [:manual, :file, :ec2, :rax, :vmware, :gce, :azure, :azure_rm, :openstack, :satellite6, :cloudforms, :custom, nil] The source to use for this group.\n attribute :source\n validates :source, expression_inclusion: {:in=>[:manual, :file, :ec2, :rax, :vmware, :gce, :azure, :azure_rm, :openstack, :satellite6, :cloudforms, :custom], :message=>\"%{value} needs to be :manual, :file, :ec2, :rax, :vmware, :gce, :azure, :azure_rm, :openstack, :satellite6, :cloudforms, :custom\"}, allow_nil: true\n\n # @return [Object, nil] Regions for cloud provider.\n attribute :source_regions\n\n # @return [Object, nil] Override variables from source with variables from this field.\n attribute :source_vars\n\n # @return [Object, nil] Comma-separated list of filter expressions for matching hosts.\n attribute :instance_filters\n\n # @return [Object, nil] Limit groups automatically created from inventory source.\n attribute :group_by\n\n # @return [Object, nil] Inventory script to be used when group type is C(custom).\n attribute :source_script\n\n # @return [:yes, :no, nil] Delete child groups and hosts not found in source.\n attribute :overwrite\n validates :overwrite, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Override vars in child groups and hosts with those from external source.\n attribute :overwrite_vars\n\n # @return [:yes, :no, nil] Refresh inventory data from its source each time a job is run.\n attribute :update_on_launch\n validates :update_on_launch, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6922498345375061, "alphanum_fraction": 0.6922498345375061, "avg_line_length": 52.15999984741211, "blob_id": "208f08042abc91a5bacb727a3d446dda3f8517c4", "content_id": "88081c5188bc85dbd79178e019dc48171c6cb7ac", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1329, "license_type": "permissive", "max_line_length": 393, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/net_tools/ldap/ldap_attr.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove LDAP attribute values.\n class Ldap_attr < Base\n # @return [String] The name of the attribute to modify.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, :exact, nil] The state of the attribute values. If C(present), all given values will be added if they're missing. If C(absent), all given values will be removed if present. If C(exact), the set of values will be forced to exactly those provided and no others. If I(state=exact) and I(value) is an empty list, all values for this attribute will be removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :exact], :message=>\"%{value} needs to be :present, :absent, :exact\"}, allow_nil: true\n\n # @return [Array<String>, String] The value(s) to add or remove. This can be a string or a list of strings. The complex argument format is required in order to pass a list of strings (see examples).\n attribute :values\n validates :values, presence: true, type: TypeGeneric.new(String, NilClass)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6758555173873901, "alphanum_fraction": 0.6758555173873901, "avg_line_length": 57.44444274902344, "blob_id": "6c43f55d89a7984f6f1ea9db71985bf0922e410d", "content_id": "51b694de20cbd16ccec0b7f086c4950682d4f0c0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2104, "license_type": "permissive", "max_line_length": 411, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/cloud/misc/virt.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages virtual machines supported by I(libvirt).\n class Virt < Base\n # @return [String, nil] name of the guest VM being managed. Note that VM must be previously defined with xml.,This option is required unless I(command) is C(list_vms).\n attribute :name\n validates :name, type: String\n\n # @return [:destroyed, :paused, :running, :shutdown, nil] Note that there may be some lag for state requests like C(shutdown) since these refer only to VM states. After starting a guest, it may not be immediately accessible.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:destroyed, :paused, :running, :shutdown], :message=>\"%{value} needs to be :destroyed, :paused, :running, :shutdown\"}, allow_nil: true\n\n # @return [:create, :define, :destroy, :freemem, :get_xml, :info, :list_vms, :nodeinfo, :pause, :shutdown, :start, :status, :stop, :undefine, :unpause, :virttype, nil] In addition to state management, various non-idempotent commands are available.\n attribute :command\n validates :command, expression_inclusion: {:in=>[:create, :define, :destroy, :freemem, :get_xml, :info, :list_vms, :nodeinfo, :pause, :shutdown, :start, :status, :stop, :undefine, :unpause, :virttype], :message=>\"%{value} needs to be :create, :define, :destroy, :freemem, :get_xml, :info, :list_vms, :nodeinfo, :pause, :shutdown, :start, :status, :stop, :undefine, :unpause, :virttype\"}, allow_nil: true\n\n # @return [Symbol, nil] start VM at host startup.\n attribute :autostart\n validates :autostart, type: Symbol\n\n # @return [String, nil] libvirt connection uri.\n attribute :uri\n validates :uri, type: String\n\n # @return [Object, nil] XML document used with the define command.,Must be raw XML content using C(lookup). XML cannot be reference to a file.\n attribute :xml\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6850311756134033, "alphanum_fraction": 0.6850311756134033, "avg_line_length": 39.08333206176758, "blob_id": "738586d535a82d1e123786bf860655a4ebc43eb1", "content_id": "7c1c6978b52cf1b475de293717e5cfc101953bd9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 962, "license_type": "permissive", "max_line_length": 185, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/network/vyos/vyos_lldp_interface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of LLDP interfaces configuration on VyOS network devices.\n class Vyos_lldp_interface < Base\n # @return [Object, nil] Name of the interface LLDP should be configured on.\n attribute :name\n\n # @return [Array<Hash>, Hash, nil] List of interfaces LLDP should be configured on.\n attribute :aggregate\n validates :aggregate, type: TypeGeneric.new(Hash)\n\n # @return [:present, :absent, :enabled, :disabled, nil] State of the LLDP configuration.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :enabled, :disabled], :message=>\"%{value} needs to be :present, :absent, :enabled, :disabled\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6851385235786438, "alphanum_fraction": 0.6856423020362854, "avg_line_length": 51.23684310913086, "blob_id": "3875aacf6ce92aac21ad54ad1901e00e9b765342", "content_id": "82e4e4056b10c5ba2d082e6d41248e3ac9f4bf59", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1985, "license_type": "permissive", "max_line_length": 233, "num_lines": 38, "path": "/lib/ansible/ruby/modules/generated/network/illumos/ipadm_addr.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create/delete static/dynamic IP addresses on network interfaces on Solaris/illumos systems.\n # Up/down static/dynamic IP addresses on network interfaces on Solaris/illumos systems.\n # Manage IPv6 link-local addresses on network interfaces on Solaris/illumos systems.\n class Ipadm_addr < Base\n # @return [Object, nil] Specifiies an IP address to configure in CIDR notation.\n attribute :address\n\n # @return [:static, :dhcp, :addrconf, nil] Specifiies a type of IP address to configure.\n attribute :addrtype\n validates :addrtype, expression_inclusion: {:in=>[:static, :dhcp, :addrconf], :message=>\"%{value} needs to be :static, :dhcp, :addrconf\"}, allow_nil: true\n\n # @return [String] Specifies an unique IP address on the system.\n attribute :addrobj\n validates :addrobj, presence: true, type: String\n\n # @return [Boolean, nil] Specifies that the configured IP address is temporary. Temporary IP addresses do not persist across reboots.\n attribute :temporary\n validates :temporary, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Integer, nil] Specifies the time in seconds we wait for obtaining address via DHCP.\n attribute :wait\n validates :wait, type: Integer\n\n # @return [:absent, :present, :up, :down, :enabled, :disabled, :refreshed, nil] Create/delete/enable/disable an IP address on the network interface.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :up, :down, :enabled, :disabled, :refreshed], :message=>\"%{value} needs to be :absent, :present, :up, :down, :enabled, :disabled, :refreshed\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5573080778121948, "alphanum_fraction": 0.5573080778121948, "avg_line_length": 22.19512176513672, "blob_id": "4fccd42ced2794649442d5adc3cf7be5bf4b02ab", "content_id": "f703760c04bafef763c18ceb23c55304f7bd8525", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 951, "license_type": "permissive", "max_line_length": 75, "num_lines": 41, "path": "/lib/ansible/ruby/dsl_builders/block.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# see LICENSE.txt in project root\nrequire 'ansible/ruby/models/block'\n\nmodule Ansible\n module Ruby\n module DslBuilders\n class Block < Unit\n def initialize\n super\n @task_builders = []\n end\n\n def task(name, &block)\n task_builder = Task.new name, Models::Task\n task_builder.instance_eval(&block)\n @task_builders << task_builder\n task_builder._register\n end\n\n # allow for other attributes besides the module in any order\n def _result\n tasks = @task_builders.map(&:_result)\n args = {\n tasks: tasks\n }.merge @task_args\n block = Models::Block.new args\n block.validate!\n block\n end\n\n private\n\n def _process_method(id, *)\n no_method_error id, \"Only valid options are #{_valid_attributes}\"\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6678200960159302, "alphanum_fraction": 0.6678200960159302, "avg_line_length": 33.68000030517578, "blob_id": "37ff03f548c449ec0a00453eae789a31639bb2d0", "content_id": "9d421fd2caf34281750c8c012a4be0660165f1ba", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 867, "license_type": "permissive", "max_line_length": 142, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/monitoring/uptimerobot.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module will let you start and pause Uptime Robot Monitoring\n class Uptimerobot < Base\n # @return [:started, :paused] Define whether or not the monitor should be running or paused.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:started, :paused], :message=>\"%{value} needs to be :started, :paused\"}\n\n # @return [Integer] ID of the monitor to check.\n attribute :monitorid\n validates :monitorid, presence: true, type: Integer\n\n # @return [String] Uptime Robot API key.\n attribute :apikey\n validates :apikey, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6688201427459717, "alphanum_fraction": 0.6783406734466553, "avg_line_length": 60.27083206176758, "blob_id": "2882843f191e48af1fc3f3bb9693150238e10e21", "content_id": "2760a16130ec48f90ffb6ee2998483b6ff803529", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2941, "license_type": "permissive", "max_line_length": 201, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_vxlan_global.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages global attributes of VXLAN and bridge domain on HUAWEI CloudEngine devices.\n class Ce_vxlan_global < Base\n # @return [Object, nil] Specifies a bridge domain ID. The value is an integer ranging from 1 to 16777215.\n attribute :bridge_domain_id\n\n # @return [:enable, :disable, nil] Set the tunnel mode to VXLAN when configuring the VXLAN feature.\n attribute :tunnel_mode_vxlan\n validates :tunnel_mode_vxlan, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:enable, :disable, nil] Loop prevention of VXLAN traffic in non-enhanced mode. When the device works in non-enhanced mode, inter-card forwarding of VXLAN traffic may result in loops.\n attribute :nvo3_prevent_loops\n validates :nvo3_prevent_loops, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:enable, :disable, nil] Enabling or disabling the VXLAN ACL extension function.\n attribute :nvo3_acl_extend\n validates :nvo3_acl_extend, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:l2, :l3, nil] Configuring the Layer 3 VXLAN Gateway to Work in Non-loopback Mode.\n attribute :nvo3_gw_enhanced\n validates :nvo3_gw_enhanced, expression_inclusion: {:in=>[:l2, :l3], :message=>\"%{value} needs to be :l2, :l3\"}, allow_nil: true\n\n # @return [:enable, :disable, nil] Enabling or disabling the VXLAN service extension function.\n attribute :nvo3_service_extend\n validates :nvo3_service_extend, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:enable, :disable, nil] Eth-Trunk from load balancing VXLAN packets in optimized mode.\n attribute :nvo3_eth_trunk_hash\n validates :nvo3_eth_trunk_hash, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:enable, :disable, nil] Load balancing of VXLAN packets through ECMP in optimized mode.\n attribute :nvo3_ecmp_hash\n validates :nvo3_ecmp_hash, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Determines whether the config should be present or not on the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6673387289047241, "alphanum_fraction": 0.6673387289047241, "avg_line_length": 43.28571319580078, "blob_id": "9161a55b2725a35a9adcd4e754af8171b2b1a63e", "content_id": "832db7fae9e713c8273ad443a0265f98f6e2812b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2480, "license_type": "permissive", "max_line_length": 163, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/cloud/univention/udm_dns_zone.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows to manage dns zones on a univention corporate server (UCS). It uses the python API of the UCS to create a new object or edit it.\n class Udm_dns_zone < Base\n # @return [:present, :absent, nil] Whether the dns zone is present or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:forward_zone, :reverse_zone] Define if the zone is a forward or reverse DNS zone.\n attribute :type\n validates :type, presence: true, expression_inclusion: {:in=>[:forward_zone, :reverse_zone], :message=>\"%{value} needs to be :forward_zone, :reverse_zone\"}\n\n # @return [String] DNS zone name, e.g. C(example.com).\n attribute :zone\n validates :zone, presence: true, type: String\n\n # @return [Array<String>, String, nil] List of appropriate name servers. Required if C(state=present).\n attribute :nameserver\n validates :nameserver, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] List of interface IP addresses, on which the server should response this zone. Required if C(state=present).\n attribute :interfaces\n validates :interfaces, type: TypeGeneric.new(String)\n\n # @return [Integer, nil] Interval before the zone should be refreshed.\n attribute :refresh\n validates :refresh, type: Integer\n\n # @return [Integer, nil] Interval that should elapse before a failed refresh should be retried.\n attribute :retry\n validates :retry, type: Integer\n\n # @return [Integer, nil] Specifies the upper limit on the time interval that can elapse before the zone is no longer authoritative.\n attribute :expire\n validates :expire, type: Integer\n\n # @return [Integer, nil] Minimum TTL field that should be exported with any RR from this zone.\n attribute :ttl\n validates :ttl, type: Integer\n\n # @return [String, nil] Contact person in the SOA record.\n attribute :contact\n validates :contact, type: String\n\n # @return [Object, nil] List of MX servers. (Must declared as A or AAAA records).\n attribute :mx\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6968944072723389, "alphanum_fraction": 0.6993789076805115, "avg_line_length": 37.33333206176758, "blob_id": "a0eb1a20c1373a90a823e5c3e5c85b4128278052", "content_id": "2e8ba6e577c3abfa035ec4b929af7fe2c23f0614", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 805, "license_type": "permissive", "max_line_length": 229, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_vpc_vgw_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gather facts about virtual gateways in AWS.\n class Ec2_vpc_vgw_facts < Base\n # @return [Hash, nil] A dict of filters to apply. Each dict item consists of a filter key and a filter value. See U(http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeRouteTables.html) for possible filters.\n attribute :filters\n validates :filters, type: Hash\n\n # @return [String, nil] Get details of a specific Virtual Gateway ID. This value should be provided as a list.\n attribute :vpn_gateway_ids\n validates :vpn_gateway_ids, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6808943152427673, "alphanum_fraction": 0.6811846494674683, "avg_line_length": 50.402984619140625, "blob_id": "b9f0bf3dee25bafb453b4adf0635709d2aab6dd5", "content_id": "c4215ee1c54b20f4a3c95e5b0a0e73eb37c4a6c7", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3444, "license_type": "permissive", "max_line_length": 220, "num_lines": 67, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/elasticache.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage cache clusters in Amazon Elasticache.\n # Returns information about the specified cache cluster.\n class Elasticache < Base\n # @return [:present, :absent, :rebooted] C(absent) or C(present) are idempotent actions that will create or destroy a cache cluster as needed. C(rebooted) will reboot the cluster, resulting in a momentary outage.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent, :rebooted], :message=>\"%{value} needs to be :present, :absent, :rebooted\"}\n\n # @return [String] The cache cluster identifier\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:redis, :memcached, nil] Name of the cache engine to be used.\n attribute :engine\n validates :engine, expression_inclusion: {:in=>[:redis, :memcached], :message=>\"%{value} needs to be :redis, :memcached\"}, allow_nil: true\n\n # @return [String, nil] The version number of the cache engine\n attribute :cache_engine_version\n validates :cache_engine_version, type: String\n\n # @return [String, nil] The compute and memory capacity of the nodes in the cache cluster\n attribute :node_type\n validates :node_type, type: String\n\n # @return [Integer, nil] The initial number of cache nodes that the cache cluster will have. Required when state=present.\n attribute :num_nodes\n validates :num_nodes, type: Integer\n\n # @return [Integer, nil] The port number on which each of the cache nodes will accept connections\n attribute :cache_port\n validates :cache_port, type: Integer\n\n # @return [Object, nil] The name of the cache parameter group to associate with this cache cluster. If this argument is omitted, the default cache parameter group for the specified engine will be used.\n attribute :cache_parameter_group\n\n # @return [Object, nil] The subnet group name to associate with. Only use if inside a vpc. Required if inside a vpc\n attribute :cache_subnet_group\n\n # @return [Object, nil] A list of vpc security group names to associate with this cache cluster. Only use if inside a vpc\n attribute :security_group_ids\n\n # @return [Array<String>, String, nil] A list of cache security group names to associate with this cache cluster. Must be an empty list if inside a vpc\n attribute :cache_security_groups\n validates :cache_security_groups, type: TypeGeneric.new(String)\n\n # @return [String, nil] The EC2 Availability Zone in which the cache cluster will be created\n attribute :zone\n validates :zone, type: String\n\n # @return [:yes, :no, nil] Wait for cache cluster result before returning\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Whether to destroy and recreate an existing cache cluster if necessary in order to modify its state\n attribute :hard_modify\n validates :hard_modify, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.704531729221344, "alphanum_fraction": 0.7135951519012451, "avg_line_length": 56.068965911865234, "blob_id": "aa5f132e22d3b7496f5233c27a9c596193e29209", "content_id": "cdc573b3d867e7d27d7d97d7f71d81b3dcf2bef7", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1655, "license_type": "permissive", "max_line_length": 597, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_guest_disk_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to gather facts about disks belonging to given virtual machine.\n # All parameters and VMware object names are case sensitive.\n class Vmware_guest_disk_facts < Base\n # @return [String, nil] Name of the virtual machine.,This is required parameter, if parameter C(uuid) is not supplied.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] UUID of the instance to gather facts if known, this is VMware's unique identifier.,This is required parameter, if parameter C(name) is not supplied.\n attribute :uuid\n validates :uuid, type: String\n\n # @return [Object, nil] Destination folder, absolute or relative path to find an existing guest.,This is required parameter, only if multiple VMs are found with same name.,The folder should include the datacenter. ESX's datacenter is ha-datacenter,Examples:, folder: /ha-datacenter/vm, folder: ha-datacenter/vm, folder: /datacenter1/vm, folder: datacenter1/vm, folder: /datacenter1/vm/folder1, folder: datacenter1/vm/folder1, folder: /folder1/datacenter1/vm, folder: folder1/datacenter1/vm, folder: /folder1/datacenter1/vm/folder2, folder: vm/folder2, folder: folder2\n attribute :folder\n\n # @return [String] The datacenter name to which virtual machine belongs to.\n attribute :datacenter\n validates :datacenter, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6902173757553101, "alphanum_fraction": 0.6902173757553101, "avg_line_length": 13.15384578704834, "blob_id": "9d29151aea56a05f8b6792ec468c99b14cd43547", "content_id": "60f86022d906ac234857bceea19728f92c1ff894", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 184, "license_type": "permissive", "max_line_length": 42, "num_lines": 13, "path": "/examples/roles/dummy/handlers/main.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nhandler 'reboot' do\n ansible_include 'handler_include.yml' do\n static true\n end\nend\n\nhandler 'say hi' do\n debug do\n msg 'hello there'\n end\nend\n" }, { "alpha_fraction": 0.6758893132209778, "alphanum_fraction": 0.6845849752426147, "avg_line_length": 41.16666793823242, "blob_id": "190f6fcf4d7dd08a725b04edb1495184eee37ffb", "content_id": "f5f2f012bdc8a0c3d2343f9bf92b9d67320baaa4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1265, "license_type": "permissive", "max_line_length": 171, "num_lines": 30, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_startup.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages a system startup information on HUAWEI CloudEngine switches.\n class Ce_startup < Base\n # @return [String, nil] Name of the configuration file that is applied for the next startup. The value is a string of 5 to 255 characters.\n attribute :cfg_file\n validates :cfg_file, type: String\n\n # @return [Object, nil] File name of the system software that is applied for the next startup. The value is a string of 5 to 255 characters.\n attribute :software_file\n\n # @return [Object, nil] Name of the patch file that is applied for the next startup.\n attribute :patch_file\n\n # @return [Object, nil] Position of the device.The value is a string of 1 to 32 characters. The possible value of slot is all, slave-board, or the specific slotID.\n attribute :slot\n\n # @return [:display, nil] Display the startup information.\n attribute :action\n validates :action, expression_inclusion: {:in=>[:display], :message=>\"%{value} needs to be :display\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.695388674736023, "alphanum_fraction": 0.695388674736023, "avg_line_length": 58.296875, "blob_id": "32d7f29cf1efb199c3d3498219f61ee34facf573", "content_id": "d7c76a0f33815aacc90f6e64ee572872f25c4f50", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3795, "license_type": "permissive", "max_line_length": 433, "num_lines": 64, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/django_manage.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages a Django application using the I(manage.py) application frontend to I(django-admin). With the I(virtualenv) parameter, all management commands will be executed by the given I(virtualenv) installation.\n class Django_manage < Base\n # @return [:cleanup, :collectstatic, :flush, :loaddata, :migrate, :runfcgi, :syncdb, :test, :validate] The name of the Django management command to run. Built in commands are cleanup, collectstatic, flush, loaddata, migrate, runfcgi, syncdb, test, and validate.,Other commands can be entered, but will fail if they're unknown to Django. Other commands that may prompt for user input should be run with the I(--noinput) flag.\n attribute :command\n validates :command, presence: true, expression_inclusion: {:in=>[:cleanup, :collectstatic, :flush, :loaddata, :migrate, :runfcgi, :syncdb, :test, :validate], :message=>\"%{value} needs to be :cleanup, :collectstatic, :flush, :loaddata, :migrate, :runfcgi, :syncdb, :test, :validate\"}\n\n # @return [String] The path to the root of the Django application where B(manage.py) lives.\n attribute :app_path\n validates :app_path, presence: true, type: String\n\n # @return [String, nil] The Python path to the application's settings module, such as 'myapp.settings'.\n attribute :settings\n validates :settings, type: String\n\n # @return [String, nil] A directory to add to the Python path. Typically used to include the settings module if it is located external to the application directory.\n attribute :pythonpath\n validates :pythonpath, type: String\n\n # @return [String, nil] An optional path to a I(virtualenv) installation to use while running the manage application.\n attribute :virtualenv\n validates :virtualenv, type: String\n\n # @return [String, nil] A list of space-delimited apps to target. Used by the 'test' command.\n attribute :apps\n validates :apps, type: String\n\n # @return [Object, nil] The name of the table used for database-backed caching. Used by the 'createcachetable' command.\n attribute :cache_table\n\n # @return [Symbol, nil] Clear the existing files before trying to copy or link the original file.,Used only with the 'collectstatic' command. The C(--noinput) argument will be added automatically.\n attribute :clear\n validates :clear, type: Symbol\n\n # @return [Object, nil] The database to target. Used by the 'createcachetable', 'flush', 'loaddata', and 'syncdb' commands.\n attribute :database\n\n # @return [:yes, :no, nil] Fail the command immediately if a test fails. Used by the 'test' command.\n attribute :failfast\n validates :failfast, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] A space-delimited list of fixture file names to load in the database. B(Required) by the 'loaddata' command.\n attribute :fixtures\n validates :fixtures, type: String\n\n # @return [Object, nil] Will skip over out-of-order missing migrations, you can only use this parameter with I(migrate)\n attribute :skip\n\n # @return [Object, nil] Will run out-of-order or missing migrations as they are not rollback migrations, you can only use this parameter with 'migrate' command\n attribute :merge\n\n # @return [Object, nil] Will create links to the files instead of copying them, you can only use this parameter with 'collectstatic' command\n attribute :link\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6748422980308533, "alphanum_fraction": 0.6832515597343445, "avg_line_length": 61.043479919433594, "blob_id": "d3d271df7fc36eabefbb0616a1a235e167a6c3a6", "content_id": "f840e0f3a732ea579a0ac8b1719e5c45a9962eef", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2854, "license_type": "permissive", "max_line_length": 449, "num_lines": 46, "path": "/lib/ansible/ruby/modules/generated/remote_management/hpilo/hpilo_boot.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module boots a system through its HP iLO interface. The boot media can be one of: cdrom, floppy, hdd, network or usb.\n # This module requires the hpilo python module.\n class Hpilo_boot < Base\n # @return [String] The HP iLO hostname/address that is linked to the physical system.\n attribute :host\n validates :host, presence: true, type: String\n\n # @return [String, nil] The login name to authenticate to the HP iLO interface.\n attribute :login\n validates :login, type: String\n\n # @return [String, nil] The password to authenticate to the HP iLO interface.\n attribute :password\n validates :password, type: String\n\n # @return [:cdrom, :floppy, :hdd, :network, :normal, :usb, nil] The boot media to boot the system from\n attribute :media\n validates :media, expression_inclusion: {:in=>[:cdrom, :floppy, :hdd, :network, :normal, :usb], :message=>\"%{value} needs to be :cdrom, :floppy, :hdd, :network, :normal, :usb\"}, allow_nil: true\n\n # @return [String, nil] The URL of a cdrom, floppy or usb boot media image. protocol://username:password@hostname:port/filename,protocol is either 'http' or 'https',username:password is optional,port is optional\n attribute :image\n validates :image, type: String\n\n # @return [:boot_always, :boot_once, :connect, :disconnect, :no_boot, :poweroff, nil] The state of the boot media.,no_boot: Do not boot from the device,boot_once: Boot from the device once and then notthereafter,boot_always: Boot from the device each time the serveris rebooted,connect: Connect the virtual media device and set to boot_always,disconnect: Disconnects the virtual media device and set to no_boot,poweroff: Power off the server\n attribute :state\n validates :state, expression_inclusion: {:in=>[:boot_always, :boot_once, :connect, :disconnect, :no_boot, :poweroff], :message=>\"%{value} needs to be :boot_always, :boot_once, :connect, :disconnect, :no_boot, :poweroff\"}, allow_nil: true\n\n # @return [Symbol, nil] Whether to force a reboot (even when the system is already booted).,As a safeguard, without force, hpilo_boot will refuse to reboot a server that is already running.\n attribute :force\n validates :force, type: Symbol\n\n # @return [:SSLv3, :SSLv23, :TLSv1, :TLSv1_1, :TLSv1_2, nil] Change the ssl_version used.\n attribute :ssl_version\n validates :ssl_version, expression_inclusion: {:in=>[:SSLv3, :SSLv23, :TLSv1, :TLSv1_1, :TLSv1_2], :message=>\"%{value} needs to be :SSLv3, :SSLv23, :TLSv1, :TLSv1_1, :TLSv1_2\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6883777379989624, "alphanum_fraction": 0.6924939751625061, "avg_line_length": 59.735294342041016, "blob_id": "3ba44ace56c3e8451d7a6d2d838d9875ec6d5386", "content_id": "2f45d2198faf7901a4d776ad1479db2670434b3e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4130, "license_type": "permissive", "max_line_length": 565, "num_lines": 68, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_bd_subnet.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage Subnets on Cisco ACI fabrics.\n class Aci_bd_subnet < Base\n # @return [String, nil] The name of the Bridge Domain.\n attribute :bd\n validates :bd, type: String\n\n # @return [String, nil] The description for the Subnet.\n attribute :description\n validates :description, type: String\n\n # @return [Symbol, nil] Determines if the Subnet should be treated as a VIP; used when the BD is extended to multiple sites.,The APIC defaults to C(no) when unset during creation.\n attribute :enable_vip\n validates :enable_vip, type: Symbol\n\n # @return [String, nil] The IPv4 or IPv6 gateway address for the Subnet.\n attribute :gateway\n validates :gateway, type: String\n\n # @return [Integer, nil] The subnet mask for the Subnet.,This is the number assocated with CIDR notation.,For IPv4 addresses, accepted values range between C(0) and C(32).,For IPv6 addresses, accepted Values range between C(0) and C(128).\n attribute :mask\n validates :mask, type: Integer\n\n # @return [Object, nil] The IPv6 Neighbor Discovery Prefix Policy to associate with the Subnet.\n attribute :nd_prefix_policy\n\n # @return [Symbol, nil] Determines if the Subnet is preferred over all available Subnets. Only one Subnet per Address Family (IPv4/IPv6). can be preferred in the Bridge Domain.,The APIC defaults to C(no) when unset during creation.\n attribute :preferred\n validates :preferred, type: Symbol\n\n # @return [String, nil] The Route Profile to the associate with the Subnet.\n attribute :route_profile\n validates :route_profile, type: String\n\n # @return [String, nil] The L3 Out that contains the assocated Route Profile.\n attribute :route_profile_l3_out\n validates :route_profile_l3_out, type: String\n\n # @return [:private, :public, :shared, nil] Determines the scope of the Subnet.,The C(private) option only allows communication with hosts in the same VRF.,The C(public) option allows the Subnet to be advertised outside of the ACI Fabric, and allows communication with hosts in other VRFs.,The shared option limits communication to hosts in either the same VRF or the shared VRF.,The value is a list of options, C(private) and C(public) are mutually exclusive, but both can be used with C(shared).,The APIC defaults to C(private) when unset during creation.\n attribute :scope\n validates :scope, expression_inclusion: {:in=>[:private, :public, :shared], :message=>\"%{value} needs to be :private, :public, :shared\"}, allow_nil: true\n\n # @return [:nd_ra, :no_gw, :querier_ip, :unspecified, nil] Determines the Subnet's Control State.,The C(querier_ip) option is used to treat the gateway_ip as an IGMP querier source IP.,The C(nd_ra) option is used to treate the gateway_ip address as a Neighbor Discovery Router Advertisement Prefix.,The C(no_gw) option is used to remove default gateway functionality from the gateway address.,The APIC defaults to C(nd_ra) when unset during creation.\n attribute :subnet_control\n validates :subnet_control, expression_inclusion: {:in=>[:nd_ra, :no_gw, :querier_ip, :unspecified], :message=>\"%{value} needs to be :nd_ra, :no_gw, :querier_ip, :unspecified\"}, allow_nil: true\n\n # @return [String, nil] The name of the Subnet.\n attribute :subnet_name\n validates :subnet_name, type: String\n\n # @return [String, nil] The name of the Tenant.\n attribute :tenant\n validates :tenant, type: String\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6522430777549744, "alphanum_fraction": 0.6557429432868958, "avg_line_length": 41.47297286987305, "blob_id": "6dc8edfb7b95edb0e66aadfab6ed5b6ddca7d940", "content_id": "00f0fa27cef3bb7731b8697989b28a601b0e374c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3143, "license_type": "permissive", "max_line_length": 161, "num_lines": 74, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_disk_offering.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create and delete disk offerings for guest VMs.\n # Update display_text or display_offering of existing disk offering.\n class Cs_disk_offering < Base\n # @return [Integer, nil] Size of the disk offering in GB (1GB = 1,073,741,824 bytes).\n attribute :disk_size\n validates :disk_size, type: Integer\n\n # @return [Object, nil] Bytes read rate of the disk offering.\n attribute :bytes_read_rate\n\n # @return [Object, nil] Bytes write rate of the disk offering.\n attribute :bytes_write_rate\n\n # @return [String, nil] Display text of the disk offering.,If not set, C(name) will be used as C(display_text) while creating.\n attribute :display_text\n validates :display_text, type: String\n\n # @return [Object, nil] Domain the disk offering is related to.,Public for all domains and subdomains if not set.\n attribute :domain\n\n # @return [Object, nil] Hypervisor snapshot reserve space as a percent of a volume.,Only for managed storage using Xen or VMware.\n attribute :hypervisor_snapshot_reserve\n\n # @return [Symbol, nil] Whether disk offering iops is custom or not.\n attribute :customized\n validates :customized, type: Symbol\n\n # @return [Object, nil] IO requests read rate of the disk offering.\n attribute :iops_read_rate\n\n # @return [Object, nil] IO requests write rate of the disk offering.\n attribute :iops_write_rate\n\n # @return [Object, nil] Max. iops of the disk offering.\n attribute :iops_max\n\n # @return [Object, nil] Min. iops of the disk offering.\n attribute :iops_min\n\n # @return [String] Name of the disk offering.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:thin, :sparse, :fat, nil] Provisioning type used to create volumes.\n attribute :provisioning_type\n validates :provisioning_type, expression_inclusion: {:in=>[:thin, :sparse, :fat], :message=>\"%{value} needs to be :thin, :sparse, :fat\"}, allow_nil: true\n\n # @return [:present, :absent, nil] State of the disk offering.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:local, :shared, nil] The storage type of the disk offering.\n attribute :storage_type\n validates :storage_type, expression_inclusion: {:in=>[:local, :shared], :message=>\"%{value} needs to be :local, :shared\"}, allow_nil: true\n\n # @return [String, nil] The storage tags for this disk offering.\n attribute :storage_tags\n validates :storage_tags, type: String\n\n # @return [Symbol, nil] An optional field, whether to display the offering to the end user or not.\n attribute :display_offering\n validates :display_offering, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6580565571784973, "alphanum_fraction": 0.6586715579032898, "avg_line_length": 47.53731155395508, "blob_id": "00dd729ff6933088723b129baa42ae9486fb8d4b", "content_id": "11288fda2fb983a61add66acfdd11c0fb2bc4262", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3252, "license_type": "permissive", "max_line_length": 335, "num_lines": 67, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gce_pd.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can create and destroy unformatted GCE persistent disks U(https://developers.google.com/compute/docs/disks#persistentdisks). It also supports attaching and detaching disks from running instances. Full install/configuration instructions for the gce* modules can be found in the comments of ansible/test/gce_tests.py.\n class Gce_pd < Base\n # @return [:yes, :no, nil] do not destroy the disk, merely detach it from an instance\n attribute :detach_only\n validates :detach_only, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] instance name if you wish to attach or detach the disk\n attribute :instance_name\n validates :instance_name, type: String\n\n # @return [:READ_WRITE, :READ_ONLY, nil] GCE mount mode of disk, READ_ONLY (default) or READ_WRITE\n attribute :mode\n validates :mode, expression_inclusion: {:in=>[:READ_WRITE, :READ_ONLY], :message=>\"%{value} needs to be :READ_WRITE, :READ_ONLY\"}, allow_nil: true\n\n # @return [String] name of the disk\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Integer, nil] whole integer size of disk (in GB) to create, default is 10 GB\n attribute :size_gb\n validates :size_gb, type: Integer\n\n # @return [Object, nil] the source image to use for the disk\n attribute :image\n\n # @return [Object, nil] the source snapshot to use for the disk\n attribute :snapshot\n\n # @return [:active, :present, :absent, :deleted, nil] desired state of the persistent disk\n attribute :state\n validates :state, expression_inclusion: {:in=>[:active, :present, :absent, :deleted], :message=>\"%{value} needs to be :active, :present, :absent, :deleted\"}, allow_nil: true\n\n # @return [String, nil] zone in which to create the disk\n attribute :zone\n validates :zone, type: String\n\n # @return [Object, nil] service account email\n attribute :service_account_email\n\n # @return [Object, nil] path to the pem file associated with the service account email This option is deprecated. Use 'credentials_file'.\n attribute :pem_file\n\n # @return [Object, nil] path to the JSON file associated with the service account email\n attribute :credentials_file\n\n # @return [Object, nil] your GCE project ID\n attribute :project_id\n\n # @return [:\"pd-standard\", :\"pd-ssd\", nil] type of disk provisioned\n attribute :disk_type\n validates :disk_type, expression_inclusion: {:in=>[:\"pd-standard\", :\"pd-ssd\"], :message=>\"%{value} needs to be :\\\"pd-standard\\\", :\\\"pd-ssd\\\"\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(yes), deletes the volume when instance is terminated\n attribute :delete_on_termination\n validates :delete_on_termination, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6748802065849304, "alphanum_fraction": 0.6748802065849304, "avg_line_length": 39.58333206176758, "blob_id": "87c89c3821b9dcddd8a968500ed0e404a11c75bb", "content_id": "13aa98632ded20df0b96d87b8aa4f58f2a0f3c31", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1461, "license_type": "permissive", "max_line_length": 193, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_service_policy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Service policies allow you to configure timers and port misuse rules, if enabled, on a per rule or per context basis.\n class Bigip_service_policy < Base\n # @return [String] Name of the service policy.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Description of the service policy.\n attribute :description\n\n # @return [String, nil] The timer policy to attach to the service policy.\n attribute :timer_policy\n validates :timer_policy, type: String\n\n # @return [String, nil] The port misuse policy to attach to the service policy.,Requires that C(afm) be provisioned to use. If C(afm) is not provisioned, this parameter will be ignored.\n attribute :port_misuse_policy\n validates :port_misuse_policy, type: String\n\n # @return [:present, :absent, nil] Whether the resource should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6460905075073242, "alphanum_fraction": 0.6584362387657166, "avg_line_length": 27.58823585510254, "blob_id": "01adbe78e1c5049193c285bba746d82219bcab9a", "content_id": "1bb7bb76567f68b1f683bd84523c4b4c6b66abf4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 486, "license_type": "permissive", "max_line_length": 118, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_vtp_version.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages VTP version configuration.\n class Nxos_vtp_version < Base\n # @return [1, 2] VTP version number.\n attribute :version\n validates :version, presence: true, expression_inclusion: {:in=>[1, 2], :message=>\"%{value} needs to be 1, 2\"}\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6930213570594788, "alphanum_fraction": 0.6934247612953186, "avg_line_length": 60.974998474121094, "blob_id": "cfdfcf9ba92d80d4935f4aa1355b024683457a6d", "content_id": "5532756d5d2afe903746e344eef7c727a942e4b9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2479, "license_type": "permissive", "max_line_length": 281, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/execute_lambda.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module executes AWS Lambda functions, allowing synchronous and asynchronous invocation.\n class Execute_lambda < Base\n # @return [String, nil] The name of the function to be invoked. This can only be used for invocations within the calling account. To invoke a function in another account, use I(function_arn) to specify the full ARN.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] The name of the function to be invoked\n attribute :function_arn\n validates :function_arn, type: String\n\n # @return [:yes, :no, nil] If C(tail_log=yes), the result of the task will include the last 4 KB of the CloudWatch log for the function execution. Log tailing only works if you use synchronous invocation C(wait=yes). This is usually used for development or testing Lambdas.\n attribute :tail_log\n validates :tail_log, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Whether to wait for the function results or not. If I(wait) is C(no), the task will not return any results. To wait for the Lambda function to complete, set C(wait=yes) and the result will be available in the I(output) key.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Do not *actually* invoke the function. A C(DryRun) call will check that the caller has permissions to call the function, especially for checking cross-account permissions.\n attribute :dry_run\n validates :dry_run, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Which version/alias of the function to run. This defaults to the C(LATEST) revision, but can be set to any existing version or alias. See https;//docs.aws.amazon.com/lambda/latest/dg/versioning-aliases.html for details.\n attribute :version_qualifier\n validates :version_qualifier, type: String\n\n # @return [Object, nil] A dictionary in any form to be provided as input to the Lambda function.\n attribute :payload\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7050676941871643, "alphanum_fraction": 0.7088448405265808, "avg_line_length": 63.836734771728516, "blob_id": "8668da3aed23e21726d17757ca717f686e9a2876", "content_id": "3ab2cc2eb05db2f42f3c72b1423b33e334b1bff5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3177, "license_type": "permissive", "max_line_length": 394, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/windows/win_eventlog.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows the addition, clearing and removal of local Windows event logs, and the creation and removal of sources from a given event log. Also allows the specification of settings per log and source.\n class Win_eventlog < Base\n # @return [String] Name of the event log to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :clear, :present, nil] Desired state of the log and/or sources.,When C(sources) is populated, state is checked for sources.,When C(sources) is not populated, state is checked for the specified log itself.,If C(state) is C(clear), event log entries are cleared for the target log.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :clear, :present], :message=>\"%{value} needs to be :absent, :clear, :present\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] A list of one or more sources to ensure are present/absent in the log.,When C(category_file), C(message_file) and/or C(parameter_file) are specified, these values are applied across all sources.\n attribute :sources\n validates :sources, type: TypeGeneric.new(String)\n\n # @return [String, nil] For one or more sources specified, the path to a custom category resource file.\n attribute :category_file\n validates :category_file, type: String\n\n # @return [String, nil] For one or more sources specified, the path to a custom event message resource file.\n attribute :message_file\n validates :message_file, type: String\n\n # @return [String, nil] For one or more sources specified, the path to a custom parameter resource file.\n attribute :parameter_file\n validates :parameter_file, type: String\n\n # @return [String, nil] The maximum size of the event log.,Value must be between 64KB and 4GB, and divisible by 64KB.,Size can be specified in KB, MB or GB (e.g. 128KB, 16MB, 2.5GB).\n attribute :maximum_size\n validates :maximum_size, type: String\n\n # @return [:OverwriteOlder, :OverwriteAsNeeded, :DoNotOverwrite, nil] The action for the log to take once it reaches its maximum size.,For C(OverwriteOlder), new log entries overwrite those older than the C(retention_days) value.,For C(OverwriteAsNeeded), each new entry overwrites the oldest entry.,For C(DoNotOverwrite), all existing entries are kept and new entries are not retained.\n attribute :overflow_action\n validates :overflow_action, expression_inclusion: {:in=>[:OverwriteOlder, :OverwriteAsNeeded, :DoNotOverwrite], :message=>\"%{value} needs to be :OverwriteOlder, :OverwriteAsNeeded, :DoNotOverwrite\"}, allow_nil: true\n\n # @return [Integer, nil] The minimum number of days event entries must remain in the log.,This option is only used when C(overflow_action) is C(OverwriteOlder).\n attribute :retention_days\n validates :retention_days, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6470957398414612, "alphanum_fraction": 0.6477237343788147, "avg_line_length": 44.5, "blob_id": "8d51da0043d6c7add379cef7559e534745f07602", "content_id": "ae106925fb23965d2b9967eb9d0fef405d4fbd41", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3185, "license_type": "permissive", "max_line_length": 165, "num_lines": 70, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_firewall.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates and removes firewall rules.\n class Cs_firewall < Base\n # @return [String, nil] Public IP address the ingress rule is assigned to.,Required if C(type=ingress).\n attribute :ip_address\n validates :ip_address, type: String\n\n # @return [String, nil] Network the egress rule is related to.,Required if C(type=egress).\n attribute :network\n validates :network, type: String\n\n # @return [:present, :absent, nil] State of the firewall rule.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:ingress, :egress, nil] Type of the firewall rule.\n attribute :type\n validates :type, expression_inclusion: {:in=>[:ingress, :egress], :message=>\"%{value} needs to be :ingress, :egress\"}, allow_nil: true\n\n # @return [:tcp, :udp, :icmp, :all, nil] Protocol of the firewall rule.,C(all) is only available if C(type=egress).\n attribute :protocol\n validates :protocol, expression_inclusion: {:in=>[:tcp, :udp, :icmp, :all], :message=>\"%{value} needs to be :tcp, :udp, :icmp, :all\"}, allow_nil: true\n\n # @return [String, nil] List of CIDRs (full notation) to be used for firewall rule.,Since version 2.5, it is a list of CIDR.\n attribute :cidrs\n validates :cidrs, type: String\n\n # @return [Integer, nil] Start port for this rule.,Considered if C(protocol=tcp) or C(protocol=udp).\n attribute :start_port\n validates :start_port, type: Integer\n\n # @return [Integer, nil] End port for this rule. Considered if C(protocol=tcp) or C(protocol=udp).,If not specified, equal C(start_port).\n attribute :end_port\n validates :end_port, type: Integer\n\n # @return [Object, nil] Type of the icmp message being sent.,Considered if C(protocol=icmp).\n attribute :icmp_type\n\n # @return [Object, nil] Error code for this icmp message.,Considered if C(protocol=icmp).\n attribute :icmp_code\n\n # @return [Object, nil] Domain the firewall rule is related to.\n attribute :domain\n\n # @return [Object, nil] Account the firewall rule is related to.\n attribute :account\n\n # @return [Object, nil] Name of the project the firewall rule is related to.\n attribute :project\n\n # @return [Object, nil] Name of the zone in which the virtual machine is in.,If not set, default zone is used.\n attribute :zone\n\n # @return [Boolean, nil] Poll async jobs until job has finished.\n attribute :poll_async\n validates :poll_async, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] List of tags. Tags are a list of dictionaries having keys C(key) and C(value).,To delete all tags, set a empty list e.g. C(tags: []).\n attribute :tags\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.689911961555481, "alphanum_fraction": 0.6932972073554993, "avg_line_length": 51.75, "blob_id": "23e76a834707fe8bc8a7b222642161f7fa90a7dd", "content_id": "17dc1952b75ce253d68f0b95341a5d168309b358", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2954, "license_type": "permissive", "max_line_length": 543, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/notification/mqtt.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Publish a message on an MQTT topic.\n class Mqtt < Base\n # @return [String, nil] MQTT broker address/name\n attribute :server\n validates :server, type: String\n\n # @return [Integer, nil] MQTT broker port number\n attribute :port\n validates :port, type: Integer\n\n # @return [Object, nil] Username to authenticate against the broker.\n attribute :username\n\n # @return [Object, nil] Password for C(username) to authenticate against the broker.\n attribute :password\n\n # @return [String, nil] MQTT client identifier\n attribute :client_id\n validates :client_id, type: String\n\n # @return [String] MQTT topic name\n attribute :topic\n validates :topic, presence: true, type: String\n\n # @return [String] Payload. The special string C(\"None\") may be used to send a NULL (i.e. empty) payload which is useful to simply notify with the I(topic) or to clear previously retained messages.\n attribute :payload\n validates :payload, presence: true, type: String\n\n # @return [0, 1, 2, nil] QoS (Quality of Service)\n attribute :qos\n validates :qos, expression_inclusion: {:in=>[0, 1, 2], :message=>\"%{value} needs to be 0, 1, 2\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Setting this flag causes the broker to retain (i.e. keep) the message so that applications that subsequently subscribe to the topic can received the last retained message immediately.\n attribute :retain\n validates :retain, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] The path to the Certificate Authority certificate files that are to be treated as trusted by this client. If this is the only option given then the client will operate in a similar manner to a web browser. That is to say it will require the broker to have a certificate signed by the Certificate Authorities in ca_certs and will communicate using TLS v1, but will not attempt any form of authentication. This provides basic network encryption but may not be sufficient depending on how the broker is configured.\n attribute :ca_certs\n\n # @return [Object, nil] The path pointing to the PEM encoded client certificate. If this is not None it will be used as client information for TLS based authentication. Support for this feature is broker dependent.\n attribute :certfile\n\n # @return [Object, nil] The path pointing to the PEM encoded client private key. If this is not None it will be used as client information for TLS based authentication. Support for this feature is broker dependent.\n attribute :keyfile\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6730158925056458, "alphanum_fraction": 0.6730158925056458, "avg_line_length": 29, "blob_id": "0c5a801d5f50b9528f5b0006aa4d55d8ab434262", "content_id": "eb7bec3bee7eb81df0848d88aaf93d629a012f04", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 630, "license_type": "permissive", "max_line_length": 85, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/database/influxdb/influxdb_write.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Write data points into InfluxDB.\n class Influxdb_write < Base\n # @return [Array<Hash>, Hash] Data points as dict to write into the database.\n attribute :data_points\n validates :data_points, presence: true, type: TypeGeneric.new(Hash)\n\n # @return [String] Name of the database.\n attribute :database_name\n validates :database_name, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6539440155029297, "alphanum_fraction": 0.6545801758766174, "avg_line_length": 37.34146499633789, "blob_id": "6de7236246f23ff1931563eaeffad7473de10aea", "content_id": "e0b8a155a476d01903fd02e70a75ee33b3927956", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1572, "license_type": "permissive", "max_line_length": 179, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_vpc_peer.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Read the AWS documentation for VPC Peering Connections U(http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-peering.html)\n class Ec2_vpc_peer < Base\n # @return [String, nil] VPC id of the requesting VPC.\n attribute :vpc_id\n validates :vpc_id, type: String\n\n # @return [String, nil] Peering connection id.\n attribute :peering_id\n validates :peering_id, type: String\n\n # @return [String, nil] Region of the accepting VPC.\n attribute :peer_region\n validates :peer_region, type: String\n\n # @return [String, nil] VPC id of the accepting VPC.\n attribute :peer_vpc_id\n validates :peer_vpc_id, type: String\n\n # @return [Integer, nil] The AWS account number for cross account peering.\n attribute :peer_owner_id\n validates :peer_owner_id, type: Integer\n\n # @return [Hash, nil] Dictionary of tags to look for and apply when creating a Peering Connection.\n attribute :tags\n validates :tags, type: Hash\n\n # @return [:present, :absent, :accept, :reject, nil] Create, delete, accept, reject a peering connection.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :accept, :reject], :message=>\"%{value} needs to be :present, :absent, :accept, :reject\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.6363636255264282, "avg_line_length": 26.310344696044922, "blob_id": "7af9b97650ed12ad7a5df50b137a5d1f7d0e8d49", "content_id": "3006339175a2cf5bb93b45434ef63fb94a55fdbb", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 792, "license_type": "permissive", "max_line_length": 69, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/system/make.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Run targets in a Makefile.\n class Make < Base\n # @return [String, nil] The target to run\n attribute :target\n validates :target, type: String\n\n # @return [Hash, nil] Any extra parameters to pass to make\n attribute :params\n validates :params, type: Hash\n\n # @return [String] cd into this directory before running make\n attribute :chdir\n validates :chdir, presence: true, type: String\n\n # @return [String, nil] Use file as a Makefile\n attribute :file\n validates :file, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6729190945625305, "alphanum_fraction": 0.6799530982971191, "avg_line_length": 39.619049072265625, "blob_id": "3056a6c65d26de1457b7f55d15a6c9176ac0fb54", "content_id": "996be1920832f14f08a0cc8dde0638b9be629e22", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 853, "license_type": "permissive", "max_line_length": 222, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_asg_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gather facts about ec2 Auto Scaling Groups (ASGs) in AWS\n class Ec2_asg_facts < Base\n # @return [String, nil] The prefix or name of the auto scaling group(s) you are searching for.,Note: This is a regular expression match with implicit '^' (beginning of string). Append '$' for a complete name match.\n attribute :name\n validates :name, type: String\n\n # @return [Hash, nil] A dictionary/hash of tags in the format { tag1_name: 'tag1_value', tag2_name: 'tag2_value' } to match against the auto scaling group(s) you are searching for.\\r\\n\n attribute :tags\n validates :tags, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6603773832321167, "alphanum_fraction": 0.6603773832321167, "avg_line_length": 41.400001525878906, "blob_id": "030fdaadb620e5aeaa590d7fe6691bc15495e096", "content_id": "a288124b64eb443c27d57afcdd1b96fa407baf75", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1060, "license_type": "permissive", "max_line_length": 143, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/packaging/os/apt_rpm.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages packages with I(apt-rpm). Both low-level (I(rpm)) and high-level (I(apt-get)) package manager binaries required.\n class Apt_rpm < Base\n # @return [Array<String>, String] name of package to install, upgrade or remove.\n attribute :pkg\n validates :pkg, presence: true, type: TypeGeneric.new(String)\n\n # @return [:absent, :present, nil] Indicates the desired package state.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:yes, :no, nil] update the package database first C(apt-get update).\n attribute :update_cache\n validates :update_cache, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6554307341575623, "alphanum_fraction": 0.6554307341575623, "avg_line_length": 51.44643020629883, "blob_id": "fd82d0d1f1859f22647c8eec9954f7f96b65a7d4", "content_id": "51933f5295e54ad17c7d9469faa94dadf617925e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2937, "license_type": "permissive", "max_line_length": 300, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/net_tools/dnsimple.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages domains and records via the DNSimple API, see the docs: U(http://developer.dnsimple.com/).\n class Dnsimple < Base\n # @return [String, nil] Account email. If omitted, the environment variables C(DNSIMPLE_EMAIL) and C(DNSIMPLE_API_TOKEN) will be looked for.,If those aren't found, a C(.dnsimple) file will be looked for, see: U(https://github.com/mikemaccana/dnsimple-python#getting-started).\n attribute :account_email\n validates :account_email, type: String\n\n # @return [String, nil] Account API token. See I(account_email) for more information.\n attribute :account_api_token\n validates :account_api_token, type: String\n\n # @return [String, nil] Domain to work with. Can be the domain name (e.g. \"mydomain.com\") or the numeric ID of the domain in DNSimple.,If omitted, a list of domains will be returned.,If domain is present but the domain doesn't exist, it will be created.\n attribute :domain\n validates :domain, type: String\n\n # @return [String, nil] Record to add, if blank a record for the domain will be created, supports the wildcard (*).\n attribute :record\n validates :record, type: String\n\n # @return [String, nil] List of records to ensure they either exist or do not exist.\n attribute :record_ids\n validates :record_ids, type: String\n\n # @return [:A, :ALIAS, :CNAME, :MX, :SPF, :URL, :TXT, :NS, :SRV, :NAPTR, :PTR, :AAAA, :SSHFP, :HINFO, :POOL, nil] The type of DNS record to create.\n attribute :type\n validates :type, expression_inclusion: {:in=>[:A, :ALIAS, :CNAME, :MX, :SPF, :URL, :TXT, :NS, :SRV, :NAPTR, :PTR, :AAAA, :SSHFP, :HINFO, :POOL], :message=>\"%{value} needs to be :A, :ALIAS, :CNAME, :MX, :SPF, :URL, :TXT, :NS, :SRV, :NAPTR, :PTR, :AAAA, :SSHFP, :HINFO, :POOL\"}, allow_nil: true\n\n # @return [Integer, nil] The TTL to give the new record in seconds.\n attribute :ttl\n validates :ttl, type: Integer\n\n # @return [String, nil] Record value.,Must be specified when trying to ensure a record exists.\n attribute :value\n validates :value, type: String\n\n # @return [Object, nil] Record priority.\n attribute :priority\n\n # @return [:present, :absent, nil] whether the record should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Symbol, nil] Whether the record should be the only one for that record type and record name.,Only use with C(state) is set to C(present) on a record.\n attribute :solo\n validates :solo, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6940509676933289, "alphanum_fraction": 0.6940509676933289, "avg_line_length": 53.30769348144531, "blob_id": "3feb72d64b7ede16859e440bedd6ae7bac12d439", "content_id": "86d1e112b13547247af015924f01d4e999a7131f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2118, "license_type": "permissive", "max_line_length": 266, "num_lines": 39, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_postgresqldatabase.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and delete instance of PostgreSQL Database.\n class Azure_rm_postgresqldatabase < Base\n # @return [String] The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] The name of the server.\n attribute :server_name\n validates :server_name, presence: true, type: String\n\n # @return [String] The name of the database.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] The charset of the database. Check PostgreSQL documentation for possible values.,This is only set on creation, use I(force_update) to recreate a database if the values don't match.\n attribute :charset\n\n # @return [Object, nil] The collation of the database. Check PostgreSQL documentation for possible values.,This is only set on creation, use I(force_update) to recreate a database if the values don't match.\n attribute :collation\n\n # @return [:yes, :no, nil] When set to C(true), will delete and recreate the existing PostgreSQL database if any of the properties don't match what is set.,When set to C(false), no change will occur to the database even if any of the properties do not match.\n attribute :force_update\n validates :force_update, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:absent, :present, nil] Assert the state of the PostgreSQL database. Use 'present' to create or update a database and 'absent' to delete it.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6920803785324097, "alphanum_fraction": 0.6920803785324097, "avg_line_length": 47.342857360839844, "blob_id": "9c891dc5734ecfb062e4941e246171c433c056a2", "content_id": "3ff27af071580d47d611cc190eb5a2dc18e51fe3", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1692, "license_type": "permissive", "max_line_length": 198, "num_lines": 35, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_guest_custom_attributes.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to add, remove and update custom attributes for the given virtual machine.\n class Vmware_guest_custom_attributes < Base\n # @return [Object] Name of the virtual machine to work with.\n attribute :name\n validates :name, presence: true\n\n # @return [:present, :absent, nil] The action to take.,If set to C(present), then custom attribute is added or updated.,If set to C(absent), then custom attribute is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] UUID of the virtual machine to manage if known. This is VMware's unique identifier.,This is required parameter, if C(name) is not supplied.\n attribute :uuid\n validates :uuid, type: String\n\n # @return [Object, nil] Absolute path to find an existing guest.,This is required parameter, if C(name) is supplied and multiple virtual machines with same name are found.\n attribute :folder\n\n # @return [Object] Datacenter name where the virtual machine is located in.\n attribute :datacenter\n validates :datacenter, presence: true\n\n # @return [Object, nil] A list of name and value of custom attributes that needs to be manage.,Value of custom attribute is not required and will be ignored, if C(state) is set to C(absent).\n attribute :attributes\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6769230961799622, "alphanum_fraction": 0.6769230961799622, "avg_line_length": 40.48936080932617, "blob_id": "f20d9456624385a6417bb3cd10355981eaf13ff0", "content_id": "bd698a3f000986dc4753584855d23b50a0f5cb56", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1950, "license_type": "permissive", "max_line_length": 191, "num_lines": 47, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/ansible_tower/tower_workflow_template.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, or destroy Ansible Tower workflows. See U(https://www.ansible.com/tower) for an overview.\n class Tower_workflow_template < Base\n # @return [Symbol, nil] If enabled, simultaneous runs of this job template will be allowed.\n attribute :allow_simultaneous\n validates :allow_simultaneous, type: Symbol\n\n # @return [String, nil] The description to use for the workflow.\n attribute :description\n validates :description, type: String\n\n # @return [Object, nil] Extra variables used by Ansible in YAML or key=value format.\\r\\n\n attribute :extra_vars\n\n # @return [String] The name to use for the workflow.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The organization the workflow is linked to.\n attribute :organization\n validates :organization, type: String\n\n # @return [String, nil] The schema is a JSON- or YAML-formatted string defining the hierarchy structure that connects the nodes. Refer to Tower documentation for more information.\\r\\n\n attribute :schema\n validates :schema, type: String\n\n # @return [Symbol, nil] Setting that variable will prompt the user for job type on the workflow launch.\n attribute :survey_enabled\n validates :survey_enabled, type: Symbol\n\n # @return [Object, nil] The definition of the survey associated to the workflow.\n attribute :survey\n\n # @return [:present, :absent, nil] Desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6775280833244324, "alphanum_fraction": 0.6775280833244324, "avg_line_length": 49.85714340209961, "blob_id": "47e6b75a4d269db92eba236b122a821c59fa1f20", "content_id": "c6625d1c5235431c590f771c71f3dfa0a748b61d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1780, "license_type": "permissive", "max_line_length": 262, "num_lines": 35, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_server_actions.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Perform server actions on an existing compute instance from OpenStack. This module does not return any data other than changed true/false. When I(action) is 'rebuild', then I(image) parameter is required.\n class Os_server_action < Base\n # @return [String] Name or ID of the instance\n attribute :server\n validates :server, presence: true, type: String\n\n # @return [:yes, :no, nil] If the module should wait for the instance action to be performed.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] The amount of time the module should wait for the instance to perform the requested action.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [:stop, :start, :pause, :unpause, :lock, :unlock, :suspend, :resume, :rebuild, nil] Perform the given action. The lock and unlock actions always return changed as the servers API does not provide lock status.\n attribute :action\n validates :action, expression_inclusion: {:in=>[:stop, :start, :pause, :unpause, :lock, :unlock, :suspend, :resume, :rebuild], :message=>\"%{value} needs to be :stop, :start, :pause, :unpause, :lock, :unlock, :suspend, :resume, :rebuild\"}, allow_nil: true\n\n # @return [Object, nil] Image the server should be rebuilt with\n attribute :image\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6531736254692078, "alphanum_fraction": 0.658405601978302, "avg_line_length": 54.022727966308594, "blob_id": "5a1f3ebefdb46917318f46a68c5f34f67722315b", "content_id": "b4b7dd265b9775cb8b56af1e785de48aff44f899", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 7263, "license_type": "permissive", "max_line_length": 346, "num_lines": 132, "path": "/lib/ansible/ruby/modules/generated/monitoring/grafana_datasource.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create/update/delete Grafana datasources via API.\n class Grafana_datasource < Base\n # @return [String] The Grafana URL.\n attribute :grafana_url\n validates :grafana_url, presence: true, type: String\n\n # @return [String] The name of the datasource.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:graphite, :prometheus, :elasticsearch, :influxdb, :opentsdb, :mysql, :postgres, :\"alexanderzobnin-zabbix-datasource\"] The type of the datasource.\n attribute :ds_type\n validates :ds_type, presence: true, expression_inclusion: {:in=>[:graphite, :prometheus, :elasticsearch, :influxdb, :opentsdb, :mysql, :postgres, :\"alexanderzobnin-zabbix-datasource\"], :message=>\"%{value} needs to be :graphite, :prometheus, :elasticsearch, :influxdb, :opentsdb, :mysql, :postgres, :\\\"alexanderzobnin-zabbix-datasource\\\"\"}\n\n # @return [String] The URL of the datasource.\n attribute :url\n validates :url, presence: true, type: String\n\n # @return [:direct, :proxy, nil] The access mode for this datasource.\n attribute :access\n validates :access, expression_inclusion: {:in=>[:direct, :proxy], :message=>\"%{value} needs to be :direct, :proxy\"}, allow_nil: true\n\n # @return [String, nil] The Grafana API user.\n attribute :grafana_user\n validates :grafana_user, type: String\n\n # @return [String, nil] The Grafana API password.\n attribute :grafana_password\n validates :grafana_password, type: String\n\n # @return [Object, nil] The Grafana API key.,If set, C(grafana_user) and C(grafana_password) will be ignored.\n attribute :grafana_api_key\n\n # @return [String, nil] Name of the database for the datasource.,This options is required when the C(ds_type) is C(influxdb), C(elasticsearch) (index name), C(mysql) or C(postgres).\n attribute :database\n validates :database, type: String\n\n # @return [Object, nil] The datasource login user for influxdb datasources.\n attribute :user\n\n # @return [Object, nil] The datasource password\n attribute :password\n\n # @return [String, nil] The datasource basic auth user.,Setting this option with basic_auth_password will enable basic auth.\n attribute :basic_auth_user\n validates :basic_auth_user, type: String\n\n # @return [String, nil] The datasource basic auth password, when C(basic auth) is C(yes).\n attribute :basic_auth_password\n validates :basic_auth_password, type: String\n\n # @return [:yes, :no, nil] Whether credentials such as cookies or auth headers should be sent with cross-site requests.\n attribute :with_credentials\n validates :with_credentials, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] The client TLS certificate.,If C(tls_client_cert) and C(tls_client_key) are set, this will enable TLS authentication.,Starts with ----- BEGIN CERTIFICATE -----\n attribute :tls_client_cert\n\n # @return [Object, nil] The client TLS private key,Starts with ----- BEGIN RSA PRIVATE KEY -----\n attribute :tls_client_key\n\n # @return [String, nil] The TLS CA certificate for self signed certificates.,Only used when C(tls_client_cert) and C(tls_client_key) are set.\n attribute :tls_ca_cert\n validates :tls_ca_cert, type: String\n\n # @return [Symbol, nil] Skip the TLS datasource certificate verification.\n attribute :tls_skip_verify\n validates :tls_skip_verify, type: Symbol\n\n # @return [:yes, :no, nil] Make this datasource the default one.\n attribute :is_default\n validates :is_default, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Grafana Organisation ID in which the datasource should be created.,Not used when C(grafana_api_key) is set, because the C(grafana_api_key) only belong to one organisation.\n attribute :org_id\n validates :org_id, type: Integer\n\n # @return [:absent, :present, nil] Status of the datasource\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [2, 5, 56, nil] Elasticsearch version (for C(ds_type = elasticsearch) only),Version 56 is for elasticsearch 5.6+ where tou can specify the C(max_concurrent_shard_requests) option.\n attribute :es_version\n validates :es_version, expression_inclusion: {:in=>[2, 5, 56], :message=>\"%{value} needs to be 2, 5, 56\"}, allow_nil: true\n\n # @return [Integer, nil] Starting with elasticsearch 5.6, you can specify the max concurrent shard per requests.\n attribute :max_concurrent_shard_requests\n validates :max_concurrent_shard_requests, type: Integer\n\n # @return [String, nil] Name of the time field in elasticsearch ds.,For example C(@timestamp)\n attribute :time_field\n validates :time_field, type: String\n\n # @return [String, nil] Minimum group by interval for C(influxdb) or C(elasticsearch) datasources.,for example C(>10s)\n attribute :time_interval\n validates :time_interval, type: String\n\n # @return [:\"\", :Hourly, :Daily, :Weekly, :Monthly, :Yearly, nil] For elasticsearch C(ds_type), this is the index pattern used.\n attribute :interval\n validates :interval, expression_inclusion: {:in=>[:\"\", :Hourly, :Daily, :Weekly, :Monthly, :Yearly], :message=>\"%{value} needs to be :\\\"\\\", :Hourly, :Daily, :Weekly, :Monthly, :Yearly\"}, allow_nil: true\n\n # @return [1, 2, 3, nil] The opentsdb version.,Use C(1) for <=2.1, C(2) for ==2.2, C(3) for ==2.3.\n attribute :tsdb_version\n validates :tsdb_version, expression_inclusion: {:in=>[1, 2, 3], :message=>\"%{value} needs to be 1, 2, 3\"}, allow_nil: true\n\n # @return [:millisecond, :second, nil] The opentsdb time resolution.\n attribute :tsdb_resolution\n validates :tsdb_resolution, expression_inclusion: {:in=>[:millisecond, :second], :message=>\"%{value} needs to be :millisecond, :second\"}, allow_nil: true\n\n # @return [:disable, :require, :\"verify-ca\", :\"verify-full\", nil] SSL mode for C(postgres) datasoure type.\n attribute :sslmode\n validates :sslmode, expression_inclusion: {:in=>[:disable, :require, :\"verify-ca\", :\"verify-full\"], :message=>\"%{value} needs to be :disable, :require, :\\\"verify-ca\\\", :\\\"verify-full\\\"\"}, allow_nil: true\n\n # @return [Symbol, nil] Use trends or not for zabbix datasource type\n attribute :trends\n validates :trends, type: Symbol\n\n # @return [:yes, :no, nil] Whether to validate the Grafana certificate.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6730055809020996, "alphanum_fraction": 0.6730055809020996, "avg_line_length": 44.87234115600586, "blob_id": "395c81af3c399e6d6bb8d581792b8ab47f1b94a4", "content_id": "09599edfa3deb732e72f5c71aec0f1a7413554be", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2156, "license_type": "permissive", "max_line_length": 155, "num_lines": 47, "path": "/lib/ansible/ruby/modules/generated/cloud/centurylink/clc_modify_server.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # An Ansible module to modify servers in CenturyLink Cloud.\n class Clc_modify_server < Base\n # @return [Array<String>, String] A list of server Ids to modify.\n attribute :server_ids\n validates :server_ids, presence: true, type: TypeGeneric.new(String)\n\n # @return [Integer, nil] How many CPUs to update on the server\n attribute :cpu\n validates :cpu, type: Integer\n\n # @return [Integer, nil] Memory (in GB) to set to the server.\n attribute :memory\n validates :memory, type: Integer\n\n # @return [Object, nil] The anti affinity policy id to be set for a hyper scale server. This is mutually exclusive with 'anti_affinity_policy_name'\n attribute :anti_affinity_policy_id\n\n # @return [String, nil] The anti affinity policy name to be set for a hyper scale server. This is mutually exclusive with 'anti_affinity_policy_id'\n attribute :anti_affinity_policy_name\n validates :anti_affinity_policy_name, type: String\n\n # @return [Object, nil] The alert policy id to be associated to the server. This is mutually exclusive with 'alert_policy_name'\n attribute :alert_policy_id\n\n # @return [String, nil] The alert policy name to be associated to the server. This is mutually exclusive with 'alert_policy_id'\n attribute :alert_policy_name\n validates :alert_policy_name, type: String\n\n # @return [:present, :absent, nil] The state to insure that the provided resources are in.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Whether to wait for the provisioning tasks to finish before returning.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6988363265991211, "alphanum_fraction": 0.7022498250007629, "avg_line_length": 68.30107879638672, "blob_id": "6f85a72f137f71b956854b309f13fcb4ab07ca75", "content_id": "b3684d46315bdd4b9493a1bca33c39d8ea0a3ff2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6445, "license_type": "permissive", "max_line_length": 625, "num_lines": 93, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_storage_domains.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Module to manage storage domains in oVirt/RHV\n class Ovirt_storage_domain < Base\n # @return [Object, nil] Id of the storage domain to be imported.\n attribute :id\n\n # @return [String, nil] Name of the storage domain to manage. (Not required when state is I(imported))\n attribute :name\n validates :name, type: String\n\n # @return [:present, :absent, :maintenance, :unattached, :imported, :update_ovf_store, nil] Should the storage domain be present/absent/maintenance/unattached/imported/update_ovf_store,I(imported) is supported since version 2.4.,I(update_ovf_store) is supported since version 2.5, currently if C(wait) is (true), we don't wait for update.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :maintenance, :unattached, :imported, :update_ovf_store], :message=>\"%{value} needs to be :present, :absent, :maintenance, :unattached, :imported, :update_ovf_store\"}, allow_nil: true\n\n # @return [Object, nil] Description of the storage domain.\n attribute :description\n\n # @return [Object, nil] Comment of the storage domain.\n attribute :comment\n\n # @return [String, Integer, nil] Data center name where storage domain should be attached.,This parameter isn't idempotent, it's not possible to change data center of storage domain.\n attribute :data_center\n validates :data_center, type: MultipleTypes.new(String, Integer)\n\n # @return [:data, :iso, :export, nil] Function of the storage domain.,This parameter isn't idempotent, it's not possible to change domain function of storage domain.\n attribute :domain_function\n validates :domain_function, expression_inclusion: {:in=>[:data, :iso, :export], :message=>\"%{value} needs to be :data, :iso, :export\"}, allow_nil: true\n\n # @return [String, nil] Host to be used to mount storage.\n attribute :host\n validates :host, type: String\n\n # @return [Hash, nil] Dictionary with values for localfs storage type:,C(path) - Path of the mount point. E.g.: /path/to/my/data,Note that these parameters are not idempotent.\n attribute :localfs\n validates :localfs, type: Hash\n\n # @return [Hash, nil] Dictionary with values for NFS storage type:,C(address) - Address of the NFS server. E.g.: myserver.mydomain.com,C(path) - Path of the mount point. E.g.: /path/to/my/data,C(version) - NFS version. One of: I(auto), I(v3), I(v4) or I(v4_1).,C(timeout) - The time in tenths of a second to wait for a response before retrying NFS requests. Range 0 to 65535.,C(retrans) - The number of times to retry a request before attempting further recovery actions. Range 0 to 65535.,C(mount_options) - Option which will be passed when mounting storage.,Note that these parameters are not idempotent.\n attribute :nfs\n validates :nfs, type: Hash\n\n # @return [Hash, nil] Dictionary with values for iSCSI storage type:,C(address) - Address of the iSCSI storage server.,C(port) - Port of the iSCSI storage server.,C(target) - The target IQN for the storage device.,C(lun_id) - LUN id(s).,C(username) - A CHAP user name for logging into a target.,C(password) - A CHAP password for logging into a target.,C(override_luns) - If I(True) ISCSI storage domain luns will be overridden before adding.,C(target_lun_map) - List of dictionary containing targets and LUNs.\",Note that these parameters are not idempotent.,Parameter C(target_lun_map) is supported since Ansible 2.5.\n attribute :iscsi\n validates :iscsi, type: Hash\n\n # @return [Object, nil] Dictionary with values for PosixFS storage type:,C(path) - Path of the mount point. E.g.: /path/to/my/data,C(vfs_type) - Virtual File System type.,C(mount_options) - Option which will be passed when mounting storage.,Note that these parameters are not idempotent.\n attribute :posixfs\n\n # @return [Hash, nil] Dictionary with values for GlusterFS storage type:,C(address) - Address of the Gluster server. E.g.: myserver.mydomain.com,C(path) - Path of the mount point. E.g.: /path/to/my/data,C(mount_options) - Option which will be passed when mounting storage.,Note that these parameters are not idempotent.\n attribute :glusterfs\n validates :glusterfs, type: Hash\n\n # @return [Hash, nil] Dictionary with values for fibre channel storage type:,C(lun_id) - LUN id.,C(override_luns) - If I(True) FCP storage domain LUNs will be overridden before adding.,Note that these parameters are not idempotent.\n attribute :fcp\n validates :fcp, type: Hash\n\n # @return [Symbol, nil] Boolean flag which indicates whether the storage domain should wipe the data after delete.\n attribute :wipe_after_delete\n validates :wipe_after_delete, type: Symbol\n\n # @return [Symbol, nil] Boolean flag which indicates whether the storage domain is configured as backup or not.\n attribute :backup\n validates :backup, type: Symbol\n\n # @return [Integer, nil] Indicates the minimal free space the storage domain should contain in percentages.\n attribute :critical_space_action_blocker\n validates :critical_space_action_blocker, type: Integer\n\n # @return [Integer, nil] Indicates the minimum percentage of a free space in a storage domain to present a warning.\n attribute :warning_low_space\n validates :warning_low_space, type: Integer\n\n # @return [Symbol, nil] Logical remove of the storage domain. If I(true) retains the storage domain's data for import.,This parameter is relevant only when C(state) is I(absent).\n attribute :destroy\n validates :destroy, type: Symbol\n\n # @return [Symbol, nil] If I(True) storage domain will be formatted after removing it from oVirt/RHV.,This parameter is relevant only when C(state) is I(absent).\n attribute :format\n validates :format, type: Symbol\n\n # @return [Symbol, nil] If I(True) storage domain blocks will be discarded upon deletion. Enabled by default.,This parameter is relevant only for block based storage domains.\n attribute :discard_after_delete\n validates :discard_after_delete, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7141104340553284, "alphanum_fraction": 0.7202454209327698, "avg_line_length": 46.94117736816406, "blob_id": "dcf0ba36950e8d57247c8e51d5a14a28efc564ed", "content_id": "47884784ef79c22c9afdb1637b0494562a98ca73", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 815, "license_type": "permissive", "max_line_length": 324, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/system/python_requirements_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Get info about available Python requirements on the target host, including listing required libraries and gathering versions.\n class Python_requirements_facts < Base\n # @return [Array<String>, String, nil] A list of version-likes or module names to check for installation. Supported operators: <, >, <=, >=, or ==. The bare module name like I(ansible), the module with a specific version like I(boto3==1.6.1), or a partial version like I(requests>2) are all valid specifications.\\r\\n\n attribute :dependencies\n validates :dependencies, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7285921573638916, "alphanum_fraction": 0.7285921573638916, "avg_line_length": 42.0625, "blob_id": "496413c95041b8fdae41ab6d5f8ae8903459aa1c", "content_id": "7a19f9711f8874e87f365af91fb82c482e9f5c49", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 689, "license_type": "permissive", "max_line_length": 289, "num_lines": 16, "path": "/lib/ansible/ruby/modules/generated/utilities/logic/import_tasks.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Imports a list of tasks to be added to the current playbook for subsequent execution.\n class Import_tasks < Base\n # @return [Object, nil] The name of the imported file is specified directly without any other option.,Most keywords, including loops and conditionals, only applied to the imported tasks, not to this statement itself. If you need any of those to apply, use M(include_tasks) instead.\n attribute :free_form, original_name: 'free-form'\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6822503209114075, "alphanum_fraction": 0.6901912689208984, "avg_line_length": 84.97115325927734, "blob_id": "e90975cb1026c9b07c922e7d498620a5648aeeab", "content_id": "3a4ebed3ea379645790a60fe7592898c72a5c8ee", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 17882, "license_type": "permissive", "max_line_length": 386, "num_lines": 208, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_bgp_af.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages BGP Address-family configurations on HUAWEI CloudEngine switches.\n class Ce_bgp_af < Base\n # @return [:present, :absent, nil] Specify desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object] Name of a BGP instance. The name is a case-sensitive string of characters. The BGP instance can be used only after the corresponding VPN instance is created. The value is a string of 1 to 31 case-sensitive characters.\n attribute :vrf_name\n validates :vrf_name, presence: true\n\n # @return [:ipv4uni, :ipv4multi, :ipv4vpn, :ipv6uni, :ipv6vpn, :evpn] Address family type of a BGP instance.\n attribute :af_type\n validates :af_type, presence: true, expression_inclusion: {:in=>[:ipv4uni, :ipv4multi, :ipv4vpn, :ipv6uni, :ipv6vpn, :evpn], :message=>\"%{value} needs to be :ipv4uni, :ipv4multi, :ipv4vpn, :ipv6uni, :ipv6vpn, :evpn\"}\n\n # @return [Object, nil] Specify the maximum number of equal-cost IBGP routes. The value is an integer ranging from 1 to 65535.\n attribute :max_load_ibgp_num\n\n # @return [:no_use, :true, :false, nil] If the value is true, the next hop of an advertised route is changed to the advertiser itself in IBGP load-balancing scenarios. If the value is false, the next hop of an advertised route is not changed to the advertiser itself in IBGP load-balancing scenarios.\n attribute :ibgp_ecmp_nexthop_changed\n validates :ibgp_ecmp_nexthop_changed, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [Object, nil] Specify the maximum number of equal-cost EBGP routes. The value is an integer ranging from 1 to 65535.\n attribute :max_load_ebgp_num\n\n # @return [:no_use, :true, :false, nil] If the value is true, the next hop of an advertised route is changed to the advertiser itself in EBGP load-balancing scenarios. If the value is false, the next hop of an advertised route is not changed to the advertiser itself in EBGP load-balancing scenarios.\n attribute :ebgp_ecmp_nexthop_changed\n validates :ebgp_ecmp_nexthop_changed, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [Object, nil] Specify the maximum number of equal-cost routes in the BGP routing table. The value is an integer ranging from 1 to 65535.\n attribute :maximum_load_balance\n\n # @return [:no_use, :true, :false, nil] If the value is true, the next hop of an advertised route is changed to the advertiser itself in BGP load-balancing scenarios. If the value is false, the next hop of an advertised route is not changed to the advertiser itself in BGP load-balancing scenarios.\n attribute :ecmp_nexthop_changed\n validates :ecmp_nexthop_changed, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [Object, nil] Set the Local-Preference attribute. The value is an integer. The value is an integer ranging from 0 to 4294967295.\n attribute :default_local_pref\n\n # @return [Object, nil] Specify the Multi-Exit-Discriminator (MED) of BGP routes. The value is an integer ranging from 0 to 4294967295.\n attribute :default_med\n\n # @return [:no_use, :true, :false, nil] If the value is true, importing default routes to the BGP routing table is allowed. If the value is false, importing default routes to the BGP routing table is not allowed.\n attribute :default_rt_import_enable\n validates :default_rt_import_enable, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [Object, nil] ID of a router that is in IPv4 address format. The value is a string of 0 to 255 characters. The value is in dotted decimal notation.\n attribute :router_id\n\n # @return [:no_use, :true, :false, nil] If the value is true, VPN BGP instances are enabled to automatically select router IDs. If the value is false, VPN BGP instances are disabled from automatically selecting router IDs.\n attribute :vrf_rid_auto_sel\n validates :vrf_rid_auto_sel, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, the third-party next hop function is enabled. If the value is false, the third-party next hop function is disabled.\n attribute :nexthop_third_party\n validates :nexthop_third_party, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, automatic aggregation is enabled for locally imported routes. If the value is false, automatic aggregation is disabled for locally imported routes.\n attribute :summary_automatic\n validates :summary_automatic, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, BGP auto FRR is enabled. If the value is false, BGP auto FRR is disabled.\n attribute :auto_frr_enable\n validates :auto_frr_enable, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] Load balancing as path ignore.\n attribute :load_balancing_as_path_ignore\n validates :load_balancing_as_path_ignore, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, BGP routes cannot be advertised to the IP routing table. If the value is false, Routes preferred by BGP are advertised to the IP routing table.\n attribute :rib_only_enable\n validates :rib_only_enable, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [Object, nil] Specify the name of a routing policy. The value is a string of 1 to 40 characters.\n attribute :rib_only_policy_name\n\n # @return [:no_use, :true, :false, nil] If the value is true, BGP is enabled to advertise only optimal routes in the RM to peers. If the value is false, BGP is not enabled to advertise only optimal routes in the RM to peers.\n attribute :active_route_advertise\n validates :active_route_advertise, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, the AS path attribute is ignored when BGP selects an optimal route. If the value is false, the AS path attribute is not ignored when BGP selects an optimal route. An AS path with a smaller length has a higher priority.\n attribute :as_path_neglect\n validates :as_path_neglect, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, when BGP selects an optimal route, the system uses 4294967295 as the MED value of a route if the route's attribute does not carry a MED value. If the value is false, the system uses 0 as the MED value of a route if the route's attribute does not carry a MED value.\n attribute :med_none_as_maximum\n validates :med_none_as_maximum, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, the router ID attribute is ignored when BGP selects the optimal route. If the value is false, the router ID attribute is not ignored when BGP selects the optimal route.\n attribute :router_id_neglect\n validates :router_id_neglect, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, the metrics of next-hop IGP routes are not compared when BGP selects an optimal route. If the value is false, the metrics of next-hop IGP routes are not compared when BGP selects an optimal route. A route with a smaller metric has a higher priority.\n attribute :igp_metric_ignore\n validates :igp_metric_ignore, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, the MEDs of routes learned from peers in different autonomous systems are compared when BGP selects an optimal route. If the value is false, the MEDs of routes learned from peers in different autonomous systems are not compared when BGP selects an optimal route.\n attribute :always_compare_med\n validates :always_compare_med, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, BGP deterministic-MED is enabled. If the value is false, BGP deterministic-MED is disabled.\n attribute :determin_med\n validates :determin_med, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [Object, nil] Set the protocol priority of EBGP routes. The value is an integer ranging from 1 to 255.\n attribute :preference_external\n\n # @return [Object, nil] Set the protocol priority of IBGP routes. The value is an integer ranging from 1 to 255.\n attribute :preference_internal\n\n # @return [Object, nil] Set the protocol priority of a local BGP route. The value is an integer ranging from 1 to 255.\n attribute :preference_local\n\n # @return [Object, nil] Set a routing policy to filter routes so that a configured priority is applied to the routes that match the specified policy. The value is a string of 1 to 40 characters.\n attribute :prefrence_policy_name\n\n # @return [:no_use, :true, :false, nil] If the value is true, route reflection is enabled between clients. If the value is false, route reflection is disabled between clients.\n attribute :reflect_between_client\n validates :reflect_between_client, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [Object, nil] Set a cluster ID. Configuring multiple RRs in a cluster can enhance the stability of the network. The value is an integer ranging from 1 to 4294967295.\n attribute :reflector_cluster_id\n\n # @return [Object, nil] Set a cluster ipv4 address. The value is expressed in the format of an IPv4 address.\n attribute :reflector_cluster_ipv4\n\n # @return [Object, nil] Set the number of the extended community filter supported by an RR group. The value is a string of 1 to 51 characters.\n attribute :rr_filter_number\n\n # @return [:no_use, :true, :false, nil] If the value is true, VPN-Target filtering function is performed for received VPN routes. If the value is false, VPN-Target filtering function is not performed for received VPN routes.\n attribute :policy_vpn_target\n validates :policy_vpn_target, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:default, :dependTunnel, :dependIp, nil] Next hop select depend type.\n attribute :next_hop_sel_depend_type\n validates :next_hop_sel_depend_type, expression_inclusion: {:in=>[:default, :dependTunnel, :dependIp], :message=>\"%{value} needs to be :default, :dependTunnel, :dependIp\"}, allow_nil: true\n\n # @return [Object, nil] Specify the name of a route-policy for route iteration. The value is a string of 1 to 40 characters.\n attribute :nhp_relay_route_policy_name\n\n # @return [:no_use, :true, :false, nil] If the value is true, after the fast EBGP interface awareness function is enabled, EBGP sessions on an interface are deleted immediately when the interface goes Down. If the value is false, after the fast EBGP interface awareness function is enabled, EBGP sessions on an interface are not deleted immediately when the interface goes Down.\n attribute :ebgp_if_sensitive\n validates :ebgp_if_sensitive, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, the route reflector is enabled to modify route path attributes based on an export policy. If the value is false, the route reflector is disabled from modifying route path attributes based on an export policy.\n attribute :reflect_chg_path\n validates :reflect_chg_path, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [Object, nil] Number of Add-Path routes. The value is an integer ranging from 2 to 64.\n attribute :add_path_sel_num\n\n # @return [Object, nil] Route selection delay. The value is an integer ranging from 0 to 3600.\n attribute :route_sel_delay\n\n # @return [:no_use, :true, :false, nil] Allow routes with BGP origin AS validation result Invalid to be selected. If the value is true, invalid routes can participate in route selection. If the value is false, invalid routes cannot participate in route selection.\n attribute :allow_invalid_as\n validates :allow_invalid_as, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, modifying extended community attributes is allowed. If the value is false, modifying extended community attributes is not allowed.\n attribute :policy_ext_comm_enable\n validates :policy_ext_comm_enable, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, the function to advertise supernetwork unicast routes is enabled. If the value is false, the function to advertise supernetwork unicast routes is disabled.\n attribute :supernet_uni_adv\n validates :supernet_uni_adv, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, the function to advertise supernetwork label is enabled. If the value is false, the function to advertise supernetwork label is disabled.\n attribute :supernet_label_adv\n validates :supernet_label_adv, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [Object, nil] Ingress lsp policy name.\n attribute :ingress_lsp_policy_name\n\n # @return [:no_use, :true, :false, nil] Originator prior.\n attribute :originator_prior\n validates :originator_prior, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, enable reduce priority to advertise route. If the value is false, disable reduce priority to advertise route.\n attribute :lowest_priority\n validates :lowest_priority, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, relay delay enable. If the value is false, relay delay disable.\n attribute :relay_delay_enable\n validates :relay_delay_enable, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:direct, :ospf, :isis, :static, :rip, :ospfv3, :ripng, nil] Routing protocol from which routes can be imported.\n attribute :import_protocol\n validates :import_protocol, expression_inclusion: {:in=>[:direct, :ospf, :isis, :static, :rip, :ospfv3, :ripng], :message=>\"%{value} needs to be :direct, :ospf, :isis, :static, :rip, :ospfv3, :ripng\"}, allow_nil: true\n\n # @return [Object, nil] Process ID of an imported routing protocol. The value is an integer ranging from 0 to 4294967295.\n attribute :import_process_id\n\n # @return [Object, nil] Specify the IP address advertised by BGP. The value is a string of 0 to 255 characters.\n attribute :network_address\n\n # @return [Object, nil] Specify the mask length of an IP address. The value is an integer ranging from 0 to 128.\n attribute :mask_len\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6339700818061829, "alphanum_fraction": 0.6546205282211304, "avg_line_length": 57.69696807861328, "blob_id": "1853f1e4c860a913806245a6b95fd218b36460c5", "content_id": "a05e550f9423d82360633d3868b0da5d69a9015e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1937, "license_type": "permissive", "max_line_length": 329, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/system/filesystem.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module creates a filesystem.\n class Filesystem < Base\n # @return [:btrfs, :ext2, :ext3, :ext4, :ext4dev, :f2fs, :lvm, :ocfs2, :reiserfs, :xfs, :vfat] Filesystem type to be created.,reiserfs support was added in 2.2.,lvm support was added in 2.5.,since 2.5, I(dev) can be an image file.,vfat support was added in 2.5,ocfs2 support was added in 2.6,f2fs support was added in 2.7\n attribute :fstype\n validates :fstype, presence: true, expression_inclusion: {:in=>[:btrfs, :ext2, :ext3, :ext4, :ext4dev, :f2fs, :lvm, :ocfs2, :reiserfs, :xfs, :vfat], :message=>\"%{value} needs to be :btrfs, :ext2, :ext3, :ext4, :ext4dev, :f2fs, :lvm, :ocfs2, :reiserfs, :xfs, :vfat\"}\n\n # @return [String] Target path to device or image file.\n attribute :dev\n validates :dev, presence: true, type: String\n\n # @return [:yes, :no, nil] If C(yes), allows to create new filesystem on devices that already has filesystem.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(yes), if the block device and filesytem size differ, grow the filesystem into the space.,Supported for C(ext2), C(ext3), C(ext4), C(ext4dev), C(f2fs), C(lvm), C(xfs) and C(vfat) filesystems.,XFS Will only grow if mounted.,vFAT will likely fail if fatresize < 1.04.\n attribute :resizefs\n validates :resizefs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] List of options to be passed to mkfs command.\n attribute :opts\n validates :opts, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.674924910068512, "alphanum_fraction": 0.674924910068512, "avg_line_length": 39.3636360168457, "blob_id": "6fc9a7d92da003211d9b64818e7c68f6df02ccfc", "content_id": "0dcfe5aed0a5422aab9870aabc2ffb092535326d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1332, "license_type": "permissive", "max_line_length": 188, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/storage/infinidat/infini_export.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module creates, deletes or modifies NFS exports on Infinibox.\n class Infini_export < Base\n # @return [String] Export name. Should always start with C(/). (ex. name=/data)\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Creates/Modifies export when present and removes when absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Internal path of the export.\n attribute :inner_path\n validates :inner_path, type: String\n\n # @return [Array<String>, String, nil] List of dictionaries with client entries. See examples. Check infini_export_client module to modify individual NFS client entries for export.\n attribute :client_list\n validates :client_list, type: TypeGeneric.new(String)\n\n # @return [String] Name of exported file system.\n attribute :filesystem\n validates :filesystem, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6427657008171082, "alphanum_fraction": 0.6427657008171082, "avg_line_length": 32.956520080566406, "blob_id": "8fecf1c739cd91997e34da13f938fe98047e1b3e", "content_id": "63d4ccdca421cd47a40ff9e92e9188810a9af454", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1562, "license_type": "permissive", "max_line_length": 143, "num_lines": 46, "path": "/lib/ansible/ruby/modules/generated/database/postgresql/postgresql_schema.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove PostgreSQL schema from a remote host.\n class Postgresql_schema < Base\n # @return [String] Name of the schema to add or remove.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Name of the database to connect to.\n attribute :database\n validates :database, type: String\n\n # @return [Object, nil] The username used to authenticate with.\n attribute :login_user\n\n # @return [Object, nil] The password used to authenticate with.\n attribute :login_password\n\n # @return [String, nil] Host running the database.\n attribute :login_host\n validates :login_host, type: String\n\n # @return [Object, nil] Path to a Unix domain socket for local connections.\n attribute :login_unix_socket\n\n # @return [String, nil] Name of the role to set as owner of the schema.\n attribute :owner\n validates :owner, type: String\n\n # @return [Integer, nil] Database port to connect to.\n attribute :port\n validates :port, type: Integer\n\n # @return [:present, :absent, nil] The schema state.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6612331867218018, "alphanum_fraction": 0.6612331867218018, "avg_line_length": 50.30908966064453, "blob_id": "efa83cf96bcf96765942b5399e3393d7e450d2f4", "content_id": "687dfbab896cd6ee30af31800182c5b7fa57ac16", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2822, "license_type": "permissive", "max_line_length": 213, "num_lines": 55, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/netapp_e_flashcache.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or remove SSD caches on a NetApp E-Series storage array.\n class Netapp_e_flashcache < Base\n # @return [String] The username to authenticate with the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_username\n validates :api_username, presence: true, type: String\n\n # @return [String] The password to authenticate with the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_password\n validates :api_password, presence: true, type: String\n\n # @return [String] The url to the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_url\n validates :api_url, presence: true, type: String\n\n # @return [Boolean, nil] Should https certificates be validated?\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String] The ID of the array to manage (as configured on the web services proxy).\n attribute :ssid\n validates :ssid, presence: true, type: String\n\n # @return [:present, :absent] Whether the specified SSD cache should exist or not.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String] The name of the SSD cache to manage\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:filesystem, :database, :media, nil] The type of workload to optimize the cache for.\n attribute :io_type\n validates :io_type, expression_inclusion: {:in=>[:filesystem, :database, :media], :message=>\"%{value} needs to be :filesystem, :database, :media\"}, allow_nil: true\n\n # @return [Object, nil] The minimum number of disks to use for building the cache. The cache will be expanded if this number exceeds the number of disks already in place\n attribute :disk_count\n\n # @return [:bytes, :b, :kb, :mb, :gb, :tb, :pb, :eb, :zb, :yb, nil] The unit to be applied to size arguments\n attribute :size_unit\n validates :size_unit, expression_inclusion: {:in=>[:bytes, :b, :kb, :mb, :gb, :tb, :pb, :eb, :zb, :yb], :message=>\"%{value} needs to be :bytes, :b, :kb, :mb, :gb, :tb, :pb, :eb, :zb, :yb\"}, allow_nil: true\n\n # @return [Object, nil] The minimum size (in size_units) of the ssd cache. The cache will be expanded if this exceeds the current size of the cache.\n attribute :cache_size_min\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6764490008354187, "alphanum_fraction": 0.6764490008354187, "avg_line_length": 41.59375, "blob_id": "793a62e19b7095beb207926fe01d4a9188ef9aa3", "content_id": "cc195eb7ac238b73f94a9e14ad1e0d4e89580195", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1363, "license_type": "permissive", "max_line_length": 175, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/network/bigswitch/bigmon_chain.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create and remove a bigmon inline service chain.\n class Bigmon_chain < Base\n # @return [String] The name of the chain.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Whether the service chain should be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The controller IP address.\n attribute :controller\n validates :controller, presence: true, type: String\n\n # @return [Boolean, nil] If C(false), SSL certificates will not be validated. This should only be used on personally controlled devices using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] Bigmon access token. If this isn't set, the environment variable C(BIGSWITCH_ACCESS_TOKEN) is used.\n attribute :access_token\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6844863891601562, "alphanum_fraction": 0.6850104928016663, "avg_line_length": 45.53658676147461, "blob_id": "b11772dd6ef5b345772a4545495851c6048c0b43", "content_id": "45828a64f78dabb6e0dd554e453ce22f7325fb8c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1908, "license_type": "permissive", "max_line_length": 232, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/jenkins_script.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The C(jenkins_script) module takes a script plus a dict of values to use within the script and returns the result of the script being run.\n class Jenkins_script < Base\n # @return [String] The groovy script to be executed. This gets passed as a string Template if args is defined.\n attribute :script\n validates :script, presence: true, type: String\n\n # @return [String, nil] The jenkins server to execute the script against. The default is a local jenkins instance that is not being proxied through a webserver.\n attribute :url\n validates :url, type: String\n\n # @return [:yes, :no, nil] If set to C(no), the SSL certificates will not be validated. This should only set to C(no) used on personally controlled sites using self-signed certificates as it avoids verifying the source site.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] The username to connect to the jenkins server with.\n attribute :user\n validates :user, type: String\n\n # @return [String, nil] The password to connect to the jenkins server with.\n attribute :password\n validates :password, type: String\n\n # @return [Integer, nil] The request timeout in seconds\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [Hash, nil] A dict of key-value pairs used in formatting the script using string.Template (see https://docs.python.org/2/library/string.html#template-strings).\n attribute :args\n validates :args, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6956865787506104, "alphanum_fraction": 0.6956865787506104, "avg_line_length": 57.76744079589844, "blob_id": "26aa65fdb5d9ae3ed719dc6c986e03e74e9cd1b3", "content_id": "91b677a38700c4ea54a5fbad76a2c800246c3e23", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2527, "license_type": "permissive", "max_line_length": 368, "num_lines": 43, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_securitygroup.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update or delete a network security group. A security group contains Access Control List (ACL) rules that allow or deny network traffic to subnets or individual network interfaces. A security group is created with a set of default security rules and an empty set of security rules. Shape traffic flow by adding rules to the empty set of security rules.\n class Azure_rm_securitygroup < Base\n # @return [Object, nil] The set of default rules automatically added to a security group at creation. In general default rules will not be modified. Modify rules to shape the flow of traffic to or from a subnet or NIC. See rules below for the makeup of a rule dict.\n attribute :default_rules\n\n # @return [Object, nil] Valid azure location. Defaults to location of the resource group.\n attribute :location\n\n # @return [String, nil] Name of the security group to operate on.\n attribute :name\n validates :name, type: String\n\n # @return [:yes, :no, nil] Remove any existing rules not matching those defined in the default_rules parameter.\n attribute :purge_default_rules\n validates :purge_default_rules, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Remove any existing rules not matching those defined in the rules parameters.\n attribute :purge_rules\n validates :purge_rules, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String] Name of the resource group the security group belongs to.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [Array<Hash>, Hash, nil] Set of rules shaping traffic flow to or from a subnet or NIC. Each rule is a dictionary.\n attribute :rules\n validates :rules, type: TypeGeneric.new(Hash)\n\n # @return [:absent, :present, nil] Assert the state of the security group. Set to 'present' to create or update a security group. Set to 'absent' to remove a security group.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6685150861740112, "avg_line_length": 38.585365295410156, "blob_id": "bbaef2183decf74701cb0f689434981594efd07f", "content_id": "b2ef9c18b7fd460dafc85aa4b81558e45b2a4fa0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1623, "license_type": "permissive", "max_line_length": 191, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/monitoring/honeybadger_deployment.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Notify Honeybadger.io about app deployments (see http://docs.honeybadger.io/article/188-deployment-tracking)\n class Honeybadger_deployment < Base\n # @return [String] API token.\n attribute :token\n validates :token, presence: true, type: String\n\n # @return [String] The environment name, typically 'production', 'staging', etc.\n attribute :environment\n validates :environment, presence: true, type: String\n\n # @return [String, nil] The username of the person doing the deployment\n attribute :user\n validates :user, type: String\n\n # @return [String, nil] URL of the project repository\n attribute :repo\n validates :repo, type: String\n\n # @return [String, nil] A hash, number, tag, or other identifier showing what revision was deployed\n attribute :revision\n validates :revision, type: String\n\n # @return [String, nil] Optional URL to submit the notification to.\n attribute :url\n validates :url, type: String\n\n # @return [:yes, :no, nil] If C(no), SSL certificates for the target url will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6582880616188049, "alphanum_fraction": 0.65964674949646, "avg_line_length": 39.88888931274414, "blob_id": "4bb30e2e80d335c5657055c0af694b78a191383c", "content_id": "cfd1d00396366eeb6a571a737bf337f5189db0bd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1472, "license_type": "permissive", "max_line_length": 185, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/cloud/rackspace/rax_cbs_attachments.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manipulate Rackspace Cloud Block Storage Volume Attachments\n class Rax_cbs_attachments < Base\n # @return [Object, nil] The device path to attach the volume to, e.g. /dev/xvde.,Before 2.4 this was a required field. Now it can be left to null to auto assign the device name.\n attribute :device\n\n # @return [Object] Name or id of the volume to attach/detach\n attribute :volume\n validates :volume, presence: true\n\n # @return [Object] Name or id of the server to attach/detach\n attribute :server\n validates :server, presence: true\n\n # @return [:present, :absent] Indicate desired state of the resource\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [:yes, :no, nil] wait for the volume to be in 'in-use'/'available' state before returning\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] how long before wait gives up, in seconds\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6565982699394226, "alphanum_fraction": 0.6583577990531921, "avg_line_length": 45.08108139038086, "blob_id": "31f84281c7041e58cfb2bcb53a9ddb494b37e91a", "content_id": "660b78884270680069a7235ec10fe2dbfde8c243", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3410, "license_type": "permissive", "max_line_length": 253, "num_lines": 74, "path": "/lib/ansible/ruby/modules/generated/remote_management/manageiq/manageiq_provider.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The manageiq_provider module supports adding, updating, and deleting provider in ManageIQ.\n class Manageiq_provider < Base\n # @return [:absent, :present, :refresh, nil] absent - provider should not exist, present - provider should be present, refresh - provider will be refreshed\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :refresh], :message=>\"%{value} needs to be :absent, :present, :refresh\"}, allow_nil: true\n\n # @return [String] The provider's name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:Openshift, :Amazon, :oVirt, :VMware, :Azure, :Director, :OpenStack, :GCE] The provider's type.\n attribute :type\n validates :type, presence: true, expression_inclusion: {:in=>[:Openshift, :Amazon, :oVirt, :VMware, :Azure, :Director, :OpenStack, :GCE], :message=>\"%{value} needs to be :Openshift, :Amazon, :oVirt, :VMware, :Azure, :Director, :OpenStack, :GCE\"}\n\n # @return [String, nil] The ManageIQ zone name that will manage the provider.\n attribute :zone\n validates :zone, type: String\n\n # @return [String, nil] The provider region name to connect to (e.g. AWS region for Amazon).\n attribute :provider_region\n validates :provider_region, type: String\n\n # @return [Object, nil] The first port in the host VNC range. defaults to None.\n attribute :host_default_vnc_port_start\n\n # @return [Object, nil] The last port in the host VNC range. defaults to None.\n attribute :host_default_vnc_port_end\n\n # @return [String, nil] Microsoft Azure subscription ID. defaults to None.\n attribute :subscription\n validates :subscription, type: String\n\n # @return [String, nil] Google Compute Engine Project ID. defaults to None.\n attribute :project\n validates :project, type: String\n\n # @return [String, nil] Tenant ID. defaults to None.\n attribute :azure_tenant_id\n validates :azure_tenant_id, type: String\n\n # @return [:yes, :no, nil] Whether to enable mapping of existing tenants. defaults to False.\n attribute :tenant_mapping_enabled\n validates :tenant_mapping_enabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:v2, :v3, nil] The OpenStack Keystone API version. defaults to None.\n attribute :api_version\n validates :api_version, expression_inclusion: {:in=>[:v2, :v3], :message=>\"%{value} needs to be :v2, :v3\"}, allow_nil: true\n\n # @return [Hash, nil] Default endpoint connection information, required if state is true.\n attribute :provider\n validates :provider, type: Hash\n\n # @return [Hash, nil] Metrics endpoint connection information.\n attribute :metrics\n validates :metrics, type: Hash\n\n # @return [Object, nil] Alerts endpoint connection information.\n attribute :alerts\n\n # @return [Hash, nil] SSH key pair used for SSH connections to all hosts in this provider.\n attribute :ssh_keypair\n validates :ssh_keypair, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7081586718559265, "alphanum_fraction": 0.7088035941123962, "avg_line_length": 58.63461685180664, "blob_id": "6b8897455883f9c85caf292e65126fd72e6efc2a", "content_id": "dde87eb2b56fdd9374dfecc93624165c3a3b5d3e", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3101, "license_type": "permissive", "max_line_length": 270, "num_lines": 52, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/netapp_e_volume_copy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create and delete snapshots images on volume groups for NetApp E-series storage arrays.\n class Netapp_e_volume_copy < Base\n # @return [Object] The username to authenticate with the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_username\n validates :api_username, presence: true\n\n # @return [Object] The password to authenticate with the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_password\n validates :api_password, presence: true\n\n # @return [Object] The url to the SANtricity WebServices Proxy or embedded REST API, for example C(https://prod-1.wahoo.acme.com/devmgr/v2).\n attribute :api_url\n validates :api_url, presence: true\n\n # @return [Boolean, nil] Should https certificates be validated?\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] The id of the volume copy source.,If used, must be paired with destination_volume_id,Mutually exclusive with volume_copy_pair_id, and search_volume_id\n attribute :source_volume_id\n\n # @return [Object, nil] The id of the volume copy destination.,If used, must be paired with source_volume_id,Mutually exclusive with volume_copy_pair_id, and search_volume_id\n attribute :destination_volume_id\n\n # @return [Object, nil] The id of a given volume copy pair,Mutually exclusive with destination_volume_id, source_volume_id, and search_volume_id,Can use to delete or check presence of volume pairs,Must specify this or (destination_volume_id and source_volume_id)\n attribute :volume_copy_pair_id\n\n # @return [:present, :absent] Whether the specified volume copy pair should exist or not.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [Boolean, nil] Defines if a copy pair will be created if it does not exist.,If set to True destination_volume_id and source_volume_id are required.\n attribute :create_copy_pair_if_does_not_exist\n validates :create_copy_pair_if_does_not_exist, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] starts a re-copy or stops a copy in progress,Note: If you stop the initial file copy before it it done the copy pair will be destroyed,Requires volume_copy_pair_id\n attribute :start_stop_copy\n\n # @return [Object, nil] Searches for all valid potential target and source volumes that could be used in a copy_pair,Mutually exclusive with volume_copy_pair_id, destination_volume_id and source_volume_id\n attribute :search_volume_id\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6829484701156616, "alphanum_fraction": 0.6829484701156616, "avg_line_length": 39.21428680419922, "blob_id": "1a719a3bb1c181fef044025dca87426a91be4f70", "content_id": "973f6829054e51c77721f646f1f92a367e4b9b9d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1126, "license_type": "permissive", "max_line_length": 176, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_vms_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Retrieve facts about one or more oVirt/RHV virtual machines.\n class Ovirt_vm_facts < Base\n # @return [String, nil] Search term which is accepted by oVirt/RHV search backend.,For example to search VM X from cluster Y use following pattern: name=X and cluster=Y\n attribute :pattern\n validates :pattern, type: String\n\n # @return [Symbol, nil] If I(true) all the attributes of the virtual machines should be included in the response.\n attribute :all_content\n validates :all_content, type: Symbol\n\n # @return [Boolean, nil] If I(true) performed search will take case into account.\n attribute :case_sensitive\n validates :case_sensitive, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] The maximum number of results to return.\n attribute :max\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7000842690467834, "alphanum_fraction": 0.7034540772438049, "avg_line_length": 70.93939208984375, "blob_id": "65ed06b59e51c9614a7688fc94d5a6ba51ff7121", "content_id": "8d20b796366e164806c8616120ed2dd159059fc9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2374, "license_type": "permissive", "max_line_length": 556, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/remote_management/ucs/ucs_lan_connectivity.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configures LAN Connectivity Policies on Cisco UCS Manager.\n # Examples can be used with the UCS Platform Emulator U(https://communities.cisco.com/ucspe).\n class Ucs_lan_connectivity < Base\n # @return [:present, :absent, nil] If C(present), will verify LAN Connectivity Policies are present and will create if needed.,If C(absent), will verify LAN Connectivity Policies are absent and will delete if needed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The name of the LAN Connectivity Policy.,This name can be between 1 and 16 alphanumeric characters.,You cannot use spaces or any special characters other than - (hyphen), \"_\" (underscore), : (colon), and . (period).,You cannot change this name after the policy is created.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] A description of the LAN Connectivity Policy.,Cisco recommends including information about where and when to use the policy.,Enter up to 256 characters.,You can use any characters or spaces except the following:,` (accent mark), (backslash), ^ (carat), \" (double quote), = (equal sign), > (greater than), < (less than), or ' (single quote).\n attribute :description\n\n # @return [Array<Hash>, Hash, nil] List of vNICs used by the LAN Connectivity Policy.,vNICs used by the LAN Connectivity Policy must be created from a vNIC template.,Each list element has the following suboptions:,= name, The name of the vNIC (required).,= vnic_template, The name of the vNIC template (required).,- adapter_policy, The name of the Ethernet adapter policy., A user defined policy can be used, or one of the system defined policies.,- order, String specifying the vNIC assignment order (e.g., '1', '2')., [Default: unspecified]\n attribute :vnic_list\n validates :vnic_list, type: TypeGeneric.new(Hash)\n\n # @return [String, nil] Org dn (distinguished name)\n attribute :org_dn\n validates :org_dn, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6389971971511841, "alphanum_fraction": 0.6445682644844055, "avg_line_length": 34.900001525878906, "blob_id": "2e8454cf46811be96fcb8d1865f1bf93686cf76d", "content_id": "db6433e146312a78fcb9ceea87e14143f281f9ae", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1795, "license_type": "permissive", "max_line_length": 143, "num_lines": 50, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_static_route.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages the static routes on HUAWEI CloudEngine switches.\n class Ce_static_route < Base\n # @return [Object] Destination ip address of static route.\n attribute :prefix\n validates :prefix, presence: true\n\n # @return [Object] Destination ip mask of static route.\n attribute :mask\n validates :mask, presence: true\n\n # @return [:v4, :v6] Destination ip address family type of static route.\n attribute :aftype\n validates :aftype, presence: true, expression_inclusion: {:in=>[:v4, :v6], :message=>\"%{value} needs to be :v4, :v6\"}\n\n # @return [Object, nil] Next hop address of static route.\n attribute :next_hop\n\n # @return [Object, nil] Next hop interface full name of static route.\n attribute :nhp_interface\n\n # @return [Object, nil] VPN instance of destination ip address.\n attribute :vrf\n\n # @return [Object, nil] VPN instance of next hop ip address.\n attribute :destvrf\n\n # @return [Object, nil] Route tag value (numeric).\n attribute :tag\n\n # @return [Object, nil] Name of the route. Used with the name parameter on the CLI.\n attribute :description\n\n # @return [Object, nil] Preference or administrative difference of route (range 1-255).\n attribute :pref\n\n # @return [:present, :absent, nil] Specify desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6959435343742371, "alphanum_fraction": 0.6962962746620178, "avg_line_length": 63.431819915771484, "blob_id": "94a6bfc2ee0ab776736bbf4b67e6a9f1af88d9e9", "content_id": "2271da1547aaa67dc9cbe0d5b0cceda9ad2d9418", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2835, "license_type": "permissive", "max_line_length": 490, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/files/assemble.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Assembles a configuration file from fragments. Often a particular program will take a single configuration file and does not support a C(conf.d) style structure where it is easy to build up the configuration from multiple sources. C(assemble) will take a directory of files that can be local or have already been transferred to the system, and concatenate them together to produce a destination file. Files are assembled in string sorting order. Puppet calls this idea I(fragments).\n class Assemble < Base\n # @return [String] An already existing directory full of source files.\n attribute :src\n validates :src, presence: true, type: String\n\n # @return [String] A file to create using the concatenation of all of the source files.\n attribute :dest\n validates :dest, presence: true, type: String\n\n # @return [:yes, :no, nil] Create a backup file (if C(yes)), including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.\n attribute :backup\n validates :backup, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] A delimiter to separate the file contents.\n attribute :delimiter\n validates :delimiter, type: String\n\n # @return [:yes, :no, nil] If False, it will search for src at originating/master machine, if True it will go to the remote/target machine for the src. Default is True.\n attribute :remote_src\n validates :remote_src, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Assemble files only if C(regex) matches the filename. If not set, all files are assembled. All \"\\\\\" (backslash) must be escaped as \"\\\\\\\\\" to comply yaml syntax. Uses Python regular expressions; see U(http://docs.python.org/2/library/re.html).\n attribute :regexp\n\n # @return [:yes, :no, nil] A boolean that controls if files that start with a '.' will be included or not.\n attribute :ignore_hidden\n validates :ignore_hidden, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] The validation command to run before copying into place. The path to the file to validate is passed in via '%s' which must be present as in the sshd example below. The command is passed securely so shell features like expansion and pipes won't work.\n attribute :validate\n validates :validate, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6776859760284424, "alphanum_fraction": 0.6776859760284424, "avg_line_length": 34.588233947753906, "blob_id": "12ef865bce0b11510064d43090b2b273997a38e5", "content_id": "fc338bb3dc737d0dc8e5a1d1d5873136e6f53631", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 605, "license_type": "permissive", "max_line_length": 145, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/packaging/os/package_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Return information about installed packages as facts\n class Package_facts < Base\n # @return [:auto, :rpm, :apt, nil] The package manager used by the system so we can query the package information\n attribute :manager\n validates :manager, expression_inclusion: {:in=>[:auto, :rpm, :apt], :message=>\"%{value} needs to be :auto, :rpm, :apt\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6964626908302307, "alphanum_fraction": 0.6993308067321777, "avg_line_length": 81.85148620605469, "blob_id": "3beb2097833b5bc9977647bc1ab20d412424c5a9", "content_id": "2faa718b8da70af644c8b9fc1ba29a3ed03713f1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 8368, "license_type": "permissive", "max_line_length": 555, "num_lines": 101, "path": "/lib/ansible/ruby/modules/generated/packaging/os/yum.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Installs, upgrade, downgrades, removes, and lists packages and groups with the I(yum) package manager.\n # This module only works on Python 2. If you require Python 3 support see the M(dnf) module.\n class Yum < Base\n # @return [:auto, :yum, :yum4, :dnf, nil] This module supports C(yum) (as it always has), this is known as C(yum3)/C(YUM3)/C(yum-deprecated) by upstream yum developers. As of Ansible 2.7+, this module also supports C(YUM4), which is the \"new yum\" and it has an C(dnf) backend.,By default, this module will select the backend based on the C(ansible_pkg_mgr) fact.\n attribute :use_backend\n validates :use_backend, expression_inclusion: {:in=>[:auto, :yum, :yum4, :dnf], :message=>\"%{value} needs to be :auto, :yum, :yum4, :dnf\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] A package name or package specifier with version, like C(name-1.0).,If a previous version is specified, the task also needs to turn C(allow_downgrade) on. See the C(allow_downgrade) documentation for caveats with downgrading packages.,When using state=latest, this can be C('*') which means run C(yum -y update).,You can also pass a url or a local path to a rpm file (using state=present). To operate on several packages this can accept a comma separated string of packages or (as of 2.0) a list of packages.\n attribute :name\n validates :name, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] Package name(s) to exclude when state=present, or latest\n attribute :exclude\n validates :exclude, type: TypeGeneric.new(String)\n\n # @return [String, nil] Package name to run the equivalent of yum list <package> against. In addition to listing packages, use can also list the following: C(installed), C(updates), C(available) and C(repos).\n attribute :list\n validates :list, type: String\n\n # @return [:absent, :installed, :latest, :present, :removed, nil] Whether to install (C(present) or C(installed), C(latest)), or remove (C(absent) or C(removed)) a package.,C(present) and C(installed) will simply ensure that a desired package is installed.,C(latest) will update the specified package if it's not of the latest available version.,C(absent) and C(removed) will remove the specified package.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :installed, :latest, :present, :removed], :message=>\"%{value} needs to be :absent, :installed, :latest, :present, :removed\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] I(Repoid) of repositories to enable for the install/update operation. These repos will not persist beyond the transaction. When specifying multiple repos, separate them with a C(\",\").,As of Ansible 2.7, this can alternatively be a list instead of C(\",\") separated string\n attribute :enablerepo\n validates :enablerepo, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] I(Repoid) of repositories to disable for the install/update operation. These repos will not persist beyond the transaction. When specifying multiple repos, separate them with a C(\",\").,As of Ansible 2.7, this can alternatively be a list instead of C(\",\") separated string\n attribute :disablerepo\n validates :disablerepo, type: TypeGeneric.new(String)\n\n # @return [Object, nil] The remote yum configuration file to use for the transaction.\n attribute :conf_file\n\n # @return [:yes, :no, nil] Whether to disable the GPG checking of signatures of packages being installed. Has an effect only if state is I(present) or I(latest).\n attribute :disable_gpg_check\n validates :disable_gpg_check, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Skip packages with broken dependencies(devsolve) and are causing problems.\n attribute :skip_broken\n validates :skip_broken, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Force yum to check if cache is out of date and redownload if needed. Has an effect only if state is I(present) or I(latest).\n attribute :update_cache\n validates :update_cache, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] This only applies if using a https url as the source of the rpm. e.g. for localinstall. If set to C(no), the SSL certificates will not be validated.,This should only set to C(no) used on personally controlled sites using self-signed certificates as it avoids verifying the source site.,Prior to 2.1 the code worked as if this was set to C(yes).\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] When using latest, only update installed packages. Do not install packages.,Has an effect only if state is I(latest)\n attribute :update_only\n validates :update_only, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Specifies an alternative installroot, relative to which all packages will be installed.\n attribute :installroot\n validates :installroot, type: String\n\n # @return [:yes, :no, nil] If set to C(yes), and C(state=latest) then only installs updates that have been marked security related.\n attribute :security\n validates :security, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] If set to C(yes), and C(state=latest) then only installs updates that have been marked bugfix related.\n attribute :bugfix\n validates :bugfix, type: String\n\n # @return [:yes, :no, nil] Specify if the named package and version is allowed to downgrade a maybe already installed higher version of that package. Note that setting allow_downgrade=True can make this module behave in a non-idempotent way. The task could end up with a set of packages that does not match the complete list of specified packages to install (because dependencies between the downgraded package and others can cause changes to the packages which were in the earlier transaction).\n attribute :allow_downgrade\n validates :allow_downgrade, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] I(Plugin) name to enable for the install/update operation. The enabled plugin will not persist beyond the transaction.\n attribute :enable_plugin\n\n # @return [Object, nil] I(Plugin) name to disable for the install/update operation. The disabled plugins will not persist beyond the transaction.\n attribute :disable_plugin\n\n # @return [Object, nil] Specifies an alternative release from which all packages will be installed.\n attribute :releasever\n\n # @return [Symbol, nil] If C(yes), removes all \"leaf\" packages from the system that were originally installed as dependencies of user-installed packages but which are no longer required by any such package. Should be used alone or when state is I(absent),NOTE: This feature requires yum >= 3.4.3 (RHEL/CentOS 7+)\n attribute :autoremove\n validates :autoremove, type: Symbol\n\n # @return [Object, nil] Disable the excludes defined in YUM config files.,If set to C(all), disables all excludes.,If set to C(main), disable excludes defined in [main] in yum.conf.,If set to C(repoid), disable excludes defined for given repo id.\n attribute :disable_excludes\n\n # @return [:yes, :no, nil] Only download the packages, do not install them.\n attribute :download_only\n validates :download_only, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6915032863616943, "alphanum_fraction": 0.6917647123336792, "avg_line_length": 62.75, "blob_id": "92da7783a4ac728ecd481bc871baa720a9887d34", "content_id": "50ed4c04852c69471b1cdd935137397459f92062", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3825, "license_type": "permissive", "max_line_length": 812, "num_lines": 60, "path": "/lib/ansible/ruby/modules/generated/clustering/consul_kv.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows the retrieval, addition, modification and deletion of key/value entries in a consul cluster via the agent. The entire contents of the record, including the indices, flags and session are returned as 'value'.\n # If the key represents a prefix then Note that when a value is removed, the existing value if any is returned as part of the results.\n # See http://www.consul.io/docs/agent/http.html#kv for more details.\n class Consul_kv < Base\n # @return [:absent, :acquire, :present, :release, nil] The action to take with the supplied key and value. If the state is 'present' and `value` is set, the key contents will be set to the value supplied and `changed` will be set to `true` only if the value was different to the current contents. If the state is 'present' and `value` is not set, the existing value associated to the key will be returned. The state 'absent' will remove the key/value pair, again 'changed' will be set to true only if the key actually existed prior to the removal. An attempt can be made to obtain or free the lock associated with a key/value pair with the states 'acquire' or 'release' respectively. a valid session must be supplied to make the attempt changed will be true if the attempt is successful, false otherwise.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :acquire, :present, :release], :message=>\"%{value} needs to be :absent, :acquire, :present, :release\"}, allow_nil: true\n\n # @return [String] The key at which the value should be stored.\n attribute :key\n validates :key, presence: true, type: String\n\n # @return [String, Integer] The value should be associated with the given key, required if C(state) is C(present).\n attribute :value\n validates :value, presence: true, type: MultipleTypes.new(String, Integer)\n\n # @return [:yes, :no, nil] If the key represents a prefix, each entry with the prefix can be retrieved by setting this to C(yes).\n attribute :recurse\n validates :recurse, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] The session that should be used to acquire or release a lock associated with a key/value pair.\n attribute :session\n validates :session, type: String\n\n # @return [Object, nil] The token key indentifying an ACL rule set that controls access to the key value pair\n attribute :token\n\n # @return [Object, nil] Used when acquiring a lock with a session. If the C(cas) is C(0), then Consul will only put the key if it does not already exist. If the C(cas) value is non-zero, then the key is only set if the index matches the ModifyIndex of that key.\n attribute :cas\n\n # @return [Object, nil] Opaque integer value that can be passed when setting a value.\n attribute :flags\n\n # @return [String, nil] Host of the consul agent.\n attribute :host\n validates :host, type: String\n\n # @return [Integer, nil] The port on which the consul agent is running.\n attribute :port\n validates :port, type: Integer\n\n # @return [String, nil] The protocol scheme on which the consul agent is running.\n attribute :scheme\n validates :scheme, type: String\n\n # @return [:yes, :no, nil] Whether to verify the tls certificate of the consul agent.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7041343450546265, "alphanum_fraction": 0.7077519297599792, "avg_line_length": 60.42856979370117, "blob_id": "5104780e8e1c200d1a9aa0443e3fb0a657a677bf", "content_id": "2ed5ac31ca394b2d4ec048ba1399ee5f49ade6f3", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3870, "license_type": "permissive", "max_line_length": 498, "num_lines": 63, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_monitor_https.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages F5 BIG-IP LTM https monitors.\n class Bigip_monitor_https < Base\n # @return [String] Monitor name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] The description of the monitor.\n attribute :description\n\n # @return [String, nil] The parent template of this monitor template. Once this value has been set, it cannot be changed. By default, this value is the C(https) parent on the C(Common) partition.\n attribute :parent\n validates :parent, type: String\n\n # @return [Object, nil] The send string for the monitor call. When creating a new monitor, if this value is not provided, the default C(GET /\\\\r\\\\n) will be used.\n attribute :send\n\n # @return [Object, nil] The receive string for the monitor call.\n attribute :receive\n\n # @return [Object, nil] This setting works like C(receive), except that the system marks the node or pool member disabled when its response matches the C(receive_disable) string but not C(receive). To use this setting, you must specify both C(receive_disable) and C(receive).\n attribute :receive_disable\n\n # @return [String, nil] IP address part of the IP/port definition. If this parameter is not provided when creating a new monitor, then the default value will be '*'.\n attribute :ip\n validates :ip, type: String\n\n # @return [Object, nil] Port address part of the IP/port definition. If this parameter is not provided when creating a new monitor, then the default value will be '*'. Note that if specifying an IP address, a value between 1 and 65535 must be specified\n attribute :port\n\n # @return [Object, nil] The interval specifying how frequently the monitor instance of this template will run. If this parameter is not provided when creating a new monitor, then the default value will be 5. This value B(must) be less than the C(timeout) value.\n attribute :interval\n\n # @return [Object, nil] The number of seconds in which the node or service must respond to the monitor request. If the target responds within the set time period, it is considered up. If the target does not respond within the set time period, it is considered down. You can change this number to any number you want, however, it should be 3 times the interval number of seconds plus 1 second. If this parameter is not provided when creating a new monitor, then the default value will be 16.\n attribute :timeout\n\n # @return [Object, nil] Specifies the amount of time in seconds after the first successful response before a node will be marked up. A value of 0 will cause a node to be marked up immediately after a valid response is received from the node. If this parameter is not provided when creating a new monitor, then the default value will be 0.\n attribute :time_until_up\n\n # @return [Object, nil] Specifies the user name, if the monitored target requires authentication.\n attribute :target_username\n\n # @return [Object, nil] Specifies the password, if the monitored target requires authentication.\n attribute :target_password\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [:present, :absent, nil] When C(present), ensures that the monitor exists.,When C(absent), ensures the monitor is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6641176342964172, "alphanum_fraction": 0.6644117832183838, "avg_line_length": 57.620689392089844, "blob_id": "471eebbd61eb2a835a379056f7eea1abad63fb8e", "content_id": "ee8022400faaf300a2ca503956c32c9eaed10a6f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6800, "license_type": "permissive", "max_line_length": 567, "num_lines": 116, "path": "/lib/ansible/ruby/modules/generated/files/synchronize.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # C(synchronize) is a wrapper around rsync to make common tasks in your playbooks quick and easy. It is run and originates on the local host where Ansible is being run. Of course, you could just use the C(command) action to call rsync yourself, but you also have to add a fair number of boilerplate options and host facts. C(synchronize) is not intended to provide access to the full power of rsync, but does make the most common invocations easier to implement. You `still` may need to call rsync directly via C(command) or C(shell) depending on your use case.\n class Synchronize < Base\n # @return [String] Path on the source host that will be synchronized to the destination; The path can be absolute or relative.\n attribute :src\n validates :src, presence: true, type: String\n\n # @return [String] Path on the destination host that will be synchronized from the source; The path can be absolute or relative.\n attribute :dest\n validates :dest, presence: true, type: String\n\n # @return [Array<String>, String, nil] Port number for ssh on the destination host. Prior to ansible 2.0, the ansible_ssh_port inventory var took precedence over this value.\n attribute :dest_port\n validates :dest_port, type: TypeGeneric.new(String)\n\n # @return [:pull, :push, nil] Specify the direction of the synchronization. In push mode the localhost or delegate is the source; In pull mode the remote host in context is the source.\n attribute :mode\n validates :mode, expression_inclusion: {:in=>[:pull, :push], :message=>\"%{value} needs to be :pull, :push\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Mirrors the rsync archive flag, enables recursive, links, perms, times, owner, group flags and -D.\n attribute :archive\n validates :archive, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Skip based on checksum, rather than mod-time & size; Note that that \"archive\" option is still enabled by default - the \"checksum\" option will not disable it.\n attribute :checksum\n validates :checksum, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Compress file data during the transfer. In most cases, leave this enabled unless it causes problems.\n attribute :compress\n validates :compress, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Skip creating new files on receiver.\n attribute :existing_only\n validates :existing_only, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Delete files in C(dest) that don't exist (after transfer, not before) in the C(src) path. This option requires C(recursive=yes).\n attribute :delete\n validates :delete, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Transfer directories without recursing\n attribute :dirs\n validates :dirs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Symbol, nil] Recurse into directories.\n attribute :recursive\n validates :recursive, type: Symbol\n\n # @return [Symbol, nil] Copy symlinks as symlinks.\n attribute :links\n validates :links, type: Symbol\n\n # @return [:yes, :no, nil] Copy symlinks as the item that they point to (the referent) is copied, rather than the symlink.\n attribute :copy_links\n validates :copy_links, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Symbol, nil] Preserve permissions.\n attribute :perms\n validates :perms, type: Symbol\n\n # @return [Symbol, nil] Preserve modification times\n attribute :times\n validates :times, type: Symbol\n\n # @return [Symbol, nil] Preserve owner (super user only)\n attribute :owner\n validates :owner, type: Symbol\n\n # @return [Symbol, nil] Preserve group\n attribute :group\n validates :group, type: Symbol\n\n # @return [String, nil] Specify the rsync command to run on the remote host. See C(--rsync-path) on the rsync man page.,To specify the rsync command to run on the local host, you need to set this your task var C(ansible_rsync_path).\n attribute :rsync_path\n validates :rsync_path, type: String\n\n # @return [Integer, nil] Specify a C(--timeout) for the rsync command in seconds.\n attribute :rsync_timeout\n validates :rsync_timeout, type: Integer\n\n # @return [Boolean, nil] put user@ for the remote paths. If you have a custom ssh config to define the remote user for a host that does not match the inventory user, you should set this parameter to \"no\".\n attribute :set_remote_user\n validates :set_remote_user, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Use the ssh_args specified in ansible.cfg\n attribute :use_ssh_args\n validates :use_ssh_args, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] Specify additional rsync options by passing in an array.\n attribute :rsync_opts\n validates :rsync_opts, type: TypeGeneric.new(String)\n\n # @return [:yes, :no, nil] Tells rsync to keep the partial file which should make a subsequent transfer of the rest of the file much faster.\n attribute :partial\n validates :partial, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Verify destination host key.\n attribute :verify_host\n validates :verify_host, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Specify the private key to use for SSH-based rsync connections (e.g. C(~/.ssh/id_rsa))\n attribute :private_key\n\n # @return [String, nil] add a destination to hard link against during the rsync.\n attribute :link_dest\n validates :link_dest, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6902695298194885, "alphanum_fraction": 0.6971219778060913, "avg_line_length": 66.01020050048828, "blob_id": "0248cbfe7d7fa161232a13aa65035819cfa9e510", "content_id": "90d02a64ea6e8bbf705081c92dd50cfb6e5ed973", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6567, "license_type": "permissive", "max_line_length": 593, "num_lines": 98, "path": "/lib/ansible/ruby/modules/generated/monitoring/zabbix/zabbix_host.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows you to create, modify and delete Zabbix host entries and associated group and template data.\n class Zabbix_host < Base\n # @return [String] Name of the host in Zabbix.,host_name is the unique identifier used and cannot be updated using this module.\n attribute :host_name\n validates :host_name, presence: true, type: String\n\n # @return [String, nil] Visible name of the host in Zabbix.\n attribute :visible_name\n validates :visible_name, type: String\n\n # @return [String, nil] Description of the host in Zabbix.\n attribute :description\n validates :description, type: String\n\n # @return [Array<String>, String, nil] List of host groups the host is part of.\n attribute :host_groups\n validates :host_groups, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] List of templates linked to the host.\n attribute :link_templates\n validates :link_templates, type: TypeGeneric.new(String)\n\n # @return [:automatic, :manual, :disabled, nil] Configure the inventory mode.\n attribute :inventory_mode\n validates :inventory_mode, expression_inclusion: {:in=>[:automatic, :manual, :disabled], :message=>\"%{value} needs to be :automatic, :manual, :disabled\"}, allow_nil: true\n\n # @return [Hash, nil] Add Facts for a zabbix inventory (e.g. Tag) (see example below).,Please review the interface documentation for more information on the supported properties,https://www.zabbix.com/documentation/3.2/manual/api/reference/host/object#host_inventory\n attribute :inventory_zabbix\n validates :inventory_zabbix, type: Hash\n\n # @return [:enabled, :disabled, nil] Monitoring status of the host.\n attribute :status\n validates :status, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:present, :absent, nil] State of the host.,On C(present), it will create if host does not exist or update the host if the associated data is different.,On C(absent) will remove a host if it exists.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] The name of the Zabbix proxy to be used.\n attribute :proxy\n validates :proxy, type: String\n\n # @return [Object, nil] List of interfaces to be created for the host (see example below).,Available keys are: I(dns), I(ip), I(main), I(port), I(type), I(useip), and I(bulk).,Please review the interface documentation for more information on the supported properties,https://www.zabbix.com/documentation/2.0/manual/appendix/api/hostinterface/definitions#host_interface,If an interface definition is incomplete, this module will attempt to fill in sensible values.,I(type) can also be C(agent), C(snmp), C(ipmi), or C(jmx) instead of its numerical value.\n attribute :interfaces\n\n # @return [Integer, nil] Specifies what encryption to use for outgoing connections.,Possible values, 1 (no encryption), 2 (PSK), 4 (certificate).,Works only with >= Zabbix 3.0\n attribute :tls_connect\n validates :tls_connect, type: Integer\n\n # @return [Integer, nil] Specifies what types of connections are allowed for incoming connections.,The tls_accept parameter accepts values of 1 to 7,Possible values, 1 (no encryption), 2 (PSK), 4 (certificate).,Values can be combined.,Works only with >= Zabbix 3.0\n attribute :tls_accept\n validates :tls_accept, type: Integer\n\n # @return [String, nil] It is a unique name by which this specific PSK is referred to by Zabbix components,Do not put sensitive information in the PSK identity string, it is transmitted over the network unencrypted.,Works only with >= Zabbix 3.0\n attribute :tls_psk_identity\n validates :tls_psk_identity, type: String\n\n # @return [String, nil] PSK value is a hard to guess string of hexadecimal digits.,The preshared key, at least 32 hex digits. Required if either tls_connect or tls_accept has PSK enabled.,Works only with >= Zabbix 3.0\n attribute :tls_psk\n validates :tls_psk, type: String\n\n # @return [Object, nil] Required certificate issuer.,Works only with >= Zabbix 3.0\n attribute :tls_issuer\n\n # @return [Object, nil] Required certificate subject.,Works only with >= Zabbix 3.0\n attribute :tls_subject\n\n # @return [Integer, nil] IPMI authentication algorithm.,Please review the Host object documentation for more information on the supported properties,https://www.zabbix.com/documentation/3.4/manual/api/reference/host/object,Possible values are, C(0) (none), C(1) (MD2), C(2) (MD5), C(4) (straight), C(5) (OEM), C(6) (RMCP+), with -1 being the API default.,Please note that the Zabbix API will treat absent settings as default when updating any of the I(ipmi_)-options; this means that if you attempt to set any of the four options individually, the rest will be reset to default values.\n attribute :ipmi_authtype\n validates :ipmi_authtype, type: Integer\n\n # @return [Integer, nil] IPMI privilege level.,Please review the Host object documentation for more information on the supported properties,https://www.zabbix.com/documentation/3.4/manual/api/reference/host/object,Possible values are C(1) (callback), C(2) (user), C(3) (operator), C(4) (admin), C(5) (OEM), with C(2) being the API default.,also see the last note in the I(ipmi_authtype) documentation\n attribute :ipmi_privilege\n validates :ipmi_privilege, type: Integer\n\n # @return [String, nil] IPMI username.,also see the last note in the I(ipmi_authtype) documentation\n attribute :ipmi_username\n validates :ipmi_username, type: String\n\n # @return [String, nil] IPMI password.,also see the last note in the I(ipmi_authtype) documentation\n attribute :ipmi_password\n validates :ipmi_password, type: String\n\n # @return [:yes, :no, nil] Overwrite the host configuration, even if already present.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6970033049583435, "alphanum_fraction": 0.698113203048706, "avg_line_length": 41.904762268066406, "blob_id": "8fe9dd02796c60e472ade6e1b22d5307f517e28d", "content_id": "c3c5de9de40e4abdaf5871f4c60a8028d4115c17", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 901, "license_type": "permissive", "max_line_length": 349, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/remote_management/oneview/oneview_san_manager_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Retrieve facts about one or more of the SAN Managers from OneView\n class Oneview_san_manager_facts < Base\n # @return [String, nil] Provider Display Name.\n attribute :provider_display_name\n validates :provider_display_name, type: String\n\n # @return [Hash, nil] List of params to delimit, filter and sort the list of resources.,params allowed: - C(start): The first item to return, using 0-based indexing. - C(count): The number of resources to return. - C(query): A general query string to narrow the list of resources returned. - C(sort): The sort order of the returned data set.\n attribute :params\n validates :params, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.697084903717041, "alphanum_fraction": 0.7059569358825684, "avg_line_length": 51.599998474121094, "blob_id": "0663694a04baee6ad90415c516e2a6f893c2a8e1", "content_id": "ac31aec892a427bc7c10274321d1c29fb08f2e1e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1578, "license_type": "permissive", "max_line_length": 220, "num_lines": 30, "path": "/lib/ansible/ruby/modules/generated/crypto/acme/acme_challenge_cert_helper.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Prepares certificates for ACME challenges such as C(tls-alpn-01).\n # The raw data is provided by the M(acme_certificate) module, and needs to be converted to a certificate to be used for challenge validation. This module provides a simple way to generate the required certificates.\n # The C(tls-alpn-01) implementation is based on L(the draft-05 version of the specification,https://tools.ietf.org/html/draft-ietf-acme-tls-alpn-05).\n class Acme_challenge_cert_helper < Base\n # @return [:\"tls-alpn-01\"] The challenge type.\n attribute :challenge\n validates :challenge, presence: true, expression_inclusion: {:in=>[:\"tls-alpn-01\"], :message=>\"%{value} needs to be :\\\"tls-alpn-01\\\"\"}\n\n # @return [String] The C(challenge_data) entry provided by M(acme_certificate) for the challenge.\n attribute :challenge_data\n validates :challenge_data, presence: true, type: String\n\n # @return [String, nil] Path to a file containing the private key file to use for this challenge certificate.,Mutually exclusive with C(private_key_content).\n attribute :private_key_src\n validates :private_key_src, type: String\n\n # @return [Object, nil] Content of the private key to use for this challenge certificate.,Mutually exclusive with C(private_key_src).\n attribute :private_key_content\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6750972867012024, "alphanum_fraction": 0.6763942837715149, "avg_line_length": 44.35293960571289, "blob_id": "1da3d1b5fae416e7e57f6e719aa4ce4a7e891599", "content_id": "ec2b7619acde6c5fb69a1fce529af4be030d1b8b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1542, "license_type": "permissive", "max_line_length": 198, "num_lines": 34, "path": "/lib/ansible/ruby/modules/generated/storage/purestorage/purefa_pgsnap.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or delete local protection group snapshots on Pure Storage FlashArray.\n # This module only supports local protection groups.\n class Purefa_pgsnap < Base\n # @return [String] The name of the source protection group.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Suffix of snapshot name.\n attribute :suffix\n validates :suffix, type: String\n\n # @return [:absent, :present, :copy, nil] Define whether the protection group snapshot should exist or not. Copy (added in 2.7) will force an overwrite of an exisitng volume from a snapshot.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :copy], :message=>\"%{value} needs to be :absent, :present, :copy\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Define whether to eradicate the snapshot on delete or leave in trash.\n attribute :eradicate\n validates :eradicate, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Restore a specific volume from a protection group snapshot. This implies overwrite of the current full volume. USE WITH CARE!!\n attribute :restore\n validates :restore, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.3726113438606262, "alphanum_fraction": 0.37633997201919556, "avg_line_length": 26.996440887451172, "blob_id": "d32b098a6f254d03e8bd5eccf0535ec1ac5262a1", "content_id": "2807e04f70dc783b98884472457122048df3b607", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 23601, "license_type": "permissive", "max_line_length": 197, "num_lines": 843, "path": "/util/parser/option_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# See LICENSE.txt for license\nrequire 'spec_helper'\nrequire 'ansible-ruby'\nrequire_relative './option'\nrequire_relative '../option_formatter'\n\ndescribe Ansible::Ruby::Parser::Option do\n describe '::parse' do\n subject(:option_data) { Ansible::Ruby::Parser::Option.parse(name, details, example) }\n\n let(:name) { 'login_user' }\n let(:example) { false }\n let(:required) { false }\n let(:default) { nil }\n let(:description) { ['The username used to authenticate with'] }\n let(:choices) { nil }\n let(:type) { nil }\n\n let(:details) do\n {\n description: description,\n required: required,\n default: default,\n choices: choices,\n type: type\n }\n end\n\n context 'optional' do\n context 'yes' do\n it { is_expected.to be_a Ansible::Ruby::Parser::OptionData }\n it do\n is_expected.to have_attributes name: 'login_user',\n required?: false,\n choices: nil\n end\n end\n\n context 'no' do\n let(:required) { true }\n\n it do\n is_expected.to have_attributes name: 'login_user',\n required?: true,\n choices: nil\n end\n end\n end\n\n context 'description' do\n context 'is string' do\n let(:description) { 'The username used to authenticate with' }\n\n it do\n is_expected.to have_attributes description: ['The username used to authenticate with'],\n name: 'login_user'\n end\n end\n\n context 'contains carriage return' do\n let(:description) { [\"The username used to authenticate with \\r\\n something\"] }\n\n it do\n is_expected.to have_attributes description: ['The username used to authenticate with \\\\r\\\\n something'],\n name: 'login_user'\n end\n end\n end\n\n context 'choices' do\n let(:choices) { %w[present absent] }\n let(:default) { 'present' }\n let(:required) { false }\n\n context 'required' do\n let(:required) { true }\n\n it do\n is_expected.to have_attributes name: 'login_user',\n required?: true,\n types: [String],\n choices: %i[present absent]\n end\n end\n\n context 'not required' do\n let(:required) { false }\n\n it do\n is_expected.to have_attributes name: 'login_user',\n required?: false,\n types: [String],\n choices: %i[present absent]\n end\n end\n\n context 'different types' do\n let(:default) { 'abc' }\n let(:choices) { [1, 'abc'] }\n\n it do\n is_expected.to have_attributes name: 'login_user',\n required?: false,\n types: [],\n choices: [1, :abc]\n end\n end\n\n context 'no default' do\n let(:default) { nil }\n\n it do\n is_expected.to have_attributes name: 'login_user',\n required?: false,\n types: [Symbol],\n choices: %i[present absent]\n end\n end\n\n context 'no included' do\n context 'with string' do\n # is really [present, no, yes] in YAML\n let(:choices) { ['present', true, false] }\n\n it do\n is_expected.to have_attributes name: 'login_user',\n required?: false,\n types: [],\n choices: [:present, true, false]\n end\n end\n\n context 'boolean without string' do\n let(:choices) { [true, false] }\n let(:default) { nil }\n\n it do\n is_expected.to have_attributes name: 'login_user',\n required?: false,\n types: [TrueClass, FalseClass],\n choices: [true, false]\n end\n end\n end\n\n context 'integers' do\n let(:choices) { [1, 2, 3] }\n let(:default) { nil }\n\n it do\n is_expected.to have_attributes name: 'login_user',\n required?: false,\n types: [Integer],\n choices: [1, 2, 3]\n end\n end\n\n context 'empty' do\n let(:choices) { [] }\n\n context 'default' do\n let(:default) { 123 }\n\n it do\n is_expected.to have_attributes name: 'login_user',\n required?: false,\n types: [Integer],\n choices: nil\n end\n end\n\n context 'no default' do\n let(:default) { nil }\n\n it do\n is_expected.to have_attributes name: 'login_user',\n required?: false,\n types: [],\n choices: nil\n end\n end\n end\n end\n\n context 'default' do\n { String => 'foo', Integer => 1, Float => 1.5 }.each do |type, value|\n context type do\n let(:default) { value }\n\n it do\n is_expected.to have_attributes name: 'login_user',\n required?: false,\n types: [type],\n choices: nil\n end\n end\n end\n\n context 'None string' do\n let(:default) { 'None' }\n\n it do\n is_expected.to have_attributes name: 'login_user',\n required?: false,\n types: [],\n choices: nil\n end\n end\n\n [true, false].each do |bool_test|\n context bool_test do\n let(:default) { bool_test }\n\n it do\n is_expected.to have_attributes name: 'login_user',\n required?: false,\n choices: [true, false],\n types: include(TrueClass, FalseClass)\n end\n end\n end\n\n context 'flat array' do\n context 'string' do\n let(:default) { 'hello,there' }\n\n it do\n is_expected.to have_attributes name: 'login_user',\n required?: false,\n choices: nil,\n types: [TypeGeneric]\n end\n\n it { is_expected.to have_type_generic String }\n end\n\n context 'integer' do\n let(:default) { '123,456' }\n\n it do\n is_expected.to have_attributes name: 'login_user',\n required?: false,\n choices: nil,\n types: [TypeGeneric]\n end\n\n it { is_expected.to have_type_generic Integer }\n end\n\n context 'float' do\n let(:default) { '123.12,456.89' }\n\n it do\n is_expected.to have_attributes name: 'login_user',\n required?: false,\n choices: nil,\n types: [TypeGeneric]\n end\n\n it { is_expected.to have_type_generic Float }\n end\n end\n\n context 'flat hash' do\n let(:default) { '{\"Name\":\"SuperService-new-AMI\", \"type\":\"SuperService\"}' }\n\n it do\n is_expected.to have_attributes name: 'login_user',\n required?: false,\n choices: nil,\n types: [Hash]\n end\n end\n end\n\n context 'from example' do\n context 'on its own' do\n let(:name) { 'name' }\n let(:example) do\n [\n { 'postgresql_db' => 'name=acme' },\n { 'postgresql_db' => \"name=acme encoding='UTF-8' lc_collate='de_DE.UTF-8' lc_ctype='de_DE.UTF-8' template='template0' else=55\" }\n ]\n end\n\n it do\n is_expected.to have_attributes name: 'name',\n choices: nil,\n types: [String]\n end\n end\n\n context 'list of tasks' do\n let(:name) { 'username' }\n let(:example) do\n {\n 'tasks' => [\n {\n 'name' => 'create stuff',\n 'action' => 'ejabberd_user username=test host=server password=password'\n }\n ]\n }\n end\n\n it do\n is_expected.to have_attributes name: 'username',\n choices: nil,\n types: [String]\n end\n end\n\n context 'false value/no examples' do\n let(:name) { 'name' }\n let(:example) { false }\n\n it do\n is_expected.to have_attributes name: 'name',\n choices: nil,\n types: []\n end\n end\n\n # some are more inline, this is how cloudformation.py is\n context 'list of tasks' do\n let(:name) { 'name' }\n\n let(:example) do\n [\n {\n 'name' => 'some task',\n 'cloudformation' => {\n 'name' => 444.44,\n 'something' => 'else'\n }\n }\n ]\n end\n\n it do\n is_expected.to have_attributes name: 'name',\n choices: nil,\n types: [Float]\n end\n end\n\n context 'Ansible variable' do\n let(:name) { 'name' }\n\n let(:example) do\n [\n {\n 'name' => 'some task',\n 'cloudformation' => {\n 'name' => variable\n }\n }\n ]\n end\n\n context 'normal' do\n let(:variable) { \"{{ lookup('file','policy.json') }}\" }\n\n it do\n is_expected.to have_attributes name: 'name',\n choices: nil,\n types: [String]\n end\n end\n\n context 'leading spaces' do\n let(:variable) { \" {{ lookup('file','policy.json') }}\" }\n\n it do\n is_expected.to have_attributes name: 'name',\n choices: nil,\n types: [String]\n end\n end\n end\n\n context 'mix of hash and inline' do\n let(:name) { 'stack_name' }\n\n let(:example) do\n [\n {\n 'name' => 'some task',\n 'cloudformation' => 'stack_name=\"ansible-cloudformation\" state=present region=us-east-1 disable_rollback=true template_url=https://s3.amazonaws.com/my-bucket/cloudformation.template'\n }\n ]\n end\n\n it do\n is_expected.to have_attributes name: 'stack_name',\n choices: nil,\n types: [String]\n end\n end\n\n context 'play type syntax' do\n let(:name) { 'something' }\n\n let(:example) do\n [\n 'postgresql_db' => {\n 'something' => 450.4,\n 'name' => 'newtest'\n },\n 'register' => 'instance'\n ]\n end\n\n it do\n is_expected.to have_attributes name: 'something',\n choices: nil,\n types: [Float]\n end\n end\n\n context 'hash' do\n let(:name) { 'something' }\n\n let(:example) do\n [\n {\n 'name' => 'some task',\n 'cloudformation' => {\n 'name' => 444.44,\n 'something' => {\n 'setting1' => true\n }\n }\n }\n ]\n end\n\n it do\n is_expected.to have_attributes name: 'something',\n choices: nil,\n types: [Hash]\n end\n end\n\n context 'args' do\n let(:name) { 'something' }\n\n let(:example) do\n [\n {\n 'name' => 'some task',\n 'cloudformation' => 'stack_name=\"ansible-cloudformation\" state=present region=us-east-1 disable_rollback=true template_url=https://s3.amazonaws.com/my-bucket/cloudformation.template',\n 'args' => {\n 'something' => {\n 'setting1' => true\n }\n }\n }\n ]\n end\n\n it do\n is_expected.to have_attributes name: 'something',\n choices: nil,\n types: [Hash]\n end\n end\n\n context 'playbook' do\n let(:name) { 'something' }\n\n let(:example) do\n [\n {\n 'name' => 'some task',\n 'cloudformation' => {\n 'name' => 444.44,\n 'something' => 'else'\n }\n },\n {\n 'name' => 'some task',\n 'become' => true,\n 'gather_facts' => true,\n 'roles' => %w[role1 role2]\n }\n ]\n end\n\n it do\n is_expected.to have_attributes name: 'something',\n choices: nil,\n types: [String]\n end\n end\n\n context 'multiple equals' do\n let(:name) { 'name' }\n\n let(:example) do\n [\n { 'postgresql_db' => 'apt: name=foo=1.00 state=present' }\n ]\n end\n\n it do\n is_expected.to have_attributes name: 'name',\n choices: nil,\n types: [String]\n end\n end\n\n context 'quoted' do\n let(:name) { 'template' }\n let(:example) do\n [\n { 'postgresql_db' => 'name=acme' },\n { 'postgresql_db' => \"name=acme encoding='UTF-8' lc_collate='de_DE.UTF-8' lc_ctype='de_DE.UTF-8' template='template0' else=55\" }\n ]\n end\n\n it do\n is_expected.to have_attributes name: 'template',\n choices: nil,\n types: [String]\n end\n end\n\n context 'flat array' do\n let(:name) { 'name' }\n\n let(:example) do\n [\n { 'postgresql_db' => \"apt: name='12,13' state=present\" }\n ]\n end\n\n it do\n is_expected.to have_attributes name: 'name',\n choices: nil,\n types: [TypeGeneric]\n end\n\n it { is_expected.to have_type_generic Integer }\n end\n\n context 'example has multiple types' do\n let(:name) { 'lines' }\n\n let(:example) do\n [\n {\n 'postgresql_db' => {\n 'lines' => 'hello'\n }\n },\n {\n 'postgresql_db' => {\n 'lines' => 456\n }\n }\n ]\n end\n\n it do\n is_expected.to have_attributes name: 'lines',\n choices: nil,\n types: [String, Integer]\n end\n end\n\n context 'example has array' do\n let(:name) { 'lines' }\n\n context 'array of different types' do\n let(:example) do\n [\n {\n 'postgresql_db' => {\n 'lines' => %w[hello there 123]\n }\n }\n ]\n end\n\n it do\n is_expected.to have_attributes name: 'lines',\n choices: nil,\n types: [TypeGeneric]\n end\n\n it { is_expected.to have_type_generic String }\n end\n\n context 'only array' do\n let(:example) do\n [\n {\n 'postgresql_db' => {\n 'lines' => %w[hello there dude]\n }\n },\n {\n 'postgresql_db' => {\n 'lines' => %w[hello there again]\n }\n }\n ]\n end\n\n it do\n is_expected.to have_attributes name: 'lines',\n choices: nil,\n types: [TypeGeneric]\n end\n\n it { is_expected.to have_type_generic String }\n end\n\n context 'array comes before non-array value' do\n let(:example) do\n [\n {\n 'postgresql_db' => {\n 'lines' => %w[hello there dude]\n }\n },\n {\n 'postgresql_db' => {\n 'lines' => 'howdy'\n }\n }\n ]\n end\n\n it do\n is_expected.to have_attributes name: 'lines',\n choices: nil,\n types: [TypeGeneric]\n end\n\n it { is_expected.to have_type_generic String }\n end\n\n context 'array comes after non-array value' do\n let(:example) do\n [\n {\n 'postgresql_db' => {\n 'lines' => 'howdy'\n }\n },\n {\n 'postgresql_db' => {\n 'lines' => %w[hello there dude]\n }\n }\n ]\n end\n\n it do\n is_expected.to have_attributes name: 'lines',\n choices: nil,\n types: [TypeGeneric]\n end\n\n it { is_expected.to have_type_generic String }\n end\n end\n\n context 'double equals' do\n let(:name) { 'lines' }\n let(:example) do\n [\n {\n 'postgresql_db' => nil,\n 'lines' => [\n 'result[0].sys_ver_str == 7.2(0)D1(1)',\n 'foo'\n ]\n }\n ]\n end\n\n it do\n is_expected.to have_attributes name: 'lines',\n choices: nil,\n types: []\n end\n end\n\n context 'empty choices' do\n let(:name) { 'username' }\n let(:choices) { [] }\n let(:example) do\n {\n 'tasks' => [\n {\n 'name' => 'create stuff',\n 'action' => 'ejabberd_user username=test host=server password=password'\n }\n ]\n }\n end\n\n it do\n is_expected.to have_attributes name: 'username',\n choices: nil,\n types: [String]\n end\n end\n\n context 'multiple types' do\n let(:name) { 'lines' }\n let(:example) do\n [\n {\n 'postgresql_db' => {\n 'lines' => ['howdy']\n }\n },\n {\n 'postgresql_db' => {\n 'lines' => [{ hello: 'there' }]\n }\n }\n ]\n end\n\n it do\n is_expected.to have_attributes name: 'lines',\n choices: nil,\n types: [TypeGeneric]\n end\n\n it { is_expected.to have_type_generic String, Hash }\n end\n end\n\n context 'type provided' do\n context 'int' do\n let(:type) { 'int' }\n\n it do\n is_expected.to have_attributes name: 'login_user',\n types: [Integer],\n choices: nil\n end\n end\n\n context 'string' do\n let(:type) { 'str' }\n\n context 'without choices' do\n it do\n is_expected.to have_attributes name: 'login_user',\n types: [String],\n choices: nil\n end\n end\n\n context 'path' do\n let(:type) { 'path' }\n\n it do\n is_expected.to have_attributes name: 'login_user',\n types: [String],\n choices: nil\n end\n end\n\n context 'with choices' do\n let(:choices) do\n %w[a b]\n end\n\n it do\n is_expected.to have_attributes name: 'login_user',\n types: [Symbol],\n choices: %i[a b]\n end\n end\n end\n\n context 'bool' do\n let(:type) { 'bool' }\n\n context 'yes/no' do\n let(:default) { 'no' }\n\n it do\n is_expected.to have_attributes name: 'login_user',\n types: [Symbol],\n choices: %i[yes no]\n end\n end\n\n context 'True/False' do\n let(:default) { 'True' }\n\n it do\n is_expected.to have_attributes name: 'login_user',\n choices: [true, false],\n types: include(TrueClass, FalseClass)\n end\n end\n\n context 'true/false' do\n let(:default) { true }\n\n it do\n is_expected.to have_attributes name: 'login_user',\n choices: [true, false],\n types: include(TrueClass, FalseClass)\n end\n end\n end\n\n context 'list' do\n let(:type) { 'list' }\n\n it do\n is_expected.to have_attributes name: 'login_user',\n types: [TypeGeneric],\n choices: nil\n end\n it { is_expected.to have_type_generic String }\n end\n\n context 'dict' do\n let(:type) { 'dict' }\n\n it do\n is_expected.to have_attributes name: 'login_user',\n types: [Hash],\n choices: nil\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6836065649986267, "alphanum_fraction": 0.6868852376937866, "avg_line_length": 32.88888931274414, "blob_id": "97d52014852849e41b6f5ed834afc9dd16dc1838", "content_id": "124f9dd702cddf8c9782aa14e29e2a06aaa9959e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 610, "license_type": "permissive", "max_line_length": 125, "num_lines": 18, "path": "/lib/ansible/ruby/modules/generated/net_tools/basics/slurp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module works like M(fetch). It is used for fetching a base64- encoded blob containing the data in a remote file.\n # This module is also supported for Windows targets.\n class Slurp < Base\n # @return [String] The file on the remote system to fetch. This I(must) be a file, not a directory.\n attribute :src\n validates :src, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.49753567576408386, "alphanum_fraction": 0.502204954624176, "avg_line_length": 24.032466888427734, "blob_id": "788f04d46ab144c599d8fb30a0eb80dc771539c0", "content_id": "8b0233c8e22d95c11e43df60573572503d8a2ba7", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3855, "license_type": "permissive", "max_line_length": 97, "num_lines": 154, "path": "/lib/ansible/ruby/dsl_builders/args_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# see LICENSE.txt in project root\nrequire 'spec_helper'\n\ndescribe Ansible::Ruby::DslBuilders::Args do\n let(:builder) { Ansible::Ruby::DslBuilders::Args.new recipient }\n\n let(:recipient_klass) do\n recipient_klass = Class.new(Ansible::Ruby::Modules::Base) do\n attribute :src\n validates :src, presence: true\n attribute :dest\n validates :dest, presence: true\n # E.g. like the URI module\n attribute :method\n end\n stub_const 'Ansible::Ruby::Modules::Copy', recipient_klass\n recipient_klass\n end\n\n subject(:recipient) { recipient_klass.new {} }\n\n before { builder.instance_eval ruby }\n\n let(:end_product_hash) { recipient.to_h[:copy] }\n\n context 'jinja' do\n context 'variable' do\n let(:ruby) do\n <<-RUBY\n src jinja('a_file')\n dest '/file2.conf'\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Modules::Copy }\n it do\n is_expected.to have_attributes src: Ansible::Ruby::Models::JinjaExpression.new('a_file'),\n dest: '/file2.conf'\n end\n end\n\n context 'item' do\n context 'single value' do\n let(:ruby) do\n <<-RUBY\n item = Ansible::Ruby::DslBuilders::JinjaItemNode.new\n\n src item\n dest '/file2.conf'\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Modules::Copy }\n\n it do\n expect(end_product_hash).to eq src: '{{ item }}',\n dest: '/file2.conf'\n end\n end\n\n context 'array' do\n let(:ruby) do\n <<-RUBY\n item = Ansible::Ruby::DslBuilders::JinjaItemNode.new\n\n src [item, item]\n dest '/file2.conf'\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Modules::Copy }\n\n it do\n expect(end_product_hash).to eq src: ['{{ item }}', '{{ item }}'],\n dest: '/file2.conf'\n end\n end\n\n context 'mixed values' do\n let(:ruby) do\n <<-RUBY\n item = Ansible::Ruby::DslBuilders::JinjaItemNode.new\n\n src [item, item.key]\n dest '/file2.conf'\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Modules::Copy }\n\n it do\n expect(end_product_hash).to eq src: ['{{ item }}', '{{ item.key }}'],\n dest: '/file2.conf'\n end\n end\n\n context 'hash' do\n let(:ruby) do\n <<-RUBY\n item = Ansible::Ruby::DslBuilders::JinjaItemNode.new\n\n src stuff: item, bar: item\n dest '/file2.conf'\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Modules::Copy }\n\n it do\n expect(end_product_hash).to eq src: {\n stuff: '{{ item }}',\n bar: '{{ item }}'\n },\n dest: '/file2.conf'\n end\n end\n end\n end\n\n context 'Ruby Kernel methods' do\n Ansible::Ruby::DslBuilders::Args::KERNEL_METHOD_OVERRIDES.each do |method|\n context \"##{method}\" do\n let(:recipient_klass) do\n klass = super()\n klass.class_eval { attribute method }\n klass\n end\n\n let(:ruby) { \"#{method} 123\" }\n\n it { is_expected.to have_attributes method => 123 }\n end\n end\n end\n\n context 'method as an attribute' do\n let(:ruby) do\n <<-RUBY\n src 'stuff'\n dest '/file2.conf'\n method 'foo'\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Modules::Copy }\n it do\n is_expected.to have_attributes src: 'stuff',\n dest: '/file2.conf',\n method: 'foo'\n end\n end\nend\n" }, { "alpha_fraction": 0.672386884689331, "alphanum_fraction": 0.6730109453201294, "avg_line_length": 59.47169876098633, "blob_id": "5b21c2ad7bd53c4f691d0860e14565e650ddb47c", "content_id": "dd8fd955d9e158a28664dea3f4f57fe642f44376", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3205, "license_type": "permissive", "max_line_length": 328, "num_lines": 53, "path": "/lib/ansible/ruby/modules/generated/files/blockinfile.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module will insert/update/remove a block of multi-line text surrounded by customizable marker lines.\n class Blockinfile < Base\n # @return [String] The file to modify.,Before 2.3 this option was only usable as I(dest), I(destfile) and I(name).\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [:absent, :present, nil] Whether the block should be there or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] The marker line template. \"{mark}\" will be replaced with the values in marker_begin (default=\"BEGIN\") and marker_end (default=\"END\").\n attribute :marker\n validates :marker, type: String\n\n # @return [String, nil] The text to insert inside the marker lines. If it's missing or an empty string, the block will be removed as if C(state) were specified to C(absent).\n attribute :block\n validates :block, type: String\n\n # @return [:EOF, :\"*regex*\", nil] If specified, the block will be inserted after the last match of specified regular expression. A special value is available; C(EOF) for inserting the block at the end of the file. If specified regular expression has no matches, C(EOF) will be used instead.\n attribute :insertafter\n validates :insertafter, expression_inclusion: {:in=>[:EOF, :\"*regex*\"], :message=>\"%{value} needs to be :EOF, :\\\"*regex*\\\"\"}, allow_nil: true\n\n # @return [:BOF, :\"*regex*\", nil] If specified, the block will be inserted before the last match of specified regular expression. A special value is available; C(BOF) for inserting the block at the beginning of the file. If specified regular expression has no matches, the block will be inserted at the end of the file.\n attribute :insertbefore\n validates :insertbefore, expression_inclusion: {:in=>[:BOF, :\"*regex*\"], :message=>\"%{value} needs to be :BOF, :\\\"*regex*\\\"\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Create a new file if it doesn't exist.\n attribute :create\n validates :create, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.\n attribute :backup\n validates :backup, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] This will be inserted at {mark} in the opening ansible block marker.\n attribute :marker_begin\n validates :marker_begin, type: String\n\n # @return [String, nil] This will be inserted at {mark} in the closing ansible block marker.\n attribute :marker_end\n validates :marker_end, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6805357933044434, "alphanum_fraction": 0.6839555501937866, "avg_line_length": 50.60293960571289, "blob_id": "b038b025970dff5a7710261e4abb8ecb359ed621", "content_id": "2655666b9fc404cbfb20e34cdbbd978ccb2def33", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3509, "license_type": "permissive", "max_line_length": 217, "num_lines": 68, "path": "/lib/ansible/ruby/modules/generated/cloud/oneandone/oneandone_firewall_policy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, remove, reconfigure, update firewall policies. This module has a dependency on 1and1 >= 1.0\n class Oneandone_firewall_policy < Base\n # @return [:present, :absent, :update, nil] Define a firewall policy state to create, remove, or update.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :update], :message=>\"%{value} needs to be :present, :absent, :update\"}, allow_nil: true\n\n # @return [String] Authenticating API token provided by 1&1.\n attribute :auth_token\n validates :auth_token, presence: true, type: String\n\n # @return [Object, nil] Custom API URL. Overrides the ONEANDONE_API_URL environement variable.\n attribute :api_url\n\n # @return [String] Firewall policy name used with present state. Used as identifier (id or name) when used with absent state. maxLength=128\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] The identifier (id or name) of the firewall policy used with update state.\n attribute :firewall_policy\n validates :firewall_policy, presence: true, type: String\n\n # @return [Array<Hash>, Hash, nil] A list of rules that will be set for the firewall policy. Each rule must contain protocol parameter, in addition to three optional parameters (port_from, port_to, and source)\n attribute :rules\n validates :rules, type: TypeGeneric.new(Hash)\n\n # @return [Array<String>, String, nil] A list of server identifiers (id or name) to be assigned to a firewall policy. Used in combination with update state.\n attribute :add_server_ips\n validates :add_server_ips, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] A list of server IP ids to be unassigned from a firewall policy. Used in combination with update state.\n attribute :remove_server_ips\n validates :remove_server_ips, type: TypeGeneric.new(String)\n\n # @return [Array<Hash>, Hash, nil] A list of rules that will be added to an existing firewall policy. It is syntax is the same as the one used for rules parameter. Used in combination with update state.\n attribute :add_rules\n validates :add_rules, type: TypeGeneric.new(Hash)\n\n # @return [Array<String>, String, nil] A list of rule ids that will be removed from an existing firewall policy. Used in combination with update state.\n attribute :remove_rules\n validates :remove_rules, type: TypeGeneric.new(String)\n\n # @return [String, nil] Firewall policy description. maxLength=256\n attribute :description\n validates :description, type: String\n\n # @return [:yes, :no, nil] wait for the instance to be in state 'running' before returning\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] how long before wait gives up, in seconds\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [Integer, nil] Defines the number of seconds to wait when using the _wait_for methods\n attribute :wait_interval\n validates :wait_interval, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7102339267730713, "alphanum_fraction": 0.7137426733970642, "avg_line_length": 75, "blob_id": "58b0d2e741afb87be2ae246128955bd4c0c0786b", "content_id": "02d62e669a9de8c1608dc4ccf70cfc3492f85eec", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3420, "license_type": "permissive", "max_line_length": 577, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/network/netscaler/netscaler_ssl_certkey.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage ssl cerificate keys.\n class Netscaler_ssl_certkey < Base\n # @return [String, nil] Name for the certificate and private-key pair. Must begin with an ASCII alphanumeric or underscore C(_) character, and must contain only ASCII alphanumeric, underscore C(_), hash C(#), period C(.), space C( ), colon C(:), at C(@), equals C(=), and hyphen C(-) characters. Cannot be changed after the certificate-key pair is created.,The following requirement applies only to the NetScaler CLI:,If the name includes one or more spaces, enclose the name in double or single quotation marks (for example, \"my cert\" or 'my cert').,Minimum length = 1\n attribute :certkey\n validates :certkey, type: String\n\n # @return [String, nil] Name of and, optionally, path to the X509 certificate file that is used to form the certificate-key pair. The certificate file should be present on the appliance's hard-disk drive or solid-state drive. Storing a certificate in any location other than the default might cause inconsistency in a high availability setup. /nsconfig/ssl/ is the default path.,Minimum length = 1\n attribute :cert\n validates :cert, type: String\n\n # @return [String, nil] Name of and, optionally, path to the private-key file that is used to form the certificate-key pair. The certificate file should be present on the appliance's hard-disk drive or solid-state drive. Storing a certificate in any location other than the default might cause inconsistency in a high availability setup. /nsconfig/ssl/ is the default path.,Minimum length = 1\n attribute :key\n validates :key, type: String\n\n # @return [Boolean, nil] Passphrase that was used to encrypt the private-key. Use this option to load encrypted private-keys in PEM format.\n attribute :password\n validates :password, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:DER, :PEM, :PFX, nil] Input format of the certificate and the private-key files. The three formats supported by the appliance are:,PEM - Privacy Enhanced Mail,DER - Distinguished Encoding Rule,PFX - Personal Information Exchange.\n attribute :inform\n validates :inform, expression_inclusion: {:in=>[:DER, :PEM, :PFX], :message=>\"%{value} needs to be :DER, :PEM, :PFX\"}, allow_nil: true\n\n # @return [String, nil] Pass phrase used to encrypt the private-key. Required when adding an encrypted private-key in PEM format.,Minimum length = 1\n attribute :passplain\n validates :passplain, type: String\n\n # @return [:enabled, :disabled, nil] Issue an alert when the certificate is about to expire.\n attribute :expirymonitor\n validates :expirymonitor, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [Integer, nil] Time, in number of days, before certificate expiration, at which to generate an alert that the certificate is about to expire.,Minimum value = C(10),Maximum value = C(100)\n attribute :notificationperiod\n validates :notificationperiod, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7164017558097839, "alphanum_fraction": 0.7164017558097839, "avg_line_length": 60.511112213134766, "blob_id": "c46196317991937d6fed02d25b6be8dbe5e29fb5", "content_id": "1451d19e9e0e01e8fc8cfc2fe86c1dcfda941da9", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2768, "license_type": "permissive", "max_line_length": 396, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigiq_application_fasthttp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages BIG-IQ applications used for load balancing an HTTP-based application, speeding up connections and reducing the number of connections to the back-end server.\n class Bigiq_application_fasthttp < Base\n # @return [String] Name of the new application.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Description of the application.\n attribute :description\n validates :description, type: String\n\n # @return [Array<Hash>, Hash, nil] A list of servers that the application is hosted on.,If you are familiar with other BIG-IP setting, you might also refer to this list as the list of pool members.,When creating a new application, at least one server is required.\n attribute :servers\n validates :servers, type: TypeGeneric.new(Hash)\n\n # @return [Hash, nil] Settings to configure the virtual which will receive the inbound connection.,This virtual will be used to host the HTTP endpoint of the application.\n attribute :inbound_virtual\n validates :inbound_virtual, type: Hash\n\n # @return [String, nil] Specifies the name of service environment that the application will be deployed to.,When creating a new application, this parameter is required.,The service environment type will be discovered by this module automatically. Therefore, it is crucial that you maintain unique names for items in the different service environment types (at this time, SSGs and BIGIPs).\n attribute :service_environment\n validates :service_environment, type: String\n\n # @return [Symbol, nil] Collects statistics of the BIG-IP that the application is deployed to.,This parameter is only relevant when specifying a C(service_environment) which is a BIG-IP; not an SSG.\n attribute :add_analytics\n validates :add_analytics, type: Symbol\n\n # @return [:absent, :present, nil] The state of the resource on the system.,When C(present), guarantees that the resource exists with the provided attributes.,When C(absent), removes the resource from the system.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [Boolean, nil] If the module should wait for the application to be created, deleted or updated.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6799007654190063, "alphanum_fraction": 0.6804521679878235, "avg_line_length": 45.5, "blob_id": "eb00fcb9c777b3940c0f8f0b30e454ea90b6ed72", "content_id": "91a61b002ad1f78350e314019a9d3da4d9298e97", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3627, "license_type": "permissive", "max_line_length": 260, "num_lines": 78, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_sslkeyandcertificate.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure SSLKeyAndCertificate object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_sslkeyandcertificate < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Object, nil] Ca certificates in certificate chain.\n attribute :ca_certs\n\n # @return [Hash] Sslcertificate settings for sslkeyandcertificate.\n attribute :certificate\n validates :certificate, presence: true, type: Hash\n\n # @return [Object, nil] It is a reference to an object of type certificatemanagementprofile.\n attribute :certificate_management_profile_ref\n\n # @return [Object, nil] Creator name.\n attribute :created_by\n\n # @return [Object, nil] Dynamic parameters needed for certificate management profile.\n attribute :dynamic_params\n\n # @return [Object, nil] Encrypted private key corresponding to the private key (e.g.,Those generated by an hsm such as thales nshield).\n attribute :enckey_base64\n\n # @return [Object, nil] Name of the encrypted private key (e.g.,Those generated by an hsm such as thales nshield).\n attribute :enckey_name\n\n # @return [Object, nil] It is a reference to an object of type hardwaresecuritymodulegroup.\n attribute :hardwaresecuritymodulegroup_ref\n\n # @return [String, nil] Private key.\n attribute :key\n validates :key, type: String\n\n # @return [Object, nil] Sslkeyparams settings for sslkeyandcertificate.\n attribute :key_params\n\n # @return [String] Name of the object.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Enum options - ssl_certificate_finished, ssl_certificate_pending.,Default value when not specified in API or module is interpreted by Avi Controller as SSL_CERTIFICATE_FINISHED.\n attribute :status\n\n # @return [Object, nil] It is a reference to an object of type tenant.\n attribute :tenant_ref\n\n # @return [String, nil] Enum options - ssl_certificate_type_virtualservice, ssl_certificate_type_system, ssl_certificate_type_ca.,Default value when not specified in API or module is interpreted by Avi Controller as SSL_CERTIFICATE_TYPE_VIRTUALSERVICE.\n attribute :type\n validates :type, type: String\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Unique object identifier of the object.\n attribute :uuid\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6994759440422058, "alphanum_fraction": 0.6994759440422058, "avg_line_length": 63.54411697387695, "blob_id": "87828e38fa5e83026719e451938bd4f3ec8116fd", "content_id": "32ea74dd2a0fbec7ea78f2a905c77837d3f74fbb", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4389, "license_type": "permissive", "max_line_length": 240, "num_lines": 68, "path": "/lib/ansible/ruby/modules/generated/windows/win_domain_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates, modifies or removes groups in Active Directory.\n # For local groups, use the M(win_group) module instead.\n class Win_domain_group < Base\n # @return [Hash, nil] A dict of custom LDAP attributes to set on the group.,This can be used to set custom attributes that are not exposed as module parameters, e.g. C(mail).,See the examples on how to format this parameter.\n attribute :attributes\n validates :attributes, type: Hash\n\n # @return [:distribution, :security, nil] The category of the group, this is the value to assign to the LDAP C(groupType) attribute.,If a new group is created then C(security) will be used by default.\n attribute :category\n validates :category, expression_inclusion: {:in=>[:distribution, :security], :message=>\"%{value} needs to be :distribution, :security\"}, allow_nil: true\n\n # @return [Object, nil] The value to be assigned to the LDAP C(description) attribute.\n attribute :description\n\n # @return [Object, nil] The value to assign to the LDAP C(displayName) attribute.\n attribute :display_name\n\n # @return [String, nil] The username to use when interacting with AD.,If this is not set then the user Ansible used to log in with will be used instead.\n attribute :domain_username\n validates :domain_username, type: String\n\n # @return [String, nil] The password for C(username).\n attribute :domain_password\n validates :domain_password, type: String\n\n # @return [String, nil] Specifies the Active Directory Domain Services instance to connect to.,Can be in the form of an FQDN or NetBIOS name.,If not specified then the value is based on the domain of the computer running PowerShell.\n attribute :domain_server\n validates :domain_server, type: String\n\n # @return [:yes, :no, nil] Will ignore the C(ProtectedFromAccidentalDeletion) flag when deleting or moving a group.,The module will fail if one of these actions need to occur and this value is set to C(no).\n attribute :ignore_protection\n validates :ignore_protection, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] The value to be assigned to the LDAP C(managedBy) attribute.,This value can be in the forms C(Distinguished Name), C(objectGUID), C(objectSid) or C(sAMAccountName), see examples for more details.\n attribute :managed_by\n validates :managed_by, type: String\n\n # @return [Array<String>, String] The name of the group to create, modify or remove.,This value can be in the forms C(Distinguished Name), C(objectGUID), C(objectSid) or C(sAMAccountName), see examples for more details.\n attribute :name\n validates :name, presence: true, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] The full LDAP path to create or move the group to.,This should be the path to the parent object to create or move the group to.,See examples for details of how this path is formed.\n attribute :organizational_unit\n validates :organizational_unit, type: TypeGeneric.new(String)\n\n # @return [Symbol, nil] Will set the C(ProtectedFromAccidentalDeletion) flag based on this value.,This flag stops a user from deleting or moving a group to a different path.\n attribute :protect\n validates :protect, type: Symbol\n\n # @return [:domainlocal, :global, :universal, nil] The scope of the group.,If C(state=present) and the group doesn't exist then this must be set.\n attribute :scope\n validates :scope, expression_inclusion: {:in=>[:domainlocal, :global, :universal], :message=>\"%{value} needs to be :domainlocal, :global, :universal\"}, allow_nil: true\n\n # @return [:absent, :present, nil] If C(state=present) this module will ensure the group is created and is configured accordingly.,If C(state=absent) this module will delete the group if it exists\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6784840822219849, "alphanum_fraction": 0.6803178191184998, "avg_line_length": 59.592594146728516, "blob_id": "e1c3dbd30a4690032b5f5f0c3e1ed335fda0d04a", "content_id": "9a3b843a1d847e2178f53d5c475143d04da1e371", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3272, "license_type": "permissive", "max_line_length": 302, "num_lines": 54, "path": "/lib/ansible/ruby/modules/generated/files/ini_file.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage (add, remove, change) individual settings in an INI-style file without having to manage the file as a whole with, say, M(template) or M(assemble). Adds missing sections if they don't exist.\n # Before version 2.0, comments are discarded when the source file is read, and therefore will not show up in the destination file.\n # Since version 2.3, this module adds missing ending newlines to files to keep in line with the POSIX standard, even when no other modifications need to be applied.\n class Ini_file < Base\n # @return [String] Path to the INI-style file; this file is created if required.,Before 2.3 this option was only usable as I(dest).\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [String] Section name in INI file. This is added if C(state=present) automatically when a single value is being set.,If left empty or set to `null`, the I(option) will be placed before the first I(section). Using `null` is also required if the config format does not support sections.\n attribute :section\n validates :section, presence: true, type: String\n\n # @return [String, nil] If set (required for changing a I(value)), this is the name of the option.,May be omitted if adding/removing a whole I(section).\n attribute :option\n validates :option, type: String\n\n # @return [String, nil] The string value to be associated with an I(option). May be omitted when removing an I(option).\n attribute :value\n validates :value, type: String\n\n # @return [:yes, :no, nil] Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.\n attribute :backup\n validates :backup, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] All arguments accepted by the M(file) module also work here\n attribute :others\n\n # @return [:absent, :present, nil] If set to C(absent) the option or section will be removed if present instead of created.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Do not insert spaces before and after '=' symbol\n attribute :no_extra_spaces\n validates :no_extra_spaces, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If set to 'no', the module will fail if the file does not already exist. By default it will create the file if it is missing.\n attribute :create\n validates :create, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Symbol, nil] allow option without value and without '=' symbol\n attribute :allow_no_value\n validates :allow_no_value, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7084359526634216, "alphanum_fraction": 0.7096675038337708, "avg_line_length": 65.28571319580078, "blob_id": "75157d9146bb936bab748524df2fc8ccdf9a3c4e", "content_id": "c7ccd6e1a775c21074493a3019530db901bdb7f1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3248, "license_type": "permissive", "max_line_length": 431, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/identity/keycloak/keycloak_clienttemplate.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows the administration of Keycloak client templates via the Keycloak REST API. It requires access to the REST API via OpenID Connect; the user connecting and the client being used must have the requisite access rights. In a default Keycloak installation, admin-cli and an admin user would work, as would a separate client definition with the scope tailored to your needs and a user having the expected roles.\n # The names of module options are snake_cased versions of the camelCase ones found in the Keycloak API and its documentation at U(http://www.keycloak.org/docs-api/3.3/rest-api/)\n # The Keycloak API does not always enforce for only sensible settings to be used -- you can set SAML-specific settings on an OpenID Connect client for instance and vice versa. Be careful. If you do not specify a setting, usually a sensible default is chosen.\n class Keycloak_clienttemplate < Base\n # @return [:present, :absent, nil] State of the client template,On C(present), the client template will be created (or updated if it exists already).,On C(absent), the client template will be removed if it exists\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Id of client template to be worked on. This is usually a UUID.\n attribute :id\n validates :id, type: String\n\n # @return [String, nil] Realm this client template is found in.\n attribute :realm\n validates :realm, type: String\n\n # @return [String, nil] Name of the client template\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] Description of the client template in Keycloak\n attribute :description\n\n # @return [:\"openid-connect\", :saml, nil] Type of client template (either C(openid-connect) or C(saml).\n attribute :protocol\n validates :protocol, expression_inclusion: {:in=>[:\"openid-connect\", :saml], :message=>\"%{value} needs to be :\\\"openid-connect\\\", :saml\"}, allow_nil: true\n\n # @return [Boolean, nil] Is the \"Full Scope Allowed\" feature set for this client template or not. This is 'fullScopeAllowed' in the Keycloak REST API.\n attribute :full_scope_allowed\n validates :full_scope_allowed, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash, nil] a list of dicts defining protocol mappers for this client template. This is 'protocolMappers' in the Keycloak REST API.\n attribute :protocol_mappers\n validates :protocol_mappers, type: TypeGeneric.new(Hash)\n\n # @return [Object, nil] A dict of further attributes for this client template. This can contain various configuration settings, though in the default installation of Keycloak as of 3.4, none are documented or known, so this is usually empty.\n attribute :attributes\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6865000128746033, "alphanum_fraction": 0.690500020980835, "avg_line_length": 50.28205108642578, "blob_id": "3167cceca3fad64aadcaa9c76ff719d62590638f", "content_id": "69de6864d7c1b0760a533b8c77c06e07ab6050bc", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2000, "license_type": "permissive", "max_line_length": 309, "num_lines": 39, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_security_port_list.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages the AFM port lists on a BIG-IP. This module can be used to add and remove port list entries.\n class Bigip_firewall_port_list < Base\n # @return [String] Specifies the name of the port list.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [Object, nil] Description of the port list\n attribute :description\n\n # @return [String, Array<Integer>, Integer, nil] Simple list of port values to add to the list\n attribute :ports\n validates :ports, type: TypeGeneric.new(Integer)\n\n # @return [Array<String>, String, nil] A list of port ranges where the range starts with a port number, is followed by a dash (-) and then a second number.,If the first number is greater than the second number, the numbers will be reversed so-as to be properly formatted. ie, 90-78 would become 78-90.\n attribute :port_ranges\n validates :port_ranges, type: TypeGeneric.new(String)\n\n # @return [Object, nil] Simple list of existing port lists to add to this list. Port lists can be specified in either their fully qualified name (/Common/foo) or their short name (foo). If a short name is used, the C(partition) argument will automatically be prepended to the short name.\n attribute :port_lists\n\n # @return [:present, :absent, nil] When C(present), ensures that the address list and entries exists.,When C(absent), ensures the address list is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5790031552314758, "alphanum_fraction": 0.5790031552314758, "avg_line_length": 25.19444465637207, "blob_id": "cbc4d3bd8de9bac55dfcf480dfb94825419a4771", "content_id": "cf14bd96894d5ac10e248a72b7689073d6cd5b27", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 943, "license_type": "permissive", "max_line_length": 77, "num_lines": 36, "path": "/lib/ansible/ruby/rake/clean.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# See LICENSE.txt in root of repository\n\nrequire 'rake/tasklib'\nrequire 'ansible/ruby/rake/task_util'\n\nmodule Ansible\n module Ruby\n module Rake\n class Clean < ::Rake::TaskLib\n include TaskUtil\n\n # :reek:Attribute - Rake DSL gets ugly if we don't use a block\n attr_accessor :files\n\n def initialize(parameters = :default)\n name, deps = parse_params parameters\n yield self if block_given?\n raise 'You did not supply any files!' unless files && [*files].any?\n\n clean_files = yaml_filenames [*files]\n task name => deps do\n exist = clean_files.select { |file| File.exist? file }\n if exist.any?\n puts 'Cleaning ansible-ruby files'\n rm_rf exist\n else\n puts 'No ansible-ruby files exist to clean'\n end\n end\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6593309640884399, "alphanum_fraction": 0.6646126508712769, "avg_line_length": 39.57143020629883, "blob_id": "8ddb6372df867d798d9d35c73f974bffd47f4df4", "content_id": "8eaba456fc44e549579d226b85e6a05a8f79606c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1136, "license_type": "permissive", "max_line_length": 160, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/cloud/dimensiondata/dimensiondata_network.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, and delete MCP 1.0 & 2.0 networks\n class Dimensiondata_network < Base\n # @return [String] The name of the network domain to create.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Additional description of the network domain.\n attribute :description\n\n # @return [:ESSENTIALS, :ADVANCED, nil] The service plan, either \"ESSENTIALS\" or \"ADVANCED\".,MCP 2.0 Only.\n attribute :service_plan\n validates :service_plan, expression_inclusion: {:in=>[:ESSENTIALS, :ADVANCED], :message=>\"%{value} needs to be :ESSENTIALS, :ADVANCED\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Should the resource be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6873156428337097, "alphanum_fraction": 0.7227138876914978, "avg_line_length": 21.600000381469727, "blob_id": "6bd114cf468299ba7368e512c1ec99bfc05722e0", "content_id": "9daa556e2604e427d4604c2942f5e8a8daf723cb", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 339, "license_type": "permissive", "max_line_length": 66, "num_lines": 15, "path": "/lib/ansible/ruby/modules/custom/packaging/os/apt.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# VALIDATED_CHECKSUM: 4t8xwzQpe7ap54uEob4z4MEmLw0vgiYFg0M1S10DyGo=\nrequire 'ansible/ruby/modules/generated/packaging/os/apt'\n\nmodule Ansible\n module Ruby\n module Modules\n class Apt\n # Can either be a list or a single item\n remove_existing_validations :name\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.677511990070343, "alphanum_fraction": 0.677511990070343, "avg_line_length": 36.32143020629883, "blob_id": "92f11ff732a7810eabe6f0af322665bec227b701", "content_id": "78c8ea2f293d54787bf7c8008aabbedde8a53663", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1045, "license_type": "permissive", "max_line_length": 147, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/network/onyx/onyx_pfc_interface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of priority flow control (PFC) on interfaces of Mellanox ONYX network devices.\n class Onyx_pfc_interface < Base\n # @return [String, nil] Name of the interface PFC should be configured on.\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] List of interfaces PFC should be configured on.\n attribute :aggregate\n\n # @return [Symbol, nil] Purge interfaces not defined in the aggregate parameter.\n attribute :purge\n validates :purge, type: Symbol\n\n # @return [:enabled, :disabled, nil] State of the PFC configuration.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5413436889648438, "alphanum_fraction": 0.5422049760818481, "avg_line_length": 29.959999084472656, "blob_id": "a18187e5cb8daf18666991baef4cac3a80c84551", "content_id": "116d6332506bde505dab8127c4c1adc264dc479c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2322, "license_type": "permissive", "max_line_length": 96, "num_lines": 75, "path": "/util/parser.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# See LICENSE.txt for license\n\nrequire_relative 'parser/option'\nrequire_relative 'parser/yaml'\nrequire_relative './option_formatter'\nrequire 'yaml'\n\nmodule Ansible\n module Ruby\n module Parser\n KLASS_INDENT = Array.new(6, ' ').join ''\n OPTION_INDENT = Array.new(8, ' ').join ''\n\n class << self\n # :reek:ControlParameter - Coming from Rake task, no easier answer\n def from_yaml_string(desc_yaml, example_yaml, example_fail_is_ok)\n metadata = Yaml.parse desc_yaml, 'description'\n mod = metadata['module']\n example = begin\n Yaml.parse example_yaml, 'example', mod\n rescue StandardError\n raise unless ENV['IGNORE_EXAMPLES'] || example_fail_is_ok\n\n nil\n end\n klass_description = metadata['description']\n klass_description ||= [*metadata['short_description']]\n klass mod, klass_description do\n options(metadata['options'], example)\n end\n end\n\n private\n\n def options(options, example)\n options ||= {}\n all_lines = options.map do |name, detail|\n option_data = Option.parse(name, detail, example)\n lines = OptionFormatter.format(option_data).map { |line| \"#{OPTION_INDENT}#{line}\" }\n # separate attributes with a line break\n lines << ''\n end.flatten\n # Get rid of the last extra line\n all_lines.pop\n all_lines.join \"\\n\"\n end\n\n def klass(mod, description)\n # indentation, etc.\n description = [*description].map { |line| KLASS_INDENT + \"# #{line}\" }.join \"\\n\"\n description += \"\\n\" unless description.empty?\n klass_name = mod.capitalize\n <<~RUBY\n # frozen_string_literal: true\n # See LICENSE.txt at root of repository\n # GENERATED FILE - DO NOT EDIT!!\n require 'ansible/ruby/modules/base'\n\n module Ansible\n module Ruby\n module Modules\n #{description + KLASS_INDENT}class #{klass_name} < Base\n #{yield}\n end\n end\n end\n end\n RUBY\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6591567397117615, "alphanum_fraction": 0.6620534062385559, "avg_line_length": 55.490909576416016, "blob_id": "5710eebf3a7ecdc8a7c6667b4af71f64ad5c53c8", "content_id": "2ea5eebe082a8df8a98689a6d6dc1e450b51cae0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3107, "license_type": "permissive", "max_line_length": 416, "num_lines": 55, "path": "/lib/ansible/ruby/modules/generated/cloud/rackspace/rax_clb.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # creates / deletes a Rackspace Public Cloud load balancer.\n class Rax_clb < Base\n # @return [:RANDOM, :LEAST_CONNECTIONS, :ROUND_ROBIN, :WEIGHTED_LEAST_CONNECTIONS, :WEIGHTED_ROUND_ROBIN, nil] algorithm for the balancer being created\n attribute :algorithm\n validates :algorithm, expression_inclusion: {:in=>[:RANDOM, :LEAST_CONNECTIONS, :ROUND_ROBIN, :WEIGHTED_LEAST_CONNECTIONS, :WEIGHTED_ROUND_ROBIN], :message=>\"%{value} needs to be :RANDOM, :LEAST_CONNECTIONS, :ROUND_ROBIN, :WEIGHTED_LEAST_CONNECTIONS, :WEIGHTED_ROUND_ROBIN\"}, allow_nil: true\n\n # @return [Object, nil] A hash of metadata to associate with the instance\n attribute :meta\n\n # @return [String, nil] Name to give the load balancer\n attribute :name\n validates :name, type: String\n\n # @return [Integer, nil] Port for the balancer being created\n attribute :port\n validates :port, type: Integer\n\n # @return [:DNS_TCP, :DNS_UDP, :FTP, :HTTP, :HTTPS, :IMAPS, :IMAPv4, :LDAP, :LDAPS, :MYSQL, :POP3, :POP3S, :SMTP, :TCP, :TCP_CLIENT_FIRST, :UDP, :UDP_STREAM, :SFTP, nil] Protocol for the balancer being created\n attribute :protocol\n validates :protocol, expression_inclusion: {:in=>[:DNS_TCP, :DNS_UDP, :FTP, :HTTP, :HTTPS, :IMAPS, :IMAPv4, :LDAP, :LDAPS, :MYSQL, :POP3, :POP3S, :SMTP, :TCP, :TCP_CLIENT_FIRST, :UDP, :UDP_STREAM, :SFTP], :message=>\"%{value} needs to be :DNS_TCP, :DNS_UDP, :FTP, :HTTP, :HTTPS, :IMAPS, :IMAPv4, :LDAP, :LDAPS, :MYSQL, :POP3, :POP3S, :SMTP, :TCP, :TCP_CLIENT_FIRST, :UDP, :UDP_STREAM, :SFTP\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Indicate desired state of the resource\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Integer, nil] timeout for communication between the balancer and the node\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [:PUBLIC, :SERVICENET, nil] type of interface for the balancer being created\n attribute :type\n validates :type, expression_inclusion: {:in=>[:PUBLIC, :SERVICENET], :message=>\"%{value} needs to be :PUBLIC, :SERVICENET\"}, allow_nil: true\n\n # @return [Object, nil] Virtual IP ID to use when creating the load balancer for purposes of sharing an IP with another load balancer of another protocol\n attribute :vip_id\n\n # @return [:yes, :no, nil] wait for the balancer to be in state 'running' before returning\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] how long before wait gives up, in seconds\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.723901093006134, "alphanum_fraction": 0.7280219793319702, "avg_line_length": 57.2400016784668, "blob_id": "46c6eaba3e100af59254da7454c221337b1da6fd", "content_id": "283bd629943bb6fcf5ba25ce09bebf56da465d63", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1456, "license_type": "permissive", "max_line_length": 373, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/windows/win_regmerge.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Wraps the reg.exe command to import the contents of a registry file.\n # Suitable for use with registry files created using M(win_template).\n # Windows registry files have a specific format and must be constructed correctly with carriage return and line feed line endings otherwise they will not be merged.\n # Exported registry files often start with a Byte Order Mark which must be removed if the file is to templated using M(win_template).\n # Registry file format is described at U(https://support.microsoft.com/en-us/kb/310516)\n # See also M(win_template), M(win_regedit)\n class Win_regmerge < Base\n # @return [String] The full path including file name to the registry file on the remote machine to be merged\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [Object, nil] The parent key to use when comparing the contents of the registry to the contents of the file. Needs to be in HKLM or HKCU part of registry. Use a PS-Drive style path for example HKLM:\\SOFTWARE not HKEY_LOCAL_MACHINE\\SOFTWARE If not supplied, or the registry key is not found, no comparison will be made, and the module will report changed.\n attribute :compare_key\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6830102801322937, "alphanum_fraction": 0.6830102801322937, "avg_line_length": 46.4054069519043, "blob_id": "131eb8a4fedbe9485069359bce4b50985d5576f2", "content_id": "f16966ac54ca34eb92e5df61b5f81d15956ab911", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1754, "license_type": "permissive", "max_line_length": 169, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_containerregistry.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and delete an Azure Container Registry.\n class Azure_rm_containerregistry < Base\n # @return [String] Name of a resource group where the Container Registry exists or will be created.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] Name of the Container Registry.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, nil] Assert the state of the container registry. Use 'present' to create or update an container registry and 'absent' to delete it.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] Valid azure location. Defaults to location of the resource group.\n attribute :location\n validates :location, type: String\n\n # @return [Symbol, nil] If enabled, you can use the registry name as username and admin user access key as password to docker login to your container registry.\n attribute :admin_user_enabled\n validates :admin_user_enabled, type: Symbol\n\n # @return [:Basic, :Standard, :Premium, nil] Specifies the SKU to use. Currently can be either Basic, Standard or Premium.\n attribute :sku\n validates :sku, expression_inclusion: {:in=>[:Basic, :Standard, :Premium], :message=>\"%{value} needs to be :Basic, :Standard, :Premium\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6871369481086731, "alphanum_fraction": 0.6871369481086731, "avg_line_length": 42.03571319580078, "blob_id": "37ca490ede3042e5d0a2224d3d9a512ff809bb2d", "content_id": "634ac9b24d92bda2e024bde9d18cac6d9158995d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1205, "license_type": "permissive", "max_line_length": 263, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_server_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove server groups from OpenStack.\n class Os_server_group < Base\n # @return [:present, :absent, nil] Indicate desired state of the resource. When I(state) is 'present', then I(policies) is required.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] Server group name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Array<String>, String, nil] A list of one or more policy names to associate with the server group. The list must contain at least one policy name. The current valid policy names are anti-affinity, affinity, soft-anti-affinity and soft-affinity.\n attribute :policies\n validates :policies, type: TypeGeneric.new(String)\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.650173008441925, "alphanum_fraction": 0.6512110829353333, "avg_line_length": 44.873016357421875, "blob_id": "15cf1cf52b281c23765901f655fec086ea5e9e20", "content_id": "d946f0d602cd4648763e03b74b274f1cb0dd4687", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2890, "license_type": "permissive", "max_line_length": 153, "num_lines": 63, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_pim_interface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages PIM interface configuration settings.\n class Nxos_pim_interface < Base\n # @return [String] Full name of the interface such as Ethernet1/33.\n attribute :interface\n validates :interface, presence: true, type: String\n\n # @return [:yes, :no, nil] Enable/disable sparse-mode on the interface.\n attribute :sparse\n validates :sparse, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Configures priority for PIM DR election on interface.\n attribute :dr_prio\n validates :dr_prio, type: Integer\n\n # @return [Object, nil] Authentication for hellos on this interface.\n attribute :hello_auth_key\n\n # @return [Symbol, nil] Hello interval in milliseconds for this interface.\n attribute :hello_interval\n validates :hello_interval, type: Symbol\n\n # @return [String, nil] Policy for join-prune messages (outbound).\n attribute :jp_policy_out\n validates :jp_policy_out, type: String\n\n # @return [String, nil] Policy for join-prune messages (inbound).\n attribute :jp_policy_in\n validates :jp_policy_in, type: String\n\n # @return [:prefix, :routemap, nil] Type of policy mapped to C(jp_policy_out).\n attribute :jp_type_out\n validates :jp_type_out, expression_inclusion: {:in=>[:prefix, :routemap], :message=>\"%{value} needs to be :prefix, :routemap\"}, allow_nil: true\n\n # @return [:prefix, :routemap, nil] Type of policy mapped to C(jp_policy_in).\n attribute :jp_type_in\n validates :jp_type_in, expression_inclusion: {:in=>[:prefix, :routemap], :message=>\"%{value} needs to be :prefix, :routemap\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Configures interface to be a boundary of a PIM domain.\n attribute :border\n validates :border, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Configures a neighbor policy for filtering adjacencies.\n attribute :neighbor_policy\n\n # @return [:prefix, :routemap, nil] Type of policy mapped to neighbor_policy.\n attribute :neighbor_type\n validates :neighbor_type, expression_inclusion: {:in=>[:prefix, :routemap], :message=>\"%{value} needs to be :prefix, :routemap\"}, allow_nil: true\n\n # @return [:present, :default, nil] Manages desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :default], :message=>\"%{value} needs to be :present, :default\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.3942148685455322, "alphanum_fraction": 0.4074380099773407, "avg_line_length": 26.657142639160156, "blob_id": "4e39522fb97145885d3b11abd1efa8a562533fb9", "content_id": "6fff2fa7cc9ec13372bff0389c421e83bae2cc99", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4840, "license_type": "permissive", "max_line_length": 115, "num_lines": 175, "path": "/lib/ansible/ruby/models/play_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'spec_helper'\nrequire 'ansible-ruby'\n\ndescribe Ansible::Ruby::Models::Play do\n before do\n stub_const('Ansible::Ruby::Modules::Ec2', module_klass)\n end\n\n let(:module_klass) do\n Class.new(Ansible::Ruby::Modules::Base) do\n attribute :foo\n validates :foo, presence: true\n end\n end\n\n let(:task) do\n Ansible::Ruby::Models::Task.new name: 'do stuff on EC2',\n module: module_klass.new(foo: 123)\n end\n\n let(:tasks_model) { Ansible::Ruby::Models::Tasks.new(items: task_array) }\n let(:task_array) { [task] }\n\n subject(:hash) { instance.to_h }\n\n context 'basic' do\n let(:instance) do\n Ansible::Ruby::Models::Play.new tasks: tasks_model,\n hosts: %w[host1 host2]\n end\n\n it do\n is_expected.to eq(hosts: 'host1:host2',\n tasks: [\n {\n name: 'do stuff on EC2',\n ec2: {\n foo: 123\n }\n }\n ])\n end\n end\n\n context 'vars' do\n let(:instance) do\n Ansible::Ruby::Models::Play.new tasks: tasks_model,\n hosts: %w[host1 host2],\n vars: {\n var1: 'value1'\n }\n end\n\n it do\n is_expected.to eq(hosts: 'host1:host2',\n vars: {\n var1: 'value1'\n },\n tasks: [\n {\n name: 'do stuff on EC2',\n ec2: {\n foo: 123\n }\n }\n ])\n end\n end\n\n context 'play name' do\n let(:instance) do\n Ansible::Ruby::Models::Play.new tasks: tasks_model,\n name: 'play name',\n hosts: %w[host1 host2]\n end\n\n it do\n is_expected.to eq(hosts: 'host1:host2',\n name: 'play name',\n tasks: [\n {\n name: 'do stuff on EC2',\n ec2: {\n foo: 123\n }\n }\n ])\n end\n\n it 'puts the name right after hosts for readability' do\n expect(hash.stringify_keys.keys).to eq %w[hosts name tasks]\n end\n end\n\n context 'single host' do\n let(:instance) do\n Ansible::Ruby::Models::Play.new tasks: tasks_model,\n hosts: 'host1'\n end\n\n it do\n is_expected.to eq(hosts: 'host1',\n tasks: [\n {\n name: 'do stuff on EC2',\n ec2: {\n foo: 123\n }\n }\n ])\n end\n end\n\n context 'tasks and roles' do\n subject { instance }\n\n let(:instance) do\n Ansible::Ruby::Models::Play.new tasks: tasks_model,\n hosts: 'host1',\n roles: 'role1'\n end\n\n it { is_expected.to_not be_valid }\n it { is_expected.to have_errors tasks: 'Cannot supply both tasks and roles!' }\n end\n\n context 'no tasks and no roles' do\n subject { instance }\n\n let(:instance) { Ansible::Ruby::Models::Play.new hosts: 'host1' }\n\n it { is_expected.to_not be_valid }\n it { is_expected.to have_errors tasks: 'Must supply either task(s) or role(s)!' }\n end\n\n context 'role' do\n context 'single' do\n let(:instance) do\n Ansible::Ruby::Models::Play.new roles: 'role1',\n hosts: 'host1'\n end\n\n it do\n is_expected.to eq(hosts: 'host1',\n roles: %w[role1])\n end\n end\n\n context 'multiple' do\n let(:instance) do\n Ansible::Ruby::Models::Play.new roles: %w[role1 role2],\n hosts: 'host1'\n end\n\n it do\n is_expected.to eq(hosts: 'host1',\n roles: %w[role1 role2])\n end\n end\n\n context 'tags' do\n let(:instance) do\n Ansible::Ruby::Models::Play.new roles: [{ role: 'role1', tag: 'clone' }, { role: 'role2', tag: 'clone2' }],\n hosts: 'host1'\n end\n\n it do\n is_expected.to eq(hosts: 'host1',\n roles: [{ role: 'role1', tag: 'clone' }, { role: 'role2', tag: 'clone2' }])\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6724137663841248, "alphanum_fraction": 0.6724137663841248, "avg_line_length": 42.5, "blob_id": "54753335dc91ffccd1b72504865f9d6b204de17a", "content_id": "37e344afabe28840ffc1bbf0239e07d61f7825b6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4002, "license_type": "permissive", "max_line_length": 215, "num_lines": 92, "path": "/lib/ansible/ruby/modules/generated/network/panos/panos_object.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Policy objects form the match criteria for policy rules and many other functions in PAN-OS. These may include address object, address groups, service objects, service groups, and tag.\n class Panos_object < Base\n # @return [String] IP address (or hostname) of PAN-OS device or Panorama management console being configured.\n attribute :ip_address\n validates :ip_address, presence: true, type: String\n\n # @return [String, nil] Username credentials to use for authentication.\n attribute :username\n validates :username, type: String\n\n # @return [String] Password credentials to use for authentication.\n attribute :password\n validates :password, presence: true, type: String\n\n # @return [String, nil] API key that can be used instead of I(username)/I(password) credentials.\n attribute :api_key\n validates :api_key, type: String\n\n # @return [String] The operation to be performed. Supported values are I(add)/I(delete)/I(find).\n attribute :operation\n validates :operation, presence: true, type: String\n\n # @return [String, nil] The name of the address object.\n attribute :addressobject\n validates :addressobject, type: String\n\n # @return [String, nil] The IP address of the host or network in CIDR notation.\n attribute :address\n validates :address, type: String\n\n # @return [Object, nil] The type of address object definition. Valid types are I(ip-netmask) and I(ip-range).\n attribute :address_type\n\n # @return [String, nil] A static group of address objects or dynamic address group.\n attribute :addressgroup\n validates :addressgroup, type: String\n\n # @return [Array<String>, String, nil] A group of address objects to be used in an addressgroup definition.\n attribute :static_value\n validates :static_value, type: TypeGeneric.new(String)\n\n # @return [Object, nil] The filter match criteria to be used in a dynamic addressgroup definition.\n attribute :dynamic_value\n\n # @return [String, nil] The name of the service object.\n attribute :serviceobject\n validates :serviceobject, type: String\n\n # @return [Object, nil] The source port to be used in a service object definition.\n attribute :source_port\n\n # @return [String, nil] The destination port to be used in a service object definition.\n attribute :destination_port\n validates :destination_port, type: String\n\n # @return [String, nil] The IP protocol to be used in a service object definition. Valid values are I(tcp) or I(udp).\n attribute :protocol\n validates :protocol, type: String\n\n # @return [Object, nil] A group of service objects.\n attribute :servicegroup\n\n # @return [Object, nil] The group of service objects used in a servicegroup definition.\n attribute :services\n\n # @return [String, nil] The description of the object.\n attribute :description\n validates :description, type: String\n\n # @return [String, nil] The name of an object or rule tag.\n attribute :tag_name\n validates :tag_name, type: String\n\n # @return [String, nil] - The color of the tag object. Valid values are I(red, green, blue, yellow, copper, orange, purple, gray, light green, cyan, light gray, blue gray, lime, black, gold, and brown).\\r\\n\n attribute :color\n validates :color, type: String\n\n # @return [String, nil] - The name of the Panorama device group. The group must exist on Panorama. If device group is not defined it is assumed that we are contacting a firewall.\\r\\n\n attribute :devicegroup\n validates :devicegroup, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6729006171226501, "alphanum_fraction": 0.6751008629798889, "avg_line_length": 51.44230651855469, "blob_id": "df2fc3b864adad2def56151566f3373773cfc969", "content_id": "1d9188074d68519196ef35e3fce2d5374dbe4a55", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2727, "license_type": "permissive", "max_line_length": 346, "num_lines": 52, "path": "/lib/ansible/ruby/modules/generated/monitoring/zabbix/zabbix_proxy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows you to create, modify, get and delete Zabbix proxy entries.\n class Zabbix_proxy < Base\n # @return [String] Name of the proxy in Zabbix.\n attribute :proxy_name\n validates :proxy_name, presence: true, type: String\n\n # @return [String, nil] Description of the proxy..\n attribute :description\n validates :description, type: String\n\n # @return [:active, :passive, nil] Type of proxy. (4 - active, 5 - passive)\n attribute :status\n validates :status, expression_inclusion: {:in=>[:active, :passive], :message=>\"%{value} needs to be :active, :passive\"}, allow_nil: true\n\n # @return [:no_encryption, :PSK, :certificate, nil] Connections to proxy.\n attribute :tls_connect\n validates :tls_connect, expression_inclusion: {:in=>[:no_encryption, :PSK, :certificate], :message=>\"%{value} needs to be :no_encryption, :PSK, :certificate\"}, allow_nil: true\n\n # @return [:no_encryption, :PSK, :certificate, nil] Connections from proxy.\n attribute :tls_accept\n validates :tls_accept, expression_inclusion: {:in=>[:no_encryption, :PSK, :certificate], :message=>\"%{value} needs to be :no_encryption, :PSK, :certificate\"}, allow_nil: true\n\n # @return [Object, nil] Certificate issuer.\n attribute :tls_issuer\n\n # @return [Object, nil] Certificate subject.\n attribute :tls_subject\n\n # @return [Object, nil] PSK identity. Required if either I(tls_connect) or I(tls_accept) has PSK enabled.\n attribute :tls_psk_identity\n\n # @return [Object, nil] The preshared key, at least 32 hex digits. Required if either I(tls_connect) or I(tls_accept) has PSK enabled.\n attribute :tls_psk\n\n # @return [:present, :absent, nil] State of the proxy.,On C(present), it will create if proxy does not exist or update the proxy if the associated data is different.,On C(absent) will remove a proxy if it exists.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Dictionary with params for the interface when proxy is in passive mode,Available values are: dns, ip, main, port, type and useip.,Please review the interface documentation for more information on the supported properties,U(https://www.zabbix.com/documentation/3.2/manual/api/reference/proxy/object#proxy_interface)\n attribute :interface\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6971962451934814, "alphanum_fraction": 0.6990654468536377, "avg_line_length": 51.19512176513672, "blob_id": "19cc1f8841c0008d37cde68beb5e0daa6009bee8", "content_id": "947e5018494210cf0210b3a8b7390a3b02635059", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2140, "license_type": "permissive", "max_line_length": 183, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_availabilityset.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and delete Azure availability set. An availability set cannot be updated, you will have to recreate one instead. The only update operation will be for the tags.\n class Azure_rm_availabilityset < Base\n # @return [String] Name of a resource group where the availability set exists or will be created.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] Name of the availability set.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, nil] Assert the state of the availability set. Use 'present' to create or update a availability set and 'absent' to delete a availability set.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] Valid azure location. Defaults to location of the resource group.\n attribute :location\n validates :location, type: String\n\n # @return [Integer, nil] Update domains indicate groups of virtual machines and underlying physical hardware that can be rebooted at the same time. Default is 5.\n attribute :platform_update_domain_count\n validates :platform_update_domain_count, type: Integer\n\n # @return [Integer, nil] Fault domains define the group of virtual machines that share a common power source and network switch. Should be between 1 and 3. Default is 3\n attribute :platform_fault_domain_count\n validates :platform_fault_domain_count, type: Integer\n\n # @return [:Classic, :Aligned, nil] Define if the availability set supports managed disks.\n attribute :sku\n validates :sku, expression_inclusion: {:in=>[:Classic, :Aligned], :message=>\"%{value} needs to be :Classic, :Aligned\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6894317269325256, "alphanum_fraction": 0.6894317269325256, "avg_line_length": 54.72222137451172, "blob_id": "21f6461cb5986da5cd6bc136849fd1faa9d0c25c", "content_id": "6139e578ed6542b32f0bd0ddc553e38f3c31da20", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2006, "license_type": "permissive", "max_line_length": 342, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/network/aos/aos_device.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Apstra AOS Device module let you manage your devices in AOS easily. You can approve devices and define in which state the device should be. Currently only the state I(normal) is supported but the goal is to extend this module with additional state. This module is idempotent and support the I(check) mode. It's using the AOS REST API.\n class Aos_device < Base\n # @return [String] An existing AOS session as obtained by M(aos_login) module.\n attribute :session\n validates :session, presence: true, type: String\n\n # @return [String, nil] The device serial-number; i.e. uniquely identifies the device in the AOS system. Only one of I(name) or I(id) can be set.\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] The AOS internal id for a device; i.e. uniquely identifies the device in the AOS system. Only one of I(name) or I(id) can be set.\n attribute :id\n\n # @return [:normal, nil] Define in which state the device should be. Currently only I(normal) is supported but the goal is to add I(maint) and I(decomm).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:normal], :message=>\"%{value} needs to be :normal\"}, allow_nil: true\n\n # @return [:yes, :no, nil] The approve argument instruct the module to convert a device in quarantine mode into approved mode.\n attribute :approve\n validates :approve, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] When approving a device using the I(approve) argument, it's possible define the location of the device.\n attribute :location\n validates :location, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6302816867828369, "alphanum_fraction": 0.6302816867828369, "avg_line_length": 34.5, "blob_id": "3447facf2ec0a8132eba27b56f82206193bd83e3", "content_id": "01d5f970a1b551e409aaaab2d6a6f90367b02a20", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1704, "license_type": "permissive", "max_line_length": 143, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_instance_nic.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add and remove nic to and from network\n class Cs_instance_nic < Base\n # @return [String] Name of instance.\n attribute :vm\n validates :vm, presence: true, type: String\n\n # @return [String] Name of the network.\n attribute :network\n validates :network, presence: true, type: String\n\n # @return [String, nil] IP address to be used for the nic.\n attribute :ip_address\n validates :ip_address, type: String\n\n # @return [Object, nil] Name of the VPC the C(vm) is related to.\n attribute :vpc\n\n # @return [Object, nil] Domain the instance is related to.\n attribute :domain\n\n # @return [Object, nil] Account the instance is related to.\n attribute :account\n\n # @return [Object, nil] Name of the project the instance is deployed in.\n attribute :project\n\n # @return [Object, nil] Name of the zone in which the instance is deployed in.,If not set, default zone is used.\n attribute :zone\n\n # @return [:present, :absent, nil] State of the nic.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Poll async jobs until job has finished.\n attribute :poll_async\n validates :poll_async, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6722407937049866, "alphanum_fraction": 0.6722407937049866, "avg_line_length": 36.375, "blob_id": "3b4ebf6c2b94c2d662b109a29f143e8af3eac2d1", "content_id": "c4bea4c719317738ed52367d87b995dd0b3f0bca", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1196, "license_type": "permissive", "max_line_length": 143, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_security_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or Remove security groups from an OpenStack cloud.\n class Os_security_group < Base\n # @return [String] Name that has to be given to the security group. This module requires that security group names be unique.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Long description of the purpose of the security group\n attribute :description\n validates :description, type: String\n\n # @return [:present, :absent, nil] Should the resource be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Unique name or ID of the project.\n attribute :project\n validates :project, type: String\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6906318068504333, "alphanum_fraction": 0.6906318068504333, "avg_line_length": 48.17856979370117, "blob_id": "4b107f6450ebfec3f6177fd18ca287d227df3a43", "content_id": "ed0c136e0221842d7c648295acf178d93801c71a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1377, "license_type": "permissive", "max_line_length": 277, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/system/openwrt_init.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Controls OpenWrt services on remote hosts.\n class Openwrt_init < Base\n # @return [String] Name of the service.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:started, :stopped, :restarted, :reloaded, nil] C(started)/C(stopped) are idempotent actions that will not run commands unless necessary. C(restarted) will always bounce the service. C(reloaded) will always reload.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:started, :stopped, :restarted, :reloaded], :message=>\"%{value} needs to be :started, :stopped, :restarted, :reloaded\"}, allow_nil: true\n\n # @return [Symbol, nil] Whether the service should start on boot. B(At least one of state and enabled are required.)\n attribute :enabled\n validates :enabled, type: Symbol\n\n # @return [Object, nil] If the service does not respond to the 'running' command, name a substring to look for as would be found in the output of the I(ps) command as a stand-in for a 'running' result. If the string is found, the service will be assumed to be running.\n attribute :pattern\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6717436909675598, "alphanum_fraction": 0.6727941036224365, "avg_line_length": 50.4594612121582, "blob_id": "d63cd7919f42c74a00f7467ba0f4f129ffff0123", "content_id": "0f5305fa9131bda036d023daef08e76fe1513f59", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1904, "license_type": "permissive", "max_line_length": 293, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/files/xattr.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages filesystem user defined extended attributes, requires that they are enabled on the target filesystem and that the setfattr/getfattr utilities are present.\n class Xattr < Base\n # @return [String] The full path of the file/object to get the facts of.,Before 2.3 this option was only usable as I(name).\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [String, nil] Namespace of the named name/key.\n attribute :namespace\n validates :namespace, type: String\n\n # @return [String, nil] The name of a specific Extended attribute key to set/retrieve.\n attribute :key\n validates :key, type: String\n\n # @return [String, nil] The value to set the named name/key to, it automatically sets the C(state) to 'set'.\n attribute :value\n validates :value, type: String\n\n # @return [:absent, :all, :keys, :present, :read, nil] defines which state you want to do. C(read) retrieves the current value for a C(key) (default) C(present) sets C(name) to C(value), default if value is set C(all) dumps all data C(keys) retrieves all keys C(absent) deletes the key\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :all, :keys, :present, :read], :message=>\"%{value} needs to be :absent, :all, :keys, :present, :read\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(yes), dereferences symlinks and sets/gets attributes on symlink target, otherwise acts on symlink itself.\n attribute :follow\n validates :follow, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7295454740524292, "alphanum_fraction": 0.7295454740524292, "avg_line_length": 61.85714340209961, "blob_id": "f4dc17fe55641ec6049c562e241168a488f15b3b", "content_id": "88c0140ddef7e694fde289beff3999a2da80eb78", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1760, "license_type": "permissive", "max_line_length": 792, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_traffic_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Supports managing traffic groups and their attributes on a BIG-IP.\n class Bigip_traffic_group < Base\n # @return [String] The name of the traffic group.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [:present, :absent, nil] When C(present), ensures that the traffic group exists.,When C(absent), ensures the traffic group is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the floating Media Access Control (MAC) address associated with the floating IP addresses defined for a traffic group.,Primarily, a MAC masquerade address minimizes ARP communications or dropped packets as a result of failover.,A MAC masquerade address ensures that any traffic destined for a specific traffic group reaches an available device after failover, which happens because along with the traffic group, the MAC masquerade address floats to the available device.,Without a MAC masquerade address, the sending host must learn the MAC address for a newly-active device, either by sending an ARP request or by relying on the gratuitous ARP from the newly-active device.,To unset the MAC address, specify an empty value (C(\"\")) to this parameter.\n attribute :mac_address\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.672099232673645, "alphanum_fraction": 0.6786670088768005, "avg_line_length": 63.234375, "blob_id": "0269e733e655c26d016a07868c8a2f8d19f79aa8", "content_id": "df3613694a5ec9888920bd23e037c45c34234f7d", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4111, "license_type": "permissive", "max_line_length": 239, "num_lines": 64, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/netapp_e_storagepool.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or remove disk groups and disk pools for NetApp E-series storage arrays.\n class Netapp_e_storagepool < Base\n # @return [:present, :absent] Whether the specified storage pool should exist or not.,Note that removing a storage pool currently requires the removal of all defined volumes first.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String] The name of the storage pool to manage\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] The number of disks to use for building the storage pool. The pool will be expanded if this number exceeds the number of disks already in place\n attribute :criteria_drive_count\n\n # @return [:hdd, :ssd, nil] The type of disk (hdd or ssd) to use when searching for candidates to use.\n attribute :criteria_drive_type\n validates :criteria_drive_type, expression_inclusion: {:in=>[:hdd, :ssd], :message=>\"%{value} needs to be :hdd, :ssd\"}, allow_nil: true\n\n # @return [:bytes, :b, :kb, :mb, :gb, :tb, :pb, :eb, :zb, :yb, nil] The unit used to interpret size parameters\n attribute :criteria_size_unit\n validates :criteria_size_unit, expression_inclusion: {:in=>[:bytes, :b, :kb, :mb, :gb, :tb, :pb, :eb, :zb, :yb], :message=>\"%{value} needs to be :bytes, :b, :kb, :mb, :gb, :tb, :pb, :eb, :zb, :yb\"}, allow_nil: true\n\n # @return [Object, nil] The minimum individual drive size (in size_unit) to consider when choosing drives for the storage pool.\n attribute :criteria_drive_min_size\n\n # @return [Object, nil] The minimum size of the storage pool (in size_unit). The pool will be expanded if this value exceeds itscurrent size.\n attribute :criteria_min_usable_capacity\n\n # @return [:sas, :sas4k, :fibre, :fibre520b, :scsi, :sata, :pata, nil] The interface type to use when selecting drives for the storage pool (no value means all interface types will be considered)\n attribute :criteria_drive_interface_type\n validates :criteria_drive_interface_type, expression_inclusion: {:in=>[:sas, :sas4k, :fibre, :fibre520b, :scsi, :sata, :pata], :message=>\"%{value} needs to be :sas, :sas4k, :fibre, :fibre520b, :scsi, :sata, :pata\"}, allow_nil: true\n\n # @return [Object, nil] Whether full disk encryption ability is required for drives to be added to the storage pool\n attribute :criteria_drive_require_fde\n\n # @return [:raidAll, :raid0, :raid1, :raid3, :raid5, :raid6, :raidDiskPool] Only required when the requested state is 'present'. The RAID level of the storage pool to be created.\n attribute :raid_level\n validates :raid_level, presence: true, expression_inclusion: {:in=>[:raidAll, :raid0, :raid1, :raid3, :raid5, :raid6, :raidDiskPool], :message=>\"%{value} needs to be :raidAll, :raid0, :raid1, :raid3, :raid5, :raid6, :raidDiskPool\"}\n\n # @return [Symbol, nil] Whether to erase secured disks before adding to storage pool\n attribute :erase_secured_drives\n validates :erase_secured_drives, type: Symbol\n\n # @return [Symbol, nil] Whether to convert to a secure storage pool. Will only work if all drives in the pool are security capable.\n attribute :secure_pool\n validates :secure_pool, type: Symbol\n\n # @return [Object, nil] Set the number of drives reserved by the storage pool for reconstruction operations. Only valide on raid disk pools.\n attribute :reserve_drive_count\n\n # @return [Boolean, nil] Prior to removing a storage pool, delete all volumes in the pool.\n attribute :remove_volumes\n validates :remove_volumes, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.651583731174469, "alphanum_fraction": 0.651583731174469, "avg_line_length": 33, "blob_id": "6dd0b7437124935b0db6fd92a24ff234729971d7", "content_id": "f3cf3131934169d0976afce6ee659706ab1ce590", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1326, "license_type": "permissive", "max_line_length": 143, "num_lines": 39, "path": "/lib/ansible/ruby/modules/generated/database/postgresql/postgresql_ext.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove PostgreSQL extensions from a database.\n class Postgresql_ext < Base\n # @return [String] name of the extension to add or remove\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] name of the database to add or remove the extension to/from\n attribute :db\n validates :db, presence: true, type: String\n\n # @return [Object, nil] The username used to authenticate with\n attribute :login_user\n\n # @return [Object, nil] The password used to authenticate with\n attribute :login_password\n\n # @return [String, nil] Host running the database\n attribute :login_host\n validates :login_host, type: String\n\n # @return [Integer, nil] Database port to connect to.\n attribute :port\n validates :port, type: Integer\n\n # @return [:present, :absent, nil] The database extension state\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6902293562889099, "alphanum_fraction": 0.6958844065666199, "avg_line_length": 54.842105865478516, "blob_id": "611c2fd81be18280f565c5a18a49d49c89ffcc3e", "content_id": "2c76e13ab591f89f98820e271b1e2f108f93ee05", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3183, "license_type": "permissive", "max_line_length": 469, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_compute_health_check.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # An HealthCheck resource. This resource defines a template for how individual virtual machines should be checked for health, via one of the supported protocols.\n class Gcp_compute_health_check < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Integer, nil] How often (in seconds) to send a health check. The default value is 5 seconds.\n attribute :check_interval_sec\n validates :check_interval_sec, type: Integer\n\n # @return [Object, nil] An optional description of this resource. Provide this property when you create the resource.\n attribute :description\n\n # @return [Integer, nil] A so-far unhealthy instance will be marked healthy after this many consecutive successes. The default value is 2.\n attribute :healthy_threshold\n validates :healthy_threshold, type: Integer\n\n # @return [String, nil] Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash.\n attribute :name\n validates :name, type: String\n\n # @return [Integer, nil] How long (in seconds) to wait before claiming failure.,The default value is 5 seconds. It is invalid for timeoutSec to have greater value than checkIntervalSec.\n attribute :timeout_sec\n validates :timeout_sec, type: Integer\n\n # @return [Integer, nil] A so-far healthy instance will be marked unhealthy after this many consecutive failures. The default value is 2.\n attribute :unhealthy_threshold\n validates :unhealthy_threshold, type: Integer\n\n # @return [:TCP, :SSL, :HTTP, nil] Specifies the type of the healthCheck, either TCP, SSL, HTTP or HTTPS. If not specified, the default is TCP. Exactly one of the protocol-specific health check field must be specified, which must match type field.\n attribute :type\n validates :type, expression_inclusion: {:in=>[:TCP, :SSL, :HTTP], :message=>\"%{value} needs to be :TCP, :SSL, :HTTP\"}, allow_nil: true\n\n # @return [Object, nil] A nested object resource.\n attribute :http_health_check\n\n # @return [Object, nil] A nested object resource.\n attribute :https_health_check\n\n # @return [Hash, nil] A nested object resource.\n attribute :tcp_health_check\n validates :tcp_health_check, type: Hash\n\n # @return [Object, nil] A nested object resource.\n attribute :ssl_health_check\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6538922190666199, "alphanum_fraction": 0.6538922190666199, "avg_line_length": 28.821428298950195, "blob_id": "ecb5f1fe78d9d3b7205671924b0ab3fc91a85a3d", "content_id": "d809ed6dcdd4ff2058b2245ff5ffe7239c338b52", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 835, "license_type": "permissive", "max_line_length": 92, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/remote_management/hpilo/hponcfg.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This modules configures the HP iLO interface using hponcfg.\n class Hponcfg < Base\n # @return [Object] The XML file as accepted by hponcfg.\n attribute :path\n validates :path, presence: true\n\n # @return [Object, nil] The minimum firmware level needed.\n attribute :minfw\n\n # @return [String, nil] Path to the hponcfg executable (`hponcfg` which uses $PATH).\n attribute :executable\n validates :executable, type: String\n\n # @return [Symbol, nil] Run hponcfg in verbose mode (-v).\n attribute :verbose\n validates :verbose, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.659936249256134, "alphanum_fraction": 0.6748140454292297, "avg_line_length": 46.04999923706055, "blob_id": "2e4892ac70a35b60b5728525d6c5a6fb2b339103", "content_id": "ddde1e7d6e776f6b6068af9214bbcddc0c9f38ee", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1882, "license_type": "permissive", "max_line_length": 181, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_mlag_interface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages MLAG interface attributes on HUAWEI CloudEngine switches.\n class Ce_mlag_interface < Base\n # @return [Object, nil] Name of the local M-LAG interface. The value is ranging from 0 to 511.\n attribute :eth_trunk_id\n\n # @return [String, nil] ID of a DFS group.The value is 1.\n attribute :dfs_group_id\n validates :dfs_group_id, type: String\n\n # @return [Object, nil] ID of the M-LAG. The value is an integer that ranges from 1 to 2048.\n attribute :mlag_id\n\n # @return [Object, nil] M-LAG global LACP system MAC address. The value is a string of 0 to 255 characters. The default value is the MAC address of the Ethernet port of MPU.\n attribute :mlag_system_id\n\n # @return [Object, nil] M-LAG global LACP system priority. The value is an integer ranging from 0 to 65535. The default value is 32768.\n attribute :mlag_priority_id\n\n # @return [Object, nil] Name of the interface that enters the Error-Down state when the peer-link fails. The value is a string of 1 to 63 characters.\n attribute :interface\n\n # @return [:enable, :disable, nil] Configure the interface on the slave device to enter the Error-Down state.\n attribute :mlag_error_down\n validates :mlag_error_down, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Specify desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7052797675132751, "alphanum_fraction": 0.7057525515556335, "avg_line_length": 75.44578552246094, "blob_id": "cbc0b75eae20463bb07939b51d1ffa7d7ed16622", "content_id": "ac60ef67ce912bd144ff8ac1bbc8cc05159fd690", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 12690, "license_type": "permissive", "max_line_length": 469, "num_lines": 166, "path": "/lib/ansible/ruby/modules/generated/identity/keycloak/keycloak_client.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows the administration of Keycloak clients via the Keycloak REST API. It requires access to the REST API via OpenID Connect; the user connecting and the client being used must have the requisite access rights. In a default Keycloak installation, admin-cli and an admin user would work, as would a separate client definition with the scope tailored to your needs and a user having the expected roles.\n # The names of module options are snake_cased versions of the camelCase ones found in the Keycloak API and its documentation at U(http://www.keycloak.org/docs-api/3.3/rest-api/). Aliases are provided so camelCased versions can be used as well.\n # The Keycloak API does not always enforce for only sensible settings to be used -- you can set SAML-specific settings on an OpenID Connect client for instance and vice versa. Be careful. If you do not specify a setting, usually a sensible default is chosen.\n class Keycloak_client < Base\n # @return [:present, :absent, nil] State of the client,On C(present), the client will be created (or updated if it exists already).,On C(absent), the client will be removed if it exists\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] The realm to create the client in.\n attribute :realm\n validates :realm, type: String\n\n # @return [String, nil] Client id of client to be worked on. This is usually an alphanumeric name chosen by you. Either this or I(id) is required. If you specify both, I(id) takes precedence. This is 'clientId' in the Keycloak REST API.\n attribute :client_id\n validates :client_id, type: String\n\n # @return [String, nil] Id of client to be worked on. This is usually an UUID. Either this or I(client_id) is required. If you specify both, this takes precedence.\n attribute :id\n validates :id, type: String\n\n # @return [String, nil] Name of the client (this is not the same as I(client_id))\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] Description of the client in Keycloak\n attribute :description\n validates :description, type: String\n\n # @return [String, nil] Root URL appended to relative URLs for this client This is 'rootUrl' in the Keycloak REST API.\n attribute :root_url\n validates :root_url, type: String\n\n # @return [String, nil] URL to the admin interface of the client This is 'adminUrl' in the Keycloak REST API.\n attribute :admin_url\n validates :admin_url, type: String\n\n # @return [String, nil] Default URL to use when the auth server needs to redirect or link back to the client This is 'baseUrl' in the Keycloak REST API.\n attribute :base_url\n validates :base_url, type: String\n\n # @return [Boolean, nil] Is this client enabled or not?\n attribute :enabled\n validates :enabled, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:\"client-secret\", :\"client-jwt\", nil] How do clients authenticate with the auth server? Either C(client-secret) or C(client-jwt) can be chosen. When using C(client-secret), the module parameter I(secret) can set it, while for C(client-jwt), you can use the keys C(use.jwks.url), C(jwks.url), and C(jwt.credential.certificate) in the I(attributes) module parameter to configure its behavior. This is 'clientAuthenticatorType' in the Keycloak REST API.\n attribute :client_authenticator_type\n validates :client_authenticator_type, expression_inclusion: {:in=>[:\"client-secret\", :\"client-jwt\"], :message=>\"%{value} needs to be :\\\"client-secret\\\", :\\\"client-jwt\\\"\"}, allow_nil: true\n\n # @return [String, nil] When using I(client_authenticator_type) C(client-secret) (the default), you can specify a secret here (otherwise one will be generated if it does not exit). If changing this secret, the module will not register a change currently (but the changed secret will be saved).\n attribute :secret\n validates :secret, type: String\n\n # @return [String, nil] The registration access token provides access for clients to the client registration service. This is 'registrationAccessToken' in the Keycloak REST API.\n attribute :registration_access_token\n validates :registration_access_token, type: String\n\n # @return [Array<String>, String, nil] list of default roles for this client. If the client roles referenced do not exist yet, they will be created. This is 'defaultRoles' in the Keycloak REST API.\n attribute :default_roles\n validates :default_roles, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] Acceptable redirect URIs for this client. This is 'redirectUris' in the Keycloak REST API.\n attribute :redirect_uris\n validates :redirect_uris, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] List of allowed CORS origins. This is 'webOrigins' in the Keycloak REST API.\n attribute :web_origins\n validates :web_origins, type: TypeGeneric.new(String)\n\n # @return [Integer, nil] Revoke any tokens issued before this date for this client (this is a UNIX timestamp). This is 'notBefore' in the Keycloak REST API.\n attribute :not_before\n validates :not_before, type: Integer\n\n # @return [Boolean, nil] The access type of this client is bearer-only. This is 'bearerOnly' in the Keycloak REST API.\n attribute :bearer_only\n validates :bearer_only, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] If enabled, users have to consent to client access. This is 'consentRequired' in the Keycloak REST API.\n attribute :consent_required\n validates :consent_required, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Enable standard flow for this client or not (OpenID connect). This is 'standardFlowEnabled' in the Keycloak REST API.\n attribute :standard_flow_enabled\n validates :standard_flow_enabled, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Enable implicit flow for this client or not (OpenID connect). This is 'implictFlowEnabled' in the Keycloak REST API.\n attribute :implicit_flow_enabled\n validates :implicit_flow_enabled, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Are direct access grants enabled for this client or not (OpenID connect). This is 'directAccessGrantsEnabled' in the Keycloak REST API.\n attribute :direct_access_grants_enabled\n validates :direct_access_grants_enabled, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Are service accounts enabled for this client or not (OpenID connect). This is 'serviceAccountsEnabled' in the Keycloak REST API.\n attribute :service_accounts_enabled\n validates :service_accounts_enabled, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Are authorization services enabled for this client or not (OpenID connect). This is 'authorizationServicesEnabled' in the Keycloak REST API.\n attribute :authorization_services_enabled\n validates :authorization_services_enabled, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Is the access type for this client public or not. This is 'publicClient' in the Keycloak REST API.\n attribute :public_client\n validates :public_client, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Is frontchannel logout enabled for this client or not. This is 'frontchannelLogout' in the Keycloak REST API.\n attribute :frontchannel_logout\n validates :frontchannel_logout, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:\"openid-connect\", :saml, nil] Type of client (either C(openid-connect) or C(saml).\n attribute :protocol\n validates :protocol, expression_inclusion: {:in=>[:\"openid-connect\", :saml], :message=>\"%{value} needs to be :\\\"openid-connect\\\", :saml\"}, allow_nil: true\n\n # @return [Boolean, nil] Is the \"Full Scope Allowed\" feature set for this client or not. This is 'fullScopeAllowed' in the Keycloak REST API.\n attribute :full_scope_allowed\n validates :full_scope_allowed, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Integer, nil] Cluster node re-registration timeout for this client. This is 'nodeReRegistrationTimeout' in the Keycloak REST API.\n attribute :node_re_registration_timeout\n validates :node_re_registration_timeout, type: Integer\n\n # @return [Hash, nil] dict of registered cluster nodes (with C(nodename) as the key and last registration time as the value). This is 'registeredNodes' in the Keycloak REST API.\n attribute :registered_nodes\n validates :registered_nodes, type: Hash\n\n # @return [String, nil] Client template to use for this client. If it does not exist this field will silently be dropped. This is 'clientTemplate' in the Keycloak REST API.\n attribute :client_template\n validates :client_template, type: String\n\n # @return [Boolean, nil] Whether or not to use configuration from the I(client_template). This is 'useTemplateConfig' in the Keycloak REST API.\n attribute :use_template_config\n validates :use_template_config, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Whether or not to use scope configuration from the I(client_template). This is 'useTemplateScope' in the Keycloak REST API.\n attribute :use_template_scope\n validates :use_template_scope, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Whether or not to use mapper configuration from the I(client_template). This is 'useTemplateMappers' in the Keycloak REST API.\n attribute :use_template_mappers\n validates :use_template_mappers, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Whether or not surrogate auth is required. This is 'surrogateAuthRequired' in the Keycloak REST API.\n attribute :surrogate_auth_required\n validates :surrogate_auth_required, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] a data structure defining the authorization settings for this client. For reference, please see the Keycloak API docs at U(http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_resourceserverrepresentation). This is 'authorizationSettings' in the Keycloak REST API.\n attribute :authorization_settings\n\n # @return [Array<Hash>, Hash, nil] a list of dicts defining protocol mappers for this client. This is 'protocolMappers' in the Keycloak REST API.\n attribute :protocol_mappers\n validates :protocol_mappers, type: TypeGeneric.new(Hash)\n\n # @return [Hash, nil] A dict of further attributes for this client. This can contain various configuration settings; an example is given in the examples section. While an exhaustive list of permissible options is not available; possible options as of Keycloak 3.4 are listed below. The Keycloak API does not validate whether a given option is appropriate for the protocol used; if specified anyway, Keycloak will simply not use it.\n attribute :attributes\n validates :attributes, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6792828440666199, "alphanum_fraction": 0.6792828440666199, "avg_line_length": 40.83333206176758, "blob_id": "5c9093d39bf101d5ddd5d07d1dbdcaaa4925ad45", "content_id": "8f6c4f745528b28c541fe74d008b557281614c10", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1004, "license_type": "permissive", "max_line_length": 155, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_guest_boot_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to gather facts aboyt boot options for the given virtual machine.\n class Vmware_guest_boot_facts < Base\n # @return [String, nil] Name of the VM to work with.,This is required if C(uuid) parameter is not supplied.\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] UUID of the instance to manage if known, this is VMware's BIOS UUID.,This is required if C(name) parameter is not supplied.\n attribute :uuid\n\n # @return [:first, :last, nil] If multiple virtual machines matching the name, use the first or last found.\n attribute :name_match\n validates :name_match, expression_inclusion: {:in=>[:first, :last], :message=>\"%{value} needs to be :first, :last\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6937573552131653, "alphanum_fraction": 0.6949352025985718, "avg_line_length": 44.89189147949219, "blob_id": "77d8871efb145b5093f84bab135dc2e055c1a37a", "content_id": "e93887fee40ffdcb9418d6bb01c584e5267f6e67", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1698, "license_type": "permissive", "max_line_length": 170, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_evpn_vni.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages Cisco Ethernet Virtual Private Network (EVPN) VXLAN Network Identifier (VNI) configurations of a Nexus device.\n class Nxos_evpn_vni < Base\n # @return [Integer] The EVPN VXLAN Network Identifier.\n attribute :vni\n validates :vni, presence: true, type: Integer\n\n # @return [String] The VPN Route Distinguisher (RD). The RD is combined with the IPv4 or IPv6 prefix learned by the PE router to create a globally unique address.\n attribute :route_distinguisher\n validates :route_distinguisher, presence: true, type: String\n\n # @return [String, nil] Enables/Disables route-target settings for both import and export target communities using a single property.\n attribute :route_target_both\n validates :route_target_both, type: String\n\n # @return [Array<String>, String, nil] Sets the route-target 'import' extended communities.\n attribute :route_target_import\n validates :route_target_import, type: TypeGeneric.new(String)\n\n # @return [String, nil] Sets the route-target 'export' extended communities.\n attribute :route_target_export\n validates :route_target_export, type: String\n\n # @return [:present, :absent, nil] Determines whether the config should be present or not on the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.654904305934906, "alphanum_fraction": 0.654904305934906, "avg_line_length": 39.780487060546875, "blob_id": "e755156d49a52c9aadf26e46c4d82e7a97a03f56", "content_id": "16ee629a13823d051ce14d2656b842ac2bee4eb1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1672, "license_type": "permissive", "max_line_length": 211, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/network/ovs/openvswitch_db.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Set column values in record in database table.\n class Openvswitch_db < Base\n # @return [:present, :absent, nil] Configures the state of the key. When set to I(present), the I(key) and I(value) pair will be set on the I(record) and when set to I(absent) the I(key) will not be set.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] Identifies the table in the database.\n attribute :table\n validates :table, presence: true, type: String\n\n # @return [String] Identifies the recoard in the table.\n attribute :record\n validates :record, presence: true, type: String\n\n # @return [String] Identifies the column in the record.\n attribute :col\n validates :col, presence: true, type: String\n\n # @return [String, nil] Identifies the key in the record column, when the column is a map type.\n attribute :key\n validates :key, type: String\n\n # @return [Boolean] Expected value for the table, record, column and key.\n attribute :value\n validates :value, presence: true, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}\n\n # @return [Integer, nil] How long to wait for ovs-vswitchd to respond\n attribute :timeout\n validates :timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7338695526123047, "alphanum_fraction": 0.7342270016670227, "avg_line_length": 97.15789794921875, "blob_id": "3b71e4399d1c1eb82d6b366122feabbd31578949", "content_id": "7f6afc943c76eadb9638e16e56149494a7b76872", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5595, "license_type": "permissive", "max_line_length": 688, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/network/junos/junos_config.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides an implementation for working with the active configuration running on Juniper JUNOS devices. It provides a set of arguments for loading configuration, performing rollback operations and zeroing the active configuration on the device.\n class Junos_config < Base\n # @return [Array<String>, String, nil] This argument takes a list of C(set) or C(delete) configuration lines to push into the remote device. Each line must start with either C(set) or C(delete). This argument is mutually exclusive with the I(src) argument.\n attribute :lines\n validates :lines, type: TypeGeneric.new(String)\n\n # @return [String, nil] The I(src) argument provides a path to the configuration file to load into the remote system. The path can either be a full system path to the configuration file if the value starts with / or relative to the root of the implemented role or playbook. This argument is mutually exclusive with the I(lines) argument.\n attribute :src\n validates :src, type: String\n\n # @return [:xml, :set, :text, :json, nil] The I(src_format) argument specifies the format of the configuration found int I(src). If the I(src_format) argument is not provided, the module will attempt to determine the format of the configuration file specified in I(src).\n attribute :src_format\n validates :src_format, expression_inclusion: {:in=>[:xml, :set, :text, :json], :message=>\"%{value} needs to be :xml, :set, :text, :json\"}, allow_nil: true\n\n # @return [Integer, nil] The C(rollback) argument instructs the module to rollback the current configuration to the identifier specified in the argument. If the specified rollback identifier does not exist on the remote device, the module will fail. To rollback to the most recent commit, set the C(rollback) argument to 0.\n attribute :rollback\n validates :rollback, type: Integer\n\n # @return [Boolean, nil] The C(zeroize) argument is used to completely sanitize the remote device configuration back to initial defaults. This argument will effectively remove all current configuration statements on the remote device.\n attribute :zeroize\n validates :zeroize, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Integer, nil] The C(confirm) argument will configure a time out value in minutes for the commit to be confirmed before it is automatically rolled back. If the C(confirm) argument is set to False, this argument is silently ignored. If the value for this argument is set to 0, the commit is confirmed immediately.\n attribute :confirm\n validates :confirm, type: Integer\n\n # @return [String, nil] The C(comment) argument specifies a text string to be used when committing the configuration. If the C(confirm) argument is set to False, this argument is silently ignored.\n attribute :comment\n validates :comment, type: String\n\n # @return [:yes, :no, nil] The C(replace) argument will instruct the remote device to replace the current configuration hierarchy with the one specified in the corresponding hierarchy of the source configuration loaded from this module.,Note this argument should be considered deprecated. To achieve the equivalent, set the I(update) argument to C(replace). This argument will be removed in a future release. The C(replace) and C(update) argument is mutually exclusive.\n attribute :replace\n validates :replace, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] This argument will cause the module to create a full backup of the current C(running-config) from the remote device before any changes are made. The backup file is written to the C(backup) folder in the playbook root directory or role root directory, if playbook is part of an ansible role. If the directory does not exist, it is created.\n attribute :backup\n validates :backup, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:merge, :override, :replace, nil] This argument will decide how to load the configuration data particulary when the candidate configuration and loaded configuration contain conflicting statements. Following are accepted values. C(merge) combines the data in the loaded configuration with the candidate configuration. If statements in the loaded configuration conflict with statements in the candidate configuration, the loaded statements replace the candidate ones. C(override) discards the entire candidate configuration and replaces it with the loaded configuration. C(replace) substitutes each hierarchy level in the loaded configuration for the corresponding level.\n attribute :update\n validates :update, expression_inclusion: {:in=>[:merge, :override, :replace], :message=>\"%{value} needs to be :merge, :override, :replace\"}, allow_nil: true\n\n # @return [:yes, :no, nil] This argument will execute commit operation on remote device. It can be used to confirm a previous commit.\n attribute :confirm_commit\n validates :confirm_commit, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6184288263320923, "alphanum_fraction": 0.6491435170173645, "avg_line_length": 39.30952453613281, "blob_id": "5b7b55d5204e4ea5220e8d2212b7bb748486335c", "content_id": "f75049b9a75e9cf378538ec715624c3aa62039f4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1693, "license_type": "permissive", "max_line_length": 230, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_snmp_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages SNMP user configurations on CloudEngine switches.\n class Ce_snmp_user < Base\n # @return [Object, nil] Access control list number.\n attribute :acl_number\n\n # @return [Object, nil] Unique name to identify the USM user.\n attribute :usm_user_name\n\n # @return [Object, nil] Unique name to identify the local user.\n attribute :aaa_local_user\n\n # @return [Object, nil] Remote engine id of the USM user.\n attribute :remote_engine_id\n\n # @return [Object, nil] Name of the group where user belongs to.\n attribute :user_group\n\n # @return [:noAuth, :md5, :sha, nil] Authentication protocol.\n attribute :auth_protocol\n validates :auth_protocol, expression_inclusion: {:in=>[:noAuth, :md5, :sha], :message=>\"%{value} needs to be :noAuth, :md5, :sha\"}, allow_nil: true\n\n # @return [Object, nil] The authentication password. Password length, 8-255 characters.\n attribute :auth_key\n\n # @return [:noPriv, :des56, :\"3des168\", :aes128, :aes192, :aes256, nil] Encryption protocol.\n attribute :priv_protocol\n validates :priv_protocol, expression_inclusion: {:in=>[:noPriv, :des56, :\"3des168\", :aes128, :aes192, :aes256], :message=>\"%{value} needs to be :noPriv, :des56, :\\\"3des168\\\", :aes128, :aes192, :aes256\"}, allow_nil: true\n\n # @return [Object, nil] The encryption password. Password length 8-255 characters.\n attribute :priv_key\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6775911450386047, "alphanum_fraction": 0.6775911450386047, "avg_line_length": 46.86274337768555, "blob_id": "f994a427487fb03e2b643e02fc2b053c1d0be2dc", "content_id": "30083f96d0398b664807159e4b02ae537f66199a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2441, "license_type": "permissive", "max_line_length": 225, "num_lines": 51, "path": "/lib/ansible/ruby/modules/generated/cloud/rackspace/rax_files.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manipulate Rackspace Cloud Files Containers\n class Rax_files < Base\n # @return [:yes, :no, nil] Optionally clear existing metadata when applying metadata to existing containers. Selecting this option is only appropriate when setting type=meta\n attribute :clear_meta\n validates :clear_meta, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object] The container to use for container or metadata operations.\n attribute :container\n validates :container, presence: true\n\n # @return [Object, nil] A hash of items to set as metadata values on a container\n attribute :meta\n\n # @return [Object, nil] Used to set a container as private, removing it from the CDN. B(Warning!) Private containers, if previously made public, can have live objects available until the TTL on cached objects expires\n attribute :private\n\n # @return [Object, nil] Used to set a container as public, available via the Cloud Files CDN\n attribute :public\n\n # @return [String, nil] Region to create an instance in\n attribute :region\n validates :region, type: String\n\n # @return [:present, :absent, nil] Indicate desired state of the resource\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] In seconds, set a container-wide TTL for all objects cached on CDN edge nodes. Setting a TTL is only appropriate for containers that are public\n attribute :ttl\n\n # @return [:file, :meta, nil] Type of object to do work on, i.e. metadata object or a container object\n attribute :type\n validates :type, expression_inclusion: {:in=>[:file, :meta], :message=>\"%{value} needs to be :file, :meta\"}, allow_nil: true\n\n # @return [Object, nil] Sets an object to be presented as the HTTP error page when accessed by the CDN URL\n attribute :web_error\n\n # @return [Object, nil] Sets an object to be presented as the HTTP index page when accessed by the CDN URL\n attribute :web_index\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6929658055305481, "alphanum_fraction": 0.6929658055305481, "avg_line_length": 42.83333206176758, "blob_id": "00a2ef877a711899c491b6b74b50154b5b9fdbcd", "content_id": "a8258a783db0a97e7fd247284fb848deccbdef42", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1052, "license_type": "permissive", "max_line_length": 207, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/utilities/logic/include_tasks.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Includes a file with a list of tasks to be executed in the current playbook.\n class Include_tasks < Base\n # @return [String, nil] The name of the imported file is specified directly without any other option.,Unlike M(import_tasks), most keywords, including loops and conditionals, apply to this statement.\n attribute :file\n validates :file, type: String\n\n # @return [Hash, nil] Accepts a hash of task keywords (e.g. C(tags), C(become)) that will be applied to the tasks within the include.\n attribute :apply\n validates :apply, type: Hash\n\n # @return [Object, nil] Supplying a file name via free-form C(- include_tasks: file.yml) of a file to be included is the equivalent\\r\\nof specifying an argument of I(file).\\r\\n\n attribute :free_form, original_name: 'free-form'\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6858895421028137, "alphanum_fraction": 0.6858895421028137, "avg_line_length": 48.39393997192383, "blob_id": "9963587101c0db199a71b57f24d8ab96ea36b8e6", "content_id": "447ce4c70c67f10855a73a7d1011ecc4a693ab86", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1630, "license_type": "permissive", "max_line_length": 423, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/system/runit.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Controls runit services on remote hosts using the sv utility.\n class Runit < Base\n # @return [String] Name of the service to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:killed, :once, :reloaded, :restarted, :started, :stopped, nil] C(started)/C(stopped) are idempotent actions that will not run commands unless necessary. C(restarted) will always bounce the service (sv restart) and C(killed) will always bounce the service (sv force-stop). C(reloaded) will send a HUP (sv reload). C(once) will run a normally downed sv once (sv once), not really an idempotent operation.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:killed, :once, :reloaded, :restarted, :started, :stopped], :message=>\"%{value} needs to be :killed, :once, :reloaded, :restarted, :started, :stopped\"}, allow_nil: true\n\n # @return [Symbol, nil] Whether the service is enabled or not, if disabled it also implies stopped.\n attribute :enabled\n validates :enabled, type: Symbol\n\n # @return [String, nil] directory runsv watches for services\n attribute :service_dir\n validates :service_dir, type: String\n\n # @return [String, nil] directory where services are defined, the source of symlinks to service_dir.\n attribute :service_src\n validates :service_src, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6638211607933044, "alphanum_fraction": 0.6699187159538269, "avg_line_length": 47.235294342041016, "blob_id": "b6e2a6b1ec8b0432253efe26b17a1624c69deb13", "content_id": "ed77ddd57c27a47a718e14c736e7ddf68ae86c8e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2460, "license_type": "permissive", "max_line_length": 233, "num_lines": 51, "path": "/lib/ansible/ruby/modules/generated/cloud/centurylink/clc_loadbalancer.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # An Ansible module to Create, Delete shared loadbalancers in CenturyLink Cloud.\n class Clc_loadbalancer < Base\n # @return [String] The name of the loadbalancer\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] A description for the loadbalancer\n attribute :description\n\n # @return [Object] The alias of your CLC Account\n attribute :alias\n validates :alias, presence: true\n\n # @return [Object] The location of the datacenter where the load balancer resides in\n attribute :location\n validates :location, presence: true\n\n # @return [:leastConnection, :roundRobin, nil] -The balancing method for the load balancer pool\n attribute :method\n validates :method, expression_inclusion: {:in=>[:leastConnection, :roundRobin], :message=>\"%{value} needs to be :leastConnection, :roundRobin\"}, allow_nil: true\n\n # @return [:standard, :sticky, nil] The persistence method for the load balancer\n attribute :persistence\n validates :persistence, expression_inclusion: {:in=>[:standard, :sticky], :message=>\"%{value} needs to be :standard, :sticky\"}, allow_nil: true\n\n # @return [80, 443, nil] Port to configure on the public-facing side of the load balancer pool\n attribute :port\n validates :port, expression_inclusion: {:in=>[80, 443], :message=>\"%{value} needs to be 80, 443\"}, allow_nil: true\n\n # @return [Object, nil] A list of nodes that needs to be added to the load balancer pool\n attribute :nodes\n\n # @return [:enabled, :disabled, nil] The status of the loadbalancer\n attribute :status\n validates :status, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:present, :absent, :port_absent, :nodes_present, :nodes_absent, nil] Whether to create or delete the load balancer pool\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :port_absent, :nodes_present, :nodes_absent], :message=>\"%{value} needs to be :present, :absent, :port_absent, :nodes_present, :nodes_absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6853776574134827, "alphanum_fraction": 0.6853776574134827, "avg_line_length": 41.44117736816406, "blob_id": "56fefdddd9047875abd42ba6af09cce37b5fe077", "content_id": "941cee2c388bce4d1020537be179e91b5b69f78d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1443, "license_type": "permissive", "max_line_length": 162, "num_lines": 34, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_pim_rp_address.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages configuration of an Protocol Independent Multicast (PIM) static rendezvous point (RP) address instance.\n class Nxos_pim_rp_address < Base\n # @return [String] Configures a Protocol Independent Multicast (PIM) static rendezvous point (RP) address. Valid values are unicast addresses.\n attribute :rp_address\n validates :rp_address, presence: true, type: String\n\n # @return [Object, nil] Group range for static RP. Valid values are multicast addresses.\n attribute :group_list\n\n # @return [Object, nil] Prefix list policy for static RP. Valid values are prefix-list policy names.\n attribute :prefix_list\n\n # @return [Object, nil] Route map policy for static RP. Valid values are route-map policy names.\n attribute :route_map\n\n # @return [Symbol, nil] Group range is treated in PIM bidirectional mode.\n attribute :bidir\n validates :bidir, type: Symbol\n\n # @return [:present, :absent, :default] Specify desired state of the resource.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent, :default], :message=>\"%{value} needs to be :present, :absent, :default\"}\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.671480119228363, "alphanum_fraction": 0.672382652759552, "avg_line_length": 38.57143020629883, "blob_id": "5635428359cfce1af1b52e5d946b27eeeb2aae88", "content_id": "337b5a7414416145a3ce716cee69103ad3a3ae0c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1108, "license_type": "permissive", "max_line_length": 157, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_rpm.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Install software maintenance upgrade (smu) RPMS and 3rd party RPMS on Cisco NX-OS devices.\n class Nxos_rpm < Base\n # @return [String] Name of the RPM package.\n attribute :pkg\n validates :pkg, presence: true, type: String\n\n # @return [String, nil] The remote file system of the device. If omitted, devices that support a file_system parameter will use their default values.\n attribute :file_system\n validates :file_system, type: String\n\n # @return [Object, nil] List of RPM/patch definitions.\n attribute :aggregate\n\n # @return [:present, :absent, nil] If the state is present, the rpm will be installed, If the state is absent, it will be removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6549749374389648, "alphanum_fraction": 0.6549749374389648, "avg_line_length": 41.33333206176758, "blob_id": "7a024e9fa23ca430582b4306d36d8f651bec67f1", "content_id": "7dbeac346615d50eb3b18dd42d8d39dbf4fc6771", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1397, "license_type": "permissive", "max_line_length": 210, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/source_control/github_key.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates, removes, or updates GitHub access keys.\n class Github_key < Base\n # @return [String] GitHub Access Token with permission to list and create public keys.\n attribute :token\n validates :token, presence: true, type: String\n\n # @return [String] SSH key name\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] SSH public key value. Required when C(state=present).\n attribute :pubkey\n validates :pubkey, type: String\n\n # @return [:present, :absent, nil] Whether to remove a key, ensure that it exists, or update its value.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:yes, :no, nil] The default is C(yes), which will replace the existing remote key if it's different than C(pubkey). If C(no), the key will only be set if no key with the given C(name) exists.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6436170339584351, "alphanum_fraction": 0.6499999761581421, "avg_line_length": 36.599998474121094, "blob_id": "f307e8b09ad995e49c37a4d56639af18b3b9a3a3", "content_id": "d23a9b1263793f1b103039be243d3d3f496d7541", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 940, "license_type": "permissive", "max_line_length": 143, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_ntp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or delete or modify NTP server in ONTAP\n class Na_ontap_ntp < Base\n # @return [:present, :absent, nil] Whether the specified NTP server should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object] The name of the NTP server to manage.\n attribute :server_name\n validates :server_name, presence: true\n\n # @return [:auto, 3, 4, nil] give version for NTP server\n attribute :version\n validates :version, expression_inclusion: {:in=>[:auto, 3, 4], :message=>\"%{value} needs to be :auto, 3, 4\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6956128478050232, "alphanum_fraction": 0.6965174078941345, "avg_line_length": 60.41666793823242, "blob_id": "de41b5084e42b85fd2302e19d0fb6e1055d906f4", "content_id": "b4b443b2cd896eaadbc518b04968398d90f4ab4a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2211, "license_type": "permissive", "max_line_length": 331, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_waf_web_acl.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Read the AWS documentation for WAF U(https://aws.amazon.com/documentation/waf/)\n class Aws_waf_web_acl < Base\n # @return [String] Name of the Web Application Firewall ACL to manage\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:block, :allow, :count, nil] The action that you want AWS WAF to take when a request doesn't match the criteria specified in any of the Rule objects that are associated with the WebACL\n attribute :default_action\n validates :default_action, expression_inclusion: {:in=>[:block, :allow, :count], :message=>\"%{value} needs to be :block, :allow, :count\"}, allow_nil: true\n\n # @return [:present, :absent, nil] whether the Web ACL should be present or absent\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] A friendly name or description for the metrics for this WebACL,The name can contain only alphanumeric characters (A-Z, a-z, 0-9); the name can't contain whitespace.,You can't change metric_name after you create the WebACL,Metric name will default to I(name) with disallowed characters stripped out\n attribute :metric_name\n\n # @return [Array<Hash>, Hash, nil] A list of rules that the Web ACL will enforce.,Each rule must contain I(name), I(action), I(priority) keys.,Priorities must be unique, but not necessarily consecutive. Lower numbered priorities are evalauted first.,The I(type) key can be passed as C(rate_based), it defaults to C(regular)\n attribute :rules\n validates :rules, type: TypeGeneric.new(Hash)\n\n # @return [Boolean, nil] Whether to remove rules that aren't passed with C(rules). Defaults to false\n attribute :purge_rules\n validates :purge_rules, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6608811616897583, "alphanum_fraction": 0.6608811616897583, "avg_line_length": 31.565217971801758, "blob_id": "652290f9794ec9cce83f2b6fa52b3b5cbd5f2b0c", "content_id": "63cf7db4e8c64eb523f070ed74a48df5c0369dd9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 749, "license_type": "permissive", "max_line_length": 143, "num_lines": 23, "path": "/lib/ansible/ruby/modules/generated/cloud/rackspace/rax_network.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # creates / deletes a Rackspace Public Cloud isolated network.\n class Rax_network < Base\n # @return [:present, :absent, nil] Indicate desired state of the resource\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Label (name) to give the network\n attribute :label\n\n # @return [Object, nil] cidr of the network being created\n attribute :cidr\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6645569801330566, "alphanum_fraction": 0.6671940684318542, "avg_line_length": 42.09090805053711, "blob_id": "ab5ef46c9764bf01a5d75c116bedc6171f1ca1be", "content_id": "a1aabde22db919fcc9249c9fa309056c4e00990f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1896, "license_type": "permissive", "max_line_length": 161, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/network/ovs/openvswitch_bridge.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage Open vSwitch bridges\n class Openvswitch_bridge < Base\n # @return [String] Name of bridge or fake bridge to manage\n attribute :bridge\n validates :bridge, presence: true, type: String\n\n # @return [String, nil] Bridge parent of the fake bridge to manage\n attribute :parent\n validates :parent, type: String\n\n # @return [Integer, nil] The VLAN id of the fake bridge to manage (must be between 0 and 4095). This parameter is required if I(parent) parameter is set.\n attribute :vlan\n validates :vlan, type: Integer\n\n # @return [:present, :absent, nil] Whether the bridge should exist\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Integer, nil] How long to wait for ovs-vswitchd to respond\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [Hash, nil] A dictionary of external-ids. Omitting this parameter is a No-op. To clear all external-ids pass an empty value.\n attribute :external_ids\n validates :external_ids, type: Hash\n\n # @return [:secure, :standalone, nil] Set bridge fail-mode. The default value (None) is a No-op.\n attribute :fail_mode\n validates :fail_mode, expression_inclusion: {:in=>[:secure, :standalone], :message=>\"%{value} needs to be :secure, :standalone\"}, allow_nil: true\n\n # @return [Object, nil] Run set command after bridge configuration. This parameter is non-idempotent, play will always return I(changed) state if present\n attribute :set\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7021517753601074, "alphanum_fraction": 0.7021517753601074, "avg_line_length": 35.79166793823242, "blob_id": "882ce67b5ad9ff80e62a8d7c4bc9d1babf387c71", "content_id": "ae5ad81df7ce7a9248f48354c37df4098ead5b5f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 883, "license_type": "permissive", "max_line_length": 277, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_port_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Retrieve facts about ports from OpenStack.\n class Os_port_facts < Base\n # @return [String, nil] Unique name or ID of a port.\n attribute :port\n validates :port, type: String\n\n # @return [Hash, nil] A dictionary of meta data to use for further filtering. Elements of this dictionary will be matched against the returned port dictionaries. Matching is currently limited to strings within the port dictionary, or strings within nested dictionaries.\n attribute :filters\n validates :filters, type: Hash\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6439942121505737, "alphanum_fraction": 0.6439942121505737, "avg_line_length": 37.38888931274414, "blob_id": "6954e11991151a0cef3100b3059bec94f3ffc499", "content_id": "43db303dfd2aa52010bc9b4bda8cb31b0a89c0a0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1382, "license_type": "permissive", "max_line_length": 143, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/ansible_tower/tower_host.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, or destroy Ansible Tower hosts. See U(https://www.ansible.com/tower) for an overview.\n class Tower_host < Base\n # @return [String] The name to use for the host.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The description to use for the host.\n attribute :description\n validates :description, type: String\n\n # @return [String] Inventory the host should be made a member of.\n attribute :inventory\n validates :inventory, presence: true, type: String\n\n # @return [:yes, :no, nil] If the host should be enabled.\n attribute :enabled\n validates :enabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Variables to use for the host. Use C(@) for a file.\n attribute :variables\n\n # @return [:present, :absent, nil] Desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6476816534996033, "alphanum_fraction": 0.6593647599220276, "avg_line_length": 43.90163803100586, "blob_id": "dc26f4d2014b41e611a95b81306975f1f0d0bb89", "content_id": "c40638de167affb271d9933dcea533425fefe256", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2739, "license_type": "permissive", "max_line_length": 355, "num_lines": 61, "path": "/lib/ansible/ruby/modules/generated/net_tools/infinity/infinity.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage Infinity IPAM using REST API\n class Infinity < Base\n # @return [Object] Infinity server_ip with IP address\n attribute :server_ip\n validates :server_ip, presence: true\n\n # @return [Object] Username to access Infinity,The user must have Rest API privileges\n attribute :username\n validates :username, presence: true\n\n # @return [Object] Infinity password\n attribute :password\n validates :password, presence: true\n\n # @return [:reserve_next_available_ip, :release_ip, :delete_network, :add_network, :reserve_network, :release_network, :get_network_id] Action to perform\n attribute :action\n validates :action, presence: true, expression_inclusion: {:in=>[:reserve_next_available_ip, :release_ip, :delete_network, :add_network, :reserve_network, :release_network, :get_network_id], :message=>\"%{value} needs to be :reserve_next_available_ip, :release_ip, :delete_network, :add_network, :reserve_network, :release_network, :get_network_id\"}\n\n # @return [String, nil] Network ID\n attribute :network_id\n validates :network_id, type: String\n\n # @return [String, nil] IP Address for a reservation or a release\n attribute :ip_address\n validates :ip_address, type: String\n\n # @return [String, nil] Network address with CIDR format (e.g., 192.168.310.0)\n attribute :network_address\n validates :network_address, type: String\n\n # @return [String, nil] Network bitmask (e.g. 255.255.255.220) or CIDR format (e.g., /26)\n attribute :network_size\n validates :network_size, type: String\n\n # @return [String, nil] The name of a network\n attribute :network_name\n validates :network_name, type: String\n\n # @return [Integer, nil] the parent network id for a given network\n attribute :network_location\n validates :network_location, type: Integer\n\n # @return [:lan, :shared_lan, :supernet, nil] Network type defined by Infinity\n attribute :network_type\n validates :network_type, expression_inclusion: {:in=>[:lan, :shared_lan, :supernet], :message=>\"%{value} needs to be :lan, :shared_lan, :supernet\"}, allow_nil: true\n\n # @return [4, 6, :dual, nil] Network family defined by Infinity, e.g. IPv4, IPv6 and Dual stack\n attribute :network_family\n validates :network_family, expression_inclusion: {:in=>[4, 6, :dual], :message=>\"%{value} needs to be 4, 6, :dual\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.681560754776001, "alphanum_fraction": 0.6840780377388, "avg_line_length": 43.13888931274414, "blob_id": "944415aeabea0e61fff09cd59ef222663b6ddae3", "content_id": "64b5f5e75d8164cd3a4cfa4ed674d9eb9ec8d166", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1589, "license_type": "permissive", "max_line_length": 159, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_switch_policy_vpc_protection_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage switch policy explicit vPC protection groups on Cisco ACI fabrics.\n class Aci_switch_policy_vpc_protection_group < Base\n # @return [String] The name of the Explicit vPC Protection Group.\n attribute :protection_group\n validates :protection_group, presence: true, type: String\n\n # @return [Integer] The Explicit vPC Protection Group ID.\n attribute :protection_group_id\n validates :protection_group_id, presence: true, type: Integer\n\n # @return [Object, nil] The vPC domain policy to be associated with the Explicit vPC Protection Group.\n attribute :vpc_domain_policy\n\n # @return [Integer] The ID of the first Leaf Switch for the Explicit vPC Protection Group.\n attribute :switch_1_id\n validates :switch_1_id, presence: true, type: Integer\n\n # @return [Integer] The ID of the Second Leaf Switch for the Explicit vPC Protection Group.\n attribute :switch_2_id\n validates :switch_2_id, presence: true, type: Integer\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6516368389129639, "alphanum_fraction": 0.6516368389129639, "avg_line_length": 39.474998474121094, "blob_id": "dd12e651d7bd053a7ca328e59f9a7545c2248b61", "content_id": "b0820c7cbd7373eed09880f0b6dbecf0afd6f54b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1619, "license_type": "permissive", "max_line_length": 162, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_fabric_node.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage Fabric Node Members on Cisco ACI fabrics.\n class Aci_fabric_node < Base\n # @return [Integer, nil] The pod id of the new Fabric Node Member.\n attribute :pod_id\n validates :pod_id, type: Integer\n\n # @return [String, nil] Serial Number for the new Fabric Node Member.\n attribute :serial\n validates :serial, type: String\n\n # @return [Integer, nil] Node ID Number for the new Fabric Node Member.\n attribute :node_id\n validates :node_id, type: Integer\n\n # @return [String, nil] Switch Name for the new Fabric Node Member.\n attribute :switch\n validates :switch, type: String\n\n # @return [Object, nil] Description for the new Fabric Node Member.\n attribute :description\n\n # @return [:leaf, :spine, :unspecified, nil] Role for the new Fabric Node Member.\n attribute :role\n validates :role, expression_inclusion: {:in=>[:leaf, :spine, :unspecified], :message=>\"%{value} needs to be :leaf, :spine, :unspecified\"}, allow_nil: true\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.653298556804657, "alphanum_fraction": 0.6568580865859985, "avg_line_length": 46.34831619262695, "blob_id": "4174c5dabc43202fba4cc26c97bca5fadc408f16", "content_id": "93b866913c86fca43f61988819c49415b2c412d5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4214, "license_type": "permissive", "max_line_length": 149, "num_lines": 89, "path": "/lib/ansible/ruby/modules/generated/monitoring/statusio_maintenance.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates a maintenance window for status.io\n # Deletes a maintenance window for status.io\n class Statusio_maintenance < Base\n # @return [String, nil] A descriptive title for the maintenance window\n attribute :title\n validates :title, type: String\n\n # @return [String, nil] Message describing the maintenance window\n attribute :desc\n validates :desc, type: String\n\n # @return [:present, :absent, nil] Desired state of the package.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] Your unique API ID from status.io\n attribute :api_id\n validates :api_id, presence: true, type: String\n\n # @return [String] Your unique API Key from status.io\n attribute :api_key\n validates :api_key, presence: true, type: String\n\n # @return [String] Your unique StatusPage ID from status.io\n attribute :statuspage\n validates :statuspage, presence: true, type: String\n\n # @return [String, nil] Status.io API URL. A private apiary can be used instead.\n attribute :url\n validates :url, type: String\n\n # @return [Array<String>, String, nil] The given name of your component (server name)\n attribute :components\n validates :components, type: TypeGeneric.new(String)\n\n # @return [Object, nil] The given name of your container (data center)\n attribute :containers\n\n # @return [:yes, :no, nil] If it affects all components and containers\n attribute :all_infrastructure_affected\n validates :all_infrastructure_affected, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Automatically start and end the maintenance window\n attribute :automation\n validates :automation, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Notify subscribers now\n attribute :maintenance_notify_now\n validates :maintenance_notify_now, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Notify subscribers 72 hours before maintenance start time\n attribute :maintenance_notify_72_hr\n validates :maintenance_notify_72_hr, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Notify subscribers 24 hours before maintenance start time\n attribute :maintenance_notify_24_hr\n validates :maintenance_notify_24_hr, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Notify subscribers 1 hour before maintenance start time\n attribute :maintenance_notify_1_hr\n validates :maintenance_notify_1_hr, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] The maintenance id number when deleting a maintenance window\n attribute :maintenance_id\n validates :maintenance_id, type: String\n\n # @return [Integer, nil] The length of time in UTC that the maintenance will run (starting from playbook runtime)\n attribute :minutes\n validates :minutes, type: Integer\n\n # @return [String, nil] Date maintenance is expected to start (Month/Day/Year) (UTC),End Date is worked out from start_date + minutes\n attribute :start_date\n validates :start_date, type: String\n\n # @return [Integer, nil] Time maintenance is expected to start (Hour:Minutes) (UTC),End Time is worked out from start_time + minutes\n attribute :start_time\n validates :start_time, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7137080430984497, "alphanum_fraction": 0.714112401008606, "avg_line_length": 53.9555549621582, "blob_id": "8c0617e900ad175cef5633581675f0b8011d1fc6", "content_id": "24de64f2a55e3748e81755b50cf63b766df48404", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2473, "license_type": "permissive", "max_line_length": 278, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/monitoring/logicmonitor_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # LogicMonitor is a hosted, full-stack, infrastructure monitoring platform.\n # This module collects facts about hosts and host groups within your LogicMonitor account.\n class Logicmonitor_facts < Base\n # @return [:host, :hostgroup] The LogicMonitor object you wish to manage.\n attribute :target\n validates :target, presence: true, expression_inclusion: {:in=>[:host, :hostgroup], :message=>\"%{value} needs to be :host, :hostgroup\"}\n\n # @return [String] The LogicMonitor account company name. If you would log in to your account at \"superheroes.logicmonitor.com\" you would use \"superheroes\".\n attribute :company\n validates :company, presence: true, type: String\n\n # @return [String] A LogicMonitor user name. The module will authenticate and perform actions on behalf of this user.\n attribute :user\n validates :user, presence: true, type: String\n\n # @return [Array<String>, String] The password for the chosen LogicMonitor User.,If an md5 hash is used, the digest flag must be set to true.\n attribute :password\n validates :password, presence: true, type: TypeGeneric.new(String)\n\n # @return [Object, nil] The fully qualified domain name of a collector in your LogicMonitor account.,This is optional for querying a LogicMonitor host when a displayname is specified.,This is required for querying a LogicMonitor host when a displayname is not specified.\n attribute :collector\n\n # @return [String, nil] The hostname of a host in your LogicMonitor account, or the desired hostname of a device to add into monitoring.,Required for managing hosts (target=host).\n attribute :hostname\n validates :hostname, type: String\n\n # @return [String, nil] The display name of a host in your LogicMonitor account or the desired display name of a device to add into monitoring.\n attribute :displayname\n validates :displayname, type: String\n\n # @return [String, nil] The fullpath of the hostgroup object you would like to manage.,Recommend running on a single ansible host.,Required for management of LogicMonitor host groups (target=hostgroup).\n attribute :fullpath\n validates :fullpath, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7226690053939819, "alphanum_fraction": 0.7287546396255493, "avg_line_length": 76.98304748535156, "blob_id": "bae39cb02785bd54ebfa86a6dba7f5cb0440b8f0", "content_id": "1155b0de7c4a83830c61f440012beded7cabbe40", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4601, "license_type": "permissive", "max_line_length": 649, "num_lines": 59, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_compute_image.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Represents an Image resource.\n # Google Compute Engine uses operating system images to create the root persistent disks for your instances. You specify an image when you create an instance. Images contain a boot loader, an operating system, and a root file system. Linux operating system images are also capable of running containers on Compute Engine.\n # Images can be either public or custom.\n # Public images are provided and maintained by Google, open-source communities, and third-party vendors. By default, all projects have access to these images and can use them to create instances. Custom images are available only to your project. You can create a custom image from root persistent disks and other images. Then, use the custom image to create an instance.\n class Gcp_compute_image < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] An optional description of this resource. Provide this property when you create the resource.\n attribute :description\n\n # @return [Object, nil] Size of the image when restored onto a persistent disk (in GB).\n attribute :disk_size_gb\n\n # @return [Object, nil] The name of the image family to which this image belongs. You can create disks by specifying an image family instead of a specific image name. The image family always returns its latest image that is not deprecated. The name of the image family must comply with RFC1035.\n attribute :family\n\n # @return [Object, nil] A list of features to enable on the guest OS. Applicable for bootable images only. Currently, only one feature can be enabled, VIRTIO_SCSI_MULTIQUEUE, which allows each virtual CPU to have its own queue. For Windows images, you can only enable VIRTIO_SCSI_MULTIQUEUE on images with driver version 1.2.0.1621 or higher. Linux images with kernel versions 3.17 and higher will support VIRTIO_SCSI_MULTIQUEUE.,For new Windows images, the server might also populate this field with the value WINDOWS, to indicate that this is a Windows image.,This value is purely informational and does not enable or disable any features.\n attribute :guest_os_features\n\n # @return [Object, nil] Encrypts the image using a customer-supplied encryption key.,After you encrypt an image with a customer-supplied key, you must provide the same key if you use the image later (e.g. to create a disk from the image) .\n attribute :image_encryption_key\n\n # @return [Object, nil] Any applicable license URI.\n attribute :licenses\n\n # @return [String] Name of the resource; provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] The parameters of the raw disk image.\n attribute :raw_disk\n\n # @return [String, nil] Refers to a gcompute_disk object You must provide either this property or the rawDisk.source property but not both to create an image.\n attribute :source_disk\n validates :source_disk, type: String\n\n # @return [Object, nil] The customer-supplied encryption key of the source disk. Required if the source disk is protected by a customer-supplied encryption key.\n attribute :source_disk_encryption_key\n\n # @return [Object, nil] The ID value of the disk used to create this image. This value may be used to determine whether the image was taken from the current or a previous instance of a given disk name.\n attribute :source_disk_id\n\n # @return [:RAW, nil] The type of the image used to create this disk. The default and only value is RAW .\n attribute :source_type\n validates :source_type, expression_inclusion: {:in=>[:RAW], :message=>\"%{value} needs to be :RAW\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6849299669265747, "alphanum_fraction": 0.6860596537590027, "avg_line_length": 68.15625, "blob_id": "5743e42a5bbcb633fe2e9259830f43b1a965c5bb", "content_id": "66679f69bb34d34a7c4a8b4464f5ce05c48a435b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 8852, "license_type": "permissive", "max_line_length": 379, "num_lines": 128, "path": "/lib/ansible/ruby/modules/generated/system/user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage user accounts and user attributes.\n # For Windows targets, use the M(win_user) module instead.\n class User < Base\n # @return [String] Name of the user to create, remove or modify.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Integer, nil] Optionally sets the I(UID) of the user.\n attribute :uid\n validates :uid, type: Integer\n\n # @return [String, nil] Optionally sets the description (aka I(GECOS)) of user account.\n attribute :comment\n validates :comment, type: String\n\n # @return [Symbol, nil] macOS only, optionally hide the user from the login window and system preferences.,The default will be 'True' if the I(system) option is used.\n attribute :hidden\n validates :hidden, type: Symbol\n\n # @return [:yes, :no, nil] Optionally when used with the -u option, this option allows to change the user ID to a non-unique value.\n attribute :non_unique\n validates :non_unique, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Optionally sets the seuser type (user_u) on selinux enabled systems.\n attribute :seuser\n\n # @return [String, nil] Optionally sets the user's primary group (takes a group name).\n attribute :group\n validates :group, type: String\n\n # @return [Array<String>, String, nil] List of groups user will be added to. When set to an empty string C(''), C(null), or C(~), the user is removed from all groups except the primary group. (C(~) means C(null) in YAML),Before version 2.3, the only input format allowed was a comma separated string. Now this parameter accepts a list as well as a comma separated string.\n attribute :groups\n validates :groups, type: TypeGeneric.new(String)\n\n # @return [:yes, :no, nil] If C(yes), add the user to the groups specified in C(groups).,If C(no), user will only be added to the groups specified in C(groups), removing them from all other groups.\n attribute :append\n validates :append, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Optionally set the user's shell.,On macOS, before version 2.5, the default shell for non-system users was /usr/bin/false. Since 2.5, the default shell for non-system users on macOS is /bin/bash.,On other operating systems, the default shell is determined by the underlying tool being used. See Notes for details.\n attribute :shell\n validates :shell, type: String\n\n # @return [Object, nil] Optionally set the user's home directory.\n attribute :home\n\n # @return [Object, nil] Optionally set a home skeleton directory. Requires create_home option!\n attribute :skeleton\n\n # @return [Object, nil] Optionally set the user's password to this crypted value.,On macOS systems, this value has to be cleartext. Beware of security issues.,See U(https://docs.ansible.com/ansible/faq.html#how-do-i-generate-crypted-passwords-for-the-user-module) for details on various ways to generate these password values.\n attribute :password\n\n # @return [:absent, :present, nil] Whether the account should exist or not, taking action if the state is different from what is stated.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Unless set to C(no), a home directory will be made for the user when the account is created or if the home directory does not exist.,Changed from C(createhome) to C(create_home) in version 2.5.\n attribute :create_home\n validates :create_home, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If set to C(yes) when used with C(home=), attempt to move the user's old home directory to the specified directory if it isn't there already and the old home exists.\n attribute :move_home\n validates :move_home, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] When creating an account C(state=present), setting this to C(yes) makes the user a system account. This setting cannot be changed on existing users.\n attribute :system\n validates :system, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] This only affects C(state=absent), it forces removal of the user and associated directories on supported platforms. The behavior is the same as C(userdel --force), check the man page for C(userdel) on your system for details and support.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] This only affects C(state=absent), it attempts to remove directories associated with the user. The behavior is the same as C(userdel --remove), check the man page for details and support.\n attribute :remove\n validates :remove, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Optionally sets the user's login class, a feature of most BSD OSs.\n attribute :login_class\n\n # @return [:yes, :no, nil] Whether to generate a SSH key for the user in question. This will B(not) overwrite an existing SSH key.\n attribute :generate_ssh_key\n validates :generate_ssh_key, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Optionally specify number of bits in SSH key to create.\n attribute :ssh_key_bits\n validates :ssh_key_bits, type: String\n\n # @return [String, nil] Optionally specify the type of SSH key to generate. Available SSH key types will depend on implementation present on target host.\n attribute :ssh_key_type\n validates :ssh_key_type, type: String\n\n # @return [String, nil] Optionally specify the SSH key filename. If this is a relative filename then it will be relative to the user's home directory.\n attribute :ssh_key_file\n validates :ssh_key_file, type: String\n\n # @return [String, nil] Optionally define the comment for the SSH key.\n attribute :ssh_key_comment\n validates :ssh_key_comment, type: String\n\n # @return [Object, nil] Set a passphrase for the SSH key. If no passphrase is provided, the SSH key will default to having no passphrase.\n attribute :ssh_key_passphrase\n\n # @return [:always, :on_create, nil] C(always) will update passwords if they differ. C(on_create) will only set the password for newly created users.\n attribute :update_password\n validates :update_password, expression_inclusion: {:in=>[:always, :on_create], :message=>\"%{value} needs to be :always, :on_create\"}, allow_nil: true\n\n # @return [Integer, nil] An expiry time for the user in epoch, it will be ignored on platforms that do not support this. Currently supported on GNU/Linux, FreeBSD, and DragonFlyBSD.,Since version 2.6 you can remove the expiry time specify a negative value. Currently supported on GNU/Linux and FreeBSD.\n attribute :expires\n validates :expires, type: Integer\n\n # @return [Symbol, nil] Lock the password (usermod -L, pw lock, usermod -C). BUT implementation differs on different platforms, this option does not always mean the user cannot login via other methods. This option does not disable the user, only lock the password. Do not change the password in the same task. Currently supported on Linux, FreeBSD, DragonFlyBSD, NetBSD.\n attribute :password_lock\n validates :password_lock, type: Symbol\n\n # @return [:yes, :no, nil] Forces the use of \"local\" command alternatives on platforms that implement it. This is useful in environments that use centralized authentification when you want to manipulate the local users. I.E. it uses `luseradd` instead of `useradd`.,This requires that these commands exist on the targeted host, otherwise it will be a fatal error.\n attribute :local\n validates :local, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6643533110618591, "alphanum_fraction": 0.6643533110618591, "avg_line_length": 43.02777862548828, "blob_id": "7cbc192476db07d18d1893af768314e1a83cdc1c", "content_id": "40bb4e3a1e4ad8fca7e1c81ecf493f9ca6605416", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1585, "license_type": "permissive", "max_line_length": 163, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_portchannel.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages port-channel specific configuration parameters.\n class Nxos_portchannel < Base\n # @return [Integer] Channel-group number for the port-channel.\n attribute :group\n validates :group, presence: true, type: Integer\n\n # @return [Boolean, nil] Mode for the port-channel, i.e. on, active, passive.\n attribute :mode\n validates :mode, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] Min links required to keep portchannel up.\n attribute :min_links\n\n # @return [Array<String>, String, nil] List of interfaces that will be managed in a given portchannel.\n attribute :members\n validates :members, type: TypeGeneric.new(String)\n\n # @return [:false, :true, nil] When true it forces port-channel members to match what is declared in the members param. This can be used to remove members.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:false, :true], :message=>\"%{value} needs to be :false, :true\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Manage the state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7003874182701111, "alphanum_fraction": 0.707131564617157, "avg_line_length": 91.91999816894531, "blob_id": "5042f4b8bd19f5e7e8c33eebd6f8c59f4b9a7678", "content_id": "4d57696bfd66eadb7f7825a3409009cc90e86b5e", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6969, "license_type": "permissive", "max_line_length": 635, "num_lines": 75, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_snmp_community.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Assists in managing SNMP communities on a BIG-IP. Different SNMP versions are supported by this module. Take note of the different parameters offered by this module, as different parameters work for different versions of SNMP. Typically this becomes an interest if you are mixing versions C(v2c) and C(3).\n class Bigip_snmp_community < Base\n # @return [:present, :absent, nil] When C(present), ensures that the address list and entries exists.,When C(absent), ensures the address list is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:v1, :v2c, :v3, nil] Specifies to which Simple Network Management Protocol (SNMP) version the trap destination applies.\n attribute :version\n validates :version, expression_inclusion: {:in=>[:v1, :v2c, :v3], :message=>\"%{value} needs to be :v1, :v2c, :v3\"}, allow_nil: true\n\n # @return [String, nil] Name that identifies the SNMP community.,When C(version) is C(v1) or C(v2c), this parameter is required.,The name C(public) is a reserved name on the BIG-IP. This module handles that name differently than others. Functionally, you should not see a difference however.\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] Specifies the community string (password) for access to the MIB.,This parameter is only relevant when C(version) is C(v1), or C(v2c). If C(version) is something else, this parameter is ignored.\n attribute :community\n\n # @return [String, nil] Specifies the source address for access to the MIB.,This parameter can accept a value of C(all).,If this parameter is not specified, the value C(all) is used.,This parameter is only relevant when C(version) is C(v1), or C(v2c). If C(version) is something else, this parameter is ignored.,If C(source) is set to C(all), then it is not possible to specify an C(oid). This will raise an error.,This parameter should be provided when C(state) is C(absent), so that the correct community is removed. To remove the C(public) SNMP community that comes with a BIG-IP, this parameter should be set to C(default).\n attribute :source\n validates :source, type: String\n\n # @return [Object, nil] Specifies the port for the trap destination.,This parameter is only relevant when C(version) is C(v1), or C(v2c). If C(version) is something else, this parameter is ignored.\n attribute :port\n\n # @return [Float, nil] Specifies the object identifier (OID) for the record.,When C(version) is C(v3), this parameter is required.,When C(version) is either C(v1) or C(v2c), if this value is specified, then C(source) must not be set to C(all).\n attribute :oid\n validates :oid, type: Float\n\n # @return [:ro, :rw, :\"read-only\", :\"read-write\", nil] Specifies the user's access level to the MIB.,When creating a new community, if this parameter is not specified, the default is C(ro).,When C(ro), specifies that the user can view the MIB, but cannot modify the MIB.,When C(rw), specifies that the user can view and modify the MIB.\n attribute :access\n validates :access, expression_inclusion: {:in=>[:ro, :rw, :\"read-only\", :\"read-write\"], :message=>\"%{value} needs to be :ro, :rw, :\\\"read-only\\\", :\\\"read-write\\\"\"}, allow_nil: true\n\n # @return [4, 6, nil] Specifies whether the record applies to IPv4 or IPv6 addresses.,When creating a new community, if this value is not specified, the default of C(4) will be used.,This parameter is only relevant when C(version) is C(v1), or C(v2c). If C(version) is something else, this parameter is ignored.\n attribute :ip_version\n validates :ip_version, expression_inclusion: {:in=>[4, 6], :message=>\"%{value} needs to be 4, 6\"}, allow_nil: true\n\n # @return [String, nil] Specifies the name of the user for whom you want to grant access to the SNMP v3 MIB.,This parameter is only relevant when C(version) is C(v3). If C(version) is something else, this parameter is ignored.,When creating a new SNMP C(v3) community, this parameter is required.,This parameter cannot be changed once it has been set.\n attribute :snmp_username\n validates :snmp_username, type: String\n\n # @return [:md5, :sha, :none, nil] Specifies the authentication method for the user.,When C(md5), specifies that the system uses the MD5 algorithm to authenticate the user.,When C(sha), specifies that the secure hash algorithm (SHA) to authenticate the user.,When C(none), specifies that user does not require authentication.,When creating a new SNMP C(v3) community, if this parameter is not specified, the default of C(sha) will be used.\n attribute :snmp_auth_protocol\n validates :snmp_auth_protocol, expression_inclusion: {:in=>[:md5, :sha, :none], :message=>\"%{value} needs to be :md5, :sha, :none\"}, allow_nil: true\n\n # @return [String, nil] Specifies the password for the user.,When creating a new SNMP C(v3) community, this parameter is required.,This value must be at least 8 characters long.\n attribute :snmp_auth_password\n validates :snmp_auth_password, type: String\n\n # @return [:aes, :des, :none, nil] Specifies the encryption protocol.,When C(aes), specifies that the system encrypts the user information using AES (Advanced Encryption Standard).,When C(des), specifies that the system encrypts the user information using DES (Data Encryption Standard).,When C(none), specifies that the system does not encrypt the user information.,When creating a new SNMP C(v3) community, if this parameter is not specified, the default of C(aes) will be used.\n attribute :snmp_privacy_protocol\n validates :snmp_privacy_protocol, expression_inclusion: {:in=>[:aes, :des, :none], :message=>\"%{value} needs to be :aes, :des, :none\"}, allow_nil: true\n\n # @return [String, nil] Specifies the password for the user.,When creating a new SNMP C(v3) community, this parameter is required.,This value must be at least 8 characters long.\n attribute :snmp_privacy_password\n validates :snmp_privacy_password, type: String\n\n # @return [:always, :on_create, nil] C(always) will allow to update passwords if the user chooses to do so. C(on_create) will only set the password for newly created resources.\n attribute :update_password\n validates :update_password, expression_inclusion: {:in=>[:always, :on_create], :message=>\"%{value} needs to be :always, :on_create\"}, allow_nil: true\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6692167520523071, "alphanum_fraction": 0.6692167520523071, "avg_line_length": 39.367645263671875, "blob_id": "e732836a41355087a31c1ecb133d0e81d68e9067", "content_id": "9eceb3304c017015bad6596e09bbcf29e4e86d99", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2745, "license_type": "permissive", "max_line_length": 159, "num_lines": 68, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_aaa_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage AAA users on Cisco ACI fabrics.\n class Aci_aaa_user < Base\n # @return [String, nil] The password of the locally-authenticated user.\n attribute :aaa_password\n validates :aaa_password, type: String\n\n # @return [Integer, nil] The lifetime of the locally-authenticated user password.\n attribute :aaa_password_lifetime\n validates :aaa_password_lifetime, type: Integer\n\n # @return [Symbol, nil] Whether this account needs password update.\n attribute :aaa_password_update_required\n validates :aaa_password_update_required, type: Symbol\n\n # @return [String, nil] The name of the locally-authenticated user user to add.\n attribute :aaa_user\n validates :aaa_user, type: String\n\n # @return [Symbol, nil] Whether to clear the password history of a locally-authenticated user.\n attribute :clear_password_history\n validates :clear_password_history, type: Symbol\n\n # @return [Object, nil] Description for the AAA user.\n attribute :description\n\n # @return [String, nil] The email address of the locally-authenticated user.\n attribute :email\n validates :email, type: String\n\n # @return [Symbol, nil] The status of the locally-authenticated user account.\n attribute :enabled\n validates :enabled, type: Symbol\n\n # @return [String, nil] The expiration date of the locally-authenticated user account.\n attribute :expiration\n validates :expiration, type: String\n\n # @return [Symbol, nil] Whether to enable an expiration date for the locally-authenticated user account.\n attribute :expires\n validates :expires, type: Symbol\n\n # @return [String, nil] The first name of the locally-authenticated user.\n attribute :first_name\n validates :first_name, type: String\n\n # @return [String, nil] The last name of the locally-authenticated user.\n attribute :last_name\n validates :last_name, type: String\n\n # @return [String, nil] The phone number of the locally-authenticated user.\n attribute :phone\n validates :phone, type: String\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6728855967521667, "alphanum_fraction": 0.6728855967521667, "avg_line_length": 32.5, "blob_id": "51d347dae48e9c17ae32b5ba92dbed8d6d35951c", "content_id": "70b0119180d7cc744dfe42e55ddb9dda36d3e5cc", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 804, "license_type": "permissive", "max_line_length": 86, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/windows/win_scheduled_task_stat.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Will return whether the folder and task exists.\n # Returns the names of tasks in the folder specified.\n # If C(name) is set and exists, will return information on the task itself.\n # Use M(win_scheduled_task) to configure a scheduled task.\n class Win_scheduled_task_stat < Base\n # @return [String, nil] The folder path where the task lives.\n attribute :path\n validates :path, type: String\n\n # @return [String, nil] The name of the scheduled task to get information for.\n attribute :name\n validates :name, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6804238557815552, "alphanum_fraction": 0.6809815764427185, "avg_line_length": 47.4594612121582, "blob_id": "372941f293c186695af37ed84d4ecd50ce181ac9", "content_id": "14a7cf43c0389e69d104ec2aeb4e40c2c3a04fb4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1793, "license_type": "permissive", "max_line_length": 239, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/cloud/docker/docker_volume.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create/remove Docker volumes.\n # Performs largely the same function as the \"docker volume\" CLI subcommand.\n class Docker_volume < Base\n # @return [String] Name of the volume to operate on.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Specify the type of volume. Docker provides the C(local) driver, but 3rd party drivers can also be used.\n attribute :driver\n validates :driver, type: String\n\n # @return [Hash, nil] Dictionary of volume settings. Consult docker docs for valid options and values: U(https://docs.docker.com/engine/reference/commandline/volume_create/#driver-specific-options)\n attribute :driver_options\n validates :driver_options, type: Hash\n\n # @return [Object, nil] List of labels to set for the volume\n attribute :labels\n\n # @return [:yes, :no, nil] With state C(present) causes the volume to be deleted and recreated if the volume already exist and the driver, driver options or labels differ. This will cause any data in the existing volume to be lost.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:absent, :present, nil] C(absent) deletes the volume.,C(present) creates the volume, if it does not already exist.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6828815340995789, "alphanum_fraction": 0.688265860080719, "avg_line_length": 75.94285583496094, "blob_id": "fe72d8f4174c565dc0c433a284f035940e237c40", "content_id": "cc48e2b5c7b2f37b209653fbd51538a14a995db2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5386, "license_type": "permissive", "max_line_length": 825, "num_lines": 70, "path": "/lib/ansible/ruby/modules/generated/files/template.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Templates are processed by the Jinja2 templating language (U(http://jinja.pocoo.org/docs/)) - documentation on the template formatting can be found in the Template Designer Documentation (U(http://jinja.pocoo.org/docs/templates/)).\n # Six additional variables can be used in templates: C(ansible_managed) (configurable via the C(defaults) section of C(ansible.cfg)) contains a string which can be used to describe the template name, host, modification time of the template file and the owner uid. C(template_host) contains the node name of the template's machine. C(template_uid) is the numeric user id of the owner. C(template_path) is the path of the template. C(template_fullpath) is the absolute path of the template. C(template_run_date) is the date that the template was rendered.\n class Template < Base\n # @return [String] Path of a Jinja2 formatted template on the Ansible controller. This can be a relative or absolute path.\n attribute :src\n validates :src, presence: true, type: String\n\n # @return [String] Location to render the template to on the remote machine.\n attribute :dest\n validates :dest, presence: true, type: String\n\n # @return [:yes, :no, nil] Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.\n attribute :backup\n validates :backup, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:\"\\\\n\", :\"\\\\r\", :\"\\\\r\\\\n\", nil] Specify the newline sequence to use for templating files.\n attribute :newline_sequence\n validates :newline_sequence, expression_inclusion: {:in=>[:\"\\\\n\", :\"\\\\r\", :\"\\\\r\\\\n\"], :message=>\"%{value} needs to be :\\\"\\\\\\\\n\\\", :\\\"\\\\\\\\r\\\", :\\\"\\\\\\\\r\\\\\\\\n\\\"\"}, allow_nil: true\n\n # @return [String, nil] The string marking the beginning of a block.\n attribute :block_start_string\n validates :block_start_string, type: String\n\n # @return [String, nil] The string marking the end of a block.\n attribute :block_end_string\n validates :block_end_string, type: String\n\n # @return [String, nil] The string marking the beginning of a print statement.\n attribute :variable_start_string\n validates :variable_start_string, type: String\n\n # @return [String, nil] The string marking the end of a print statement.\n attribute :variable_end_string\n validates :variable_end_string, type: String\n\n # @return [:yes, :no, nil] If this is set to True the first newline after a block is removed (block, not variable tag!).\n attribute :trim_blocks\n validates :trim_blocks, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If this is set to True leading spaces and tabs are stripped from the start of a line to a block. Setting this option to True requires Jinja2 version >=2.7.\n attribute :lstrip_blocks\n validates :lstrip_blocks, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] the default is C(yes), which will replace the remote file when contents are different than the source. If C(no), the file will only be transferred if the destination does not exist.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] This flag indicates that filesystem links in the destination, if they exist, should be followed.,Previous to Ansible 2.4, this was hardcoded as C(yes).\n attribute :follow\n validates :follow, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, Array<String>, String, nil] Mode the file or directory should be. For those used to I(/usr/bin/chmod) remember that modes are actually octal numbers. You must either add a leading zero so that Ansible's YAML parser knows it is an octal number (like C(0644) or C(01777)) or quote it (like C('644') or C('1777')) so Ansible receives a string and can do its own conversion from string into number. Giving Ansible a number without following one of these rules will end up with a decimal number which will have unexpected results. As of version 1.8, the mode may be specified as a symbolic mode (for example, C(u+rwx) or C(u=rw,g=r,o=r)). As of version 2.6, the mode may also be the special string C(preserve). C(preserve) means that the file will be given the same permissions as the source file.\n attribute :mode\n validates :mode, type: TypeGeneric.new(String)\n\n # @return [String, nil] Overrides the encoding used to write the template file defined by C(dest).,It defaults to C('utf-8'), but any encoding supported by python can be used.,The source template file must always be encoded using C('utf-8'), for homogeneity.\n attribute :output_encoding\n validates :output_encoding, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6967126131057739, "alphanum_fraction": 0.6972428560256958, "avg_line_length": 43.904762268066406, "blob_id": "e9692118eb49dc650f82e35d8feeac7145da0bb3", "content_id": "cb3345b6ca5168dd48968a0d4a7d76c86746222c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1886, "license_type": "permissive", "max_line_length": 237, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_scaling_policy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Can create or delete scaling policies for autoscaling groups\n # Referenced autoscaling groups must already exist\n class Ec2_scaling_policy < Base\n # @return [:present, :absent] register or deregister the policy\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String] Unique name for the scaling policy\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] Name of the associated autoscaling group\n attribute :asg_name\n validates :asg_name, presence: true, type: String\n\n # @return [:ChangeInCapacity, :ExactCapacity, :PercentChangeInCapacity, nil] The type of change in capacity of the autoscaling group\n attribute :adjustment_type\n validates :adjustment_type, expression_inclusion: {:in=>[:ChangeInCapacity, :ExactCapacity, :PercentChangeInCapacity], :message=>\"%{value} needs to be :ChangeInCapacity, :ExactCapacity, :PercentChangeInCapacity\"}, allow_nil: true\n\n # @return [Integer, nil] The amount by which the autoscaling group is adjusted by the policy\n attribute :scaling_adjustment\n validates :scaling_adjustment, type: Integer\n\n # @return [Integer, nil] Minimum amount of adjustment when policy is triggered\n attribute :min_adjustment_step\n validates :min_adjustment_step, type: Integer\n\n # @return [Integer, nil] The minimum period of time between which autoscaling actions can take place\n attribute :cooldown\n validates :cooldown, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6863200664520264, "alphanum_fraction": 0.6938716173171997, "avg_line_length": 59.403507232666016, "blob_id": "c691e81221f79a1c059d15cfe73d31636f67bc8e", "content_id": "655f761ad09bfbec6ae9906b926f332c3e0a58cb", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3443, "license_type": "permissive", "max_line_length": 503, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/windows/win_nssm.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # nssm is a service helper which doesn't suck. See U(https://nssm.cc/) for more information.\n class Win_nssm < Base\n # @return [String] Name of the service to operate on.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, :started, :stopped, :restarted, nil] State of the service on the system.,Note that NSSM actions like \"pause\", \"continue\", \"rotate\" do not fit the declarative style of ansible, so these should be implemented via the ansible command module.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :started, :stopped, :restarted], :message=>\"%{value} needs to be :absent, :present, :started, :stopped, :restarted\"}, allow_nil: true\n\n # @return [String, nil] The application binary to run as a service,Specify this whenever the service may need to be installed (state: present, started, stopped, restarted),Note that the application name must look like the following, if the directory includes spaces:,nssm install service \"C:\\\\Program Files\\\\app.exe\\\\\" \"C:\\\\Path with spaces\\\\\",See commit 0b386fc1984ab74ee59b7bed14b7e8f57212c22b in the nssm.git project for more info: U(https://git.nssm.cc/?p=nssm.git;a=commit;h=0b386fc1984ab74ee59b7bed14b7e8f57212c22b)\\r\\n\n attribute :application\n validates :application, type: String\n\n # @return [String, nil] Path to receive output.\n attribute :stdout_file\n validates :stdout_file, type: String\n\n # @return [String, nil] Path to receive error output.\n attribute :stderr_file\n validates :stderr_file, type: String\n\n # @return [String, nil] A string representing a dictionary of parameters to be passed to the application when it starts.,Use either this or C(app_parameters_free_form), not both.\n attribute :app_parameters\n validates :app_parameters, type: String\n\n # @return [String, nil] Single string of parameters to be passed to the service.,Use either this or C(app_parameters), not both.\n attribute :app_parameters_free_form\n validates :app_parameters_free_form, type: String\n\n # @return [Array<String>, String, nil] Service dependencies that has to be started to trigger startup, separated by comma.\n attribute :dependencies\n validates :dependencies, type: TypeGeneric.new(String)\n\n # @return [String, nil] User to be used for service startup.\n attribute :user\n validates :user, type: String\n\n # @return [String, nil] Password to be used for service startup.\n attribute :password\n validates :password, type: String\n\n # @return [:auto, :delayed, :disabled, :manual, nil] If C(auto) is selected, the service will start at bootup.,C(delayed) causes a delayed but automatic start after boot (added in version 2.5).,C(manual) means that the service will start only when another service needs it.,C(disabled) means that the service will stay off, regardless if it is needed or not.\n attribute :start_mode\n validates :start_mode, expression_inclusion: {:in=>[:auto, :delayed, :disabled, :manual], :message=>\"%{value} needs to be :auto, :delayed, :disabled, :manual\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6654040217399597, "alphanum_fraction": 0.6679292917251587, "avg_line_length": 19.30769157409668, "blob_id": "ceaeb4fe7f034f193799c9ff52433c51ec869471", "content_id": "6b3659524d368e31e15e9d364fcde7e911e4381d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 792, "license_type": "permissive", "max_line_length": 83, "num_lines": 39, "path": "/lib/ansible/ruby/models/type_generic.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# See LICENSE.txt for license\nclass TypeGeneric\n attr_reader :klasses\n\n def initialize(*klasses)\n @klasses = klasses\n end\n\n def valid?(value)\n validation_object = validation_object(value)\n # Don't worry about nil\n return true unless validation_object\n\n @klasses.any? { |klass| validation_object.is_a? klass }\n end\n\n def error(attribute, value)\n object = validation_object(value)\n \"Attribute #{attribute} expected to be a #{@klasses} but was a #{object.class}\"\n end\n\n def eql?(other)\n other.is_a?(TypeGeneric) && other.klasses == @klasses\n end\n\n def hash\n @klasses.inject(0) do |hash, klass|\n hash ^ klass.hash\n end\n end\n\n private\n\n def validation_object(value)\n value.is_a?(Array) ? value[0] : value\n end\nend\n" }, { "alpha_fraction": 0.6796361804008484, "alphanum_fraction": 0.6806467771530151, "avg_line_length": 51.078948974609375, "blob_id": "f8d4b371b72abf90d2de132a3e3503d80e13e0f3", "content_id": "15a18bc6a257cf9fba8a1dad6f7d87b5c120f613", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1979, "license_type": "permissive", "max_line_length": 314, "num_lines": 38, "path": "/lib/ansible/ruby/modules/generated/utilities/logic/import_role.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Much like the `roles:` keyword, this task loads a role, but it allows you to control it when the role tasks run in between other tasks of the play.\n # Most keywords, loops and conditionals will only be applied to the imported tasks, not to this statement itself. If you want the opposite behavior, use M(include_role) instead. To better understand the difference you can read the L(Including and Importing Guide,../user_guide/playbooks_reuse_includes.html).\n class Import_role < Base\n # @return [String] The name of the role to be executed.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] File to load from a role's C(tasks/) directory.\n attribute :tasks_from\n validates :tasks_from, type: String\n\n # @return [String, nil] File to load from a role's C(vars/) directory.\n attribute :vars_from\n validates :vars_from, type: String\n\n # @return [String, nil] File to load from a role's C(defaults/) directory.\n attribute :defaults_from\n validates :defaults_from, type: String\n\n # @return [:yes, :no, nil] Overrides the role's metadata setting to allow using a role more than once with the same parameters.\n attribute :allow_duplicates\n validates :allow_duplicates, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] This option is a no op, and the functionality described in previous versions was not implemented. This option will be removed in Ansible v2.8.\n attribute :private\n validates :private, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6743429899215698, "alphanum_fraction": 0.6743429899215698, "avg_line_length": 50.26388931274414, "blob_id": "d8c933559d2dd6b74769da153393bdffbf5bd5a6", "content_id": "8834228e443f0bf493228df73e8d089052a60e2b", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3691, "license_type": "permissive", "max_line_length": 399, "num_lines": 72, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_deploy_ovf.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to deploy a VMware VM from an OVF or OVA file\n class Vmware_deploy_ovf < Base\n # @return [:yes, :no, nil] Whether or not to allow duplicate VM names. ESXi allows duplicates, vCenter may not.\n attribute :allow_duplicates\n validates :allow_duplicates, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Datacenter to deploy to.\n attribute :datacenter\n validates :datacenter, type: String\n\n # @return [Object, nil] Cluster to deploy to.\n attribute :cluster\n\n # @return [String, nil] Datastore to deploy to.\n attribute :datastore\n validates :datastore, type: String\n\n # @return [Object, nil] The key of the chosen deployment option.\n attribute :deployment_option\n\n # @return [:flat, :eagerZeroedThick, :monolithicSparse, :twoGbMaxExtentSparse, :twoGbMaxExtentFlat, :thin, :sparse, :thick, :seSparse, :monolithicFlat, nil] Disk provisioning type.\n attribute :disk_provisioning\n validates :disk_provisioning, expression_inclusion: {:in=>[:flat, :eagerZeroedThick, :monolithicSparse, :twoGbMaxExtentSparse, :twoGbMaxExtentFlat, :thin, :sparse, :thick, :seSparse, :monolithicFlat], :message=>\"%{value} needs to be :flat, :eagerZeroedThick, :monolithicSparse, :twoGbMaxExtentSparse, :twoGbMaxExtentFlat, :thin, :sparse, :thick, :seSparse, :monolithicFlat\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Cause the module to treat OVF Import Spec warnings as errors.\n attribute :fail_on_spec_warnings\n validates :fail_on_spec_warnings, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Absolute path of folder to place the virtual machine.,If not specified, defaults to the value of C(datacenter.vmFolder).\n attribute :folder\n\n # @return [Object, nil] Name of the VM to work with.,Virtual machine names in vCenter are not necessarily unique, which may be problematic.\n attribute :name\n\n # @return [Array<String>, String, nil] C(key: value) mapping of OVF network name, to the vCenter network name.\n attribute :networks\n validates :networks, type: TypeGeneric.new(String)\n\n # @return [String, nil] Path to OVF or OVA file to deploy.\n attribute :ovf\n validates :ovf, type: String\n\n # @return [Boolean, nil] Whether or not to power on the virtual machine after creation.\n attribute :power_on\n validates :power_on, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] The assignment of values to the properties found in the OVF as key value pairs.\n attribute :properties\n\n # @return [String, nil] Resource Pool to deploy to.\n attribute :resource_pool\n validates :resource_pool, type: String\n\n # @return [Boolean, nil] Wait for the host to power on.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Symbol, nil] Wait until vCenter detects an IP address for the VM.,This requires vmware-tools (vmtoolsd) to properly work after creation.\n attribute :wait_for_ip_address\n validates :wait_for_ip_address, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6769437193870544, "alphanum_fraction": 0.6796246767044067, "avg_line_length": 45.625, "blob_id": "edf644e3490d38890976139df3db273240647bbf", "content_id": "2037120166731b777e30dae8cd7e78f73beb6005", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1492, "license_type": "permissive", "max_line_length": 266, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/storage/zfs/zfs.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages ZFS file systems, volumes, clones and snapshots\n class Zfs < Base\n # @return [String] File system, snapshot or volume name e.g. C(rpool/myfs).\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present] Whether to create (C(present)), or remove (C(absent)) a file system, snapshot or volume. All parents/children will be created/destroyed as needed to reach the desired state.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}\n\n # @return [String, nil] Snapshot from which to create a clone.\n attribute :origin\n validates :origin, type: String\n\n # @return [Object, nil] (**DEPRECATED**) This will be removed in Ansible-2.9. Set these values in the,C(extra_zfs_properties) option instead.,The C(zfs) module takes key=value pairs for zfs properties to be set.,See the zfs(8) man page for more information.\n attribute :key_value\n\n # @return [Hash, nil] A dictionary of zfs properties to be set.,See the zfs(8) man page for more information.\n attribute :extra_zfs_properties\n validates :extra_zfs_properties, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6549375653266907, "alphanum_fraction": 0.6674233675003052, "avg_line_length": 47.94444274902344, "blob_id": "fc9d2e23a8b97ad5f31681b888e6d70f5e1a3deb", "content_id": "1c08cacdf067f1995c8819a6e5e5e52a2f479304", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1762, "license_type": "permissive", "max_line_length": 192, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_dldp_interface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages interface DLDP configuration on HUAWEI CloudEngine switches.\n class Ce_dldp_interface < Base\n # @return [Object] Must be fully qualified interface name, i.e. GE1/0/1, 10GE1/0/1, 40GE1/0/22, 100GE1/0/1.\n attribute :interface\n validates :interface, presence: true\n\n # @return [:enable, :disable, nil] Set interface DLDP enable state.\n attribute :enable\n validates :enable, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:enable, :disable, nil] Set DLDP compatible-mode enable state.\n attribute :mode_enable\n validates :mode_enable, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [Object, nil] Set the source MAC address for DLDP packets sent in the DLDP-compatible mode. The value of MAC address is in H-H-H format. H contains 1 to 4 hexadecimal digits.\n attribute :local_mac\n\n # @return [:enable, :disable, nil] Specify whether reseting interface DLDP state.\n attribute :reset\n validates :reset, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Manage the state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6651852130889893, "alphanum_fraction": 0.6740740537643433, "avg_line_length": 49.80644989013672, "blob_id": "fb2e4bab4e00c854c42b03aca86e85e0e4d3439c", "content_id": "db39e6520dc0c8736f61500ec6fac67f7fca5e9b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4725, "license_type": "permissive", "max_line_length": 313, "num_lines": 93, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates or terminates azure instances. When created optionally waits for it to be 'running'.\n class Azure < Base\n # @return [String] name of the virtual machine and associated cloud service.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] the azure location to use (e.g. 'East US')\n attribute :location\n validates :location, presence: true, type: String\n\n # @return [String, nil] azure subscription id. Overrides the AZURE_SUBSCRIPTION_ID environment variable.\n attribute :subscription_id\n validates :subscription_id, type: String\n\n # @return [String, nil] path to an azure management certificate associated with the subscription id. Overrides the AZURE_CERT_PATH environment variable.\n attribute :management_cert_path\n validates :management_cert_path, type: String\n\n # @return [String] the azure storage account in which to store the data disks.\n attribute :storage_account\n validates :storage_account, presence: true, type: String\n\n # @return [String] system image for creating the virtual machine (e.g., b39f27a8b8c64d52b05eac6a62ebad85__Ubuntu_DAILY_BUILD-precise-12_04_3-LTS-amd64-server-20131205-en-us-30GB)\n attribute :image\n validates :image, presence: true, type: String\n\n # @return [String, nil] azure role size for the new virtual machine (e.g., Small, ExtraLarge, A6). You have to pay attention to the fact that instances of type G and DS are not available in all regions (locations). Make sure if you selected the size and type of instance available in your chosen location.\n attribute :role_size\n validates :role_size, type: String\n\n # @return [Integer, nil] a comma-separated list of TCP ports to expose on the virtual machine (e.g., \"22,80\")\n attribute :endpoints\n validates :endpoints, type: Integer\n\n # @return [String, nil] the unix username for the new virtual machine.\n attribute :user\n validates :user, type: String\n\n # @return [String, nil] the unix password for the new virtual machine.\n attribute :password\n validates :password, type: String\n\n # @return [String, nil] path to an X509 certificate containing the public ssh key to install in the virtual machine. See http://www.windowsazure.com/en-us/manage/linux/tutorials/intro-to-linux/ for more details.,if this option is specified, password-based ssh authentication will be disabled.\n attribute :ssh_cert_path\n validates :ssh_cert_path, type: String\n\n # @return [String, nil] Name of virtual network.\n attribute :virtual_network_name\n validates :virtual_network_name, type: String\n\n # @return [String, nil] hostname to write /etc/hostname. Defaults to <name>.cloudapp.net.\n attribute :hostname\n validates :hostname, type: String\n\n # @return [:yes, :no, nil] wait for the instance to be in state 'running' before returning\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] how long before wait gives up, in seconds\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [Integer, nil] how long before wait gives up for redirects, in seconds\n attribute :wait_timeout_redirects\n validates :wait_timeout_redirects, type: Integer\n\n # @return [:absent, :present, nil] create or terminate instances\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Enable Auto Updates on Windows Machines\n attribute :auto_updates\n validates :auto_updates, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Enable winrm on Windows Machines\n attribute :enable_winrm\n validates :enable_winrm, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:windows, :linux, nil] The type of the os that is gettings provisioned\n attribute :os_type\n validates :os_type, expression_inclusion: {:in=>[:windows, :linux], :message=>\"%{value} needs to be :windows, :linux\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6870573163032532, "alphanum_fraction": 0.6870573163032532, "avg_line_length": 44.01449203491211, "blob_id": "0bfbb7d36e6627b48d836475f1621b61a951b2a1", "content_id": "2f3792b37f9eaf43f3ff64b5808b57e8dd51bb31", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3106, "license_type": "permissive", "max_line_length": 143, "num_lines": 69, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_appgateway.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and delete instance of Application Gateway.\n class Azure_rm_appgateway < Base\n # @return [String] The name of the resource group.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] The name of the application gateway.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Resource location. If not set, location from the resource group will be used as default.\n attribute :location\n\n # @return [Hash, nil] SKU of the application gateway resource.\n attribute :sku\n validates :sku, type: Hash\n\n # @return [Object, nil] SSL policy of the application gateway resource.\n attribute :ssl_policy\n\n # @return [Array<Hash>, Hash, nil] List of subnets used by the application gateway.\n attribute :gateway_ip_configurations\n validates :gateway_ip_configurations, type: TypeGeneric.new(Hash)\n\n # @return [Object, nil] Authentication certificates of the application gateway resource.\n attribute :authentication_certificates\n\n # @return [Object, nil] SSL certificates of the application gateway resource.\n attribute :ssl_certificates\n\n # @return [Array<Hash>, Hash, nil] Frontend IP addresses of the application gateway resource.\n attribute :frontend_ip_configurations\n validates :frontend_ip_configurations, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash, nil] List of frontend ports of the application gateway resource.\n attribute :frontend_ports\n validates :frontend_ports, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash, nil] List of backend address pool of the application gateway resource.\n attribute :backend_address_pools\n validates :backend_address_pools, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash, nil] Backend http settings of the application gateway resource.\n attribute :backend_http_settings_collection\n validates :backend_http_settings_collection, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash, nil] List of HTTP listeners of the application gateway resource.\n attribute :http_listeners\n validates :http_listeners, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash, nil] List of request routing rules of the application gateway resource.\n attribute :request_routing_rules\n validates :request_routing_rules, type: TypeGeneric.new(Hash)\n\n # @return [:absent, :present, nil] Assert the state of the Public IP. Use 'present' to create or update a and 'absent' to delete.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6672203540802002, "alphanum_fraction": 0.6672203540802002, "avg_line_length": 42, "blob_id": "a6c04873a7792dfa26b37dc76a08f165c7c73acf", "content_id": "4aca28f93cbb38e8942e45d134ca6956128220cb", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1806, "license_type": "permissive", "max_line_length": 202, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/database/mssql/mssql_db.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove MSSQL databases from a remote host.\n class Mssql_db < Base\n # @return [String] name of the database to add or remove\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] The username used to authenticate with\n attribute :login_user\n\n # @return [Object, nil] The password used to authenticate with\n attribute :login_password\n\n # @return [Object, nil] Host running the database\n attribute :login_host\n\n # @return [Integer, nil] Port of the MSSQL server. Requires login_host be defined as other then localhost if login_port is used\n attribute :login_port\n validates :login_port, type: Integer\n\n # @return [:present, :absent, :import, nil] The database state\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :import], :message=>\"%{value} needs to be :present, :absent, :import\"}, allow_nil: true\n\n # @return [String, nil] Location, on the remote host, of the dump file to read from or write to. Uncompressed SQL files (C(.sql)) files are supported.\n attribute :target\n validates :target, type: String\n\n # @return [:yes, :no, nil] Automatically commit the change only if the import succeed. Sometimes it is necessary to use autocommit=true, since some content can't be changed within a transaction.\n attribute :autocommit\n validates :autocommit, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.664600133895874, "alphanum_fraction": 0.664600133895874, "avg_line_length": 42.5945930480957, "blob_id": "e920d21a51cfeee81ee02afec94d69df7b100417", "content_id": "4b4f1e618799ccef5fe61f93054d4a9c795216d8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1613, "license_type": "permissive", "max_line_length": 163, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/iam_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage AWS IAM groups\n class Iam_group < Base\n # @return [String] The name of the group to create.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Array<String>, String, nil] A list of managed policy ARNs or friendly names to attach to the role. To embed an inline policy, use M(iam_policy).\n attribute :managed_policy\n validates :managed_policy, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] A list of existing users to add as members of the group.\n attribute :users\n validates :users, type: TypeGeneric.new(String)\n\n # @return [:present, :absent] Create or remove the IAM group\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [Boolean, nil] Deatach policy which not included in managed_policy list\n attribute :purge_policy\n validates :purge_policy, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Deatach users which not included in users list\n attribute :purge_users\n validates :purge_users, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6786642074584961, "alphanum_fraction": 0.6814471483230591, "avg_line_length": 60.25, "blob_id": "200756540a07496a90a3483878cc34da66359758", "content_id": "966ebb478a57da0f3efa04147e3b3af08382841e", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5390, "license_type": "permissive", "max_line_length": 380, "num_lines": 88, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vsphere_guest.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create/delete/reconfigure a guest VM through VMware vSphere. This module has a dependency on pysphere >= 1.7\n class Vsphere_guest < Base\n # @return [String] The hostname of the vcenter server the module will connect to, to create the guest.\n attribute :vcenter_hostname\n validates :vcenter_hostname, presence: true, type: String\n\n # @return [:yes, :no, nil] Validate SSL certs. Note, if running on python without SSLContext support (typically, python < 2.7.9) you will have to set this to C(no) as pysphere does not support validating certificates on older python. Prior to 2.1, this module would always validate on python >= 2.7.9 and never validate on python <= 2.7.8.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String] The virtual server name you wish to manage.\n attribute :guest\n validates :guest, presence: true, type: String\n\n # @return [String] Username to connect to vcenter as.\n attribute :username\n validates :username, presence: true, type: String\n\n # @return [String] Password of the user to connect to vcenter as.\n attribute :password\n validates :password, presence: true, type: String\n\n # @return [Object, nil] The name of the resource_pool to create the VM in.\n attribute :resource_pool\n\n # @return [Object, nil] The name of the cluster to create the VM in. By default this is derived from the host you tell the module to build the guest on.\n attribute :cluster\n\n # @return [Hash, nil] Dictionary which includes datacenter and hostname on which the VM should be created. For standalone ESXi hosts, ha-datacenter should be used as the datacenter name\n attribute :esxi\n validates :esxi, type: Hash\n\n # @return [:present, :powered_off, :absent, :powered_on, :restarted, :reconfigured, :reboot_guest, :poweroff_guest, nil] Indicate desired state of the vm. 'reconfigured' only applies changes to 'vm_cdrom', 'memory_mb', and 'num_cpus' in vm_hardware parameter. The 'memory_mb' and 'num_cpus' changes are applied to powered-on vms when hot-plugging is enabled for the guest.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :powered_off, :absent, :powered_on, :restarted, :reconfigured, :reboot_guest, :poweroff_guest], :message=>\"%{value} needs to be :present, :powered_off, :absent, :powered_on, :restarted, :reconfigured, :reboot_guest, :poweroff_guest\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Specifies if the VM should be deployed from a template (mutually exclusive with 'state' parameter). No guest customization changes to hardware such as CPU, RAM, NICs or Disks can be applied when launching from template.\n attribute :from_template\n validates :from_template, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Name of the source template to deploy from\n attribute :template_src\n\n # @return [Object, nil] A string that when specified, will create a linked clone copy of the VM. Snapshot must already be taken in vCenter.\n attribute :snapshot_to_clone\n\n # @return [:yes, :no, nil] Specifies if the VM should be powered on after the clone.\n attribute :power_on_after_clone\n validates :power_on_after_clone, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Hash, nil] A key, value list of disks and their sizes and which datastore to keep it in.\n attribute :vm_disk\n validates :vm_disk, type: Hash\n\n # @return [Hash, nil] A key, value list of VM config settings. Must include ['memory_mb', 'num_cpus', 'osid', 'scsi'].\n attribute :vm_hardware\n validates :vm_hardware, type: Hash\n\n # @return [Hash, nil] A key, value list of nics, their types and what network to put them on.,Optionaly with their MAC address.\n attribute :vm_nic\n validates :vm_nic, type: Hash\n\n # @return [Hash, nil] A key, value pair of any extra values you want set or changed in the vmx file of the VM. Useful to set advanced options on the VM.\n attribute :vm_extra_config\n validates :vm_extra_config, type: Hash\n\n # @return [Object, nil] Desired hardware version identifier (for example, \"vmx-08\" for vms that needs to be managed with vSphere Client). Note that changing hardware version of existing vm is not supported.\n attribute :vm_hw_version\n\n # @return [Symbol, nil] Gather facts from vCenter on a particular VM\n attribute :vmware_guest_facts\n validates :vmware_guest_facts, type: Symbol\n\n # @return [:yes, :no, nil] Boolean. Allows you to run commands which may alter the running state of a guest. Also used to reconfigure and destroy.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7338521480560303, "alphanum_fraction": 0.7348897457122803, "avg_line_length": 81.02127838134766, "blob_id": "3de10bd636675a2616606c8da1020402c5762511", "content_id": "cbe3f55144b8b000d70abaae51753eb69214ae39", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3855, "license_type": "permissive", "max_line_length": 720, "num_lines": 47, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_device_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Managing device groups allows you to create HA pairs and clusters of BIG-IP devices. Usage of this module should be done in conjunction with the C(bigip_configsync_actions) to sync configuration across the pair or cluster if auto-sync is disabled.\n class Bigip_device_group < Base\n # @return [String] Specifies the name of the device group.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:\"sync-failover\", :\"sync-only\", nil] Specifies that the type of group.,A C(sync-failover) device group contains devices that synchronize their configuration data and fail over to one another when a device becomes unavailable.,A C(sync-only) device group has no such failover. When creating a new device group, this option will default to C(sync-only).,This setting cannot be changed once it has been set.\n attribute :type\n validates :type, expression_inclusion: {:in=>[:\"sync-failover\", :\"sync-only\"], :message=>\"%{value} needs to be :\\\"sync-failover\\\", :\\\"sync-only\\\"\"}, allow_nil: true\n\n # @return [Object, nil] Description of the device group.\n attribute :description\n\n # @return [Symbol, nil] Indicates whether configuration synchronization occurs manually or automatically.,When creating a new device group, this option will default to C(no).\n attribute :auto_sync\n validates :auto_sync, type: Symbol\n\n # @return [Symbol, nil] When performing an auto-sync, specifies whether the configuration will be saved or not.,When C(no), only the running configuration will be changed on the device(s) being synced to.,When creating a new device group, this option will default to C(no).\n attribute :save_on_auto_sync\n validates :save_on_auto_sync, type: Symbol\n\n # @return [Symbol, nil] Specifies whether the system synchronizes the entire configuration during synchronization operations.,When C(no), the system performs incremental synchronization operations, based on the cache size specified in C(max_incremental_sync_size).,Incremental configuration synchronization is a mechanism for synchronizing a device-group's configuration among its members, without requiring a full configuration load for each configuration change.,In order for this to work, all devices in the device-group must initially agree on the configuration. Typically this requires at least one full configuration load to each device.,When creating a new device group, this option will default to C(no).\n attribute :full_sync\n validates :full_sync, type: Symbol\n\n # @return [Object, nil] Specifies the size of the changes cache for incremental sync.,For example, using the default, if you make more than 1024 KB worth of incremental changes, the system performs a full synchronization operation.,Using incremental synchronization operations can reduce the per-device sync/load time for configuration changes.,This setting is relevant only when C(full_sync) is C(no).\n attribute :max_incremental_sync_size\n\n # @return [:present, :absent, nil] When C(state) is C(present), ensures the device group exists.,When C(state) is C(absent), ensures that the device group is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Symbol, nil] Indicates whether failover occurs over the network or is hard-wired.,This parameter is only valid for C(type)'s that are C(sync-failover).\n attribute :network_failover\n validates :network_failover, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7266187071800232, "alphanum_fraction": 0.7458033561706543, "avg_line_length": 20.947368621826172, "blob_id": "cc511cb4952225f9998c017394e742f48b35abf1", "content_id": "98068a064e2c467823ed6bc06e35992c82d2e541", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 417, "license_type": "permissive", "max_line_length": 66, "num_lines": 19, "path": "/lib/ansible/ruby/modules/custom/files/copy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# VALIDATED_CHECKSUM: L5A1FluCE5GCjHh2FWbb3wQ/ib7zSYoD5K4gPHTDXUE=\n\n# see LICENSE.txt in project root\n\nrequire 'ansible/ruby/modules/generated/files/copy'\nrequire 'ansible/ruby/modules/helpers/file_attributes'\n\nmodule Ansible\n module Ruby\n module Modules\n class Copy\n remove_existing_validations :mode\n include Helpers::FileAttributes\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7446808218955994, "alphanum_fraction": 0.7446808218955994, "avg_line_length": 14.666666984558105, "blob_id": "f7c1d76bc1bbbedc57d09cbc0d81923df90eceaa", "content_id": "81b0fcbd851b9d71ec80f0059dbe70c85aa52bc8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 94, "license_type": "permissive", "max_line_length": 44, "num_lines": 6, "path": "/util/get_ansible_lint.py", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport ansiblelint\nimport os\n\nprint(os.path.dirname(ansiblelint.__file__))\n" }, { "alpha_fraction": 0.7223427295684814, "alphanum_fraction": 0.7223427295684814, "avg_line_length": 40.90909194946289, "blob_id": "2e77101a61f48722d54b2f6ef0ce06c3f0716bf1", "content_id": "ac75ce36809ea51aa39aeb65205de68164202446", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 922, "license_type": "permissive", "max_line_length": 232, "num_lines": 22, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/sts_session_token.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Obtain a session token from the AWS Security Token Service\n class Sts_session_token < Base\n # @return [Object, nil] The duration, in seconds, of the session token. See http://docs.aws.amazon.com/STS/latest/APIReference/API_GetSessionToken.html#API_GetSessionToken_RequestParameters for acceptable and default values.\n attribute :duration_seconds\n\n # @return [Object, nil] The identification number of the MFA device that is associated with the user who is making the GetSessionToken call.\n attribute :mfa_serial_number\n\n # @return [Object, nil] The value provided by the MFA device, if the trust policy of the user requires MFA.\n attribute :mfa_token\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7257709503173828, "alphanum_fraction": 0.7257709503173828, "avg_line_length": 63.85714340209961, "blob_id": "807be0ea87af3cf0b4e2089aa43d3cb74662c7da", "content_id": "29e3bfc8d15f00f83ffd71352bbd92afa1cdcc8b", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1816, "license_type": "permissive", "max_line_length": 392, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_host_lockdown.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to manage administrator permission for the local administrative account for the host when ESXi hostname is given.\n # All parameters and VMware objects values are case sensitive.\n # This module is destructive as administrator permission are managed using APIs used, please read options carefully and proceed.\n # Please specify C(hostname) as vCenter IP or hostname only, as lockdown operations are not possible from standalone ESXi server.\n class Vmware_host_lockdown < Base\n # @return [String, nil] Name of cluster.,All host systems from given cluster used to manage lockdown.,Required parameter, if C(esxi_hostname) is not set.\n attribute :cluster_name\n validates :cluster_name, type: String\n\n # @return [Array<String>, String, nil] List of ESXi hostname to manage lockdown.,Required parameter, if C(cluster_name) is not set.,See examples for specifications.\n attribute :esxi_hostname\n validates :esxi_hostname, type: TypeGeneric.new(String)\n\n # @return [:present, :absent, nil] State of hosts system,If set to C(present), all host systems will be set in lockdown mode.,If host system is already in lockdown mode and set to C(present), no action will be taken.,If set to C(absent), all host systems will be removed from lockdown mode.,If host system is already out of lockdown mode and set to C(absent), no action will be taken.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6977900266647339, "alphanum_fraction": 0.6977900266647339, "avg_line_length": 50.71428680419922, "blob_id": "0fe8aa0594746d3cd9c3b2cdd204475906f0e518", "content_id": "9e740c1af871a198965d7de46eaca53a9a758067", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1810, "license_type": "permissive", "max_line_length": 436, "num_lines": 35, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_gtm_datacenter.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage BIG-IP data center configuration. A data center defines the location where the physical network components reside, such as the server and link objects that share the same subnet on the network. This module is able to manipulate the data center definitions in a BIG-IP.\n class Bigip_gtm_datacenter < Base\n # @return [Object, nil] The name of the contact for the data center.\n attribute :contact\n\n # @return [Object, nil] The description of the data center.\n attribute :description\n\n # @return [String, nil] The location of the data center.\n attribute :location\n validates :location, type: String\n\n # @return [String] The name of the data center.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, :enabled, :disabled, nil] The virtual address state. If C(absent), an attempt to delete the virtual address will be made. This will only succeed if this virtual address is not in use by a virtual server. C(present) creates the virtual address and enables it. If C(enabled), enable the virtual address if it exists. If C(disabled), create the virtual address if needed, and set state to C(disabled).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :enabled, :disabled], :message=>\"%{value} needs to be :present, :absent, :enabled, :disabled\"}, allow_nil: true\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6531664133071899, "alphanum_fraction": 0.6561119556427002, "avg_line_length": 36.72222137451172, "blob_id": "e23f562b87b61bf20c53abf228c9f339844b3774", "content_id": "7ca2d935f4643ab8efed0c50e799de5b9c31de54", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1358, "license_type": "permissive", "max_line_length": 143, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_vswitch.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to add, remove and update a VMware Standard Switch to an ESXi host.\n class Vmware_vswitch < Base\n # @return [String] vSwitch name to add.,Alias C(switch) is added in version 2.4.\n attribute :switch\n validates :switch, presence: true, type: String\n\n # @return [Object, nil] A list of vmnic names or vmnic name to attach to vSwitch.,Alias C(nics) is added in version 2.4.\n attribute :nics\n\n # @return [Integer, nil] Number of port to configure on vSwitch.\n attribute :number_of_ports\n validates :number_of_ports, type: Integer\n\n # @return [Integer, nil] MTU to configure on vSwitch.\n attribute :mtu\n validates :mtu, type: Integer\n\n # @return [:absent, :present, nil] Add or remove the switch.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] Manage the vSwitch using this ESXi host system.\n attribute :esxi_hostname\n validates :esxi_hostname, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6916230320930481, "alphanum_fraction": 0.6916230320930481, "avg_line_length": 44.47618865966797, "blob_id": "2d515d52b0117e9ffa00cd8cbc6ee60e2c1ad9a2", "content_id": "e6ae7141d81404f624d87fa62c761d0fc81f96a5", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1910, "license_type": "permissive", "max_line_length": 178, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/sf_volume_access_group_manager.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, destroy, or update volume access groups on SolidFire\n class Sf_volume_access_group_manager < Base\n # @return [:present, :absent] Whether the specified volume access group should exist or not.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String] Name of the volume access group. It is not required to be unique, but recommended.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] List of initiators to include in the volume access group. If unspecified, the access group will start out without configured initiators.\n attribute :initiators\n\n # @return [Array<Integer>, Integer, nil] List of volumes to initially include in the volume access group. If unspecified, the access group will start without any volumes.\n attribute :volumes\n validates :volumes, type: TypeGeneric.new(Integer)\n\n # @return [Object, nil] The ID of the SolidFire Virtual Network ID to associate the volume access group with.\n attribute :virtual_network_id\n\n # @return [Object, nil] The ID of the VLAN Virtual Network Tag to associate the volume access group with.\n attribute :virtual_network_tags\n\n # @return [Hash, nil] List of Name/Value pairs in JSON object format.\n attribute :attributes\n validates :attributes, type: Hash\n\n # @return [Integer, nil] The ID of the volume access group to modify or delete.\n attribute :volume_access_group_id\n validates :volume_access_group_id, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7325513362884521, "alphanum_fraction": 0.7333333492279053, "avg_line_length": 80.19047546386719, "blob_id": "d0be741cce79780a1e2b4d273041504a3de3e087", "content_id": "1da9041b6110422bddac5efe6b8324f0cdc5cda9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5115, "license_type": "permissive", "max_line_length": 601, "num_lines": 63, "path": "/lib/ansible/ruby/modules/generated/network/netact/netact_cm_command.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # netact_cm_command can be used to run various configuration management operations. This module requires that the target hosts have Nokia NetAct network management system installed. Module will access the Configurator command line interface in NetAct to upload network configuration to NetAct, run configuration export, plan import and configuration provision operations To set the scope of the operation, define Distinguished Name (DN) or Working Set (WS) or Maintenance Region (MR) as input\n class Netact_cm_command < Base\n # @return [:upload, :provision, :import, :export, :Provision_Mass_Modification] Supported operations allow user to upload actual configuration from the network, to import and provision prepared plans, or export reference or actual configuration for planning purposes. Provision_Mass_Modification enables provisioning the same parameters to multiple network elements. This operation supports modifications only to one object class at a time. With this option NetAct Configurator creates and provisions a plan to the network with the given scope and options.\n attribute :operation\n validates :operation, presence: true, expression_inclusion: {:in=>[:upload, :provision, :import, :export, :Provision_Mass_Modification], :message=>\"%{value} needs to be :upload, :provision, :import, :export, :Provision_Mass_Modification\"}\n\n # @return [Object, nil] user specified operation name\n attribute :opsName\n\n # @return [Object, nil] Sets the exact scope of the operation in form of a list of managed object Distinguished Names (DN) in the network. A single DN or a list of DNs can be given (comma separated list without spaces). Alternatively, if DN or a list of DNs is not given, working set (WS) or Maintenance Region (MR) must be provided as parameter to set the scope of operation.\n attribute :DN\n\n # @return [Object, nil] Sets the scope of the operation to use one or more pre-defined working sets (WS) in NetAct. A working set contains network elements selected by user according to defined criteria. A single WS name, or multiple WSs can be provided (comma-separated list without spaces). Alternatively, if a WS name or a list of WSs is not given, Distinguished Name (DN) or Maintenance Region(MR) must be provided as parameter to set the scope of operation.\n attribute :WS\n\n # @return [Object, nil] Sets the scope of the operation to network elements assigned to a Maintenance Region (MR) Value can be set as MR IDs including the Maintenance Region Collection (MRC) information (for example MRC-FIN1/MR-Hel). Multiple MRs can be given (comma-separated list without spaces) The value of this parameter is searched through MR IDs under given MRC. If there is no match, then it is searched from all MR names. Alternatively, if MR ID or a list or MR IDs is not given, Distinguished Name (DN) or Working Set (WS) must be provided as parameter to set the scope of operation.\n attribute :MR\n\n # @return [String, nil] Specifies a plan name.\n attribute :planName\n validates :planName, type: String\n\n # @return [:plan, :actual, :reference, :template, :siteTemplate, nil] Specifies the type of the export operation.\n attribute :typeOption\n validates :typeOption, expression_inclusion: {:in=>[:plan, :actual, :reference, :template, :siteTemplate], :message=>\"%{value} needs to be :plan, :actual, :reference, :template, :siteTemplate\"}, allow_nil: true\n\n # @return [:RAML2, :CSV, :XLSX, nil] Indicates file format.\n attribute :fileFormat\n validates :fileFormat, expression_inclusion: {:in=>[:RAML2, :CSV, :XLSX], :message=>\"%{value} needs to be :RAML2, :CSV, :XLSX\"}, allow_nil: true\n\n # @return [String, nil] Specifies a file name. Valid for Import and Export operations.\n attribute :fileName\n validates :fileName, type: String\n\n # @return [Object, nil] Specifies full path to plan file location for the import operation. This parameter (inputFile) or the fileName parameter must be filled. If both are present then the inputFile is used.\n attribute :inputFile\n\n # @return [Symbol, nil] Specifies if backup plan generation is enabled.\n attribute :createBackupPlan\n validates :createBackupPlan, type: Symbol\n\n # @return [String, nil] Specifies a backup plan name\n attribute :backupPlanName\n validates :backupPlanName, type: String\n\n # @return [Object, nil] NetAct Configurator will print more info\n attribute :verbose\n\n # @return [String, nil] Extra options to be set for operations. Check Configuration Management > Configuration Management Operating Procedures > Command Line Operations in Nokia NetAct user documentation for further information for extra options.\n attribute :extra_opts\n validates :extra_opts, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.693518877029419, "alphanum_fraction": 0.693518877029419, "avg_line_length": 55.89583206176758, "blob_id": "d1ebcf0bb412eca79c3d71a420b8afbaddf3ff4d", "content_id": "2c1dacfbc8235d9339291b1623e503f26cd89876", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2731, "license_type": "permissive", "max_line_length": 272, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/identity/cyberark/cyberark_authentication.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Authenticates to CyberArk Vault using Privileged Account Security Web Services SDK and creates a session fact that can be used by other modules. It returns an Ansible fact called I(cyberark_session). Every module can use this fact as C(cyberark_session) parameter.\n class Cyberark_authentication < Base\n # @return [:present, :absent, nil] Specifies if an authentication logon/logoff and a cyberark_session should be added/removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] The name of the user who will logon to the Vault.\n attribute :username\n validates :username, type: String\n\n # @return [String, nil] The password of the user.\n attribute :password\n validates :password, type: String\n\n # @return [Object, nil] The new password of the user. This parameter is optional, and enables you to change a password.\n attribute :new_password\n\n # @return [String, nil] A string containing the base URL of the server hosting CyberArk's Privileged Account Security Web Services SDK.\n attribute :api_base_url\n validates :api_base_url, type: String\n\n # @return [:yes, :no, nil] If C(false), SSL certificates will not be validated. This should only set to C(false) used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Whether or not Shared Logon Authentication will be used.\n attribute :use_shared_logon_authentication\n validates :use_shared_logon_authentication, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Whether or not users will be authenticated via a RADIUS server. Valid values are true/false.\n attribute :use_radius_authentication\n validates :use_radius_authentication, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Dictionary set by a CyberArk authentication containing the different values to perform actions on a logged-on CyberArk session.\n attribute :cyberark_session\n validates :cyberark_session, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7202918529510498, "alphanum_fraction": 0.7265462279319763, "avg_line_length": 60.23404312133789, "blob_id": "f4acad4f1d478d31e36194cc71681caa05c98e5a", "content_id": "3b3483d67472bc99cc38e199cb82a852348c542b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2878, "license_type": "permissive", "max_line_length": 406, "num_lines": 47, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_compute_instance_group_manager.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates a managed instance group using the information that you specify in the request. After the group is created, it schedules an action to create instances in the group using the specified instance template. This operation is marked as DONE when the group is created even if the instances in the group have not yet been created. You must separately verify the status of the individual instances.\n # A managed instance group can have up to 1000 VM instances per group.\n class Gcp_compute_instance_group_manager < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The base instance name to use for instances in this group. The value must be 1-58 characters long. Instances are named by appending a hyphen and a random four-character string to the base instance name.,The base instance name must comply with RFC1035.\n attribute :base_instance_name\n validates :base_instance_name, presence: true, type: String\n\n # @return [Object, nil] An optional description of this resource. Provide this property when you create the resource.\n attribute :description\n\n # @return [String] The instance template that is specified for this managed instance group. The group uses this template to create all new instances in the managed instance group.\n attribute :instance_template\n validates :instance_template, presence: true, type: String\n\n # @return [String] The name of the managed instance group. The name must be 1-63 characters long, and comply with RFC1035.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Named ports configured for the Instance Groups complementary to this Instance Group Manager.\n attribute :named_ports\n\n # @return [Object, nil] TargetPool resources to which instances in the instanceGroup field are added. The target pools automatically apply to all of the instances in the managed instance group.\n attribute :target_pools\n\n # @return [Integer, nil] The target number of running instances for this managed instance group. Deleting or abandoning instances reduces this number. Resizing the group changes this number.\n attribute :target_size\n validates :target_size, type: Integer\n\n # @return [String] The zone the managed instance group resides.\n attribute :zone\n validates :zone, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6544980406761169, "alphanum_fraction": 0.6544980406761169, "avg_line_length": 33.088890075683594, "blob_id": "68790d2a654e3001ec8bb51c680633c6fd34280e", "content_id": "55544290cd89734c54f1db3791fd22cc4c0d7a2e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1534, "license_type": "permissive", "max_line_length": 143, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_volume.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or Remove cinder block storage volumes\n class Os_volume < Base\n # @return [Object, nil] Size of volume in GB. This parameter is required when the I(state) parameter is 'present'.\n attribute :size\n\n # @return [Object] Name of volume\n attribute :display_name\n validates :display_name, presence: true\n\n # @return [Object, nil] String describing the volume\n attribute :display_description\n\n # @return [Object, nil] Volume type for volume\n attribute :volume_type\n\n # @return [Object, nil] Image name or id for boot from volume\n attribute :image\n\n # @return [Object, nil] Volume snapshot id to create from\n attribute :snapshot_id\n\n # @return [Object, nil] Volume name or id to create from\n attribute :volume\n\n # @return [:present, :absent, nil] Should the resource be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n\n # @return [Object, nil] Scheduler hints passed to volume API in form of dict\n attribute :scheduler_hints\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.671875, "alphanum_fraction": 0.671875, "avg_line_length": 37, "blob_id": "7094291dcd02a7173b9301d1c0271368fa120483", "content_id": "7a08fee9ea4a84bdad9075fa59b7675f64a52b32", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1216, "license_type": "permissive", "max_line_length": 143, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_log_publisher.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages log publishers on a BIG-IP.\n class Bigip_log_publisher < Base\n # @return [String] Specifies the name of the log publisher.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Specifies a description for the log publisher.\n attribute :description\n\n # @return [Array<String>, String, nil] Specifies log destinations for this log publisher to use.\n attribute :destinations\n validates :destinations, type: TypeGeneric.new(String)\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [:present, :absent, nil] When C(present), ensures that the resource exists.,When C(absent), ensures the resource is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.672583818435669, "alphanum_fraction": 0.6748380064964294, "avg_line_length": 61.26315689086914, "blob_id": "4bc8f873a7e60d2804c3c517f7398babe69279c3", "content_id": "5a55b5e7233ab822d4b945be833d0006745fbe5f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3549, "license_type": "permissive", "max_line_length": 603, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/database/mysql/mysql_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Adds or removes a user from a MySQL database.\n class Mysql_user < Base\n # @return [String] name of the user (role) to add or remove\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Integer, String, nil] set the user's password.\n attribute :password\n validates :password, type: MultipleTypes.new(Integer, String)\n\n # @return [:yes, :no, nil] Indicate that the 'password' field is a `mysql_native_password` hash\n attribute :encrypted\n validates :encrypted, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] the 'host' part of the MySQL username\n attribute :host\n validates :host, type: String\n\n # @return [:yes, :no, nil] override the host option, making ansible apply changes to all hostnames for a given user. This option cannot be used when creating users\n attribute :host_all\n validates :host_all, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] MySQL privileges string in the format: C(db.table:priv1,priv2).,Multiple privileges can be specified by separating each one using a forward slash: C(db.table:priv/db.table:priv).,The format is based on MySQL C(GRANT) statement.,Database and table names can be quoted, MySQL-style.,If column privileges are used, the C(priv1,priv2) part must be exactly as returned by a C(SHOW GRANT) statement. If not followed, the module will always report changes. It includes grouping columns by permission (C(SELECT(col1,col2)) instead of C(SELECT(col1),SELECT(col2))).\n attribute :priv\n validates :priv, type: TypeGeneric.new(String)\n\n # @return [:yes, :no, nil] Append the privileges defined by priv to the existing ones for this user instead of overwriting existing ones.\n attribute :append_privs\n validates :append_privs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Whether binary logging should be enabled or disabled for the connection.\n attribute :sql_log_bin\n validates :sql_log_bin, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Whether the user should exist. When C(absent), removes the user.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Check if mysql allows login as root/nopassword before trying supplied credentials.\n attribute :check_implicit_admin\n validates :check_implicit_admin, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:always, :on_create, nil] C(always) will update passwords if they differ. C(on_create) will only set the password for newly created users.\n attribute :update_password\n validates :update_password, expression_inclusion: {:in=>[:always, :on_create], :message=>\"%{value} needs to be :always, :on_create\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.695770800113678, "alphanum_fraction": 0.698499321937561, "avg_line_length": 37.578948974609375, "blob_id": "f6717353b0c3da39ddd295b0cca0b4d6547bcb0e", "content_id": "1db1011baa5c609c6b059bdded3ecc96f2f6d8dd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 733, "license_type": "permissive", "max_line_length": 285, "num_lines": 19, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_vpc_nacl_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gather facts about Network ACLs in an AWS VPC\n class Ec2_vpc_nacl_facts < Base\n # @return [Object, nil] A list of Network ACL IDs to retrieve facts about.\n attribute :nacl_ids\n\n # @return [Object, nil] A dict of filters to apply. Each dict item consists of a filter key and a filter value. See U(http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeNetworkAcls.html) for possible filters. Filter names and values are case sensitive.\n attribute :filters\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7049689292907715, "alphanum_fraction": 0.7049689292907715, "avg_line_length": 20.46666717529297, "blob_id": "fee0fcc8a10714875958d70052c5da6b4a436f81", "content_id": "2f0241f6c8335fb0b5f729d07f40ca4d286b8113", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 322, "license_type": "permissive", "max_line_length": 65, "num_lines": 15, "path": "/lib/ansible/ruby/modules/generated/cloud/vultr/vultr_account_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gather facts about account balance, charges and payments.\n class Vultr_account_facts < Base\n\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7742347121238708, "alphanum_fraction": 0.7767857313156128, "avg_line_length": 51.266666412353516, "blob_id": "b71b52da4ab85b2741ea087fae3e5116f2b9ecf0", "content_id": "a45d732c1418f0f5a452d6851ac3782870e973b1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 784, "license_type": "permissive", "max_line_length": 535, "num_lines": 15, "path": "/lib/ansible/ruby/modules/generated/network/cnos/cnos_reload.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows you to restart the switch using the current startup configuration. The module is usually invoked after the running configuration has been saved over the startup configuration. This module uses SSH to manage network device configuration. The results of the operation can be viewed in results directory. For more information about this module and customizing it usage for your use cases, please visit U(http://systemx.lenovofiles.com/help/index.jsp?topic=%2Fcom.lenovo.switchmgt.ansible.doc%2Fcnos_reload.html)\n class Cnos_reload < Base\n\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6967326402664185, "alphanum_fraction": 0.6976529955863953, "avg_line_length": 50.738094329833984, "blob_id": "47792f43a7b346e33dfeec043bd801c5e584cf3a", "content_id": "fd245fbd2b1b0083ec3b054e2030a911870dd316", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2173, "license_type": "permissive", "max_line_length": 317, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/cloud/docker/docker_login.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Provides functionality similar to the \"docker login\" command.\n # Authenticate with a docker registry and add the credentials to your local Docker config file. Adding the credentials to the config files allows future connections to the registry using tools such as Ansible's Docker modules, the Docker CLI and docker-py without needing to provide credentials.\n # Running in check mode will perform the authentication without updating the config file.\n class Docker_login < Base\n # @return [String, nil] The registry URL.\n attribute :registry_url\n validates :registry_url, type: String\n\n # @return [String] The username for the registry account\n attribute :username\n validates :username, presence: true, type: String\n\n # @return [String] The plaintext password for the registry account\n attribute :password\n validates :password, presence: true, type: String\n\n # @return [Object, nil] The email address for the registry account.\n attribute :email\n\n # @return [:yes, :no, nil] Refresh existing authentication found in the configuration file.\n attribute :reauthorize\n validates :reauthorize, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Custom path to the Docker CLI configuration file.\n attribute :config_path\n validates :config_path, type: String\n\n # @return [:present, :absent, nil] This controls the current state of the user. C(present) will login in a user, C(absent) will log them out.,To logout you only need the registry server, which defaults to DockerHub.,Before 2.1 you could ONLY log in.,docker does not support 'logout' with a custom config file.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7129337787628174, "alphanum_fraction": 0.7160883545875549, "avg_line_length": 34.22222137451172, "blob_id": "741ed54b24d9fa261c45322f58a5e1966a6d73cb", "content_id": "23086fac37e8613a6fb174550d01c488516f9655", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 634, "license_type": "permissive", "max_line_length": 130, "num_lines": 18, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_host_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to gathers facts like CPU, memory, datastore, network and system etc. about ESXi host system.\n # Please specify hostname or IP address of ESXi host system as C(hostname).\n # If hostname or IP address of vCenter is provided as C(hostname), then information about first ESXi hostsystem is returned.\n # VSAN facts added in 2.7 version.\n class Vmware_host_facts < Base\n\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.49321267008781433, "alphanum_fraction": 0.49502262473106384, "avg_line_length": 29.69444465637207, "blob_id": "d4f13415bf2e4e067ca294f872e54fe9154d7ad5", "content_id": "ff10c95b9c361a2c3e57232450e8c48a44b37d62", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1105, "license_type": "permissive", "max_line_length": 129, "num_lines": 36, "path": "/lib/ansible/ruby/modules/free_form.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# See LICENSE.txt for license\nmodule Ansible\n module Ruby\n module Modules\n module FreeForm\n class << self\n def included(base)\n klass_name = base.name.demodulize.underscore\n base.validates :free_form,\n presence: { message: \"Argument directly after #{klass_name} e.g. #{klass_name}(arg) cannot be blank\" }\n base.validates :free_form,\n type: {\n type: String,\n message: \"#{klass_name}(%{value}), %{value} is expected to be a String but was a %{type}\"\n }\n end\n end\n\n def to_h\n result = super\n # base module will always have 1 key that is the module\n module_key = result.keys[0]\n args = result[module_key]\n free_form_arg = args.delete :free_form\n result = {\n module_key => free_form_arg\n }\n result[:args] = args if args.any?\n result\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6822130680084229, "alphanum_fraction": 0.6835848093032837, "avg_line_length": 47.599998474121094, "blob_id": "245d3bdcfd44c933307dc6fcd278e46078d373df", "content_id": "9f043532da796ce4e6546ca9e77fff5df8565d88", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2187, "license_type": "permissive", "max_line_length": 233, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/packaging/os/swupd.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages updates and bundles with the swupd bundle manager, which is used by the Clear Linux Project for Intel Architecture.\n class Swupd < Base\n # @return [Object, nil] URL pointing to the contents of available bundles. If not specified, the contents are retrieved from clearlinux.org.\n attribute :contenturl\n\n # @return [Object, nil] The format suffix for version file downloads. For example [1,2,3,staging,etc]. If not specified, the default format is used.\n attribute :format\n\n # @return [Integer, nil] The manifest contains information about the bundles at certaion version of the OS. Specify a Manifest version to verify against that version or leave unspecified to verify against the current version.\n attribute :manifest\n validates :manifest, type: Integer\n\n # @return [String, nil] Name of the (I)bundle to install or remove.\n attribute :name\n validates :name, type: String\n\n # @return [:present, :absent, nil] Indicates the desired (I)bundle state. C(present) ensures the bundle is installed while C(absent) ensures the (I)bundle is not installed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Boolean, nil] Updates the OS to the latest version.\n attribute :update\n validates :update, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] Overrides both I(contenturl) and I(versionurl).\n attribute :url\n\n # @return [Boolean, nil] Verify content for OS version.\n attribute :verify\n validates :verify, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] URL for version string download.\n attribute :versionurl\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.66697758436203, "alphanum_fraction": 0.66697758436203, "avg_line_length": 35.965518951416016, "blob_id": "960b1632141b44ea95703b4a9a377cf3844daa54", "content_id": "3dad5a1f5ae76cf08f08be5399ffcd7d183fb23d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1072, "license_type": "permissive", "max_line_length": 143, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/storage/purestorage/purefa_hg.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, delete or modifiy hostgroups on Pure Storage FlashArrays.\n class Purefa_hg < Base\n # @return [String] The name of the hostgroup.\n attribute :hostgroup\n validates :hostgroup, presence: true, type: String\n\n # @return [:absent, :present, nil] Define whether the hostgroup should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] List of existing hosts to add to hostgroup.\n attribute :host\n validates :host, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] List of existing volumes to add to hostgroup.\n attribute :volume\n validates :volume, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6606857776641846, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 41.50847625732422, "blob_id": "d18889a31a284b789a68dd2c03478a6d52a36d9a", "content_id": "fe94a4c7e64495073fd362c9006493ef248ced3a", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2508, "license_type": "permissive", "max_line_length": 243, "num_lines": 59, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/sf_snapshot_schedule_manager.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, destroy, or update accounts on SolidFire\n class Sf_snapshot_schedule_manager < Base\n # @return [:present, :absent] Whether the specified schedule should exist or not.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [Object, nil] Pause / Resume a schedule.\n attribute :paused\n\n # @return [Boolean, nil] Should the schedule recur?\n attribute :recurring\n validates :recurring, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Integer, nil] Time interval in days.\n attribute :time_interval_days\n validates :time_interval_days, type: Integer\n\n # @return [Integer, nil] Time interval in hours.\n attribute :time_interval_hours\n validates :time_interval_hours, type: Integer\n\n # @return [Integer, nil] Time interval in minutes.\n attribute :time_interval_minutes\n validates :time_interval_minutes, type: Integer\n\n # @return [String] Name for the snapshot schedule.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Name for the created snapshots.\n attribute :snapshot_name\n validates :snapshot_name, type: String\n\n # @return [Integer, nil] Volume IDs that you want to set the snapshot schedule for.,At least 1 volume ID is required for creating a new schedule.,required when C(state=present)\n attribute :volumes\n validates :volumes, type: Integer\n\n # @return [Object, nil] Retention period for the snapshot.,Format is 'HH:mm:ss'.\n attribute :retention\n\n # @return [Integer, nil] The schedule ID for the schedule that you want to update or delete.\n attribute :schedule_id\n validates :schedule_id, type: Integer\n\n # @return [String, nil] Starting date for the schedule.,Required when C(state=present).,Please use two '-' in the above format, or you may see an error- TypeError, is not JSON serializable description.,Format: C(2016--12--01T00:00:00Z)\n attribute :starting_date\n validates :starting_date, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6698440313339233, "alphanum_fraction": 0.6698440313339233, "avg_line_length": 36.225807189941406, "blob_id": "01566ad54db1b48be4959834ad34ce50fdb4e489", "content_id": "61d4d2ad3f7c6d3d7fb7a705ccbc236213d225b7", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1154, "license_type": "permissive", "max_line_length": 143, "num_lines": 31, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_keypair.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or Remove key pair from OpenStack\n class Os_keypair < Base\n # @return [String] Name that has to be given to the key pair\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] The public key that would be uploaded to nova and injected into VMs upon creation.\n attribute :public_key\n\n # @return [String, nil] Path to local file containing ssh public key. Mutually exclusive with public_key.\n attribute :public_key_file\n validates :public_key_file, type: String\n\n # @return [:present, :absent, nil] Should the resource be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7028380632400513, "alphanum_fraction": 0.7028380632400513, "avg_line_length": 34.235294342041016, "blob_id": "0a8b6363064cc664ba41532c47b7a3d1f2f1637b", "content_id": "ab047597760e9d9e7b0fc87f5b1cd305b285acdf", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 599, "license_type": "permissive", "max_line_length": 115, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/utilities/logic/import_playbook.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Includes a file with a list of plays to be executed.\n # Files with a list of plays can only be included at the top level. You cannot use this action inside a play.\n class Import_playbook < Base\n # @return [Object, nil] The name of the imported playbook is specified directly without any other option.\n attribute :free_form, original_name: 'free-form'\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6734250783920288, "alphanum_fraction": 0.6734250783920288, "avg_line_length": 40.84848403930664, "blob_id": "75831ee7273f6f45b7a59251c02582e414b6e2df", "content_id": "6b79a9f9e7e6960faf5d8079a4a1909250abbc5a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1381, "license_type": "permissive", "max_line_length": 159, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/network/illumos/ipadm_addrprop.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Modify IP address properties on Solaris/illumos systems.\n class Ipadm_addrprop < Base\n # @return [String] Specifies the address object we want to manage.\n attribute :addrobj\n validates :addrobj, presence: true, type: String\n\n # @return [String] Specifies the name of the address property we want to manage.\n attribute :property\n validates :property, presence: true, type: String\n\n # @return [String, nil] Specifies the value we want to set for the address property.\n attribute :value\n validates :value, type: String\n\n # @return [Boolean, nil] Specifies that the address property value is temporary. Temporary values do not persist across reboots.\n attribute :temporary\n validates :temporary, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:present, :absent, :reset, nil] Set or reset the property value.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :reset], :message=>\"%{value} needs to be :present, :absent, :reset\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6555755138397217, "alphanum_fraction": 0.6569244861602783, "avg_line_length": 40.96226501464844, "blob_id": "fe09a07af614ef9334b2fb79f562d5f28fef58a3", "content_id": "dfc70e27cd36d557398e9c048a543cc87b588565", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2224, "license_type": "permissive", "max_line_length": 200, "num_lines": 53, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_logging.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of logging on Cisco NX-OS devices.\n class Nxos_logging < Base\n # @return [:console, :logfile, :module, :monitor, :server, nil] Destination of the logs.\n attribute :dest\n validates :dest, expression_inclusion: {:in=>[:console, :logfile, :module, :monitor, :server], :message=>\"%{value} needs to be :console, :logfile, :module, :monitor, :server\"}, allow_nil: true\n\n # @return [String, nil] Hostname or IP Address for remote logging (when dest is 'server').\n attribute :remote_server\n validates :remote_server, type: String\n\n # @return [String, nil] VRF to be used while configuring remote logging (when dest is 'server').\n attribute :use_vrf\n validates :use_vrf, type: String\n\n # @return [String, nil] Interface to be used while configuring source-interface for logging (e.g., 'Ethernet1/2', 'mgmt0')\n attribute :interface\n validates :interface, type: String\n\n # @return [String, nil] If value of C(dest) is I(logfile) it indicates file-name.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] Facility name for logging.\n attribute :facility\n validates :facility, type: String\n\n # @return [Integer, nil] Set logging severity levels.\n attribute :dest_level\n validates :dest_level, type: Integer\n\n # @return [Integer, nil] Set logging serverity levels for facility based log messages.\n attribute :facility_level\n validates :facility_level, type: Integer\n\n # @return [Array<Hash>, Hash, nil] List of logging definitions.\n attribute :aggregate\n validates :aggregate, type: TypeGeneric.new(Hash)\n\n # @return [:present, :absent, nil] State of the logging configuration.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.47377344965934753, "alphanum_fraction": 0.47504502534866333, "avg_line_length": 31.318492889404297, "blob_id": "55028bbe6f4bcecffd3e3625b519202c28216a38", "content_id": "1c5ef66887f51f1e6d9b2c99474e3ae9eef7b39b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 9437, "license_type": "permissive", "max_line_length": 118, "num_lines": 292, "path": "/util/parser/option.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# See LICENSE.txt for license\nrequire 'json'\n\nrequire_relative './option_data'\n\nmodule Ansible\n module Ruby\n module Parser\n module Option\n class << self\n def parse(name, details, example)\n puts \"---\\nParsing option #{name}\" if debug?\n details = details.symbolize_keys\n description = parse_description(details)\n sample_values = find_sample_values name, details, example\n specified_type = details[:type]\n choices = parse_choices(details)\n types = derive_types sample_values,\n specified_type,\n choices\n # Example only has true or false\n missing_bool_type = missing_bool_type types\n if missing_bool_type\n types << missing_bool_type\n choices = [true, false]\n end\n puts \"Sample values: #{sample_values}\\nDerived Types: #{types}\" if debug?\n OptionData.new name: name,\n description: description,\n required: details[:required],\n types: types,\n choices: choices\n rescue StandardError\n $stderr << \"Problem parsing option #{name}!\"\n raise\n ensure\n puts \"\\nDone Parsing option #{name}\" if debug?\n end\n\n def parse_description(details)\n # can be both an array and string, could have carriage returns in it\n lines = [*details[:description]]\n lines.map do |line|\n line.gsub(/\\r?\\n/, '\\\\r\\\\n')\n end\n end\n\n private\n\n def debug?\n ENV['DEBUG']\n end\n\n def missing_bool_type(types)\n result = [TrueClass, FalseClass] - types\n result.length == 1 ? result[0] : nil\n end\n\n def find_sample_values(attribute, details, example)\n union_type = union_type? details\n default = details[:default]\n # A lot of options with no defaults in Ansible have a value of None\n result = if use_default?(default, union_type)\n default\n elsif (choices = parse_choices(details)) && !union_type\n choices[0]\n elsif union_type\n nil\n elsif [Hash, Array].include? example.class\n values_by_key = values_by_key(example)\n values_by_key[attribute]\n else\n []\n end\n [*result]\n end\n\n def use_default?(default, union_type)\n !default.is_a?(NilClass) && !union_type && default != 'None'\n end\n\n def parse_choices(details)\n choices = details[:choices]\n specified_type = details[:type]\n default = details[:default]\n return nil unless choices&.any? || specified_type && default\n return derive_choices_from_type_and_default(specified_type, default) if specified_type && default\n\n choices.map do |choice|\n result = parse_value_into_num choice\n result = result.to_sym if result.is_a?(String)\n result\n end\n end\n\n def derive_choices_from_type_and_default(type,\n default)\n case type\n when 'bool'\n case default\n when 'yes', 'no'\n %i[yes no]\n when 'True', 'False', true, false\n [true, false]\n end\n end\n end\n\n def choice_classes(details)\n choices = parse_choices details\n return nil unless choices\n\n choices.map do |choice|\n case choice\n when TrueClass, FalseClass\n # for YARD purposes\n 'Boolean'\n else\n choice.class\n end\n end.uniq\n end\n\n def union_type?(details)\n klasses = choice_classes details\n klasses && klasses.length != 1\n end\n\n def values_by_key(example)\n example = example['tasks'] if example.is_a?(Hash) && example['tasks']\n first_cut = example.map { |ex| ex.reject { |key, _| key == 'name' } }\n .map { |ex| ex.map { |_, value| value } }\n .flatten\n array_of_hashes = first_cut.map do |value|\n if value.is_a?(String)\n hash_equal_sign_pairs(value)\n elsif value.is_a? Hash\n value\n end\n end.compact\n array_of_hashes.each_with_object({}) do |hash, result|\n hash.each do |key, value|\n by_key = result[key] ||= []\n by_key << value\n by_key.uniq!\n end\n result\n end\n end\n\n def hash_equal_sign_pairs(key_value_str)\n Hash[key_value_str.split(' ').map do |pair|\n equals = pair.split '='\n next unless equals.length >= 2\n\n # some attributes have data like attr=value=value2, only want attr=value\n equals[0..1]\n end.compact]\n end\n\n def derive_types(values,\n specified_type,\n choices)\n types = specified_type ? map_type(specified_type, choices) : values.map { |value| derive_type value }.uniq\n generic = types.find { |type| type.is_a?(TypeGeneric) }\n # No need to include generic and the generic's type\n without_type_outside = types.reject { |type| generic&.klasses&.include?(type) }\n collapse_generics without_type_outside\n end\n\n def map_type(type,\n choices)\n case type\n when 'bool'\n if choices == [true, false]\n [TrueClass, FalseClass]\n else\n [Symbol]\n end\n when 'int'\n [Integer]\n when 'str', 'path'\n choices ? [Symbol] : [String]\n when 'list'\n [TypeGeneric.new(String)]\n when 'dict'\n [Hash]\n else\n raise \"Unknown type #{type}\"\n end\n end\n\n def collapse_generics(types)\n grouped = Hash.new { |hash, key| hash[key] = [] }\n types.each do |type|\n if type.is_a?(TypeGeneric)\n grouped[:generic] += type.klasses\n else\n grouped[:others] << type\n end\n end\n generics = grouped[:generic]\n others = grouped[:others]\n others << TypeGeneric.new(*generics) if generics.any?\n others\n end\n\n def derive_type(value)\n value = unquote_string(value)\n if hash?(value)\n Hash\n elsif (array = parse_array(value))\n item = array[0]\n value = parse_value_into_num item\n klass = handle_fixnum value.class\n TypeGeneric.new klass\n else\n handle_fixnum value.class\n end\n end\n\n def parse_array(value)\n flat_array(value) || (value.is_a?(Array) && value)\n end\n\n def variable_expression?(value)\n value.lstrip.start_with?('{{')\n end\n\n def handle_fixnum(klass)\n # Integers are more clear\n klass == Fixnum ? Integer : klass\n end\n\n def parse_value_into_num(item)\n return item unless item.is_a?(String)\n\n parsed_float(item) || parsed_integer(item) || item\n end\n\n # some sample values are foo='stuff,bar'\n def unquote_string(value)\n return value unless value.is_a?(String) && !variable_expression?(value)\n\n ((unquoted_match = /'(.*)'/.match(value)) && unquoted_match[1]) || value\n end\n\n def parsed_integer(value)\n Integer(value)\n rescue StandardError\n false\n end\n\n def parsed_float(value)\n value.include?('.') && Float(value)\n rescue StandardError\n false\n end\n\n def hash?(value)\n return false unless value.is_a?(String)\n\n JSON.parse(value).is_a?(Hash)\n rescue StandardError\n # JSON.parse knows\n false\n end\n\n def flat_array(*values)\n # be conservative for now\n return nil unless values.length == 1\n\n value = values[0]\n return nil unless value.is_a?(String) && value.include?(',') && !variable_expression?(value)\n\n items = value.split(',').map do |item|\n item = parse_value_into_num(item)\n item.inspect\n end\n array_str = \"[#{items.join(', ')}]\"\n JSON.parse array_str\n rescue StandardError\n # if we can't parse it with what we did, it's not an array\n false\n end\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7067694664001465, "alphanum_fraction": 0.7087801694869995, "avg_line_length": 65.31111145019531, "blob_id": "5f9fa22b0236177f6f0539b9be47db4771a36811", "content_id": "ae45b53465d23266613b40556f02bd3d53e388ff", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2984, "license_type": "permissive", "max_line_length": 795, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/files/replace.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module will replace all instances of a pattern within a file.\n # It is up to the user to maintain idempotence by ensuring that the same pattern would never match any replacements made.\n class Replace < Base\n # @return [String] The file to modify.,Before 2.3 this option was only usable as I(dest), I(destfile) and I(name).\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [String] The regular expression to look for in the contents of the file. Uses Python regular expressions; see U(http://docs.python.org/2/library/re.html). Uses MULTILINE mode, which means C(^) and C($) match the beginning and end of the file, as well as the beginning and end respectively of I(each line) of the file.,Does not use DOTALL, which means the C(.) special character matches any character I(except newlines). A common mistake is to assume that a negated character set like C([^#]) will also not match newlines. In order to exclude newlines, they must be added to the set like C([^#\\\\n]).,Note that, as of ansible 2, short form tasks should have any escape sequences backslash-escaped in order to prevent them being parsed as string literal escapes. See the examples.\n attribute :regexp\n validates :regexp, presence: true, type: String\n\n # @return [String, nil] The string to replace regexp matches. May contain backreferences that will get expanded with the regexp capture groups if the regexp matches. If not set, matches are removed entirely.\n attribute :replace\n validates :replace, type: String\n\n # @return [String, nil] If specified, the line after the replace/remove will start. Can be used in combination with C(before). Uses Python regular expressions; see U(http://docs.python.org/2/library/re.html).\n attribute :after\n validates :after, type: String\n\n # @return [String, nil] If specified, the line before the replace/remove will occur. Can be used in combination with C(after). Uses Python regular expressions; see U(http://docs.python.org/2/library/re.html).\n attribute :before\n validates :before, type: String\n\n # @return [:yes, :no, nil] Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.\n attribute :backup\n validates :backup, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] All arguments accepted by the M(file) module also work here.\n attribute :others\n\n # @return [String, nil] The character encoding for reading and writing the file.\n attribute :encoding\n validates :encoding, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6336293816566467, "alphanum_fraction": 0.642107367515564, "avg_line_length": 50.072166442871094, "blob_id": "51cd5a47690041799dfd421d76f3d2554ad7e4eb", "content_id": "efc5a08c36d7b81e93985220b59314c06ced2dd2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4954, "license_type": "permissive", "max_line_length": 238, "num_lines": 97, "path": "/lib/ansible/ruby/modules/generated/net_tools/cloudflare_dns.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages dns records via the Cloudflare API, see the docs: U(https://api.cloudflare.com/)\n class Cloudflare_dns < Base\n # @return [String] Account API token. You can obtain your API key from the bottom of the Cloudflare 'My Account' page, found here: U(https://dash.cloudflare.com/)\\r\\n\n attribute :account_api_token\n validates :account_api_token, presence: true, type: String\n\n # @return [String] Account email.\n attribute :account_email\n validates :account_email, presence: true, type: String\n\n # @return [Integer, nil] Algorithm number. Required for C(type=DS) and C(type=SSHFP) when C(state=present).\n attribute :algorithm\n validates :algorithm, type: Integer\n\n # @return [0, 1, 2, 3, nil] Certificate usage number. Required for C(type=TLSA) when C(state=present).\n attribute :cert_usage\n validates :cert_usage, expression_inclusion: {:in=>[0, 1, 2, 3], :message=>\"%{value} needs to be 0, 1, 2, 3\"}, allow_nil: true\n\n # @return [1, 2, nil] Hash type number. Required for C(type=DS), C(type=SSHFP) and C(type=TLSA) when C(state=present).\n attribute :hash_type\n validates :hash_type, expression_inclusion: {:in=>[1, 2], :message=>\"%{value} needs to be 1, 2\"}, allow_nil: true\n\n # @return [Integer, nil] DNSSEC key tag. Needed for C(type=DS) when C(state=present).\n attribute :key_tag\n validates :key_tag, type: Integer\n\n # @return [Integer, nil] Service port. Required for C(type=SRV) and C(type=TLSA).\n attribute :port\n validates :port, type: Integer\n\n # @return [String, nil] Record priority. Required for C(type=MX) and C(type=SRV)\n attribute :priority\n validates :priority, type: String\n\n # @return [String, nil] Service protocol. Required for C(type=SRV) and C(type=TLSA).,Common values are tcp and udp.,Before Ansible 2.6 only tcp and udp were available.\n attribute :proto\n validates :proto, type: String\n\n # @return [:yes, :no, nil] Proxy through cloudflare network or just use DNS\n attribute :proxied\n validates :proxied, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Record to add. Required if C(state=present). Default is C(@) (e.g. the zone name)\n attribute :record\n validates :record, type: String\n\n # @return [0, 1, nil] Selector number. Required for C(type=TLSA) when C(state=present).\n attribute :selector\n validates :selector, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [String, nil] Record service. Required for C(type=SRV)\n attribute :service\n validates :service, type: String\n\n # @return [Boolean, nil] Whether the record should be the only one for that record type and record name. Only use with C(state=present),This will delete all other records with the same record name and type.\n attribute :solo\n validates :solo, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Whether the record(s) should exist or not\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Integer, nil] Timeout for Cloudflare API calls\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [String, nil] The TTL to give the new record. Must be between 120 and 2,147,483,647 seconds, or 1 for automatic.\n attribute :ttl\n validates :ttl, type: String\n\n # @return [:A, :AAAA, :CNAME, :TXT, :SRV, :MX, :NS, :DS, :SPF, :SSHFP, :TLSA, nil] The type of DNS record to create. Required if C(state=present),C(type=DS), C(type=SSHFP) and C(type=TLSA) added in Ansible 2.7.\n attribute :type\n validates :type, expression_inclusion: {:in=>[:A, :AAAA, :CNAME, :TXT, :SRV, :MX, :NS, :DS, :SPF, :SSHFP, :TLSA], :message=>\"%{value} needs to be :A, :AAAA, :CNAME, :TXT, :SRV, :MX, :NS, :DS, :SPF, :SSHFP, :TLSA\"}, allow_nil: true\n\n # @return [String, nil] The record value. Required for C(state=present)\n attribute :value\n validates :value, type: String\n\n # @return [String, nil] Service weight. Required for C(type=SRV)\n attribute :weight\n validates :weight, type: String\n\n # @return [String] The name of the Zone to work with (e.g. \"example.com\"). The Zone must already exist.\n attribute :zone\n validates :zone, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6977218389511108, "alphanum_fraction": 0.6990819573402405, "avg_line_length": 63.63736343383789, "blob_id": "478edb090a90835b03c0eab26f7010d3b501d5f5", "content_id": "7335e2634f6afca160c29a8d49f3e7c74ebb9eef", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5882, "license_type": "permissive", "max_line_length": 649, "num_lines": 91, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_host.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Module to manage hosts in oVirt/RHV\n class Ovirt_host < Base\n # @return [String] Name of the host to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, :maintenance, :upgraded, :started, :restarted, :stopped, :reinstalled, :iscsidiscover, :iscsilogin, nil] State which should a host to be in after successful completion.,I(iscsilogin) and I(iscsidiscover) are supported since version 2.4.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :maintenance, :upgraded, :started, :restarted, :stopped, :reinstalled, :iscsidiscover, :iscsilogin], :message=>\"%{value} needs to be :present, :absent, :maintenance, :upgraded, :started, :restarted, :stopped, :reinstalled, :iscsidiscover, :iscsilogin\"}, allow_nil: true\n\n # @return [Object, nil] Description of the host.\n attribute :comment\n\n # @return [Integer, nil] The amount of time in seconds the module should wait for the host to get into desired state.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [String, nil] Name of the cluster, where host should be created.\n attribute :cluster\n validates :cluster, type: String\n\n # @return [String, nil] Host address. It can be either FQDN (preferred) or IP address.\n attribute :address\n validates :address, type: String\n\n # @return [String, nil] Password of the root. It's required in case C(public_key) is set to I(False).\n attribute :password\n validates :password, type: String\n\n # @return [Symbol, nil] I(True) if the public key should be used to authenticate to host.,It's required in case C(password) is not set.\n attribute :public_key\n validates :public_key, type: Symbol\n\n # @return [:enabled, :disabled, nil] Specify if host will have enabled Kdump integration.\n attribute :kdump_integration\n validates :kdump_integration, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [Object, nil] SPM priority of the host. Integer value from 1 to 10, where higher number means higher priority.\n attribute :spm_priority\n\n # @return [Symbol, nil] If True host iptables will be overridden by host deploy script.,Note that C(override_iptables) is I(false) by default in oVirt/RHV.\n attribute :override_iptables\n validates :override_iptables, type: Symbol\n\n # @return [Symbol, nil] If True host will be forcibly moved to desired state.\n attribute :force\n validates :force, type: Symbol\n\n # @return [Symbol, nil] Override the display address of all VMs on this host with specified address.\n attribute :override_display\n validates :override_display, type: Symbol\n\n # @return [Array<String>, String, nil] List of kernel boot parameters.,Following are most common kernel parameters used for host:,Hostdev Passthrough & SR-IOV: intel_iommu=on,Nested Virtualization: kvm-intel.nested=1,Unsafe Interrupts: vfio_iommu_type1.allow_unsafe_interrupts=1,PCI Reallocation: pci=realloc,C(Note:),Modifying kernel boot parameters settings can lead to a host boot failure. Please consult the product documentation before doing any changes.,Kernel boot parameters changes require host deploy and restart. The host needs to be I(reinstalled) successfully and then to be I(rebooted) for kernel boot parameters to be applied.\n attribute :kernel_params\n validates :kernel_params, type: TypeGeneric.new(String)\n\n # @return [:deploy, :undeploy, nil] If I(deploy) it means this host should deploy also hosted engine components.,If I(undeploy) it means this host should un-deploy hosted engine components and this host will not function as part of the High Availability cluster.\n attribute :hosted_engine\n validates :hosted_engine, expression_inclusion: {:in=>[:deploy, :undeploy], :message=>\"%{value} needs to be :deploy, :undeploy\"}, allow_nil: true\n\n # @return [Symbol, nil] Enable or disable power management of the host.,For more comprehensive setup of PM use C(ovirt_host_pm) module.\n attribute :power_management_enabled\n validates :power_management_enabled, type: Symbol\n\n # @return [Boolean, nil] If C(state) is I(present) activate the host.,This parameter is good to disable, when you don't want to change the state of host when using I(present) C(state).\n attribute :activate\n validates :activate, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Hash, nil] If C(state) is I(iscsidiscover) it means that the iscsi attribute is being used to discover targets,If C(state) is I(iscsilogin) it means that the iscsi attribute is being used to login to the specified targets passed as part of the iscsi attribute\n attribute :iscsi\n validates :iscsi, type: Hash\n\n # @return [Boolean, nil] If I(true) and C(state) is I(upgraded) run check for upgrade action before executing upgrade action.\n attribute :check_upgrade\n validates :check_upgrade, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] If I(true) and C(state) is I(upgraded) reboot host after successful upgrade.\n attribute :reboot_after_upgrade\n validates :reboot_after_upgrade, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6464340090751648, "alphanum_fraction": 0.6479514241218567, "avg_line_length": 39.34693908691406, "blob_id": "4b1d5afd36af561fdb2ec0f12ec4f30eba58c204", "content_id": "106570ed00ad0d97fec1a9c647ca017ecf009a3c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1977, "license_type": "permissive", "max_line_length": 144, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/cloud/rackspace/rax_cbs.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manipulate Rackspace Cloud Block Storage Volumes\n class Rax_cbs < Base\n # @return [Object, nil] Description to give the volume being created\n attribute :description\n\n # @return [Object, nil] image to use for bootable volumes. Can be an C(id), C(human_id) or C(name). This option requires C(pyrax>=1.9.3)\n attribute :image\n\n # @return [Object, nil] A hash of metadata to associate with the volume\n attribute :meta\n\n # @return [String] Name to give the volume being created\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Integer] Size of the volume to create in Gigabytes\n attribute :size\n validates :size, presence: true, type: Integer\n\n # @return [Object, nil] The id of the snapshot to create the volume from\n attribute :snapshot_id\n\n # @return [:present, :absent] Indicate desired state of the resource\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [:SATA, :SSD] Type of the volume being created\n attribute :volume_type\n validates :volume_type, presence: true, expression_inclusion: {:in=>[:SATA, :SSD], :message=>\"%{value} needs to be :SATA, :SSD\"}\n\n # @return [:yes, :no, nil] wait for the volume to be in state 'available' before returning\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] how long before wait gives up, in seconds\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.71074378490448, "alphanum_fraction": 0.71074378490448, "avg_line_length": 58.093021392822266, "blob_id": "fbeafff2c681a414988bc1c61d497ec99a2ab585", "content_id": "4e043c664b32142919b6efc060b234a5493096da", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2541, "license_type": "permissive", "max_line_length": 321, "num_lines": 43, "path": "/lib/ansible/ruby/modules/generated/system/sysvinit.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Controls services on target hosts that use the SysV init system.\n class Sysvinit < Base\n # @return [String] Name of the service.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:started, :stopped, :restarted, :reloaded, nil] C(started)/C(stopped) are idempotent actions that will not run commands unless necessary. Not all init scripts support C(restarted) nor C(reloaded) natively, so these will both trigger a stop and start as needed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:started, :stopped, :restarted, :reloaded], :message=>\"%{value} needs to be :started, :stopped, :restarted, :reloaded\"}, allow_nil: true\n\n # @return [Symbol, nil] Whether the service should start on boot. B(At least one of state and enabled are required.)\n attribute :enabled\n validates :enabled, type: Symbol\n\n # @return [Integer, nil] If the service is being C(restarted) or C(reloaded) then sleep this many seconds between the stop and start command. This helps to workaround badly behaving services.\n attribute :sleep\n validates :sleep, type: Integer\n\n # @return [Object, nil] A substring to look for as would be found in the output of the I(ps) command as a stand-in for a status result.,If the string is found, the service will be assumed to be running.,This option is mainly for use with init scripts that don't support the 'status' option.\n attribute :pattern\n\n # @return [Array<Integer>, Integer, nil] The runlevels this script should be enabled/disabled from.,Use this to override the defaults set by the package or init script itself.\n attribute :runlevels\n validates :runlevels, type: TypeGeneric.new(Integer)\n\n # @return [Object, nil] Additional arguments provided on the command line that some init scripts accept.\n attribute :arguments\n\n # @return [Symbol, nil] Have the module daemonize as the service itself might not do so properly.,This is useful with badly written init scripts or deamons, which commonly manifests as the task hanging as it is still holding the tty or the service dying when the task is over as the connection closes the session.\n attribute :daemonize\n validates :daemonize, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6181172132492065, "alphanum_fraction": 0.6323268413543701, "avg_line_length": 55.29999923706055, "blob_id": "ffbab13b0e6a428b51b84ae8b730e0a86b6dddad", "content_id": "616abc291bd12ca5369649c585efb9c4c74d099e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1689, "license_type": "permissive", "max_line_length": 398, "num_lines": 30, "path": "/lib/ansible/ruby/modules/generated/notification/syslogger.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Uses syslog to add log entries to the host.\n # Can specify facility and priority.\n class Syslogger < Base\n # @return [String] This is the message to place in syslog\n attribute :msg\n validates :msg, presence: true, type: String\n\n # @return [:emerg, :alert, :crit, :err, :warning, :notice, :info, :debug, nil] Set the log priority\n attribute :priority\n validates :priority, expression_inclusion: {:in=>[:emerg, :alert, :crit, :err, :warning, :notice, :info, :debug], :message=>\"%{value} needs to be :emerg, :alert, :crit, :err, :warning, :notice, :info, :debug\"}, allow_nil: true\n\n # @return [:kern, :user, :mail, :daemon, :auth, :lpr, :news, :uucp, :cron, :syslog, :local0, :local1, :local2, :local3, :local4, :local5, :local6, :local7, nil] Set the log facility\n attribute :facility\n validates :facility, expression_inclusion: {:in=>[:kern, :user, :mail, :daemon, :auth, :lpr, :news, :uucp, :cron, :syslog, :local0, :local1, :local2, :local3, :local4, :local5, :local6, :local7], :message=>\"%{value} needs to be :kern, :user, :mail, :daemon, :auth, :lpr, :news, :uucp, :cron, :syslog, :local0, :local1, :local2, :local3, :local4, :local5, :local6, :local7\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Log the pid in brackets\n attribute :log_pid\n validates :log_pid, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6415672898292542, "alphanum_fraction": 0.6436116099357605, "avg_line_length": 41.536231994628906, "blob_id": "9dacc15cbfaca1e6b92f6b79dd0a029d692234c0", "content_id": "487ae117d0560e9001a071f861a7e28938d6ca63", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2935, "license_type": "permissive", "max_line_length": 217, "num_lines": 69, "path": "/lib/ansible/ruby/modules/generated/windows/win_firewall_rule.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows you to create/remove/update firewall rules.\n class Win_firewall_rule < Base\n # @return [:yes, :no, nil] Is this firewall rule enabled or disabled.\n attribute :enabled\n validates :enabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:absent, :present, nil] Should this rule be added or removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String] The rules name\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:in, :out] Is this rule for inbound or outbound traffic.\n attribute :direction\n validates :direction, presence: true, expression_inclusion: {:in=>[:in, :out], :message=>\"%{value} needs to be :in, :out\"}\n\n # @return [:allow, :block, :bypass] What to do with the items this rule is for.\n attribute :action\n validates :action, presence: true, expression_inclusion: {:in=>[:allow, :block, :bypass], :message=>\"%{value} needs to be :allow, :block, :bypass\"}\n\n # @return [Object, nil] Description for the firewall rule.\n attribute :description\n\n # @return [String, nil] The local ip address this rule applies to.\n attribute :localip\n validates :localip, type: String\n\n # @return [String, nil] The remote ip address/range this rule applies to.\n attribute :remoteip\n validates :remoteip, type: String\n\n # @return [Integer, nil] The local port this rule applies to.\n attribute :localport\n validates :localport, type: Integer\n\n # @return [Object, nil] The remote port this rule applies to.\n attribute :remoteport\n\n # @return [Object, nil] The program this rule applies to.\n attribute :program\n\n # @return [Object, nil] The service this rule applies to.\n attribute :service\n\n # @return [String, nil] The protocol this rule applies to.\n attribute :protocol\n validates :protocol, type: String\n\n # @return [Array<String>, String, nil] The profile this rule applies to.\n attribute :profiles\n validates :profiles, type: TypeGeneric.new(String)\n\n # @return [:yes, :no, nil] Replace any existing rule by removing it first.,This is no longer required in 2.4 as rules no longer need replacing when being modified.,DEPRECATED in 2.4 and will be removed in 2.9.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6092843413352966, "alphanum_fraction": 0.6499032974243164, "avg_line_length": 62.04878234863281, "blob_id": "35731013b8b5f898aea509ee492b3fa7d1849631", "content_id": "bdf488aef8c47ac7511def4eba20dfd16c1ced03", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2585, "license_type": "permissive", "max_line_length": 416, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_contract.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage Contract resources on Cisco ACI fabrics.\n class Aci_contract < Base\n # @return [String] The name of the contract.\n attribute :contract\n validates :contract, presence: true, type: String\n\n # @return [String, nil] Description for the contract.\n attribute :description\n validates :description, type: String\n\n # @return [String] The name of the tenant.\n attribute :tenant\n validates :tenant, presence: true, type: String\n\n # @return [:\"application-profile\", :context, :global, :tenant, nil] The scope of a service contract.,The APIC defaults to C(context) when unset during creation.\n attribute :scope\n validates :scope, expression_inclusion: {:in=>[:\"application-profile\", :context, :global, :tenant], :message=>\"%{value} needs to be :\\\"application-profile\\\", :context, :global, :tenant\"}, allow_nil: true\n\n # @return [:level1, :level2, :level3, :unspecified, nil] The desired QoS class to be used.,The APIC defaults to C(unspecified) when unset during creation.\n attribute :priority\n validates :priority, expression_inclusion: {:in=>[:level1, :level2, :level3, :unspecified], :message=>\"%{value} needs to be :level1, :level2, :level3, :unspecified\"}, allow_nil: true\n\n # @return [:AF11, :AF12, :AF13, :AF21, :AF22, :AF23, :AF31, :AF32, :AF33, :AF41, :AF42, :AF43, :CS0, :CS1, :CS2, :CS3, :CS4, :CS5, :CS6, :CS7, :EF, :VA, :unspecified, nil] The target Differentiated Service (DSCP) value.,The APIC defaults to C(unspecified) when unset during creation.\n attribute :dscp\n validates :dscp, expression_inclusion: {:in=>[:AF11, :AF12, :AF13, :AF21, :AF22, :AF23, :AF31, :AF32, :AF33, :AF41, :AF42, :AF43, :CS0, :CS1, :CS2, :CS3, :CS4, :CS5, :CS6, :CS7, :EF, :VA, :unspecified], :message=>\"%{value} needs to be :AF11, :AF12, :AF13, :AF21, :AF22, :AF23, :AF31, :AF32, :AF33, :AF41, :AF42, :AF43, :CS0, :CS1, :CS2, :CS3, :CS4, :CS5, :CS6, :CS7, :EF, :VA, :unspecified\"}, allow_nil: true\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6459770202636719, "alphanum_fraction": 0.6652147769927979, "avg_line_length": 54.8445930480957, "blob_id": "5b3e4898d9582d6396b83d628cd98c253872ed06", "content_id": "cc7ec655d488ad86d5672b755ecc068a7fa2a220", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 8265, "license_type": "permissive", "max_line_length": 357, "num_lines": 148, "path": "/lib/ansible/ruby/modules/generated/net_tools/nmcli.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage the network devices. Create, modify and manage various connection and device type e.g., ethernet, teams, bonds, vlans etc.\n # On CentOS and Fedora like systems, install dependencies as 'yum/dnf install -y python-gobject NetworkManager-glib'\n # On Ubuntu and Debian like systems, install dependencies as 'apt-get install -y libnm-glib-dev'\n class Nmcli < Base\n # @return [:present, :absent] Whether the device should exist or not, taking action if the state is different from what is stated.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [Boolean, nil] Whether the connection should start on boot.,Whether the connection profile can be automatically activated\n attribute :autoconnect\n validates :autoconnect, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String] Where conn_name will be the name used to call the connection. when not provided a default name is generated: <type>[-<ifname>][-<num>]\n attribute :conn_name\n validates :conn_name, presence: true, type: String\n\n # @return [String, nil] Where IFNAME will be the what we call the interface name.,interface to bind the connection to. The connection will only be applicable to this interface name.,A special value of \"*\" can be used for interface-independent connections.,The ifname argument is mandatory for all connection types except bond, team, bridge and vlan.\n attribute :ifname\n validates :ifname, type: String\n\n # @return [:ethernet, :team, :\"team-slave\", :bond, :\"bond-slave\", :bridge, :\"bridge-slave\", :vlan, :generic, nil] This is the type of device or network connection that you wish to create or modify.,type C(generic) is added in version 2.5.\n attribute :type\n validates :type, expression_inclusion: {:in=>[:ethernet, :team, :\"team-slave\", :bond, :\"bond-slave\", :bridge, :\"bridge-slave\", :vlan, :generic], :message=>\"%{value} needs to be :ethernet, :team, :\\\"team-slave\\\", :bond, :\\\"bond-slave\\\", :bridge, :\\\"bridge-slave\\\", :vlan, :generic\"}, allow_nil: true\n\n # @return [:\"balance-rr\", :\"active-backup\", :\"balance-xor\", :broadcast, :\"802.3ad\", :\"balance-tlb\", :\"balance-alb\", nil] This is the type of device or network connection that you wish to create for a bond, team or bridge.\n attribute :mode\n validates :mode, expression_inclusion: {:in=>[:\"balance-rr\", :\"active-backup\", :\"balance-xor\", :broadcast, :\"802.3ad\", :\"balance-tlb\", :\"balance-alb\"], :message=>\"%{value} needs to be :\\\"balance-rr\\\", :\\\"active-backup\\\", :\\\"balance-xor\\\", :broadcast, :\\\"802.3ad\\\", :\\\"balance-tlb\\\", :\\\"balance-alb\\\"\"}, allow_nil: true\n\n # @return [Object, nil] master <master (ifname, or connection UUID or conn_name) of bridge, team, bond master connection profile.\n attribute :master\n\n # @return [String, nil] The IPv4 address to this interface using this format ie: \"192.0.2.24/24\"\n attribute :ip4\n validates :ip4, type: String\n\n # @return [String, nil] The IPv4 gateway for this interface using this format ie: \"192.0.2.1\"\n attribute :gw4\n validates :gw4, type: String\n\n # @return [Object, nil] A list of upto 3 dns servers, ipv4 format e.g. To add two IPv4 DNS server addresses: \"192.0.2.53 198.51.100.53\"\n attribute :dns4\n\n # @return [Object, nil] A list of DNS search domains.\n attribute :dns4_search\n\n # @return [Object, nil] The IPv6 address to this interface using this format ie: \"abbe::cafe\"\n attribute :ip6\n\n # @return [Object, nil] The IPv6 gateway for this interface using this format ie: \"2001:db8::1\"\n attribute :gw6\n\n # @return [Object, nil] A list of upto 3 dns servers, ipv6 format e.g. To add two IPv6 DNS server addresses: \"2001:4860:4860::8888 2001:4860:4860::8844\"\n attribute :dns6\n\n # @return [Object, nil] A list of DNS search domains.\n attribute :dns6_search\n\n # @return [Integer, nil] The connection MTU, e.g. 9000. This can't be applied when creating the interface and is done once the interface has been created.,Can be used when modifying Team, VLAN, Ethernet (Future plans to implement wifi, pppoe, infiniband)\n attribute :mtu\n validates :mtu, type: Integer\n\n # @return [Object, nil] DHCP Client Identifier sent to the DHCP server.\n attribute :dhcp_client_id\n\n # @return [Object, nil] This is only used with bond and is the primary interface name (for \"active-backup\" mode), this is the usually the 'ifname'\n attribute :primary\n\n # @return [Integer, nil] This is only used with bond - miimon\n attribute :miimon\n validates :miimon, type: Integer\n\n # @return [Object, nil] This is only used with bond - downdelay\n attribute :downdelay\n\n # @return [Object, nil] This is only used with bond - updelay\n attribute :updelay\n\n # @return [Object, nil] This is only used with bond - ARP interval\n attribute :arp_interval\n\n # @return [Object, nil] This is only used with bond - ARP IP target\n attribute :arp_ip_target\n\n # @return [Symbol, nil] This is only used with bridge and controls whether Spanning Tree Protocol (STP) is enabled for this bridge\n attribute :stp\n validates :stp, type: Symbol\n\n # @return [Integer, nil] This is only used with 'bridge' - sets STP priority\n attribute :priority\n validates :priority, type: Integer\n\n # @return [Integer, nil] This is only used with bridge - [forward-delay <2-30>] STP forwarding delay, in seconds\n attribute :forwarddelay\n validates :forwarddelay, type: Integer\n\n # @return [Integer, nil] This is only used with bridge - [hello-time <1-10>] STP hello time, in seconds\n attribute :hellotime\n validates :hellotime, type: Integer\n\n # @return [Integer, nil] This is only used with bridge - [max-age <6-42>] STP maximum message age, in seconds\n attribute :maxage\n validates :maxage, type: Integer\n\n # @return [Integer, nil] This is only used with bridge - [ageing-time <0-1000000>] the Ethernet MAC address aging time, in seconds\n attribute :ageingtime\n validates :ageingtime, type: Integer\n\n # @return [Object, nil] This is only used with bridge - MAC address of the bridge (note: this requires a recent kernel feature, originally introduced in 3.15 upstream kernel)\\r\\n\n attribute :mac\n\n # @return [Integer, nil] This is only used with 'bridge-slave' - [<0-63>] - STP priority of this slave\n attribute :slavepriority\n validates :slavepriority, type: Integer\n\n # @return [Integer, nil] This is only used with 'bridge-slave' - [<1-65535>] - STP port cost for destinations via this slave\n attribute :path_cost\n validates :path_cost, type: Integer\n\n # @return [:yes, :no, nil] This is only used with 'bridge-slave' - 'hairpin mode' for the slave, which allows frames to be sent back out through the slave the frame was received on.\n attribute :hairpin\n validates :hairpin, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] This is only used with VLAN - VLAN ID in range <0-4095>\n attribute :vlanid\n\n # @return [Object, nil] This is only used with VLAN - parent device this VLAN is on, can use ifname\n attribute :vlandev\n\n # @return [Object, nil] This is only used with VLAN - flags\n attribute :flags\n\n # @return [Object, nil] This is only used with VLAN - VLAN ingress priority mapping\n attribute :ingress\n\n # @return [Object, nil] This is only used with VLAN - VLAN egress priority mapping\n attribute :egress\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6961130499839783, "alphanum_fraction": 0.6961130499839783, "avg_line_length": 46.16666793823242, "blob_id": "7f6fc63792288bb8bed6a38fa4e1fefb81ca0a7d", "content_id": "4fdae8b867b8d78e972b41c440218915a708f7e6", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1981, "license_type": "permissive", "max_line_length": 178, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_elementsw_access_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, destroy, or update access groups on Element Software Cluster.\n class Na_elementsw_access_group < Base\n # @return [:present, :absent] Whether the specified access group should exist or not.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String, Integer, nil] ID or Name of the access group to modify or delete.,Required for delete and modify operations.\n attribute :src_access_group_id\n validates :src_access_group_id, type: MultipleTypes.new(String, Integer)\n\n # @return [String, nil] New name for the access group for create and modify operation.,Required for create operation.\n attribute :new_name\n validates :new_name, type: String\n\n # @return [Object, nil] List of initiators to include in the access group. If unspecified, the access group will start out without configured initiators.\n attribute :initiators\n\n # @return [Array<Integer>, Integer, nil] List of volumes to initially include in the volume access group. If unspecified, the access group will start without any volumes.\n attribute :volumes\n validates :volumes, type: TypeGeneric.new(Integer)\n\n # @return [Object, nil] The ID of the Element SW Software Cluster Virtual Network ID to associate the access group with.\n attribute :virtual_network_id\n\n # @return [Object, nil] The ID of the VLAN Virtual Network Tag to associate the access group with.\n attribute :virtual_network_tags\n\n # @return [Hash, nil] List of Name/Value pairs in JSON object format.\n attribute :attributes\n validates :attributes, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7068557739257812, "alphanum_fraction": 0.7068557739257812, "avg_line_length": 39.28571319580078, "blob_id": "ad9571386f73d3a1c5bbb7a4f811d054bc44e81f", "content_id": "b332a1d052cb4708d8c6dd81c41ecaed86c8e67b", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 846, "license_type": "permissive", "max_line_length": 149, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_host_config_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to gather facts about an ESXi host's advance configuration information when ESXi hostname or Cluster name is given.\n class Vmware_host_config_facts < Base\n # @return [String, nil] Name of the cluster from which the ESXi host belong to.,If C(esxi_hostname) is not given, this parameter is required.\n attribute :cluster_name\n validates :cluster_name, type: String\n\n # @return [String, nil] ESXi hostname to gather facts from.,If C(cluster_name) is not given, this parameter is required.\n attribute :esxi_hostname\n validates :esxi_hostname, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6624472737312317, "alphanum_fraction": 0.6635020971298218, "avg_line_length": 40.21739196777344, "blob_id": "2fe7759253bcb3a76fe27db3d87e3a522bda4eec", "content_id": "ce2474957caf4a4da59fc62cb77cd8d5829eb040", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1896, "license_type": "permissive", "max_line_length": 154, "num_lines": 46, "path": "/lib/ansible/ruby/modules/generated/source_control/gitlab_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # When the group does not exist in Gitlab, it will be created.\n # When the group does exist and state=absent, the group will be deleted.\n # As of Ansible version 2.7, this module make use of a different python module and thus some arguments are deprecated.\n class Gitlab_group < Base\n # @return [Object] Url of Gitlab server, with protocol (http or https).\n attribute :server_url\n validates :server_url, presence: true\n\n # @return [Boolean, nil] When using https if SSL certificate needs to be verified.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] Gitlab user name.\n attribute :login_user\n\n # @return [Object, nil] Gitlab password for login_user\n attribute :login_password\n\n # @return [Object, nil] Gitlab token for logging in.\n attribute :login_token\n\n # @return [Object] Name of the group you want to create.\n attribute :name\n validates :name, presence: true\n\n # @return [Object, nil] The path of the group you want to create, this will be server_url/group_path,If not supplied, the group_name will be used.\n attribute :path\n\n # @return [Object, nil] A description for the group.\n attribute :description\n\n # @return [:present, :absent, nil] create or delete group.,Possible values are present and absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7046343088150024, "alphanum_fraction": 0.7046343088150024, "avg_line_length": 58.70000076293945, "blob_id": "214130bf1e74091838fdf7382b47ffa116a23f68", "content_id": "93c18062ecc8c811677a1869ee5ce00876342f1b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1791, "license_type": "permissive", "max_line_length": 283, "num_lines": 30, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_rest.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Enables the management of the Cisco ACI fabric through direct access to the Cisco APIC REST API.\n # Thanks to the idempotent nature of the APIC, this module is idempotent and reports changes.\n class Aci_rest < Base\n # @return [:delete, :get, :post, nil] The HTTP method of the request.,Using C(delete) is typically used for deleting objects.,Using C(get) is typically used for querying objects.,Using C(post) is typically used for modifying objects.\n attribute :method\n validates :method, expression_inclusion: {:in=>[:delete, :get, :post], :message=>\"%{value} needs to be :delete, :get, :post\"}, allow_nil: true\n\n # @return [Array<String>, String] URI being used to execute API calls.,Must end in C(.xml) or C(.json).\n attribute :path\n validates :path, presence: true, type: TypeGeneric.new(String)\n\n # @return [String, Hash, nil] When used instead of C(src), sets the payload of the API request directly.,This may be convenient to template simple requests.,For anything complex use the C(template) lookup plugin (see examples) or the M(template) module with parameter C(src).\n attribute :content\n validates :content, type: MultipleTypes.new(String, Hash)\n\n # @return [String, nil] Name of the absolute path of the filname that includes the body of the HTTP request being sent to the ACI fabric.,If you require a templated payload, use the C(content) parameter together with the C(template) lookup plugin, or use M(template).\n attribute :src\n validates :src, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6957250833511353, "alphanum_fraction": 0.6957250833511353, "avg_line_length": 46.720001220703125, "blob_id": "95e318b8b47907afade4ec1e747c6eb3f121331e", "content_id": "0135dc1ee92ad93df3e455c3f523f1ecbd127e35", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1193, "license_type": "permissive", "max_line_length": 262, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/monitoring/monit.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage the state of a program monitored via I(Monit)\n class Monit < Base\n # @return [String] The name of the I(monit) program/process to manage\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :started, :stopped, :restarted, :monitored, :unmonitored, :reloaded] The state of service\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :started, :stopped, :restarted, :monitored, :unmonitored, :reloaded], :message=>\"%{value} needs to be :present, :started, :stopped, :restarted, :monitored, :unmonitored, :reloaded\"}\n\n # @return [Integer, nil] If there are pending actions for the service monitored by monit, then Ansible will check for up to this many seconds to verify the requested action has been performed. Ansible will sleep for five seconds between each check.\n attribute :timeout\n validates :timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7309219241142273, "alphanum_fraction": 0.7353330254554749, "avg_line_length": 67.69696807861328, "blob_id": "5b68d392a80babc1e776f8958661f5540a40e6e6", "content_id": "0f378469ecd6006ea9170e93e66a2cd2e7c88377", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2267, "license_type": "permissive", "max_line_length": 977, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_pubsub_subscription.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # A named resource representing the stream of messages from a single, specific topic, to be delivered to the subscribing application.\n class Gcp_pubsub_subscription < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Name of the subscription.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] A reference to a Topic resource.\n attribute :topic\n validates :topic, type: String\n\n # @return [Hash, nil] If push delivery is used with this subscription, this field is used to configure it. An empty pushConfig signifies that the subscriber will pull and ack messages using API methods.\n attribute :push_config\n validates :push_config, type: Hash\n\n # @return [Integer, nil] This value is the maximum time after a subscriber receives a message before the subscriber should acknowledge the message. After message delivery but before the ack deadline expires and before the message is acknowledged, it is an outstanding message and will not be delivered again during that time (on a best-effort basis).,For pull subscriptions, this value is used as the initial value for the ack deadline. To override this value for a given message, call subscriptions.modifyAckDeadline with the corresponding ackId if using pull. The minimum custom deadline you can specify is 10 seconds. The maximum custom deadline you can specify is 600 seconds (10 minutes).,If this parameter is 0, a default value of 10 seconds is used.,For push delivery, this value is also used to set the request timeout for the call to the push endpoint.,If the subscriber never acknowledges the message, the Pub/Sub system will eventually redeliver the message.\n attribute :ack_deadline_seconds\n validates :ack_deadline_seconds, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6788718700408936, "alphanum_fraction": 0.6798614263534546, "avg_line_length": 44.931819915771484, "blob_id": "4385cb40926e2f483033a3f81cf3bfad7429225e", "content_id": "7781be7231cd405824b8f8d710cacb16c6a0872b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2021, "license_type": "permissive", "max_line_length": 251, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_autoscale.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, delete an autoscale setting.\n class Azure_rm_autoscale < Base\n # @return [String, nil] The identifier of the resource to apply autoscale setting.,It could be the resource id string.,It also could be a dict contains the C(name), C(subscription_id), C(namespace), C(types), C(resource_group) of the resource.\n attribute :target\n validates :target, type: String\n\n # @return [String] resource group of the resource.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [Boolean, nil] Specifies whether automatic scaling is enabled for the resource.\n attribute :enabled\n validates :enabled, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash, nil] The collection of automatic scaling profiles that specify different scaling parameters for different time periods.,A maximum of 20 profiles can be specified.\n attribute :profiles\n validates :profiles, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash, nil] the collection of notifications.\n attribute :notifications\n validates :notifications, type: TypeGeneric.new(Hash)\n\n # @return [:present, :absent, nil] Assert the state of the virtual network. Use 'present' to create or update and 'absent' to delete.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] location of the resource.\n attribute :location\n\n # @return [String] name of the resource.\n attribute :name\n validates :name, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7183308601379395, "alphanum_fraction": 0.7213114500045776, "avg_line_length": 38.47058868408203, "blob_id": "aa0f1b251f6647e7f6a3d8d86f856f7b521647ab", "content_id": "77eb25cc8c9115ca88251e5a84bfdd87a818cd8b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 671, "license_type": "permissive", "max_line_length": 269, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_compute_http_health_check_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gather facts for GCP HttpHealthCheck\n class Gcp_compute_http_health_check_facts < Base\n # @return [Array<String>, String, nil] A list of filter value pairs. Available filters are listed here U(https://cloud.google.com/sdk/gcloud/reference/topic/filters). Each additional filter in the list will act be added as an AND condition (filter1 and filter2)\n attribute :filters\n validates :filters, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6707199811935425, "alphanum_fraction": 0.6790400147438049, "avg_line_length": 51.08333206176758, "blob_id": "3239a7422d0176e1193159aa5969cea59cdef6c8", "content_id": "07fca57a8acb1f56554c41d881f013348ef1b593", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3125, "license_type": "permissive", "max_line_length": 264, "num_lines": 60, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ecs_taskdefinition.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Registers or deregisters task definitions in the Amazon Web Services (AWS) EC2 Container Service (ECS)\n class Ecs_taskdefinition < Base\n # @return [:present, :absent] State whether the task definition should exist or be deleted\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [Object, nil] The arn of the task description to delete\n attribute :arn\n\n # @return [String, nil] A Name that would be given to the task definition\n attribute :family\n validates :family, type: String\n\n # @return [Object, nil] A revision number for the task definition\n attribute :revision\n\n # @return [Object, nil] Always create new task definition\n attribute :force_create\n\n # @return [Array<Hash>, Hash, nil] A list of containers definitions\n attribute :containers\n validates :containers, type: TypeGeneric.new(Hash)\n\n # @return [:bridge, :host, :none, :awsvpc, nil] The Docker networking mode to use for the containers in the task.,C(awsvpc) mode was added in Ansible 2.5\n attribute :network_mode\n validates :network_mode, expression_inclusion: {:in=>[:bridge, :host, :none, :awsvpc], :message=>\"%{value} needs to be :bridge, :host, :none, :awsvpc\"}, allow_nil: true\n\n # @return [Object, nil] The Amazon Resource Name (ARN) of the IAM role that containers in this task can assume. All containers in this task are granted the permissions that are specified in this role.\n attribute :task_role_arn\n\n # @return [Object, nil] The Amazon Resource Name (ARN) of the task execution role that the Amazon ECS container agent and the Docker daemon can assume.\n attribute :execution_role_arn\n\n # @return [Array<Hash>, Hash, nil] A list of names of volumes to be attached\n attribute :volumes\n validates :volumes, type: TypeGeneric.new(Hash)\n\n # @return [:EC2, :FARGATE, nil] The launch type on which to run your task\n attribute :launch_type\n validates :launch_type, expression_inclusion: {:in=>[:EC2, :FARGATE], :message=>\"%{value} needs to be :EC2, :FARGATE\"}, allow_nil: true\n\n # @return [Integer, nil] The number of cpu units used by the task. If using the EC2 launch type, this field is optional and any value can be used. If using the Fargate launch type, this field is required and you must use one of [256, 512, 1024, 2048, 4096]\n attribute :cpu\n validates :cpu, type: Integer\n\n # @return [String, nil] The amount (in MiB) of memory used by the task. If using the EC2 launch type, this field is optional and any value can be used. If using the Fargate launch type, this field is required and is limited by the cpu\n attribute :memory\n validates :memory, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6441595554351807, "alphanum_fraction": 0.6441595554351807, "avg_line_length": 45.18421173095703, "blob_id": "c23d151ac1582847b6b1f26e5ecab31e7a6efb5a", "content_id": "7a36781bf739d13cee9aaf4906bd6ff2e025e191", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3510, "license_type": "permissive", "max_line_length": 213, "num_lines": 76, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_volume.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or destroy or modify volumes on NetApp ONTAP.\n class Na_ontap_volume < Base\n # @return [:present, :absent, nil] Whether the specified volume should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The name of the volume to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] Name of the vserver to use.\n attribute :vserver\n validates :vserver, presence: true, type: String\n\n # @return [Object, nil] Name of the existing volume to be renamed to name.\n attribute :from_name\n\n # @return [Symbol, nil] Set True if the volume is an Infinite Volume. Deleting an infinite volume is asynchronous.\n attribute :is_infinite\n validates :is_infinite, type: Symbol\n\n # @return [Boolean, nil] Whether the specified volume is online, or not.\n attribute :is_online\n validates :is_online, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] The name of the aggregate the flexvol should exist on.,Required when C(state=present).\n attribute :aggregate_name\n validates :aggregate_name, type: String\n\n # @return [Integer, nil] The size of the volume in (size_unit). Required when C(state=present).\n attribute :size\n validates :size, type: Integer\n\n # @return [:bytes, :b, :kb, :mb, :gb, :tb, :pb, :eb, :zb, :yb, nil] The unit used to interpret the size parameter.\n attribute :size_unit\n validates :size_unit, expression_inclusion: {:in=>[:bytes, :b, :kb, :mb, :gb, :tb, :pb, :eb, :zb, :yb], :message=>\"%{value} needs to be :bytes, :b, :kb, :mb, :gb, :tb, :pb, :eb, :zb, :yb\"}, allow_nil: true\n\n # @return [Object, nil] The volume type, either read-write (RW) or data-protection (DP).\n attribute :type\n\n # @return [Object, nil] Name of the export policy.\n attribute :policy\n\n # @return [String, nil] Junction path of the volume.\n attribute :junction_path\n validates :junction_path, type: String\n\n # @return [:none, :volume, nil] Space guarantee style for the volume.\n attribute :space_guarantee\n validates :space_guarantee, expression_inclusion: {:in=>[:none, :volume], :message=>\"%{value} needs to be :none, :volume\"}, allow_nil: true\n\n # @return [Object, nil] Amount of space reserved for snapshot copies of the volume.\n attribute :percent_snapshot_space\n\n # @return [:mixed, :ntfs, :unified, :unix, nil] The security style associated with this volume.\n attribute :volume_security_style\n validates :volume_security_style, expression_inclusion: {:in=>[:mixed, :ntfs, :unified, :unix], :message=>\"%{value} needs to be :mixed, :ntfs, :unified, :unix\"}, allow_nil: true\n\n # @return [Symbol, nil] Whether or not to enable Volume Encryption.\n attribute :encrypt\n validates :encrypt, type: Symbol\n\n # @return [Object, nil] Allows a storage efficiency policy to be set on volume creation.\n attribute :efficiency_policy\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7007791996002197, "alphanum_fraction": 0.7080519199371338, "avg_line_length": 55.617645263671875, "blob_id": "5774289c539c76a3236581feed595926afdb75c2", "content_id": "453c0435a49c1001963e605b6d112af88abcb052", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1925, "license_type": "permissive", "max_line_length": 464, "num_lines": 34, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_compute_backend_bucket.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Backend buckets allow you to use Google Cloud Storage buckets with HTTP(S) load balancing.\n # An HTTP(S) load balancer can direct traffic to specified URLs to a backend bucket rather than a backend service. It can send requests for static content to a Cloud Storage bucket and requests for dynamic content a virtual machine instance.\n class Gcp_compute_backend_bucket < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] Cloud Storage bucket name.\n attribute :bucket_name\n validates :bucket_name, presence: true, type: String\n\n # @return [String, nil] An optional textual description of the resource; provided by the client when the resource is created.\n attribute :description\n validates :description, type: String\n\n # @return [Symbol, nil] If true, enable Cloud CDN for this BackendBucket.\n attribute :enable_cdn\n validates :enable_cdn, type: Symbol\n\n # @return [String] Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash.\n attribute :name\n validates :name, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7241144180297852, "alphanum_fraction": 0.7241144180297852, "avg_line_length": 68.9047622680664, "blob_id": "20d938555df1b8381e56e5a5850cccdbe01f21ad", "content_id": "58204b2ea69a18112a1d75306d50b209a4e6e59f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1468, "license_type": "permissive", "max_line_length": 463, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/cloud/digital_ocean/digital_ocean_snapshot_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to gather facts about snapshot facts based upon provided values such as droplet, volume and snapshot id.\n class Digital_ocean_snapshot_facts < Base\n # @return [:all, :droplet, :volume, :by_id, nil] Specifies the type of snapshot facts to be retrived.,If set to C(droplet), then facts are gathered related to snapshots based on Droplets only.,If set to C(volume), then facts are gathered related to snapshots based on volumes only.,If set to C(by_id), then facts are gathered related to snapshots based on snapshot id only.,If not set to any of the above, then facts are gathered related to all snapshots.\n attribute :snapshot_type\n validates :snapshot_type, expression_inclusion: {:in=>[:all, :droplet, :volume, :by_id], :message=>\"%{value} needs to be :all, :droplet, :volume, :by_id\"}, allow_nil: true\n\n # @return [Integer, String, nil] To retrieve information about a snapshot, please specify this as a snapshot id.,If set to actual snapshot id, then facts are gathered related to that particular snapshot only.,This is required parameter, if C(snapshot_type) is set to C(by_id).\n attribute :snapshot_id\n validates :snapshot_id, type: MultipleTypes.new(Integer, String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.661113977432251, "alphanum_fraction": 0.661113977432251, "avg_line_length": 39.02083206176758, "blob_id": "40292f8c4a6790733c5c7377e89491cad11eac9a", "content_id": "76e259d772f8abab93b224ad027c97171ecb252c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1921, "license_type": "permissive", "max_line_length": 143, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_stack.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or Remove a Stack to an OpenStack Heat\n class Os_stack < Base\n # @return [:present, :absent, nil] Indicate desired state of the resource\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] Name of the stack that should be created, name could be char and digit, no space\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Tag for the stack that should be created, name could be char and digit, no space\n attribute :tag\n validates :tag, type: String\n\n # @return [String, nil] Path of the template file to use for the stack creation\n attribute :template\n validates :template, type: String\n\n # @return [Array<String>, String, nil] List of environment files that should be used for the stack creation\n attribute :environment\n validates :environment, type: TypeGeneric.new(String)\n\n # @return [Hash, nil] Dictionary of parameters for the stack creation\n attribute :parameters\n validates :parameters, type: Hash\n\n # @return [:yes, :no, nil] Rollback stack creation\n attribute :rollback\n validates :rollback, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Maximum number of seconds to wait for the stack creation\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7233429551124573, "alphanum_fraction": 0.7377521395683289, "avg_line_length": 18.27777862548828, "blob_id": "b5239b778e267a0b4da5c5f184a9353d6a668505", "content_id": "3390e51f28ccfd9ed9f78218a70f25e7fae5121f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 347, "license_type": "permissive", "max_line_length": 66, "num_lines": 18, "path": "/lib/ansible/ruby/modules/custom/commands/shell.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# VALIDATED_CHECKSUM: joWp3ZYxGmVxwPkHwt/+g+Yloq9F0rXjFxjU2UOeLA8=\n\n# See LICENSE.txt for license\n\nrequire 'ansible/ruby/modules/free_form'\nrequire 'ansible/ruby/modules/generated/commands/shell'\n\nmodule Ansible\n module Ruby\n module Modules\n class Shell\n include FreeForm\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6663785576820374, "alphanum_fraction": 0.6663785576820374, "avg_line_length": 35.15625, "blob_id": "528bea6c7e4994bb51499a2fc53321c69177cf06", "content_id": "7dab21b87d2e0435290d4188ddf4a08538802c65", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1157, "license_type": "permissive", "max_line_length": 143, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage OpenStack Identity Groups. Groups can be created, deleted or updated. Only the I(description) value can be updated.\n class Os_group < Base\n # @return [String] Group name\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Group description\n attribute :description\n validates :description, type: String\n\n # @return [String, nil] Domain id to create the group in if the cloud supports domains.\n attribute :domain_id\n validates :domain_id, type: String\n\n # @return [:present, :absent, nil] Should the resource be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6753689050674438, "alphanum_fraction": 0.6799091696739197, "avg_line_length": 35.70833206176758, "blob_id": "d5b1e58659ca2a358bc45bdcc410fc46a34a77f0", "content_id": "90c2007ca5f549fcef3a76d7f39ff479778f6a09", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 881, "license_type": "permissive", "max_line_length": 155, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_guest_find.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Find the folder path(s) for a virtual machine by name or UUID\n class Vmware_guest_find < Base\n # @return [String, nil] Name of the VM to work with.,This is required if C(uuid) parameter is not supplied.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] UUID of the instance to manage if known, this is VMware's BIOS UUID.,This is required if C(name) parameter is not supplied.\n attribute :uuid\n validates :uuid, type: String\n\n # @return [Object, nil] Destination datacenter for the find operation.,Deprecated in 2.5, will be removed in 2.9 release.\n attribute :datacenter\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7112194895744324, "alphanum_fraction": 0.7118698954582214, "avg_line_length": 57.01886749267578, "blob_id": "6ca306c2112442ff87b9733f1a275a155be0a717", "content_id": "c714047c382a7b8f22aac4a0994f27e935afa1e3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3075, "license_type": "permissive", "max_line_length": 296, "num_lines": 53, "path": "/lib/ansible/ruby/modules/generated/net_tools/nios/nios_zone.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Adds and/or removes instances of DNS zone objects from Infoblox NIOS servers. This module manages NIOS C(zone_auth) objects using the Infoblox WAPI interface over REST.\n class Nios_zone < Base\n # @return [Object] Specifies the qualified domain name to either add or remove from the NIOS instance based on the configured C(state) value.\n attribute :fqdn\n validates :fqdn, presence: true\n\n # @return [String] Configures the DNS view name for the configured resource. The specified DNS zone must already exist on the running NIOS instance prior to configuring zones.\n attribute :view\n validates :view, presence: true, type: String\n\n # @return [Array<Hash>, Hash, nil] Configures the grid primary servers for this zone.\n attribute :grid_primary\n validates :grid_primary, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash, nil] Configures the grid secondary servers for this zone.\n attribute :grid_secondaries\n validates :grid_secondaries, type: TypeGeneric.new(Hash)\n\n # @return [String, nil] Configures the name server group for this zone. Name server group is mutually exclusive with grid primary and grid secondaries.\n attribute :ns_group\n validates :ns_group, type: String\n\n # @return [Symbol, nil] If set to true, causes the NIOS DNS service to restart and load the new zone configuration\n attribute :restart_if_needed\n validates :restart_if_needed, type: Symbol\n\n # @return [String, nil] Create an authorative Reverse-Mapping Zone which is an area of network space for which one or more name servers-primary and secondary-have the responsibility to respond to address-to-name queries. It supports reverse-mapping zones for both IPv4 and IPv6 addresses.\n attribute :zone_format\n validates :zone_format, type: String\n\n # @return [Hash, nil] Allows for the configuration of Extensible Attributes on the instance of the object. This argument accepts a set of key / value pairs for configuration.\n attribute :extattrs\n validates :extattrs, type: Hash\n\n # @return [String, nil] Configures a text string comment to be associated with the instance of this object. The provided text string will be configured on the object instance.\n attribute :comment\n validates :comment, type: String\n\n # @return [:present, :absent, nil] Configures the intended state of the instance of the object on the NIOS server. When this value is set to C(present), the object is configured on the device and when this value is set to C(absent) the value is removed (if necessary) from the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7341471910476685, "alphanum_fraction": 0.7355035543441772, "avg_line_length": 97.30000305175781, "blob_id": "76460b8c3e0030c2ef2fdf38af9285cdb07e1a6b", "content_id": "ba675f7fe3c9bde3b608e8fcc33cc739c899dc9c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2949, "license_type": "permissive", "max_line_length": 539, "num_lines": 30, "path": "/lib/ansible/ruby/modules/generated/network/netconf/netconf_get.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # NETCONF is a network management protocol developed and standardized by the IETF. It is documented in RFC 6241.\n # This module allows the user to fetch configuration and state data from NETCONF enabled network devices.\n class Netconf_get < Base\n # @return [:running, :candidate, :startup, nil] This argument specifies the datastore from which configuration data should be fetched. Valid values are I(running), I(candidate) and I(startup). If the C(source) value is not set both configuration and state information are returned in response from running datastore.\n attribute :source\n validates :source, expression_inclusion: {:in=>[:running, :candidate, :startup], :message=>\"%{value} needs to be :running, :candidate, :startup\"}, allow_nil: true\n\n # @return [String, nil] This argument specifies the XML string which acts as a filter to restrict the portions of the data to be are retrieved from the remote device. If this option is not specified entire configuration or state data is returned in result depending on the value of C(source) option. The C(filter) value can be either XML string or XPath, if the filter is in XPath format the NETCONF server running on remote host should support xpath capability else it will result in an error.\n attribute :filter\n validates :filter, type: String\n\n # @return [:json, :pretty, :xml, nil] Encoding scheme to use when serializing output from the device. The option I(json) will serialize the output as JSON data. If the option value is I(json) it requires jxmlease to be installed on control node. The option I(pretty) is similar to received XML response but is using human readable format (spaces, new lines). The option value I(xml) is similar to received XML response but removes all XML namespaces.\n attribute :display\n validates :display, expression_inclusion: {:in=>[:json, :pretty, :xml], :message=>\"%{value} needs to be :json, :pretty, :xml\"}, allow_nil: true\n\n # @return [:never, :always, :\"if-supported\", nil] Instructs the module to explicitly lock the datastore specified as C(source). If no I(source) is defined, the I(running) datastore will be locked. By setting the option value I(always) is will explicitly lock the datastore mentioned in C(source) option. By setting the option value I(never) it will not lock the C(source) datastore. The value I(if-supported) allows better interworking with NETCONF servers, which do not support the (un)lock operation for all supported datastores.\n attribute :lock\n validates :lock, expression_inclusion: {:in=>[:never, :always, :\"if-supported\"], :message=>\"%{value} needs to be :never, :always, :\\\"if-supported\\\"\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6738989353179932, "alphanum_fraction": 0.6738989353179932, "avg_line_length": 46.5076904296875, "blob_id": "a94d71f7882a8fff5c74072ed38097d749e4025d", "content_id": "281f482f0fc84cfc22b93eebdb49d38fc9c2a605", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3088, "license_type": "permissive", "max_line_length": 370, "num_lines": 65, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_interface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creating / deleting and modifying the LIF.\n class Na_ontap_interface < Base\n # @return [:present, :absent, nil] Whether the specified interface should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] Specifies the logical interface (LIF) name.\n attribute :interface_name\n validates :interface_name, presence: true, type: String\n\n # @return [String, nil] Specifies the LIF's home node.,Required when C(state=present).\n attribute :home_node\n validates :home_node, type: String\n\n # @return [String, nil] Specifies the LIF's home port.,Required when C(state=present)\n attribute :home_port\n validates :home_port, type: String\n\n # @return [String, nil] Specifies the role of the LIF.,Required when C(state=present).\n attribute :role\n validates :role, type: String\n\n # @return [String, nil] Specifies the LIF's IP address.,Required when C(state=present)\n attribute :address\n validates :address, type: String\n\n # @return [String, nil] Specifies the LIF's netmask.,Required when C(state=present).\n attribute :netmask\n validates :netmask, type: String\n\n # @return [String] The name of the vserver to use.\n attribute :vserver\n validates :vserver, presence: true, type: String\n\n # @return [String, nil] Specifies the firewall policy for the LIF.\n attribute :firewall_policy\n validates :firewall_policy, type: String\n\n # @return [String, nil] Specifies the failover policy for the LIF.\n attribute :failover_policy\n validates :failover_policy, type: String\n\n # @return [:up, :down, nil] Specifies the administrative status of the LIF.\n attribute :admin_status\n validates :admin_status, expression_inclusion: {:in=>[:up, :down], :message=>\"%{value} needs to be :up, :down\"}, allow_nil: true\n\n # @return [Boolean, nil] If true, data LIF will revert to its home node under certain circumstances such as startup, and load balancing migration capability is disabled automatically\n attribute :is_auto_revert\n validates :is_auto_revert, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] Specifies the list of data protocols configured on the LIF. By default, the values in this element are nfs, cifs and fcache. Other supported protocols are iscsi and fcp. A LIF can be configured to not support any data protocols by specifying 'none'. Protocol values of none, iscsi or fcp can't be combined with any other data protocol(s).\n attribute :protocols\n validates :protocols, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6696282625198364, "alphanum_fraction": 0.6783960461616516, "avg_line_length": 67.43199920654297, "blob_id": "d0ddde80c38c3496a907afce58315c71024d7d4a", "content_id": "6d7c2e731f9b94ce4ad6a3850abe0b12245b3fab", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 8554, "license_type": "permissive", "max_line_length": 309, "num_lines": 125, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_bgp_neighbor.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages BGP peer configurations on HUAWEI CloudEngine switches.\n class Ce_bgp_neighbor < Base\n # @return [:present, :absent, nil] Specify desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object] Name of a BGP instance. The name is a case-sensitive string of characters. The BGP instance can be used only after the corresponding VPN instance is created.\n attribute :vrf_name\n validates :vrf_name, presence: true\n\n # @return [Object] Connection address of a peer, which can be an IPv4 or IPv6 address.\n attribute :peer_addr\n validates :peer_addr, presence: true\n\n # @return [Object] AS number of a peer. The value is a string of 1 to 11 characters.\n attribute :remote_as\n validates :remote_as, presence: true\n\n # @return [Object, nil] Description of a peer, which can be letters or digits. The value is a string of 1 to 80 characters.\n attribute :description\n\n # @return [Object, nil] Fake AS number that is specified for a local peer. The value is a string of 1 to 11 characters.\n attribute :fake_as\n\n # @return [:no_use, :true, :false, nil] If the value is true, the EBGP peer can use either a fake AS number or the actual AS number. If the value is false, the EBGP peer can only use a fake AS number.\n attribute :dual_as\n validates :dual_as, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, the router has all extended capabilities. If the value is false, the router does not have all extended capabilities.\n attribute :conventional\n validates :conventional, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, BGP is enabled to advertise REFRESH packets. If the value is false, the route refresh function is enabled.\n attribute :route_refresh\n validates :route_refresh, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, the session with a specified peer is torn down and all related routing entries are cleared. If the value is false, the session with a specified peer is retained.\n attribute :is_ignore\n validates :is_ignore, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [Object, nil] Name of a source interface that sends BGP packets. The value is a string of 1 to 63 characters.\n attribute :local_if_name\n\n # @return [Object, nil] Maximum number of hops in an indirect EBGP connection. The value is an ranging from 1 to 255.\n attribute :ebgp_max_hop\n\n # @return [Object, nil] Enable GTSM on a peer or peer group. The valid-TTL-Value parameter is used to specify the number of TTL hops to be detected. The value is an integer ranging from 1 to 255.\n attribute :valid_ttl_hops\n\n # @return [Object, nil] The value can be Connect-only, Listen-only, or Both.\n attribute :connect_mode\n\n # @return [:no_use, :true, :false, nil] If the value is true, BGP is enabled to record peer session status and event information. If the value is false, BGP is disabled from recording peer session status and event information.\n attribute :is_log_change\n validates :is_log_change, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:null, :cipher, :simple, nil] Enable BGP peers to establish a TCP connection and perform the Message Digest 5 (MD5) authentication for BGP messages.\n attribute :pswd_type\n validates :pswd_type, expression_inclusion: {:in=>[:null, :cipher, :simple], :message=>\"%{value} needs to be :null, :cipher, :simple\"}, allow_nil: true\n\n # @return [Object, nil] The character string in a password identifies the contents of the password, spaces not supported. The value is a string of 1 to 255 characters.\n attribute :pswd_cipher_text\n\n # @return [Object, nil] Specify the Keepalive time of a peer or peer group. The value is an integer ranging from 0 to 21845. The default value is 60.\n attribute :keep_alive_time\n\n # @return [Object, nil] Specify the Hold time of a peer or peer group. The value is 0 or an integer ranging from 3 to 65535.\n attribute :hold_time\n\n # @return [Object, nil] Specify the Min hold time of a peer or peer group.\n attribute :min_hold_time\n\n # @return [Object, nil] Specify the Keychain authentication name used when BGP peers establish a TCP connection. The value is a string of 1 to 47 case-insensitive characters.\n attribute :key_chain_name\n\n # @return [Object, nil] ConnectRetry interval. The value is an integer ranging from 1 to 65535.\n attribute :conn_retry_time\n\n # @return [Object, nil] Maximum TCP MSS value used for TCP connection establishment for a peer. The value is an integer ranging from 176 to 4096.\n attribute :tcp_MSS\n\n # @return [:no_use, :true, :false, nil] If the value is true, peer create MPLS Local IFNET disable. If the value is false, peer create MPLS Local IFNET enable.\n attribute :mpls_local_ifnet_disable\n validates :mpls_local_ifnet_disable, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] Add the global AS number to the Update packets to be advertised.\n attribute :prepend_global_as\n validates :prepend_global_as, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] Add the Fake AS number to received Update packets.\n attribute :prepend_fake_as\n validates :prepend_fake_as, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, peers are enabled to inherit the BFD function from the peer group. If the value is false, peers are disabled to inherit the BFD function from the peer group.\n attribute :is_bfd_block\n validates :is_bfd_block, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [Object, nil] Specify the detection multiplier. The default value is 3. The value is an integer ranging from 3 to 50.\n attribute :multiplier\n\n # @return [:no_use, :true, :false, nil] If the value is true, BFD is enabled. If the value is false, BFD is disabled.\n attribute :is_bfd_enable\n validates :is_bfd_enable, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [Object, nil] Specify the minimum interval at which BFD packets are received. The value is an integer ranging from 50 to 1000, in milliseconds.\n attribute :rx_interval\n\n # @return [Object, nil] Specify the minimum interval at which BFD packets are sent. The value is an integer ranging from 50 to 1000, in milliseconds.\n attribute :tx_interval\n\n # @return [:no_use, :true, :false, nil] If the value is true, the system is enabled to preferentially use the single-hop mode for BFD session setup between IBGP peers. If the value is false, the system is disabled from preferentially using the single-hop mode for BFD session setup between IBGP peers.\n attribute :is_single_hop\n validates :is_single_hop, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7371134161949158, "alphanum_fraction": 0.7375099062919617, "avg_line_length": 77.8125, "blob_id": "292df6b5199f17a054f0bf2d18667648aceef812", "content_id": "fc2ad69b83c5095a2daab5a03b34f497b21669d0", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2522, "license_type": "permissive", "max_line_length": 844, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_iapp_template.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages TCL iApp templates on a BIG-IP. This module will allow you to deploy iApp templates to the BIG-IP and manage their lifecycle. The conventional way to use this module is to import new iApps as needed or by extracting the contents of the iApp archive that is provided at downloads.f5.com and then importing all the iApps with this module. This module can also update existing iApps provided that the source of the iApp changed while the name stayed the same. Note however that this module will not reconfigure any services that may have been created using the C(bigip_iapp_service) module. iApps are normally not updated in production. Instead, new versions are deployed and then existing services are changed to consume that new template. As such, the ability to update templates in-place requires the C(force) option to be used.\n class Bigip_iapp_template < Base\n # @return [Symbol, nil] Specifies whether or not to force the uploading of an iApp. When C(yes), will force update the iApp even if there are iApp services using it. This will not update the running service though. Use C(bigip_iapp_service) to do that. When C(no), will update the iApp only if there are no iApp services using the template.\n attribute :force\n validates :force, type: Symbol\n\n # @return [Object, nil] The name of the iApp template that you want to delete. This option is only available when specifying a C(state) of C(absent) and is provided as a way to delete templates that you may no longer have the source of.\n attribute :name\n\n # @return [String, nil] Sets the contents of an iApp template directly to the specified value. This is for simple values, but can be used with lookup plugins for anything complex or with formatting. C(content) must be provided when creating new templates.\n attribute :content\n validates :content, type: String\n\n # @return [:present, :absent, nil] Whether the iApp template should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7220660448074341, "alphanum_fraction": 0.7248769998550415, "avg_line_length": 68.41463470458984, "blob_id": "3952465517e629369ac3adac3e4d3659803c642c", "content_id": "9b923c036ad017b727bc4641e24f4ae4c7314eb4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2846, "license_type": "permissive", "max_line_length": 374, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/windows/win_domain_computer.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, read, update and delete computers in Active Directory using a windows bridge computer to launch New-ADComputer, Get-ADComputer, Set-ADComputer, Remove-ADComputer and Move-ADObject powershell commands.\n class Win_domain_computer < Base\n # @return [String] Specifies the name of the object. This parameter sets the Name property of the Active Directory object. The LDAP display name (ldapDisplayName) of this property is name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Specifies the Security Account Manager (SAM) account name of the computer. It maximum is 256 characters, 15 is advised for older operating systems compatibility. The LDAP display name (ldapDisplayName) for this property is sAMAccountName. If ommitted the value is the same as C(name). Note. All computer SAMAccountNames needs to end with a $.\n attribute :sam_account_name\n validates :sam_account_name, type: String\n\n # @return [:yes, :no, nil] Specifies if an account is enabled. An enabled account requires a password. This parameter sets the Enabled property for an account object. This parameter also sets the ADS_UF_ACCOUNTDISABLE flag of the Active Directory User Account Control (UAC) attribute.\n attribute :enabled\n validates :enabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] Specifies the X.500 path of the Organizational Unit (OU) or container where the new object is created. Required when I(state=present).\n attribute :ou\n validates :ou, type: TypeGeneric.new(String)\n\n # @return [String, nil] Specifies a description of the object. This parameter sets the value of the Description property for the object. The LDAP display name (ldapDisplayName) for this property is description.\n attribute :description\n validates :description, type: String\n\n # @return [String, nil] Specifies the fully qualified domain name (FQDN) of the computer. This parameter sets the DNSHostName property for a computer object. The LDAP display name for this property is dNSHostName. Required when I(state=present).\n attribute :dns_hostname\n validates :dns_hostname, type: String\n\n # @return [:present, :absent, nil] Specified whether the computer should be C(present) or C(absent) in Active Directory.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6890278458595276, "alphanum_fraction": 0.6915861368179321, "avg_line_length": 49.25714111328125, "blob_id": "38fb4ea4e7fe50b50039660a8bdef4affe5f71b5", "content_id": "69d4b1dc35684f5effb6a39f5dd04bb694b2d02f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3518, "license_type": "permissive", "max_line_length": 310, "num_lines": 70, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ecs_service.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates or terminates ecs services.\n class Ecs_service < Base\n # @return [:present, :absent, :deleting] The desired state of the service\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent, :deleting], :message=>\"%{value} needs to be :present, :absent, :deleting\"}\n\n # @return [String] The name of the service\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The name of the cluster in which the service exists\n attribute :cluster\n validates :cluster, type: String\n\n # @return [String, nil] The task definition the service will run. This parameter is required when state=present\n attribute :task_definition\n validates :task_definition, type: String\n\n # @return [Object, nil] The list of ELBs defined for this service\n attribute :load_balancers\n\n # @return [Integer, nil] The count of how many instances of the service. This parameter is required when state=present\n attribute :desired_count\n validates :desired_count, type: Integer\n\n # @return [Object, nil] Unique, case-sensitive identifier you provide to ensure the idempotency of the request. Up to 32 ASCII characters are allowed.\n attribute :client_token\n\n # @return [Object, nil] The name or full Amazon Resource Name (ARN) of the IAM role that allows your Amazon ECS container agent to make calls to your load balancer on your behalf. This parameter is only required if you are using a load balancer with your service, in a network mode other than `awsvpc`.\n attribute :role\n\n # @return [Integer, nil] The time to wait before checking that the service is available\n attribute :delay\n validates :delay, type: Integer\n\n # @return [Integer, nil] The number of times to check that the service is available\n attribute :repeat\n validates :repeat, type: Integer\n\n # @return [Hash, nil] Optional parameters that control the deployment_configuration; format is '{\"maximum_percent\":<integer>, \"minimum_healthy_percent\":<integer>}\n attribute :deployment_configuration\n validates :deployment_configuration, type: Hash\n\n # @return [Array<Hash>, Hash, nil] The placement constraints for the tasks in the service\n attribute :placement_constraints\n validates :placement_constraints, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash, nil] The placement strategy objects to use for tasks in your service. You can specify a maximum of 5 strategy rules per service\n attribute :placement_strategy\n validates :placement_strategy, type: TypeGeneric.new(Hash)\n\n # @return [Hash, nil] network configuration of the service. Only applicable for task definitions created with C(awsvpc) I(network_mode).,assign_public_ip requires botocore >= 1.8.4\n attribute :network_configuration\n validates :network_configuration, type: Hash\n\n # @return [:EC2, :FARGATE, nil] The launch type on which to run your service\n attribute :launch_type\n validates :launch_type, expression_inclusion: {:in=>[:EC2, :FARGATE], :message=>\"%{value} needs to be :EC2, :FARGATE\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6554455161094666, "alphanum_fraction": 0.6554455161094666, "avg_line_length": 33.82758712768555, "blob_id": "afb48c7b79bf67d024f00839afc6204056aec26b", "content_id": "58a7f70e3b541d5c294b1c41f3439fbeefca4de6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1010, "license_type": "permissive", "max_line_length": 143, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/storage/infinidat/infini_fs.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module creates, deletes or modifies filesystems on Infinibox.\n class Infini_fs < Base\n # @return [String] File system name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Creates/Modifies file system when present or removes when absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] File system size in MB, GB or TB units. See examples.\n attribute :size\n validates :size, type: String\n\n # @return [String] Pool that will host file system.\n attribute :pool\n validates :pool, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7011784315109253, "alphanum_fraction": 0.7011784315109253, "avg_line_length": 39.965518951416016, "blob_id": "b535fe2aefcd78ca9678a7c851a9c860f5214f78", "content_id": "7f22c3616777e93917a8dae33649e768c7bd3620", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1188, "license_type": "permissive", "max_line_length": 248, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_cdot_license.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove licenses on NetApp ONTAP.\n class Na_cdot_license < Base\n # @return [Symbol, nil] Remove licenses that have no controller affiliation in the cluster.\n attribute :remove_unused\n validates :remove_unused, type: Symbol\n\n # @return [Symbol, nil] Remove licenses that have expired in the cluster.\n attribute :remove_expired\n validates :remove_expired, type: Symbol\n\n # @return [NilClass, nil] Serial number of the node associated with the license.,This parameter is used primarily when removing license for a specific service.,If this parameter is not provided, the cluster serial number is used by default.\n attribute :serial_number\n validates :serial_number, type: NilClass\n\n # @return [Hash, nil] List of licenses to add or remove.,Please note that trying to remove a non-existent license will throw an error.\n attribute :licenses\n validates :licenses, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.696753740310669, "alphanum_fraction": 0.6999208331108093, "avg_line_length": 42.55172348022461, "blob_id": "c2c689531916896323264c0fb51865e9915b8f87", "content_id": "0924b9ef30b912a2218ca5696a62e6b09898364f", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1263, "license_type": "permissive", "max_line_length": 224, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_wait.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # You can wait for BIG-IP to be \"ready\". By \"ready\", we mean that BIG-IP is ready to accept configuration.\n # This module can take into account situations where the device is in the middle of rebooting due to a configuration change.\n class Bigip_wait < Base\n # @return [Integer, nil] Maximum number of seconds to wait for.,When used without other conditions it is equivalent of just sleeping.,The default timeout is deliberately set to 2 hours because no individual REST API.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [Integer, nil] Number of seconds to wait before starting to poll.\n attribute :delay\n validates :delay, type: Integer\n\n # @return [Integer, nil] Number of seconds to sleep between checks, before 2.3 this was hardcoded to 1 second.\n attribute :sleep\n validates :sleep, type: Integer\n\n # @return [Object, nil] This overrides the normal error message from a failure to meet the required conditions.\n attribute :msg\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7061855792999268, "alphanum_fraction": 0.7074742317199707, "avg_line_length": 39.842105865478516, "blob_id": "8f5c13ac1c73894c6c18af3f94d9ec7c85c141a9", "content_id": "fe939264006e5e8f4e248465181b5feb2a103104", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 776, "license_type": "permissive", "max_line_length": 192, "num_lines": 19, "path": "/lib/ansible/ruby/modules/generated/windows/win_webpicmd.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Installs packages using Web Platform Installer command-line (U(http://www.iis.net/learn/install/web-platform-installer/web-platform-installer-v4-command-line-webpicmdexe-rtw-release)).\n # Must be installed and present in PATH (see M(win_chocolatey) module; 'webpicmd' is the package name, and you must install 'lessmsi' first too)?\n # Install IIS first (see M(win_feature) module).\n class Win_webpicmd < Base\n # @return [Object] Name of the package to be installed.\n attribute :name\n validates :name, presence: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6571224331855774, "alphanum_fraction": 0.6592698693275452, "avg_line_length": 36.75675582885742, "blob_id": "c39f73b7b9950f385aa6b4612293afb578390719", "content_id": "a9e2d60c64fa7283ae759e198490f56f949818d5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1397, "license_type": "permissive", "max_line_length": 172, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/notification/nexmo.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Send a SMS message via nexmo\n class Nexmo < Base\n # @return [String] Nexmo API Key\n attribute :api_key\n validates :api_key, presence: true, type: String\n\n # @return [String] Nexmo API Secret\n attribute :api_secret\n validates :api_secret, presence: true, type: String\n\n # @return [Integer] Nexmo Number to send from\n attribute :src\n validates :src, presence: true, type: Integer\n\n # @return [Array<Integer>, Integer] Phone number(s) to send SMS message to\n attribute :dest\n validates :dest, presence: true, type: TypeGeneric.new(Integer)\n\n # @return [String] Message to text to send. Messages longer than 160 characters will be split into multiple messages\n attribute :msg\n validates :msg, presence: true, type: String\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.4658018946647644, "alphanum_fraction": 0.4870283007621765, "avg_line_length": 21.91891860961914, "blob_id": "0cf168c1208a0222e74ae7c170b039ed5650da2c", "content_id": "0038d218d968d9597b95870012ee9ad7548d06ec", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 848, "license_type": "permissive", "max_line_length": 122, "num_lines": 37, "path": "/lib/ansible/ruby/modules/custom/utilities/logic/set_fact_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# see LICENSE.txt in project root\nrequire 'spec_helper'\n\ndescribe Ansible::Ruby::Modules::Set_fact do\n subject(:mod) do\n Ansible::Ruby::Modules::Set_fact.new free_form: { stuff: 123,\n howdy: 456 }\n end\n\n describe '#to_h' do\n subject { mod.to_h }\n\n it do\n is_expected.to eq set_fact: {\n stuff: 123,\n howdy: 456\n }\n end\n\n context 'jinja' do\n subject do\n mod = Ansible::Ruby::Modules::Set_fact.new free_form: { stuff: 123,\n howdy: Ansible::Ruby::Models::JinjaExpression.new('foo') }\n mod.to_h\n end\n\n it do\n is_expected.to eq set_fact: {\n stuff: 123,\n howdy: '{{ foo }}'\n }\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6727005839347839, "alphanum_fraction": 0.6727005839347839, "avg_line_length": 45.45454406738281, "blob_id": "4510f10e8556e3f90f0c936a537513bed251aae4", "content_id": "58d04252c5a182149f308940fa581517efd4a37c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2044, "license_type": "permissive", "max_line_length": 423, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/cloud/opennebula/one_host.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages OpenNebula Hosts\n class One_host < Base\n # @return [String] Hostname of the machine to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, :enabled, :disabled, :offline, nil] Takes the host to the desired lifecycle state.,If C(absent) the host will be deleted from the cluster.,If C(present) the host will be created in the cluster (includes C(enabled), C(disabled) and C(offline) states).,If C(enabled) the host is fully operational.,C(disabled), e.g. to perform maintenance operations.,C(offline), host is totally offline.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :enabled, :disabled, :offline], :message=>\"%{value} needs to be :absent, :present, :enabled, :disabled, :offline\"}, allow_nil: true\n\n # @return [String, nil] The name of the information manager, this values are taken from the oned.conf with the tag name IM_MAD (name)\n attribute :im_mad_name\n validates :im_mad_name, type: String\n\n # @return [String, nil] The name of the virtual machine manager mad name, this values are taken from the oned.conf with the tag name VM_MAD (name)\n attribute :vmm_mad_name\n validates :vmm_mad_name, type: String\n\n # @return [Integer, nil] The cluster ID.\n attribute :cluster_id\n validates :cluster_id, type: Integer\n\n # @return [String, nil] The cluster specified by name.\n attribute :cluster_name\n validates :cluster_name, type: String\n\n # @return [Object, nil] The labels for this host.\n attribute :labels\n\n # @return [Hash, nil] The template or attribute changes to merge into the host template.\n attribute :template\n validates :template, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6508504748344421, "alphanum_fraction": 0.6508504748344421, "avg_line_length": 33.90625, "blob_id": "2cd634a4f86248a50d2260e579d0499f705dec46", "content_id": "cdc6ceeb3b0c53473ccc0bcf17ebc10322a9833f", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1117, "license_type": "permissive", "max_line_length": 143, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_qtree.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or destroy Qtrees.\n class Na_ontap_qtree < Base\n # @return [:present, :absent, nil] Whether the specified qtree should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The name of the qtree to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Name of the qtree to be renamed.\n attribute :from_name\n\n # @return [String, nil] The name of the FlexVol the qtree should exist on. Required when C(state=present).\n attribute :flexvol_name\n validates :flexvol_name, type: String\n\n # @return [String] The name of the vserver to use.\n attribute :vserver\n validates :vserver, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7125974893569946, "alphanum_fraction": 0.7225242257118225, "avg_line_length": 78.83018493652344, "blob_id": "c92774b471399649dbb8df04dfde8e3f8495f4d3", "content_id": "db2391411938d32c652df1ccbc62c32b7f80f2ad", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4231, "license_type": "permissive", "max_line_length": 402, "num_lines": 53, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_nxapi.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configures the NXAPI feature on devices running Cisco NXOS. The NXAPI feature is absent from the configuration by default. Since this module manages the NXAPI feature it only supports the use of the C(Cli) transport.\n class Nxos_nxapi < Base\n # @return [Integer, nil] Configure the port with which the HTTP server will listen on for requests. By default, NXAPI will bind the HTTP service to the standard HTTP port 80. This argument accepts valid port values in the range of 1 to 65535.\n attribute :http_port\n validates :http_port, type: Integer\n\n # @return [Boolean, nil] Controls the operating state of the HTTP protocol as one of the underlying transports for NXAPI. By default, NXAPI will enable the HTTP transport when the feature is first configured. To disable the use of the HTTP transport, set the value of this argument to False.\n attribute :http\n validates :http, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Integer, nil] Configure the port with which the HTTPS server will listen on for requests. By default, NXAPI will bind the HTTPS service to the standard HTTPS port 443. This argument accepts valid port values in the range of 1 to 65535.\n attribute :https_port\n validates :https_port, type: Integer\n\n # @return [Symbol, nil] Controls the operating state of the HTTPS protocol as one of the underlying transports for NXAPI. By default, NXAPI will disable the HTTPS transport when the feature is first configured. To enable the use of the HTTPS transport, set the value of this argument to True.\n attribute :https\n validates :https, type: Symbol\n\n # @return [Symbol, nil] The NXAPI feature provides a web base UI for developers for entering commands. This feature is initially disabled when the NXAPI feature is configured for the first time. When the C(sandbox) argument is set to True, the developer sandbox URL will accept requests and when the value is set to False, the sandbox URL is unavailable. This is supported on NX-OS 7K series.\n attribute :sandbox\n validates :sandbox, type: Symbol\n\n # @return [:present, :absent, nil] The C(state) argument controls whether or not the NXAPI feature is configured on the remote device. When the value is C(present) the NXAPI feature configuration is present in the device running-config. When the values is C(absent) the feature configuration is removed from the running-config.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Symbol, nil] Controls the use of whether strong or weak ciphers are configured. By default, this feature is disabled and weak ciphers are configured. To enable the use of strong ciphers, set the value of this argument to True.\n attribute :ssl_strong_ciphers\n validates :ssl_strong_ciphers, type: Symbol\n\n # @return [Boolean, nil] Controls the use of the Transport Layer Security version 1.0 is configured. By default, this feature is enabled. To disable the use of TLSV1.0, set the value of this argument to True.\n attribute :tlsv1_0\n validates :tlsv1_0, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Symbol, nil] Controls the use of the Transport Layer Security version 1.1 is configured. By default, this feature is disabled. To enable the use of TLSV1.1, set the value of this argument to True.\n attribute :tlsv1_1\n validates :tlsv1_1, type: Symbol\n\n # @return [Symbol, nil] Controls the use of the Transport Layer Security version 1.2 is configured. By default, this feature is disabled. To enable the use of TLSV1.2, set the value of this argument to True.\n attribute :tlsv1_2\n validates :tlsv1_2, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6646616458892822, "alphanum_fraction": 0.6646616458892822, "avg_line_length": 44.34090805053711, "blob_id": "cab0603789b99d619e0499364ab07977df39a710", "content_id": "3945f19d8d4033354e9fe5a4916ed2d30fea5991", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1995, "license_type": "permissive", "max_line_length": 166, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_alertscriptconfig.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure AlertScriptConfig object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_alertscriptconfig < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [String, nil] User defined alert action script.,Please refer to kb.avinetworks.com for more information.\n attribute :action_script\n validates :action_script, type: String\n\n # @return [String] A user-friendly name of the script.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] It is a reference to an object of type tenant.\n attribute :tenant_ref\n validates :tenant_ref, type: String\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Unique object identifier of the object.\n attribute :uuid\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6529064774513245, "alphanum_fraction": 0.6529064774513245, "avg_line_length": 41.39285659790039, "blob_id": "b4c6601602ca47ec6ccf02611b83fa562e307eca", "content_id": "131a7a2080e45f1a40d3bce47c1dfa356b7f4432", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2374, "license_type": "permissive", "max_line_length": 225, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, disable, lock, enable and remove users.\n class Cs_user < Base\n # @return [String] Username of the user.\n attribute :username\n validates :username, presence: true, type: String\n\n # @return [String, nil] Account the user will be created under.,Required on C(state=present).\n attribute :account\n validates :account, type: String\n\n # @return [String, nil] Password of the user to be created.,Required on C(state=present).,Only considered on creation and will not be updated if user exists.\n attribute :password\n validates :password, type: String\n\n # @return [String, nil] First name of the user.,Required on C(state=present).\n attribute :first_name\n validates :first_name, type: String\n\n # @return [String, nil] Last name of the user.,Required on C(state=present).\n attribute :last_name\n validates :last_name, type: String\n\n # @return [String, nil] Email of the user.,Required on C(state=present).\n attribute :email\n validates :email, type: String\n\n # @return [Object, nil] Timezone of the user.\n attribute :timezone\n\n # @return [Symbol, nil] If API keys of the user should be generated.,Note: Keys can not be removed by the API again.\n attribute :keys_registered\n validates :keys_registered, type: Symbol\n\n # @return [String, nil] Domain the user is related to.\n attribute :domain\n validates :domain, type: String\n\n # @return [:present, :absent, :enabled, :disabled, :locked, :unlocked, nil] State of the user.,C(unlocked) is an alias for C(enabled).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :enabled, :disabled, :locked, :unlocked], :message=>\"%{value} needs to be :present, :absent, :enabled, :disabled, :locked, :unlocked\"}, allow_nil: true\n\n # @return [Boolean, nil] Poll async jobs until job has finished.\n attribute :poll_async\n validates :poll_async, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6216860413551331, "alphanum_fraction": 0.6529639363288879, "avg_line_length": 62.339622497558594, "blob_id": "ee640c49e1994d8eedbe45c4860fda7291e31adb", "content_id": "887f2e218109dcf036169e522782ae9540930e93", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3357, "license_type": "permissive", "max_line_length": 416, "num_lines": 53, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_contract_subject.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage initial Contract Subjects on Cisco ACI fabrics.\n class Aci_contract_subject < Base\n # @return [String, nil] The name of the tenant.\n attribute :tenant\n validates :tenant, type: String\n\n # @return [String, nil] The contract subject name.\n attribute :subject\n validates :subject, type: String\n\n # @return [String, nil] The name of the Contract.\n attribute :contract\n validates :contract, type: String\n\n # @return [Symbol, nil] Determines if the APIC should reverse the src and dst ports to allow the return traffic back, since ACI is stateless filter.,The APIC defaults to C(yes) when unset during creation.\n attribute :reverse_filter\n validates :reverse_filter, type: Symbol\n\n # @return [:level1, :level2, :level3, :unspecified, nil] The QoS class.,The APIC defaults to C(unspecified) when unset during creation.\n attribute :priority\n validates :priority, expression_inclusion: {:in=>[:level1, :level2, :level3, :unspecified], :message=>\"%{value} needs to be :level1, :level2, :level3, :unspecified\"}, allow_nil: true\n\n # @return [:AF11, :AF12, :AF13, :AF21, :AF22, :AF23, :AF31, :AF32, :AF33, :AF41, :AF42, :AF43, :CS0, :CS1, :CS2, :CS3, :CS4, :CS5, :CS6, :CS7, :EF, :VA, :unspecified, nil] The target DSCP.,The APIC defaults to C(unspecified) when unset during creation.\n attribute :dscp\n validates :dscp, expression_inclusion: {:in=>[:AF11, :AF12, :AF13, :AF21, :AF22, :AF23, :AF31, :AF32, :AF33, :AF41, :AF42, :AF43, :CS0, :CS1, :CS2, :CS3, :CS4, :CS5, :CS6, :CS7, :EF, :VA, :unspecified], :message=>\"%{value} needs to be :AF11, :AF12, :AF13, :AF21, :AF22, :AF23, :AF31, :AF32, :AF33, :AF41, :AF42, :AF43, :CS0, :CS1, :CS2, :CS3, :CS4, :CS5, :CS6, :CS7, :EF, :VA, :unspecified\"}, allow_nil: true\n\n # @return [String, nil] Description for the contract subject.\n attribute :description\n validates :description, type: String\n\n # @return [:all, :at_least_one, :at_most_one, :none, nil] The match criteria across consumers.,The APIC defaults to C(at_least_one) when unset during creation.\n attribute :consumer_match\n validates :consumer_match, expression_inclusion: {:in=>[:all, :at_least_one, :at_most_one, :none], :message=>\"%{value} needs to be :all, :at_least_one, :at_most_one, :none\"}, allow_nil: true\n\n # @return [:all, :at_least_one, :at_most_one, :none, nil] The match criteria across providers.,The APIC defaults to C(at_least_one) when unset during creation.\n attribute :provider_match\n validates :provider_match, expression_inclusion: {:in=>[:all, :at_least_one, :at_most_one, :none], :message=>\"%{value} needs to be :all, :at_least_one, :at_most_one, :none\"}, allow_nil: true\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6654804348945618, "alphanum_fraction": 0.6797152757644653, "avg_line_length": 57.25609588623047, "blob_id": "2f7474d1cef4da997852b4a78d039f2db4c041e5", "content_id": "05f64497089f757ad66c460a75aaf72f8f1e0ba6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4777, "license_type": "permissive", "max_line_length": 299, "num_lines": 82, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_vrrp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages VRRP interface attributes on HUAWEI CloudEngine devices.\n class Ce_vrrp < Base\n # @return [Object, nil] Name of an interface. The value is a string of 1 to 63 characters.\n attribute :interface\n\n # @return [String, nil] VRRP backup group ID. The value is an integer ranging from 1 to 255.\n attribute :vrid\n validates :vrid, type: String\n\n # @return [Object, nil] Virtual IP address. The value is a string of 0 to 255 characters.\n attribute :virtual_ip\n\n # @return [:normal, :member, :admin, nil] Type of a VRRP backup group.\n attribute :vrrp_type\n validates :vrrp_type, expression_inclusion: {:in=>[:normal, :member, :admin], :message=>\"%{value} needs to be :normal, :member, :admin\"}, allow_nil: true\n\n # @return [:yes, :no, nil] mVRRP ignores an interface Down event.\n attribute :admin_ignore_if_down\n validates :admin_ignore_if_down, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Tracked mVRRP ID. The value is an integer ranging from 1 to 255.\n attribute :admin_vrid\n\n # @return [Object, nil] Tracked mVRRP interface name. The value is a string of 1 to 63 characters.\n attribute :admin_interface\n\n # @return [:yes, :no, nil] Disable the flowdown function for service VRRP.\n attribute :admin_flowdown\n validates :admin_flowdown, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Configured VRRP priority. The value ranges from 1 to 254. The default value is 100. A larger value indicates a higher priority.\n attribute :priority\n\n # @return [:v2, :v3, nil] VRRP version. The default version is v2.\n attribute :version\n validates :version, expression_inclusion: {:in=>[:v2, :v3], :message=>\"%{value} needs to be :v2, :v3\"}, allow_nil: true\n\n # @return [Object, nil] Configured interval between sending advertisements, in milliseconds. Only the master router sends VRRP advertisements. The default value is 1000 milliseconds.\n attribute :advertise_interval\n\n # @return [Object, nil] Preemption delay. The value is an integer ranging from 0 to 3600. The default value is 0.\n attribute :preempt_timer_delay\n\n # @return [Object, nil] Interval at which gratuitous ARP packets are sent, in seconds. The value ranges from 30 to 1200.The default value is 300.\n attribute :gratuitous_arp_interval\n\n # @return [Object, nil] Delay in recovering after an interface goes Up. The delay is used for interface flapping suppression. The value is an integer ranging from 0 to 3600. The default value is 0 seconds.\n attribute :recover_delay\n\n # @return [Object, nil] The configured holdMultiplier.The value is an integer ranging from 3 to 10. The default value is 3.\n attribute :holding_multiplier\n\n # @return [:simple, :md5, :none, nil] Authentication type used for VRRP packet exchanges between virtual routers. The values are noAuthentication, simpleTextPassword, md5Authentication. The default value is noAuthentication.\n attribute :auth_mode\n validates :auth_mode, expression_inclusion: {:in=>[:simple, :md5, :none], :message=>\"%{value} needs to be :simple, :md5, :none\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Select the display mode of an authentication key. By default, an authentication key is displayed in ciphertext.\n attribute :is_plain\n validates :is_plain, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] This object is set based on the authentication type. When noAuthentication is specified, the value is empty. When simpleTextPassword or md5Authentication is specified, the value is a string of 1 to 8 characters in plaintext and displayed as a blank text for security.\n attribute :auth_key\n\n # @return [:enable, :disable, nil] mVRRP's fast resume mode.\n attribute :fast_resume\n validates :fast_resume, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Specify desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6710351705551147, "alphanum_fraction": 0.6719186902046204, "avg_line_length": 60.73636245727539, "blob_id": "06761adf631aaf22b13dc56db6372a1c18624af9", "content_id": "262eaa7f05f00231723d876bbe71f8c9dc7fcebf", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6791, "license_type": "permissive", "max_line_length": 619, "num_lines": 110, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gce.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates or terminates Google Compute Engine (GCE) instances. See U(https://cloud.google.com/compute) for an overview. Full install/configuration instructions for the gce* modules can be found in the comments of ansible/test/gce_tests.py.\n class Gce < Base\n # @return [String, nil] image string to use for the instance (default will follow latest stable debian image)\n attribute :image\n validates :image, type: String\n\n # @return [String, nil] image family from which to select the image. The most recent non-deprecated image in the family will be used.\n attribute :image_family\n validates :image_family, type: String\n\n # @return [Array<String>, String, nil] A list of other projects (accessible with the provisioning credentials) to be searched for the image.\n attribute :external_projects\n validates :external_projects, type: TypeGeneric.new(String)\n\n # @return [String, nil] a comma-separated list of instance names to create or destroy\n attribute :instance_names\n validates :instance_names, type: String\n\n # @return [String, nil] machine type to use for the instance, use 'n1-standard-1' by default\n attribute :machine_type\n validates :machine_type, type: String\n\n # @return [Hash, nil] a hash/dictionary of custom data for the instance; '{\"key\":\"value\", ...}'\n attribute :metadata\n validates :metadata, type: Hash\n\n # @return [String, nil] service account email\n attribute :service_account_email\n validates :service_account_email, type: String\n\n # @return [:bigquery, :\"cloud-platform\", :\"compute-ro\", :\"compute-rw\", :\"useraccounts-ro\", :\"useraccounts-rw\", :datastore, :\"logging-write\", :monitoring, :\"sql-admin\", :\"storage-full\", :\"storage-ro\", :\"storage-rw\", :taskqueue, :\"userinfo-email\", nil] service account permissions (see U(https://cloud.google.com/sdk/gcloud/reference/compute/instances/create), --scopes section for detailed information)\n attribute :service_account_permissions\n validates :service_account_permissions, expression_inclusion: {:in=>[:bigquery, :\"cloud-platform\", :\"compute-ro\", :\"compute-rw\", :\"useraccounts-ro\", :\"useraccounts-rw\", :datastore, :\"logging-write\", :monitoring, :\"sql-admin\", :\"storage-full\", :\"storage-ro\", :\"storage-rw\", :taskqueue, :\"userinfo-email\"], :message=>\"%{value} needs to be :bigquery, :\\\"cloud-platform\\\", :\\\"compute-ro\\\", :\\\"compute-rw\\\", :\\\"useraccounts-ro\\\", :\\\"useraccounts-rw\\\", :datastore, :\\\"logging-write\\\", :monitoring, :\\\"sql-admin\\\", :\\\"storage-full\\\", :\\\"storage-ro\\\", :\\\"storage-rw\\\", :taskqueue, :\\\"userinfo-email\\\"\"}, allow_nil: true\n\n # @return [Object, nil] path to the pem file associated with the service account email This option is deprecated. Use 'credentials_file'.\n attribute :pem_file\n\n # @return [String, nil] path to the JSON file associated with the service account email\n attribute :credentials_file\n validates :credentials_file, type: String\n\n # @return [String, nil] your GCE project ID\n attribute :project_id\n validates :project_id, type: String\n\n # @return [Object, nil] either a name of a single instance or when used with 'num_instances', the base name of a cluster of nodes\n attribute :name\n\n # @return [Object, nil] can be used with 'name', specifies the number of nodes to provision using 'name' as a base name\n attribute :num_instances\n\n # @return [String, nil] name of the network, 'default' will be used if not specified\n attribute :network\n validates :network, type: String\n\n # @return [String, nil] name of the subnetwork in which the instance should be created\n attribute :subnetwork\n validates :subnetwork, type: String\n\n # @return [:yes, :no, nil] if set, create the instance with a persistent boot disk\n attribute :persistent_boot_disk\n validates :persistent_boot_disk, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash, nil] a list of persistent disks to attach to the instance; a string value gives the name of the disk; alternatively, a dictionary value can define 'name' and 'mode' ('READ_ONLY' or 'READ_WRITE'). The first entry will be the boot disk (which must be READ_WRITE).\n attribute :disks\n validates :disks, type: TypeGeneric.new(Hash)\n\n # @return [:active, :present, :absent, :deleted, :started, :stopped, :terminated, nil] desired state of the resource\n attribute :state\n validates :state, expression_inclusion: {:in=>[:active, :present, :absent, :deleted, :started, :stopped, :terminated], :message=>\"%{value} needs to be :active, :present, :absent, :deleted, :started, :stopped, :terminated\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] a comma-separated list of tags to associate with the instance\n attribute :tags\n validates :tags, type: TypeGeneric.new(String)\n\n # @return [String] the GCE zone to use. The list of available zones is at U(https://cloud.google.com/compute/docs/regions-zones/regions-zones#available).\n attribute :zone\n validates :zone, presence: true, type: String\n\n # @return [:yes, :no, nil] set to C(yes) if the instance can forward ip packets (useful for gateways)\n attribute :ip_forward\n validates :ip_forward, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] type of external ip, ephemeral by default; alternatively, a fixed gce ip or ip name can be given. Specify 'none' if no external ip is desired.\n attribute :external_ip\n validates :external_ip, type: String\n\n # @return [:yes, :no, nil] if set boot disk will be removed after instance destruction\n attribute :disk_auto_delete\n validates :disk_auto_delete, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] if set to C(yes), instances will be preemptible and time-limited. (requires libcloud >= 0.20.0)\n attribute :preemptible\n validates :preemptible, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] The size of the boot disk created for this instance (in GB)\n attribute :disk_size\n validates :disk_size, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6948623061180115, "alphanum_fraction": 0.6981832385063171, "avg_line_length": 61.42683029174805, "blob_id": "2660af4d1322431bde28f0485820dc1292b122ae", "content_id": "301cdb34496ad5792c7e3556c65d32496d697f61", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5119, "license_type": "permissive", "max_line_length": 303, "num_lines": 82, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/elb_application_lb.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage an AWS Application Elastic Load Balancer. See U(https://aws.amazon.com/blogs/aws/new-aws-application-load-balancer/) for details.\n class Elb_application_lb < Base\n # @return [Symbol, nil] Whether or not to enable access logs. When true, I(access_logs_s3_bucket) must be set.\n attribute :access_logs_enabled\n validates :access_logs_enabled, type: Symbol\n\n # @return [String, nil] The name of the S3 bucket for the access logs. This attribute is required if access logs in Amazon S3 are enabled. The bucket must exist in the same region as the load balancer and have a bucket policy that grants Elastic Load Balancing permission to write to the bucket.\n attribute :access_logs_s3_bucket\n validates :access_logs_s3_bucket, type: String\n\n # @return [String, nil] The prefix for the location in the S3 bucket. If you don't specify a prefix, the access logs are stored in the root of the bucket.\n attribute :access_logs_s3_prefix\n validates :access_logs_s3_prefix, type: String\n\n # @return [Symbol, nil] Indicates whether deletion protection for the ELB is enabled.\n attribute :deletion_protection\n validates :deletion_protection, type: Symbol\n\n # @return [Symbol, nil] Indicates whether to enable HTTP2 routing.\n attribute :http2\n validates :http2, type: Symbol\n\n # @return [Integer, nil] The number of seconds to wait before an idle connection is closed.\n attribute :idle_timeout\n validates :idle_timeout, type: Integer\n\n # @return [Array<Hash>, Hash, nil] A list of dicts containing listeners to attach to the ELB. See examples for detail of the dict required. Note that listener keys are CamelCased.\n attribute :listeners\n validates :listeners, type: TypeGeneric.new(Hash)\n\n # @return [String] The name of the load balancer. This name must be unique within your AWS account, can have a maximum of 32 characters, must contain only alphanumeric characters or hyphens, and must not begin or end with a hyphen.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Boolean, nil] If yes, existing listeners will be purged from the ELB to match exactly what is defined by I(listeners) parameter. If the I(listeners) parameter is not set then listeners will not be modified\n attribute :purge_listeners\n validates :purge_listeners, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] If yes, existing tags will be purged from the resource to match exactly what is defined by I(tags) parameter. If the I(tags) parameter is not set then tags will not be modified.\n attribute :purge_tags\n validates :purge_tags, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] A list of the IDs of the subnets to attach to the load balancer. You can specify only one subnet per Availability Zone. You must specify subnets from at least two Availability Zones. Required if state=present.\n attribute :subnets\n validates :subnets, type: TypeGeneric.new(String)\n\n # @return [Object, nil] A list of the names or IDs of the security groups to assign to the load balancer. Required if state=present.\n attribute :security_groups\n\n # @return [:\"internet-facing\", :internal, nil] Internet-facing or internal load balancer. An ELB scheme can not be modified after creation.\n attribute :scheme\n validates :scheme, expression_inclusion: {:in=>[:\"internet-facing\", :internal], :message=>\"%{value} needs to be :\\\"internet-facing\\\", :internal\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Create or destroy the load balancer.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] A dictionary of one or more tags to assign to the load balancer.\n attribute :tags\n\n # @return [Symbol, nil] Wait for the load balancer to have a state of 'active' before completing. A status check is performed every 15 seconds until a successful state is reached. An error is returned after 40 failed checks.\n attribute :wait\n validates :wait, type: Symbol\n\n # @return [Object, nil] The time in seconds to use in conjunction with I(wait).\n attribute :wait_timeout\n\n # @return [Boolean, nil] When set to no, keep the existing load balancer rules in place. Will modify and add, but will not delete.\n attribute :purge_rules\n validates :purge_rules, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6471579074859619, "alphanum_fraction": 0.6480000019073486, "avg_line_length": 41.41071319580078, "blob_id": "8a6e01c9bea802b917462c6c0e4f3cfac880da2c", "content_id": "ce87a5c81ca38c3f2aa0d055cdead6a61b05e263", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2375, "license_type": "permissive", "max_line_length": 251, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/database/misc/redis.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Unified utility to interact with redis instances.\n class Redis < Base\n # @return [:config, :flush, :slave] The selected redis command,C(config) (new in 1.6), ensures a configuration setting on an instance.,C(flush) flushes all the instance or a specified db.,C(slave) sets a redis instance in slave or master mode.\n attribute :command\n validates :command, presence: true, expression_inclusion: {:in=>[:config, :flush, :slave], :message=>\"%{value} needs to be :config, :flush, :slave\"}\n\n # @return [Object, nil] The password used to authenticate with (usually not used)\n attribute :login_password\n\n # @return [String, nil] The host running the database\n attribute :login_host\n validates :login_host, type: String\n\n # @return [Integer, nil] The port to connect to\n attribute :login_port\n validates :login_port, type: Integer\n\n # @return [String, nil] The host of the master instance [slave command]\n attribute :master_host\n validates :master_host, type: String\n\n # @return [Integer, nil] The port of the master instance [slave command]\n attribute :master_port\n validates :master_port, type: Integer\n\n # @return [:master, :slave, nil] the mode of the redis instance [slave command]\n attribute :slave_mode\n validates :slave_mode, expression_inclusion: {:in=>[:master, :slave], :message=>\"%{value} needs to be :master, :slave\"}, allow_nil: true\n\n # @return [Integer, nil] The database to flush (used in db mode) [flush command]\n attribute :db\n validates :db, type: Integer\n\n # @return [:all, :db, nil] Type of flush (all the dbs in a redis instance or a specific one) [flush command]\n attribute :flush_mode\n validates :flush_mode, expression_inclusion: {:in=>[:all, :db], :message=>\"%{value} needs to be :all, :db\"}, allow_nil: true\n\n # @return [String, nil] A redis config key.\n attribute :name\n validates :name, type: String\n\n # @return [Integer, nil] A redis config value.\n attribute :value\n validates :value, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6874301433563232, "alphanum_fraction": 0.6888267993927002, "avg_line_length": 61.8070182800293, "blob_id": "3dfdb9eda10fd9244dbf87cf62299d480e7504cf", "content_id": "e30fbd269e86dedc14a5ee9243c32d9a055e3e21", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3580, "license_type": "permissive", "max_line_length": 339, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/system/firewalld.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows for addition or deletion of services and ports either tcp or udp in either running or permanent firewalld rules.\n class Firewalld < Base\n # @return [String, nil] Name of a service to add/remove to/from firewalld - service must be listed in output of firewall-cmd --get-services.\n attribute :service\n validates :service, type: String\n\n # @return [String, nil] Name of a port or port range to add/remove to/from firewalld. Must be in the form PORT/PROTOCOL or PORT-PORT/PROTOCOL for port ranges.\n attribute :port\n validates :port, type: String\n\n # @return [String, nil] Rich rule to add/remove to/from firewalld.\n attribute :rich_rule\n validates :rich_rule, type: String\n\n # @return [String, nil] The source/network you would like to add/remove to/from firewalld\n attribute :source\n validates :source, type: String\n\n # @return [String, nil] The interface you would like to add/remove to/from a zone in firewalld\n attribute :interface\n validates :interface, type: String\n\n # @return [:work, :drop, :internal, :external, :trusted, :home, :dmz, :public, :block, nil] The firewalld zone to add/remove to/from (NOTE: default zone can be configured per system but \"public\" is default from upstream. Available choices can be extended based on per-system configs, listed here are \"out of the box\" defaults).\\r\\n\n attribute :zone\n validates :zone, expression_inclusion: {:in=>[:work, :drop, :internal, :external, :trusted, :home, :dmz, :public, :block], :message=>\"%{value} needs to be :work, :drop, :internal, :external, :trusted, :home, :dmz, :public, :block\"}, allow_nil: true\n\n # @return [Symbol, nil] Should this configuration be in the running firewalld configuration or persist across reboots. As of Ansible version 2.3, permanent operations can operate on firewalld configs when it's not running (requires firewalld >= 3.0.9). (NOTE: If this is false, immediate is assumed true.)\\r\\n\n attribute :permanent\n validates :permanent, type: Symbol\n\n # @return [:yes, :no, nil] Should this configuration be applied immediately, if set as permanent\n attribute :immediate\n validates :immediate, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:enabled, :disabled, :present, :absent] Enable or disable a setting. For ports: Should this port accept(enabled) or reject(disabled) connections. The states \"present\" and \"absent\" can only be used in zone level operations (i.e. when no other parameters but zone and state are set).\\r\\n\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:enabled, :disabled, :present, :absent], :message=>\"%{value} needs to be :enabled, :disabled, :present, :absent\"}\n\n # @return [Integer, nil] The amount of time the rule should be in effect for when non-permanent.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [Boolean, nil] The masquerade setting you would like to enable/disable to/from zones within firewalld\n attribute :masquerade\n validates :masquerade, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6752577424049377, "alphanum_fraction": 0.6757732033729553, "avg_line_length": 54.42856979370117, "blob_id": "aae242b31476cdb1d525d0e9b0fadc3c35646b51", "content_id": "fe23bb2ca05362becf2b6b4c1ae17da7a1d9de0e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3880, "license_type": "permissive", "max_line_length": 379, "num_lines": 70, "path": "/lib/ansible/ruby/modules/generated/windows/win_get_url.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Downloads files from HTTP, HTTPS, or FTP to the remote server. The remote server I(must) have direct access to the remote resource.\n # For non-Windows targets, use the M(get_url) module instead.\n class Win_get_url < Base\n # @return [String] The full URL of a file to download.\n attribute :url\n validates :url, presence: true, type: String\n\n # @return [String] The location to save the file at the URL.,Be sure to include a filename and extension as appropriate.\n attribute :dest\n validates :dest, presence: true, type: String\n\n # @return [:yes, :no, nil] If C(yes), will always download the file. If C(no), will only download the file if it does not exist or the remote file has been modified more recently than the local file.,This works by sending an http HEAD request to retrieve last modified time of the requested resource, so for this to work, the remote web server must support HEAD requests.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Hash, nil] Add custom HTTP headers to a request (as a dictionary).\n attribute :headers\n validates :headers, type: Hash\n\n # @return [String, nil] Basic authentication username.\n attribute :url_username\n validates :url_username, type: String\n\n # @return [String, nil] Basic authentication password.\n attribute :url_password\n validates :url_password, type: String\n\n # @return [:yes, :no, nil] If C(yes), will add a Basic authentication header on the initial request.,If C(no), will use Microsoft's WebClient to handle authentication.\n attribute :force_basic_auth\n validates :force_basic_auth, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] This option is deprecated since v2.4, please use C(validate_certs) instead.,If C(yes), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n attribute :skip_certificate_validation\n validates :skip_certificate_validation, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.,If C(skip_certificate_validation) was set, it overrides this option.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] The full URL of the proxy server to download through.\n attribute :proxy_url\n validates :proxy_url, type: String\n\n # @return [String, nil] Proxy authentication username.\n attribute :proxy_username\n validates :proxy_username, type: String\n\n # @return [String, nil] Proxy authentication password.\n attribute :proxy_password\n validates :proxy_password, type: String\n\n # @return [:yes, :no, nil] If C(no), it will not use a proxy, even if one is defined in an environment variable on the target hosts.\n attribute :use_proxy\n validates :use_proxy, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Timeout in seconds for URL request.\n attribute :timeout\n validates :timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6886188983917236, "alphanum_fraction": 0.6886188983917236, "avg_line_length": 46.39393997192383, "blob_id": "69dd203d268e6eb0c463b9bc1a1f48a61437e93b", "content_id": "a7c780a00389294139401160700e38eca048c178", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1564, "license_type": "permissive", "max_line_length": 189, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/notification/cisco_spark.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Send a message to a Cisco Spark Room or Individual with options to control the formatting.\n class Cisco_spark < Base\n # @return [:roomId, :toPersonEmail, :toPersonId] The request parameter you would like to send the message to.,Messages can be sent to either a room or individual (by ID or E-Mail).\n attribute :recipient_type\n validates :recipient_type, presence: true, expression_inclusion: {:in=>[:roomId, :toPersonEmail, :toPersonId], :message=>\"%{value} needs to be :roomId, :toPersonEmail, :toPersonId\"}\n\n # @return [String] The unique identifier associated with the supplied C(recipient_type).\n attribute :recipient_id\n validates :recipient_id, presence: true, type: String\n\n # @return [:text, :markdown, nil] Specifies how you would like the message formatted.\n attribute :message_type\n validates :message_type, expression_inclusion: {:in=>[:text, :markdown], :message=>\"%{value} needs to be :text, :markdown\"}, allow_nil: true\n\n # @return [String] Your personal access token required to validate the Spark API.\n attribute :personal_token\n validates :personal_token, presence: true, type: String\n\n # @return [String] The message you would like to send.\n attribute :message\n validates :message, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6796213388442993, "alphanum_fraction": 0.6831091046333313, "avg_line_length": 53.24324417114258, "blob_id": "ddedae78b21c77b0f01826b328dc953d67dd82fe", "content_id": "1dc7a290939b630b931a6b0824af486a27452885", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2007, "license_type": "permissive", "max_line_length": 254, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/network/a10/a10_server_axapi3.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage SLB (Server Load Balancer) server objects on A10 Networks devices via aXAPIv3.\n class A10_server_axapi3 < Base\n # @return [Object] The SLB (Server Load Balancer) server name.\n attribute :server_name\n validates :server_name, presence: true\n\n # @return [String] The SLB (Server Load Balancer) server IPv4 address.\n attribute :server_ip\n validates :server_ip, presence: true, type: String\n\n # @return [:enable, :disable, nil] The SLB (Server Load Balancer) virtual server status.\n attribute :server_status\n validates :server_status, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash, nil] A list of ports to create for the server. Each list item should be a dictionary which specifies the C(port:) and C(protocol:).\n attribute :server_ports\n validates :server_ports, type: TypeGeneric.new(Hash)\n\n # @return [:create, :update, :remove, nil] Create, Update or Remove SLB server. For create and update operation, we use the IP address and server name specified in the POST message. For delete operation, we use the server name in the request URI.\n attribute :operation\n validates :operation, expression_inclusion: {:in=>[:create, :update, :remove], :message=>\"%{value} needs to be :create, :update, :remove\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated. This should only be used on personally controlled devices using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6839506030082703, "alphanum_fraction": 0.6839506030082703, "avg_line_length": 40.89655303955078, "blob_id": "ddc375ffbc674894bd2582e71e71cbfb4515ba14", "content_id": "b6da6e2f2e79995d180923f1bc8ebd775566afbf", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1215, "license_type": "permissive", "max_line_length": 144, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_elasticbeanstalk_app.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # creates, updates, deletes beanstalk applications if app_name is provided\n class Aws_elasticbeanstalk_app < Base\n # @return [String, nil] name of the beanstalk application you wish to manage\n attribute :app_name\n validates :app_name, type: String\n\n # @return [String, nil] the description of the application\n attribute :description\n validates :description, type: String\n\n # @return [:absent, :present, nil] whether to ensure the application is present or absent\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [Boolean, nil] when set to true, running environments will be terminated before deleting the application\n attribute :terminate_by_force\n validates :terminate_by_force, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6752519607543945, "alphanum_fraction": 0.6752519607543945, "avg_line_length": 36.20833206176758, "blob_id": "580238d012d338a6989a9e294325d57765cf3616", "content_id": "6013cbd4a37af263fd558ffc06e91b6c153743e9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 893, "license_type": "permissive", "max_line_length": 143, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/system/kernel_blacklist.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove kernel modules from blacklist.\n class Kernel_blacklist < Base\n # @return [String] Name of kernel module to black- or whitelist.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, nil] Whether the module should be present in the blacklist or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [Object, nil] If specified, use this blacklist file instead of C(/etc/modprobe.d/blacklist-ansible.conf).\n attribute :blacklist_file\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7030539512634277, "alphanum_fraction": 0.7056530117988586, "avg_line_length": 50.29999923706055, "blob_id": "2e8099685dd4d53ba6b4871c72614722490b15b2", "content_id": "e171deea3711f036a0107aede8c2f38ffa4e051d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1539, "license_type": "permissive", "max_line_length": 278, "num_lines": 30, "path": "/lib/ansible/ruby/modules/generated/cloud/rackspace/rax_mon_notification_plan.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or delete a Rackspace Cloud Monitoring notification plan by associating existing rax_mon_notifications with severity levels. Rackspace monitoring module flow | rax_mon_entity -> rax_mon_check -> rax_mon_notification -> *rax_mon_notification_plan* -> rax_mon_alarm\n class Rax_mon_notification_plan < Base\n # @return [:present, :absent, nil] Ensure that the notification plan with this C(label) exists or does not exist.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object] Defines a friendly name for this notification plan. String between 1 and 255 characters long.\n attribute :label\n validates :label, presence: true\n\n # @return [Object, nil] Notification list to use when the alarm state is CRITICAL. Must be an array of valid rax_mon_notification ids.\n attribute :critical_state\n\n # @return [Object, nil] Notification list to use when the alarm state is WARNING. Must be an array of valid rax_mon_notification ids.\n attribute :warning_state\n\n # @return [Object, nil] Notification list to use when the alarm state is OK. Must be an array of valid rax_mon_notification ids.\n attribute :ok_state\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6833937168121338, "alphanum_fraction": 0.6833937168121338, "avg_line_length": 46.14634323120117, "blob_id": "a4ed7c302a5f6f9a92628190c6bfaa5e6c37ea67", "content_id": "df3b4c91005043d0b68dc277ec6a888fea6721fe", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1933, "license_type": "permissive", "max_line_length": 258, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/notification/mattermost.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Sends notifications to U(http://your.mattermost.url) via the Incoming WebHook integration.\n class Mattermost < Base\n # @return [String] Mattermost url (i.e. http://mattermost.yourcompany.com).\n attribute :url\n validates :url, presence: true, type: String\n\n # @return [String] Mattermost webhook api key. Log into your mattermost site, go to Menu -> Integration -> Incoming Webhook -> Add Incoming Webhook. This will give you full URL. api_key is the last part. http://mattermost.example.com/hooks/C(API_KEY)\n attribute :api_key\n validates :api_key, presence: true, type: String\n\n # @return [String] Text to send. Note that the module does not handle escaping characters.\n attribute :text\n validates :text, presence: true, type: String\n\n # @return [String, nil] Channel to send the message to. If absent, the message goes to the channel selected for the I(api_key).\n attribute :channel\n validates :channel, type: String\n\n # @return [String, nil] This is the sender of the message (Username Override need to be enabled by mattermost admin, see mattermost doc.\n attribute :username\n validates :username, type: String\n\n # @return [String, nil] Url for the message sender's icon.\n attribute :icon_url\n validates :icon_url, type: String\n\n # @return [Boolean, nil] If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6985178589820862, "alphanum_fraction": 0.7163034081459045, "avg_line_length": 69.8024673461914, "blob_id": "7794ec9aa0b1a6e7c12264eae56f85054a83f404", "content_id": "31e8a1f5f53fbe093b5beff751d826852da769bc", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5735, "license_type": "permissive", "max_line_length": 601, "num_lines": 81, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_sflow.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configure Sampled Flow (sFlow) to monitor traffic on an interface in real time, detect abnormal traffic, and locate the source of attack traffic, ensuring stable running of the network.\n class Ce_sflow < Base\n # @return [Object, nil] Specifies the IPv4/IPv6 address of an sFlow agent.\n attribute :agent_ip\n\n # @return [Object, nil] Specifies the source IPv4/IPv6 address of sFlow packets.\n attribute :source_ip\n\n # @return [1, 2, nil] Specifies the ID of an sFlow collector. This ID is used when you specify the collector in subsequent sFlow configuration.\n attribute :collector_id\n validates :collector_id, expression_inclusion: {:in=>[1, 2], :message=>\"%{value} needs to be 1, 2\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the IPv4/IPv6 address of the sFlow collector.\n attribute :collector_ip\n\n # @return [Object, nil] Specifies the name of a VPN instance. The value is a string of 1 to 31 case-sensitive characters, spaces not supported. When double quotation marks are used around the string, spaces are allowed in the string. The value C(_public_) is reserved and cannot be used as the VPN instance name.\n attribute :collector_ip_vpn\n\n # @return [Object, nil] Specifies the maximum length of sFlow packets sent from an sFlow agent to an sFlow collector. The value is an integer, in bytes. It ranges from 1024 to 8100. The default value is 1400.\n attribute :collector_datagram_size\n\n # @return [Object, nil] Specifies the UDP destination port number of sFlow packets. The value is an integer that ranges from 1 to 65535. The default value is 6343.\n attribute :collector_udp_port\n\n # @return [:meth, :enhanced, nil] Configures the device to send sFlow packets through service interfaces, enhancing the sFlow packet forwarding capability. The enhanced parameter is optional. No matter whether you configure the enhanced mode, the switch determines to send sFlow packets through service cards or management port based on the routing information on the collector. When the value is meth, the device forwards sFlow packets at the control plane. When the value is enhanced, the device forwards sFlow packets at the forwarding plane to enhance the sFlow packet forwarding capacity.\n attribute :collector_meth\n validates :collector_meth, expression_inclusion: {:in=>[:meth, :enhanced], :message=>\"%{value} needs to be :meth, :enhanced\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the description of an sFlow collector. The value is a string of 1 to 255 case-sensitive characters without spaces.\n attribute :collector_description\n\n # @return [Object, nil] Full name of interface for Flow Sampling or Counter. It must be a physical interface, Eth-Trunk, or Layer 2 subinterface.\n attribute :sflow_interface\n\n # @return [Object, nil] Indicates the ID list of the collector.\n attribute :sample_collector\n\n # @return [Object, nil] Specifies the flow sampling rate in the format 1/rate. The value is an integer and ranges from 1 to 4294967295. The default value is 8192.\n attribute :sample_rate\n\n # @return [Object, nil] Specifies the maximum length of sampled packets. The value is an integer and ranges from 18 to 512, in bytes. The default value is 128.\n attribute :sample_length\n\n # @return [:inbound, :outbound, :both, nil] Enables flow sampling in the inbound or outbound direction.\n attribute :sample_direction\n validates :sample_direction, expression_inclusion: {:in=>[:inbound, :outbound, :both], :message=>\"%{value} needs to be :inbound, :outbound, :both\"}, allow_nil: true\n\n # @return [Object, nil] Indicates the ID list of the counter collector.\n attribute :counter_collector\n\n # @return [Object, nil] Indicates the counter sampling interval. The value is an integer that ranges from 10 to 4294967295, in seconds. The default value is 20.\n attribute :counter_interval\n\n # @return [:enable, :disable, nil] Configures the sFlow packets sent by the switch not to carry routing information.\n attribute :export_route\n validates :export_route, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the rate of sFlow packets sent from a card to the control plane. The value is an integer that ranges from 100 to 1500, in pps.\n attribute :rate_limit\n\n # @return [Object, nil] Specifies the slot where the rate of output sFlow packets is limited. If this parameter is not specified, the rate of sFlow packets sent from all cards to the control plane is limited. The value is an integer or a string of characters.\n attribute :rate_limit_slot\n\n # @return [Object, nil] Enable the Embedded Network Processor (ENP) chip function. The switch uses the ENP chip to perform sFlow sampling, and the maximum sFlow sampling interval is 65535. If you set the sampling interval to be larger than 65535, the switch automatically restores it to 65535. The value is an integer or 'all'.\n attribute :forward_enp_slot\n\n # @return [:present, :absent, nil] Determines whether the config should be present or not on the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6896551847457886, "alphanum_fraction": 0.6931034326553345, "avg_line_length": 42.93939208984375, "blob_id": "aaf29840f6f5876e79286151f2695e5dd38d9b6b", "content_id": "24134bfc354b416e129adfbfb2db5bc5d81ca710", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1450, "license_type": "permissive", "max_line_length": 250, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/apache2_module.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Enables or disables a specified module of the Apache2 webserver.\n class Apache2_module < Base\n # @return [String] Name of the module to enable/disable as given to C(a2enmod/a2dismod).\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Identifier of the module as listed by C(apache2ctl -M). This is optional and usually determined automatically by the common convention of appending C(_module) to I(name) as well as custom exception for popular modules.\n attribute :identifier\n validates :identifier, type: String\n\n # @return [Symbol, nil] Force disabling of default modules and override Debian warnings.\n attribute :force\n validates :force, type: Symbol\n\n # @return [:present, :absent, nil] Desired state of the module.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Symbol, nil] Ignore configuration checks about inconsistent module configuration. Especially for mpm_* modules.\n attribute :ignore_configcheck\n validates :ignore_configcheck, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6794639825820923, "alphanum_fraction": 0.6794639825820923, "avg_line_length": 54.220001220703125, "blob_id": "edc8dcbc99bd996e43a12f995e9b4b95175812d2", "content_id": "a56b9b57045b170656883da6f7dcb20be1aa915f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2761, "license_type": "permissive", "max_line_length": 399, "num_lines": 50, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_permissions.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Module to manage permissions of users/groups in oVirt/RHV.\n class Ovirt_permission < Base\n # @return [String, nil] Name of the role to be assigned to user/group on specific object.\n attribute :role\n validates :role, type: String\n\n # @return [:absent, :present, nil] Should the permission be present/absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [Object, nil] ID of the object where the permissions should be managed.\n attribute :object_id\n\n # @return [String, nil] Name of the object where the permissions should be managed.\n attribute :object_name\n validates :object_name, type: String\n\n # @return [:cluster, :cpu_profile, :data_center, :disk, :disk_profile, :host, :network, :storage_domain, :system, :template, :vm, :vm_pool, :vnic_profile, nil] The object where the permissions should be managed.\n attribute :object_type\n validates :object_type, expression_inclusion: {:in=>[:cluster, :cpu_profile, :data_center, :disk, :disk_profile, :host, :network, :storage_domain, :system, :template, :vm, :vm_pool, :vnic_profile], :message=>\"%{value} needs to be :cluster, :cpu_profile, :data_center, :disk, :disk_profile, :host, :network, :storage_domain, :system, :template, :vm, :vm_pool, :vnic_profile\"}, allow_nil: true\n\n # @return [String, nil] Username of the user to manage. In most LDAPs it's I(uid) of the user, but in Active Directory you must specify I(UPN) of the user.,Note that if user does not exist in the system this module will fail, you should ensure the user exists by using M(ovirt_users) module.\n attribute :user_name\n validates :user_name, type: String\n\n # @return [Object, nil] Name of the group to manage.,Note that if group does not exist in the system this module will fail, you should ensure the group exists by using M(ovirt_groups) module.\n attribute :group_name\n\n # @return [String] Authorization provider of the user/group.\n attribute :authz_name\n validates :authz_name, presence: true, type: String\n\n # @return [Object, nil] Namespace of the authorization provider, where user/group resides.\n attribute :namespace\n\n # @return [String, nil] Name of the quota to assign permission. Works only with C(object_type) I(data_center).\n attribute :quota_name\n validates :quota_name, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7011672854423523, "alphanum_fraction": 0.7011672854423523, "avg_line_length": 51.448978424072266, "blob_id": "3247e65036ff01c67622d705a02a867566e8dbb6", "content_id": "0d77bb2c9f77de339267c387843a04d5b9c483af", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2570, "license_type": "permissive", "max_line_length": 169, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/netapp_e_amg.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows for the creation, removal and updating of Asynchronous Mirror Groups for NetApp E-series storage arrays\n class Netapp_e_amg < Base\n # @return [String] The name of the async array you wish to target, or create.,If C(state) is present and the name isn't found, it will attempt to create.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] The ID of the secondary array to be used in mirroing process\n attribute :secondaryArrayId\n validates :secondaryArrayId, presence: true, type: String\n\n # @return [Integer, nil] The synchronization interval in minutes\n attribute :syncIntervalMinutes\n validates :syncIntervalMinutes, type: Integer\n\n # @return [:yes, :no, nil] Setting this to true will cause other synchronization values to be ignored\n attribute :manualSync\n validates :manualSync, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Recovery point warning threshold (minutes). The user will be warned when the age of the last good failures point exceeds this value\n attribute :recoveryWarnThresholdMinutes\n validates :recoveryWarnThresholdMinutes, type: Integer\n\n # @return [Integer, nil] Recovery point warning threshold\n attribute :repoUtilizationWarnThreshold\n validates :repoUtilizationWarnThreshold, type: Integer\n\n # @return [:iscsi, :fibre, nil] The intended protocol to use if both Fibre and iSCSI are available.\n attribute :interfaceType\n validates :interfaceType, expression_inclusion: {:in=>[:iscsi, :fibre], :message=>\"%{value} needs to be :iscsi, :fibre\"}, allow_nil: true\n\n # @return [Integer, nil] The threshold (in minutes) for notifying the user that periodic synchronization has taken too long to complete.\n attribute :syncWarnThresholdMinutes\n validates :syncWarnThresholdMinutes, type: Integer\n\n # @return [:absent, :present] A C(state) of present will either create or update the async mirror group.,A C(state) of absent will remove the async mirror group.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.660015344619751, "alphanum_fraction": 0.6722946763038635, "avg_line_length": 37.32352828979492, "blob_id": "70e981a4aa52a312e55c6416e45793f05b393ca7", "content_id": "c5e14b38a8e8f1564d67d0bd90842d19093eb6d3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1303, "license_type": "permissive", "max_line_length": 143, "num_lines": 34, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_gslbapplicationpersistenceprofile.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure GslbApplicationPersistenceProfile object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_gslbapplicationpersistenceprofile < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [Object, nil] Field introduced in 17.1.1.\n attribute :description\n\n # @return [String] A user-friendly name for the persistence profile.,Field introduced in 17.1.1.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] It is a reference to an object of type tenant.,Field introduced in 17.1.1.\n attribute :tenant_ref\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Uuid of the persistence profile.,Field introduced in 17.1.1.\n attribute :uuid\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6566866040229797, "alphanum_fraction": 0.6566866040229797, "avg_line_length": 40.75, "blob_id": "246333a6a901c7d9529ef99949238f814c7ce537", "content_id": "9edfd176e463dbad31a2a5a4d7e2a7c03e9254f5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1503, "license_type": "permissive", "max_line_length": 187, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/remote_management/cobbler/cobbler_sync.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Sync Cobbler to commit changes.\n class Cobbler_sync < Base\n # @return [String, nil] The name or IP address of the Cobbler system.\n attribute :host\n validates :host, type: String\n\n # @return [Object, nil] Port number to be used for REST connection.,The default value depends on parameter C(use_ssl).\n attribute :port\n\n # @return [String, nil] The username to log in to Cobbler.\n attribute :username\n validates :username, type: String\n\n # @return [String] The password to log in to Cobbler.\n attribute :password\n validates :password, presence: true, type: String\n\n # @return [:yes, :no, nil] If C(no), an HTTP connection will be used instead of the default HTTPS connection.\n attribute :use_ssl\n validates :use_ssl, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated.,This should only set to C(no) when used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.695937991142273, "alphanum_fraction": 0.6989903450012207, "avg_line_length": 66.6031723022461, "blob_id": "0e821e448b4a8785a838b675e2d03c8df498ee0c", "content_id": "3d82231acf4f8e3547af3fa2c146f062de6248a1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4265, "license_type": "permissive", "max_line_length": 511, "num_lines": 63, "path": "/lib/ansible/ruby/modules/generated/remote_management/ucs/ucs_vhba_template.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configures vHBA templates on Cisco UCS Manager.\n # Examples can be used with the UCS Platform Emulator U(https://communities.cisco.com/ucspe).\n class Ucs_vhba_template < Base\n # @return [:present, :absent, nil] If C(present), will verify vHBA templates are present and will create if needed.,If C(absent), will verify vHBA templates are absent and will delete if needed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The name of the virtual HBA template.,This name can be between 1 and 16 alphanumeric characters.,You cannot use spaces or any special characters other than - (hyphen), \"_\" (underscore), : (colon), and . (period).,You cannot change this name after the template is created.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] A user-defined description of the template.,Enter up to 256 characters.,You can use any characters or spaces except the following:,` (accent mark), (backslash), ^ (carat), \" (double quote), = (equal sign), > (greater than), < (less than), or ' (single quote).\n attribute :description\n\n # @return [:A, :B, nil] The Fabric ID field.,The name of the fabric interconnect that vHBAs created with this template are associated with.\n attribute :fabric\n validates :fabric, expression_inclusion: {:in=>[:A, :B], :message=>\"%{value} needs to be :A, :B\"}, allow_nil: true\n\n # @return [:none, :primary, :secondary, nil] The Redundancy Type used for template pairing from the Primary or Secondary redundancy template.,primary — Creates configurations that can be shared with the Secondary template.,Any other shared changes on the Primary template are automatically synchronized to the Secondary template.,secondary — All shared configurations are inherited from the Primary template.,none - Legacy vHBA template behavior. Select this option if you do not want to use redundancy.\n attribute :redundancy_type\n validates :redundancy_type, expression_inclusion: {:in=>[:none, :primary, :secondary], :message=>\"%{value} needs to be :none, :primary, :secondary\"}, allow_nil: true\n\n # @return [String, nil] The VSAN to associate with vHBAs created from this template.\n attribute :vsan\n validates :vsan, type: String\n\n # @return [:\"initial-template\", :\"updating-template\", nil] The Template Type field.,This can be one of the following:,initial-template — vHBAs created from this template are not updated if the template changes.,updating-template - vHBAs created from this template are updated if the template changes.\n attribute :template_type\n validates :template_type, expression_inclusion: {:in=>[:\"initial-template\", :\"updating-template\"], :message=>\"%{value} needs to be :\\\"initial-template\\\", :\\\"updating-template\\\"\"}, allow_nil: true\n\n # @return [String, nil] The Max Data Field Size field.,The maximum size of the Fibre Channel frame payload bytes that the vHBA supports.,Enter an string between '256' and '2112'.\n attribute :max_data\n validates :max_data, type: String\n\n # @return [String, nil] The WWPN pool that a vHBA created from this template uses to derive its WWPN address.\n attribute :wwpn_pool\n validates :wwpn_pool, type: String\n\n # @return [Object, nil] The QoS policy that is associated with vHBAs created from this template.\n attribute :qos_policy\n\n # @return [Object, nil] The SAN pin group that is associated with vHBAs created from this template.\n attribute :pin_group\n\n # @return [String, nil] The statistics collection policy that is associated with vHBAs created from this template.\n attribute :stats_policy\n validates :stats_policy, type: String\n\n # @return [String, nil] Org dn (distinguished name)\n attribute :org_dn\n validates :org_dn, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6466774940490723, "alphanum_fraction": 0.658427894115448, "avg_line_length": 57.070587158203125, "blob_id": "7e1aa41d6a54537917a4ba5c57e7d79172a6f55a", "content_id": "57d4c5cea32482ebfed85027a6b9110165f12168", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4936, "license_type": "permissive", "max_line_length": 165, "num_lines": 85, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_nfs.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Enable or disable NFS on ONTAP\n class Na_ontap_nfs < Base\n # @return [:present, :absent, nil] Whether NFS should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:started, :stopped, nil] Whether the specified NFS should be enabled or disabled. Creates NFS service if doesnt exist.\n attribute :service_state\n validates :service_state, expression_inclusion: {:in=>[:started, :stopped], :message=>\"%{value} needs to be :started, :stopped\"}, allow_nil: true\n\n # @return [String] Name of the vserver to use.\n attribute :vserver\n validates :vserver, presence: true, type: String\n\n # @return [:enabled, :disabled, nil] status of NFSv3.\n attribute :nfsv3\n validates :nfsv3, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] status of if NFSv3 clients see change in FSID as they traverse filesystems.\n attribute :nfsv3_fsid_change\n validates :nfsv3_fsid_change, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] status of NFSv4.\n attribute :nfsv4\n validates :nfsv4, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] status of NFSv41.\n attribute :nfsv41\n validates :nfsv41, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] status of vstorage_state.\n attribute :vstorage_state\n validates :vstorage_state, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [String, nil] Name of the nfsv4_id_domain to use.\n attribute :nfsv4_id_domain\n validates :nfsv4_id_domain, type: String\n\n # @return [:enabled, :disabled, nil] status of NFS v4.0 ACL feature\n attribute :nfsv40_acl\n validates :nfsv40_acl, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] status for NFS v4.0 read delegation feature.\n attribute :nfsv40_read_delegation\n validates :nfsv40_read_delegation, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] status for NFS v4.0 write delegation feature.\n attribute :nfsv40_write_delegation\n validates :nfsv40_write_delegation, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] status of NFS v4.1 ACL feature\n attribute :nfsv41_acl\n validates :nfsv41_acl, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] status for NFS v4.1 read delegation feature.\n attribute :nfsv41_read_delegation\n validates :nfsv41_read_delegation, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] status for NFS v4.1 write delegation feature.\n attribute :nfsv41_write_delegation\n validates :nfsv41_write_delegation, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] Enable TCP (support from ONTAP 9.3 onward).\n attribute :tcp\n validates :tcp, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] Enable UDP (support from ONTAP 9.3 onward).\n attribute :udp\n validates :udp, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] Whether SVM allows showmount\n attribute :showmount\n validates :showmount, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6738428473472595, "alphanum_fraction": 0.6738428473472595, "avg_line_length": 36.15999984741211, "blob_id": "d4d7f4aa75d40472afd137ccf1d5bca1b0173209", "content_id": "520136e3136544aae1947da95b69e9d37fcd80fe", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 929, "license_type": "permissive", "max_line_length": 143, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_snmp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create/Delete SNMP community\n class Na_ontap_snmp < Base\n # @return [String] Access control for the community. The only supported value is 'ro' (read-only)\n attribute :access_control\n validates :access_control, presence: true, type: String\n\n # @return [String] The name of the SNMP community to manage.\n attribute :community_name\n validates :community_name, presence: true, type: String\n\n # @return [:present, :absent, nil] Whether the specified SNMP community should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6765217185020447, "alphanum_fraction": 0.6765217185020447, "avg_line_length": 45, "blob_id": "bb00a8c787738600f3a901db8f8038e8443ad444", "content_id": "9e4c3304b4b7769c71f084f3ca10bc912abc51fc", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1150, "license_type": "permissive", "max_line_length": 270, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_sys_db.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage BIG-IP system database variables\n class Bigip_sys_db < Base\n # @return [String] The database variable to manipulate.\n attribute :key\n validates :key, presence: true, type: String\n\n # @return [:present, :reset, nil] The state of the variable on the system. When C(present), guarantees that an existing variable is set to C(value). When C(reset) sets the variable back to the default value. At least one of value and state C(reset) are required.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :reset], :message=>\"%{value} needs to be :present, :reset\"}, allow_nil: true\n\n # @return [Boolean, nil] The value to set the key to. At least one of value and state C(reset) are required.\n attribute :value\n validates :value, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6976984143257141, "alphanum_fraction": 0.7066300511360168, "avg_line_length": 53.924530029296875, "blob_id": "94486b234893d7b072b804811b06f1e8c5ab86c3", "content_id": "44ce3f71787f68e16192b41f0f46137286915d5e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2911, "license_type": "permissive", "max_line_length": 345, "num_lines": 53, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_vpc_endpoint.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates AWS VPC endpoints.\n # Deletes AWS VPC endpoints.\n # This module support check mode.\n class Ec2_vpc_endpoint < Base\n # @return [String, nil] Required when creating a VPC endpoint.\n attribute :vpc_id\n validates :vpc_id, type: String\n\n # @return [String, nil] An AWS supported vpc endpoint service. Use the ec2_vpc_endpoint_facts module to describe the supported endpoint services.,Required when creating an endpoint.\n attribute :service\n validates :service, type: String\n\n # @return [String, nil] A properly formatted json policy as string, see U(https://github.com/ansible/ansible/issues/7005#issuecomment-42894813). Cannot be used with I(policy_file).,Option when creating an endpoint. If not provided AWS will utilise a default policy which provides full access to the service.\n attribute :policy\n validates :policy, type: String\n\n # @return [String, nil] The path to the properly json formatted policy file, see U(https://github.com/ansible/ansible/issues/7005#issuecomment-42894813) on how to use it properly. Cannot be used with I(policy).,Option when creating an endpoint. If not provided AWS will utilise a default policy which provides full access to the service.\n attribute :policy_file\n validates :policy_file, type: String\n\n # @return [:present, :absent, nil] present to ensure resource is created.,absent to remove resource\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Symbol, nil] When specified, will wait for either available status for state present. Unfortunately this is ignored for delete actions due to a difference in behaviour from AWS.\n attribute :wait\n validates :wait, type: Symbol\n\n # @return [Integer, nil] Used in conjunction with wait. Number of seconds to wait for status. Unfortunately this is ignored for delete actions due to a difference in behaviour from AWS.\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [Array<String>, String, nil] List of one or more route table ids to attach to the endpoint. A route is added to the route table with the destination of the endpoint if provided.\n attribute :route_table_ids\n validates :route_table_ids, type: TypeGeneric.new(String)\n\n # @return [Object, nil] One or more vpc endpoint ids to remove from the AWS account\n attribute :vpc_endpoint_id\n\n # @return [Object, nil] Optional client token to ensure idempotency\n attribute :client_token\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6611534953117371, "alphanum_fraction": 0.6636980772018433, "avg_line_length": 68.35294342041016, "blob_id": "9fe9e108d1a4c55f3da7b02e0771d6774d467f33", "content_id": "54f5bd29445315c0e3d80caee0e1c8a0a05fb665", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2358, "license_type": "permissive", "max_line_length": 938, "num_lines": 34, "path": "/lib/ansible/ruby/modules/generated/notification/campfire.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Send a message to Campfire.\n # Messages with newlines will result in a \"Paste\" message being sent.\n class Campfire < Base\n # @return [String] The subscription name to use.\n attribute :subscription\n validates :subscription, presence: true, type: String\n\n # @return [Integer] API token.\n attribute :token\n validates :token, presence: true, type: Integer\n\n # @return [Integer] Room number to which the message should be sent.\n attribute :room\n validates :room, presence: true, type: Integer\n\n # @return [String] The message body.\n attribute :msg\n validates :msg, presence: true, type: String\n\n # @return [:\"56k\", :bell, :bezos, :bueller, :clowntown, :cottoneyejoe, :crickets, :dadgummit, :dangerzone, :danielsan, :deeper, :drama, :greatjob, :greyjoy, :guarantee, :heygirl, :horn, :horror, :inconceivable, :live, :loggins, :makeitso, :noooo, :nyan, :ohmy, :ohyeah, :pushit, :rimshot, :rollout, :rumble, :sax, :secret, :sexyback, :story, :tada, :tmyk, :trololo, :trombone, :unix, :vuvuzela, :what, :whoomp, :yeah, :yodel, nil] Send a notification sound before the message.\n attribute :notify\n validates :notify, expression_inclusion: {:in=>[:\"56k\", :bell, :bezos, :bueller, :clowntown, :cottoneyejoe, :crickets, :dadgummit, :dangerzone, :danielsan, :deeper, :drama, :greatjob, :greyjoy, :guarantee, :heygirl, :horn, :horror, :inconceivable, :live, :loggins, :makeitso, :noooo, :nyan, :ohmy, :ohyeah, :pushit, :rimshot, :rollout, :rumble, :sax, :secret, :sexyback, :story, :tada, :tmyk, :trololo, :trombone, :unix, :vuvuzela, :what, :whoomp, :yeah, :yodel], :message=>\"%{value} needs to be :\\\"56k\\\", :bell, :bezos, :bueller, :clowntown, :cottoneyejoe, :crickets, :dadgummit, :dangerzone, :danielsan, :deeper, :drama, :greatjob, :greyjoy, :guarantee, :heygirl, :horn, :horror, :inconceivable, :live, :loggins, :makeitso, :noooo, :nyan, :ohmy, :ohyeah, :pushit, :rimshot, :rollout, :rumble, :sax, :secret, :sexyback, :story, :tada, :tmyk, :trololo, :trombone, :unix, :vuvuzela, :what, :whoomp, :yeah, :yodel\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6880881786346436, "alphanum_fraction": 0.6964237689971924, "avg_line_length": 54.50746154785156, "blob_id": "035f67e01f9bd35401b79ca4048a048e970e3a8e", "content_id": "3f208ce15bd004acc62923c8410739928e95873c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3719, "license_type": "permissive", "max_line_length": 266, "num_lines": 67, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_poolgroupdeploymentpolicy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure PoolGroupDeploymentPolicy object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_poolgroupdeploymentpolicy < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Symbol, nil] It will automatically disable old production pools once there is a new production candidate.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :auto_disable_old_prod_pools\n validates :auto_disable_old_prod_pools, type: Symbol\n\n # @return [Object, nil] It is a reference to an object of type cloud.\n attribute :cloud_ref\n\n # @return [Object, nil] User defined description for the object.\n attribute :description\n\n # @return [Object, nil] Duration of evaluation period for automatic deployment.,Allowed values are 60-86400.,Default value when not specified in API or module is interpreted by Avi Controller as 300.,Units(SEC).\n attribute :evaluation_duration\n\n # @return [String] The name of the pool group deployment policy.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] List of pgdeploymentrule.\n attribute :rules\n\n # @return [Object, nil] Deployment scheme.,Enum options - BLUE_GREEN, CANARY.,Default value when not specified in API or module is interpreted by Avi Controller as BLUE_GREEN.\n attribute :scheme\n\n # @return [Object, nil] Target traffic ratio before pool is made production.,Allowed values are 1-100.,Default value when not specified in API or module is interpreted by Avi Controller as 100.,Units(RATIO).\n attribute :target_test_traffic_ratio\n\n # @return [Object, nil] It is a reference to an object of type tenant.\n attribute :tenant_ref\n\n # @return [Object, nil] Ratio of the traffic that is sent to the pool under test.,Test ratio of 100 means blue green.,Allowed values are 1-100.,Default value when not specified in API or module is interpreted by Avi Controller as 100.\n attribute :test_traffic_ratio_rampup\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Uuid of the pool group deployment policy.\n attribute :uuid\n\n # @return [Object, nil] Webhook configured with url that avi controller will pass back information about pool group, old and new pool information and current deployment,rule results.,It is a reference to an object of type webhook.,Field introduced in 17.1.1.\n attribute :webhook_ref\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6702755689620972, "alphanum_fraction": 0.6751968264579773, "avg_line_length": 38.07692337036133, "blob_id": "19348efde4e33320e42d2647fc7bda801c831198", "content_id": "4c0dc3db10d9eed6718604f383f29cd5f9ba1f16", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1016, "license_type": "permissive", "max_line_length": 186, "num_lines": 26, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/dynamodb_ttl.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Uses boto3 to set TTL.\n # requires botocore version 1.5.24 or higher.\n class Dynamodb_ttl < Base\n # @return [:enable, :disable, nil] state to set DynamoDB table to\n attribute :state\n validates :state, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [String] name of the DynamoDB table to work on\n attribute :table_name\n validates :table_name, presence: true, type: String\n\n # @return [String] the name of the Time to Live attribute used to store the expiration time for items in the table,this appears to be required by the API even when disabling TTL.\n attribute :attribute_name\n validates :attribute_name, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6731757521629333, "alphanum_fraction": 0.6731757521629333, "avg_line_length": 37.91999816894531, "blob_id": "de3c5a396e8d1f8c7fd2b8f55245588dfb9d6859", "content_id": "c8b827cab80bb8d7d5fa8a303673987235625848", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 973, "license_type": "permissive", "max_line_length": 155, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vcenter_license.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add and delete vCenter license keys.\n class Vcenter_license < Base\n # @return [Array<String>, String, nil] The optional labels of the license key to manage in vSphere vCenter.,This is dictionary with key/value pair.\n attribute :labels\n validates :labels, type: TypeGeneric.new(String)\n\n # @return [String] The license key to manage in vSphere vCenter.\n attribute :license\n validates :license, presence: true, type: String\n\n # @return [:absent, :present, nil] Whether to add (C(present)) or remove (C(absent)) the license key.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6537013649940491, "alphanum_fraction": 0.6562107801437378, "avg_line_length": 36.069766998291016, "blob_id": "f2d1cbd9e5073abcb8ae34015e6fb33202d4e1c6", "content_id": "cd647fc2671d0c3f389a5e470a7d12a9e2db2342", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1594, "license_type": "permissive", "max_line_length": 143, "num_lines": 43, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_static_route.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages static route configuration\n class Nxos_static_route < Base\n # @return [String] Destination prefix of static route.\n attribute :prefix\n validates :prefix, presence: true, type: String\n\n # @return [String] Next hop address or interface of static route. If interface, it must be the fully-qualified interface name.\n attribute :next_hop\n validates :next_hop, presence: true, type: String\n\n # @return [String, nil] VRF for static route.\n attribute :vrf\n validates :vrf, type: String\n\n # @return [Object, nil] Route tag value (numeric) or keyword 'default'.\n attribute :tag\n\n # @return [String, nil] Name of the route or keyword 'default'. Used with the name parameter on the CLI.\n attribute :route_name\n validates :route_name, type: String\n\n # @return [Integer, nil] Preference or administrative difference of route (range 1-255) or keyword 'default'.\n attribute :pref\n validates :pref, type: Integer\n\n # @return [Object, nil] List of static route definitions\n attribute :aggregate\n\n # @return [:present, :absent, nil] Manage the state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.670164942741394, "alphanum_fraction": 0.670164942741394, "avg_line_length": 29.31818199157715, "blob_id": "b4d9c6478da31b83f5b37026ce274fcb4c090be1", "content_id": "772543de30f0781f2665b29984d7f8106b0abe42", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 667, "license_type": "permissive", "max_line_length": 79, "num_lines": 22, "path": "/lib/ansible/ruby/modules/generated/inventory/group_by.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Use facts to create ad-hoc groups that can be used later in a playbook.\n # This module is also supported for Windows targets.\n class Group_by < Base\n # @return [String] The variables whose values will be used as groups\n attribute :key\n validates :key, presence: true, type: String\n\n # @return [String, nil] The list of the parent groups\n attribute :parents\n validates :parents, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6705202460289001, "alphanum_fraction": 0.6705202460289001, "avg_line_length": 58.655174255371094, "blob_id": "4fe47a27cc1ba840b712b2804b1b3cbddc9e1167", "content_id": "1f6e03199ba4d891d73ad9325b4fef105be602c1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1730, "license_type": "permissive", "max_line_length": 428, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/remote_management/manageiq/manageiq_tags.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The manageiq_tags module supports adding, updating and deleting tags in ManageIQ.\n class Manageiq_tags < Base\n # @return [:absent, :present, :list, nil] absent - tags should not exist,,present - tags should exist,,list - list current tags.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :list], :message=>\"%{value} needs to be :absent, :present, :list\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash, nil] tags - list of dictionaries, each includes 'name' and 'category' keys.,required if state is present or absent.\n attribute :tags\n validates :tags, type: TypeGeneric.new(Hash)\n\n # @return [:provider, :host, :vm, :blueprint, :category, :cluster, :\"data store\", :group, :\"resource pool\", :service, :\"service template\", :template, :tenant, :user] the relevant resource type in manageiq\n attribute :resource_type\n validates :resource_type, presence: true, expression_inclusion: {:in=>[:provider, :host, :vm, :blueprint, :category, :cluster, :\"data store\", :group, :\"resource pool\", :service, :\"service template\", :template, :tenant, :user], :message=>\"%{value} needs to be :provider, :host, :vm, :blueprint, :category, :cluster, :\\\"data store\\\", :group, :\\\"resource pool\\\", :service, :\\\"service template\\\", :template, :tenant, :user\"}\n\n # @return [String] the relevant resource name in manageiq\n attribute :resource_name\n validates :resource_name, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6833333373069763, "alphanum_fraction": 0.6833333373069763, "avg_line_length": 39, "blob_id": "43a6575e5c42f0318caed5fbad79d67165bdd508", "content_id": "cdfd7215efb0b560d64d47ade35fcc389a10a19c", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1320, "license_type": "permissive", "max_line_length": 157, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_broadcast_domain.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Modify a ONTAP broadcast domain.\n class Na_ontap_broadcast_domain < Base\n # @return [:present, :absent, nil] Whether the specified broadcast domain should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] Specify the broadcast_domain name\n attribute :broadcast_domain\n validates :broadcast_domain, presence: true, type: String\n\n # @return [String, nil] Specify the required mtu for the broadcast domain\n attribute :mtu\n validates :mtu, type: String\n\n # @return [String, nil] Specify the required ipspace for the broadcast domain.,A domain ipspace can not be modified after the domain has been created\n attribute :ipspace\n validates :ipspace, type: String\n\n # @return [Array<String>, String, nil] Specify the ports associated with this broadcast domain. Should be comma separated\n attribute :ports\n validates :ports, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6653963327407837, "alphanum_fraction": 0.6653963327407837, "avg_line_length": 45.03508758544922, "blob_id": "1022afa0d4d807ee99e1533924288c8232d96343", "content_id": "be1dd1d5be78046d7fe3995bb7d625b68ae999b1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2624, "license_type": "permissive", "max_line_length": 169, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_containerinstance.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and delete an Azure Container Instance.\n class Azure_rm_containerinstance < Base\n # @return [String] Name of resource group.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] The name of the container group.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:linux, :windows, nil] The OS type of containers.\n attribute :os_type\n validates :os_type, expression_inclusion: {:in=>[:linux, :windows], :message=>\"%{value} needs to be :linux, :windows\"}, allow_nil: true\n\n # @return [:absent, :present, nil] Assert the state of the container instance. Use 'present' to create or update an container instance and 'absent' to delete it.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:public, :none, nil] The IP address type of the container group (default is 'none')\n attribute :ip_address\n validates :ip_address, expression_inclusion: {:in=>[:public, :none], :message=>\"%{value} needs to be :public, :none\"}, allow_nil: true\n\n # @return [Array<Integer>, Integer, nil] List of ports exposed within the container group.\n attribute :ports\n validates :ports, type: TypeGeneric.new(Integer)\n\n # @return [Object, nil] Valid azure location. Defaults to location of the resource group.\n attribute :location\n\n # @return [Object, nil] The container image registry login server.\n attribute :registry_login_server\n\n # @return [Object, nil] The username to log in container image registry server.\n attribute :registry_username\n\n # @return [Object, nil] The password to log in container image registry server.\n attribute :registry_password\n\n # @return [Array<Hash>, Hash, nil] List of containers.\n attribute :containers\n validates :containers, type: TypeGeneric.new(Hash)\n\n # @return [:yes, :no, nil] Force update of existing container instance. Any update will result in deletion and recreation of existing containers.\n attribute :force_update\n validates :force_update, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6747496128082275, "alphanum_fraction": 0.6784396171569824, "avg_line_length": 46.42499923706055, "blob_id": "fa9507c670bcd258b0175a18d12b2e3ea47b3abe", "content_id": "bc27d266ff802882be3a6307bd6a9e2019994f6a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1897, "license_type": "permissive", "max_line_length": 482, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_snmp_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages SNMP user configuration.\n class Nxos_snmp_user < Base\n # @return [String] Name of the user.\n attribute :user\n validates :user, presence: true, type: String\n\n # @return [String, nil] Group to which the user will belong to. If state = present, and the user is existing, the group is added to the user. If the user is not existing, user entry is created with this group argument. If state = absent, only the group is removed from the user entry. However, to maintain backward compatibility, if the existing user belongs to only one group, and if group argument is same as the existing user's group, then the user entry also is deleted.\n attribute :group\n validates :group, type: String\n\n # @return [:md5, :sha, nil] Authentication parameters for the user.\n attribute :authentication\n validates :authentication, expression_inclusion: {:in=>[:md5, :sha], :message=>\"%{value} needs to be :md5, :sha\"}, allow_nil: true\n\n # @return [String, nil] Authentication password when using md5 or sha. This is not idempotent\n attribute :pwd\n validates :pwd, type: String\n\n # @return [Object, nil] Privacy password for the user. This is not idempotent\n attribute :privacy\n\n # @return [Symbol, nil] Enables AES-128 bit encryption when using privacy password.\n attribute :encrypt\n validates :encrypt, type: Symbol\n\n # @return [:present, :absent, nil] Manage the state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6773102879524231, "alphanum_fraction": 0.6773102879524231, "avg_line_length": 58.155555725097656, "blob_id": "487756dce9ab5a0a30edd6349f179eba70a14286", "content_id": "fdc8ee66dc0022410114a19915d523bb285dde37", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2662, "license_type": "permissive", "max_line_length": 239, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/files/patch.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Apply patch files using the GNU patch tool.\n class Patch < Base\n # @return [String, nil] Path of a base directory in which the patch file will be applied. May be omitted when C(dest) option is specified, otherwise required.\n attribute :basedir\n validates :basedir, type: String\n\n # @return [String, nil] Path of the file on the remote machine to be patched.,The names of the files to be patched are usually taken from the patch file, but if there's just one file to be patched it can specified with this option.\n attribute :dest\n validates :dest, type: String\n\n # @return [String] Path of the patch file as accepted by the GNU patch tool. If C(remote_src) is 'no', the patch source file is looked up from the module's I(files) directory.\n attribute :src\n validates :src, presence: true, type: String\n\n # @return [:absent, :present, nil] Whether the patch should be applied or reverted.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), it will search for src at originating/master machine, if C(yes) it will go to the remote/target machine for the C(src).\n attribute :remote_src\n validates :remote_src, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Number that indicates the smallest prefix containing leading slashes that will be stripped from each file name found in the patch file. For more information see the strip parameter of the GNU patch tool.\n attribute :strip\n validates :strip, type: Integer\n\n # @return [:yes, :no, nil] Passes C(--backup --version-control=numbered) to patch, producing numbered backup copies.\n attribute :backup\n validates :backup, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Setting to C(yes) will disable patch's heuristic for transforming CRLF line endings into LF. Line endings of src and dest must match. If set to C(no), C(patch) will replace CRLF in C(src) files on POSIX.\n attribute :binary\n validates :binary, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7053045034408569, "alphanum_fraction": 0.7056319713592529, "avg_line_length": 61.32653045654297, "blob_id": "754c2bb6c687b146b2a51e8d975ffa92bbace204", "content_id": "9bd759322b895f34bb2d841e2d1f9cf2658f06e3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3054, "license_type": "permissive", "max_line_length": 619, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/cloud/docker/docker_network.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create/remove Docker networks and connect containers to them.\n # Performs largely the same function as the \"docker network\" CLI subcommand.\n class Docker_network < Base\n # @return [String] Name of the network to operate on.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Array<String>, String, nil] List of container names or container IDs to connect to a network.\n attribute :connected\n validates :connected, type: TypeGeneric.new(String)\n\n # @return [String, nil] Specify the type of network. Docker provides bridge and overlay drivers, but 3rd party drivers can also be used.\n attribute :driver\n validates :driver, type: String\n\n # @return [Hash, nil] Dictionary of network settings. Consult docker docs for valid options and values.\n attribute :driver_options\n validates :driver_options, type: Hash\n\n # @return [:yes, :no, nil] With state I(absent) forces disconnecting all containers from the network prior to deleting the network. With state I(present) will disconnect all containers, delete the network and re-create the network. This option is required if you have changed the IPAM or driver options and want an existing network to be updated to use the new options.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] By default the connected list is canonical, meaning containers not on the list are removed from the network. Use C(appends) to leave existing containers connected.\n attribute :appends\n validates :appends, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Specify an IPAM driver.\n attribute :ipam_driver\n\n # @return [Hash, nil] Dictionary of IPAM options.\n attribute :ipam_options\n validates :ipam_options, type: Hash\n\n # @return [:absent, :present, nil] I(absent) deletes the network. If a network has connected containers, it cannot be deleted. Use the C(force) option to disconnect all containers and delete the network.,I(present) creates the network, if it does not already exist with the specified parameters, and connects the list of containers provided via the connected parameter. Containers not on the list will be disconnected. An empty list will leave no containers connected to the network. Use the C(appends) option to leave existing containers connected. Use the C(force) options to force re-creation of the network.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6879475116729736, "alphanum_fraction": 0.6915274262428284, "avg_line_length": 62.24528121948242, "blob_id": "2d88bdb4d7d64e37d24e5f6ae41393440922ab50", "content_id": "2ef470c6335e7537b75d2735e017750b0aedb268", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3352, "license_type": "permissive", "max_line_length": 554, "num_lines": 53, "path": "/lib/ansible/ruby/modules/generated/system/solaris_zone.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, start, stop and delete Solaris zones. This module doesn't currently allow changing of options for a zone that's already been created.\n class Solaris_zone < Base\n # @return [:absent, :attached, :configured, :detached, :installed, :present, :running, :started, :stopped] C(present), configure and install the zone.,C(installed), synonym for C(present).,C(running), if the zone already exists, boot it, otherwise, configure and install the zone first, then boot it.,C(started), synonym for C(running).,C(stopped), shutdown a zone.,C(absent), destroy the zone.,C(configured), configure the ready so that it's to be attached.,C(attached), attach a zone, but do not boot it.,C(detached), shutdown and detach a zone\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:absent, :attached, :configured, :detached, :installed, :present, :running, :started, :stopped], :message=>\"%{value} needs to be :absent, :attached, :configured, :detached, :installed, :present, :running, :started, :stopped\"}\n\n # @return [String] Zone name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The path where the zone will be created. This is required when the zone is created, but not used otherwise.\n attribute :path\n validates :path, type: String\n\n # @return [:yes, :no, nil] Whether to create a sparse (C(true)) or whole root (C(false)) zone.\n attribute :sparse\n validates :sparse, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] The password hash for the root account. If not specified, the zone's root account will not have a password.\n attribute :root_password\n validates :root_password, type: String\n\n # @return [String, nil] The zonecfg configuration commands for this zone. See zonecfg(1M) for the valid options and syntax. Typically this is a list of options separated by semi-colons or new lines, e.g. \"set auto-boot=true;add net;set physical=bge0;set address=10.1.1.1;end\"\n attribute :config\n validates :config, type: String\n\n # @return [String, nil] Extra options to the zonecfg(1M) create command.\n attribute :create_options\n validates :create_options, type: String\n\n # @return [String, nil] Extra options to the zoneadm(1M) install command. To automate Solaris 11 zone creation, use this to specify the profile XML file, e.g. install_options=\"-c sc_profile.xml\"\n attribute :install_options\n validates :install_options, type: String\n\n # @return [String, nil] Extra options to the zoneadm attach command. For example, this can be used to specify whether a minimum or full update of packages is required and if any packages need to be deleted. For valid values, see zoneadm(1M)\n attribute :attach_options\n validates :attach_options, type: String\n\n # @return [Integer, nil] Timeout, in seconds, for zone to boot.\n attribute :timeout\n validates :timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5581682920455933, "alphanum_fraction": 0.5693069100379944, "avg_line_length": 20.263158798217773, "blob_id": "eb167f20c139a1cb455623c5f0ed879b4df01090", "content_id": "30b6d62c084535d8947b59c33d5e0570ad61b5af", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 808, "license_type": "permissive", "max_line_length": 97, "num_lines": 38, "path": "/lib/ansible/ruby/modules/base_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'spec_helper'\nrequire 'ansible-ruby'\nrequire 'ansible/ruby/modules/base'\n\ndescribe Ansible::Ruby::Modules::Base do\n before do\n stub_const('Ansible::Ruby::Modules::Ec2', module_klass)\n end\n\n let(:module_klass) do\n Class.new(Ansible::Ruby::Modules::Base) do\n attribute :foo\n validates :foo, presence: true\n end\n end\n\n subject { instance.to_h }\n\n let(:instance) { module_klass.new(foo: 123) }\n\n it do\n is_expected.to eq(ec2: {\n foo: 123\n })\n end\n\n context 'jinja' do\n let(:instance) { module_klass.new(foo: Ansible::Ruby::Models::JinjaExpression.new('howdy')) }\n\n it do\n is_expected.to eq(ec2: {\n foo: '{{ howdy }}'\n })\n end\n end\nend\n" }, { "alpha_fraction": 0.6696212887763977, "alphanum_fraction": 0.6704270839691162, "avg_line_length": 37.78125, "blob_id": "809d4ce5f73f8c75ca3bdc806d3111873ec37cd7", "content_id": "96a35c244b813905be011a63ec36304585ffb773", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1241, "license_type": "permissive", "max_line_length": 160, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_lc_find.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Returns list of matching Launch Configurations for a given name, along with other useful information\n # Results can be sorted and sliced\n # It depends on boto\n # Based on the work by Tom Bamford (https://github.com/tombamford)\n class Ec2_lc_find < Base\n # @return [Object] The AWS region to use.\n attribute :region\n validates :region, presence: true\n\n # @return [String] A Launch Configuration to match,It'll be compiled as regex\n attribute :name_regex\n validates :name_regex, presence: true, type: String\n\n # @return [:ascending, :descending, nil] Order in which to sort results.\n attribute :sort_order\n validates :sort_order, expression_inclusion: {:in=>[:ascending, :descending], :message=>\"%{value} needs to be :ascending, :descending\"}, allow_nil: true\n\n # @return [Integer, nil] How many results to show.,Corresponds to Python slice notation like list[:limit].\n attribute :limit\n validates :limit, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6788055300712585, "alphanum_fraction": 0.6824471950531006, "avg_line_length": 46.344825744628906, "blob_id": "9e707a65da5dfcc4df49ed488c593d9fab65ad8c", "content_id": "06bc3838efe9656b637dfd8ef9c8f0305e209e1e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1373, "license_type": "permissive", "max_line_length": 371, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/windows/win_msg.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Wraps the msg.exe command in order to send messages to Windows hosts.\n class Win_msg < Base\n # @return [String, nil] Who to send the message to. Can be a username, sessionname or sessionid.\n attribute :to\n validates :to, type: String\n\n # @return [Integer, nil] How long to wait for receiver to acknowledge message, in seconds.\n attribute :display_seconds\n validates :display_seconds, type: Integer\n\n # @return [:yes, :no, nil] Whether to wait for users to respond. Module will only wait for the number of seconds specified in display_seconds or 10 seconds if not specified. However, if I(wait) is C(yes), the message is sent to each logged on user in turn, waiting for the user to either press 'ok' or for the timeout to elapse before moving on to the next user.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] The text of the message to be displayed.,The message must be less than 256 characters.\n attribute :msg\n validates :msg, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6889975666999817, "alphanum_fraction": 0.6889975666999817, "avg_line_length": 42.51063919067383, "blob_id": "d0ed98d642019dfaaafc8eb352a7ac1909f4e635", "content_id": "c08499f8508bd34c170044616b50086d875465b4", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2045, "license_type": "permissive", "max_line_length": 143, "num_lines": 47, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_cluster_peer.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create/Delete cluster peer relations on ONTAP\n class Na_ontap_cluster_peer < Base\n # @return [:present, :absent, nil] Whether the specified cluster peer should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Intercluster address of the source cluster.,Used as peer-address in destination cluster.\n attribute :source_intercluster_lif\n validates :source_intercluster_lif, type: String\n\n # @return [String, nil] Intercluster address of the destination cluster.,Used as peer-address in source cluster.\n attribute :dest_intercluster_lif\n validates :dest_intercluster_lif, type: String\n\n # @return [String, nil] The arbitrary passphrase that matches the one given to the peer cluster.\n attribute :passphrase\n validates :passphrase, type: String\n\n # @return [String, nil] The name of the source cluster name in the peer relation to be deleted.\n attribute :source_cluster_name\n validates :source_cluster_name, type: String\n\n # @return [String, nil] The name of the destination cluster name in the peer relation to be deleted.\n attribute :dest_cluster_name\n validates :dest_cluster_name, type: String\n\n # @return [String] Destination cluster IP or hostname which needs to be peered.\n attribute :dest_hostname\n validates :dest_hostname, presence: true, type: String\n\n # @return [Object, nil] Destination username.,Optional if this is same as source username.\n attribute :dest_username\n\n # @return [Object, nil] Destination password.,Optional if this is same as source password.\n attribute :dest_password\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6721498966217041, "alphanum_fraction": 0.6822023987770081, "avg_line_length": 63.367645263671875, "blob_id": "73745d2636a09e1842656ffc86dd72dcd221595d", "content_id": "b073c07c442e60b4d1a0c69bed07286ad0f4a7d0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4377, "license_type": "permissive", "max_line_length": 370, "num_lines": 68, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_static_binding_to_epg.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Bind static paths to EPGs on Cisco ACI fabrics.\n class Aci_static_binding_to_epg < Base\n # @return [String, nil] Name of an existing tenant.\n attribute :tenant\n validates :tenant, type: String\n\n # @return [String, nil] Name of an existing application network profile, that will contain the EPGs.\n attribute :ap\n validates :ap, type: String\n\n # @return [String, nil] The name of the end point group.\n attribute :epg\n validates :epg, type: String\n\n # @return [Object, nil] Description for the static path to EPG binding.\n attribute :description\n\n # @return [Integer, nil] The encapsulation ID associating the C(epg) with the interface path.,This acts as the secondary C(encap_id) when using micro-segmentation.,Accepted values are any valid encap ID for specified encap, currently ranges between C(1) and C(4096).\n attribute :encap_id\n validates :encap_id, type: Integer\n\n # @return [Integer, nil] Determines the primary encapsulation ID associating the C(epg) with the interface path when using micro-segmentation.,Accepted values are any valid encap ID for specified encap, currently ranges between C(1) and C(4096).\n attribute :primary_encap_id\n validates :primary_encap_id, type: Integer\n\n # @return [:immediate, :lazy, nil] The Deployement Immediacy of Static EPG on PC, VPC or Interface.,The APIC defaults to C(lazy) when unset during creation.\n attribute :deploy_immediacy\n validates :deploy_immediacy, expression_inclusion: {:in=>[:immediate, :lazy], :message=>\"%{value} needs to be :immediate, :lazy\"}, allow_nil: true\n\n # @return [:\"802.1p\", :access, :native, :regular, :tagged, :trunk, :untagged, nil] Determines how layer 2 tags will be read from and added to frames.,Values C(802.1p) and C(native) are identical.,Values C(access) and C(untagged) are identical.,Values C(regular), C(tagged) and C(trunk) are identical.,The APIC defaults to C(trunk) when unset during creation.\n attribute :interface_mode\n validates :interface_mode, expression_inclusion: {:in=>[:\"802.1p\", :access, :native, :regular, :tagged, :trunk, :untagged], :message=>\"%{value} needs to be :\\\"802.1p\\\", :access, :native, :regular, :tagged, :trunk, :untagged\"}, allow_nil: true\n\n # @return [:fex, :port_channel, :switch_port, :vpc, nil] The type of interface for the static EPG deployement.\n attribute :interface_type\n validates :interface_type, expression_inclusion: {:in=>[:fex, :port_channel, :switch_port, :vpc], :message=>\"%{value} needs to be :fex, :port_channel, :switch_port, :vpc\"}, allow_nil: true\n\n # @return [Integer, nil] The pod number part of the tDn.,C(pod_id) is usually an integer below C(10).\n attribute :pod_id\n validates :pod_id, type: Integer\n\n # @return [Integer, nil] The switch ID(s) that the C(interface) belongs to.,When C(interface_type) is C(switch_port), C(port_channel), or C(fex), then C(leafs) is a string of the leaf ID.,When C(interface_type) is C(vpc), then C(leafs) is a list with both leaf IDs.,The C(leafs) value is usually something like '101' or '101-102' depending on C(connection_type).\n attribute :leafs\n validates :leafs, type: Integer\n\n # @return [String, nil] The C(interface) string value part of the tDn.,Usually a policy group like C(test-IntPolGrp) or an interface of the following format C(1/7) depending on C(interface_type).\n attribute :interface\n validates :interface, type: String\n\n # @return [Integer, nil] The C(extpaths) integer value part of the tDn.,C(extpaths) is only used if C(interface_type) is C(fex).,Usually something like C(1011).\n attribute :extpaths\n validates :extpaths, type: Integer\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6722232103347778, "alphanum_fraction": 0.6723986864089966, "avg_line_length": 54.8725471496582, "blob_id": "781dd6ab39220d8588d79ec7b9e0edab17db22d7", "content_id": "e8ded5630449ed922b7ac2264c3b2026234b2908", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5699, "license_type": "permissive", "max_line_length": 330, "num_lines": 102, "path": "/lib/ansible/ruby/modules/generated/cloud/rackspace/rax.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # creates / deletes a Rackspace Public Cloud instance and optionally waits for it to be 'running'.\n class Rax < Base\n # @return [:yes, :no, nil] Whether or not to increment a single number with the name of the created servers. Only applicable when used with the I(group) attribute or meta key.\n attribute :auto_increment\n validates :auto_increment, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Whether or not to boot the instance from a Cloud Block Storage volume. If C(yes) and I(image) is specified a new volume will be created at boot time. I(boot_volume_size) is required with I(image) to create a new volume at boot time.\n attribute :boot_from_volume\n validates :boot_from_volume, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Cloud Block Storage ID or Name to use as the boot volume of the instance\n attribute :boot_volume\n\n # @return [Integer, nil] Size of the volume to create in Gigabytes. This is only required with I(image) and I(boot_from_volume).\n attribute :boot_volume_size\n validates :boot_volume_size, type: Integer\n\n # @return [:yes, :no, nil] Whether the I(boot_volume) or newly created volume from I(image) will be terminated when the server is terminated\n attribute :boot_volume_terminate\n validates :boot_volume_terminate, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Attach read-only configuration drive to server as label config-2\n attribute :config_drive\n validates :config_drive, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] number of instances to launch\n attribute :count\n validates :count, type: Integer\n\n # @return [Integer, nil] number count to start at\n attribute :count_offset\n validates :count_offset, type: Integer\n\n # @return [:auto, :manual, nil] Disk partitioning strategy\n attribute :disk_config\n validates :disk_config, expression_inclusion: {:in=>[:auto, :manual], :message=>\"%{value} needs to be :auto, :manual\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Explicitly ensure an exact count of instances, used with state=active/present. If specified as C(yes) and I(count) is less than the servers matched, servers will be deleted to match the count. If the number of matched servers is fewer than specified in I(count) additional servers will be added.\n attribute :exact_count\n validates :exact_count, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] A hash of key/value pairs to be used when creating the cloudservers client. This is considered an advanced option, use it wisely and with caution.\n attribute :extra_client_args\n\n # @return [Object, nil] A hash of key/value pairs to be used when creating a new server. This is considered an advanced option, use it wisely and with caution.\n attribute :extra_create_args\n\n # @return [Object, nil] Files to insert into the instance. remotefilename:localcontent\n attribute :files\n\n # @return [Object, nil] flavor to use for the instance\n attribute :flavor\n\n # @return [Object, nil] host group to assign to server, is also used for idempotent operations to ensure a specific number of instances\n attribute :group\n\n # @return [Object, nil] image to use for the instance. Can be an C(id), C(human_id) or C(name). With I(boot_from_volume), a Cloud Block Storage volume will be created with this image\n attribute :image\n\n # @return [Object, nil] list of instance ids, currently only used when state='absent' to remove instances\n attribute :instance_ids\n\n # @return [Object, nil] key pair to use on the instance\n attribute :key_name\n\n # @return [Object, nil] A hash of metadata to associate with the instance\n attribute :meta\n\n # @return [String, nil] Name to give the instance\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] The network to attach to the instances. If specified, you must include ALL networks including the public and private interfaces. Can be C(id) or C(label).\n attribute :networks\n validates :networks, type: String\n\n # @return [:present, :absent, nil] Indicate desired state of the resource\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Data to be uploaded to the servers config drive. This option implies I(config_drive). Can be a file path or a string\n attribute :user_data\n\n # @return [:yes, :no, nil] wait for the instance to be in state 'running' before returning\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] how long before wait gives up, in seconds\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6283643841743469, "alphanum_fraction": 0.6475155353546143, "avg_line_length": 40.10638427734375, "blob_id": "e1780fc6fffc335190f8ba3f8c32d9620bcfff87", "content_id": "bb5531b36977ea0065f5bfefe0b91122c415c2af", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1932, "license_type": "permissive", "max_line_length": 220, "num_lines": 47, "path": "/lib/ansible/ruby/modules/generated/network/fortios/fortios_address.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provide management of firewall addresses on FortiOS devices.\n class Fortios_address < Base\n # @return [:present, :absent] Specifies if address need to be added or deleted.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String] Name of the address to add or delete.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:iprange, :fqdn, :ipmask, :geography, nil] Type of the address.\n attribute :type\n validates :type, expression_inclusion: {:in=>[:iprange, :fqdn, :ipmask, :geography], :message=>\"%{value} needs to be :iprange, :fqdn, :ipmask, :geography\"}, allow_nil: true\n\n # @return [String, nil] Address value, based on type. If type=fqdn, somthing like www.google.com. If type=ipmask, you can use simple ip (192.168.0.1), ip+mask (192.168.0.1 255.255.255.0) or CIDR (192.168.0.1/32).\n attribute :value\n validates :value, type: String\n\n # @return [Object, nil] First ip in range (used only with type=iprange).\n attribute :start_ip\n\n # @return [Object, nil] Last ip in range (used only with type=iprange).\n attribute :end_ip\n\n # @return [String, nil] 2 letter country code (like FR).\n attribute :country\n validates :country, type: String\n\n # @return [String, nil] interface name the address apply to.\n attribute :interface\n validates :interface, type: String\n\n # @return [String, nil] free text to describe address.\n attribute :comment\n validates :comment, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6390899419784546, "alphanum_fraction": 0.645294725894928, "avg_line_length": 48.589744567871094, "blob_id": "63f7180b81985570fd8d914871da87214430d7fc", "content_id": "bdda9333382fd8a786b789e5c712c534436ade90", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1934, "license_type": "permissive", "max_line_length": 249, "num_lines": 39, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_dns_resource_record_set.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # A single DNS record that exists on a domain name (i.e. in a managed zone).\n # This record defines the information about the domain and where the domain / subdomains direct to.\n # The record will include the domain/subdomain name, a type (i.e. A, AAA, CAA, MX, CNAME, NS, etc) .\n class Gcp_dns_resource_record_set < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] For example, U(www.example.com.)\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:A, :AAAA, :CAA, :CNAME, :MX, :NAPTR, :NS, :PTR, :SOA, :SPF, :SRV, :TXT] One of valid DNS resource types.\n attribute :type\n validates :type, presence: true, expression_inclusion: {:in=>[:A, :AAAA, :CAA, :CNAME, :MX, :NAPTR, :NS, :PTR, :SOA, :SPF, :SRV, :TXT], :message=>\"%{value} needs to be :A, :AAAA, :CAA, :CNAME, :MX, :NAPTR, :NS, :PTR, :SOA, :SPF, :SRV, :TXT\"}\n\n # @return [Integer, nil] Number of seconds that this ResourceRecordSet can be cached by resolvers.\n attribute :ttl\n validates :ttl, type: Integer\n\n # @return [Array<String>, String, nil] As defined in RFC 1035 (section 5) and RFC 1034 (section 3.6.1) .\n attribute :target\n validates :target, type: TypeGeneric.new(String)\n\n # @return [String] Identifies the managed zone addressed by this request.,Can be the managed zone name or id.\n attribute :managed_zone\n validates :managed_zone, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6743097901344299, "alphanum_fraction": 0.6743097901344299, "avg_line_length": 43.52083206176758, "blob_id": "875fab91bb0a3af2fdbb4d7d422bfe435686ab59", "content_id": "25df3ffbe41008e4958d010760b5c03e68255b82", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2137, "license_type": "permissive", "max_line_length": 542, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_networks.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Module to manage logical networks in oVirt/RHV\n class Ovirt_network < Base\n # @return [String] Name of the network to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Should the network be present or absent\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Datacenter name where network reside.\n attribute :data_center\n validates :data_center, type: String\n\n # @return [Object, nil] Description of the network.\n attribute :description\n\n # @return [Object, nil] Comment of the network.\n attribute :comment\n\n # @return [Integer, nil] Specify VLAN tag.\n attribute :vlan_tag\n validates :vlan_tag, type: Integer\n\n # @return [Symbol, nil] If I(True) network will be marked as network for VM.,VM network carries traffic relevant to the virtual machine.\n attribute :vm_network\n validates :vm_network, type: Symbol\n\n # @return [Object, nil] Maximum transmission unit (MTU) of the network.\n attribute :mtu\n\n # @return [Object, nil] List of dictionaries describing how the network is managed in specific cluster.,C(name) - Cluster name.,C(assigned) - I(true) if the network should be assigned to cluster. Default is I(true).,C(required) - I(true) if the network must remain operational for all hosts associated with this network.,C(display) - I(true) if the network should marked as display network.,C(migration) - I(true) if the network should marked as migration network.,C(gluster) - I(true) if the network should marked as gluster network.\n attribute :clusters\n\n # @return [Object, nil] Name of the label to assign to the network.\n attribute :label\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6596558094024658, "alphanum_fraction": 0.6596558094024658, "avg_line_length": 41.86885070800781, "blob_id": "2a045553fa0c4c61223a51cb8db59a351264b1d7", "content_id": "56f06c114a5959056ad6e3520a4cc681d0da7e80", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2615, "license_type": "permissive", "max_line_length": 189, "num_lines": 61, "path": "/lib/ansible/ruby/modules/generated/packaging/language/gem.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage installation and uninstallation of Ruby gems.\n class Gem < Base\n # @return [String] The name of the gem to be managed.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, :latest, nil] The desired state of the gem. C(latest) ensures that the latest version is installed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :latest], :message=>\"%{value} needs to be :present, :absent, :latest\"}, allow_nil: true\n\n # @return [String, nil] The path to a local gem used as installation source.\n attribute :gem_source\n validates :gem_source, type: String\n\n # @return [:yes, :no, nil] Whether to include dependencies or not.\n attribute :include_dependencies\n validates :include_dependencies, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] The repository from which the gem will be installed\n attribute :repository\n\n # @return [:yes, :no, nil] Install gem in user's local gems cache or for all users\n attribute :user_install\n validates :user_install, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Override the path to the gem executable\n attribute :executable\n\n # @return [Object, nil] Install the gems into a specific directory. These gems will be independant from the global installed ones. Specifying this requires user_install to be false.\n attribute :install_dir\n\n # @return [String, nil] Rewrite the shebang line on installed scripts to use /usr/bin/env.\n attribute :env_shebang\n validates :env_shebang, type: String\n\n # @return [Float, nil] Version of the gem to be installed/removed.\n attribute :version\n validates :version, type: Float\n\n # @return [String, nil] Allow installation of pre-release versions of the gem.\n attribute :pre_release\n validates :pre_release, type: String\n\n # @return [String, nil] Install with or without docs.\n attribute :include_doc\n validates :include_doc, type: String\n\n # @return [Object, nil] Allow adding build flags for gem compilation\n attribute :build_flags\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6878942847251892, "alphanum_fraction": 0.6930009126663208, "avg_line_length": 53.573768615722656, "blob_id": "f783ddcd3899fdf71b2f4e166f383f58f2d2ebe1", "content_id": "9c783bb977ce5e1b9e018aa3041b3b5c77e526c6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3329, "license_type": "permissive", "max_line_length": 258, "num_lines": 61, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_interface_ospf.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages configuration of an OSPF interface instance.\n class Nxos_interface_ospf < Base\n # @return [String] Name of this cisco_interface resource. Valid value is a string.\n attribute :interface\n validates :interface, presence: true, type: String\n\n # @return [Integer] Name of the ospf instance.\n attribute :ospf\n validates :ospf, presence: true, type: Integer\n\n # @return [Integer] Ospf area associated with this cisco_interface_ospf instance. Valid values are a string, formatted as an IP address (i.e. \"0.0.0.0\") or as an integer.\n attribute :area\n validates :area, presence: true, type: Integer\n\n # @return [String, nil] The cost associated with this cisco_interface_ospf instance.\n attribute :cost\n validates :cost, type: String\n\n # @return [Object, nil] Time between sending successive hello packets. Valid values are an integer or the keyword 'default'.\n attribute :hello_interval\n\n # @return [Object, nil] Time interval an ospf neighbor waits for a hello packet before tearing down adjacencies. Valid values are an integer or the keyword 'default'.\n attribute :dead_interval\n\n # @return [Symbol, nil] Setting to true will prevent this interface from receiving HELLO packets.\n attribute :passive_interface\n validates :passive_interface, type: Symbol\n\n # @return [Symbol, nil] Enables or disables the usage of message digest authentication.\n attribute :message_digest\n validates :message_digest, type: Symbol\n\n # @return [Object, nil] Md5 authentication key-id associated with the ospf instance. If this is present, message_digest_encryption_type, message_digest_algorithm_type and message_digest_password are mandatory. Valid value is an integer and 'default'.\n attribute :message_digest_key_id\n\n # @return [:md5, :default, nil] Algorithm used for authentication among neighboring routers within an area. Valid values are 'md5' and 'default'.\n attribute :message_digest_algorithm_type\n validates :message_digest_algorithm_type, expression_inclusion: {:in=>[:md5, :default], :message=>\"%{value} needs to be :md5, :default\"}, allow_nil: true\n\n # @return [:cisco_type_7, :\"3des\", :default, nil] Specifies the scheme used for encrypting message_digest_password. Valid values are '3des' or 'cisco_type_7' encryption or 'default'.\n attribute :message_digest_encryption_type\n validates :message_digest_encryption_type, expression_inclusion: {:in=>[:cisco_type_7, :\"3des\", :default], :message=>\"%{value} needs to be :cisco_type_7, :\\\"3des\\\", :default\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the message_digest password. Valid value is a string.\n attribute :message_digest_password\n\n # @return [:present, :absent, nil] Determines whether the config should be present or not on the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6153846383094788, "alphanum_fraction": 0.6342229247093201, "avg_line_length": 22.592592239379883, "blob_id": "4a322ed902bf3850fe04113ba25e7d4c807ebaf6", "content_id": "6595aafa81d90e1f23549a7f146c2b336d4c5b77", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 637, "license_type": "permissive", "max_line_length": 96, "num_lines": 27, "path": "/examples/image_copy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nplay 'image copy' do\n local_host\n\n # Task returns a lazy 'register variable'\n # When it's used in further tasks, it will enable 'register' on the task it came from\n result = task 'image copy' do\n ec2_ami_copy do\n source_region 'us-east-1'\n source_image_id 'ami-1b9e2570'\n name 'test'\n wait :no\n tags type: 'ansible',\n test: '2'\n end\n end\n\n tags :foo_123\n\n task 'foobar' do\n debug { msg 'say hello' }\n\n # compiles to 'when', the ansible_ prefix is necessary since when is a reserved word in Ruby\n ansible_when \"'stuff' in #{result.stdout}\"\n end\nend\n" }, { "alpha_fraction": 0.7374149560928345, "alphanum_fraction": 0.7374149560928345, "avg_line_length": 75.03448486328125, "blob_id": "ee3f9b71a76b82f602e85a2412094617f582b874", "content_id": "0c1b06876e8bc901f68605cde9bd70033e2a1add", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2205, "license_type": "permissive", "max_line_length": 705, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_appsvcs_extension.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages application service deployments via the App Services Extension functionality in BIG-IP.\n class Bigip_appsvcs_extension < Base\n # @return [String] Declaration of tenants configured on the system.,This parameter is most often used along with the C(file) or C(template) lookup plugins. Refer to the examples section for correct usage.,For anything advanced or with formatting consider using the C(template) lookup.,This can additionally be used for specifying application service configurations directly in YAML, however that is not an encouraged practice and, if used at all, should only be used for the absolute smallest of configurations to prevent your Playbooks from becoming too large.,If you C(content) includes encrypted values (such as ciphertexts, passphrases, etc), the returned C(changed) value will always be true.\n attribute :content\n validates :content, presence: true, type: String\n\n # @return [Array<String>, String, nil] A list of tenants that you want to remove.,This parameter is only relevant when C(state) is C(absent). It will be ignored when C(state) is C(present).,A value of C(all) will remove all tenants.,Tenants can be specified as a list as well to remove only specific tenants.\n attribute :tenants\n validates :tenants, type: TypeGeneric.new(String)\n\n # @return [Symbol, nil] Force updates a declaration.,This parameter should be used in cases where your declaration includes items that are encrypted or in cases (such as WAF Policies) where you want a large reload to take place.\n attribute :force\n validates :force, type: Symbol\n\n # @return [:present, :absent, nil] When C(state) is C(present), ensures the configuration exists.,When C(state) is C(absent), ensures that the configuration is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7008018493652344, "alphanum_fraction": 0.7021763920783997, "avg_line_length": 69.40322875976562, "blob_id": "8230719419c1b4f643b08346ffac9eda9145e587", "content_id": "2232e225d2181af7c0ddc82035f903afcded060a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4365, "license_type": "permissive", "max_line_length": 463, "num_lines": 62, "path": "/lib/ansible/ruby/modules/generated/windows/win_service.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage and query Windows services.\n # For non-Windows targets, use the M(service) module instead.\n class Win_service < Base\n # @return [Array<String>, String, nil] A list of service dependencies to set for this particular service.,This should be a list of service names and not the display name of the service.,This works by C(dependency_action) to either add/remove or set the services in this list.\n attribute :dependencies\n validates :dependencies, type: TypeGeneric.new(String)\n\n # @return [:add, :remove, :set, nil] Used in conjunction with C(dependency) to either add the dependencies to the existing service dependencies.,Remove the dependencies to the existing dependencies.,Set the dependencies to only the values in the list replacing the existing dependencies.\n attribute :dependency_action\n validates :dependency_action, expression_inclusion: {:in=>[:add, :remove, :set], :message=>\"%{value} needs to be :add, :remove, :set\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Whether to allow the service user to interact with the desktop.,This should only be set to C(yes) when using the LocalSystem username.\n attribute :desktop_interact\n validates :desktop_interact, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] The description to set for the service.\n attribute :description\n validates :description, type: String\n\n # @return [String, nil] The display name to set for the service.\n attribute :display_name\n validates :display_name, type: String\n\n # @return [:yes, :no, nil] If C(yes), stopping or restarting a service with dependent services will force the dependent services to stop or restart also.,If C(no), stopping or restarting a service with dependent services may fail.\n attribute :force_dependent_services\n validates :force_dependent_services, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String] Name of the service.,If only the name parameter is specified, the module will report on whether the service exists or not without making any changes.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The path to the executable to set for the service.\n attribute :path\n validates :path, type: String\n\n # @return [String, nil] The password to set the service to start as.,This and the C(username) argument must be supplied together.,If specifying LocalSystem, NetworkService or LocalService this field must be an empty string and not null.\n attribute :password\n validates :password, type: String\n\n # @return [:auto, :delayed, :disabled, :manual, nil] Set the startup type for the service.,C(delayed) added in Ansible 2.3\n attribute :start_mode\n validates :start_mode, expression_inclusion: {:in=>[:auto, :delayed, :disabled, :manual], :message=>\"%{value} needs to be :auto, :delayed, :disabled, :manual\"}, allow_nil: true\n\n # @return [:absent, :paused, :started, :stopped, :restarted, nil] C(started)/C(stopped)/C(absent)/C(pause) are idempotent actions that will not run commands unless necessary.,C(restarted) will always bounce the service.,C(absent) added in Ansible 2.3,C(pause) was added in Ansible 2.4,Only services that support the paused state can be paused, you can check the return value C(can_pause_and_continue).,You can only pause a service that is already started.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :paused, :started, :stopped, :restarted], :message=>\"%{value} needs to be :absent, :paused, :started, :stopped, :restarted\"}, allow_nil: true\n\n # @return [String, nil] The username to set the service to start as.,This and the C(password) argument must be supplied together when using a local or domain account.,Set to C(LocalSystem) to use the SYSTEM account.\n attribute :username\n validates :username, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7009943127632141, "alphanum_fraction": 0.7009943127632141, "avg_line_length": 55.31999969482422, "blob_id": "320079607d245ccca2a9d22118e547ab547f906e", "content_id": "90d9fb9004381d220ba2a07700b9e5508a6d5d48", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1408, "license_type": "permissive", "max_line_length": 409, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/windows/win_acl_inheritance.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Change ACL (Access Control List) inheritance and optionally copy inherited ACE's (Access Control Entry) to dedicated ACE's or vice versa.\n class Win_acl_inheritance < Base\n # @return [String] Path to be used for changing inheritance\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [:absent, :present, nil] Specify whether to enable I(present) or disable I(absent) ACL inheritance\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:yes, :no, nil] For P(state) = I(absent), indicates if the inherited ACE's should be copied from the parent directory. This is necessary (in combination with removal) for a simple ACL instead of using multiple ACE deny entries.,For P(state) = I(present), indicates if the inherited ACE's should be deduplicated compared to the parent directory. This removes complexity of the ACL structure.\n attribute :reorganize\n validates :reorganize, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6957983374595642, "alphanum_fraction": 0.6968067288398743, "avg_line_length": 62.29787063598633, "blob_id": "f412047f38f19565555b5e9e364323932fd3c845", "content_id": "2a83a896fcff2a53d40600a36fd5ee1403c315c4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2975, "license_type": "permissive", "max_line_length": 427, "num_lines": 47, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_storageaccount.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update or delete a storage account.\n class Azure_rm_storageaccount < Base\n # @return [String] Name of the resource group to use.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String, nil] Name of the storage account to update or create.\n attribute :name\n validates :name, type: String\n\n # @return [:absent, :present, nil] Assert the state of the storage account. Use 'present' to create or update a storage account and 'absent' to delete an account.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [Object, nil] Valid azure location. Defaults to location of the resource group.\n attribute :location\n\n # @return [:Premium_LRS, :Standard_GRS, :Standard_LRS, :StandardSSD_LRS, :Standard_RAGRS, :Standard_ZRS, nil] Type of storage account. Required when creating a storage account. NOTE: Standard_ZRS and Premium_LRS accounts cannot be changed to other account types, and other account types cannot be changed to Standard_ZRS or Premium_LRS.\n attribute :account_type\n validates :account_type, expression_inclusion: {:in=>[:Premium_LRS, :Standard_GRS, :Standard_LRS, :StandardSSD_LRS, :Standard_RAGRS, :Standard_ZRS], :message=>\"%{value} needs to be :Premium_LRS, :Standard_GRS, :Standard_LRS, :StandardSSD_LRS, :Standard_RAGRS, :Standard_ZRS\"}, allow_nil: true\n\n # @return [Object, nil] User domain assigned to the storage account. Must be a dictionary with 'name' and 'use_sub_domain' keys where 'name' is the CNAME source. Only one custom domain is supported per storage account at this time. To clear the existing custom domain, use an empty string for the custom domain name property.,Can be added to an existing storage account. Will be ignored during storage account creation.\n attribute :custom_domain\n\n # @return [:Storage, :StorageV2, :BlobStorage, nil] The 'kind' of storage.\n attribute :kind\n validates :kind, expression_inclusion: {:in=>[:Storage, :StorageV2, :BlobStorage], :message=>\"%{value} needs to be :Storage, :StorageV2, :BlobStorage\"}, allow_nil: true\n\n # @return [:Hot, :Cool, nil] The access tier for this storage account. Required for a storage account of kind 'BlobStorage'.\n attribute :access_tier\n validates :access_tier, expression_inclusion: {:in=>[:Hot, :Cool], :message=>\"%{value} needs to be :Hot, :Cool\"}, allow_nil: true\n\n # @return [Symbol, nil] Attempt deletion if resource already exists and cannot be updated\n attribute :force\n validates :force, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6505190134048462, "alphanum_fraction": 0.6505190134048462, "avg_line_length": 38.86206817626953, "blob_id": "9586c321fae3bed9a5bae090089fb6b396fcacd1", "content_id": "9c358d0e20336dabad758f9cdc604ed7998790e0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1156, "license_type": "permissive", "max_line_length": 183, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/packaging/os/macports.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages MacPorts packages (ports)\n class Macports < Base\n # @return [String] A list of port names.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, :active, :inactive, nil] Indicates the desired state of the port.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :active, :inactive], :message=>\"%{value} needs to be :present, :absent, :active, :inactive\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Update the ports tree first.\n attribute :update_ports\n validates :update_ports, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] A port variant specification.,C(variant) is only supported with state: I(installed)/I(present).\n attribute :variant\n validates :variant, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6879866719245911, "alphanum_fraction": 0.6935483813285828, "avg_line_length": 51.115943908691406, "blob_id": "f1f6a156331f08562964d5e1c74b65718a98fb59", "content_id": "e354e6814c4cc35f96a655fbc4d5b0d8c6b9b9d9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3596, "license_type": "permissive", "max_line_length": 516, "num_lines": 69, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gce_net.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can create and destroy Google Compute Engine networks and firewall rules U(https://cloud.google.com/compute/docs/networking). The I(name) parameter is reserved for referencing a network while the I(fwname) parameter is used to reference firewall rules. IPv4 Address ranges must be specified using the CIDR U(http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing) format. Full install/configuration instructions for the gce* modules can be found in the comments of ansible/test/gce_tests.py.\n class Gce_net < Base\n # @return [String, nil] the protocol:ports to allow (I(tcp:80) or I(tcp:80,443) or I(tcp:80-800;udp:1-25)) this parameter is mandatory when creating or updating a firewall rule\n attribute :allowed\n validates :allowed, type: String\n\n # @return [String, nil] the IPv4 address range in CIDR notation for the network this parameter is not mandatory when you specified existing network in name parameter, but when you create new network, this parameter is mandatory\n attribute :ipv4_range\n validates :ipv4_range, type: String\n\n # @return [String, nil] name of the firewall rule\n attribute :fwname\n validates :fwname, type: String\n\n # @return [String, nil] name of the network\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] the source IPv4 address range in CIDR notation\n attribute :src_range\n\n # @return [Object, nil] the source instance tags for creating a firewall rule\n attribute :src_tags\n\n # @return [Object, nil] the target instance tags for creating a firewall rule\n attribute :target_tags\n\n # @return [:active, :present, :absent, :deleted, nil] desired state of the network or firewall\n attribute :state\n validates :state, expression_inclusion: {:in=>[:active, :present, :absent, :deleted], :message=>\"%{value} needs to be :active, :present, :absent, :deleted\"}, allow_nil: true\n\n # @return [Object, nil] service account email\n attribute :service_account_email\n\n # @return [Object, nil] path to the pem file associated with the service account email This option is deprecated. Use C(credentials_file).\n attribute :pem_file\n\n # @return [Object, nil] path to the JSON file associated with the service account email\n attribute :credentials_file\n\n # @return [Object, nil] your GCE project ID\n attribute :project_id\n\n # @return [:legacy, :auto, :custom, nil] network mode for Google Cloud C(legacy) indicates a network with an IP address range; C(auto) automatically generates subnetworks in different regions; C(custom) uses networks to group subnets of user specified IP address ranges https://cloud.google.com/compute/docs/networking#network_types\n attribute :mode\n validates :mode, expression_inclusion: {:in=>[:legacy, :auto, :custom], :message=>\"%{value} needs to be :legacy, :auto, :custom\"}, allow_nil: true\n\n # @return [String, nil] name of subnet to create\n attribute :subnet_name\n validates :subnet_name, type: String\n\n # @return [String, nil] region of subnet to create\n attribute :subnet_region\n validates :subnet_region, type: String\n\n # @return [Object, nil] description of subnet to create\n attribute :subnet_desc\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7013574838638306, "alphanum_fraction": 0.7050838470458984, "avg_line_length": 69.88679504394531, "blob_id": "81775683cd67cadb5e7de7b8fb71c56fbfab18df", "content_id": "db371b2d93b290a28acf1f84fe8d924b8777947b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3757, "license_type": "permissive", "max_line_length": 301, "num_lines": 53, "path": "/lib/ansible/ruby/modules/generated/clustering/k8s/kubernetes.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can manage Kubernetes resources on an existing cluster using the Kubernetes server API. Users can specify in-line API data, or specify an existing Kubernetes YAML file.\n # Currently, this module (1) Only supports HTTP Basic Auth (2) Only supports 'strategic merge' for update, http://goo.gl/fCPYxT SSL certs are not working, use C(validate_certs=off) to disable.\n class Kubernetes < Base\n # @return [String] The IPv4 API endpoint of the Kubernetes cluster.\n attribute :api_endpoint\n validates :api_endpoint, presence: true, type: String\n\n # @return [Hash] The Kubernetes YAML data to send to the API I(endpoint). This option is mutually exclusive with C('file_reference').\n attribute :inline_data\n validates :inline_data, presence: true, type: Hash\n\n # @return [String, nil] Specify full path to a Kubernets YAML file to send to API I(endpoint). This option is mutually exclusive with C('inline_data').\n attribute :file_reference\n validates :file_reference, type: String\n\n # @return [:\"JSON Patch\", :\"Merge Patch\", :\"Strategic Merge Patch\", nil] Specify patch operation for Kubernetes resource update.,For details, see the description of PATCH operations at U(https://github.com/kubernetes/kubernetes/blob/release-1.5/docs/devel/api-conventions.md#patch-operations).\n attribute :patch_operation\n validates :patch_operation, expression_inclusion: {:in=>[:\"JSON Patch\", :\"Merge Patch\", :\"Strategic Merge Patch\"], :message=>\"%{value} needs to be :\\\"JSON Patch\\\", :\\\"Merge Patch\\\", :\\\"Strategic Merge Patch\\\"\"}, allow_nil: true\n\n # @return [Object, nil] Certificate Authority data for Kubernetes server. Should be in either standard PEM format or base64 encoded PEM data. Note that certificate verification is broken until ansible supports a version of 'match_hostname' that can match the IP address against the CA data.\n attribute :certificate_authority_data\n\n # @return [:absent, :present, :replace, :update] The desired action to take on the Kubernetes data.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:absent, :present, :replace, :update], :message=>\"%{value} needs to be :absent, :present, :replace, :update\"}\n\n # @return [String, nil] The HTTP Basic Auth password for the API I(endpoint). This should be set unless using the C('insecure') option.\n attribute :url_password\n validates :url_password, type: String\n\n # @return [String, nil] The HTTP Basic Auth username for the API I(endpoint). This should be set unless using the C('insecure') option.\n attribute :url_username\n validates :url_username, type: String\n\n # @return [Boolean, nil] Reverts the connection to using HTTP instead of HTTPS. This option should only be used when execuing the M('kubernetes') module local to the Kubernetes cluster using the insecure local port (locahost:8080 by default).\n attribute :insecure\n validates :insecure, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Enable/disable certificate validation. Note that this is set to C(false) until Ansible can support IP address based certificate hostname matching (exists in >= python3.5.0).\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 35, "blob_id": "499611e52955994a8bfb6069c725b8dbb315bbc7", "content_id": "dff9796641a3bb5d134c67b998624c4c78507449", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 756, "license_type": "permissive", "max_line_length": 145, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/ansible_tower/tower_job_cancel.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Cancel Ansible Tower jobs. See U(https://www.ansible.com/tower) for an overview.\n class Tower_job_cancel < Base\n # @return [String] ID of the job to cancel\n attribute :job_id\n validates :job_id, presence: true, type: String\n\n # @return [Boolean, nil] Fail loudly if the I(job_id) does not reference a running job.\n attribute :fail_if_not_running\n validates :fail_if_not_running, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6514138579368591, "alphanum_fraction": 0.6647815108299255, "avg_line_length": 47.625, "blob_id": "46547e79e55f6045666fb130191cdc1000bbdba1", "content_id": "5a945219188b79e3522ffe214d0ea6598e6b3485", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1945, "license_type": "permissive", "max_line_length": 160, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_vxlan_tunnel.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module offers the ability to set the VNI and mapped to the BD, and configure an ingress replication list on HUAWEI CloudEngine devices.\n class Ce_vxlan_tunnel < Base\n # @return [Object, nil] Specifies a bridge domain ID. The value is an integer ranging from 1 to 16777215.\n attribute :bridge_domain_id\n\n # @return [Object, nil] Specifies a VXLAN network identifier (VNI) ID. The value is an integer ranging from 1 to 16000000.\n attribute :vni_id\n\n # @return [Object, nil] Specifies the number of an NVE interface. The value ranges from 1 to 2.\n attribute :nve_name\n\n # @return [:\"mode-l2\", :\"mode-l3\", nil] Specifies the working mode of an NVE interface.\n attribute :nve_mode\n validates :nve_mode, expression_inclusion: {:in=>[:\"mode-l2\", :\"mode-l3\"], :message=>\"%{value} needs to be :\\\"mode-l2\\\", :\\\"mode-l3\\\"\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the IP address of a remote VXLAN tunnel endpoints (VTEP). The value is in dotted decimal notation.\n attribute :peer_list_ip\n\n # @return [:bgp, :null, nil] The operation type of routing protocol.\n attribute :protocol_type\n validates :protocol_type, expression_inclusion: {:in=>[:bgp, :null], :message=>\"%{value} needs to be :bgp, :null\"}, allow_nil: true\n\n # @return [Object, nil] Specifies an IP address for a source VTEP. The value is in dotted decimal notation.\n attribute :source_ip\n\n # @return [:present, :absent, nil] Manage the state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6791259050369263, "alphanum_fraction": 0.6802760362625122, "avg_line_length": 41.414634704589844, "blob_id": "a1102f67305f7f52415cfbf54ae2598ccf0a4cee", "content_id": "5bda9391104631da932f7b03f8d27863819c0936", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1739, "license_type": "permissive", "max_line_length": 192, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/monitoring/zabbix/zabbix_template.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # create/delete/dump zabbix template\n class Zabbix_template < Base\n # @return [String] Name of zabbix template\n attribute :template_name\n validates :template_name, presence: true, type: String\n\n # @return [String, Hash, nil] JSON dump of template to import\n attribute :template_json\n validates :template_json, type: MultipleTypes.new(String, Hash)\n\n # @return [Array<String>, String, nil] List of template groups to create or delete.\n attribute :template_groups\n validates :template_groups, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] List of templates linked to the template.\n attribute :link_templates\n validates :link_templates, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] List of templates cleared from the template.,see templates_clear in https://www.zabbix.com/documentation/3.0/manual/api/reference/template/update\n attribute :clear_templates\n validates :clear_templates, type: TypeGeneric.new(String)\n\n # @return [Array<Hash>, Hash, nil] List of templates macro\n attribute :macros\n validates :macros, type: TypeGeneric.new(Hash)\n\n # @return [:present, :absent, :dump, nil] state present create/update template, absent delete template\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :dump], :message=>\"%{value} needs to be :present, :absent, :dump\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6581318378448486, "alphanum_fraction": 0.6581318378448486, "avg_line_length": 42.04081726074219, "blob_id": "780811b7bb5d47b97b5cebd6b0b86151675a6364", "content_id": "9e29c40de1d42e6e53abd11abaab8ff64fac8e49", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2109, "license_type": "permissive", "max_line_length": 152, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/cloud/webfaction/webfaction_app.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove applications on a Webfaction host. Further documentation at U(https://github.com/quentinsf/ansible-webfaction).\n class Webfaction_app < Base\n # @return [String] The name of the application\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Whether the application should exist\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The type of application to create. See the Webfaction docs at U(https://docs.webfaction.com/xmlrpc-api/apps.html) for a list.\n attribute :type\n validates :type, presence: true, type: String\n\n # @return [:yes, :no, nil] Whether the app should restart with an C(autostart.cgi) script\n attribute :autostart\n validates :autostart, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Any extra parameters required by the app\n attribute :extra_info\n validates :extra_info, type: String\n\n # @return [:yes, :no, nil] IF the port should be opened\n attribute :port_open\n validates :port_open, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String] The webfaction account to use\n attribute :login_name\n validates :login_name, presence: true, type: String\n\n # @return [String] The webfaction password to use\n attribute :login_password\n validates :login_password, presence: true, type: String\n\n # @return [String, nil] The machine name to use (optional for accounts with only one machine)\n attribute :machine\n validates :machine, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.71875, "alphanum_fraction": 0.71875, "avg_line_length": 39.34782791137695, "blob_id": "a4cdafff7b002cbaabca430237ae719b8d66f67e", "content_id": "233578e1d00023b1a31119029fe84f3a8063c276", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 928, "license_type": "permissive", "max_line_length": 192, "num_lines": 23, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_storage_vms_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Retrieve facts about one or more oVirt/RHV virtual machines relate to a storage domain.\n class Ovirt_storage_vm_facts < Base\n # @return [Symbol, nil] Flag which indicates whether to get unregistered virtual machines which contain one or more disks which reside on a storage domain or diskless virtual machines.\n attribute :unregistered\n validates :unregistered, type: Symbol\n\n # @return [Object, nil] Sets the maximum number of virtual machines to return. If not specified all the virtual machines are returned.\n attribute :max\n\n # @return [Object, nil] The storage domain name where the virtual machines should be listed.\n attribute :storage_domain\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6100000143051147, "alphanum_fraction": 0.6113793253898621, "avg_line_length": 32.72093200683594, "blob_id": "19eb91a707ac0723629db12a8f37f294e55751f2", "content_id": "cd4c22bc5f3cdd1f94ae45d5aac9c56b4a6d873e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2900, "license_type": "permissive", "max_line_length": 116, "num_lines": 86, "path": "/lib/ansible/ruby/dsl_builders/module_call.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'ansible/ruby/dsl_builders/base'\nrequire 'ansible/ruby/dsl_builders/args'\nrequire 'ansible/ruby/modules/base'\nrequire 'ansible/ruby/modules/free_form'\nrequire 'ansible/ruby/dsl_builders/jinja_item_node'\n\nmodule Ansible\n module Ruby\n module DslBuilders\n class ModuleCall < Base\n MODULES_MOD = Ansible::Ruby::Modules\n\n def respond_to_missing?(method_name, _)\n klass_name = _klass_name method_name\n MODULES_MOD.const_defined?(klass_name)\n end\n\n # Gem is a reserved Ruby keyword, method_missing alone will not catch it\n def gem(*module_args, &block)\n _process_method 'gem', *module_args, &block\n end\n\n def ansible_fail(*module_args, &block)\n # The ansible module is actually called fail\n _process_method 'fail', *module_args, &block\n end\n\n private\n\n def _klass_name(id)\n id.to_s.capitalize\n end\n\n def _process_method(id, *module_args, &block)\n module_klass = _module_klass(id)\n @result = module_klass.new({})\n _arguments(block, module_args)\n @result.validate!\n end\n\n def _arguments(block, module_args)\n free_form_module = @result.class.include?(Ansible::Ruby::Modules::FreeForm)\n raise \"Can't use arguments #{module_args} on this type of module\" if module_args.any? && !free_form_module\n raise 'You must supply a block when using this type of module' if !free_form_module && !block\n\n free_form = free_form_module && _free_form_arg(module_args)\n args_builder = Args.new @result do |attribute|\n # More user friendly to get rid of = mutators\n valid = _valid_module_attrib\n raise \"Unknown attribute '#{attribute}' for #{@result.class.name}.\\n\\nValid attributes are: #{valid}\\n\"\n end\n _block_args(args_builder, &block)\n args_builder.free_form free_form if free_form\n end\n\n def _valid_module_attrib\n (@result.methods - Modules::Base.instance_methods).reject do |method|\n method.to_s.end_with?('=') || method == :free_form\n end\n end\n\n def _module_klass(id)\n raise \"Unknown module #{id}\" unless respond_to_missing? id, true\n\n MODULES_MOD.const_get _klass_name(id)\n end\n\n def _block_args(args_builder, &block)\n return {} unless block\n\n # Delegate everything to the args builder and apply it to the module class we located\n args_builder.instance_eval(&block)\n end\n\n def _free_form_arg(module_args)\n raise 'Expected 1 argument for this type of module' unless module_args.any?\n raise 'Expected only 1 argument for this type of module' if module_args.length > 1\n\n module_args[0]\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6676798462867737, "alphanum_fraction": 0.6676798462867737, "avg_line_length": 35.55555725097656, "blob_id": "e4c7e6a17bfaf7fd41cf379add6ce579aa7897bb", "content_id": "9e590bb52ab285b2a42eb46eeb0957c0285a8cde", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 987, "license_type": "permissive", "max_line_length": 153, "num_lines": 27, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_local_user_manager.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage local users on an ESXi host\n class Vmware_local_user_manager < Base\n # @return [String] The local user name to be changed.\n attribute :local_user_name\n validates :local_user_name, presence: true, type: String\n\n # @return [Object, nil] The password to be set.\n attribute :local_user_password\n\n # @return [Object, nil] Description for the user.\n attribute :local_user_description\n\n # @return [:present, :absent, nil] Indicate desired state of the user. If the user already exists when C(state=present), the user info is updated\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6562381982803345, "alphanum_fraction": 0.6588767170906067, "avg_line_length": 41.11111068725586, "blob_id": "c03cc0d9d4531b6d48500ecd461bedd71d545197", "content_id": "ae9218d08462499e647743878f39051591575c73", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2653, "license_type": "permissive", "max_line_length": 319, "num_lines": 63, "path": "/lib/ansible/ruby/modules/generated/database/vertica/vertica_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Adds or removes Vertica database user and, optionally, assigns roles.\n # A user will not be removed until all the dependencies have been dropped.\n # In such a situation, if the module tries to remove the user it will fail and only remove roles granted to the user.\n class Vertica_user < Base\n # @return [String] Name of the user to add or remove.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Sets the user's profile.\n attribute :profile\n\n # @return [Object, nil] Sets the user's resource pool.\n attribute :resource_pool\n\n # @return [String, nil] The user's password encrypted by the MD5 algorithm.,The password must be generated with the format C(\"md5\" + md5[password + username]), resulting in a total of 35 characters. An easy way to do this is by querying the Vertica database with select 'md5'||md5('<user_password><user_name>').\n attribute :password\n validates :password, type: String\n\n # @return [Object, nil] Sets the user's password expiration.\n attribute :expired\n\n # @return [String, nil] Set to true if users are authenticated via LDAP.,The user will be created with password expired and set to I($ldap$).\n attribute :ldap\n validates :ldap, type: String\n\n # @return [String, nil] Comma separated list of roles to assign to the user.\n attribute :roles\n validates :roles, type: String\n\n # @return [:present, :absent, :locked, nil] Whether to create C(present), drop C(absent) or lock C(locked) a user.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :locked], :message=>\"%{value} needs to be :present, :absent, :locked\"}, allow_nil: true\n\n # @return [String, nil] Name of the Vertica database.\n attribute :db\n validates :db, type: String\n\n # @return [String, nil] Name of the Vertica cluster.\n attribute :cluster\n validates :cluster, type: String\n\n # @return [Integer, nil] Vertica cluster port to connect to.\n attribute :port\n validates :port, type: Integer\n\n # @return [String, nil] The username used to authenticate with.\n attribute :login_user\n validates :login_user, type: String\n\n # @return [Object, nil] The password used to authenticate with.\n attribute :login_password\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6941541433334351, "alphanum_fraction": 0.6951878070831299, "avg_line_length": 53.41875076293945, "blob_id": "a5d57ad7af2bff57b06db6e8604e5cae48c33916", "content_id": "e7d25aad7e6e38ab988526d234d61f52b33b6006", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 8707, "license_type": "permissive", "max_line_length": 252, "num_lines": 160, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_bgp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages BGP configurations on NX-OS switches.\n class Nxos_bgp < Base\n # @return [Integer] BGP autonomous system number. Valid values are String, Integer in ASPLAIN or ASDOT notation.\n attribute :asn\n validates :asn, presence: true, type: Integer\n\n # @return [String, nil] Name of the VRF. The name 'default' is a valid VRF representing the global BGP.\n attribute :vrf\n validates :vrf, type: String\n\n # @return [Symbol, nil] Enable/Disable MED comparison on paths from different autonomous systems.\n attribute :bestpath_always_compare_med\n validates :bestpath_always_compare_med, type: Symbol\n\n # @return [Symbol, nil] Enable/Disable load sharing across the providers with different (but equal-length) AS paths.\n attribute :bestpath_aspath_multipath_relax\n validates :bestpath_aspath_multipath_relax, type: Symbol\n\n # @return [Symbol, nil] Enable/Disable comparison of router IDs for identical eBGP paths.\n attribute :bestpath_compare_routerid\n validates :bestpath_compare_routerid, type: Symbol\n\n # @return [Symbol, nil] Enable/Disable neighborid. Use this when more paths available than max path config.\n attribute :bestpath_compare_neighborid\n validates :bestpath_compare_neighborid, type: Symbol\n\n # @return [Symbol, nil] Enable/Disable Ignores the cost community for BGP best-path calculations.\n attribute :bestpath_cost_community_ignore\n validates :bestpath_cost_community_ignore, type: Symbol\n\n # @return [Symbol, nil] Enable/Disable enforcement of bestpath to do a MED comparison only between paths originated within a confederation.\n attribute :bestpath_med_confed\n validates :bestpath_med_confed, type: Symbol\n\n # @return [Symbol, nil] Enable/Disable assigns the value of infinity to received routes that do not carry the MED attribute, making these routes the least desirable.\n attribute :bestpath_med_missing_as_worst\n validates :bestpath_med_missing_as_worst, type: Symbol\n\n # @return [Symbol, nil] Enable/Disable deterministic selection of the best MED pat from among the paths from the same autonomous system.\n attribute :bestpath_med_non_deterministic\n validates :bestpath_med_non_deterministic, type: Symbol\n\n # @return [Object, nil] Route Reflector Cluster-ID.\n attribute :cluster_id\n\n # @return [Object, nil] Routing domain confederation AS.\n attribute :confederation_id\n\n # @return [Object, nil] AS confederation parameters.\n attribute :confederation_peers\n\n # @return [Symbol, nil] Enable/Disable the batching evaluation of prefix advertisement to all peers.\n attribute :disable_policy_batching\n validates :disable_policy_batching, type: Symbol\n\n # @return [Object, nil] Enable/Disable the batching evaluation of prefix advertisements to all peers with prefix list.\n attribute :disable_policy_batching_ipv4_prefix_list\n\n # @return [Object, nil] Enable/Disable the batching evaluation of prefix advertisements to all peers with prefix list.\n attribute :disable_policy_batching_ipv6_prefix_list\n\n # @return [Symbol, nil] Enable/Disable enforces the neighbor autonomous system to be the first AS number listed in the AS path attribute for eBGP. On NX-OS, this property is only supported in the global BGP context.\n attribute :enforce_first_as\n validates :enforce_first_as, type: Symbol\n\n # @return [:size_small, :size_medium, :size_large, :size_disable, :default, nil] Enable/Disable cli event history buffer.\n attribute :event_history_cli\n validates :event_history_cli, expression_inclusion: {:in=>[:size_small, :size_medium, :size_large, :size_disable, :default], :message=>\"%{value} needs to be :size_small, :size_medium, :size_large, :size_disable, :default\"}, allow_nil: true\n\n # @return [:size_small, :size_medium, :size_large, :size_disable, :default, nil] Enable/Disable detail event history buffer.\n attribute :event_history_detail\n validates :event_history_detail, expression_inclusion: {:in=>[:size_small, :size_medium, :size_large, :size_disable, :default], :message=>\"%{value} needs to be :size_small, :size_medium, :size_large, :size_disable, :default\"}, allow_nil: true\n\n # @return [:size_small, :size_medium, :size_large, :size_disable, :default, nil] Enable/Disable event history buffer.\n attribute :event_history_events\n validates :event_history_events, expression_inclusion: {:in=>[:size_small, :size_medium, :size_large, :size_disable, :default], :message=>\"%{value} needs to be :size_small, :size_medium, :size_large, :size_disable, :default\"}, allow_nil: true\n\n # @return [:size_small, :size_medium, :size_large, :size_disable, :default, nil] Enable/Disable periodic event history buffer.\n attribute :event_history_periodic\n validates :event_history_periodic, expression_inclusion: {:in=>[:size_small, :size_medium, :size_large, :size_disable, :default], :message=>\"%{value} needs to be :size_small, :size_medium, :size_large, :size_disable, :default\"}, allow_nil: true\n\n # @return [Symbol, nil] Enable/Disable immediately reset the session if the link to a directly connected BGP peer goes down. Only supported in the global BGP context.\n attribute :fast_external_fallover\n validates :fast_external_fallover, type: Symbol\n\n # @return [Symbol, nil] Enable/Disable flush routes in RIB upon controlled restart. On NX-OS, this property is only supported in the global BGP context.\n attribute :flush_routes\n validates :flush_routes, type: Symbol\n\n # @return [Symbol, nil] Enable/Disable graceful restart.\n attribute :graceful_restart\n validates :graceful_restart, type: Symbol\n\n # @return [Symbol, nil] Enable/Disable graceful restart helper mode.\n attribute :graceful_restart_helper\n validates :graceful_restart_helper, type: Symbol\n\n # @return [Object, nil] Set maximum time for a restart sent to the BGP peer.\n attribute :graceful_restart_timers_restart\n\n # @return [Object, nil] Set maximum time that BGP keeps the stale routes from the restarting BGP peer.\n attribute :graceful_restart_timers_stalepath_time\n\n # @return [Symbol, nil] Enable/Disable isolate this router from BGP perspective.\n attribute :isolate\n validates :isolate, type: Symbol\n\n # @return [Object, nil] Local AS number to be used within a VRF instance.\n attribute :local_as\n\n # @return [Symbol, nil] Enable/Disable message logging for neighbor up/down event.\n attribute :log_neighbor_changes\n validates :log_neighbor_changes, type: Symbol\n\n # @return [Object, nil] Specify Maximum number of AS numbers allowed in the AS-path attribute. Valid values are between 1 and 512.\n attribute :maxas_limit\n\n # @return [Symbol, nil] Enable/Disable handle BGP neighbor down event, due to various reasons.\n attribute :neighbor_down_fib_accelerate\n validates :neighbor_down_fib_accelerate, type: Symbol\n\n # @return [Object, nil] The BGP reconnection interval for dropped sessions. Valid values are between 1 and 60.\n attribute :reconnect_interval\n\n # @return [String, nil] Router Identifier (ID) of the BGP router VRF instance.\n attribute :router_id\n validates :router_id, type: String\n\n # @return [Symbol, nil] Administratively shutdown the BGP protocol.\n attribute :shutdown\n validates :shutdown, type: Symbol\n\n # @return [Symbol, nil] Enable/Disable advertise only routes programmed in hardware to peers.\n attribute :suppress_fib_pending\n validates :suppress_fib_pending, type: Symbol\n\n # @return [Object, nil] Specify timeout for the first best path after a restart, in seconds.\n attribute :timer_bestpath_limit\n\n # @return [Object, nil] Set BGP hold timer.\n attribute :timer_bgp_hold\n\n # @return [Object, nil] Set BGP keepalive timer.\n attribute :timer_bgp_keepalive\n\n # @return [:present, :absent, nil] Determines whether the config should be present or not on the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.653236448764801, "alphanum_fraction": 0.653236448764801, "avg_line_length": 39.91891860961914, "blob_id": "366cd4f854b91d50811f682956938a0910625abf", "content_id": "82a3ab299e1fc957e2b4455e00ed7b3054ced04f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1514, "license_type": "permissive", "max_line_length": 159, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_contract_subject_to_filter.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Bind Contract Subjects to Filters on Cisco ACI fabrics.\n class Aci_contract_subject_to_filter < Base\n # @return [String, nil] The name of the contract.\n attribute :contract\n validates :contract, type: String\n\n # @return [String, nil] The name of the Filter to bind to the Subject.\n attribute :filter\n validates :filter, type: String\n\n # @return [:log, :none, nil] Determines if the binding should be set to log.,The APIC defaults to C(none) when unset during creation.\n attribute :log\n validates :log, expression_inclusion: {:in=>[:log, :none], :message=>\"%{value} needs to be :log, :none\"}, allow_nil: true\n\n # @return [String, nil] The name of the Contract Subject.\n attribute :subject\n validates :subject, type: String\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n\n # @return [String] The name of the tenant.\n attribute :tenant\n validates :tenant, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6777446866035461, "alphanum_fraction": 0.680059552192688, "avg_line_length": 65.46154022216797, "blob_id": "6bec19be76a1d5ffd974a2a4cfd34ffbf64f17a9", "content_id": "96d0a8973a2891cf74178165fba0402532c2f908", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6048, "license_type": "permissive", "max_line_length": 347, "num_lines": 91, "path": "/lib/ansible/ruby/modules/generated/source_control/git.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage I(git) checkouts of repositories to deploy files or software.\n class Git < Base\n # @return [String] git, SSH, or HTTP(S) protocol address of the git repository.\n attribute :repo\n validates :repo, presence: true, type: String\n\n # @return [String] The path of where the repository should be checked out. This parameter is required, unless C(clone) is set to C(no).\n attribute :dest\n validates :dest, presence: true, type: String\n\n # @return [String, nil] What version of the repository to check out. This can be the literal string C(HEAD), a branch name, a tag name. It can also be a I(SHA-1) hash, in which case C(refspec) needs to be specified if the given revision is not already available.\n attribute :version\n validates :version, type: String\n\n # @return [:yes, :no, nil] if C(yes), ensure that \"-o StrictHostKeyChecking=no\" is present as an ssh option.\n attribute :accept_hostkey\n validates :accept_hostkey, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Creates a wrapper script and exports the path as GIT_SSH which git then automatically uses to override ssh arguments. An example value could be \"-o StrictHostKeyChecking=no\"\n attribute :ssh_opts\n\n # @return [Object, nil] Specify an optional private key file path, on the target host, to use for the checkout.\n attribute :key_file\n\n # @return [Object, nil] Reference repository (see \"git clone --reference ...\")\n attribute :reference\n\n # @return [String, nil] Name of the remote.\n attribute :remote\n validates :remote, type: String\n\n # @return [String, nil] Add an additional refspec to be fetched. If version is set to a I(SHA-1) not reachable from any branch or tag, this option may be necessary to specify the ref containing the I(SHA-1). Uses the same syntax as the 'git fetch' command. An example value could be \"refs/meta/config\".\n attribute :refspec\n validates :refspec, type: String\n\n # @return [:yes, :no, nil] If C(yes), any modified files in the working repository will be discarded. Prior to 0.7, this was always 'yes' and could not be disabled. Prior to 1.9, the default was `yes`\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Create a shallow clone with a history truncated to the specified number or revisions. The minimum possible value is C(1), otherwise ignored. Needs I(git>=1.9.1) to work correctly.\n attribute :depth\n\n # @return [:yes, :no, nil] If C(no), do not clone the repository if it does not exist locally\n attribute :clone\n validates :clone, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), do not retrieve new revisions from the origin repository,Operations like archive will work on the existing (old) repository and might not respond to changes to the options version or remote.\n attribute :update\n validates :update, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Path to git executable to use. If not supplied, the normal mechanism for resolving binary paths will be used.\n attribute :executable\n\n # @return [:yes, :no, nil] if C(yes), repository will be created as a bare repo, otherwise it will be a standard repo with a workspace.\n attribute :bare\n validates :bare, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] The umask to set before doing any checkouts, or any other repository maintenance.\n attribute :umask\n\n # @return [:yes, :no, nil] if C(no), repository will be cloned without the --recursive option, skipping sub-modules.\n attribute :recursive\n validates :recursive, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] if C(yes), submodules will track the latest commit on their master branch (or other branch specified in .gitmodules). If C(no), submodules will be kept at the revision specified by the main project. This is equivalent to specifying the --remote flag to git submodule update.\n attribute :track_submodules\n validates :track_submodules, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] if C(yes), when cloning or checking out a C(version) verify the signature of a GPG signed commit. This requires C(git) version>=2.1.0 to be installed. The commit MUST be signed and the public key MUST be present in the GPG keyring.\n attribute :verify_commit\n validates :verify_commit, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Specify archive file path with extension. If specified, creates an archive file of the specified format containing the tree structure for the source tree. Allowed archive formats [\"zip\", \"tar.gz\", \"tar\", \"tgz\"],This will clone and perform git archive from local directory as not all git servers support git archive.\n attribute :archive\n validates :archive, type: String\n\n # @return [String, nil] The path to place the cloned repository. If specified, Git repository can be separated from working tree.\n attribute :separate_git_dir\n validates :separate_git_dir, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6951026916503906, "alphanum_fraction": 0.6951026916503906, "avg_line_length": 29.14285659790039, "blob_id": "e271deb7daa68e59b62ec560a13226c1f8dfa425", "content_id": "673893913c20317de0700562a17199a5531b9fa0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 633, "license_type": "permissive", "max_line_length": 68, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/identity/ipa/ipa_config.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Modify global configuration settings of a FreeIPA Server.\n class Ipa_config < Base\n # @return [String, nil] Default shell for new users.\n attribute :ipadefaultloginshell\n validates :ipadefaultloginshell, type: String\n\n # @return [String, nil] Default e-mail domain for new users.\n attribute :ipadefaultemaildomain\n validates :ipadefaultemaildomain, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6748136878013611, "alphanum_fraction": 0.6968703269958496, "avg_line_length": 68.89583587646484, "blob_id": "0a6393f6bdedcb3dba50ec03826a5b01fec86236", "content_id": "1e9a0ca82f6ab8baa6ddf6f38a07f6f9468a87bc", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3355, "license_type": "permissive", "max_line_length": 381, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/route53_health_check.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates and deletes DNS Health checks in Amazons Route53 service\n # Only the port, resource_path, string_match and request_interval are considered when updating existing health-checks.\n class Route53_health_check < Base\n # @return [:present, :absent] Specifies the action to take.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [Object, nil] IP address of the end-point to check. Either this or `fqdn` has to be provided.\n attribute :ip_address\n\n # @return [Object, nil] The port on the endpoint on which you want Amazon Route 53 to perform health checks. Required for TCP checks.\n attribute :port\n\n # @return [:HTTP, :HTTPS, :HTTP_STR_MATCH, :HTTPS_STR_MATCH, :TCP] The type of health check that you want to create, which indicates how Amazon Route 53 determines whether an endpoint is healthy.\n attribute :type\n validates :type, presence: true, expression_inclusion: {:in=>[:HTTP, :HTTPS, :HTTP_STR_MATCH, :HTTPS_STR_MATCH, :TCP], :message=>\"%{value} needs to be :HTTP, :HTTPS, :HTTP_STR_MATCH, :HTTPS_STR_MATCH, :TCP\"}\n\n # @return [String, nil] The path that you want Amazon Route 53 to request when performing health checks. The path can be any value for which your endpoint will return an HTTP status code of 2xx or 3xx when the endpoint is healthy, for example the file /docs/route53-health-check.html.,Required for all checks except TCP.,The path must begin with a /,Maximum 255 characters.\n attribute :resource_path\n validates :resource_path, type: String\n\n # @return [String, nil] Domain name of the endpoint to check. Either this or `ip_address` has to be provided. When both are given the `fqdn` is used in the `Host:` header of the HTTP request.\n attribute :fqdn\n validates :fqdn, type: String\n\n # @return [String, nil] If the check type is HTTP_STR_MATCH or HTTP_STR_MATCH, the string that you want Amazon Route 53 to search for in the response body from the specified resource. If the string appears in the first 5120 bytes of the response body, Amazon Route 53 considers the resource healthy.\n attribute :string_match\n validates :string_match, type: String\n\n # @return [10, 30] The number of seconds between the time that Amazon Route 53 gets a response from your endpoint and the time that it sends the next health-check request.\n attribute :request_interval\n validates :request_interval, presence: true, expression_inclusion: {:in=>[10, 30], :message=>\"%{value} needs to be 10, 30\"}\n\n # @return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] The number of consecutive health checks that an endpoint must pass or fail for Amazon Route 53 to change the current status of the endpoint from unhealthy to healthy or vice versa.\n attribute :failure_threshold\n validates :failure_threshold, presence: true, expression_inclusion: {:in=>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], :message=>\"%{value} needs to be 1, 2, 3, 4, 5, 6, 7, 8, 9, 10\"}\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6333929896354675, "alphanum_fraction": 0.6660698056221008, "avg_line_length": 50.953487396240234, "blob_id": "14eb957d18a34fe859e98869895bf510c31a9be7", "content_id": "2bddf29364b6e6edbdd0b673f7c6718e0a409833", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2234, "license_type": "permissive", "max_line_length": 256, "num_lines": 43, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_vrf_af.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages VPN instance address family of HUAWEI CloudEngine switches.\n class Ce_vrf_af < Base\n # @return [Object] VPN instance.\n attribute :vrf\n validates :vrf, presence: true\n\n # @return [:v4, :v6, nil] VPN instance address family.\n attribute :vrf_aftype\n validates :vrf_aftype, expression_inclusion: {:in=>[:v4, :v6], :message=>\"%{value} needs to be :v4, :v6\"}, allow_nil: true\n\n # @return [Object, nil] VPN instance route distinguisher,the RD used to distinguish same route prefix from different vpn. The RD must be setted before setting vpn_target_value.\n attribute :route_distinguisher\n\n # @return [:present, :absent, nil] Manage the state of the vpn target.\n attribute :vpn_target_state\n validates :vpn_target_state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:export_extcommunity, :import_extcommunity, nil] VPN instance vpn target type.\n attribute :vpn_target_type\n validates :vpn_target_type, expression_inclusion: {:in=>[:export_extcommunity, :import_extcommunity], :message=>\"%{value} needs to be :export_extcommunity, :import_extcommunity\"}, allow_nil: true\n\n # @return [Object, nil] VPN instance target value. Such as X.X.X.X:number<0-65535> or number<0-65535>:number<0-4294967295> or number<0-65535>.number<0-65535>:number<0-65535> or number<65536-4294967295>:number<0-65535> but not support 0:0 and 0.0:0.\n attribute :vpn_target_value\n\n # @return [:yes, :no, nil] Is extend vpn or normal vpn.\n attribute :evpn\n validates :evpn, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Manage the state of the af.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6556063890457153, "alphanum_fraction": 0.6556063890457153, "avg_line_length": 33.959999084472656, "blob_id": "2aec471fb2d22225817f546efe6cd261ce298111", "content_id": "22d6a4f172f907d37b22152282fb4819b40ae829", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 874, "license_type": "permissive", "max_line_length": 149, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/cloud/vultr/vultr_dns_domain.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create and remove DNS domains.\n class Vultr_dns_domain < Base\n # @return [String] The domain name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The default server IP.,Use M(vultr_dns_record) to change it once the domain is created.,Required if C(state=present).\n attribute :server_ip\n validates :server_ip, type: String\n\n # @return [:present, :absent, nil] State of the DNS domain.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6692307591438293, "alphanum_fraction": 0.6748718023300171, "avg_line_length": 40.48936080932617, "blob_id": "f5e8a575d4347d3c400f638010592dfc6c3f65fc", "content_id": "1f5f04d04bceb7bedeb32d82c0ebce1a7e7faa9b", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1950, "license_type": "permissive", "max_line_length": 143, "num_lines": 47, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_snapshot.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create/Modify/Delete ONTAP snapshots\n class Na_ontap_snapshot < Base\n # @return [:present, :absent, nil] If you want to create/modify a snapshot, or delete it.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] Name of the snapshot to be managed. The maximum string length is 256 characters.\n attribute :snapshot\n validates :snapshot, presence: true, type: String\n\n # @return [String] Name of the volume on which the snapshot is to be created.\n attribute :volume\n validates :volume, presence: true, type: String\n\n # @return [Symbol, nil] If true, the snapshot is to be created asynchronously.\n attribute :async_bool\n validates :async_bool, type: Symbol\n\n # @return [String, nil] A human readable comment attached with the snapshot. The size of the comment can be at most 255 characters.\n attribute :comment\n validates :comment, type: String\n\n # @return [Object, nil] A human readable SnapMirror Label attached with the snapshot. Size of the label can be at most 31 characters.\n attribute :snapmirror_label\n\n # @return [Symbol, nil] if this field is true, snapshot will be deleted even if some other processes are accessing it.\n attribute :ignore_owners\n validates :ignore_owners, type: Symbol\n\n # @return [Object, nil] The 128 bit unique snapshot identifier expressed in the form of UUID.\n attribute :snapshot_instance_uuid\n\n # @return [String, nil] The Vserver name\n attribute :vserver\n validates :vserver, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6482465267181396, "alphanum_fraction": 0.6482465267181396, "avg_line_length": 28.40625, "blob_id": "c652cdfc25e55a56572c7ecd3ce524f603df1f83", "content_id": "56f9772e023a13a38812a3156da84a0dd54e7667", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 941, "license_type": "permissive", "max_line_length": 72, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/database/vertica/vertica_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gathers Vertica database facts.\n class Vertica_facts < Base\n # @return [String, nil] Name of the cluster running the schema.\n attribute :cluster\n validates :cluster, type: String\n\n # @return [Integer, nil] Database port to connect to.\n attribute :port\n validates :port, type: Integer\n\n # @return [String, nil] Name of the database running the schema.\n attribute :db\n validates :db, type: String\n\n # @return [String, nil] The username used to authenticate with.\n attribute :login_user\n validates :login_user, type: String\n\n # @return [Object, nil] The password used to authenticate with.\n attribute :login_password\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.652226984500885, "alphanum_fraction": 0.652226984500885, "avg_line_length": 37.11627960205078, "blob_id": "d51740b229fd98200bb88cd505ab2970f96a4308", "content_id": "91b266ea25bc405762e2c9d7ffa3e9afa359200b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1639, "license_type": "permissive", "max_line_length": 143, "num_lines": 43, "path": "/lib/ansible/ruby/modules/generated/cloud/webfaction/webfaction_site.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove a website on a Webfaction host. Further documentation at https://github.com/quentinsf/ansible-webfaction.\n class Webfaction_site < Base\n # @return [String] The name of the website\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Whether the website should exist\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The webfaction host on which the site should be created.\n attribute :host\n validates :host, presence: true, type: String\n\n # @return [:yes, :no, nil] Whether or not to use HTTPS\n attribute :https\n validates :https, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] A mapping of URLs to apps\n attribute :site_apps\n\n # @return [Object, nil] A list of subdomains associated with this site.\n attribute :subdomains\n\n # @return [String] The webfaction account to use\n attribute :login_name\n validates :login_name, presence: true, type: String\n\n # @return [String] The webfaction password to use\n attribute :login_password\n validates :login_password, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7152737975120544, "alphanum_fraction": 0.7152737975120544, "avg_line_length": 58.82758712768555, "blob_id": "7ae8f90400b7afd3e91524d4ccc2d19fa9747533", "content_id": "aafe63c70ad049b4e3e133d9dfafa719cf3ab1e4", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1735, "license_type": "permissive", "max_line_length": 383, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_datastore_maintenancemode.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to manage maintenance mode of a datastore.\n class Vmware_datastore_maintenancemode < Base\n # @return [String, nil] Name of datastore to manage.,If C(datastore_cluster) or C(cluster_name) are not set, this parameter is required.\n attribute :datastore\n validates :datastore, type: String\n\n # @return [String, nil] Name of the datastore cluster from all child datastores to be managed.,If C(datastore) or C(cluster_name) are not set, this parameter is required.\n attribute :datastore_cluster\n validates :datastore_cluster, type: String\n\n # @return [String, nil] Name of the cluster where datastore is connected to.,If multiple datastores are connected to the given cluster, then all datastores will be managed by C(state).,If C(datastore) or C(datastore_cluster) are not set, this parameter is required.\n attribute :cluster_name\n validates :cluster_name, type: String\n\n # @return [:present, :absent, nil] If set to C(present), then enter datastore into maintenance mode.,If set to C(present) and datastore is already in maintenance mode, then no action will be taken.,If set to C(absent) and datastore is in maintenance mode, then exit maintenance mode.,If set to C(absent) and datastore is not in maintenance mode, then no action will be taken.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6902549266815186, "alphanum_fraction": 0.6952584981918335, "avg_line_length": 70.13558959960938, "blob_id": "d5015a6fa0adb08fcd4564b192107b0d6e0eb11b", "content_id": "9b6badfb5d56c210fe15617ffd063acfb5c872b1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4197, "license_type": "permissive", "max_line_length": 942, "num_lines": 59, "path": "/lib/ansible/ruby/modules/generated/notification/slack.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The C(slack) module sends notifications to U(http://slack.com) via the Incoming WebHook integration\n class Slack < Base\n # @return [Object, nil] Slack (sub)domain for your environment without protocol. (i.e. C(example.slack.com)) In 1.8 and beyond, this is deprecated and may be ignored. See token documentation for information.\n attribute :domain\n\n # @return [String] Slack integration token. This authenticates you to the slack service. Prior to 1.8, a token looked like C(3Ffe373sfhRE6y42Fg3rvf4GlK). In 1.8 and above, ansible adapts to the new slack API where tokens look like C(G922VJP24/D921DW937/3Ffe373sfhRE6y42Fg3rvf4GlK). If tokens are in the new format then slack will ignore any value of domain. If the token is in the old format the domain is required. Ansible has no control of when slack will get rid of the old API. When slack does that the old format will stop working. ** Please keep in mind the tokens are not the API tokens but are the webhook tokens. In slack these are found in the webhook URL which are obtained under the apps and integrations. The incoming webhooks can be added in that area. In some cases this may be locked by your Slack admin and you must request access. It is there that the incoming webhooks can be added. The key is on the end of the URL given to you in that section.\n attribute :token\n validates :token, presence: true, type: String\n\n # @return [String, nil] Message to send. Note that the module does not handle escaping characters. Plain-text angle brackets and ampersands should be converted to HTML entities (e.g. & to &amp;) before sending. See Slack's documentation (U(https://api.slack.com/docs/message-formatting)) for more.\n attribute :msg\n validates :msg, type: String\n\n # @return [String, nil] Channel to send the message to. If absent, the message goes to the channel selected for the I(token).\n attribute :channel\n validates :channel, type: String\n\n # @return [String, nil] This is the sender of the message.\n attribute :username\n validates :username, type: String\n\n # @return [String, nil] Url for the message sender's icon (default C(https://www.ansible.com/favicon.ico))\n attribute :icon_url\n validates :icon_url, type: String\n\n # @return [Object, nil] Emoji for the message sender. See Slack documentation for options. (if I(icon_emoji) is set, I(icon_url) will not be used)\n attribute :icon_emoji\n\n # @return [1, 0, nil] Automatically create links for channels and usernames in I(msg).\n attribute :link_names\n validates :link_names, expression_inclusion: {:in=>[1, 0], :message=>\"%{value} needs to be 1, 0\"}, allow_nil: true\n\n # @return [:full, :none, nil] Setting for the message parser at Slack\n attribute :parse\n validates :parse, expression_inclusion: {:in=>[:full, :none], :message=>\"%{value} needs to be :full, :none\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:normal, :good, :warning, :danger, nil] Allow text to use default colors - use the default of 'normal' to not send a custom color bar at the start of the message\n attribute :color\n validates :color, expression_inclusion: {:in=>[:normal, :good, :warning, :danger], :message=>\"%{value} needs to be :normal, :good, :warning, :danger\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash, nil] Define a list of attachments. This list mirrors the Slack JSON API.,For more information, see also in the (U(https://api.slack.com/docs/attachments)).\n attribute :attachments\n validates :attachments, type: TypeGeneric.new(Hash)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7027818560600281, "alphanum_fraction": 0.7086383700370789, "avg_line_length": 53.63999938964844, "blob_id": "3ae9909dc99653497e7dc3ea548cfa31966f3af1", "content_id": "12d2dc29162ec9f218923f5bebe1d6ce07c9f0d6", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1366, "license_type": "permissive", "max_line_length": 282, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigiq_utility_license.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages utility licenses on a BIG-IQ. Utility licenses are one form of licenses that BIG-IQ can distribute. These licenses, unlike regkey licenses, do not require a pool to be created before creation. Additionally, when assigning them, you assign by offering instead of key.\n class Bigiq_utility_license < Base\n # @return [String] The license key to install and activate.\n attribute :license_key\n validates :license_key, presence: true, type: String\n\n # @return [Symbol, nil] A key that signifies that you accept the F5 EULA for this license.,A copy of the EULA can be found here https://askf5.f5.com/csp/article/K12902,This is required when C(state) is C(present).\n attribute :accept_eula\n validates :accept_eula, type: Symbol\n\n # @return [:absent, :present, nil] The state of the utility license on the system.,When C(present), guarantees that the license exists.,When C(absent), removes the license from the system.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6599169373512268, "alphanum_fraction": 0.6765316724777222, "avg_line_length": 54.02857208251953, "blob_id": "7457a8595f04784b4cbbaf8d728d79ea326b3b86", "content_id": "8c5761158aee8bf0978be4018790daea6c782b30", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1926, "license_type": "permissive", "max_line_length": 223, "num_lines": 35, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_dldp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages global DLDP configuration on HUAWEI CloudEngine switches.\n class Ce_dldp < Base\n # @return [:enable, :disable, nil] Set global DLDP enable state.\n attribute :enable\n validates :enable, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:enhance, :normal, nil] Set global DLDP work-mode.\n attribute :work_mode\n validates :work_mode, expression_inclusion: {:in=>[:enhance, :normal], :message=>\"%{value} needs to be :enhance, :normal\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the interval for sending Advertisement packets. The value is an integer ranging from 1 to 100, in seconds. The default interval for sending Advertisement packets is 5 seconds.\n attribute :time_internal\n\n # @return [:md5, :simple, :sha, :\"hmac-sha256\", :none, nil] Specifies authentication algorithm of DLDP.\n attribute :auth_mode\n validates :auth_mode, expression_inclusion: {:in=>[:md5, :simple, :sha, :\"hmac-sha256\", :none], :message=>\"%{value} needs to be :md5, :simple, :sha, :\\\"hmac-sha256\\\", :none\"}, allow_nil: true\n\n # @return [Object, nil] Specifies authentication password. The value is a string of 1 to 16 case-sensitive plaintexts or 24/32/48/108/128 case-sensitive encrypted characters. The string excludes a question mark (?).\n attribute :auth_pwd\n\n # @return [:enable, :disable, nil] Specify whether reset DLDP state of disabled interfaces.\n attribute :reset\n validates :reset, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7100963592529297, "alphanum_fraction": 0.7100963592529297, "avg_line_length": 69.20587921142578, "blob_id": "a0af8a2deb60e99ee73cd102c0c0bbb8e040e334", "content_id": "5128d1667c9eeecf27ab3ea9eb7547f43d8f0016", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2387, "license_type": "permissive", "max_line_length": 779, "num_lines": 34, "path": "/lib/ansible/ruby/modules/generated/packaging/os/flatpak.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows users to add or remove flatpaks.\n # See the M(flatpak_remote) module for managing flatpak remotes.\n class Flatpak < Base\n # @return [String, nil] The path to the C(flatpak) executable to use.,By default, this module looks for the C(flatpak) executable on the path.\n attribute :executable\n validates :executable, type: String\n\n # @return [:system, :user, nil] The installation method to use.,Defines if the I(flatpak) is supposed to be installed globally for the whole C(system) or only for the current C(user).\n attribute :method\n validates :method, expression_inclusion: {:in=>[:system, :user], :message=>\"%{value} needs to be :system, :user\"}, allow_nil: true\n\n # @return [String] The name of the flatpak to manage.,When used with I(state=present), I(name) can be specified as an C(http(s)) URL to a C(flatpakref) file or the unique reverse DNS name that identifies a flatpak.,When suppying a reverse DNS name, you can use the I(remote) option to specify on what remote to look for the flatpak. An example for a reverse DNS name is C(org.gnome.gedit).,When used with I(state=absent), it is recommended to specify the name in the reverse DNS format.,When supplying an C(http(s)) URL with I(state=absent), the module will try to match the installed flatpak based on the name of the flatpakref to remove it. However, there is no guarantee that the names of the flatpakref file and the reverse DNS name of the installed flatpak do match.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The flatpak remote (repository) to install the flatpak from.,By default, C(flathub) is assumed, but you do need to add the flathub flatpak_remote before you can use this.,See the M(flatpak_remote) module for managing flatpak remotes.\n attribute :remote\n validates :remote, type: String\n\n # @return [:absent, :present, nil] Indicates the desired package state.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6712815165519714, "alphanum_fraction": 0.6744763851165771, "avg_line_length": 45.95000076293945, "blob_id": "5ff4fcdb0f2a574c173a045bf97333c2cd1b4f66", "content_id": "304bd8b1127404752d7ac8a13dbae6c932c52805", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2817, "license_type": "permissive", "max_line_length": 166, "num_lines": 60, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_vsdatascriptset.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure VSDataScriptSet object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_vsdatascriptset < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Object, nil] Creator name.,Field introduced in 17.1.11,17.2.4.\n attribute :created_by\n\n # @return [Object, nil] Datascripts to execute.\n attribute :datascript\n\n # @return [Object, nil] User defined description for the object.\n attribute :description\n\n # @return [Object, nil] Uuid of ip groups that could be referred by vsdatascriptset objects.,It is a reference to an object of type ipaddrgroup.\n attribute :ipgroup_refs\n\n # @return [String] Name for the virtual service datascript collection.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Uuid of pool groups that could be referred by vsdatascriptset objects.,It is a reference to an object of type poolgroup.\n attribute :pool_group_refs\n\n # @return [Object, nil] Uuid of pools that could be referred by vsdatascriptset objects.,It is a reference to an object of type pool.\n attribute :pool_refs\n\n # @return [Object, nil] Uuid of string groups that could be referred by vsdatascriptset objects.,It is a reference to an object of type stringgroup.\n attribute :string_group_refs\n\n # @return [Object, nil] It is a reference to an object of type tenant.\n attribute :tenant_ref\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Uuid of the virtual service datascript collection.\n attribute :uuid\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6669348478317261, "alphanum_fraction": 0.6669348478317261, "avg_line_length": 36.66666793823242, "blob_id": "a4cc1fc8b4616dd2ef23178859546bbdebd8480f", "content_id": "bf6ae49891fa1349e3df41c8a07af2362eba5b80", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1243, "license_type": "permissive", "max_line_length": 143, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_timer_policy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage timer policies on a BIG-IP.\n class Bigip_timer_policy < Base\n # @return [String] Specifies the name of the timer policy.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Specifies descriptive text that identifies the timer policy.\n attribute :description\n validates :description, type: String\n\n # @return [Array<Hash>, Hash, nil] Rules that you want assigned to the timer policy\n attribute :rules\n validates :rules, type: TypeGeneric.new(Hash)\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [:present, :absent, nil] When C(present), ensures that the resource exists.,When C(absent), ensures the resource is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6597437262535095, "alphanum_fraction": 0.6597437262535095, "avg_line_length": 39.41071319580078, "blob_id": "9a1d6e69a06f471de9cfd4ea4518d4cf4bce5083", "content_id": "19e3d1baa5e9585d67e09626d65ce40f8f71bad1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2263, "license_type": "permissive", "max_line_length": 153, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/messaging/rabbitmq_binding.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module uses rabbitMQ REST APIs to create / delete bindings.\n class Rabbitmq_binding < Base\n # @return [:present, :absent, nil] Whether the bindings should be present or absent.,Only present implemented at the momemt.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] source exchange to create binding on.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] rabbitMQ user for the connection.\n attribute :login_user\n validates :login_user, type: String\n\n # @return [Boolean, nil] rabbitMQ password for the connection.\n attribute :login_password\n validates :login_password, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] rabbitMQ host for the connection.\n attribute :login_host\n validates :login_host, type: String\n\n # @return [Integer, nil] rabbitMQ management API port.\n attribute :login_port\n validates :login_port, type: Integer\n\n # @return [String, nil] rabbitMQ virtual host.\n attribute :vhost\n validates :vhost, type: String\n\n # @return [String] destination exchange or queue for the binding.\n attribute :destination\n validates :destination, presence: true, type: String\n\n # @return [:queue, :exchange] Either queue or exchange.\n attribute :destination_type\n validates :destination_type, presence: true, expression_inclusion: {:in=>[:queue, :exchange], :message=>\"%{value} needs to be :queue, :exchange\"}\n\n # @return [String, nil] routing key for the binding.\n attribute :routing_key\n validates :routing_key, type: String\n\n # @return [Object, nil] extra arguments for exchange. If defined this argument is a key/value dictionary.\n attribute :arguments\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6880044341087341, "alphanum_fraction": 0.6880044341087341, "avg_line_length": 59.8983039855957, "blob_id": "85ac13c688236d1f090f920a4d38e8daad030065", "content_id": "2d9e2963d0f40d0a52207529ece53363e6b2be74", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3593, "license_type": "permissive", "max_line_length": 393, "num_lines": 59, "path": "/lib/ansible/ruby/modules/generated/database/postgresql/postgresql_lang.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Adds, removes or changes procedural languages with a PostgreSQL database.\n # This module allows you to add a language, remote a language or change the trust relationship with a PostgreSQL database. The module can be used on the machine where executed or on a remote host.\n # When removing a language from a database, it is possible that dependencies prevent the database from being removed. In that case, you can specify casade to automatically drop objects that depend on the language (such as functions in the language). In case the language can't be deleted because it is required by the database system, you can specify fail_on_drop=no to ignore the error.\n # Be carefull when marking a language as trusted since this could be a potential security breach. Untrusted languages allow only users with the PostgreSQL superuser privilege to use this language to create new functions.\n class Postgresql_lang < Base\n # @return [String] name of the procedural language to add, remove or change\n attribute :lang\n validates :lang, presence: true, type: String\n\n # @return [:yes, :no, nil] make this language trusted for the selected db\n attribute :trust\n validates :trust, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] name of database where the language will be added, removed or changed\n attribute :db\n validates :db, type: String\n\n # @return [:yes, :no, nil] marks the language as trusted, even if it's marked as untrusted in pg_pltemplate.,use with care!\n attribute :force_trust\n validates :force_trust, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] if C(yes), fail when removing a language. Otherwise just log and continue,in some cases, it is not possible to remove a language (used by the db-system). When dependencies block the removal, consider using C(cascade).\n attribute :fail_on_drop\n validates :fail_on_drop, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] when dropping a language, also delete object that depend on this language.,only used when C(state=absent).\n attribute :cascade\n validates :cascade, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Database port to connect to.\n attribute :port\n validates :port, type: Integer\n\n # @return [String, nil] User used to authenticate with PostgreSQL\n attribute :login_user\n validates :login_user, type: String\n\n # @return [Object, nil] Password used to authenticate with PostgreSQL (must match C(login_user))\n attribute :login_password\n\n # @return [String, nil] Host running PostgreSQL where you want to execute the actions.\n attribute :login_host\n validates :login_host, type: String\n\n # @return [:present, :absent, nil] The state of the language for the selected database\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6607142686843872, "alphanum_fraction": 0.6607142686843872, "avg_line_length": 44.4054069519043, "blob_id": "4f377e3e2942bef2d149815e8ca6417003709b9c", "content_id": "6727aa82ea71f5ae1cc6526edd8e71e70cbaf183", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1680, "license_type": "permissive", "max_line_length": 335, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/system/aix_inittab.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages the inittab on AIX.\n class Aix_inittab < Base\n # @return [String] Name of the inittab entry.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Integer] Runlevel of the entry.\n attribute :runlevel\n validates :runlevel, presence: true, type: Integer\n\n # @return [:boot, :bootwait, :hold, :initdefault, false, :once, :ondemand, :powerfail, :powerwait, :respawn, :sysinit, :wait] Action what the init has to do with this entry.\n attribute :action\n validates :action, presence: true, expression_inclusion: {:in=>[:boot, :bootwait, :hold, :initdefault, false, :once, :ondemand, :powerfail, :powerwait, :respawn, :sysinit, :wait], :message=>\"%{value} needs to be :boot, :bootwait, :hold, :initdefault, false, :once, :ondemand, :powerfail, :powerwait, :respawn, :sysinit, :wait\"}\n\n # @return [String] What command has to run.\n attribute :command\n validates :command, presence: true, type: String\n\n # @return [String, nil] After which inittabline should the new entry inserted.\n attribute :insertafter\n validates :insertafter, type: String\n\n # @return [:absent, :present, nil] Whether the entry should be present or absent in the inittab file.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6773256063461304, "alphanum_fraction": 0.6773256063461304, "avg_line_length": 42, "blob_id": "7840a39945e96117fb8b3da03f2dc1357df625c8", "content_id": "dd30f4b5a2e4687b7ac3c16ef1713f7b37988ae3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1376, "license_type": "permissive", "max_line_length": 136, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/cloud/centurylink/clc_blueprint_package.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # An Ansible module to deploy blue print package on a set of servers in CenturyLink Cloud.\n class Clc_blueprint_package < Base\n # @return [Array<String>, String] A list of server Ids to deploy the blue print package.\n attribute :server_ids\n validates :server_ids, presence: true, type: TypeGeneric.new(String)\n\n # @return [String] The package id of the blue print.\n attribute :package_id\n validates :package_id, presence: true, type: String\n\n # @return [Object, nil] The dictionary of arguments required to deploy the blue print.\n attribute :package_params\n\n # @return [:present, nil] Whether to install or un-install the package. Currently it supports only \"present\" for install action.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present], :message=>\"%{value} needs to be :present\"}, allow_nil: true\n\n # @return [Boolean, nil] Whether to wait for the tasks to finish before returning.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6823387742042542, "alphanum_fraction": 0.6823387742042542, "avg_line_length": 49.272727966308594, "blob_id": "d16672356ac74e30afa4ef156325890f7bd8b706", "content_id": "83eeaea8d2059a4202facd41e603ff5f09e52641", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1659, "license_type": "permissive", "max_line_length": 255, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/network/aos/aos_logical_device.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Apstra AOS Logical Device module let you manage your Logical Devices easily. You can create create and delete Logical Device by Name, ID or by using a JSON File. This module is idempotent and support the I(check) mode. It's using the AOS REST API.\n class Aos_logical_device < Base\n # @return [String] An existing AOS session as obtained by M(aos_login) module.\n attribute :session\n validates :session, presence: true, type: String\n\n # @return [String, nil] Name of the Logical Device to manage. Only one of I(name), I(id) or I(content) can be set.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] AOS Id of the Logical Device to manage (can't be used to create a new Logical Device), Only one of I(name), I(id) or I(content) can be set.\n attribute :id\n validates :id, type: String\n\n # @return [String, nil] Datastructure of the Logical Device to create. The data can be in YAML / JSON or directly a variable. It's the same datastructure that is returned on success in I(value).\n attribute :content\n validates :content, type: String\n\n # @return [:present, :absent, nil] Indicate what is the expected state of the Logical Device (present or not).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6791086196899414, "alphanum_fraction": 0.6793872117996216, "avg_line_length": 53.39393997192383, "blob_id": "726a9d386a69b3482121b32ced9751a9e4e130f5", "content_id": "fe5ad5ca82804e078bdda5c84c8f232b4f7632b3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3590, "license_type": "permissive", "max_line_length": 456, "num_lines": 66, "path": "/lib/ansible/ruby/modules/generated/monitoring/grafana_dashboard.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, delete, export Grafana dashboards via API.\n class Grafana_dashboard < Base\n # @return [Object] The Grafana URL.\n attribute :url\n validates :url, presence: true\n\n # @return [String, nil] The Grafana API user.\n attribute :url_username\n validates :url_username, type: String\n\n # @return [String, nil] The Grafana API password.\n attribute :url_password\n validates :url_password, type: String\n\n # @return [Object, nil] The Grafana API key.,If set, I(grafana_user) and I(grafana_password) will be ignored.\n attribute :grafana_api_key\n\n # @return [Integer, nil] The Grafana Organisation ID where the dashboard will be imported / exported.,Not used when I(grafana_api_key) is set, because the grafana_api_key only belongs to one organisation..\n attribute :org_id\n validates :org_id, type: Integer\n\n # @return [:absent, :export, :present] State of the dashboard.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:absent, :export, :present], :message=>\"%{value} needs to be :absent, :export, :present\"}\n\n # @return [Object, nil] Deprecated since Grafana 5. Use grafana dashboard uid instead.,slug of the dashboard. It's the friendly url name of the dashboard.,When C(state) is C(present), this parameter can override the slug in the meta section of the json file.,If you want to import a json dashboard exported directly from the interface (not from the api), you have to specify the slug parameter because there is no meta section in the exported json.\n attribute :slug\n\n # @return [Object, nil] uid of the dasboard to export when C(state) is C(export) or C(absent).\n attribute :uid\n\n # @return [Object, nil] The path to the json file containing the Grafana dashboard to import or export.\n attribute :path\n\n # @return [:yes, :no, nil] Override existing dashboard when state is present.\n attribute :overwrite\n validates :overwrite, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Set a commit message for the version history.,Only used when C(state) is C(present).\n attribute :message\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated.,This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] PEM formatted certificate chain file to be used for SSL client authentication.,This file can also include the key as well, and if the key is included, client_key is not required\n attribute :client_cert\n\n # @return [Object, nil] PEM formatted file that contains your private key to be used for SSL client,authentication. If client_cert contains both the certificate and key, this option is not required\n attribute :client_key\n\n # @return [:yes, :no, nil] Boolean of whether or not to use proxy.\n attribute :use_proxy\n validates :use_proxy, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6689895391464233, "alphanum_fraction": 0.6689895391464233, "avg_line_length": 41, "blob_id": "3ec2551e0adadae5f6a1fc045ab843be846460aa", "content_id": "65a8a9786d31e392222f15ab5510c8e366ed0a3e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1722, "license_type": "permissive", "max_line_length": 148, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_ntp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages core NTP configuration.\n class Nxos_ntp < Base\n # @return [String, nil] Network address of NTP server.\n attribute :server\n validates :server, type: String\n\n # @return [Object, nil] Network address of NTP peer.\n attribute :peer\n\n # @return [Integer, nil] Authentication key identifier to use with given NTP server or peer or keyword 'default'.\n attribute :key_id\n validates :key_id, type: Integer\n\n # @return [:enabled, :disabled, nil] Makes given NTP server or peer the preferred NTP server or peer for the device.\n attribute :prefer\n validates :prefer, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [Object, nil] Makes the device communicate with the given NTP server or peer over a specific VRF or keyword 'default'.\n attribute :vrf_name\n\n # @return [Object, nil] Local source address from which NTP messages are sent or keyword 'default'\n attribute :source_addr\n\n # @return [Object, nil] Local source interface from which NTP messages are sent. Must be fully qualified interface name or keyword 'default'\n attribute :source_int\n\n # @return [:present, :absent, nil] Manage the state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6860215067863464, "alphanum_fraction": 0.6860215067863464, "avg_line_length": 26.352941513061523, "blob_id": "32ec78ca527e68a967591ab3d4f1c71a62654655", "content_id": "f1fe71a228193b3ca139aa1695d91121f3d29a46", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 465, "license_type": "permissive", "max_line_length": 77, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/windows/win_timezone.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Sets machine time to the specified timezone.\n class Win_timezone < Base\n # @return [String] Timezone to set to.,Example: Central Standard Time\n attribute :timezone\n validates :timezone, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6877541542053223, "alphanum_fraction": 0.689561665058136, "avg_line_length": 50.46511459350586, "blob_id": "9bd2746b4763e194a4fbb5de0e7b733c4ced6e35", "content_id": "5eeb6590f526b25b8026d9a9a8cf42168f5cd4cd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2213, "license_type": "permissive", "max_line_length": 418, "num_lines": 43, "path": "/lib/ansible/ruby/modules/generated/network/netvisor/pn_cluster.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Execute cluster-create or cluster-delete command.\n # A cluster allows two switches to cooperate in high-availability (HA) deployments. The nodes that form the cluster must be members of the same fabric. Clusters are typically used in conjunction with a virtual link aggregation group (VLAG) that allows links physically connected to two separate switches appear as a single trunk to a third device. The third device can be a switch,server, or any Ethernet device.\n class Pn_cluster < Base\n # @return [Object, nil] Provide login username if user is not root.\n attribute :pn_cliusername\n\n # @return [Object, nil] Provide login password if user is not root.\n attribute :pn_clipassword\n\n # @return [Object, nil] Target switch to run the cli on.\n attribute :pn_cliswitch\n\n # @return [:present, :absent] Specify action to perform. Use 'present' to create cluster and 'absent' to delete cluster.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String] Specify the name of the cluster.\n attribute :pn_name\n validates :pn_name, presence: true, type: String\n\n # @return [String, nil] Specify the name of the first switch in the cluster.,Required for 'cluster-create'.\n attribute :pn_cluster_node1\n validates :pn_cluster_node1, type: String\n\n # @return [String, nil] Specify the name of the second switch in the cluster.,Required for 'cluster-create'.\n attribute :pn_cluster_node2\n validates :pn_cluster_node2, type: String\n\n # @return [:validate, :\"no-validate\", nil] Validate the inter-switch links and state of switches in the cluster.\n attribute :pn_validate\n validates :pn_validate, expression_inclusion: {:in=>[:validate, :\"no-validate\"], :message=>\"%{value} needs to be :validate, :\\\"no-validate\\\"\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6559678912162781, "alphanum_fraction": 0.6559678912162781, "avg_line_length": 33.379310607910156, "blob_id": "54414d1ce211f38acda7859ca4e07aa529e6281b", "content_id": "2dc9854a8d932ca494652d61e869d88a33c1f3e8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 997, "license_type": "permissive", "max_line_length": 143, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/vultr/vultr_block_storage.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage block storage volumes on Vultr.\n class Vultr_block_storage < Base\n # @return [String] Name of the block storage volume.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Integer] Size of the block storage volume in GB.\n attribute :size\n validates :size, presence: true, type: Integer\n\n # @return [String] Region the block storage volume is deployed into.\n attribute :region\n validates :region, presence: true, type: String\n\n # @return [:present, :absent, nil] State of the block storage volume.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6623970866203308, "alphanum_fraction": 0.6623970866203308, "avg_line_length": 36.68965530395508, "blob_id": "89d5d5f4eb5b0226d1aef2e3896e506fd68ada39", "content_id": "171c0ae7bef2b2a99a845ded0085a23c4570426c", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1093, "license_type": "permissive", "max_line_length": 182, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_snat_pool.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage SNAT pools on a BIG-IP.\n class Bigip_snat_pool < Base\n # @return [Array<String>, String, nil] List of members to put in the SNAT pool. When a C(state) of present is provided, this parameter is required. Otherwise, it is optional.\n attribute :members\n validates :members, type: TypeGeneric.new(String)\n\n # @return [String] The name of the SNAT pool.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Whether the SNAT pool should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6740919947624207, "alphanum_fraction": 0.6740919947624207, "avg_line_length": 42.02083206176758, "blob_id": "7b1de76ebee82af24f6d7fa75076a33ad2e0b8be", "content_id": "4023c898c7eba37e30d45b192b23835a6fbb5936", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2065, "license_type": "permissive", "max_line_length": 189, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_cifs_server.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creating / deleting and modifying the CIFS server.\n class Na_ontap_cifs_server < Base\n # @return [:present, :absent, nil] Whether the specified cifs_server should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:stopped, :started, nil] CIFS Server Administrative Status.\n attribute :service_state\n validates :service_state, expression_inclusion: {:in=>[:stopped, :started], :message=>\"%{value} needs to be :stopped, :started\"}, allow_nil: true\n\n # @return [String] Specifies the cifs_server name.\n attribute :cifs_server_name\n validates :cifs_server_name, presence: true, type: String\n\n # @return [Object, nil] Specifies the cifs server admin username.\n attribute :admin_user_name\n\n # @return [Object, nil] Specifies the cifs server admin password.\n attribute :admin_password\n\n # @return [Object, nil] The Fully Qualified Domain Name of the Windows Active Directory this CIFS server belongs to.\n attribute :domain\n\n # @return [Object, nil] The NetBIOS name of the domain or workgroup this CIFS server belongs to.\n attribute :workgroup\n\n # @return [Object, nil] The Organizational Unit (OU) within the Windows Active Directory this CIFS server belongs to.\n attribute :ou\n\n # @return [Symbol, nil] If this is set and a machine account with the same name as specified in 'cifs_server_name' exists in the Active Directory, it will be overwritten and reused.\n attribute :force\n validates :force, type: Symbol\n\n # @return [String] The name of the vserver to use.\n attribute :vserver\n validates :vserver, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7018405199050903, "alphanum_fraction": 0.7042945027351379, "avg_line_length": 37.80952453613281, "blob_id": "d88380001dbf430f36ca0f1906324a817afc79c4", "content_id": "b313e93cdb85388421fc0af1874926f875af2a76", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 815, "license_type": "permissive", "max_line_length": 229, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_vpc_nat_gateway_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gets various details related to AWS VPC Managed Nat Gateways\n class Ec2_vpc_nat_gateway_facts < Base\n # @return [Array<String>, String, nil] Get details of specific nat gateway IDs\n attribute :nat_gateway_ids\n validates :nat_gateway_ids, type: TypeGeneric.new(String)\n\n # @return [Hash, nil] A dict of filters to apply. Each dict item consists of a filter key and a filter value. See U(http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeNatGateways.html) for possible filters.\n attribute :filters\n validates :filters, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7084386348724365, "alphanum_fraction": 0.7111335396766663, "avg_line_length": 66.46591186523438, "blob_id": "ee49f8deba252d94d95c13377b01acbd2479f757", "content_id": "bfde7927aa29d0173655017df8f89c07128ba00c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5937, "license_type": "permissive", "max_line_length": 493, "num_lines": 88, "path": "/lib/ansible/ruby/modules/generated/clustering/consul.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Registers services and checks for an agent with a consul cluster. A service is some process running on the agent node that should be advertised by consul's discovery mechanism. It may optionally supply a check definition, a periodic service test to notify the consul cluster of service's health.\n # Checks may also be registered per node e.g. disk usage, or cpu usage and notify the health of the entire node to the cluster. Service level checks do not require a check name or id as these are derived by Consul from the Service name and id respectively by appending 'service:' Node level checks require a check_name and optionally a check_id.\n # Currently, there is no complete way to retrieve the script, interval or ttl metadata for a registered check. Without this metadata it is not possible to tell if the data supplied with ansible represents a change to a check. As a result this does not attempt to determine changes and will always report a changed occurred. An api method is planned to supply this metadata so at that stage change management will be added.\n # See http://consul.io for more details.\n class Consul < Base\n # @return [:present, :absent] register or deregister the consul service, defaults to present\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String, nil] Unique name for the service on a node, must be unique per node, required if registering a service. May be omitted if registering a node level check\n attribute :service_name\n validates :service_name, type: String\n\n # @return [String, nil] the ID for the service, must be unique per node, defaults to the service name if the service name is supplied\n attribute :service_id\n validates :service_id, type: String\n\n # @return [String, nil] host of the consul agent defaults to localhost\n attribute :host\n validates :host, type: String\n\n # @return [Integer, nil] the port on which the consul agent is running\n attribute :port\n validates :port, type: Integer\n\n # @return [String, nil] the protocol scheme on which the consul agent is running\n attribute :scheme\n validates :scheme, type: String\n\n # @return [:yes, :no, nil] whether to verify the tls certificate of the consul agent\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Notes to attach to check when registering it.\n attribute :notes\n\n # @return [Integer, nil] the port on which the service is listening. Can optionally be supplied for registration of a service, i.e. if service_name or service_id is set\n attribute :service_port\n validates :service_port, type: Integer\n\n # @return [String, nil] the address to advertise that the service will be listening on. This value will be passed as the I(Address) parameter to Consul's U(/v1/agent/service/register) API method, so refer to the Consul API documentation for further details.\n attribute :service_address\n validates :service_address, type: String\n\n # @return [Array<String>, String, nil] a list of tags that will be attached to the service registration.\n attribute :tags\n validates :tags, type: TypeGeneric.new(String)\n\n # @return [String, nil] the script/command that will be run periodically to check the health of the service. Scripts require an interval and vise versa\n attribute :script\n validates :script, type: String\n\n # @return [String, nil] the interval at which the service check will be run. This is a number with a s or m suffix to signify the units of seconds or minutes e.g 15s or 1m. If no suffix is supplied, m will be used by default e.g. 1 will be 1m. Required if the script param is specified.\n attribute :interval\n validates :interval, type: String\n\n # @return [String, nil] an ID for the service check, defaults to the check name, ignored if part of a service definition.\n attribute :check_id\n validates :check_id, type: String\n\n # @return [String, nil] a name for the service check, defaults to the check id. required if standalone, ignored if part of service definition.\n attribute :check_name\n validates :check_name, type: String\n\n # @return [Object, nil] checks can be registered with a ttl instead of a script and interval this means that the service will check in with the agent before the ttl expires. If it doesn't the check will be considered failed. Required if registering a check and the script an interval are missing Similar to the interval this is a number with a s or m suffix to signify the units of seconds or minutes e.g 15s or 1m. If no suffix is supplied, m will be used by default e.g. 1 will be 1m\n attribute :ttl\n\n # @return [String, nil] checks can be registered with an http endpoint. This means that consul will check that the http endpoint returns a successful http status. Interval must also be provided with this option.\n attribute :http\n validates :http, type: String\n\n # @return [Object, nil] A custom HTTP check timeout. The consul default is 10 seconds. Similar to the interval this is a number with a s or m suffix to signify the units of seconds or minutes, e.g. 15s or 1m.\n attribute :timeout\n\n # @return [Object, nil] the token key indentifying an ACL rule set. May be required to register services.\n attribute :token\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6655231714248657, "alphanum_fraction": 0.6655231714248657, "avg_line_length": 42.724998474121094, "blob_id": "4c5045b9b36fbc0a3e7edc98c4a35145dfd15393", "content_id": "2fe5632a080cb6e4bbb3de0eab017d2bf40678aa", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1749, "license_type": "permissive", "max_line_length": 195, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_log_destination.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages log destinations on a BIG-IP.\n class Bigip_log_destination < Base\n # @return [String] Specifies the name of the log destination.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] The description of the log destination.\n attribute :description\n\n # @return [:\"remote-high-speed-log\", :\"remote-syslog\"] Specifies the type of log destination.,Once created, this parameter cannot be changed.\n attribute :type\n validates :type, presence: true, expression_inclusion: {:in=>[:\"remote-high-speed-log\", :\"remote-syslog\"], :message=>\"%{value} needs to be :\\\"remote-high-speed-log\\\", :\\\"remote-syslog\\\"\"}\n\n # @return [Hash, nil] This parameter is only available when C(type) is C(remote-high-speed-log).\n attribute :pool_settings\n validates :pool_settings, type: Hash\n\n # @return [Hash, nil] This parameter is only available when C(type) is C(remote-syslog).\n attribute :syslog_settings\n validates :syslog_settings, type: Hash\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [:present, :absent, nil] When C(present), ensures that the resource exists.,When C(absent), ensures the resource is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.652958869934082, "alphanum_fraction": 0.6575727462768555, "avg_line_length": 50.391754150390625, "blob_id": "f96773a5dfd82c551a942b7164529331ccc6f57f", "content_id": "8ce25609821e1c98fe414bc08a3b5f2e06acf480", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4985, "license_type": "permissive", "max_line_length": 242, "num_lines": 97, "path": "/lib/ansible/ruby/modules/generated/cloud/profitbricks/profitbricks.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, destroy, update, start, stop, and reboot a ProfitBricks virtual machine. When the virtual machine is created it can optionally wait for it to be 'running' before returning. This module has a dependency on profitbricks >= 1.0.0\n class Profitbricks < Base\n # @return [:yes, :no, nil] Whether or not to increment a single number in the name for created virtual machines.\n attribute :auto_increment\n validates :auto_increment, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String] The name of the virtual machine.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] The system image ID for creating the virtual machine, e.g. a3eae284-a2fe-11e4-b187-5f1f641608c8.\n attribute :image\n validates :image, presence: true, type: String\n\n # @return [Object, nil] Password set for the administrative user.\n attribute :image_password\n\n # @return [Object, nil] Public SSH keys allowing access to the virtual machine.\n attribute :ssh_keys\n\n # @return [String, nil] The datacenter to provision this virtual machine.\n attribute :datacenter\n validates :datacenter, type: String\n\n # @return [Integer, nil] The number of CPU cores to allocate to the virtual machine.\n attribute :cores\n validates :cores, type: Integer\n\n # @return [Integer, nil] The amount of memory to allocate to the virtual machine.\n attribute :ram\n validates :ram, type: Integer\n\n # @return [:AMD_OPTERON, :INTEL_XEON, nil] The CPU family type to allocate to the virtual machine.\n attribute :cpu_family\n validates :cpu_family, expression_inclusion: {:in=>[:AMD_OPTERON, :INTEL_XEON], :message=>\"%{value} needs to be :AMD_OPTERON, :INTEL_XEON\"}, allow_nil: true\n\n # @return [Integer, nil] The size in GB of the boot volume.\n attribute :volume_size\n validates :volume_size, type: Integer\n\n # @return [:IDE, :VIRTIO, nil] The bus type for the volume.\n attribute :bus\n validates :bus, expression_inclusion: {:in=>[:IDE, :VIRTIO], :message=>\"%{value} needs to be :IDE, :VIRTIO\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] list of instance ids, currently only used when state='absent' to remove instances.\n attribute :instance_ids\n validates :instance_ids, type: TypeGeneric.new(String)\n\n # @return [Integer, nil] The number of virtual machines to create.\n attribute :count\n validates :count, type: Integer\n\n # @return [:\"us/las\", :\"de/fra\", :\"de/fkb\", nil] The datacenter location. Use only if you want to create the Datacenter or else this value is ignored.\n attribute :location\n validates :location, expression_inclusion: {:in=>[:\"us/las\", :\"de/fra\", :\"de/fkb\"], :message=>\"%{value} needs to be :\\\"us/las\\\", :\\\"de/fra\\\", :\\\"de/fkb\\\"\"}, allow_nil: true\n\n # @return [:yes, :no, nil] This will assign the machine to the public LAN. If no LAN exists with public Internet access it is created.\n attribute :assign_public_ip\n validates :assign_public_ip, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] The ID of the LAN you wish to add the servers to.\n attribute :lan\n validates :lan, type: Integer\n\n # @return [Object, nil] The ProfitBricks username. Overrides the PB_SUBSCRIPTION_ID environment variable.\n attribute :subscription_user\n\n # @return [Object, nil] THe ProfitBricks password. Overrides the PB_PASSWORD environment variable.\n attribute :subscription_password\n\n # @return [:yes, :no, nil] wait for the instance to be in state 'running' before returning\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] how long before wait gives up, in seconds\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [:yes, :no, nil] remove the bootVolume of the virtual machine you're destroying.\n attribute :remove_boot_volume\n validates :remove_boot_volume, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:running, :stopped, :absent, :present, nil] create or terminate instances\n attribute :state\n validates :state, expression_inclusion: {:in=>[:running, :stopped, :absent, :present], :message=>\"%{value} needs to be :running, :stopped, :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7033748030662537, "alphanum_fraction": 0.7051509618759155, "avg_line_length": 62.73584747314453, "blob_id": "230c09bf1c16409e56d2689514d8e5bf3fb345c6", "content_id": "d0a8acf5e248d140abae3a519b9a8ed175bd7167", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3378, "license_type": "permissive", "max_line_length": 328, "num_lines": 53, "path": "/lib/ansible/ruby/modules/generated/database/proxysql/proxysql_mysql_users.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The M(proxysql_mysql_users) module adds or removes mysql users using the proxysql admin interface.\n class Proxysql_mysql_users < Base\n # @return [String] Name of the user connecting to the mysqld or ProxySQL instance.\n attribute :username\n validates :username, presence: true, type: String\n\n # @return [Object, nil] Password of the user connecting to the mysqld or ProxySQL instance.\n attribute :password\n\n # @return [Object, nil] A user with I(active) set to C(False) will be tracked in the database, but will be never loaded in the in-memory data structures. If omitted the proxysql database default for I(active) is C(True).\n attribute :active\n\n # @return [Object, nil] If I(use_ssl) is set to C(True), connections by this user will be made using SSL connections. If omitted the proxysql database default for I(use_ssl) is C(False).\n attribute :use_ssl\n\n # @return [Object, nil] If there is no matching rule for the queries sent by this user, the traffic it generates is sent to the specified hostgroup. If omitted the proxysql database default for I(use_ssl) is 0.\n attribute :default_hostgroup\n\n # @return [Object, nil] The schema to which the connection should change to by default.\n attribute :default_schema\n\n # @return [Object, nil] If this is set for the user with which the MySQL client is connecting to ProxySQL (thus a \"frontend\" user), transactions started within a hostgroup will remain within that hostgroup regardless of any other rules. If omitted the proxysql database default for I(transaction_persistent) is C(False).\n attribute :transaction_persistent\n\n # @return [Object, nil] If I(fast_forward) is set to C(True), I(fast_forward) will bypass the query processing layer (rewriting, caching) and pass through the query directly as is to the backend server. If omitted the proxysql database default for I(fast_forward) is C(False).\n attribute :fast_forward\n\n # @return [Boolean, nil] If I(backend) is set to C(True), this (username, password) pair is used for authenticating to the ProxySQL instance.\n attribute :backend\n validates :backend, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] If I(frontend) is set to C(True), this (username, password) pair is used for authenticating to the mysqld servers against any hostgroup.\n attribute :frontend\n validates :frontend, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] The maximum number of connections ProxySQL will open to the backend for this user. If omitted the proxysql database default for I(max_connections) is 10000.\n attribute :max_connections\n\n # @return [:present, :absent, nil] When C(present) - adds the user, when C(absent) - removes the user.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6821191906929016, "alphanum_fraction": 0.6821191906929016, "avg_line_length": 34.52941131591797, "blob_id": "0091ea16abc0c8163e298d2fbafb573930b1aa28", "content_id": "008ae2fc28ed056b9d883a2bac9e53a3268ca0f1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1208, "license_type": "permissive", "max_line_length": 101, "num_lines": 34, "path": "/lib/ansible/ruby/modules/generated/remote_management/redfish/redfish_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Builds Redfish URIs locally and sends them to remote OOB controllers to get information back.\n # Information retrieved is placed in a location specified by the user.\n class Redfish_facts < Base\n # @return [String, nil] List of categories to execute on OOB controller\n attribute :category\n validates :category, type: String\n\n # @return [Array<String>, String, nil] List of commands to execute on OOB controller\n attribute :command\n validates :command, type: TypeGeneric.new(String)\n\n # @return [String] Base URI of OOB controller\n attribute :baseuri\n validates :baseuri, presence: true, type: String\n\n # @return [String] User for authentication with OOB controller\n attribute :user\n validates :user, presence: true, type: String\n\n # @return [String] Password for authentication with OOB controller\n attribute :password\n validates :password, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6507009267807007, "alphanum_fraction": 0.6542056202888489, "avg_line_length": 43.27586364746094, "blob_id": "239e43c58034b4dde0d2ef920c9879c61f34bd96", "content_id": "a8a833915a0f0741d0d4241c009365e79d37b6d4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2568, "license_type": "permissive", "max_line_length": 212, "num_lines": 58, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_vpc.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and delete VPCs.\n class Cs_vpc < Base\n # @return [String] Name of the VPC.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Display text of the VPC.,If not set, C(name) will be used for creating.\n attribute :display_text\n validates :display_text, type: String\n\n # @return [String, nil] CIDR of the VPC, e.g. 10.1.0.0/16,All VPC guest networks' CIDRs must be within this CIDR.,Required on I(state=present).\n attribute :cidr\n validates :cidr, type: String\n\n # @return [Object, nil] Network domain for the VPC.,All networks inside the VPC will belong to this domain.,Only considered while creating the VPC, can not be changed.\n attribute :network_domain\n\n # @return [Object, nil] Name of the VPC offering.,If not set, default VPC offering is used.\n attribute :vpc_offering\n\n # @return [Symbol, nil] Whether to redeploy a VPC router or not when I(state=restarted)\n attribute :clean_up\n validates :clean_up, type: Symbol\n\n # @return [:present, :absent, :stopped, :restarted, nil] State of the VPC.,The state C(present) creates a started VPC.,The state C(stopped) is only considered while creating the VPC, added in version 2.6.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :stopped, :restarted], :message=>\"%{value} needs to be :present, :absent, :stopped, :restarted\"}, allow_nil: true\n\n # @return [Object, nil] Domain the VPC is related to.\n attribute :domain\n\n # @return [Object, nil] Account the VPC is related to.\n attribute :account\n\n # @return [Object, nil] Name of the project the VPC is related to.\n attribute :project\n\n # @return [Object, nil] Name of the zone.,If not set, default zone is used.\n attribute :zone\n\n # @return [Object, nil] List of tags. Tags are a list of dictionaries having keys C(key) and C(value).,For deleting all tags, set an empty list e.g. I(tags: []).\n attribute :tags\n\n # @return [Boolean, nil] Poll async jobs until job has finished.\n attribute :poll_async\n validates :poll_async, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6653576493263245, "alphanum_fraction": 0.6667601466178894, "avg_line_length": 46.53333282470703, "blob_id": "a0b5124d7289f5b79ffa76ae142ed1ae5800a072", "content_id": "b102bfe2fd5eeb7235e585f49cacfbc725faa3b9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3565, "license_type": "permissive", "max_line_length": 174, "num_lines": 75, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudscale/cloudscale_server.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, start, stop and delete servers on the cloudscale.ch IaaS service.\n # All operations are performed using the cloudscale.ch public API v1.\n # For details consult the full API documentation: U(https://www.cloudscale.ch/en/api/v1).\n # A valid API token is required for all operations. You can create as many tokens as you like using the cloudscale.ch control panel at U(https://control.cloudscale.ch).\n class Cloudscale_server < Base\n # @return [:running, :stopped, :absent, nil] State of the server\n attribute :state\n validates :state, expression_inclusion: {:in=>[:running, :stopped, :absent], :message=>\"%{value} needs to be :running, :stopped, :absent\"}, allow_nil: true\n\n # @return [String, nil] Name of the Server.,Either C(name) or C(uuid) are required. These options are mutually exclusive.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] UUID of the server.,Either C(name) or C(uuid) are required. These options are mutually exclusive.\n attribute :uuid\n validates :uuid, type: String\n\n # @return [String, nil] Flavor of the server.\n attribute :flavor\n validates :flavor, type: String\n\n # @return [String, nil] Image used to create the server.\n attribute :image\n validates :image, type: String\n\n # @return [Integer, nil] Size of the root volume in GB.\n attribute :volume_size_gb\n validates :volume_size_gb, type: Integer\n\n # @return [Integer, nil] Size of the bulk storage volume in GB.,No bulk storage volume if not set.\n attribute :bulk_volume_size_gb\n validates :bulk_volume_size_gb, type: Integer\n\n # @return [String, nil] List of SSH public keys.,Use the full content of your .pub file here.\n attribute :ssh_keys\n validates :ssh_keys, type: String\n\n # @return [Boolean, nil] Attach a public network interface to the server.\n attribute :use_public_network\n validates :use_public_network, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Attach a private network interface to the server.\n attribute :use_private_network\n validates :use_private_network, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Enable IPv6 on the public network interface.\n attribute :use_ipv6\n validates :use_ipv6, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] UUID of another server to create an anti-affinity group with.\n attribute :anti_affinity_with\n validates :anti_affinity_with, type: String\n\n # @return [Object, nil] Cloud-init configuration (cloud-config) data to use for the server.\n attribute :user_data\n\n # @return [String, nil] cloudscale.ch API token.,This can also be passed in the CLOUDSCALE_API_TOKEN environment variable.\n attribute :api_token\n validates :api_token, type: String\n\n # @return [Integer, nil] Timeout in seconds for calls to the cloudscale.ch API.\n attribute :api_timeout\n validates :api_timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.682645857334137, "alphanum_fraction": 0.6874767541885376, "avg_line_length": 50.75, "blob_id": "c8978e7285cf76844fdf6208d4d448378771f2c0", "content_id": "30dbe27728031b53ffc3d4032fdd3b156420b38d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2691, "license_type": "permissive", "max_line_length": 501, "num_lines": 52, "path": "/lib/ansible/ruby/modules/generated/database/misc/elasticsearch_plugin.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages Elasticsearch plugins.\n class Elasticsearch_plugin < Base\n # @return [String] Name of the plugin to install.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Desired state of a plugin.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Optionally set the source location to retrieve the plugin from. This can be a file:// URL to install from a local file, or a remote URL. If this is not set, the plugin location is just based on the name.,The name parameter must match the descriptor in the plugin ZIP specified.,Is only used if the state would change, which is solely checked based on the name parameter. If, for example, the plugin is already installed, changing this has no effect.,For ES 1.x use url.\n attribute :src\n\n # @return [Object, nil] Set exact URL to download the plugin from (Only works for ES 1.x).,For ES 2.x and higher, use src.\n attribute :url\n\n # @return [String, nil] Timeout setting: 30s, 1m, 1h...,Only valid for Elasticsearch < 5.0. This option is ignored for Elasticsearch > 5.0.\n attribute :timeout\n validates :timeout, type: String\n\n # @return [Boolean, nil] Force batch mode when installing plugins. This is only necessary if a plugin requires additional permissions and console detection fails.\n attribute :force\n validates :force, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] Location of the plugin binary. If this file is not found, the default plugin binaries will be used.,The default changed in Ansible 2.4 to None.\n attribute :plugin_bin\n\n # @return [String, nil] Your configured plugin directory specified in Elasticsearch\n attribute :plugin_dir\n validates :plugin_dir, type: String\n\n # @return [Object, nil] Proxy host to use during plugin installation\n attribute :proxy_host\n\n # @return [Object, nil] Proxy port to use during plugin installation\n attribute :proxy_port\n\n # @return [String, nil] Version of the plugin to be installed. If plugin exists with previous version, it will NOT be updated\n attribute :version\n validates :version, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6577253341674805, "alphanum_fraction": 0.6577253341674805, "avg_line_length": 38.65957260131836, "blob_id": "569f7765e8700020cf7173d6adccaf4df4080f06", "content_id": "0ce42133e977d61f671f04bd3a77c07da61ba21f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1864, "license_type": "permissive", "max_line_length": 159, "num_lines": 47, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_switch_leaf_selector.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Bind leaf selectors (with node block range and policy group) to switch policy leaf profiles on Cisco ACI fabrics.\n class Aci_switch_leaf_selector < Base\n # @return [Object, nil] The description to assign to the C(leaf).\n attribute :description\n\n # @return [String, nil] Name of the Leaf Profile to which we add a Selector.\n attribute :leaf_profile\n validates :leaf_profile, type: String\n\n # @return [String, nil] Name of Leaf Selector.\n attribute :leaf\n validates :leaf, type: String\n\n # @return [String, nil] Name of Node Block range to be added to Leaf Selector of given Leaf Profile.\n attribute :leaf_node_blk\n validates :leaf_node_blk, type: String\n\n # @return [Object, nil] The description to assign to the C(leaf_node_blk)\n attribute :leaf_node_blk_description\n\n # @return [Integer, nil] Start of Node Block range.\n attribute :from\n validates :from, type: Integer\n\n # @return [Integer, nil] Start of Node Block range.\n attribute :to\n validates :to, type: Integer\n\n # @return [String, nil] Name of the Policy Group to be added to Leaf Selector of given Leaf Profile.\n attribute :policy_group\n validates :policy_group, type: String\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6678129434585571, "alphanum_fraction": 0.6678129434585571, "avg_line_length": 41.764705657958984, "blob_id": "ca8d0ebf4187921dcf0ccc6f5ced2846815fb59f", "content_id": "2faf5cd4c41010bda577e7be99a02a5b6e279c2f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1454, "license_type": "permissive", "max_line_length": 182, "num_lines": 34, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_api_session.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used for calling any resources defined in Avi REST API. U(https://avinetworks.com/)\n # This module is useful for invoking HTTP Patch methods and accessing resources that do not have an REST object associated with them.\n class Avi_api_session < Base\n # @return [:get, :put, :post, :patch, :delete] Allowed HTTP methods for RESTful services and are supported by Avi Controller.\n attribute :http_method\n validates :http_method, presence: true, expression_inclusion: {:in=>[:get, :put, :post, :patch, :delete], :message=>\"%{value} needs to be :get, :put, :post, :patch, :delete\"}\n\n # @return [Hash, nil] HTTP body in YAML or JSON format.\n attribute :data\n validates :data, type: Hash\n\n # @return [Hash, nil] Query parameters passed to the HTTP API.\n attribute :params\n validates :params, type: Hash\n\n # @return [String, nil] Path for Avi API resource. For example, C(path: virtualservice) will translate to C(api/virtualserivce).\n attribute :path\n validates :path, type: String\n\n # @return [Integer, nil] Timeout (in seconds) for Avi API calls.\n attribute :timeout\n validates :timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7075664401054382, "alphanum_fraction": 0.7075664401054382, "avg_line_length": 29.5625, "blob_id": "944f74936080c21e606292f137c2ef6196829860", "content_id": "ce716cc721642101beb94d1722e0249b4ae365a6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 489, "license_type": "permissive", "max_line_length": 134, "num_lines": 16, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_client_config.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Get I(openstack) client config data from clouds.yaml or environment\n class Os_client_config < Base\n # @return [Object, nil] List of clouds to limit the return list to. No value means return information on all configured clouds\n attribute :clouds\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6700071692466736, "alphanum_fraction": 0.6732283234596252, "avg_line_length": 51.71697998046875, "blob_id": "e01cf71b19e4a2a69f1adefa5c3d0a8f02662ad1", "content_id": "f821b8f97fa7e3b9aa3aa3d57fb8a06321d73026", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2794, "license_type": "permissive", "max_line_length": 291, "num_lines": 53, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_epg.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage End Point Groups (EPG) on Cisco ACI fabrics.\n class Aci_epg < Base\n # @return [String, nil] Name of an existing tenant.\n attribute :tenant\n validates :tenant, type: String\n\n # @return [String] Name of an existing application network profile, that will contain the EPGs.\n attribute :ap\n validates :ap, presence: true, type: String\n\n # @return [String] Name of the end point group.\n attribute :epg\n validates :epg, presence: true, type: String\n\n # @return [String] Name of the bridge domain being associated with the EPG.\n attribute :bd\n validates :bd, presence: true, type: String\n\n # @return [:level1, :level2, :level3, :unspecified, nil] The QoS class.,The APIC defaults to C(unspecified) when unset during creation.\n attribute :priority\n validates :priority, expression_inclusion: {:in=>[:level1, :level2, :level3, :unspecified], :message=>\"%{value} needs to be :level1, :level2, :level3, :unspecified\"}, allow_nil: true\n\n # @return [:enforced, :unenforced, nil] The Intra EPG Isolation.,The APIC defaults to C(unenforced) when unset during creation.\n attribute :intra_epg_isolation\n validates :intra_epg_isolation, expression_inclusion: {:in=>[:enforced, :unenforced], :message=>\"%{value} needs to be :enforced, :unenforced\"}, allow_nil: true\n\n # @return [String, nil] Description for the EPG.\n attribute :description\n validates :description, type: String\n\n # @return [:none, :\"proxy-arp\", nil] The forwarding control used by the EPG.,The APIC defaults to C(none) when unset during creation.\n attribute :fwd_control\n validates :fwd_control, expression_inclusion: {:in=>[:none, :\"proxy-arp\"], :message=>\"%{value} needs to be :none, :\\\"proxy-arp\\\"\"}, allow_nil: true\n\n # @return [Symbol, nil] Whether ot not the EPG is part of the Preferred Group and can communicate without contracts.,This is very convenient for migration scenarios, or when ACI is used for network automation but not for policy.,The APIC defaults to C(no) when unset during creation.\n attribute :preferred_group\n validates :preferred_group, type: Symbol\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6742857098579407, "alphanum_fraction": 0.6742857098579407, "avg_line_length": 35.2068977355957, "blob_id": "2f73de73aa8f3c7cc47e4cf109e07f8ceb799ade", "content_id": "43594502ba80adc43308bf2dd339e11771f72c48", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1050, "license_type": "permissive", "max_line_length": 143, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/jboss.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Deploy applications to JBoss standalone using the filesystem\n class Jboss < Base\n # @return [String] The name of the deployment\n attribute :deployment\n validates :deployment, presence: true, type: String\n\n # @return [String, nil] The remote path of the application ear or war to deploy\n attribute :src\n validates :src, type: String\n\n # @return [String, nil] The location in the filesystem where the deployment scanner listens\n attribute :deploy_path\n validates :deploy_path, type: String\n\n # @return [:present, :absent, nil] Whether the application should be deployed or undeployed\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6866862773895264, "alphanum_fraction": 0.6866862773895264, "avg_line_length": 45.686275482177734, "blob_id": "d69c639718306b67262c3ce4479b6808de608e76", "content_id": "4927be6b8b7925df6b9683b0e51ed53380dad863", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2381, "license_type": "permissive", "max_line_length": 193, "num_lines": 51, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_elementsw_ldap.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Enable, disable ldap, and add ldap users\n class Na_elementsw_ldap < Base\n # @return [:present, :absent] Whether the specified volume should exist or not.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [:DirectBind, :SearchAndBind, nil] Identifies which user authentication method to use.\n attribute :authType\n validates :authType, expression_inclusion: {:in=>[:DirectBind, :SearchAndBind], :message=>\"%{value} needs to be :DirectBind, :SearchAndBind\"}, allow_nil: true\n\n # @return [Object, nil] The base DN of the tree to start the group search (will do a subtree search from here)\n attribute :groupSearchBaseDn\n\n # @return [:NoGroup, :ActiveDirectory, :MemberDN, nil] Controls the default group search filter used\n attribute :groupSearchType\n validates :groupSearchType, expression_inclusion: {:in=>[:NoGroup, :ActiveDirectory, :MemberDN], :message=>\"%{value} needs to be :NoGroup, :ActiveDirectory, :MemberDN\"}, allow_nil: true\n\n # @return [String, nil] A comma-separated list of LDAP server URIs\n attribute :serverURIs\n validates :serverURIs, type: String\n\n # @return [Object, nil] The base DN of the tree to start the search (will do a subtree search from here)\n attribute :userSearchBaseDN\n\n # @return [Object, nil] A dully qualified DN to log in with to perform an LDAp search for the user (needs read access to the LDAP directory).\n attribute :searchBindDN\n\n # @return [Object, nil] The password for the searchBindDN account used for searching\n attribute :searchBindPassword\n\n # @return [Object, nil] the LDAP Filter to use\n attribute :userSearchFilter\n\n # @return [Array<String>, String, nil] A string that is used form a fully qualified user DN.\n attribute :userDNTemplate\n validates :userDNTemplate, type: TypeGeneric.new(String)\n\n # @return [Object, nil] For use with the CustomFilter Search type\n attribute :groupSearchCustomFilter\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6619331240653992, "alphanum_fraction": 0.6703313589096069, "avg_line_length": 62.582523345947266, "blob_id": "6118f812e082317dd7dbd078178361b08c527bb6", "content_id": "78dd4ea2a9674edacb6b703bf257e4aa2f6e5e77", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6549, "license_type": "permissive", "max_line_length": 387, "num_lines": 103, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_bgp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages BGP configurations on HUAWEI CloudEngine switches.\n class Ce_bgp < Base\n # @return [:present, :absent, nil] Specify desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Local AS number. The value is a string of 1 to 11 characters.\n attribute :as_number\n\n # @return [:no_use, :true, :false, nil] Enable GR of the BGP speaker in the specified address family, peer address, or peer group.\n attribute :graceful_restart\n validates :graceful_restart, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [Object, nil] Period of waiting for the End-Of-RIB flag. The value is an integer ranging from 3 to 3000. The default value is 600.\n attribute :time_wait_for_rib\n\n # @return [Object, nil] Maximum number of AS numbers in the AS_Path attribute. The default value is 255.\n attribute :as_path_limit\n\n # @return [:no_use, :true, :false, nil] Check the first AS in the AS_Path of the update messages from EBGP peers.\n attribute :check_first_as\n validates :check_first_as, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [Object, nil] Confederation ID. The value is a string of 1 to 11 characters.\n attribute :confed_id_number\n\n # @return [:no_use, :true, :false, nil] Configure the device to be compatible with devices in a nonstandard confederation.\n attribute :confed_nonstanded\n validates :confed_nonstanded, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] The function to automatically select router IDs for all VPN BGP instances is enabled.\n attribute :bgp_rid_auto_sel\n validates :bgp_rid_auto_sel, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, the system stores all route update messages received from all peers (groups) after BGP connection setup. If the value is false, the system stores only BGP update messages that are received from peers and pass the configured import policy.\n attribute :keep_all_routes\n validates :keep_all_routes, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] Support BGP RIB memory protection.\n attribute :memory_limit\n validates :memory_limit, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] Peer disconnection through GR.\n attribute :gr_peer_reset\n validates :gr_peer_reset, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] Interrupt BGP all neighbor.\n attribute :is_shutdown\n validates :is_shutdown, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [Object, nil] Suppress interval.\n attribute :suppress_interval\n\n # @return [Object, nil] Hold interval.\n attribute :hold_interval\n\n # @return [Object, nil] Clear interval.\n attribute :clear_interval\n\n # @return [Object, nil] Confederation AS number, in two-byte or four-byte format. The value is a string of 1 to 11 characters.\n attribute :confed_peer_as_num\n\n # @return [Object, nil] Name of a BGP instance. The name is a case-sensitive string of characters.\n attribute :vrf_name\n\n # @return [:no_use, :true, :false, nil] If the value is true, VPN BGP instances are enabled to automatically select router IDs. If the value is false, VPN BGP instances are disabled from automatically selecting router IDs.\n attribute :vrf_rid_auto_sel\n validates :vrf_rid_auto_sel, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [Object, nil] ID of a router that is in IPv4 address format.\n attribute :router_id\n\n # @return [Object, nil] If the value of a timer changes, the BGP peer relationship between the routers is disconnected. The value is an integer ranging from 0 to 21845. The default value is 60.\n attribute :keepalive_time\n\n # @return [Object, nil] Hold time, in seconds. The value of the hold time can be 0 or range from 3 to 65535.\n attribute :hold_time\n\n # @return [Object, nil] Min hold time, in seconds. The value of the hold time can be 0 or range from 20 to 65535.\n attribute :min_hold_time\n\n # @return [Object, nil] ConnectRetry interval. The value is an integer, in seconds. The default value is 32s.\n attribute :conn_retry_time\n\n # @return [:no_use, :true, :false, nil] If the value is true, After the fast EBGP interface awareness function is enabled, EBGP sessions on an interface are deleted immediately when the interface goes Down. If the value is false, After the fast EBGP interface awareness function is enabled, EBGP sessions on an interface are not deleted immediately when the interface goes Down.\n attribute :ebgp_if_sensitive\n validates :ebgp_if_sensitive, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:ipv4uni, :ipv6uni, nil] Type of a created address family, which can be IPv4 unicast or IPv6 unicast. The default type is IPv4 unicast.\n attribute :default_af_type\n validates :default_af_type, expression_inclusion: {:in=>[:ipv4uni, :ipv6uni], :message=>\"%{value} needs to be :ipv4uni, :ipv6uni\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.67423015832901, "alphanum_fraction": 0.67423015832901, "avg_line_length": 28.380952835083008, "blob_id": "f8b0d4a82da2cc20785f69c5b58c8a315059dd47", "content_id": "8c19068ec651396552007df7b099e0338276da20", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 617, "license_type": "permissive", "max_line_length": 97, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_reboot.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Reboot a HUAWEI CloudEngine switches.\n class Ce_reboot < Base\n # @return [Symbol, nil] Safeguard boolean. Set to true if you're sure you want to reboot.\n attribute :confirm\n validates :confirm, type: Symbol\n\n # @return [Symbol, nil] Flag indicating whether to save the configuration.\n attribute :save_config\n validates :save_config, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6764857769012451, "alphanum_fraction": 0.6790697574615479, "avg_line_length": 57.6363639831543, "blob_id": "7079d38b151798a3ffecf330661cbf6838150440", "content_id": "3d9d19e62dedf020b194665607f49a9faf142961", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3870, "license_type": "permissive", "max_line_length": 454, "num_lines": 66, "path": "/lib/ansible/ruby/modules/generated/network/netvisor/pn_vlag.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Execute vlag-create/vlag-delete/vlag-modify command.\n # A virtual link aggregation group (VLAG) allows links that are physically connected to two different Pluribus Networks devices to appear as a single trunk to a third device. The third device can be a switch, server, or any Ethernet device. A VLAG can provide Layer 2 multipathing, which allows you to create redundancy by increasing bandwidth, enabling multiple parallel paths between nodes and loadbalancing traffic where alternative paths exist.\n class Pn_vlag < Base\n # @return [Object, nil] Provide login username if user is not root.\n attribute :pn_cliusername\n\n # @return [Object, nil] Provide login password if user is not root.\n attribute :pn_clipassword\n\n # @return [Object, nil] Target switch(es) to run this command on.\n attribute :pn_cliswitch\n\n # @return [:present, :absent, :update] State the action to perform. Use 'present' to create vlag, 'absent' to delete vlag and 'update' to modify vlag.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent, :update], :message=>\"%{value} needs to be :present, :absent, :update\"}\n\n # @return [String] The C(pn_name) takes a valid name for vlag configuration.\n attribute :pn_name\n validates :pn_name, presence: true, type: String\n\n # @return [String, nil] Specify the local VLAG port.,Required for vlag-create.\n attribute :pn_port\n validates :pn_port, type: String\n\n # @return [String, nil] Specify the peer VLAG port.,Required for vlag-create.\n attribute :pn_peer_port\n validates :pn_peer_port, type: String\n\n # @return [:\"active-active\", :\"active-standby\", nil] Specify the mode for the VLAG. Active-standby indicates one side is active and the other side is in standby mode. Active-active indicates that both sides of the vlag are up by default.\n attribute :pn_mode\n validates :pn_mode, expression_inclusion: {:in=>[:\"active-active\", :\"active-standby\"], :message=>\"%{value} needs to be :\\\"active-active\\\", :\\\"active-standby\\\"\"}, allow_nil: true\n\n # @return [String, nil] Specify the fabric-name of the peer switch.\n attribute :pn_peer_switch\n validates :pn_peer_switch, type: String\n\n # @return [:move, :ignore, nil] Specify the failover action as move or ignore.\n attribute :pn_failover_action\n validates :pn_failover_action, expression_inclusion: {:in=>[:move, :ignore], :message=>\"%{value} needs to be :move, :ignore\"}, allow_nil: true\n\n # @return [:off, :passive, :active, nil] Specify the LACP mode.\n attribute :pn_lacp_mode\n validates :pn_lacp_mode, expression_inclusion: {:in=>[:off, :passive, :active], :message=>\"%{value} needs to be :off, :passive, :active\"}, allow_nil: true\n\n # @return [:slow, :fast, nil] Specify the LACP timeout as slow(30 seconds) or fast(4 seconds).\n attribute :pn_lacp_timeout\n validates :pn_lacp_timeout, expression_inclusion: {:in=>[:slow, :fast], :message=>\"%{value} needs to be :slow, :fast\"}, allow_nil: true\n\n # @return [:bundle, :individual, nil] Specify the LACP fallback mode as bundles or individual.\n attribute :pn_lacp_fallback\n validates :pn_lacp_fallback, expression_inclusion: {:in=>[:bundle, :individual], :message=>\"%{value} needs to be :bundle, :individual\"}, allow_nil: true\n\n # @return [Object, nil] Specify the LACP fallback timeout in seconds. The range is between 30 and 60 seconds with a default value of 50 seconds.\n attribute :pn_lacp_fallback_timeout\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7070393562316895, "alphanum_fraction": 0.7093685269355774, "avg_line_length": 66.78947448730469, "blob_id": "656b052add8a961cd050266de06c40d9f593107e", "content_id": "ee92e212a2826df68bd36e5b03923c931094c923", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3864, "license_type": "permissive", "max_line_length": 323, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_interface_policy_port_channel.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage port channel interface policies on Cisco ACI fabrics.\n class Aci_interface_policy_port_channel < Base\n # @return [String] Name of the port channel.\n attribute :port_channel\n validates :port_channel, presence: true, type: String\n\n # @return [String, nil] The description for the port channel.\n attribute :description\n validates :description, type: String\n\n # @return [Integer, nil] Maximum links.,Accepted values range between 1 and 16.,The APIC defaults to C(16) when unset during creation.\n attribute :max_links\n validates :max_links, type: Integer\n\n # @return [Integer, nil] Minimum links.,Accepted values range between 1 and 16.,The APIC defaults to C(1) when unset during creation.\n attribute :min_links\n validates :min_links, type: Integer\n\n # @return [:active, :\"mac-pin\", :\"mac-pin-nicload\", :off, :passive, nil] Port channel interface policy mode.,Determines the LACP method to use for forming port-channels.,The APIC defaults to C(off) when unset during creation.\n attribute :mode\n validates :mode, expression_inclusion: {:in=>[:active, :\"mac-pin\", :\"mac-pin-nicload\", :off, :passive], :message=>\"%{value} needs to be :active, :\\\"mac-pin\\\", :\\\"mac-pin-nicload\\\", :off, :passive\"}, allow_nil: true\n\n # @return [Symbol, nil] Determines if Fast Select is enabled for Hot Standby Ports.,This makes up the LACP Policy Control Policy; if one setting is defined, then all other Control Properties left undefined or set to false will not exist after the task is ran.,The APIC defaults to C(yes) when unset during creation.\n attribute :fast_select\n validates :fast_select, type: Symbol\n\n # @return [Symbol, nil] Determines if Graceful Convergence is enabled.,This makes up the LACP Policy Control Policy; if one setting is defined, then all other Control Properties left undefined or set to false will not exist after the task is ran.,The APIC defaults to C(yes) when unset during creation.\n attribute :graceful_convergence\n validates :graceful_convergence, type: Symbol\n\n # @return [Symbol, nil] Determines if Load Defer is enabled.,This makes up the LACP Policy Control Policy; if one setting is defined, then all other Control Properties left undefined or set to false will not exist after the task is ran.,The APIC defaults to C(no) when unset during creation.\n attribute :load_defer\n validates :load_defer, type: Symbol\n\n # @return [Symbol, nil] Determines if Suspend Individual is enabled.,This makes up the LACP Policy Control Policy; if one setting is defined, then all other Control Properties left undefined or set to false will not exist after the task is ran.,The APIC defaults to C(yes) when unset during creation.\n attribute :suspend_individual\n validates :suspend_individual, type: Symbol\n\n # @return [Symbol, nil] Determines if Symmetric Hashing is enabled.,This makes up the LACP Policy Control Policy; if one setting is defined, then all other Control Properties left undefined or set to false will not exist after the task is ran.,The APIC defaults to C(no) when unset during creation.\n attribute :symmetric_hash\n validates :symmetric_hash, type: Symbol\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6863829493522644, "alphanum_fraction": 0.6876595616340637, "avg_line_length": 52.40909194946289, "blob_id": "f2bf2a864d649e390635ab7ed759400abc45d177", "content_id": "d12efb9ddf6a3fe57778d1668fd5f5381bc4bd42", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2350, "license_type": "permissive", "max_line_length": 527, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_host_networks.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Module to manage host networks in oVirt/RHV.\n class Ovirt_host_network < Base\n # @return [String] Name of the host to manage networks for.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Should the host be present/absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Hash, nil] Dictionary describing network bond:,C(name) - Bond name.,C(mode) - Bonding mode.,C(options) - Bonding options.,C(interfaces) - List of interfaces to create a bond.\n attribute :bond\n validates :bond, type: Hash\n\n # @return [String, nil] Name of the network interface where logical network should be attached.\n attribute :interface\n validates :interface, type: String\n\n # @return [Array<Hash>, Hash, nil] List of dictionary describing networks to be attached to interface or bond:,C(name) - Name of the logical network to be assigned to bond or interface.,C(boot_protocol) - Boot protocol one of the I(none), I(static) or I(dhcp).,C(address) - IP address in case of I(static) boot protocol is used.,C(netmask) - Subnet mask in case of I(static) boot protocol is used.,C(gateway) - Gateway in case of I(static) boot protocol is used.,C(version) - IP version. Either v4 or v6. Default is v4.\n attribute :networks\n validates :networks, type: TypeGeneric.new(Hash)\n\n # @return [Object, nil] List of names of the network label to be assigned to bond or interface.\n attribute :labels\n\n # @return [Symbol, nil] If I(true) verify connectivity between host and engine.,Network configuration changes will be rolled back if connectivity between engine and the host is lost after changing network configuration.\n attribute :check\n validates :check, type: Symbol\n\n # @return [Symbol, nil] If I(true) network configuration will be persistent, by default they are temporary.\n attribute :save\n validates :save, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6869158744812012, "alphanum_fraction": 0.6869158744812012, "avg_line_length": 31.100000381469727, "blob_id": "83b7204bdd3c9fc5b505a4133288eebbe0772f21", "content_id": "e74334baae791562929735296496f162d42a33c5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 642, "license_type": "permissive", "max_line_length": 157, "num_lines": 20, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_smu.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Perform software maintenance upgrades (SMUs) on Cisco NX-OS devices.\n class Nxos_smu < Base\n # @return [String] Name of the remote package.\n attribute :pkg\n validates :pkg, presence: true, type: String\n\n # @return [Object, nil] The remote file system of the device. If omitted, devices that support a file_system parameter will use their default values.\n attribute :file_system\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6737623810768127, "alphanum_fraction": 0.6737623810768127, "avg_line_length": 41.08333206176758, "blob_id": "ade5738f4a3eddf0a977f8e79bf4bb0ae0ccb92b", "content_id": "922f92ee5c2f2dc70df648bac98b444be48cf900", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2020, "license_type": "permissive", "max_line_length": 318, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ecs_task.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates or deletes instances of task definitions.\n class Ecs_task < Base\n # @return [:run, :start, :stop] Which task operation to execute\n attribute :operation\n validates :operation, presence: true, expression_inclusion: {:in=>[:run, :start, :stop], :message=>\"%{value} needs to be :run, :start, :stop\"}\n\n # @return [String, nil] The name of the cluster to run the task on\n attribute :cluster\n validates :cluster, type: String\n\n # @return [String, nil] The task definition to start or run\n attribute :task_definition\n validates :task_definition, type: String\n\n # @return [Object, nil] A dictionary of values to pass to the new instances\n attribute :overrides\n\n # @return [Integer, nil] How many new instances to start\n attribute :count\n validates :count, type: Integer\n\n # @return [String, nil] The task to stop\n attribute :task\n validates :task, type: String\n\n # @return [Array<String>, String, nil] The list of container instances on which to deploy the task\n attribute :container_instances\n validates :container_instances, type: TypeGeneric.new(String)\n\n # @return [String, nil] A value showing who or what started the task (for informational purposes)\n attribute :started_by\n validates :started_by, type: String\n\n # @return [Hash, nil] network configuration of the service. Only applicable for task definitions created with C(awsvpc) I(network_mode).,I(network_configuration) has two keys, I(subnets), a list of subnet IDs to which the task is attached and I(security_groups), a list of group names or group IDs for the task\n attribute :network_configuration\n validates :network_configuration, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6643356680870056, "alphanum_fraction": 0.6720279455184937, "avg_line_length": 37.64864730834961, "blob_id": "c8cac6cd3e7f095ff8609c75f2861c40120cd68f", "content_id": "a884faa8f43f8a8564a775fef22d81db1527494e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1430, "license_type": "permissive", "max_line_length": 162, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_igmp_snooping.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages IGMP snooping global configuration.\n class Nxos_igmp_snooping < Base\n # @return [Symbol, nil] Enables/disables IGMP snooping on the switch.\n attribute :snooping\n validates :snooping, type: Symbol\n\n # @return [String, nil] Group membership timeout value for all VLANs on the device. Accepted values are integer in range 1-10080, I(never) and I(default).\n attribute :group_timeout\n validates :group_timeout, type: String\n\n # @return [Symbol, nil] Global link-local groups suppression.\n attribute :link_local_grp_supp\n validates :link_local_grp_supp, type: Symbol\n\n # @return [Symbol, nil] Global IGMPv1/IGMPv2 Report Suppression.\n attribute :report_supp\n validates :report_supp, type: Symbol\n\n # @return [Symbol, nil] Global IGMPv3 Report Suppression and Proxy Reporting.\n attribute :v3_report_supp\n validates :v3_report_supp, type: Symbol\n\n # @return [:present, :default, nil] Manage the state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :default], :message=>\"%{value} needs to be :present, :default\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7040358781814575, "alphanum_fraction": 0.7053548097610474, "avg_line_length": 62.18333435058594, "blob_id": "d95abdb49c4d14950f4027ead54fd0bdbb00e937", "content_id": "75e4a184827ea69509ac42ea90a73194591c073d", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3791, "license_type": "permissive", "max_line_length": 425, "num_lines": 60, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_smtp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows configuring of the BIG-IP to send mail via an SMTP server by configuring the parameters of an SMTP server.\n class Bigip_smtp < Base\n # @return [String] Specifies the name of the SMTP server configuration.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [String, nil] SMTP server host name in the format of a fully qualified domain name.,This value is required when create a new SMTP configuration.\n attribute :smtp_server\n validates :smtp_server, type: String\n\n # @return [Object, nil] Specifies the SMTP port number.,When creating a new SMTP configuration, the default is C(25) when C(encryption) is C(none) or C(tls). The default is C(465) when C(ssl) is selected.\n attribute :smtp_server_port\n\n # @return [String, nil] Host name used in SMTP headers in the format of a fully qualified domain name. This setting does not refer to the BIG-IP system's hostname.\n attribute :local_host_name\n validates :local_host_name, type: String\n\n # @return [String, nil] Email address that the email is being sent from. This is the \"Reply-to\" address that the recipient sees.\n attribute :from_address\n validates :from_address, type: String\n\n # @return [:none, :ssl, :tls, nil] Specifies whether the SMTP server requires an encrypted connection in order to send mail.\n attribute :encryption\n validates :encryption, expression_inclusion: {:in=>[:none, :ssl, :tls], :message=>\"%{value} needs to be :none, :ssl, :tls\"}, allow_nil: true\n\n # @return [Symbol, nil] Credentials can be set on an SMTP server's configuration even if that authentication is not used (think staging configs or emergency changes). This parameter acts as a switch to make the specified C(smtp_server_username) and C(smtp_server_password) parameters active or not.,When C(yes), the authentication parameters will be active.,When C(no), the authentication parameters will be inactive.\n attribute :authentication\n validates :authentication, type: Symbol\n\n # @return [String, nil] User name that the SMTP server requires when validating a user.\n attribute :smtp_server_username\n validates :smtp_server_username, type: String\n\n # @return [String, nil] Password that the SMTP server requires when validating a user.\n attribute :smtp_server_password\n validates :smtp_server_password, type: String\n\n # @return [:present, :absent, nil] When C(present), ensures that the SMTP configuration exists.,When C(absent), ensures that the SMTP configuration does not exist.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:always, :on_create, nil] Passwords are stored encrypted, so the module cannot know if the supplied C(smtp_server_password) is the same or different than the existing password. This parameter controls the updating of the C(smtp_server_password) credential.,When C(always), will always update the password.,When C(on_create), will only set the password for newly created SMTP server configurations.\n attribute :update_password\n validates :update_password, expression_inclusion: {:in=>[:always, :on_create], :message=>\"%{value} needs to be :always, :on_create\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6903747916221619, "alphanum_fraction": 0.690800666809082, "avg_line_length": 44.153846740722656, "blob_id": "d6cb281f2dbe49b86845eb32e5ee0156cf37f7e8", "content_id": "42214d8ee075a1528a2b5e4e1222ae0efd11fba0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2348, "license_type": "permissive", "max_line_length": 203, "num_lines": 52, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_direct_connect_link_aggregation_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, delete, or modify a Direct Connect link aggregation group.\n class Aws_direct_connect_link_aggregation_group < Base\n # @return [:present, :absent, nil] The state of the Direct Connect link aggregation group.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] The name of the Direct Connect link aggregation group.\n attribute :name\n\n # @return [Object, nil] The ID of the Direct Connect link aggregation group.\n attribute :link_aggregation_group_id\n\n # @return [Object, nil] The number of connections with which to intialize the link aggregation group.\n attribute :num_connections\n\n # @return [Object, nil] The minimum number of physical connections that must be operational for the LAG itself to be operational.\n attribute :min_links\n\n # @return [Object, nil] The location of the link aggregation group.\n attribute :location\n\n # @return [Object, nil] The bandwidth of the link aggregation group.\n attribute :bandwidth\n\n # @return [Object, nil] This allows the minimum number of links to be set to 0, any hosted connections disassociated, and any virtual interfaces associated to the LAG deleted.\n attribute :force_delete\n\n # @return [Object, nil] A connection ID to link with the link aggregation group upon creation.\n attribute :connection_id\n\n # @return [Object, nil] To be used with I(state=absent) to delete connections after disassociating them with the LAG.\n attribute :delete_with_disassociation\n\n # @return [Symbol, nil] Whether or not to wait for the operation to complete. May be useful when waiting for virtual interfaces to be deleted. May modify the time of waiting with C(wait_timeout).\n attribute :wait\n validates :wait, type: Symbol\n\n # @return [Integer, nil] The duration in seconds to wait if I(wait) is True.\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.69392991065979, "alphanum_fraction": 0.6942148804664612, "avg_line_length": 71.35051727294922, "blob_id": "300cc0e55ed4dec34bbb9c753bb9638ecefc5341", "content_id": "c44cf3f17cde43fc0bf6628f228074103871d9c3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 7018, "license_type": "permissive", "max_line_length": 500, "num_lines": 97, "path": "/lib/ansible/ruby/modules/generated/packaging/os/dnf.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Installs, upgrade, removes, and lists packages and groups with the I(dnf) package manager.\n class Dnf < Base\n # @return [String] A package name or package specifier with version, like C(name-1.0). When using state=latest, this can be '*' which means run: dnf -y update. You can also pass a url or a local path to a rpm file. To operate on several packages this can accept a comma separated string of packages or a list of packages.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Various (non-idempotent) commands for usage with C(/usr/bin/ansible) and I(not) playbooks. See examples.\n attribute :list\n\n # @return [:absent, :present, :installed, :removed, :latest, nil] Whether to install (C(present), C(latest)), or remove (C(absent)) a package.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :installed, :removed, :latest], :message=>\"%{value} needs to be :absent, :present, :installed, :removed, :latest\"}, allow_nil: true\n\n # @return [String, nil] I(Repoid) of repositories to enable for the install/update operation. These repos will not persist beyond the transaction. When specifying multiple repos, separate them with a \",\".\n attribute :enablerepo\n validates :enablerepo, type: String\n\n # @return [Object, nil] I(Repoid) of repositories to disable for the install/update operation. These repos will not persist beyond the transaction. When specifying multiple repos, separate them with a \",\".\n attribute :disablerepo\n\n # @return [Object, nil] The remote dnf configuration file to use for the transaction.\n attribute :conf_file\n\n # @return [:yes, :no, nil] Whether to disable the GPG checking of signatures of packages being installed. Has an effect only if state is I(present) or I(latest).\n attribute :disable_gpg_check\n validates :disable_gpg_check, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Specifies an alternative installroot, relative to which all packages will be installed.\n attribute :installroot\n validates :installroot, type: String\n\n # @return [Object, nil] Specifies an alternative release from which all packages will be installed.\n attribute :releasever\n\n # @return [Symbol, nil] If C(yes), removes all \"leaf\" packages from the system that were originally installed as dependencies of user-installed packages but which are no longer required by any such package. Should be used alone or when state is I(absent)\n attribute :autoremove\n validates :autoremove, type: Symbol\n\n # @return [Object, nil] Package name(s) to exclude when state=present, or latest. This can be a list or a comma separated string.\n attribute :exclude\n\n # @return [:yes, :no, nil] Skip packages with broken dependencies(devsolve) and are causing problems.\n attribute :skip_broken\n validates :skip_broken, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Force yum to check if cache is out of date and redownload if needed. Has an effect only if state is I(present) or I(latest).\n attribute :update_cache\n validates :update_cache, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] When using latest, only update installed packages. Do not install packages.,Has an effect only if state is I(latest)\n attribute :update_only\n validates :update_only, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If set to C(yes), and C(state=latest) then only installs updates that have been marked security related.\n attribute :security\n validates :security, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If set to C(yes), and C(state=latest) then only installs updates that have been marked bugfix related.\n attribute :bugfix\n validates :bugfix, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] I(Plugin) name to enable for the install/update operation. The enabled plugin will not persist beyond the transaction.\n attribute :enable_plugin\n\n # @return [Object, nil] I(Plugin) name to disable for the install/update operation. The disabled plugins will not persist beyond the transaction.\n attribute :disable_plugin\n\n # @return [Object, nil] Disable the excludes defined in DNF config files.,If set to C(all), disables all excludes.,If set to C(main), disable excludes defined in [main] in yum.conf.,If set to C(repoid), disable excludes defined for given repo id.\n attribute :disable_excludes\n\n # @return [:yes, :no, nil] This only applies if using a https url as the source of the rpm. e.g. for localinstall. If set to C(no), the SSL certificates will not be validated.,This should only set to C(no) used on personally controlled sites using self-signed certificates as it avoids verifying the source site.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Symbol, nil] Specify if the named package and version is allowed to downgrade a maybe already installed higher version of that package. Note that setting allow_downgrade=True can make this module behave in a non-idempotent way. The task could end up with a set of packages that does not match the complete list of specified packages to install (because dependencies between the downgraded package and others can cause changes to the packages which were in the earlier transaction).\n attribute :allow_downgrade\n validates :allow_downgrade, type: Symbol\n\n # @return [Boolean, nil] This is effectively a no-op in DNF as it is not needed with DNF, but is an accepted parameter for feature parity/compatibility with the I(yum) module.\n attribute :install_repoquery\n validates :install_repoquery, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Only download the packages, do not install them.\n attribute :download_only\n validates :download_only, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6793451905250549, "alphanum_fraction": 0.6851227879524231, "avg_line_length": 45.155555725097656, "blob_id": "c0f600d2b463d4eb11a2d2153c43b91f8a4247b9", "content_id": "cd5342aaf59516b471af4c9a8a79e2c3f119bbe0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2077, "license_type": "permissive", "max_line_length": 196, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_nic.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Module to manage network interfaces of Virtual Machines in oVirt/RHV.\n class Ovirt_nic < Base\n # @return [String] Name of the network interface to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Name of the Virtual Machine to manage.,You must provide either C(vm) parameter or C(template) parameter.\n attribute :vm\n validates :vm, type: String\n\n # @return [String, nil] Name of the template to manage.,You must provide either C(vm) parameter or C(template) parameter.\n attribute :template\n validates :template, type: String\n\n # @return [:absent, :plugged, :present, :unplugged, nil] Should the Virtual Machine NIC be present/absent/plugged/unplugged.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :plugged, :present, :unplugged], :message=>\"%{value} needs to be :absent, :plugged, :present, :unplugged\"}, allow_nil: true\n\n # @return [String, nil] Logical network to which the VM network interface should use, by default Empty network is used if network is not specified.\n attribute :network\n validates :network, type: String\n\n # @return [String, nil] Virtual network interface profile to be attached to VM network interface.\n attribute :profile\n validates :profile, type: String\n\n # @return [String, nil] Type of the network interface. For example e1000, pci_passthrough, rtl8139, rtl8139_virtio, spapr_vlan or virtio.,It's required parameter when creating the new NIC.\n attribute :interface\n validates :interface, type: String\n\n # @return [String, nil] Custom MAC address of the network interface, by default it's obtained from MAC pool.\n attribute :mac_address\n validates :mac_address, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6835852861404419, "alphanum_fraction": 0.6835852861404419, "avg_line_length": 55.121212005615234, "blob_id": "a5306f2d346a0fa2aa6282a59678b364e9c3d465", "content_id": "4a250d7d5e05099227614cd072fc0af747ff8015", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1852, "license_type": "permissive", "max_line_length": 327, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/source_control/git_config.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The C(git_config) module changes git configuration by invoking 'git config'. This is needed if you don't want to use M(template) for the entire git config file (e.g. because you need to change just C(user.email) in /etc/.git/config). Solutions involving M(command) are cumbersome or don't work correctly in check mode.\n class Git_config < Base\n # @return [:yes, :no, nil] List all settings (optionally limited to a given I(scope))\n attribute :list_all\n validates :list_all, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] The name of the setting. If no value is supplied, the value will be read from the config if it has been set.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] Path to a git repository for reading and writing values from a specific repo.\n attribute :repo\n validates :repo, type: String\n\n # @return [:local, :global, :system, nil] Specify which scope to read/set values from. This is required when setting config values. If this is set to local, you must also specify the repo parameter. It defaults to system only when not using I(list_all)=yes.\n attribute :scope\n validates :scope, expression_inclusion: {:in=>[:local, :global, :system], :message=>\"%{value} needs to be :local, :global, :system\"}, allow_nil: true\n\n # @return [String, nil] When specifying the name of a single setting, supply a value to set that setting to the given value.\n attribute :value\n validates :value, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6593578457832336, "alphanum_fraction": 0.6683633327484131, "avg_line_length": 47.18867874145508, "blob_id": "c3265571c30d0dad5435b99f6d01c64f35e8bdd0", "content_id": "9e6fca1df5a7dcc757e9593bcd33c7ed3887789f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2554, "license_type": "permissive", "max_line_length": 222, "num_lines": 53, "path": "/lib/ansible/ruby/modules/generated/network/junos/junos_logging.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of logging on Juniper JUNOS devices.\n class Junos_logging < Base\n # @return [:console, :host, :file, :user, nil] Destination of the logs.\n attribute :dest\n validates :dest, expression_inclusion: {:in=>[:console, :host, :file, :user], :message=>\"%{value} needs to be :console, :host, :file, :user\"}, allow_nil: true\n\n # @return [String, nil] If value of C(dest) is I(file) it indicates file-name, for I(user) it indicates username and for I(host) indicates the host name to be notified.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] Set logging facility.\n attribute :facility\n validates :facility, type: String\n\n # @return [String, nil] Set logging severity levels.\n attribute :level\n validates :level, type: String\n\n # @return [Array<Hash>, Hash, nil] List of logging definitions.\n attribute :aggregate\n validates :aggregate, type: TypeGeneric.new(Hash)\n\n # @return [:present, :absent, nil] State of the logging configuration.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Boolean, nil] Specifies whether or not the configuration is active or deactivated\n attribute :active\n validates :active, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Integer, nil] Rotate log frequency in minutes, this is applicable if value of I(dest) is C(file). The acceptable value is in range of 1 to 59. This controls the frequency after which log file is rotated.\n attribute :rotate_frequency\n validates :rotate_frequency, type: Integer\n\n # @return [Integer, nil] Size of the file in archive, this is applicable if value of I(dest) is C(file). The acceptable value is in range from 65536 to 1073741824 bytes.\n attribute :size\n validates :size, type: Integer\n\n # @return [Integer, nil] Number of files to be archived, this is applicable if value of I(dest) is C(file). The acceptable value is in range from 1 to 1000.\n attribute :files\n validates :files, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6670323610305786, "alphanum_fraction": 0.6670323610305786, "avg_line_length": 44.57500076293945, "blob_id": "f56f356280653dd01b68d565c52478e74d96e9ab", "content_id": "00f80f59ea75f0ec8689da0bc4882712b8c59fc7", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1823, "license_type": "permissive", "max_line_length": 176, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_image.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, delete an image from virtual machine, blob uri, managed disk or snapshot.\n class Azure_rm_image < Base\n # @return [String] Name of resource group.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] Name of the image.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] OS disk source from the same region, including a virtual machine id or name, OS disk blob uri, managed OS disk id or name, or OS snapshot id or name.\n attribute :source\n validates :source, presence: true, type: String\n\n # @return [Array<String>, String, nil] List of data disk sources, including unmanaged blob uri, managed disk id or name, or snapshot id or name.\n attribute :data_disk_sources\n validates :data_disk_sources, type: TypeGeneric.new(String)\n\n # @return [Object, nil] Location of the image. Derived from I(resource_group) if not specified.\n attribute :location\n\n # @return [:Windows, :Linux, nil] The OS type of image.\n attribute :os_type\n validates :os_type, expression_inclusion: {:in=>[:Windows, :Linux], :message=>\"%{value} needs to be :Windows, :Linux\"}, allow_nil: true\n\n # @return [:absent, :present, nil] Assert the state of the image. Use C(present) to create or update a image and C(absent) to delete an image.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7093448042869568, "alphanum_fraction": 0.7133230566978455, "avg_line_length": 88.25362396240234, "blob_id": "026e67f76d3e0187526ec1512942eb40b24b983e", "content_id": "077286ef5187bce6baf629b6a4ab7fbc85579d58", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 12317, "license_type": "permissive", "max_line_length": 611, "num_lines": 138, "path": "/lib/ansible/ruby/modules/generated/system/iptables.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Iptables is used to set up, maintain, and inspect the tables of IP packet filter rules in the Linux kernel.\n # This module does not handle the saving and/or loading of rules, but rather only manipulates the current rules that are present in memory. This is the same as the behaviour of the C(iptables) and C(ip6tables) command which this module uses internally.\n class Iptables < Base\n # @return [:filter, :nat, :mangle, :raw, :security, nil] This option specifies the packet matching table which the command should operate on. If the kernel is configured with automatic module loading, an attempt will be made to load the appropriate module for that table if it is not already there.\n attribute :table\n validates :table, expression_inclusion: {:in=>[:filter, :nat, :mangle, :raw, :security], :message=>\"%{value} needs to be :filter, :nat, :mangle, :raw, :security\"}, allow_nil: true\n\n # @return [:absent, :present, nil] Whether the rule should be absent or present.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:append, :insert, nil] Whether the rule should be appended at the bottom or inserted at the top.,If the rule already exists the chain won't be modified.\n attribute :action\n validates :action, expression_inclusion: {:in=>[:append, :insert], :message=>\"%{value} needs to be :append, :insert\"}, allow_nil: true\n\n # @return [Integer, nil] Insert the rule as the given rule number. This works only with action = 'insert'.\n attribute :rule_num\n validates :rule_num, type: Integer\n\n # @return [:ipv4, :ipv6, nil] Which version of the IP protocol this rule should apply to.\n attribute :ip_version\n validates :ip_version, expression_inclusion: {:in=>[:ipv4, :ipv6], :message=>\"%{value} needs to be :ipv4, :ipv6\"}, allow_nil: true\n\n # @return [String, nil] Chain to operate on.,This option can either be the name of a user defined chain or any of the builtin chains: 'INPUT', 'FORWARD', 'OUTPUT', 'PREROUTING', 'POSTROUTING', 'SECMARK', 'CONNSECMARK'.\n attribute :chain\n validates :chain, type: String\n\n # @return [String, nil] The protocol of the rule or of the packet to check.,The specified protocol can be one of tcp, udp, udplite, icmp, esp, ah, sctp or the special keyword \"all\", or it can be a numeric value, representing one of these protocols or a different one. A protocol name from /etc/protocols is also allowed. A \"!\" argument before the protocol inverts the test. The number zero is equivalent to all. \"all\" will match with all protocols and is taken as default when this option is omitted.\n attribute :protocol\n validates :protocol, type: String\n\n # @return [String, nil] Source specification.,Address can be either a network name, a hostname, a network IP address (with /mask), or a plain IP address.,Hostnames will be resolved once only, before the rule is submitted to the kernel. Please note that specifying any name to be resolved with a remote query such as DNS is a really bad idea.,The mask can be either a network mask or a plain number, specifying the number of 1's at the left side of the network mask. Thus, a mask of 24 is equivalent to 255.255.255.0. A \"!\" argument before the address specification inverts the sense of the address.\n attribute :source\n validates :source, type: String\n\n # @return [Object, nil] Destination specification.,Address can be either a network name, a hostname, a network IP address (with /mask), or a plain IP address.,Hostnames will be resolved once only, before the rule is submitted to the kernel. Please note that specifying any name to be resolved with a remote query such as DNS is a really bad idea.,The mask can be either a network mask or a plain number, specifying the number of 1's at the left side of the network mask. Thus, a mask of 24 is equivalent to 255.255.255.0. A \"!\" argument before the address specification inverts the sense of the address.\n attribute :destination\n\n # @return [Object, nil] TCP flags specification.,C(tcp_flags) expects a dict with the two keys C(flags) and C(flags_set).\n attribute :tcp_flags\n\n # @return [Object, nil] Specifies a match to use, that is, an extension module that tests for a specific property. The set of matches make up the condition under which a target is invoked. Matches are evaluated first to last if specified as an array and work in short-circuit fashion, i.e. if one extension yields false, evaluation will stop.\n attribute :match\n\n # @return [String, nil] This specifies the target of the rule; i.e., what to do if the packet matches it. The target can be a user-defined chain (other than the one this rule is in), one of the special builtin targets which decide the fate of the packet immediately, or an extension (see EXTENSIONS below). If this option is omitted in a rule (and the goto parameter is not used), then matching the rule will have no effect on the packet's fate, but the counters on the rule will be incremented.\n attribute :jump\n validates :jump, type: String\n\n # @return [Object, nil] Specifies a log text for the rule. Only make sense with a LOG jump.\n attribute :log_prefix\n\n # @return [Object, nil] This specifies that the processing should continue in a user specified chain. Unlike the jump argument return will not continue processing in this chain but instead in the chain that called us via jump.\n attribute :goto\n\n # @return [String, nil] Name of an interface via which a packet was received (only for packets entering the INPUT, FORWARD and PREROUTING chains). When the \"!\" argument is used before the interface name, the sense is inverted. If the interface name ends in a \"+\", then any interface which begins with this name will match. If this option is omitted, any interface name will match.\n attribute :in_interface\n validates :in_interface, type: String\n\n # @return [Object, nil] Name of an interface via which a packet is going to be sent (for packets entering the FORWARD, OUTPUT and POSTROUTING chains). When the \"!\" argument is used before the interface name, the sense is inverted. If the interface name ends in a \"+\", then any interface which begins with this name will match. If this option is omitted, any interface name will match.\n attribute :out_interface\n\n # @return [Object, nil] This means that the rule only refers to second and further fragments of fragmented packets. Since there is no way to tell the source or destination ports of such a packet (or ICMP type), such a packet will not match any rules which specify them. When the \"!\" argument precedes fragment argument, the rule will only match head fragments, or unfragmented packets.\n attribute :fragment\n\n # @return [Object, nil] This enables the administrator to initialize the packet and byte counters of a rule (during INSERT, APPEND, REPLACE operations).\n attribute :set_counters\n\n # @return [Object, nil] Source port or port range specification. This can either be a service name or a port number. An inclusive range can also be specified, using the format first:last. If the first port is omitted, '0' is assumed; if the last is omitted, '65535' is assumed. If the first port is greater than the second one they will be swapped.\n attribute :source_port\n\n # @return [Integer, nil] Destination port or port range specification. This can either be a service name or a port number. An inclusive range can also be specified, using the format first:last. If the first port is omitted, '0' is assumed; if the last is omitted, '65535' is assumed. If the first port is greater than the second one they will be swapped. This is only valid if the rule also specifies one of the following protocols: tcp, udp, dccp or sctp.\n attribute :destination_port\n validates :destination_port, type: Integer\n\n # @return [Integer, nil] This specifies a destination port or range of ports to use: without this, the destination port is never altered. This is only valid if the rule also specifies one of the following protocols: tcp, udp, dccp or sctp.\n attribute :to_ports\n validates :to_ports, type: Integer\n\n # @return [Object, nil] This specifies a destination address to use with DNAT.,Without this, the destination address is never altered.\n attribute :to_destination\n\n # @return [Object, nil] This specifies a source address to use with SNAT.,Without this, the source address is never altered.\n attribute :to_source\n\n # @return [:ignore, :match, :negate, nil] This allows matching packets that have the SYN bit set and the ACK and RST bits unset.,When negated, this matches all packets with the RST or the ACK bits set.\n attribute :syn\n validates :syn, expression_inclusion: {:in=>[:ignore, :match, :negate], :message=>\"%{value} needs to be :ignore, :match, :negate\"}, allow_nil: true\n\n # @return [Integer, nil] This allows specifying a DSCP mark to be added to packets. It takes either an integer or hex value.,Mutually exclusive with C(set_dscp_mark_class).\n attribute :set_dscp_mark\n validates :set_dscp_mark, type: Integer\n\n # @return [String, nil] This allows specifying a predefined DiffServ class which will be translated to the corresponding DSCP mark.,Mutually exclusive with C(set_dscp_mark).\n attribute :set_dscp_mark_class\n validates :set_dscp_mark_class, type: String\n\n # @return [String, nil] This specifies a comment that will be added to the rule.\n attribute :comment\n validates :comment, type: String\n\n # @return [:DNAT, :ESTABLISHED, :INVALID, :NEW, :RELATED, :SNAT, :UNTRACKED, nil] C(ctstate) is a list of the connection states to match in the conntrack module. Possible states are: 'INVALID', 'NEW', 'ESTABLISHED', 'RELATED', 'UNTRACKED', 'SNAT', 'DNAT'\n attribute :ctstate\n validates :ctstate, expression_inclusion: {:in=>[:DNAT, :ESTABLISHED, :INVALID, :NEW, :RELATED, :SNAT, :UNTRACKED], :message=>\"%{value} needs to be :DNAT, :ESTABLISHED, :INVALID, :NEW, :RELATED, :SNAT, :UNTRACKED\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the maximum average number of matches to allow per second.,The number can specify units explicitly, using `/second', `/minute', `/hour' or `/day', or parts of them (so `5/second' is the same as `5/s').\n attribute :limit\n\n # @return [Object, nil] Specifies the maximum burst before the above limit kicks in.\n attribute :limit_burst\n\n # @return [Object, nil] Specifies the UID or username to use in match by owner rule. From Ansible 2.6 when the C(!) argument is prepended then the it inverts the rule to apply instead to all users except that one specified.\n attribute :uid_owner\n\n # @return [String, nil] Specifies the error packet type to return while rejecting. It implies \"jump: REJECT\"\n attribute :reject_with\n validates :reject_with, type: String\n\n # @return [Object, nil] This allows specification of the ICMP type, which can be a numeric ICMP type, type/code pair, or one of the ICMP type names shown by the command 'iptables -p icmp -h'\n attribute :icmp_type\n\n # @return [Object, nil] Flushes the specified table and chain of all rules.,If no chain is specified then the entire table is purged.,Ignores all other parameters.\n attribute :flush\n\n # @return [:ACCEPT, :DROP, :QUEUE, :RETURN, nil] Set the policy for the chain to the given target.,Only built-in chains can have policies.,This parameter requires the C(chain) parameter.,Ignores all other parameters.\n attribute :policy\n validates :policy, expression_inclusion: {:in=>[:ACCEPT, :DROP, :QUEUE, :RETURN], :message=>\"%{value} needs to be :ACCEPT, :DROP, :QUEUE, :RETURN\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6829836964607239, "alphanum_fraction": 0.6829836964607239, "avg_line_length": 33.31999969482422, "blob_id": "6083c0b29735f9a14449a6515fc74e496de1c298", "content_id": "8bf63157357d4338759fc42bf7f635ea6ad94dda", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 858, "license_type": "permissive", "max_line_length": 100, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_dns_config.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage VMware ESXi DNS Configuration\n class Vmware_dns_config < Base\n # @return [String] The hostname that an ESXi host should be changed to.\n attribute :change_hostname_to\n validates :change_hostname_to, presence: true, type: String\n\n # @return [String] The domain the ESXi host should be apart of.\n attribute :domainname\n validates :domainname, presence: true, type: String\n\n # @return [Array<String>, String] The DNS servers that the host should be configured to use.\n attribute :dns_servers\n validates :dns_servers, presence: true, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5899025797843933, "alphanum_fraction": 0.595069408416748, "avg_line_length": 30.952829360961914, "blob_id": "a219fbe7fe5049b5a5eb0be91eb2cfc0e6549693", "content_id": "777f878cab79390fff4a7362763ea47bd1d15873", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6774, "license_type": "permissive", "max_line_length": 102, "num_lines": 212, "path": "/lib/ansible/ruby/rake/execute_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'spec_helper'\nrequire 'ansible-ruby'\nrequire 'ansible/ruby/rake/execute'\nAnsible::Ruby::Modules.autoload :Copy, 'rake/copy'\n\ndescribe Ansible::Ruby::Rake::Execute do\n include_context :rake_testing\n\n context 'real Rake run' do\n describe 'description' do\n # :reek:ControlParameter - just a test\n # :reek:BooleanParameter - just a test\n def rake(task, expect_success = true)\n @output = `rake -f Rakefile_test.rb #{task} 2>&1`\n puts @output\n expect($?.success?).to be_truthy if expect_success\n @output\n end\n\n subject { rake '-T' }\n\n it do\n is_expected.to eq <<~OUTPUT\n rake compile # explicit compile task\n rake default # the ansible task default\n rake default_clean # Cleans YAML files for :default task\n rake default_compile # Compiles YAML files for :default task\n rake stuff # named ansible task\n rake stuff_clean # Cleans YAML files for :stuff task\n rake stuff_compile # Compiles YAML files for :stuff task\n OUTPUT\n end\n end\n end\n\n context 'programmatic Rake run' do\n include_context :rake_invoke\n\n let(:yaml_file) { 'playbook1_test.yml' }\n let(:ruby_file) { 'playbook1_test.rb' }\n\n context 'default' do\n let(:task) do\n Ansible::Ruby::Rake::Execute.new do |task|\n task.playbooks = ruby_file\n end\n end\n\n it { is_expected.to execute_command 'ansible-playbook playbook1_test.yml' }\n it { is_expected.to have_yaml yaml_file, that: include('- include: included_file.yml') }\n it { is_expected.to have_yaml yaml_file, that: include('host1:host2') }\n end\n\n context 'multiple playbook files' do\n let(:task) do\n Ansible::Ruby::Rake::Execute.new do |task|\n task.playbooks = %w[playbook1_test.rb playbook2_test.rb]\n end\n end\n\n it { is_expected.to execute_command 'ansible-playbook playbook1_test.yml playbook2_test.yml' }\n it { is_expected.to have_yaml 'playbook1_test.yml', that: include('host1:host2') }\n it { is_expected.to have_yaml 'playbook2_test.yml', that: include('something else') }\n end\n\n context 'options' do\n { flat: '--ansible-option', array: ['--ansible-option'] }.each do |type, value|\n context type do\n let(:task) do\n Ansible::Ruby::Rake::Execute.new do |task|\n task.playbooks = ruby_file\n task.options = value\n end\n end\n\n it { is_expected.to execute_command 'ansible-playbook --ansible-option playbook1_test.yml' }\n end\n end\n\n context 'env override' do\n around do |example|\n ENV['ANSIBLE_OPTS'] = '--check'\n example.run\n ENV.delete 'ANSIBLE_OPTS'\n end\n\n context 'combined' do\n let(:task) do\n Ansible::Ruby::Rake::Execute.new do |task|\n task.playbooks = ruby_file\n task.options = '-v'\n end\n end\n\n it { is_expected.to execute_command 'ansible-playbook -v --check playbook1_test.yml' }\n end\n\n context 'only env' do\n let(:task) do\n Ansible::Ruby::Rake::Execute.new do |task|\n task.playbooks = ruby_file\n end\n end\n\n it { is_expected.to execute_command 'ansible-playbook --check playbook1_test.yml' }\n end\n end\n end\n\n context 'dependent task' do\n let(:test_file) { 'foobar_test.yml' }\n let(:task) do\n ::Rake::Task.define_task :foobar do\n FileUtils.touch test_file\n end\n\n Ansible::Ruby::Rake::Execute.new default: :foobar do |task|\n task.playbooks = ruby_file\n end\n end\n\n it { is_expected.to execute_command 'ansible-playbook playbook1_test.yml' }\n it { is_expected.to have_yaml yaml_file, that: include('host1:host2') }\n\n it 'executes the dependency' do\n expect(File.exist?(test_file)).to be_truthy\n end\n end\n\n context 'role tasks' do\n let(:rake_dir) { 'spec/rake/nested_tasks' }\n let(:task_yml) { 'roles/role1/tasks/task1_test.yml' }\n\n let(:task) do\n Ansible::Ruby::Rake::Execute.new do |task|\n task.playbooks = ruby_file\n end\n end\n\n it { is_expected.to have_yaml yaml_file, that: include('host1:host2', 'roles') }\n it { is_expected.to have_yaml yaml_file, that: include('- include: other_playbook.yml') }\n it { is_expected.to have_yaml task_yml, that: include('- name: Copy something over') }\n it { is_expected.to have_yaml task_yml, that: include('- include: something.yml') }\n it { is_expected.to have_yaml task_yml, that: include('- name: Copy something else over') }\n end\n\n context 'handlers' do\n let(:rake_dir) { 'spec/rake/nested_tasks' }\n let(:handler_yml) { 'roles/role1/handlers/handler1_test.yml' }\n\n let(:task) do\n Ansible::Ruby::Rake::Execute.new do |task|\n task.playbooks = ruby_file\n end\n end\n\n it { is_expected.to have_yaml yaml_file, that: include('host1:host2', 'roles') }\n it { is_expected.to have_yaml handler_yml, that: include('- name: reboot') }\n it { is_expected.to have_yaml handler_yml, that: include('shutdown') }\n end\n\n context 'no playbook' do\n def execute_task\n # overriding parent so we can test error\n end\n\n it 'should raise an error' do\n expect {Ansible::Ruby::Rake::Execute.new}.to raise_error 'You did not supply any playbooks!'\n end\n end\n\n context 'clean' do\n def execute_task\n FileUtils.touch unrelated_file\n super\n Rake::Task[:default_clean].invoke\n end\n\n after do\n puts 'cleaning test file'\n FileUtils.rm_rf unrelated_file\n end\n\n let(:task) do\n Ansible::Ruby::Rake::Execute.new do |task|\n task.playbooks = ruby_file\n end\n end\n\n context 'no roles' do\n let(:unrelated_file) { 'something.yml' }\n\n it { is_expected.to execute_command 'ansible-playbook playbook1_test.yml' }\n it { is_expected.to_not have_yaml yaml_file }\n it { is_expected.to have_yaml unrelated_file }\n end\n\n context 'roles' do\n let(:unrelated_file) { 'roles/role1/tasks/keep_this.yml' }\n let(:rake_dir) { 'spec/rake/nested_tasks' }\n let(:task_yml) { 'roles/role1/tasks/task1_test.yml' }\n\n it { is_expected.to execute_command 'ansible-playbook playbook1_test.yml' }\n it { is_expected.to_not have_yaml yaml_file }\n it { is_expected.to_not have_yaml 'playbook1_test.yml' }\n it { is_expected.to have_yaml unrelated_file }\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5973312258720398, "alphanum_fraction": 0.5973312258720398, "avg_line_length": 30.073171615600586, "blob_id": "bfdcf4caca27021cad37838f807fc2eee158067b", "content_id": "84e61596b74cab3fc38308c2aba99a422b376634", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1274, "license_type": "permissive", "max_line_length": 67, "num_lines": 41, "path": "/lib/ansible/ruby/modules/helpers/file_attributes.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# see LICENSE.txt in project root\nmodule Ansible\n module Ruby\n module Modules\n module Helpers\n module FileAttributes\n def self.included(base)\n base.remove_existing_validations :owner\n # @return [String, nil] Which user should own the file\n base.attribute :owner\n base.validates :owner, type: String\n\n base.remove_existing_validations :group\n # @return [String, nil] Which group should own the file\n base.attribute :group\n base.validates :group, type: String\n\n base.remove_existing_validations :mode\n # @return [String, nil] File mode, e.g. \"u=rw,g=r\"\n base.attribute :mode\n base.validates :mode, type: String\n\n base.remove_existing_validations :setype\n base.attribute :setype\n base.validates :setype, type: String\n\n base.remove_existing_validations :selevel\n base.attribute :selevel\n base.validates :selevel, type: String\n\n base.remove_existing_validations :validate\n base.attribute :validate\n base.validates :validate, type: String\n end\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7099853157997131, "alphanum_fraction": 0.7129221558570862, "avg_line_length": 47.64285659790039, "blob_id": "876a5ad2b9826c190fadc7a367f0b131ffe5d16d", "content_id": "fd8fd5ff8291bc09590eaaabbd1004e85f52944a", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1362, "license_type": "permissive", "max_line_length": 220, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_vmotion.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Using VMware vCenter, move a virtual machine using vMotion to a different host, and/or its vmdks to another datastore using storage vMotion.\n class Vmware_vmotion < Base\n # @return [String, nil] Name of the VM to perform a vMotion on.,This is required parameter, if C(vm_uuid) is not set.,Version 2.6 onwards, this parameter is not a required parameter, unlike the previous versions.\n attribute :vm_name\n validates :vm_name, type: String\n\n # @return [Object, nil] UUID of the virtual machine to perform a vMotion operation on.,This is a required parameter, if C(vm_name) is not set.\n attribute :vm_uuid\n\n # @return [String, nil] Name of the destination host the virtual machine should be running on.,Version 2.6 onwards, this parameter is not a required parameter, unlike the previous versions.\n attribute :destination_host\n validates :destination_host, type: String\n\n # @return [String, nil] Name of the destination datastore the virtual machine's vmdk should be moved on.\n attribute :destination_datastore\n validates :destination_datastore, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6913470029830933, "alphanum_fraction": 0.6913470029830933, "avg_line_length": 43.84000015258789, "blob_id": "fb4aeddfd43e6389ca66d512596d3abb5643786b", "content_id": "0b1e1f91c98b6281523ed65c0d429b7bfd361d70", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1121, "license_type": "permissive", "max_line_length": 151, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_gir_profile_management.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage a maintenance-mode or normal-mode profile with configuration commands that can be applied during graceful removal or graceful insertion.\n class Nxos_gir_profile_management < Base\n # @return [Array<String>, String, nil] List of commands to be included into the profile.\n attribute :commands\n validates :commands, type: TypeGeneric.new(String)\n\n # @return [:maintenance, :normal] Configure the profile as Maintenance or Normal mode.\n attribute :mode\n validates :mode, presence: true, expression_inclusion: {:in=>[:maintenance, :normal], :message=>\"%{value} needs to be :maintenance, :normal\"}\n\n # @return [:present, :absent, nil] Specify desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6935483813285828, "alphanum_fraction": 0.6982921957969666, "avg_line_length": 49.19047546386719, "blob_id": "782c0abeed2b1c0105a2e3fbe00fbb655c46828f", "content_id": "68ff8df0871e57bff84fa9567be61bc70fc9f9c9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1054, "license_type": "permissive", "max_line_length": 299, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/windows/win_disk_image.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages mount behavior for a specified ISO, VHD, or VHDX image on a Windows host. When C(state) is C(present), the image will be mounted under a system-assigned drive letter, which will be returned in the C(mount_path) value of the module result. Requires Windows 8+ or Windows Server 2012+.\n class Win_disk_image < Base\n # @return [String] Path to an ISO, VHD, or VHDX image on the target Windows host (the file cannot reside on a network share)\n attribute :image_path\n validates :image_path, presence: true, type: String\n\n # @return [:absent, :present, nil] Whether the image should be present as a drive-letter mount or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.665714681148529, "alphanum_fraction": 0.6692197918891907, "avg_line_length": 55.639705657958984, "blob_id": "07bab3cf50334fbecc88448698f2c07de5d604dd", "content_id": "a74391f5f8ca80cbed20dc150feb622390fc4776", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 7703, "license_type": "permissive", "max_line_length": 422, "num_lines": 136, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_template.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Register templates from an URL.\n # Create templates from a ROOT volume of a stopped VM or its snapshot.\n # Update (since version 2.7), extract and delete templates.\n class Cs_template < Base\n # @return [String] Name of the template.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] URL of where the template is hosted on I(state=present).,URL to which the template would be extracted on I(state=extracted).,Mutually exclusive with C(vm).\n attribute :url\n validates :url, type: String\n\n # @return [String, nil] VM name the template will be created from its volume or alternatively from a snapshot.,VM must be in stopped state if created from its volume.,Mutually exclusive with C(url).\n attribute :vm\n validates :vm, type: String\n\n # @return [String, nil] Name of the snapshot, created from the VM ROOT volume, the template will be created from.,C(vm) is required together with this argument.\n attribute :snapshot\n validates :snapshot, type: String\n\n # @return [String, nil] OS type that best represents the OS of this template.\n attribute :os_type\n validates :os_type, type: String\n\n # @return [Object, nil] The MD5 checksum value of this template.,If set, we search by checksum instead of name.\n attribute :checksum\n\n # @return [Symbol, nil] Note: this flag was not implemented and therefore marked as deprecated.,Deprecated, will be removed in version 2.11.\n attribute :is_ready\n validates :is_ready, type: Symbol\n\n # @return [Symbol, nil] Register the template to be publicly available to all users.,Only used if C(state) is present.\n attribute :is_public\n validates :is_public, type: Symbol\n\n # @return [Symbol, nil] Register the template to be featured.,Only used if C(state) is present.\n attribute :is_featured\n validates :is_featured, type: Symbol\n\n # @return [Symbol, nil] Register the template having XS/VMWare tools installed in order to support dynamic scaling of VM CPU/memory.,Only used if C(state) is present.\n attribute :is_dynamically_scalable\n validates :is_dynamically_scalable, type: Symbol\n\n # @return [Symbol, nil] Whether the template should be synced or removed across zones.,Only used if C(state) is present or absent.\n attribute :cross_zones\n validates :cross_zones, type: Symbol\n\n # @return [:http_download, :ftp_upload, nil] Mode for the template extraction.,Only used if I(state=extracted).\n attribute :mode\n validates :mode, expression_inclusion: {:in=>[:http_download, :ftp_upload], :message=>\"%{value} needs to be :http_download, :ftp_upload\"}, allow_nil: true\n\n # @return [Object, nil] Domain the template, snapshot or VM is related to.\n attribute :domain\n\n # @return [Object, nil] Account the template, snapshot or VM is related to.\n attribute :account\n\n # @return [Object, nil] Name of the project the template to be registered in.\n attribute :project\n\n # @return [String, nil] Name of the zone you wish the template to be registered or deleted from.,If not specified, first found zone will be used.\n attribute :zone\n validates :zone, type: String\n\n # @return [:all, :featured, :self, :selfexecutable, :sharedexecutable, :executable, :community, nil] Name of the filter used to search for the template.,The filter C(all) was added in 2.7.\n attribute :template_filter\n validates :template_filter, expression_inclusion: {:in=>[:all, :featured, :self, :selfexecutable, :sharedexecutable, :executable, :community], :message=>\"%{value} needs to be :all, :featured, :self, :selfexecutable, :sharedexecutable, :executable, :community\"}, allow_nil: true\n\n # @return [:display_text, :checksum, :cross_zones, nil] Options to find a template uniquely.,More than one allowed.\n attribute :template_find_options\n validates :template_find_options, expression_inclusion: {:in=>[:display_text, :checksum, :cross_zones], :message=>\"%{value} needs to be :display_text, :checksum, :cross_zones\"}, allow_nil: true\n\n # @return [:KVM, :kvm, :VMware, :vmware, :BareMetal, :baremetal, :XenServer, :xenserver, :LXC, :lxc, :HyperV, :hyperv, :UCS, :ucs, :OVM, :ovm, :Simulator, :simulator, nil] Name the hypervisor to be used for creating the new template.,Relevant when using I(state=present).\n attribute :hypervisor\n validates :hypervisor, expression_inclusion: {:in=>[:KVM, :kvm, :VMware, :vmware, :BareMetal, :baremetal, :XenServer, :xenserver, :LXC, :lxc, :HyperV, :hyperv, :UCS, :ucs, :OVM, :ovm, :Simulator, :simulator], :message=>\"%{value} needs to be :KVM, :kvm, :VMware, :vmware, :BareMetal, :baremetal, :XenServer, :xenserver, :LXC, :lxc, :HyperV, :hyperv, :UCS, :ucs, :OVM, :ovm, :Simulator, :simulator\"}, allow_nil: true\n\n # @return [Symbol, nil] Whether the template requires HVM or not.,Only considered while creating the template.\n attribute :requires_hvm\n validates :requires_hvm, type: Symbol\n\n # @return [Symbol, nil] Enable template password reset support.\n attribute :password_enabled\n validates :password_enabled, type: Symbol\n\n # @return [Object, nil] The tag for this template.\n attribute :template_tag\n\n # @return [Symbol, nil] True if the template supports the sshkey upload feature.,Only considered if C(url) is used (API limitation).\n attribute :sshkey_enabled\n validates :sshkey_enabled, type: Symbol\n\n # @return [Symbol, nil] Sets the template type to routing, i.e. if template is used to deploy routers.,Only considered if C(url) is used.\n attribute :is_routing\n validates :is_routing, type: Symbol\n\n # @return [:QCOW2, :RAW, :VHD, :OVA, nil] The format for the template.,Only considered if I(state=present).\n attribute :format\n validates :format, expression_inclusion: {:in=>[:QCOW2, :RAW, :VHD, :OVA], :message=>\"%{value} needs to be :QCOW2, :RAW, :VHD, :OVA\"}, allow_nil: true\n\n # @return [Symbol, nil] Allows the template or its derivatives to be extractable.\n attribute :is_extractable\n validates :is_extractable, type: Symbol\n\n # @return [Object, nil] Template details in key/value pairs.\n attribute :details\n\n # @return [32, 64, nil] 32 or 64 bits support.\n attribute :bits\n validates :bits, expression_inclusion: {:in=>[32, 64], :message=>\"%{value} needs to be 32, 64\"}, allow_nil: true\n\n # @return [String, nil] Display text of the template.\n attribute :display_text\n validates :display_text, type: String\n\n # @return [:present, :absent, :extracted, nil] State of the template.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :extracted], :message=>\"%{value} needs to be :present, :absent, :extracted\"}, allow_nil: true\n\n # @return [Boolean, nil] Poll async jobs until job has finished.\n attribute :poll_async\n validates :poll_async, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] List of tags. Tags are a list of dictionaries having keys C(key) and C(value).,To delete all tags, set a empty list e.g. C(tags: []).\n attribute :tags\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6474976539611816, "alphanum_fraction": 0.6490519046783447, "avg_line_length": 41.893333435058594, "blob_id": "8cc816ea96b342d0d1df9e3023e75ed816f08254", "content_id": "0fa4fc9e4075737eeae8ae49cf321fd556c0aa67", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3217, "license_type": "permissive", "max_line_length": 182, "num_lines": 75, "path": "/lib/ansible/ruby/modules/generated/storage/glusterfs/gluster_volume.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, remove, start, stop and tune GlusterFS volumes\n class Gluster_volume < Base\n # @return [String] The volume name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, :started, :stopped] Use present/absent ensure if a volume exists or not. Use started/stopped to control its availability.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:absent, :present, :started, :stopped], :message=>\"%{value} needs to be :absent, :present, :started, :stopped\"}\n\n # @return [Array<String>, String, nil] List of hosts to use for probing and brick setup.\n attribute :cluster\n validates :cluster, type: TypeGeneric.new(String)\n\n # @return [Object, nil] Override local hostname (for peer probing purposes).\n attribute :host\n\n # @return [Object, nil] Replica count for volume.\n attribute :replicas\n\n # @return [Object, nil] Arbiter count for volume.\n attribute :arbiters\n\n # @return [Object, nil] Stripe count for volume.\n attribute :stripes\n\n # @return [Object, nil] Disperse count for volume.\n attribute :disperses\n\n # @return [Object, nil] Redundancy count for volume.\n attribute :redundancies\n\n # @return [:tcp, :rdma, :\"tcp,rdma\", nil] Transport type for volume.\n attribute :transport\n validates :transport, expression_inclusion: {:in=>[:tcp, :rdma, :\"tcp,rdma\"], :message=>\"%{value} needs to be :tcp, :rdma, :\\\"tcp,rdma\\\"\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] Brick paths on servers. Multiple brick paths can be separated by commas.\n attribute :bricks\n validates :bricks, type: TypeGeneric.new(String)\n\n # @return [:yes, :no, nil] Controls whether the volume is started after creation or not.\n attribute :start_on_create\n validates :start_on_create, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Controls whether the cluster is rebalanced after changes.\n attribute :rebalance\n validates :rebalance, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Directory for limit-usage.\n attribute :directory\n validates :directory, type: String\n\n # @return [Hash, nil] A dictionary/hash with options/settings for the volume.\n attribute :options\n validates :options, type: Hash\n\n # @return [String, nil] Quota value for limit-usage (be sure to use 10.0MB instead of 10MB, see quota list).\n attribute :quota\n validates :quota, type: String\n\n # @return [Symbol, nil] If brick is being created in the root partition, module will fail. Set force to true to override this behaviour.\n attribute :force\n validates :force, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7010228037834167, "alphanum_fraction": 0.7016128897666931, "avg_line_length": 88.19298553466797, "blob_id": "4fca29969c8d8216fef2ebfe628d2e8aba4c0e23", "content_id": "0a56f19fd2ae24631c93044112e1f53b13123673", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5084, "license_type": "permissive", "max_line_length": 572, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/files/lineinfile.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module ensures a particular line is in a file, or replace an existing line using a back-referenced regular expression.\n # This is primarily useful when you want to change a single line in a file only. See the M(replace) module if you want to change multiple, similar lines or check M(blockinfile) if you want to insert/update/remove a block of lines in a file. For other cases, see the M(copy) or M(template) modules.\n class Lineinfile < Base\n # @return [String] The file to modify.,Before 2.3 this option was only usable as I(dest), I(destfile) and I(name).\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [String, nil] The regular expression to look for in every line of the file. For C(state=present), the pattern to replace if found. Only the last line found will be replaced. For C(state=absent), the pattern of the line(s) to remove. Uses Python regular expressions. See U(http://docs.python.org/2/library/re.html).\n attribute :regexp\n validates :regexp, type: String\n\n # @return [:absent, :present, nil] Whether the line should be there or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] Required for C(state=present). The line to insert/replace into the file. If C(backrefs) is set, may contain backreferences that will get expanded with the C(regexp) capture groups if the regexp matches.\n attribute :line\n validates :line, type: String\n\n # @return [:yes, :no, nil] Used with C(state=present). If set, C(line) can contain backreferences (both positional and named) that will get populated if the C(regexp) matches. This flag changes the operation of the module slightly; C(insertbefore) and C(insertafter) will be ignored, and if the C(regexp) doesn't match anywhere in the file, the file will be left unchanged. If the C(regexp) does match, the last matching line will be replaced by the expanded line parameter.\n attribute :backrefs\n validates :backrefs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:EOF, :\"*regex*\", nil] Used with C(state=present). If specified, the line will be inserted after the last match of specified regular expression. If the first match is required, use(firstmatch=yes). A special value is available; C(EOF) for inserting the line at the end of the file. If specified regular expression has no matches, EOF will be used instead. If regular expressions are passed to both C(regexp) and C(insertafter), C(insertafter) is only honored if no match for C(regexp) is found. May not be used with C(backrefs).\n attribute :insertafter\n validates :insertafter, expression_inclusion: {:in=>[:EOF, :\"*regex*\"], :message=>\"%{value} needs to be :EOF, :\\\"*regex*\\\"\"}, allow_nil: true\n\n # @return [:BOF, :\"*regex*\", nil] Used with C(state=present). If specified, the line will be inserted before the last match of specified regular expression. If the first match is required, use(firstmatch=yes). A value is available; C(BOF) for inserting the line at the beginning of the file. If specified regular expression has no matches, the line will be inserted at the end of the file. If regular expressions are passed to both C(regexp) and C(insertbefore), C(insertbefore) is only honored if no match for C(regexp) is found. May not be used with C(backrefs).\n attribute :insertbefore\n validates :insertbefore, expression_inclusion: {:in=>[:BOF, :\"*regex*\"], :message=>\"%{value} needs to be :BOF, :\\\"*regex*\\\"\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Used with C(state=present). If specified, the file will be created if it does not already exist. By default it will fail if the file is missing.\n attribute :create\n validates :create, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.\n attribute :backup\n validates :backup, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Used with C(insertafter) or C(insertbefore). If set, C(insertafter) and C(inserbefore) find a first line has regular expression matches.\n attribute :firstmatch\n validates :firstmatch, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] All arguments accepted by the M(file) module also work here.\n attribute :others\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7077151536941528, "alphanum_fraction": 0.7077151536941528, "avg_line_length": 52.91999816894531, "blob_id": "3c4a76cb16705fef2b488f0b15d31cc3a9a5194b", "content_id": "13ad71b6f8b8b1fb70ed800271cde2dfc4f909b8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1348, "license_type": "permissive", "max_line_length": 314, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/windows/win_chocolatey_config.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Used to manage Chocolatey config settings as well as unset the values.\n class Win_chocolatey_config < Base\n # @return [String] The name of the config setting to manage.,See U(https://chocolatey.org/docs/chocolatey-configuration) for a list of valid configuration settings that can be changed.,Any config values that contain encrypted values like a password are not idempotent as the plaintext value cannot be read.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, nil] When C(absent), it will ensure the setting is unset or blank.,When C(present), it will ensure the setting is set to the value of I(value).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] Used when C(state=present) that contains the value to set for the config setting.,Cannot be null or an empty string, use C(state=absent) to unset a config value instead.\n attribute :value\n validates :value, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6351259350776672, "alphanum_fraction": 0.6507828235626221, "avg_line_length": 40.97142791748047, "blob_id": "694973838a8183929d863c0a1125985614130128", "content_id": "699ea4b2a172b7b46d3dd3d7ab2fda9afceb67d6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1469, "license_type": "permissive", "max_line_length": 149, "num_lines": 35, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_ip_interface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages Layer 3 attributes for IPv4 and IPv6 interfaces on HUAWEI CloudEngine switches.\n class Ce_ip_interface < Base\n # @return [Object] Full name of interface, i.e. 40GE1/0/22, vlanif10.\n attribute :interface\n validates :interface, presence: true\n\n # @return [Object, nil] IPv4 or IPv6 Address.\n attribute :addr\n\n # @return [Object, nil] Subnet mask for IPv4 or IPv6 Address in decimal format.\n attribute :mask\n\n # @return [:v4, :v6, nil] IP address version.\n attribute :version\n validates :version, expression_inclusion: {:in=>[:v4, :v6], :message=>\"%{value} needs to be :v4, :v6\"}, allow_nil: true\n\n # @return [:main, :sub, nil] Specifies an address type. The value is an enumerated type. main, primary IP address. sub, secondary IP address.\n attribute :ipv4_type\n validates :ipv4_type, expression_inclusion: {:in=>[:main, :sub], :message=>\"%{value} needs to be :main, :sub\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Specify desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6638370156288147, "alphanum_fraction": 0.6638370156288147, "avg_line_length": 27.047618865966797, "blob_id": "eef1a2c96a13976cfbb8246efb9a30b474aa9fe8", "content_id": "a255b8d7c9db796cd6ab108f9c1dec628503e930", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 589, "license_type": "permissive", "max_line_length": 67, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_autoscale_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Get facts of Auto Scale Setting.\n class Azure_rm_autoscale_facts < Base\n # @return [String] The name of the resource group.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String, nil] The name of the Auto Scale Setting.\n attribute :name\n validates :name, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6558854579925537, "alphanum_fraction": 0.6829268336296082, "avg_line_length": 61.86666488647461, "blob_id": "fdee1a1473e6bf3c757fed9a85390ed332629e08", "content_id": "7295764910226268cb8660e0d5e51c9bc2265a29", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1886, "license_type": "permissive", "max_line_length": 493, "num_lines": 30, "path": "/lib/ansible/ruby/modules/generated/windows/win_stat.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Returns information about a Windows file.\n # For non-Windows targets, use the M(stat) module instead.\n class Win_stat < Base\n # @return [String] The full path of the file/object to get the facts of; both forward and back slashes are accepted.\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [:yes, :no, nil] Whether to return the checksum sum of the file. Between Ansible 1.9 and 2.2 this is no longer an MD5, but a SHA1 instead. As of Ansible 2.3 this is back to an MD5. Will return None if host is unable to use specified algorithm.,The default of this option changed from C(yes) to C(no) in Ansible 2.5 and will be removed altogether in Ansible 2.9.,Use C(get_checksum=true) with C(checksum_algorithm=md5) to return an md5 hash under the C(checksum) return value.\n attribute :get_md5\n validates :get_md5, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Whether to return a checksum of the file (default sha1)\n attribute :get_checksum\n validates :get_checksum, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:md5, :sha1, :sha256, :sha384, :sha512, nil] Algorithm to determine checksum of file. Will throw an error if the host is unable to use specified algorithm.\n attribute :checksum_algorithm\n validates :checksum_algorithm, expression_inclusion: {:in=>[:md5, :sha1, :sha256, :sha384, :sha512], :message=>\"%{value} needs to be :md5, :sha1, :sha256, :sha384, :sha512\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.681835412979126, "alphanum_fraction": 0.6831626892089844, "avg_line_length": 59.620689392089844, "blob_id": "931cf174773c7e4e58548b1d0588824a71c57c69", "content_id": "b0b656afb8a5f0e7f8a6c9a0e1c8dbeda6ff8396", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5274, "license_type": "permissive", "max_line_length": 420, "num_lines": 87, "path": "/lib/ansible/ruby/modules/generated/packaging/os/pulp_repo.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove Pulp repos from a remote host.\n class Pulp_repo < Base\n # @return [:yes, :no, nil] Whether or not to add the export distributor to new C(rpm) repositories.\n attribute :add_export_distributor\n validates :add_export_distributor, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Upstream feed URL to receive updates from.\n attribute :feed\n validates :feed, type: String\n\n # @return [:yes, :no, nil] httplib2, the library used by the M(uri) module only sends authentication information when a webservice responds to an initial request with a 401 status. Since some basic auth services do not properly send a 401, logins will fail. This option forces the sending of the Basic authentication header upon initial request.\n attribute :force_basic_auth\n validates :force_basic_auth, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] CA certificate string used to validate the feed source SSL certificate. This can be the file content or the path to the file.\n attribute :importer_ssl_ca_cert\n\n # @return [Object, nil] Certificate used as the client certificate when synchronizing the repository. This is used to communicate authentication information to the feed source. The value to this option must be the full path to the certificate. The specified file may be the certificate itself or a single file containing both the certificate and private key. This can be the file content or the path to the file.\n attribute :importer_ssl_client_cert\n\n # @return [Object, nil] Private key to the certificate specified in I(importer_ssl_client_cert), assuming it is not included in the certificate file itself. This can be the file content or the path to the file.\n attribute :importer_ssl_client_key\n\n # @return [String] Name of the repo to add or remove. This correlates to repo-id in Pulp.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Proxy url setting for the pulp repository importer. This is in the format scheme://host.\n attribute :proxy_host\n\n # @return [Object, nil] Proxy port setting for the pulp repository importer.\n attribute :proxy_port\n\n # @return [Object, nil] Distributor to use when state is C(publish). The default is to publish all distributors.\n attribute :publish_distributor\n\n # @return [String, nil] URL of the pulp server to connect to.\n attribute :pulp_host\n validates :pulp_host, type: String\n\n # @return [String] Relative URL for the local repository.\n attribute :relative_url\n validates :relative_url, presence: true, type: String\n\n # @return [String, nil] Repo plugin type to use (i.e. C(rpm), C(docker)).\n attribute :repo_type\n validates :repo_type, type: String\n\n # @return [:yes, :no, nil] Make the repo available over HTTP.\n attribute :serve_http\n validates :serve_http, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Make the repo available over HTTPS.\n attribute :serve_https\n validates :serve_https, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, :sync, :publish, nil] The repo state. A state of C(sync) will queue a sync of the repo. This is asynchronous but not delayed like a scheduled sync. A state of C(publish) will use the repository's distributor to publish the content.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :sync, :publish], :message=>\"%{value} needs to be :present, :absent, :sync, :publish\"}, allow_nil: true\n\n # @return [String, nil] The password for use in HTTP basic authentication to the pulp API. If the I(url_username) parameter is not specified, the I(url_password) parameter will not be used.\n attribute :url_password\n validates :url_password, type: String\n\n # @return [String, nil] The username for use in HTTP basic authentication to the pulp API.\n attribute :url_username\n validates :url_username, type: String\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Wait for asynchronous tasks to complete before returning.\n attribute :wait_for_completion\n validates :wait_for_completion, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6776632070541382, "alphanum_fraction": 0.6793814301490784, "avg_line_length": 69.9756088256836, "blob_id": "58ce85922ff34663c01ef28f8e39260c5dc4f4b8", "content_id": "055cfccb0628a67b79ad5381653c72cb30db93f1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2910, "license_type": "permissive", "max_line_length": 640, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/network/a10/a10_service_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage SLB (Server Load Balancing) service-group objects on A10 Networks devices via aXAPIv2.\n class A10_service_group < Base\n # @return [:present, :absent, nil] If the specified service group should exists.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] set active-partition\n attribute :partition\n validates :partition, type: String\n\n # @return [String] The SLB (Server Load Balancing) service-group name\n attribute :service_group\n validates :service_group, presence: true, type: String\n\n # @return [:tcp, :udp, nil] The SLB service-group protocol of TCP or UDP.\n attribute :service_group_protocol\n validates :service_group_protocol, expression_inclusion: {:in=>[:tcp, :udp], :message=>\"%{value} needs to be :tcp, :udp\"}, allow_nil: true\n\n # @return [:\"round-robin\", :\"weighted-rr\", :\"least-connection\", :\"weighted-least-connection\", :\"service-least-connection\", :\"service-weighted-least-connection\", :\"fastest-response\", :\"least-request\", :\"round-robin-strict\", :\"src-ip-only-hash\", :\"src-ip-hash\", nil] The SLB service-group load balancing method, such as round-robin or weighted-rr.\n attribute :service_group_method\n validates :service_group_method, expression_inclusion: {:in=>[:\"round-robin\", :\"weighted-rr\", :\"least-connection\", :\"weighted-least-connection\", :\"service-least-connection\", :\"service-weighted-least-connection\", :\"fastest-response\", :\"least-request\", :\"round-robin-strict\", :\"src-ip-only-hash\", :\"src-ip-hash\"], :message=>\"%{value} needs to be :\\\"round-robin\\\", :\\\"weighted-rr\\\", :\\\"least-connection\\\", :\\\"weighted-least-connection\\\", :\\\"service-least-connection\\\", :\\\"service-weighted-least-connection\\\", :\\\"fastest-response\\\", :\\\"least-request\\\", :\\\"round-robin-strict\\\", :\\\"src-ip-only-hash\\\", :\\\"src-ip-hash\\\"\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash, nil] A list of servers to add to the service group. Each list item should be a dictionary which specifies the C(server:) and C(port:), but can also optionally specify the C(status:). See the examples below for details.\n attribute :servers\n validates :servers, type: TypeGeneric.new(Hash)\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated. This should only be used on personally controlled devices using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6646153926849365, "alphanum_fraction": 0.6646153926849365, "avg_line_length": 41.12963104248047, "blob_id": "f5b97791e653542cd9a131f6ef83ed0247feb456", "content_id": "bdce95dfc1024291f3fd35e936875f1d206eb927", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2275, "license_type": "permissive", "max_line_length": 143, "num_lines": 54, "path": "/lib/ansible/ruby/modules/generated/packaging/os/rhn_register.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage registration to the Red Hat Network.\n class Rhn_register < Base\n # @return [:present, :absent, nil] whether to register (C(present)), or unregister (C(absent)) a system\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Red Hat Network username\n attribute :username\n validates :username, type: String\n\n # @return [String, nil] Red Hat Network password\n attribute :password\n validates :password, type: String\n\n # @return [String, nil] Specify an alternative Red Hat Network server URL\n attribute :server_url\n validates :server_url, type: String\n\n # @return [String, nil] supply an activation key for use with registration\n attribute :activationkey\n validates :activationkey, type: String\n\n # @return [String, nil] supply an profilename for use with registration\n attribute :profilename\n validates :profilename, type: String\n\n # @return [Object, nil] supply a custom ssl CA certificate file for use with registration\n attribute :sslcacert\n\n # @return [Object, nil] supply an organizational id for use with registration\n attribute :systemorgid\n\n # @return [Object, nil] Optionally specify a list of comma-separated channels to subscribe to upon successful registration.\n attribute :channels\n\n # @return [:yes, :no, nil] If C(no), extended update support will be requested.\n attribute :enable_eus\n validates :enable_eus, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(yes), the registered node will not upload its installed packages information to Satellite server\n attribute :nopackages\n validates :nopackages, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5234230756759644, "alphanum_fraction": 0.5276650786399841, "avg_line_length": 25.621931076049805, "blob_id": "50b696d01de1b8488edc58583ed41391844730cd", "content_id": "9e8ffdb3db80854892d5f99964c458e696b6fc2b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 16266, "license_type": "permissive", "max_line_length": 178, "num_lines": 611, "path": "/lib/ansible/ruby/dsl_builders/task_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'spec_helper'\nrequire 'ansible-ruby'\n\ndescribe Ansible::Ruby::DslBuilders::Task do\n let(:context) { Ansible::Ruby::Models::Task }\n let(:builder) { Ansible::Ruby::DslBuilders::Task.new 'Copy something', context }\n\n def evaluate\n builder.instance_eval ruby\n @variable = builder._register\n builder._result\n end\n\n subject(:task) { evaluate }\n\n before do\n Ansible::Ruby::DslBuilders::Task.counter_variable = 0\n klass = Class.new(Ansible::Ruby::Modules::Base) do\n attribute :src\n validates :src, presence: true\n attribute :dest\n validates :dest, presence: true\n end\n stub_const 'Ansible::Ruby::Modules::Copy', klass\n debug_module = Class.new(Ansible::Ruby::Modules::Base) do\n attribute :msg\n end\n stub_const 'Ansible::Ruby::Modules::Debug', debug_module\n end\n\n context 'single task' do\n let(:ruby) do\n <<-RUBY\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Task }\n\n describe 'task object' do\n it { is_expected.to be_a Ansible::Ruby::Models::Task }\n it { is_expected.to have_attributes name: 'Copy something', module: be_a(Ansible::Ruby::Modules::Copy) }\n end\n\n describe 'hash keys' do\n subject { task.to_h.stringify_keys.keys }\n\n it { is_expected.to eq %w[name copy] }\n end\n end\n\n context 'fail module' do\n let(:ruby) do\n <<-RUBY\n ansible_fail do\n msg 'foo'\n end\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Task }\n\n describe 'task object' do\n it { is_expected.to be_a Ansible::Ruby::Models::Task }\n it { is_expected.to have_attributes name: 'Copy something', module: be_a(Ansible::Ruby::Modules::Fail) }\n end\n end\n\n context 'block/rescue/always inside task' do\n let(:ruby) do\n <<-RUBY\n ansible_block do\n task 'do copy' do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n end\n end\n ansible_rescue do\n task 'do debug' do\n debug {msg 'foo'}\n end\n task 'do fail' do\n ansible_fail {msg 'bar'}\n end\n end\n ansible_always do\n task 'do always' do\n debug {msg 'stuff'}\n end\n end\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Task }\n describe 'task object' do\n it { is_expected.to be_a Ansible::Ruby::Models::Task }\n it {\n is_expected.to have_attributes name: 'Copy something',\n block: be_a(Ansible::Ruby::Models::Block),\n rescue: be_a(Ansible::Ruby::Models::Block)\n }\n end\n\n describe 'block' do\n subject(:block) { task.block }\n\n it 'has 1 copy task' do\n tasks = block.tasks\n expect(tasks.size).to eq 1\n task = tasks[0]\n expect(task.module).to be_a Ansible::Ruby::Modules::Copy\n end\n end\n\n describe 'rescue' do\n subject(:ansible_rescue) { task.rescue }\n\n it 'has 1 debug task' do\n tasks = ansible_rescue.tasks\n expect(tasks.size).to eq 2\n task = tasks[0]\n expect(task.module).to be_a Ansible::Ruby::Modules::Debug\n end\n\n it 'has 1 fail task' do\n tasks = ansible_rescue.tasks\n expect(tasks.size).to eq 2\n task = tasks[1]\n expect(task.module).to be_a Ansible::Ruby::Modules::Fail\n end\n end\n\n describe 'always' do\n subject(:ansible_always) { task.always }\n\n it 'has 1 debug task' do\n tasks = ansible_always.tasks\n expect(tasks.size).to eq 1\n task = tasks[0]\n expect(task.module).to be_a Ansible::Ruby::Modules::Debug\n end\n end\n end\n\n context 'vars' do\n let(:ruby) do\n <<-RUBY\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n vars foo: 123\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Task }\n\n describe 'hash keys' do\n subject { task.to_h.stringify_keys.keys }\n\n it { is_expected.to eq %w[name copy vars] }\n end\n end\n\n context 'delegate_to' do\n let(:ruby) do\n <<-RUBY\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n delegate_to 'somehost'\n RUBY\n end\n describe 'task object' do\n it { is_expected.to be_a Ansible::Ruby::Models::Task }\n it do\n is_expected.to have_attributes name: 'Copy something',\n module: be_a(Ansible::Ruby::Modules::Copy),\n delegate_to: 'somehost'\n end\n end\n end\n\n context 'delegate_to with facts' do\n let(:ruby) do\n <<-RUBY\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n delegate_to 'somehost'\n delegate_facts true\n RUBY\n end\n describe 'task object' do\n it { is_expected.to be_a Ansible::Ruby::Models::Task }\n it do\n is_expected.to have_attributes name: 'Copy something',\n module: be_a(Ansible::Ruby::Modules::Copy),\n delegate_to: 'somehost',\n delegate_facts: true\n end\n end\n end\n\n context 'local_action' do\n let(:ruby) do\n <<-RUBY\n local_action do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n end\n RUBY\n end\n\n describe 'task object' do\n it { is_expected.to be_a Ansible::Ruby::Models::Task }\n it do\n is_expected.to have_attributes name: 'Copy something',\n module: be_a(Ansible::Ruby::Modules::Copy),\n local_action: true\n end\n end\n end\n\n context 'remote user' do\n let(:ruby) do\n <<-RUBY\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n delegate_to 'somehost'\n remote_user 'foobar'\n RUBY\n end\n describe 'task object' do\n it { is_expected.to be_a Ansible::Ruby::Models::Task }\n it do\n is_expected.to have_attributes name: 'Copy something',\n module: be_a(Ansible::Ruby::Modules::Copy),\n delegate_to: 'somehost',\n remote_user: 'foobar'\n end\n end\n end\n\n context 'handler' do\n context 'no include' do\n let(:context) { Ansible::Ruby::Models::Handler }\n let(:ruby) do\n <<-RUBY\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n listen 'foobar'\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Handler }\n it {\n is_expected.to have_attributes name: 'Copy something',\n module: be_a(Ansible::Ruby::Modules::Copy),\n listen: 'foobar'\n }\n end\n\n context 'include' do\n let(:context) { Ansible::Ruby::Models::Handler }\n\n let(:ruby) do\n <<-RUBY\n ansible_include 'something'\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Handler }\n it do\n is_expected.to have_attributes name: 'Copy something',\n inclusion: be_a(Ansible::Ruby::Models::Inclusion)\n end\n end\n end\n\n context 'includes' do\n context 'inclusion only' do\n let(:ruby) do\n <<-RUBY\n ansible_include 'foobar.yml'\n RUBY\n end\n\n it do\n is_expected.to have_attributes name: 'Copy something',\n inclusion: be_a(Ansible::Ruby::Models::Inclusion)\n end\n\n it 'does not include th module key' do\n expect(task.to_h.keys).to_not include :module\n end\n end\n\n context 'include and module' do\n let(:ruby) do\n <<-RUBY\n ansible_include 'something'\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n RUBY\n end\n\n it 'should raise an error' do\n expect {evaluate}.to raise_error %r{You must either use an include or a module/block but not both.*}\n end\n end\n end\n\n context 'jinja' do\n let(:ruby) do\n <<-RUBY\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n with_dict jinja('servers')\n RUBY\n end\n\n it do\n is_expected.to have_attributes name: 'Copy something',\n with_dict: Ansible::Ruby::Models::JinjaExpression.new('servers')\n end\n end\n\n context 'other attributes' do\n before do\n # We just want to ensure values pass through to the model, validation isn't important here\n allow(builder).to receive(:validate?).and_return(false)\n end\n\n # We don't build name or tasks the same way as others\n (Ansible::Ruby::Models::Task.instance_methods - Object.instance_methods - %i[name= module= register= when= inclusion= vars= local_action= attributes= block= rescue= always=])\n .select { |method| method.to_s.end_with?('=') }\n .map { |method| method.to_s[0..-2] }\n .each do |method|\n\n context method do\n let(:ruby) { \"#{method} 'some_value'\\ncopy do\\nsrc 'file1'\\ndest 'file2'\\nend\\n\" }\n\n it { is_expected.to be_a Ansible::Ruby::Models::Task }\n\n it 'has the builder value' do\n expect(task.send(method)).to eq 'some_value'\n end\n end\n end\n end\n\n context 'no such attribute' do\n context 'before module' do\n let(:ruby) do\n <<-RUBY\n foobar\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n RUBY\n end\n\n it 'should raise an error' do\n expect {evaluate}.to raise_error 'Unknown module foobar'\n end\n end\n\n context 'after module' do\n let(:ruby) do\n <<-RUBY\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n foobar\n RUBY\n end\n\n it 'should raise an error' do\n expect {evaluate}.to raise_error %r{Invalid method/local variable `foobar'. Only valid options are.*}\n end\n end\n end\n\n context '2 modules in task' do\n let(:ruby) do\n <<-RUBY\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n debug { msg 'hi' }\n RUBY\n end\n\n it 'should raise an error' do\n expect {evaluate}.to raise_error(/Invalid module call `debug' since `copy' module has already been used in this task. Only valid options are.*/)\n end\n end\n\n context 'loops' do\n context 'regular task' do\n let(:ruby) do\n <<-RUBY\n with_items(jinja('servers')) do |item|\n copy do\n src item\n dest '/file2.conf'\n end\n end\n RUBY\n end\n\n it do\n is_expected.to have_attributes name: 'Copy something',\n with_items: Ansible::Ruby::Models::JinjaExpression.new('servers'),\n module: have_attributes(src: Ansible::Ruby::Models::JinjaExpression.new('item'))\n end\n end\n\n context 'splat' do\n let(:ruby) do\n <<-RUBY\n with_items(jinja('servers1'), jinja('servers2')) do |item|\n copy do\n src item\n dest '/file2.conf'\n end\n end\n RUBY\n end\n\n it do\n is_expected.to have_attributes name: 'Copy something',\n with_items: [Ansible::Ruby::Models::JinjaExpression.new('servers1'),\n Ansible::Ruby::Models::JinjaExpression.new('servers2')],\n module: have_attributes(src: Ansible::Ruby::Models::JinjaExpression.new('item'))\n end\n end\n\n context 'free form' do\n before do\n klass = Class.new(Ansible::Ruby::Modules::Base) do\n attribute :free_form\n validates :free_form, presence: true\n attribute :src\n end\n stub_const 'Ansible::Ruby::Modules::Jinjafftest', klass\n klass.class_eval do\n include Ansible::Ruby::Modules::FreeForm\n end\n end\n\n let(:ruby) do\n <<-RUBY\n with_items(jinja('servers')) do |item|\n jinjafftest \"howdy \\#{item}\" do\n src '/file1.conf'\n end\n end\n RUBY\n end\n\n it do\n is_expected.to have_attributes name: 'Copy something',\n with_items: Ansible::Ruby::Models::JinjaExpression.new('servers'),\n module: have_attributes(free_form: 'howdy {{ item }}', src: '/file1.conf')\n end\n end\n end\n\n context 'dictionary' do\n let(:ruby) do\n <<-RUBY\n with_dict(jinja('servers')) do |key, value|\n copy do\n src value.toodles\n dest key\n end\n end\n RUBY\n end\n\n it do\n is_expected.to have_attributes name: 'Copy something',\n with_dict: Ansible::Ruby::Models::JinjaExpression.new('servers'),\n module: have_attributes(src: Ansible::Ruby::Models::JinjaExpression.new('item.value.toodles'),\n dest: Ansible::Ruby::Models::JinjaExpression.new('item.key'))\n end\n end\n\n context 'no modules' do\n let(:ruby) do\n <<-RUBY\n become\n RUBY\n end\n\n it 'should raise an error' do\n expect {evaluate}.to raise_error %r{You must either use an include or a module/block but not both.*}\n end\n end\n\n context 'implicit bool true' do\n let(:ruby) do\n <<-RUBY\n become\n ignore_errors\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Task }\n it do\n is_expected.to have_attributes name: 'Copy something',\n become: true,\n ignore_errors: true,\n module: be_a(Ansible::Ruby::Modules::Copy)\n end\n end\n\n context 'register' do\n context 'valid' do\n let(:ruby) do\n <<-RUBY\n atomic_result = copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n changed_when \"'No upgrade available' not in \\#{atomic_result.stdout}\"\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Task }\n it do\n is_expected.to have_attributes name: 'Copy something',\n register: 'result_1',\n changed_when: \"'No upgrade available' not in result_1.stdout\",\n module: be_a(Ansible::Ruby::Modules::Copy)\n end\n\n it 'returns a result that matches the register usage' do\n expect(task.register).to eq 'result_1'\n expect(@variable.something).to eq 'result_1.something'\n end\n\n it 'returns a result that matches the register usage regardless of order' do\n # trigger execution\n stuff = task\n expect(@variable.something).to eq 'result_1.something'\n expect(stuff.register).to eq 'result_1'\n end\n end\n\n context 'syntax error' do\n let(:ruby) do\n <<-RUBY\n atomic_result = copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n changed_when \"'No upgrade available' not in \\#{atomicc_result.stdout}\"\n RUBY\n end\n\n it 'should raise an error' do\n expect {evaluate}.to raise_error(%r{Invalid method/local variable `atomicc_result.*})\n end\n end\n end\n\n context 'attempt to use listen with task' do\n let(:ruby) do\n <<-RUBY\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n listen 'foobar'\n RUBY\n end\n\n it 'should raise an error' do\n expect {evaluate}.to raise_error(%r{Invalid method/local variable `listen.*})\n end\n end\nend\n" }, { "alpha_fraction": 0.7256637215614319, "alphanum_fraction": 0.7319848537445068, "avg_line_length": 34.95454406738281, "blob_id": "8982c133c372a32d86a0d16effa3ec9692a24304", "content_id": "7b4e93e5a4ca5b61f18e59ead922a36df18482da", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 791, "license_type": "permissive", "max_line_length": 277, "num_lines": 22, "path": "/lib/ansible/ruby/modules/custom/utilities/helper/meta.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# VALIDATED_CHECKSUM: WzdFTS+LyBFdjn8ym5RktQ0UEXZTEQOhKhx6JCFMT4I=\n\n# See LICENSE.txt for license\n\nrequire 'ansible/ruby/modules/generated/utilities/helper/meta'\nrequire 'ansible/ruby/modules/free_form'\n\nmodule Ansible\n module Ruby\n module Modules\n class Meta\n include FreeForm\n\n # we want this to be a symbol but the FreeForm module will expect a string, so clear out its validation\n remove_existing_validations :free_form\n validates :free_form, presence: true, expression_inclusion: { in: %i[noop flush_handlers refresh_inventory clear_facts clear_host_errors end_play], message: '%{value} needs to be :noop, :flush_handlers, :refresh_inventory, :clear_facts, :clear_host_errors, :end_play' }\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7359045147895813, "alphanum_fraction": 0.7364554405212402, "avg_line_length": 99.83333587646484, "blob_id": "133f79ddd16154c686f3d66db6a1a93ff03949ff", "content_id": "452b7a8a222531095863632a3e45a14f7463a705", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5445, "license_type": "permissive", "max_line_length": 538, "num_lines": 54, "path": "/lib/ansible/ruby/modules/generated/network/dellos9/dellos9_config.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # OS9 configurations use a simple block indent file syntax for segmenting configuration into sections. This module provides an implementation for working with OS9 configuration sections in a deterministic way.\n class Dellos9_config < Base\n # @return [Array<String>, String, nil] The ordered set of commands that should be configured in the section. The commands must be the exact same commands as found in the device running-config. Be sure to note the configuration command syntax as some commands are automatically modified by the device config parser. This argument is mutually exclusive with I(src).\n attribute :lines\n validates :lines, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] The ordered set of parents that uniquely identify the section or hierarchy the commands should be checked against. If the parents argument is omitted, the commands are checked against the set of top level or global commands.\n attribute :parents\n validates :parents, type: TypeGeneric.new(String)\n\n # @return [Object, nil] Specifies the source path to the file that contains the configuration or configuration template to load. The path to the source file can either be the full path on the Ansible control host or a relative path from the playbook or role root directory. This argument is mutually exclusive with I(lines).\n attribute :src\n\n # @return [Array<String>, String, nil] The ordered set of commands to push on to the command stack if a change needs to be made. This allows the playbook designer the opportunity to perform configuration commands prior to pushing any changes without affecting how the set of commands are matched against the system.\n attribute :before\n validates :before, type: TypeGeneric.new(String)\n\n # @return [Object, nil] The ordered set of commands to append to the end of the command stack if a change needs to be made. Just like with I(before) this allows the playbook designer to append a set of commands to be executed after the command set.\n attribute :after\n\n # @return [:line, :strict, :exact, :none, nil] Instructs the module on the way to perform the matching of the set of commands against the current device config. If match is set to I(line), commands are matched line by line. If match is set to I(strict), command lines are matched with respect to position. If match is set to I(exact), command lines must be an equal match. Finally, if match is set to I(none), the module will not attempt to compare the source configuration with the running configuration on the remote device.\n attribute :match\n validates :match, expression_inclusion: {:in=>[:line, :strict, :exact, :none], :message=>\"%{value} needs to be :line, :strict, :exact, :none\"}, allow_nil: true\n\n # @return [:line, :block, nil] Instructs the module on the way to perform the configuration on the device. If the replace argument is set to I(line) then the modified lines are pushed to the device in configuration mode. If the replace argument is set to I(block) then the entire command block is pushed to the device in configuration mode if any line is not correct.\n attribute :replace\n validates :replace, expression_inclusion: {:in=>[:line, :block], :message=>\"%{value} needs to be :line, :block\"}, allow_nil: true\n\n # @return [:merge, :check, nil] The I(update) argument controls how the configuration statements are processed on the remote device. Valid choices for the I(update) argument are I(merge) and I(check). When you set this argument to I(merge), the configuration changes merge with the current device running configuration. When you set this argument to I(check) the configuration updates are determined but not actually configured on the remote device.\n attribute :update\n validates :update, expression_inclusion: {:in=>[:merge, :check], :message=>\"%{value} needs to be :merge, :check\"}, allow_nil: true\n\n # @return [Symbol, nil] The C(save) argument instructs the module to save the running- config to the startup-config at the conclusion of the module running. If check mode is specified, this argument is ignored.\n attribute :save\n validates :save, type: Symbol\n\n # @return [Object, nil] The module, by default, will connect to the remote device and retrieve the current running-config to use as a base for comparing against the contents of source. There are times when it is not desirable to have the task get the current running-config for every task in a playbook. The I(config) argument allows the implementer to pass in the configuration to use as the base config for comparison.\n attribute :config\n\n # @return [:yes, :no, nil] This argument will cause the module to create a full backup of the current C(running-config) from the remote device before any changes are made. The backup file is written to the C(backup) folder in the playbook root directory. If the directory does not exist, it is created.\n attribute :backup\n validates :backup, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7322834730148315, "alphanum_fraction": 0.7532808184623718, "avg_line_length": 20.16666603088379, "blob_id": "bd5fd8add9bef73ce254c9775aefd41652939b6f", "content_id": "9f640d763ed9933c95aa4cef06aa2b219869547d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 381, "license_type": "permissive", "max_line_length": 66, "num_lines": 18, "path": "/lib/ansible/ruby/modules/custom/files/replace.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# VALIDATED_CHECKSUM: wEhr1Qmn3zp1g3c/T5S2CNpJkLWEZM4S/ppfOtqQDQ0=\n\n# see LICENSE.txt in project root\n\nrequire 'ansible/ruby/modules/generated/files/replace'\nrequire 'ansible/ruby/modules/helpers/file_attributes'\n\nmodule Ansible\n module Ruby\n module Modules\n class Replace\n include Helpers::FileAttributes\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.703446626663208, "alphanum_fraction": 0.7046433687210083, "avg_line_length": 72.29824829101562, "blob_id": "cdcb2c49147c9fe7b5cde7667f22c756930b231a", "content_id": "6a8ee55fc2d9149be74c152a23e84b057cc35d2e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4178, "license_type": "permissive", "max_line_length": 753, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_vpc_dhcp_option.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module removes, or creates DHCP option sets, and can associate them to a VPC. Optionally, a new DHCP Options set can be created that converges a VPC's existing DHCP option set with values provided. When dhcp_options_id is provided, the module will 1. remove (with state='absent') 2. ensure tags are applied (if state='present' and tags are provided 3. attach it to a VPC (if state='present' and a vpc_id is provided. If any of the optional values are missing, they will either be treated as a no-op (i.e., inherit what already exists for the VPC) To remove existing options while inheriting, supply an empty value (e.g. set ntp_servers to [] if you want to remove them from the VPC's options) Most of the options should be self-explanatory.\n class Ec2_vpc_dhcp_option < Base\n # @return [String, nil] The domain name to set in the DHCP option sets\n attribute :domain_name\n validates :domain_name, type: String\n\n # @return [Array<String>, String, nil] A list of hosts to set the DNS servers for the VPC to. (Should be a list of IP addresses rather than host names.)\n attribute :dns_servers\n validates :dns_servers, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] List of hosts to advertise as NTP servers for the VPC.\n attribute :ntp_servers\n validates :ntp_servers, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] List of hosts to advertise as NetBIOS servers.\n attribute :netbios_name_servers\n validates :netbios_name_servers, type: TypeGeneric.new(String)\n\n # @return [Integer, nil] NetBIOS node type to advertise in the DHCP options. The AWS recommendation is to use 2 (when using netbios name services) http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_DHCP_Options.html\n attribute :netbios_node_type\n validates :netbios_node_type, type: Integer\n\n # @return [String, nil] VPC ID to associate with the requested DHCP option set. If no vpc id is provided, and no matching option set is found then a new DHCP option set is created.\n attribute :vpc_id\n validates :vpc_id, type: String\n\n # @return [:yes, :no, nil] Whether to delete the old VPC DHCP option set when associating a new one. This is primarily useful for debugging/development purposes when you want to quickly roll back to the old option set. Note that this setting will be ignored, and the old DHCP option set will be preserved, if it is in use by any other VPC. (Otherwise, AWS will return an error.)\n attribute :delete_old\n validates :delete_old, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] For any DHCP options not specified in these parameters, whether to inherit them from the options set already applied to vpc_id, or to reset them to be empty.\n attribute :inherit_existing\n validates :inherit_existing, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Hash, nil] Tags to be applied to a VPC options set if a new one is created, or if the resource_id is provided. (options must match)\n attribute :tags\n validates :tags, type: Hash\n\n # @return [String, nil] The resource_id of an existing DHCP options set. If this is specified, then it will override other settings, except tags (which will be updated to match)\n attribute :dhcp_options_id\n validates :dhcp_options_id, type: String\n\n # @return [:absent, :present, nil] create/assign or remove the DHCP options. If state is set to absent, then a DHCP options set matched either by id, or tags and options will be removed if possible.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7282123565673828, "alphanum_fraction": 0.7284472584724426, "avg_line_length": 76.4000015258789, "blob_id": "9b1808254051c8f2e3208723ea82f549f92c509a", "content_id": "972a6d361aeb41d326a969d20050f33bffd3da21", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4257, "license_type": "permissive", "max_line_length": 545, "num_lines": 55, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_iapp_service.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages TCL iApp services on a BIG-IP.\n # If you are looking for the API that is communicated with on the BIG-IP, the one the is used is C(/mgmt/tm/sys/application/service/).\n class Bigip_iapp_service < Base\n # @return [String] The name of the iApp service that you want to deploy.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The iApp template from which to instantiate a new service. This template must exist on your BIG-IP before you can successfully create a service.,When creating a new service, this parameter is required.\n attribute :template\n validates :template, type: String\n\n # @return [String, Hash, nil] A hash of all the required template variables for the iApp template. If your parameters are stored in a file (the more common scenario) it is recommended you use either the C(file) or C(template) lookups to supply the expected parameters.,These parameters typically consist of the C(lists), C(tables), and C(variables) fields.\n attribute :parameters\n validates :parameters, type: MultipleTypes.new(String, Hash)\n\n # @return [Symbol, nil] Forces the updating of an iApp service even if the parameters to the service have not changed. This option is of particular importance if the iApp template that underlies the service has been updated in-place. This option is equivalent to re-configuring the iApp if that template has changed.\n attribute :force\n validates :force, type: Symbol\n\n # @return [:present, :absent, nil] When C(present), ensures that the iApp service is created and running. When C(absent), ensures that the iApp service has been removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [Boolean, nil] Indicates whether the application service is tied to the template, so when the template is updated, the application service changes to reflect the updates.,When C(yes), disallows any updates to the resources that the iApp service has created, if they are not updated directly through the iApp.,When C(no), allows updates outside of the iApp.,If this option is specified in the Ansible task, it will take precedence over any similar setting in the iApp Service payload that you provide in the C(parameters) field.\n attribute :strict_updates\n validates :strict_updates, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] The traffic group for the iApp service. When creating a new service, if this value is not specified, the default of C(/Common/traffic-group-1) will be used.,If this option is specified in the Ansible task, it will take precedence over any similar setting in the iApp Service payload that you provide in the C(parameters) field.\n attribute :traffic_group\n\n # @return [Array<Hash>, Hash, nil] Metadata associated with the iApp service.,If this option is specified in the Ansible task, it will take precedence over any similar setting in the iApp Service payload that you provide in the C(parameters) field.\n attribute :metadata\n validates :metadata, type: TypeGeneric.new(Hash)\n\n # @return [Object, nil] Description of the iApp service.,If this option is specified in the Ansible task, it will take precedence over any similar setting in the iApp Service payload that you provide in the C(parameters) field.\n attribute :description\n\n # @return [Object, nil] The device group for the iApp service.,If this option is specified in the Ansible task, it will take precedence over any similar setting in the iApp Service payload that you provide in the C(parameters) field.\n attribute :device_group\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6391752362251282, "alphanum_fraction": 0.6391752362251282, "avg_line_length": 30.382352828979492, "blob_id": "d3d98b68759c34f3cd6e140bb5d0efc9b59988aa", "content_id": "05c9d443ed9e2a8f22388549c427f6a0b9be144f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1067, "license_type": "permissive", "max_line_length": 142, "num_lines": 34, "path": "/lib/ansible/ruby/modules/generated/storage/ibm/ibm_sa_pool.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module creates or deletes pools to be used on IBM Spectrum Accelerate storage systems.\n class Ibm_sa_pool < Base\n # @return [Object] Pool name.\n attribute :pool\n validates :pool, presence: true\n\n # @return [:present, :absent] Pool state.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [Integer, nil] Pool size in GB\n attribute :size\n validates :size, type: Integer\n\n # @return [Object, nil] Pool snapshot size in GB\n attribute :snapshot_size\n\n # @return [Object, nil] Adds the pool to the specified domain.\n attribute :domain\n\n # @return [Object, nil] Assigns a perf_class to the pool.\n attribute :perf_class\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.705810010433197, "alphanum_fraction": 0.7091915011405945, "avg_line_length": 66.77083587646484, "blob_id": "518022d2156007d233da96fe2d4d499acd8f4fc7", "content_id": "f06d97c18e9e352544d4ff5580a1300d86dcc929", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3253, "license_type": "permissive", "max_line_length": 421, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/netapp_e_iscsi_interface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configure settings of an E-Series iSCSI interface\n class Netapp_e_iscsi_interface < Base\n # @return [:A, :B] The controller that owns the port you want to configure.,Controller names are presented alphabetically, with the first controller as A, the second as B, and so on.,Current hardware models have either 1 or 2 available controllers, but that is not a guaranteed hard limitation and could change in the future.\n attribute :controller\n validates :controller, presence: true, expression_inclusion: {:in=>[:A, :B], :message=>\"%{value} needs to be :A, :B\"}\n\n # @return [String] The channel of the port to modify the configuration of.,The list of choices is not necessarily comprehensive. It depends on the number of ports that are available in the system.,The numerical value represents the number of the channel (typically from left to right on the HIC), beginning with a value of 1.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:enabled, :disabled, nil] When enabled, the provided configuration will be utilized.,When disabled, the IPv4 configuration will be cleared and IPv4 connectivity disabled.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [String, nil] The IPv4 address to assign to the interface.,Should be specified in xx.xx.xx.xx form.,Mutually exclusive with I(config_method=dhcp)\n attribute :address\n validates :address, type: String\n\n # @return [String, nil] The subnet mask to utilize for the interface.,Should be specified in xx.xx.xx.xx form.,Mutually exclusive with I(config_method=dhcp)\n attribute :subnet_mask\n validates :subnet_mask, type: String\n\n # @return [String, nil] The IPv4 gateway address to utilize for the interface.,Should be specified in xx.xx.xx.xx form.,Mutually exclusive with I(config_method=dhcp)\n attribute :gateway\n validates :gateway, type: String\n\n # @return [:dhcp, :static, nil] The configuration method type to use for this interface.,dhcp is mutually exclusive with I(address), I(subnet_mask), and I(gateway).\n attribute :config_method\n validates :config_method, expression_inclusion: {:in=>[:dhcp, :static], :message=>\"%{value} needs to be :dhcp, :static\"}, allow_nil: true\n\n # @return [Integer, nil] The maximum transmission units (MTU), in bytes.,This allows you to configure a larger value for the MTU, in order to enable jumbo frames (any value > 1500).,Generally, it is necessary to have your host, switches, and other components not only support jumbo frames, but also have it configured properly. Therefore, unless you know what you're doing, it's best to leave this at the default.\n attribute :mtu\n validates :mtu, type: Integer\n\n # @return [Object, nil] A local path to a file to be used for debug logging\n attribute :log_path\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6838709712028503, "alphanum_fraction": 0.7032257914543152, "avg_line_length": 13.090909004211426, "blob_id": "18826babf635fd237ec98df7a36c8d515c9fcb55", "content_id": "a856001fad9c837908c07b882259500e0b749314", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 155, "license_type": "permissive", "max_line_length": 36, "num_lines": 11, "path": "/spec/rake/nested_tasks/playbook1_test.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nplay 'the play name' do\n hosts %w[host1 host2]\n\n roles 'role1'\n\n user 'centos'\nend\n\nansible_include 'other_playbook.yml'\n" }, { "alpha_fraction": 0.6937384009361267, "alphanum_fraction": 0.6937384009361267, "avg_line_length": 53.6779670715332, "blob_id": "b1a37140104ce341193f68ef38c6980fe86734fa", "content_id": "2b09159403568c8b0cdd9afeede039a73e4f4221", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3226, "license_type": "permissive", "max_line_length": 380, "num_lines": 59, "path": "/lib/ansible/ruby/modules/generated/messaging/rabbitmq_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove users to RabbitMQ and assign permissions\n class Rabbitmq_user < Base\n # @return [String] Name of user to add\n attribute :user\n validates :user, presence: true, type: String\n\n # @return [String, nil] Password of user to add.,To change the password of an existing user, you must also specify C(update_password=always).\n attribute :password\n validates :password, type: String\n\n # @return [Object, nil] User tags specified as comma delimited\n attribute :tags\n\n # @return [Object, nil] a list of dicts, each dict contains vhost, configure_priv, write_priv, and read_priv, and represents a permission rule for that vhost.,This option should be preferable when you care about all permissions of the user.,You should use vhost, configure_priv, write_priv, and read_priv options instead if you care about permissions for just some vhosts.\n attribute :permissions\n\n # @return [String, nil] vhost to apply access privileges.,This option will be ignored when permissions option is used.\n attribute :vhost\n validates :vhost, type: String\n\n # @return [String, nil] erlang node name of the rabbit we wish to configure\n attribute :node\n validates :node, type: String\n\n # @return [String, nil] Regular expression to restrict configure actions on a resource for the specified vhost.,By default all actions are restricted.,This option will be ignored when permissions option is used.\n attribute :configure_priv\n validates :configure_priv, type: String\n\n # @return [String, nil] Regular expression to restrict configure actions on a resource for the specified vhost.,By default all actions are restricted.,This option will be ignored when permissions option is used.\n attribute :write_priv\n validates :write_priv, type: String\n\n # @return [String, nil] Regular expression to restrict configure actions on a resource for the specified vhost.,By default all actions are restricted.,This option will be ignored when permissions option is used.\n attribute :read_priv\n validates :read_priv, type: String\n\n # @return [:yes, :no, nil] Deletes and recreates the user.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Specify if user is to be added or removed\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:on_create, :always, nil] C(on_create) will only set the password for newly created users. C(always) will update passwords if they differ.\n attribute :update_password\n validates :update_password, expression_inclusion: {:in=>[:on_create, :always], :message=>\"%{value} needs to be :on_create, :always\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7469116449356079, "alphanum_fraction": 0.7567310929298401, "avg_line_length": 37.030120849609375, "blob_id": "8046e54b7c2f75125a9da5ddcc13e2313bb824e7", "content_id": "23295348c2b3da038335f17da5075290a6b5e437", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6314, "license_type": "permissive", "max_line_length": 271, "num_lines": 166, "path": "/README.md", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# Ansible-Ruby\n\n[![Build Status](http://img.shields.io/travis/wied03/ansible-ruby/master.svg?style=flat)](http://travis-ci.org/wied03/ansible-ruby)\n[![Maintainability](https://api.codeclimate.com/v1/badges/cbfe0b2fe408abc4dd08/maintainability)](https://codeclimate.com/github/wied03/ansible-ruby/maintainability)\n[![Test Coverage](https://api.codeclimate.com/v1/badges/cbfe0b2fe408abc4dd08/test_coverage)](https://codeclimate.com/github/wied03/ansible-ruby/test_coverage)\n[![Version](http://img.shields.io/gem/v/ansible-ruby.svg?style=flat-square)](https://rubygems.org/gems/ansible-ruby)\n\nAttempts to create a Ruby DSL on top of Ansible's YML files. Currently this is against Ansible 2.1.2.0.\n\n## What does it do?\n* Creates a Ruby DSL that compiles .rb files to YML on a file by file basis\n* Type validation\n* Assists with basic syntax regarding `register`\n* Offers a Rake task to assist in easily generating YML files from dependent Ruby files\n\n## Why does this exist?\nYAML is OK but can suffer from the same problems that exist with any markup language. If you can write in a first class language that is syntaxually easier, that might be of some benefit.\n\n## Why Ruby?\n\nIt's a productive language for me that's easy to write DSLs in. One could argue that more strongly typed languages like Crystal could be better fit for this.\n\n## How does this relate to Python and modules?\nPython is widely installed (probably moreso than Ruby :()) on machines to be managed. We recognize Ansible's choice here. This tool does not try and change how Ansible modules work. It only tries to avoid editing lots of YML directly.\n\n## Usage\n\nInstall Ruby+Bundler (this was tested with Ruby 2.2.5), then add `ansible-ruby` to your Gemfile:\n\n```ruby\ngem 'ansible-ruby'\n```\n\n## File Structure\n\nNothing changes here. Lay out playbooks/etc. like you would normally. There are 2 places right now where you can use ansible-ruby files.\n\n1. Playbooks (either with role references or embedded tasks)\n2. Tasks within roles\n\nAnsible-ruby does NOT stray beyond the boundaries of a normal Ansible YAML file. Nothing magic with includes, etc.\n\n## Examples\nHere is a playbook with a single play:\n```ruby\nplay 'the play name' do\n hosts %w(host1 host2)\n\n task 'Copy something over' do\n result = copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n\n become\n notify 'handler1'\n changed_when \"'no upgrade' in #{result.stdout}\"\n end\n\n user 'centos'\nend\n```\n\nThis will be automatically translated to:\n```yml\n---\n# This is a generated YAML file by ansible-ruby, DO NOT EDIT\n- hosts: host1:host2\n name: the play name\n tasks:\n - name: Copy something over\n copy:\n src: \"/file1.conf\"\n dest: \"/file2.conf\"\n become: true\n register: result_1\n changed_when: \"'no upgrade' in result_1.stdout\"\n notify:\n - handler1\n user: centos\n```\n\nThere is also a shortcut for a localhost/local connection play.\n\n```ruby\nplay 'command fun' do\n local_host\n \n task 'say hello' do\n command 'ls howdy'\n end\nend\n```\n\nCompiles to:\n```yml\n---\n# This is a generated YAML file by ansible-ruby, DO NOT EDIT\n- hosts: localhost\n name: command fun\n tasks:\n - name: say hello\n command: ls howdy\n connection: local\n```\n\nNote this is using a tiny bit of Ruby AST-ish syntax with the result variables to make working them more friendly. There is more work to do on this [see issue](https://github.com/wied03/ansible-ruby/issues/5).\n\nYou can see more examples in the examples/ directory in the repository.\n\n## Invoke/Rake\n\nYou can invoke all of this via a Rake task. The Rake task will, by convention, look for any .rb files under roles/role_name/tasks/*.rb and transform those as well:\n\n```ruby\nrequire 'ansible/ruby/rake/tasks'\n\ndesc 'named ansible task'\nAnsible::Ruby::Rake::Execute.new :stuff do |task|\n task.playbooks = 'lib/ansible/ruby/rake/sample_test.rb'\nend\n```\n\n## Module Support\n\nRuby code within this project parses the YAML documentation in Ansible's modules and creates model classes in Ruby to assist with validation. All of them are there but some of them might need some work.\n\n## Other Features\n* Light variable AST (see examples)\n* Helps with registering a variable in 1 task and using in another (see image_copy example)\n* Type normalization in modules (e.g. allow arrays to be passed in if a given module is expecting CSV)\n\n## Ansible Galaxy\n\nThere's no reason why you can't use Ansible Galaxy with this. It hasn't been tested much but since this tool stays within the task/playbook/etc. boundary, it should work fine to use Galaxy roles from ansible-ruby playbooks or even to build Galaxy roles with ansible-ruby.\n\n## Limitations\n\n* Type validation in generated modules isn't 100% correct. I try and fix modules as I discover the,\n* Error messages could use improvement - [see issue](https://github.com/wied03/ansible-ruby/issues/7)\n* Result variable DSL is fairly limited, all it does right now is make sure you use the right variable name (see issues for improvements) \n\n## License\nCopyright (c) 2016, BSW Technology Consulting LLC\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n" }, { "alpha_fraction": 0.726123571395874, "alphanum_fraction": 0.7268258333206177, "avg_line_length": 75.97297668457031, "blob_id": "e8276d12ec039034e8b429a29d20ffdcc5fcbdb1", "content_id": "1f3e95de9b3e7d5ee3d07376066074ff1bc85ccf", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2848, "license_type": "permissive", "max_line_length": 589, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_device_trust.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage the trust relationships between BIG-IPs. Devices, once peered, cannot be updated. If updating is needed, the peer must first be removed before it can be re-added to the trust.\n class Bigip_device_trust < Base\n # @return [String] The peer address to connect to and trust for synchronizing configuration. This is typically the management address of the remote device, but may also be a Self IP.\n attribute :peer_server\n validates :peer_server, presence: true, type: String\n\n # @return [String, nil] The hostname that you want to associate with the device. This value will be used to easily distinguish this device in BIG-IP configuration.,When trusting a new device, if this parameter is not specified, the value of C(peer_server) will be used as a default.\n attribute :peer_hostname\n validates :peer_hostname, type: String\n\n # @return [String, nil] The API username of the remote peer device that you are trusting. Note that the CLI user cannot be used unless it too has an API account. If this value is not specified, then the value of C(user), or the environment variable C(F5_USER) will be used.\n attribute :peer_user\n validates :peer_user, type: String\n\n # @return [String, nil] The password of the API username of the remote peer device that you are trusting. If this value is not specified, then the value of C(password), or the environment variable C(F5_PASSWORD) will be used.\n attribute :peer_password\n validates :peer_password, type: String\n\n # @return [:peer, :subordinate, nil] Specifies whether the device you are adding is a Peer or a Subordinate. The default is C(peer).,The difference between the two is a matter of mitigating risk of compromise.,A subordinate device cannot sign a certificate for another device.,In the case where the security of an authority device in a trust domain is compromised, the risk of compromise is minimized for any subordinate device.,Designating devices as subordinate devices is recommended for device groups with a large number of member devices, where the risk of compromise is high.\n attribute :type\n validates :type, expression_inclusion: {:in=>[:peer, :subordinate], :message=>\"%{value} needs to be :peer, :subordinate\"}, allow_nil: true\n\n # @return [:absent, :present, nil] When C(present), ensures the specified devices are trusted.,When C(absent), removes the device trusts.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6728395223617554, "alphanum_fraction": 0.6728395223617554, "avg_line_length": 37.57143020629883, "blob_id": "7b5829abb7e00f78134fd852444920bfafedae3b", "content_id": "d6ffd22ba5835d2d4a6cb638c319211848ed7596", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 810, "license_type": "permissive", "max_line_length": 195, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_external_provider_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Retrieve facts about one or more oVirt/RHV external providers.\n class Ovirt_external_provider_facts < Base\n # @return [:os_image, :os_network, :os_volume, :foreman] Type of the external provider.\n attribute :type\n validates :type, presence: true, expression_inclusion: {:in=>[:os_image, :os_network, :os_volume, :foreman], :message=>\"%{value} needs to be :os_image, :os_network, :os_volume, :foreman\"}\n\n # @return [String, nil] Name of the external provider, can be used as glob expression.\n attribute :name\n validates :name, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7015037536621094, "alphanum_fraction": 0.7015037536621094, "avg_line_length": 52.20000076293945, "blob_id": "0726c7d8a9b7e4a1d725cdb9a426245b8ded995f", "content_id": "356a514619c0d435064ebbf9adde270536e61c16", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1330, "license_type": "permissive", "max_line_length": 303, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_software_image.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages software images on a BIG-IP. These images may include both base images and hotfix images.\n class Bigip_software_image < Base\n # @return [Symbol, nil] When C(yes), will upload the file every time and replace the file on the device.,When C(no), the file will only be uploaded if it does not already exist.,Generally should be C(yes) only in cases where you have reason to believe that the image was corrupted during upload.\n attribute :force\n validates :force, type: Symbol\n\n # @return [:absent, :present, nil] When C(present), ensures that the image is uploaded.,When C(absent), ensures that the image is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] The image to put on the remote device.,This may be an absolute or relative location on the Ansible controller.,Image names, whether they are base ISOs or hotfix ISOs, B(must) be unique.\n attribute :image\n validates :image, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6271297335624695, "alphanum_fraction": 0.6539973616600037, "avg_line_length": 41.38888931274414, "blob_id": "dd0ad11a2921ea44f6066b11e725cfd1a1ca501c", "content_id": "fa699e74a80e4aebd9d865d1010d733dc1a556bd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1526, "license_type": "permissive", "max_line_length": 197, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/cloudwatchlogs_log_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or delete log_group in CloudWatchLogs.\n class Cloudwatchlogs_log_group < Base\n # @return [:present, :absent, nil] Whether the rule is present, absent or get\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The name of the log group.\n attribute :log_group_name\n validates :log_group_name, presence: true, type: String\n\n # @return [String, nil] The Amazon Resource Name (ARN) of the CMK to use when encrypting log data.\n attribute :kms_key_id\n validates :kms_key_id, type: String\n\n # @return [Hash, nil] The key-value pairs to use for the tags.\n attribute :tags\n validates :tags, type: Hash\n\n # @return [Object, nil] The number of days to retain the log events in the specified log group. Valid values are: [1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1827, 3653]\n attribute :retention\n\n # @return [Boolean, nil] Whether an existing log group should be overwritten on create.\n attribute :overwrite\n validates :overwrite, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6769449710845947, "alphanum_fraction": 0.6769449710845947, "avg_line_length": 55.21333312988281, "blob_id": "bb65a620ca8473297b3976e7b1ef3ead86cc84ed", "content_id": "0a0b2ee2789bb3a2a95f6a4389710d4aefe66cfa", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4216, "license_type": "permissive", "max_line_length": 278, "num_lines": 75, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vca_vapp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module will actively managed vCloud Air vApp instances. Instances can be created and deleted as well as both deployed and undeployed.\n class Vca_vapp < Base\n # @return [String] The name of the vCloud Air vApp instance\n attribute :vapp_name\n validates :vapp_name, presence: true, type: String\n\n # @return [String, nil] The name of the vApp template to use to create the vApp instance. If the I(state) is not `absent` then the I(template_name) value must be provided. The I(template_name) must be previously uploaded to the catalog specified by I(catalog_name)\n attribute :template_name\n validates :template_name, type: String\n\n # @return [Object, nil] The name of the network that should be attached to the virtual machine in the vApp. The virtual network specified must already be created in the vCloud Air VDC. If the I(state) is not 'absent' then the I(network_name) argument must be provided.\n attribute :network_name\n\n # @return [:pool, :dhcp, :static, nil] Configures the mode of the network connection.\n attribute :network_mode\n validates :network_mode, expression_inclusion: {:in=>[:pool, :dhcp, :static], :message=>\"%{value} needs to be :pool, :dhcp, :static\"}, allow_nil: true\n\n # @return [Object, nil] The name of the virtual machine instance in the vApp to manage.\n attribute :vm_name\n\n # @return [Object, nil] The number of vCPUs to configure for the VM in the vApp. If the I(vm_name) argument is provided, then this becomes a per VM setting otherwise it is applied to all VMs in the vApp.\n attribute :vm_cpus\n\n # @return [Object, nil] The amount of memory in MB to allocate to VMs in the vApp. If the I(vm_name) argument is provided, then this becomes a per VM setting otherise it is applied to all VMs in the vApp.\n attribute :vm_memory\n\n # @return [:noop, :poweron, :poweroff, :suspend, :shutdown, :reboot, :reset, nil] Specifies an operation to be performed on the vApp.\n attribute :operation\n validates :operation, expression_inclusion: {:in=>[:noop, :poweron, :poweroff, :suspend, :shutdown, :reboot, :reset], :message=>\"%{value} needs to be :noop, :poweron, :poweroff, :suspend, :shutdown, :reboot, :reset\"}, allow_nil: true\n\n # @return [:present, :absent, :deployed, :undeployed, nil] Configures the state of the vApp.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :deployed, :undeployed], :message=>\"%{value} needs to be :present, :absent, :deployed, :undeployed\"}, allow_nil: true\n\n # @return [String, nil] The vCloud Air username to use during authentication\n attribute :username\n validates :username, type: String\n\n # @return [String, nil] The vCloud Air password to use during authentication\n attribute :password\n validates :password, type: String\n\n # @return [Object, nil] The org to login to for creating vapp, mostly set when the service_type is vdc.\n attribute :org\n\n # @return [String, nil] The instance id in a vchs environment to be used for creating the vapp\n attribute :instance_id\n validates :instance_id, type: String\n\n # @return [Object, nil] The authentication host to be used when service type is vcd.\n attribute :host\n\n # @return [String, nil] The api version to be used with the vca\n attribute :api_version\n validates :api_version, type: String\n\n # @return [:vca, :vchs, :vcd, nil] The type of service we are authenticating against\n attribute :service_type\n validates :service_type, expression_inclusion: {:in=>[:vca, :vchs, :vcd], :message=>\"%{value} needs to be :vca, :vchs, :vcd\"}, allow_nil: true\n\n # @return [String, nil] The name of the virtual data center (VDC) where the vm should be created or contains the vAPP.\n attribute :vdc_name\n validates :vdc_name, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.701340913772583, "alphanum_fraction": 0.7078423500061035, "avg_line_length": 56.23255920410156, "blob_id": "c9f841f2194b5a48176ee83b92a2c87798fdd3b6", "content_id": "b87879aa250feae737aeae10a53f70f4af6eee8f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2461, "license_type": "permissive", "max_line_length": 374, "num_lines": 43, "path": "/lib/ansible/ruby/modules/generated/cloud/rackspace/rax_mon_alarm.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or delete a Rackspace Cloud Monitoring alarm that associates an existing rax_mon_entity, rax_mon_check, and rax_mon_notification_plan with criteria that specify what conditions will trigger which levels of notifications. Rackspace monitoring module flow | rax_mon_entity -> rax_mon_check -> rax_mon_notification -> rax_mon_notification_plan -> *rax_mon_alarm*\n class Rax_mon_alarm < Base\n # @return [:present, :absent, nil] Ensure that the alarm with this C(label) exists or does not exist.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object] Friendly name for this alarm, used to achieve idempotence. Must be a String between 1 and 255 characters long.\n attribute :label\n validates :label, presence: true\n\n # @return [Object] ID of the entity this alarm is attached to. May be acquired by registering the value of a rax_mon_entity task.\n attribute :entity_id\n validates :entity_id, presence: true\n\n # @return [Object] ID of the check that should be alerted on. May be acquired by registering the value of a rax_mon_check task.\n attribute :check_id\n validates :check_id, presence: true\n\n # @return [Object] ID of the notification plan to trigger if this alarm fires. May be acquired by registering the value of a rax_mon_notification_plan task.\n attribute :notification_plan_id\n validates :notification_plan_id, presence: true\n\n # @return [Object, nil] Alarm DSL that describes alerting conditions and their output states. Must be between 1 and 16384 characters long. See http://docs.rackspace.com/cm/api/v1.0/cm-devguide/content/alerts-language.html for a reference on the alerting language.\n attribute :criteria\n\n # @return [Symbol, nil] If yes, create this alarm, but leave it in an inactive state. Defaults to no.\n attribute :disabled\n validates :disabled, type: Symbol\n\n # @return [Object, nil] Arbitrary key/value pairs to accompany the alarm. Must be a hash of String keys and values between 1 and 255 characters long.\n attribute :metadata\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7329397797584534, "alphanum_fraction": 0.7371900677680969, "avg_line_length": 95.25, "blob_id": "0b4bc5024c71daccb813c11bf32f69cf50732258", "content_id": "1762a9053f6b3aaeac3a036b6ccf5bf4bddab27b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4235, "license_type": "permissive", "max_line_length": 806, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_compute_target_pool.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Represents a TargetPool resource, used for Load Balancing.\n class Gcp_compute_target_pool < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] This field is applicable only when the containing target pool is serving a forwarding rule as the primary pool, and its failoverRatio field is properly set to a value between [0, 1].,backupPool and failoverRatio together define the fallback behavior of the primary target pool: if the ratio of the healthy instances in the primary pool is at or below failoverRatio, traffic arriving at the load-balanced IP will be directed to the backup pool.,In case where failoverRatio and backupPool are not set, or all the instances in the backup pool are unhealthy, the traffic will be directed back to the primary pool in the \"force\" mode, where traffic will be spread to the healthy instances with the best effort, or to all instances when no instance is healthy.\n attribute :backup_pool\n\n # @return [Object, nil] An optional description of this resource.\n attribute :description\n\n # @return [Object, nil] This field is applicable only when the containing target pool is serving a forwarding rule as the primary pool (i.e., not as a backup pool to some other target pool). The value of the field must be in [0, 1].,If set, backupPool must also be set. They together define the fallback behavior of the primary target pool: if the ratio of the healthy instances in the primary pool is at or below this number, traffic arriving at the load-balanced IP will be directed to the backup pool.,In case where failoverRatio is not set or all the instances in the backup pool are unhealthy, the traffic will be directed back to the primary pool in the \"force\" mode, where traffic will be spread to the healthy instances with the best effort, or to all instances when no instance is healthy.\n attribute :failover_ratio\n\n # @return [Object, nil] A reference to a HttpHealthCheck resource.,A member instance in this pool is considered healthy if and only if the health checks pass. If not specified it means all member instances will be considered healthy at all times.\n attribute :health_check\n\n # @return [Object, nil] A list of virtual machine instances serving this pool.,They must live in zones contained in the same region as this pool.\n attribute :instances\n\n # @return [String] Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:NONE, :CLIENT_IP, :CLIENT_IP_PROTO, nil] Session affinity option. Must be one of these values: - NONE: Connections from the same client IP may go to any instance in the pool.,- CLIENT_IP: Connections from the same client IP will go to the same instance in the pool while that instance remains healthy.,- CLIENT_IP_PROTO: Connections from the same client IP with the same IP protocol will go to the same instance in the pool while that instance remains healthy.\n attribute :session_affinity\n validates :session_affinity, expression_inclusion: {:in=>[:NONE, :CLIENT_IP, :CLIENT_IP_PROTO], :message=>\"%{value} needs to be :NONE, :CLIENT_IP, :CLIENT_IP_PROTO\"}, allow_nil: true\n\n # @return [String] The region where the target pool resides.\n attribute :region\n validates :region, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.658710241317749, "alphanum_fraction": 0.658710241317749, "avg_line_length": 37.51612854003906, "blob_id": "58a22ce9c9bc606eeba9d72e1d5b8ba9e372f456", "content_id": "0bed4d0acb0428a7e6fffbb9338e12ece002710f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2388, "license_type": "permissive", "max_line_length": 143, "num_lines": 62, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/taiga_issue.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates/deletes an issue in a Taiga Project Management Platform (U(https://taiga.io)).\n # An issue is identified by the combination of project, issue subject and issue type.\n # This module implements the creation or deletion of issues (not the update).\n class Taiga_issue < Base\n # @return [String, nil] The hostname of the Taiga instance.\n attribute :taiga_host\n validates :taiga_host, type: String\n\n # @return [String] Name of the project containing the issue. Must exist previously.\n attribute :project\n validates :project, presence: true, type: String\n\n # @return [String] The issue subject.\n attribute :subject\n validates :subject, presence: true, type: String\n\n # @return [String] The issue type. Must exist previously.\n attribute :issue_type\n validates :issue_type, presence: true, type: String\n\n # @return [String, nil] The issue priority. Must exist previously.\n attribute :priority\n validates :priority, type: String\n\n # @return [String, nil] The issue status. Must exist previously.\n attribute :status\n validates :status, type: String\n\n # @return [String, nil] The issue severity. Must exist previously.\n attribute :severity\n validates :severity, type: String\n\n # @return [String, nil] The issue description.\n attribute :description\n validates :description, type: String\n\n # @return [String, nil] Path to a file to be attached to the issue.\n attribute :attachment\n validates :attachment, type: String\n\n # @return [String, nil] A string describing the file to be attached to the issue.\n attribute :attachment_description\n validates :attachment_description, type: String\n\n # @return [Object, nil] A lists of tags to be assigned to the issue.\n attribute :tags\n\n # @return [:present, :absent, nil] Whether the issue should be present or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6974564790725708, "alphanum_fraction": 0.7030789852142334, "avg_line_length": 53.92647171020508, "blob_id": "fe670edb101c54b57394b032862d67364bd272f2", "content_id": "655b3670ac00cb918262eafa3c0162224030f26b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 7470, "license_type": "permissive", "max_line_length": 405, "num_lines": 136, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_cloud.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure Cloud object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_cloud < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Object, nil] Apicconfiguration settings for cloud.\n attribute :apic_configuration\n\n # @return [Symbol, nil] Boolean flag to set apic_mode.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :apic_mode\n validates :apic_mode, type: Symbol\n\n # @return [Object, nil] Awsconfiguration settings for cloud.\n attribute :aws_configuration\n\n # @return [Object, nil] Field introduced in 17.2.1.\n attribute :azure_configuration\n\n # @return [Object, nil] Cloudstackconfiguration settings for cloud.\n attribute :cloudstack_configuration\n\n # @return [Object, nil] Custom tags for all avi created resources in the cloud infrastructure.,Field introduced in 17.1.5.\n attribute :custom_tags\n\n # @return [Symbol, nil] Select the ip address management scheme.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :dhcp_enabled\n validates :dhcp_enabled, type: Symbol\n\n # @return [Object, nil] Dns profile for the cloud.,It is a reference to an object of type ipamdnsproviderprofile.\n attribute :dns_provider_ref\n\n # @return [Object, nil] Dockerconfiguration settings for cloud.\n attribute :docker_configuration\n\n # @return [Object, nil] Dns profile for east-west services.,It is a reference to an object of type ipamdnsproviderprofile.\n attribute :east_west_dns_provider_ref\n\n # @return [Object, nil] Ipam profile for east-west services.,Warning - please use virtual subnets in this ipam profile that do not conflict with the underlay networks or any overlay networks in the cluster.,For example in aws and gcp, 169.254.0.0/16 is used for storing instance metadata.,Hence, it should not be used in this profile.,It is a reference to an object of type ipamdnsproviderprofile.\n attribute :east_west_ipam_provider_ref\n\n # @return [Symbol, nil] Use static routes for vip side network resolution during virtualservice placement.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :enable_vip_static_routes\n validates :enable_vip_static_routes, type: Symbol\n\n # @return [Object, nil] Ipam profile for the cloud.,It is a reference to an object of type ipamdnsproviderprofile.\n attribute :ipam_provider_ref\n\n # @return [Object, nil] Specifies the default license tier which would be used by new se groups.,This field by default inherits the value from system configuration.,Enum options - ENTERPRISE_16, ENTERPRISE_18.,Field introduced in 17.2.5.\n attribute :license_tier\n\n # @return [String, nil] If no license type is specified then default license enforcement for the cloud type is chosen.,The default mappings are container cloud is max ses, openstack and vmware is cores and linux it is sockets.,Enum options - LIC_BACKEND_SERVERS, LIC_SOCKETS, LIC_CORES, LIC_HOSTS, LIC_SE_BANDWIDTH.\n attribute :license_type\n validates :license_type, type: String\n\n # @return [Object, nil] Linuxserverconfiguration settings for cloud.\n attribute :linuxserver_configuration\n\n # @return [Object, nil] Mesosconfiguration settings for cloud.\n attribute :mesos_configuration\n\n # @return [Integer, nil] Mtu setting for the cloud.,Default value when not specified in API or module is interpreted by Avi Controller as 1500.,Units(BYTES).\n attribute :mtu\n validates :mtu, type: Integer\n\n # @return [String] Name of the object.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Configuration parameters for nsx manager.,Field introduced in 17.1.1.\n attribute :nsx_configuration\n\n # @return [Object, nil] Default prefix for all automatically created objects in this cloud.,This prefix can be overridden by the se-group template.\n attribute :obj_name_prefix\n\n # @return [Object, nil] Openstackconfiguration settings for cloud.\n attribute :openstack_configuration\n\n # @return [Object, nil] Oshiftk8sconfiguration settings for cloud.\n attribute :oshiftk8s_configuration\n\n # @return [Symbol, nil] Prefer static routes over interface routes during virtualservice placement.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :prefer_static_routes\n validates :prefer_static_routes, type: Symbol\n\n # @return [Object, nil] Proxyconfiguration settings for cloud.\n attribute :proxy_configuration\n\n # @return [Object, nil] Rancherconfiguration settings for cloud.\n attribute :rancher_configuration\n\n # @return [Symbol, nil] Dns records for vips are added/deleted based on the operational state of the vips.,Field introduced in 17.1.12.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :state_based_dns_registration\n validates :state_based_dns_registration, type: Symbol\n\n # @return [String, nil] It is a reference to an object of type tenant.\n attribute :tenant_ref\n validates :tenant_ref, type: String\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Unique object identifier of the object.\n attribute :uuid\n\n # @return [Object, nil] Vcloudairconfiguration settings for cloud.\n attribute :vca_configuration\n\n # @return [Hash, nil] Vcenterconfiguration settings for cloud.\n attribute :vcenter_configuration\n validates :vcenter_configuration, type: Hash\n\n # @return [String] Cloud type.,Enum options - CLOUD_NONE, CLOUD_VCENTER, CLOUD_OPENSTACK, CLOUD_AWS, CLOUD_VCA, CLOUD_APIC, CLOUD_MESOS, CLOUD_LINUXSERVER, CLOUD_DOCKER_UCP,,CLOUD_RANCHER, CLOUD_OSHIFT_K8S, CLOUD_AZURE.,Default value when not specified in API or module is interpreted by Avi Controller as CLOUD_NONE.\n attribute :vtype\n validates :vtype, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6457915902137756, "alphanum_fraction": 0.6457915902137756, "avg_line_length": 42.868133544921875, "blob_id": "892caf488d96f9ea094fc14b2e336f9aa5c1352c", "content_id": "8cc35b148dbccbb79779e2ce74561ad23054de25", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3992, "license_type": "permissive", "max_line_length": 143, "num_lines": 91, "path": "/lib/ansible/ruby/modules/generated/cloud/softlayer/sl_vm.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates or cancels SoftLayer instances.\n # When created, optionally waits for it to be 'running'.\n class Sl_vm < Base\n # @return [Object, nil] Instance Id of the virtual instance to perform action option.\n attribute :instance_id\n\n # @return [Object, nil] Hostname to be provided to a virtual instance.\n attribute :hostname\n\n # @return [Object, nil] Domain name to be provided to a virtual instance.\n attribute :domain\n\n # @return [Object, nil] Datacenter for the virtual instance to be deployed.\n attribute :datacenter\n\n # @return [Object, nil] Tag or list of tags to be provided to a virtual instance.\n attribute :tags\n\n # @return [:yes, :no, nil] Flag to determine if the instance should be hourly billed.\n attribute :hourly\n validates :hourly, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Flag to determine if the instance should be private only.\n attribute :private\n validates :private, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Flag to determine if the instance should be deployed in dedicated space.\n attribute :dedicated\n validates :dedicated, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Flag to determine if local disk should be used for the new instance.\n attribute :local_disk\n validates :local_disk, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object] Count of cpus to be assigned to new virtual instance.\n attribute :cpus\n validates :cpus, presence: true\n\n # @return [Object] Amount of memory to be assigned to new virtual instance.\n attribute :memory\n validates :memory, presence: true\n\n # @return [Integer] List of disk sizes to be assigned to new virtual instance.\n attribute :disks\n validates :disks, presence: true, type: Integer\n\n # @return [Object, nil] OS Code to be used for new virtual instance.\n attribute :os_code\n\n # @return [Object, nil] Image Template to be used for new virtual instance.\n attribute :image_id\n\n # @return [Integer, nil] NIC Speed to be assigned to new virtual instance.\n attribute :nic_speed\n validates :nic_speed, type: Integer\n\n # @return [Object, nil] VLAN by its Id to be assigned to the public NIC.\n attribute :public_vlan\n\n # @return [Object, nil] VLAN by its Id to be assigned to the private NIC.\n attribute :private_vlan\n\n # @return [Object, nil] List of ssh keys by their Id to be assigned to a virtual instance.\n attribute :ssh_keys\n\n # @return [Object, nil] URL of a post provisioning script to be loaded and executed on virtual instance.\n attribute :post_uri\n\n # @return [:absent, :present, nil] Create, or cancel a virtual instance.,Specify C(present) for create, C(absent) to cancel.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Flag used to wait for active status before returning.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Time in seconds before wait returns.\n attribute :wait_time\n validates :wait_time, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7264623641967773, "alphanum_fraction": 0.7284655570983887, "avg_line_length": 98.83999633789062, "blob_id": "27980aba85bb445307a535d73021d1627e9c4aac", "content_id": "eedd260a5c6353c5a0a3e82ce8630e968ab86133", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 9984, "license_type": "permissive", "max_line_length": 631, "num_lines": 100, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_monitor_dns.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages DNS monitors on a BIG-IP.\n class Bigip_monitor_dns < Base\n # @return [String] Specifies the name of the monitor.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The parent template of this monitor template. Once this value has been set, it cannot be changed. By default, this value is the C(dns) parent on the C(Common) partition.\n attribute :parent\n validates :parent, type: String\n\n # @return [Object, nil] The description of the monitor.\n attribute :description\n\n # @return [Integer, nil] The interval specifying how frequently the monitor instance of this template will run.,This value B(must) be less than the C(timeout) value.,When creating a new monitor, if this parameter is not provided, the default C(5) will be used.\n attribute :interval\n validates :interval, type: Integer\n\n # @return [Integer, nil] Specifies the interval for the system to use to perform the health check when a resource is up.,When C(0), specifies that the system uses the interval specified in C(interval) to check the health of the resource.,When any other number, enables specification of a different interval to use when checking the health of a resource that is up.,When creating a new monitor, if this parameter is not provided, the default C(0) will be used.\n attribute :up_interval\n validates :up_interval, type: Integer\n\n # @return [Object, nil] The number of seconds in which the node or service must respond to the monitor request.,If the target responds within the set time period, it is considered up.,If the target does not respond within the set time period, it is considered down.,You can change this number to any number you want, however, it should be 3 times the interval number of seconds plus 1 second.,If this parameter is not provided when creating a new monitor, then the default value will be C(16).\n attribute :timeout\n\n # @return [Symbol, nil] Specifies whether the monitor operates in transparent mode.,Monitors in transparent mode can monitor pool members through firewalls.,When creating a new monitor, if this parameter is not provided, then the default value will be C(no).\n attribute :transparent\n validates :transparent, type: Symbol\n\n # @return [Symbol, nil] Specifies whether the monitor operates in reverse mode.,When the monitor is in reverse mode, a successful receive string match marks the monitored object down instead of up. You can use the this mode only if you configure the C(receive) option.,This parameter is not compatible with the C(time_until_up) parameter. If C(time_until_up) is specified, it must be C(0). Or, if it already exists, it must be C(0).\n attribute :reverse\n validates :reverse, type: Symbol\n\n # @return [Object, nil] Specifies the IP address that the monitor uses from the resource record sections of the DNS response.,The IP address should be specified in the dotted-decimal notation or IPv6 notation.\n attribute :receive\n\n # @return [Object, nil] Specifies the amount of time in seconds after the first successful response before a node will be marked up.,A value of 0 will cause a node to be marked up immediately after a valid response is received from the node.,If this parameter is not provided when creating a new monitor, then the default value will be C(0).\n attribute :time_until_up\n\n # @return [Symbol, nil] Specifies whether the system automatically changes the status of a resource to B(enabled) at the next successful monitor check.,If you set this option to C(yes), you must manually re-enable the resource before the system can use it for load balancing connections.,When creating a new monitor, if this parameter is not specified, the default value is C(no).,When C(yes), specifies that you must manually re-enable the resource after an unsuccessful monitor check.,When C(no), specifies that the system automatically changes the status of a resource to B(enabled) at the next successful monitor check.\n attribute :manual_resume\n validates :manual_resume, type: Symbol\n\n # @return [Object, nil] IP address part of the IP/port definition.,If this parameter is not provided when creating a new monitor, then the default value will be C(*).\n attribute :ip\n\n # @return [Object, nil] Port address part of the IP/port definition.,If this parameter is not provided when creating a new monitor, then the default value will be C(*).,Note that if specifying an IP address, a value between 1 and 65535 must be specified.\n attribute :port\n\n # @return [String, nil] Specifies a query name for the monitor to use in a DNS query.\n attribute :query_name\n validates :query_name, type: String\n\n # @return [:a, :aaaa, nil] Specifies the type of DNS query that the monitor sends.,When creating a new monitor, if this parameter is not specified, the default value is C(a).,When C(a), specifies that the monitor will send a DNS query of type A.,When C(aaaa), specifies that the monitor will send a DNS query of type AAAA.\n attribute :query_type\n validates :query_type, expression_inclusion: {:in=>[:a, :aaaa], :message=>\"%{value} needs to be :a, :aaaa\"}, allow_nil: true\n\n # @return [:\"any-type\", :anything, :\"query-type\", nil] Specifies the type of DNS query that the monitor sends.,When creating a new monitor, if this value is not specified, the default value is C(query-type).,When C(query-type), specifies that the response should contain at least one answer of which the resource record type matches the query type.,When C(any-type), specifies that the DNS message should contain at least one answer.,When C(anything), specifies that an empty answer is enough to mark the status of the node up.\n attribute :answer_section_contains\n validates :answer_section_contains, expression_inclusion: {:in=>[:\"any-type\", :anything, :\"query-type\"], :message=>\"%{value} needs to be :\\\"any-type\\\", :anything, :\\\"query-type\\\"\"}, allow_nil: true\n\n # @return [:\"no-error\", :anything, nil] Specifies the RCODE required in the response for an up status.,When creating a new monitor, if this parameter is not specified, the default value is C(no-error).,When C(no-error), specifies that the status of the node will be marked up if the received DNS message has no error.,When C(anything), specifies that the status of the node will be marked up irrespective of the RCODE in the DNS message received.,If this parameter is set to C(anything), it will disregard the C(receive) string, and nullify it if the monitor is being updated.\n attribute :accept_rcode\n validates :accept_rcode, expression_inclusion: {:in=>[:\"no-error\", :anything], :message=>\"%{value} needs to be :\\\"no-error\\\", :anything\"}, allow_nil: true\n\n # @return [Symbol, nil] Specifies whether adaptive response time monitoring is enabled for this monitor.,When C(yes), the monitor determines the state of a service based on how divergent from the mean latency a monitor probe for that service is allowed to be. Also, values for the C(allowed_divergence), C(adaptive_limit), and and C(sampling_timespan) will be enforced.,When C(disabled), the monitor determines the state of a service based on the C(interval), C(up_interval), C(time_until_up), and C(timeout) monitor settings.\n attribute :adaptive\n validates :adaptive, type: Symbol\n\n # @return [:relative, :absolute, nil] When specifying a new monitor, if C(adaptive) is C(yes), the default is C(relative),When C(absolute), the number of milliseconds the latency of a monitor probe can exceed the mean latency of a monitor probe for the service being probed. In typical cases, if the monitor detects three probes in a row that miss the latency value you set, the pool member or node is marked down.,When C(relative), the percentage of deviation the latency of a monitor probe can exceed the mean latency of a monitor probe for the service being probed.\n attribute :allowed_divergence_type\n validates :allowed_divergence_type, expression_inclusion: {:in=>[:relative, :absolute], :message=>\"%{value} needs to be :relative, :absolute\"}, allow_nil: true\n\n # @return [Object, nil] When specifying a new monitor, if C(adaptive) is C(yes), and C(type) is C(relative), the default is C(25) percent.\n attribute :allowed_divergence_value\n\n # @return [Object, nil] Specifies the absolute number of milliseconds that may not be exceeded by a monitor probe, regardless of C(allowed_divergence) setting, for a probe to be considered successful.,This value applies regardless of the value of the C(allowed_divergence) setting.,While this value can be configured when C(adaptive) is C(no), it will not take effect on the system until C(adaptive) is C(yes).\n attribute :adaptive_limit\n\n # @return [Object, nil] Specifies the length, in seconds, of the probe history window that the system uses to calculate the mean latency and standard deviation of a monitor probe.,While this value can be configured when C(adaptive) is C(no), it will not take effect on the system until C(adaptive) is C(yes).\n attribute :sampling_timespan\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [:present, :absent, nil] When C(present), ensures that the monitor exists.,When C(absent), ensures the monitor is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6927043199539185, "alphanum_fraction": 0.7027584314346313, "avg_line_length": 64.74576568603516, "blob_id": "705a4d5ace719f6b63fcef6f2ca7190587d3eb5b", "content_id": "976bc1c358ced4797a2a9bea6776b8158a941138", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3879, "license_type": "permissive", "max_line_length": 380, "num_lines": 59, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_sql_instance.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Represents a Cloud SQL instance. Cloud SQL instances are SQL databases hosted in Google's cloud. The Instances resource provides methods for common configuration and management tasks.\n class Gcp_sql_instance < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:FIRST_GEN, :SECOND_GEN, :EXTERNAL, nil] * FIRST_GEN: First Generation instance. MySQL only.,* SECOND_GEN: Second Generation instance or PostgreSQL instance.,* EXTERNAL: A database server that is not managed by Google.\n attribute :backend_type\n validates :backend_type, expression_inclusion: {:in=>[:FIRST_GEN, :SECOND_GEN, :EXTERNAL], :message=>\"%{value} needs to be :FIRST_GEN, :SECOND_GEN, :EXTERNAL\"}, allow_nil: true\n\n # @return [Object, nil] Connection name of the Cloud SQL instance used in connection strings.\n attribute :connection_name\n\n # @return [:MYSQL_5_5, :MYSQL_5_6, :MYSQL_5_7, :POSTGRES_9_6, nil] The database engine type and version. For First Generation instances, can be MYSQL_5_5, or MYSQL_5_6. For Second Generation instances, can be MYSQL_5_6 or MYSQL_5_7. Defaults to MYSQL_5_6.,PostgreSQL instances: POSTGRES_9_6 The databaseVersion property can not be changed after instance creation.\n attribute :database_version\n validates :database_version, expression_inclusion: {:in=>[:MYSQL_5_5, :MYSQL_5_6, :MYSQL_5_7, :POSTGRES_9_6], :message=>\"%{value} needs to be :MYSQL_5_5, :MYSQL_5_6, :MYSQL_5_7, :POSTGRES_9_6\"}, allow_nil: true\n\n # @return [Object, nil] The name and status of the failover replica. This property is applicable only to Second Generation instances.\n attribute :failover_replica\n\n # @return [:CLOUD_SQL_INSTANCE, :ON_PREMISES_INSTANCE, :READ_REPLICA_INSTANCE, nil] The instance type. This can be one of the following.,* CLOUD_SQL_INSTANCE: A Cloud SQL instance that is not replicating from a master.,* ON_PREMISES_INSTANCE: An instance running on the customer's premises.,* READ_REPLICA_INSTANCE: A Cloud SQL instance configured as a read-replica.\n attribute :instance_type\n validates :instance_type, expression_inclusion: {:in=>[:CLOUD_SQL_INSTANCE, :ON_PREMISES_INSTANCE, :READ_REPLICA_INSTANCE], :message=>\"%{value} needs to be :CLOUD_SQL_INSTANCE, :ON_PREMISES_INSTANCE, :READ_REPLICA_INSTANCE\"}, allow_nil: true\n\n # @return [Object, nil] The IPv6 address assigned to the instance. This property is applicable only to First Generation instances.\n attribute :ipv6_address\n\n # @return [Object, nil] The name of the instance which will act as master in the replication setup.\n attribute :master_instance_name\n\n # @return [Object, nil] The maximum disk size of the instance in bytes.\n attribute :max_disk_size\n\n # @return [String] Name of the Cloud SQL instance. This does not include the project ID.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The geographical region. Defaults to us-central or us-central1 depending on the instance type (First Generation or Second Generation/PostgreSQL).\n attribute :region\n validates :region, type: String\n\n # @return [Object, nil] Configuration specific to failover replicas and read replicas.\n attribute :replica_configuration\n\n # @return [Hash, nil] The user settings.\n attribute :settings\n validates :settings, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6756756901741028, "alphanum_fraction": 0.6774193644523621, "avg_line_length": 38.55172348022461, "blob_id": "1ef6c77fa633668adce883432e2f163d57609048", "content_id": "3eb8014c1af280c3fdae97c508a865a1f8d123bd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1147, "license_type": "permissive", "max_line_length": 142, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/rds_subnet_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates, modifies, and deletes RDS database subnet groups. This module has a dependency on python-boto >= 2.5.\n class Rds_subnet_group < Base\n # @return [:present, :absent] Specifies whether the subnet should be present or absent.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String] Database subnet group identifier.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Database subnet group description. Only set when a new group is added.\n attribute :description\n validates :description, type: String\n\n # @return [Array<String>, String, nil] List of subnet IDs that make up the database subnet group.\n attribute :subnets\n validates :subnets, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.647082507610321, "alphanum_fraction": 0.6519114971160889, "avg_line_length": 38.44444274902344, "blob_id": "7881f455a6f344eb42d41ecda96ab77727b96169", "content_id": "257ab9990ac14e2b879626e87cb539a1047b9998", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2485, "license_type": "permissive", "max_line_length": 147, "num_lines": 63, "path": "/lib/ansible/ruby/modules/generated/crypto/openssl_pkcs12.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows one to (re-)generate PKCS#12.\n class Openssl_pkcs12 < Base\n # @return [:parse, :export, nil] C(export) or C(parse) a PKCS#12.\n attribute :action\n validates :action, expression_inclusion: {:in=>[:parse, :export], :message=>\"%{value} needs to be :parse, :export\"}, allow_nil: true\n\n # @return [String, nil] List of CA certificate to include.\n attribute :ca_certificates\n validates :ca_certificates, type: String\n\n # @return [String, nil] The path to read certificates and private keys from. Must be in PEM format.\n attribute :certificate_path\n validates :certificate_path, type: String\n\n # @return [Symbol, nil] Should the file be regenerated even if it already exists.\n attribute :force\n validates :force, type: Symbol\n\n # @return [String, nil] Specifies the friendly name for the certificate and private key.\n attribute :friendly_name\n validates :friendly_name, type: String\n\n # @return [Integer, nil] Number of times to repeat the encryption step.\n attribute :iter_size\n validates :iter_size, type: Integer\n\n # @return [Integer, nil] Number of times to repeat the MAC step.\n attribute :maciter_size\n validates :maciter_size, type: Integer\n\n # @return [Object, nil] The PKCS#12 password.\n attribute :passphrase\n\n # @return [String] Filename to write the PKCS#12 file to.\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [Object, nil] Passphrase source to decrypt any input private keys with.\n attribute :privatekey_passphrase\n\n # @return [String, nil] File to read private key from.\n attribute :privatekey_path\n validates :privatekey_path, type: String\n\n # @return [:present, :absent, nil] Whether the file should exist or not. All parameters except C(path) are ignored when state is C(absent).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] PKCS#12 file path to parse.\n attribute :src\n validates :src, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6748296618461609, "alphanum_fraction": 0.6767461895942688, "avg_line_length": 48.95744705200195, "blob_id": "e1e710211d3300227cfc0ba63cba0aab8e7123ae", "content_id": "b3140a07d8a2bc026be3fa592ec74b79345f93d8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4696, "license_type": "permissive", "max_line_length": 413, "num_lines": 94, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_ami.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Registers or deregisters ec2 images.\n class Ec2_ami < Base\n # @return [String, nil] Instance ID to create the AMI from.\n attribute :instance_id\n validates :instance_id, type: String\n\n # @return [String, nil] The name of the new AMI.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] The target architecture of the image to register\n attribute :architecture\n validates :architecture, type: String\n\n # @return [Object, nil] The target kernel id of the image to register.\n attribute :kernel_id\n\n # @return [String, nil] The virtualization type of the image to register.\n attribute :virtualization_type\n validates :virtualization_type, type: String\n\n # @return [String, nil] The root device name of the image to register.\n attribute :root_device_name\n validates :root_device_name, type: String\n\n # @return [:yes, :no, nil] Wait for the AMI to be in state 'available' before returning.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] How long before wait gives up, in seconds.\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [:absent, :present, nil] Register or deregister an AMI.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [Object, nil] Human-readable string describing the contents and purpose of the AMI.\n attribute :description\n\n # @return [Symbol, nil] Flag indicating that the bundling process should not attempt to shutdown the instance before bundling. If this flag is True, the responsibility of maintaining file system integrity is left to the owner of the instance.\n attribute :no_reboot\n validates :no_reboot, type: Symbol\n\n # @return [String, nil] Image ID to be deregistered.\n attribute :image_id\n validates :image_id, type: String\n\n # @return [Array<Hash>, Hash, nil] List of device hashes/dictionaries with custom configurations (same block-device-mapping parameters).,Valid properties include: device_name, volume_type, size/volume_size (in GB), delete_on_termination (boolean), no_device (boolean), snapshot_id, iops (for io1 volume_type), encrypted\\r\\n\n attribute :device_mapping\n validates :device_mapping, type: TypeGeneric.new(Hash)\n\n # @return [:yes, :no, nil] Delete snapshots when deregistering the AMI.\n attribute :delete_snapshot\n validates :delete_snapshot, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Hash, nil] A dictionary of tags to add to the new image; '{\"key\":\"value\"}' and '{\"key\":\"value\",\"key\":\"value\"}'\n attribute :tags\n validates :tags, type: Hash\n\n # @return [String, nil] Whether to remove existing tags that aren't passed in the C(tags) parameter\n attribute :purge_tags\n validates :purge_tags, type: String\n\n # @return [Hash, nil] Users and groups that should be able to launch the AMI. Expects dictionary with a key of user_ids and/or group_names. user_ids should be a list of account ids. group_name should be a list of groups, \"all\" is the only acceptable value currently.,You must pass all desired launch permissions if you wish to modify existing launch permissions (passing just groups will remove all users)\n attribute :launch_permissions\n validates :launch_permissions, type: Hash\n\n # @return [Object, nil] The s3 location of an image to use for the AMI.\n attribute :image_location\n\n # @return [Object, nil] A boolean representing whether enhanced networking with ENA is enabled or not.\n attribute :enhanced_networking\n\n # @return [Object, nil] A list of valid billing codes. To be used with valid accounts by aws marketplace vendors.\n attribute :billing_products\n\n # @return [Object, nil] The ID of the RAM disk.\n attribute :ramdisk_id\n\n # @return [Object, nil] Set to simple to enable enhanced networking with the Intel 82599 Virtual Function interface for the AMI and any instances that you launch from the AMI.\n attribute :sriov_net_support\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6654571890830994, "alphanum_fraction": 0.6654571890830994, "avg_line_length": 37.27777862548828, "blob_id": "19d7b42903825331b7f29682dd182ae1b847692a", "content_id": "994518677807bf97e15fc4a4079a2dbb62f3012e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1378, "license_type": "permissive", "max_line_length": 159, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/network/vyos/vyos_static_route.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of static IP routes on Vyatta VyOS network devices.\n class Vyos_static_route < Base\n # @return [String, nil] Network prefix of the static route. C(mask) param should be ignored if C(prefix) is provided with C(mask) value C(prefix/mask).\n attribute :prefix\n validates :prefix, type: String\n\n # @return [Integer, nil] Network prefix mask of the static route.\n attribute :mask\n validates :mask, type: Integer\n\n # @return [String, nil] Next hop IP of the static route.\n attribute :next_hop\n validates :next_hop, type: String\n\n # @return [Object, nil] Admin distance of the static route.\n attribute :admin_distance\n\n # @return [Array<Hash>, Hash, nil] List of static route definitions\n attribute :aggregate\n validates :aggregate, type: TypeGeneric.new(Hash)\n\n # @return [:present, :absent, nil] State of the static route configuration.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6673097014427185, "alphanum_fraction": 0.6687127351760864, "avg_line_length": 53.30476379394531, "blob_id": "1139de5494681499b884d54b8f78e968c1da8798", "content_id": "e20533428827f0496cbf156e17b419251cc16e16", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5702, "license_type": "permissive", "max_line_length": 288, "num_lines": 105, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/elb_classic_lb.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Returns information about the load balancer.\n # Will be marked changed when called only if state is changed.\n class Elb_classic_lb < Base\n # @return [:present, :absent] Create or destroy the ELB\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String] The name of the ELB\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Array<Hash>, Hash, nil] List of ports/protocols for this ELB to listen on (see example)\n attribute :listeners\n validates :listeners, type: TypeGeneric.new(Hash)\n\n # @return [:yes, :no, nil] Purge existing listeners on ELB that are not found in listeners\n attribute :purge_listeners\n validates :purge_listeners, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] List of instance ids to attach to this ELB\n attribute :instance_ids\n validates :instance_ids, type: TypeGeneric.new(String)\n\n # @return [:yes, :no, nil] Purge existing instance ids on ELB that are not found in instance_ids\n attribute :purge_instance_ids\n validates :purge_instance_ids, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] List of availability zones to enable on this ELB\n attribute :zones\n validates :zones, type: TypeGeneric.new(String)\n\n # @return [:yes, :no, nil] Purge existing availability zones on ELB that are not found in zones\n attribute :purge_zones\n validates :purge_zones, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] A list of security groups to apply to the elb\n attribute :security_group_ids\n validates :security_group_ids, type: TypeGeneric.new(String)\n\n # @return [Object, nil] A list of security group names to apply to the elb\n attribute :security_group_names\n\n # @return [Hash, nil] An associative array of health check configuration settings (see example)\n attribute :health_check\n validates :health_check, type: Hash\n\n # @return [Hash, nil] An associative array of access logs configuration settings (see example)\n attribute :access_logs\n validates :access_logs, type: Hash\n\n # @return [Array<String>, String, nil] A list of VPC subnets to use when creating ELB. Zones should be empty if using this.\n attribute :subnets\n validates :subnets, type: TypeGeneric.new(String)\n\n # @return [:yes, :no, nil] Purge existing subnet on ELB that are not found in subnets\n attribute :purge_subnets\n validates :purge_subnets, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:internal, :\"internet-facing\", nil] The scheme to use when creating the ELB. For a private VPC-visible ELB use 'internal'. If you choose to update your scheme with a different value the ELB will be destroyed and recreated. To update scheme you must use the option wait.\n attribute :scheme\n validates :scheme, expression_inclusion: {:in=>[:internal, :\"internet-facing\"], :message=>\"%{value} needs to be :internal, :\\\"internet-facing\\\"\"}, allow_nil: true\n\n # @return [:yes, :no, nil] When set to C(no), SSL certificates will not be validated for boto versions >= 2.6.0.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Wait a specified timeout allowing connections to drain before terminating an instance\n attribute :connection_draining_timeout\n validates :connection_draining_timeout, type: Integer\n\n # @return [Integer, nil] ELB connections from clients and to servers are timed out after this amount of time\n attribute :idle_timeout\n validates :idle_timeout, type: Integer\n\n # @return [:yes, :no, nil] Distribute load across all configured Availability Zones\n attribute :cross_az_load_balancing\n validates :cross_az_load_balancing, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Hash, nil] An associative array of stickiness policy settings. Policy will be applied to all listeners ( see example )\n attribute :stickiness\n validates :stickiness, type: Hash\n\n # @return [:yes, :no, nil] When specified, Ansible will check the status of the load balancer to ensure it has been successfully removed from AWS.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Used in conjunction with wait. Number of seconds to wait for the elb to be terminated. A maximum of 600 seconds (10 minutes) is allowed.\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [Hash, nil] An associative array of tags. To delete all tags, supply an empty dict.\n attribute :tags\n validates :tags, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6529351472854614, "alphanum_fraction": 0.6622039079666138, "avg_line_length": 41.838233947753906, "blob_id": "4fbb50f5c9624c7674d7d3710c0088479a6066f4", "content_id": "c679608039b0a15cb00047ab89a072130b85c63b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2913, "license_type": "permissive", "max_line_length": 143, "num_lines": 68, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_vpn_customer_gateway.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and remove VPN customer gateways.\n class Cs_vpn_customer_gateway < Base\n # @return [String] Name of the gateway.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Array<String>, String, nil] List of guest CIDRs behind the gateway.,Required if C(state=present).\n attribute :cidrs\n validates :cidrs, type: TypeGeneric.new(String)\n\n # @return [String, nil] Public IP address of the gateway.,Required if C(state=present).\n attribute :gateway\n validates :gateway, type: String\n\n # @return [String, nil] ESP policy in the format e.g. C(aes256-sha1;modp1536).,Required if C(state=present).\n attribute :esp_policy\n validates :esp_policy, type: String\n\n # @return [String, nil] IKE policy in the format e.g. C(aes256-sha1;modp1536).,Required if C(state=present).\n attribute :ike_policy\n validates :ike_policy, type: String\n\n # @return [String, nil] IPsec Preshared-Key.,Cannot contain newline or double quotes.,Required if C(state=present).\n attribute :ipsec_psk\n validates :ipsec_psk, type: String\n\n # @return [Object, nil] Lifetime in seconds of phase 1 VPN connection.,Defaulted to 86400 by the API on creation if not set.\n attribute :ike_lifetime\n\n # @return [Object, nil] Lifetime in seconds of phase 2 VPN connection.,Defaulted to 3600 by the API on creation if not set.\n attribute :esp_lifetime\n\n # @return [Symbol, nil] Enable Dead Peer Detection.,Disabled per default by the API on creation if not set.\n attribute :dpd\n validates :dpd, type: Symbol\n\n # @return [Symbol, nil] Force encapsulation for NAT traversal.,Disabled per default by the API on creation if not set.\n attribute :force_encap\n validates :force_encap, type: Symbol\n\n # @return [:present, :absent, nil] State of the VPN customer gateway.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Domain the VPN customer gateway is related to.\n attribute :domain\n\n # @return [Object, nil] Account the VPN customer gateway is related to.\n attribute :account\n\n # @return [Object, nil] Name of the project the VPN gateway is related to.\n attribute :project\n\n # @return [Boolean, nil] Poll async jobs until job has finished.\n attribute :poll_async\n validates :poll_async, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7006173133850098, "alphanum_fraction": 0.7006173133850098, "avg_line_length": 45.28571319580078, "blob_id": "81318565ea65187d4a29c931052cd19083b10bf7", "content_id": "b6ec68a9e6845f785c053d953af8138cb05928b2", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 972, "license_type": "permissive", "max_line_length": 261, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_elementsw_node.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add, remove cluster node on Element Software Cluster.\n class Na_elementsw_node < Base\n # @return [:present, :absent, nil] Element Software Storage Node operation state.,present - To add pending node to participate in cluster data storage.,absent - To remove node from active cluster. A node cannot be removed if active drives are present.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, Integer] List of IDs or Names or IP Address of nodes from cluster used for operation.\n attribute :node_id\n validates :node_id, presence: true, type: MultipleTypes.new(String, Integer)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6523192524909973, "alphanum_fraction": 0.6523192524909973, "avg_line_length": 41.73214340209961, "blob_id": "65853ba9356b93af44014d01e79e904be828b030", "content_id": "4ab8eff79e64f273ca3a65fe2d59be3d2bd4988b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2393, "license_type": "permissive", "max_line_length": 187, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/remote_management/cobbler/cobbler_system.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add, modify or remove systems in Cobbler\n class Cobbler_system < Base\n # @return [String, nil] The name or IP address of the Cobbler system.\n attribute :host\n validates :host, type: String\n\n # @return [Object, nil] Port number to be used for REST connection.,The default value depends on parameter C(use_ssl).\n attribute :port\n\n # @return [String, nil] The username to log in to Cobbler.\n attribute :username\n validates :username, type: String\n\n # @return [String] The password to log in to Cobbler.\n attribute :password\n validates :password, presence: true, type: String\n\n # @return [:yes, :no, nil] If C(no), an HTTP connection will be used instead of the default HTTPS connection.\n attribute :use_ssl\n validates :use_ssl, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated.,This should only set to C(no) when used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] The system name to manage.\n attribute :name\n validates :name, type: String\n\n # @return [Hash, nil] A dictionary with system properties.\n attribute :properties\n validates :properties, type: Hash\n\n # @return [Hash, nil] A list of dictionaries containing interface options.\n attribute :interfaces\n validates :interfaces, type: Hash\n\n # @return [Symbol, nil] Sync on changes.,Concurrently syncing Cobbler is bound to fail.\n attribute :sync\n validates :sync, type: Symbol\n\n # @return [:absent, :present, :query, nil] Whether the system should be present, absent or a query is made.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6660818457603455, "alphanum_fraction": 0.6660818457603455, "avg_line_length": 38.76744079589844, "blob_id": "d462a819be6cd06bb82f581c27a2259d62ace280", "content_id": "33957a4f91f00396ab1c211a6003af380aa77de9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1710, "license_type": "permissive", "max_line_length": 190, "num_lines": 43, "path": "/lib/ansible/ruby/modules/generated/network/panos/panos_sag.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create a static address group object in the firewall used for policy rules.\n class Panos_sag < Base\n # @return [Object, nil] API key that can be used instead of I(username)/I(password) credentials.\n attribute :api_key\n\n # @return [String] name of the dynamic address group\n attribute :sag_name\n validates :sag_name, presence: true, type: String\n\n # @return [Object] Static filter user by the address group\n attribute :static_match_filter\n validates :static_match_filter, presence: true\n\n # @return [Object, nil] - The name of the Panorama device group. The group must exist on Panorama. If device group is not defined it is assumed that we are contacting a firewall.\\r\\n\n attribute :devicegroup\n\n # @return [String, nil] The purpose / objective of the static Address Group\n attribute :description\n validates :description, type: String\n\n # @return [Array<String>, String, nil] Tags to be associated with the address group\n attribute :tags\n validates :tags, type: TypeGeneric.new(String)\n\n # @return [:yes, :no, nil] commit if changed\n attribute :commit\n validates :commit, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object] The operation to perform Supported values are I(add)/I(list)/I(delete).\n attribute :operation\n validates :operation, presence: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6897282004356384, "alphanum_fraction": 0.690787136554718, "avg_line_length": 46.21666717529297, "blob_id": "1d2d51e7408997fc0d9fe8b78f8bcc326958cd61", "content_id": "3aca87b8a070c592b32b0511a38534070dcf5ec3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2833, "license_type": "permissive", "max_line_length": 194, "num_lines": 60, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_keyvault.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and delete instance of Key Vault.\n class Azure_rm_keyvault < Base\n # @return [String] The name of the Resource Group to which the server belongs.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] Name of the vault\n attribute :vault_name\n validates :vault_name, presence: true, type: String\n\n # @return [Object, nil] Resource location. If not set, location from the resource group will be used as default.\n attribute :location\n\n # @return [String, nil] The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault.\n attribute :vault_tenant\n validates :vault_tenant, type: String\n\n # @return [Hash, nil] SKU details\n attribute :sku\n validates :sku, type: Hash\n\n # @return [Array<Hash>, Hash, nil] An array of 0 to 16 identities that have access to the key vault. All identities in the array must use the same tenant ID as the key vault's tenant ID.\n attribute :access_policies\n validates :access_policies, type: TypeGeneric.new(Hash)\n\n # @return [Symbol, nil] Property to specify whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key vault.\n attribute :enabled_for_deployment\n validates :enabled_for_deployment, type: Symbol\n\n # @return [Symbol, nil] Property to specify whether Azure Disk Encryption is permitted to retrieve secrets from the vault and unwrap keys.\n attribute :enabled_for_disk_encryption\n validates :enabled_for_disk_encryption, type: Symbol\n\n # @return [Symbol, nil] Property to specify whether Azure Resource Manager is permitted to retrieve secrets from the key vault.\n attribute :enabled_for_template_deployment\n validates :enabled_for_template_deployment, type: Symbol\n\n # @return [Symbol, nil] Property to specify whether the soft delete functionality is enabled for this key vault.\n attribute :enable_soft_delete\n validates :enable_soft_delete, type: Symbol\n\n # @return [Symbol, nil] Create vault in recovery mode.\n attribute :recover_mode\n validates :recover_mode, type: Symbol\n\n # @return [:absent, :present, nil] Assert the state of the KeyVault. Use 'present' to create or update an KeyVault and 'absent' to delete it.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.7162426710128784, "avg_line_length": 29.058822631835938, "blob_id": "96579c463bbd29d588e1ce32f6d53d7e903db644", "content_id": "8066701901d84bfc3bc05d067ce94ecbdb66fe73", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 511, "license_type": "permissive", "max_line_length": 123, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_tag_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to collect facts about VMware tags.\n # Tag feature is introduced in vSphere 6 version, so this module is not supported in the earlier versions of vSphere.\n # All variables and VMware object names are case sensitive.\n class Vmware_tag_facts < Base\n\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6314868927001953, "alphanum_fraction": 0.6314868927001953, "avg_line_length": 37.11111068725586, "blob_id": "d7df49c3e4051fc4146e6016f7dc632d03f1de2a", "content_id": "7035b18e33441d8918cf636791fcc7dba90b36d8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1715, "license_type": "permissive", "max_line_length": 143, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/ansible_tower/tower_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, or destroy Ansible Tower users. See U(https://www.ansible.com/tower) for an overview.\n class Tower_user < Base\n # @return [String] The username of the user.\n attribute :username\n validates :username, presence: true, type: String\n\n # @return [String, nil] First name of the user.\n attribute :first_name\n validates :first_name, type: String\n\n # @return [String, nil] Last name of the user.\n attribute :last_name\n validates :last_name, type: String\n\n # @return [String] Email address of the user.\n attribute :email\n validates :email, presence: true, type: String\n\n # @return [String, nil] Password of the user.\n attribute :password\n validates :password, type: String\n\n # @return [:yes, :no, nil] User is a system wide administator.\n attribute :superuser\n validates :superuser, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] User is a system wide auditor.\n attribute :auditor\n validates :auditor, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6672994494438171, "alphanum_fraction": 0.6672994494438171, "avg_line_length": 43.82978820800781, "blob_id": "67fe84c2cf2fb78aef96ac139b565dd4de64878b", "content_id": "05d128fddf23d4e00bbf14b94bd904d63b1cacf9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2107, "license_type": "permissive", "max_line_length": 165, "num_lines": 47, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_loadbalancer.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or Remove load balancer from the OpenStack load-balancer service.\n class Os_loadbalancer < Base\n # @return [String] Name that has to be given to the load balancer\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Should the resource be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] The name or id of the network for the virtual IP of the load balancer. One of vip_network, vip_subnet, or vip_port must be specified.\n attribute :vip_network\n validates :vip_network, type: String\n\n # @return [String, nil] The name or id of the subnet for the virtual IP of the load balancer. One of vip_network, vip_subnet, or vip_port must be specified.\n attribute :vip_subnet\n validates :vip_subnet, type: String\n\n # @return [Object, nil] The name or id of the load balancer virtual IP port. One of vip_network, vip_subnet, or vip_port must be specified.\n attribute :vip_port\n\n # @return [String, nil] IP address of the load balancer virtual IP.\n attribute :vip_address\n validates :vip_address, type: String\n\n # @return [:yes, :no, nil] If the module should wait for the load balancer to be created.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] The amount of time the module should wait for the load balancer to get into ACTIVE state.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6587591171264648, "alphanum_fraction": 0.6660584211349487, "avg_line_length": 43.43243408203125, "blob_id": "cf8a9e60fe1958af992dece8f23bce1ff8dff0f7", "content_id": "450e77bb9dd3440a79ed99007a45327ef35c44c3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1644, "license_type": "permissive", "max_line_length": 152, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/network/illumos/dladm_iptun.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage IP tunnel interfaces on Solaris/illumos systems.\n class Dladm_iptun < Base\n # @return [String] IP tunnel interface name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Boolean, nil] Specifies that the IP tunnel interface is temporary. Temporary IP tunnel interfaces do not persist across reboots.\n attribute :temporary\n validates :temporary, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:ipv4, :ipv6, :\"6to4\", nil] Specifies the type of tunnel to be created.\n attribute :type\n validates :type, expression_inclusion: {:in=>[:ipv4, :ipv6, :\"6to4\"], :message=>\"%{value} needs to be :ipv4, :ipv6, :\\\"6to4\\\"\"}, allow_nil: true\n\n # @return [String, nil] Literat IP address or hostname corresponding to the tunnel source.\n attribute :local_address\n validates :local_address, type: String\n\n # @return [String, nil] Literal IP address or hostname corresponding to the tunnel destination.\n attribute :remote_address\n validates :remote_address, type: String\n\n # @return [:present, :absent, nil] Create or delete Solaris/illumos VNIC.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7209302186965942, "alphanum_fraction": 0.7209302186965942, "avg_line_length": 13.333333015441895, "blob_id": "7d4435aaca747a4f1a13cff531ac738261917daf", "content_id": "9d186381bfe6f39ec0e12e7b024a5af2d56a4340", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 86, "license_type": "permissive", "max_line_length": 40, "num_lines": 6, "path": "/util/get_ansible.py", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport ansible\nimport os\n\nprint(os.path.dirname(ansible.__file__))\n" }, { "alpha_fraction": 0.689223051071167, "alphanum_fraction": 0.689223051071167, "avg_line_length": 40.27586364746094, "blob_id": "a431668af2649693f2f4ab6ad7174ccbf39dcd68", "content_id": "a81db03ee56cc0863b011562f14936719d3665d5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1197, "license_type": "permissive", "max_line_length": 166, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_config_recorder.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Module manages AWS Config configuration recorder settings\n class Aws_config_recorder < Base\n # @return [String] The name of the AWS Config resource.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Whether the Config rule should be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Amazon Resource Name (ARN) of the IAM role used to describe the AWS resources associated with the account.,Required when state=present\n attribute :role_arn\n validates :role_arn, type: String\n\n # @return [Hash, nil] Specifies the types of AWS resources for which AWS Config records configuration changes.,Required when state=present\n attribute :recording_group\n validates :recording_group, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6935975551605225, "alphanum_fraction": 0.707317054271698, "avg_line_length": 28.81818199157715, "blob_id": "4cd2f8dc377557878a3f50bffb27aa94fac8a713", "content_id": "bdfe4185e7f8cbdb08592e8fc188f90508b92edd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 656, "license_type": "permissive", "max_line_length": 139, "num_lines": 22, "path": "/lib/ansible/ruby/modules/custom/cloud/core/amazon/ec2.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# VALIDATED_CHECKSUM: 5sO9ygvKZkn0CIFQUXJiy8A7kic6cpw7YuuvnQFuNbE=\n\n# See LICENSE.txt for license\n\nrequire 'ansible/ruby/modules/generated/cloud/amazon/ec2'\n\nmodule Ansible\n module Ruby\n module Modules\n class Ec2\n remove_existing_validations :count_tag\n validates :count_tag, type: Hash\n remove_existing_validations :ebs_optimized\n validates :ebs_optimized, expression_inclusion: { in: [true, false], message: '%{value} needs to be true, false' }, allow_nil: true\n attribute :instance_profile_name\n validates :instance_profile_name, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6910319328308105, "alphanum_fraction": 0.6910319328308105, "avg_line_length": 48.33333206176758, "blob_id": "10da77fa722fe7806a8b39a5eeef26219b240f76", "content_id": "7d3c3b54c735d0b199d984c99b42da11a3c00fbb", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1628, "license_type": "permissive", "max_line_length": 335, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/windows/win_mapped_drive.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows you to modify mapped network drives for individual users.\n class Win_mapped_drive < Base\n # @return [String] The letter of the network path to map to.,This letter must not already be in use with Windows.\n attribute :letter\n validates :letter, presence: true, type: String\n\n # @return [String, nil] The password for C(username).\n attribute :password\n validates :password, type: String\n\n # @return [String, nil] The UNC path to map the drive to.,This is required if C(state=present).,If C(state=absent) and path is not set, the module will delete the mapped drive regardless of the target.,If C(state=absent) and the path is set, the module will throw an error if path does not match the target of the mapped drive.\n attribute :path\n validates :path, type: String\n\n # @return [:absent, :present, nil] If C(present) will ensure the mapped drive exists.,If C(absent) will ensure the mapped drive does not exist.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] Credentials to map the drive with.,The username MUST include the domain or servername like SERVER\\user, see the example for more information.\n attribute :username\n validates :username, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6737682819366455, "alphanum_fraction": 0.6737682819366455, "avg_line_length": 30.29166603088379, "blob_id": "24448bd576cfa2ef2c6970dbc0c1bfed094e5480", "content_id": "ca8444dc126e542565b75e24bf52ff9a99a84de9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 751, "license_type": "permissive", "max_line_length": 92, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_snapshot_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Retrieve facts about one or more oVirt/RHV virtual machine snapshots.\n class Ovirt_snapshot_facts < Base\n # @return [String] Name of the VM with snapshot.\n attribute :vm\n validates :vm, presence: true, type: String\n\n # @return [String, nil] Description of the snapshot, can be used as glob expression.\n attribute :description\n validates :description, type: String\n\n # @return [Object, nil] Id of the snapshot we want to retrieve facts about.\n attribute :snapshot_id\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6457810997962952, "alphanum_fraction": 0.6457810997962952, "avg_line_length": 47.85714340209961, "blob_id": "df69e05744b15553f3307192675ba460c9264f77", "content_id": "81a43870ef800547852e657c25c4beaa19ae17f1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2394, "license_type": "permissive", "max_line_length": 169, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/packaging/os/homebrew_cask.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages Homebrew casks.\n class Homebrew_cask < Base\n # @return [String] name of cask to install/remove\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] ':' separated list of paths to search for 'brew' executable.\n attribute :path\n validates :path, type: String\n\n # @return [:present, :absent, :upgraded, nil] state of the cask\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :upgraded], :message=>\"%{value} needs to be :present, :absent, :upgraded\"}, allow_nil: true\n\n # @return [:yes, :no, nil] update homebrew itself first. Note that C(brew cask update) is a synonym for C(brew update).\n attribute :update_homebrew\n validates :update_homebrew, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] options flags to install a package\n attribute :install_options\n validates :install_options, type: TypeGeneric.new(String)\n\n # @return [:yes, :no, nil] allow external apps\n attribute :accept_external_apps\n validates :accept_external_apps, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] upgrade all casks (mutually exclusive with `upgrade`)\n attribute :upgrade_all\n validates :upgrade_all, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] upgrade all casks (mutually exclusive with `upgrade_all`)\n attribute :upgrade\n validates :upgrade, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] upgrade casks that auto update; passes --greedy to brew cask outdated when checking if an installed cask has a newer version available\n attribute :greedy\n validates :greedy, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6599210500717163, "alphanum_fraction": 0.6648568511009216, "avg_line_length": 50.2911376953125, "blob_id": "9dd431e8ee9af3e95a7429a2bcbafff6b62420f1", "content_id": "dcea6477400c3c0e2dc65e5b99d273cc7c3ca43a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4052, "license_type": "permissive", "max_line_length": 219, "num_lines": 79, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_subnet.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or Remove a subnet to an OpenStack network\n class Os_subnet < Base\n # @return [:present, :absent, nil] Indicate desired state of the resource\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Name of the network to which the subnet should be attached,Required when I(state) is 'present'\n attribute :network_name\n validates :network_name, type: String\n\n # @return [String] The name of the subnet that should be created. Although Neutron allows for non-unique subnet names, this module enforces subnet name uniqueness.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The CIDR representation of the subnet that should be assigned to the subnet. Required when I(state) is 'present' and a subnetpool is not specified.\n attribute :cidr\n validates :cidr, type: String\n\n # @return [Integer, nil] The IP version of the subnet 4 or 6\n attribute :ip_version\n validates :ip_version, type: Integer\n\n # @return [:yes, :no, nil] Whether DHCP should be enabled for this subnet.\n attribute :enable_dhcp\n validates :enable_dhcp, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] The ip that would be assigned to the gateway for this subnet\n attribute :gateway_ip\n\n # @return [:yes, :no, nil] The gateway IP would not be assigned for this subnet\n attribute :no_gateway_ip\n validates :no_gateway_ip, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] List of DNS nameservers for this subnet.\n attribute :dns_nameservers\n validates :dns_nameservers, type: TypeGeneric.new(String)\n\n # @return [Object, nil] From the subnet pool the starting address from which the IP should be allocated.\n attribute :allocation_pool_start\n\n # @return [Object, nil] From the subnet pool the last IP that should be assigned to the virtual machines.\n attribute :allocation_pool_end\n\n # @return [Array<Hash>, Hash, nil] A list of host route dictionaries for the subnet.\n attribute :host_routes\n validates :host_routes, type: TypeGeneric.new(Hash)\n\n # @return [:\"dhcpv6-stateful\", :\"dhcpv6-stateless\", :slaac, nil] IPv6 router advertisement mode\n attribute :ipv6_ra_mode\n validates :ipv6_ra_mode, expression_inclusion: {:in=>[:\"dhcpv6-stateful\", :\"dhcpv6-stateless\", :slaac], :message=>\"%{value} needs to be :\\\"dhcpv6-stateful\\\", :\\\"dhcpv6-stateless\\\", :slaac\"}, allow_nil: true\n\n # @return [:\"dhcpv6-stateful\", :\"dhcpv6-stateless\", :slaac, nil] IPv6 address mode\n attribute :ipv6_address_mode\n validates :ipv6_address_mode, expression_inclusion: {:in=>[:\"dhcpv6-stateful\", :\"dhcpv6-stateless\", :slaac], :message=>\"%{value} needs to be :\\\"dhcpv6-stateful\\\", :\\\"dhcpv6-stateless\\\", :slaac\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Use the default subnetpool for I(ip_version) to obtain a CIDR.\n attribute :use_default_subnetpool\n validates :use_default_subnetpool, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Project name or ID containing the subnet (name admin-only)\n attribute :project\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n\n # @return [Object, nil] Dictionary with extra key/value pairs passed to the API\n attribute :extra_specs\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.4322853684425354, "alphanum_fraction": 0.45707374811172485, "avg_line_length": 19.936708450317383, "blob_id": "fa272b8de37b5031e944bbc19ede297ab4115189", "content_id": "4ab06f34d07b14a58d77fd049ed1c34d4c44e3b9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1654, "license_type": "permissive", "max_line_length": 70, "num_lines": 79, "path": "/lib/ansible/ruby/models/block_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# see LICENSE.txt in project root\nrequire 'spec_helper'\n\ndescribe Ansible::Ruby::Models::Block do\n before do\n stub_const('Ansible::Ruby::Modules::Ec2', module_klass)\n end\n\n let(:module_klass) do\n Class.new(Ansible::Ruby::Modules::Base) do\n attribute :foo\n validates :foo, presence: true\n end\n end\n\n let(:task1) do\n Ansible::Ruby::Models::Task.new name: 'do stuff on EC2',\n module: module_klass.new(foo: 123)\n end\n\n let(:task2) do\n Ansible::Ruby::Models::Task.new name: 'do more stuff on EC2',\n module: module_klass.new(foo: 456)\n end\n\n subject(:hash) { instance.to_h }\n\n context 'basic' do\n let(:instance) do\n Ansible::Ruby::Models::Block.new tasks: [task1, task2]\n end\n\n it do\n is_expected.to eq block: [\n {\n name: 'do stuff on EC2',\n ec2: {\n foo: 123\n }\n },\n {\n name: 'do more stuff on EC2',\n ec2: {\n foo: 456\n }\n }\n ]\n end\n end\n\n context 'vars' do\n let(:instance) do\n Ansible::Ruby::Models::Block.new tasks: [task1, task2],\n vars: { howdy: 123 }\n end\n\n it do\n is_expected.to eq block: [\n {\n name: 'do stuff on EC2',\n ec2: {\n foo: 123\n }\n },\n {\n name: 'do more stuff on EC2',\n ec2: {\n foo: 456\n }\n }\n ],\n vars: {\n howdy: 123\n }\n end\n end\nend\n" }, { "alpha_fraction": 0.6877058148384094, "alphanum_fraction": 0.6877058148384094, "avg_line_length": 42.380950927734375, "blob_id": "83b465e0a701e820160cb448b7f6380653b71a58", "content_id": "04dcd7af724adb7ac2616770bbbcd34c092db8c6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1822, "license_type": "permissive", "max_line_length": 129, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/network/panos/panos_cert_gen_ssh.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module generates a self-signed certificate that can be used by GlobalProtect client, SSL connector, or\n # otherwise. Root certificate must be preset on the system first. This module depends on paramiko for ssh.\n class Panos_cert_gen_ssh < Base\n # @return [String] IP address (or hostname) of PAN-OS device being configured.\n attribute :ip_address\n validates :ip_address, presence: true, type: String\n\n # @return [Object] Location of the filename that is used for the auth. Either I(key_filename) or I(password) is required.\n attribute :key_filename\n validates :key_filename, presence: true\n\n # @return [String] Password credentials to use for auth. Either I(key_filename) or I(password) is required.\n attribute :password\n validates :password, presence: true, type: String\n\n # @return [String] Human friendly certificate name (not CN but just a friendly name).\n attribute :cert_friendly_name\n validates :cert_friendly_name, presence: true, type: String\n\n # @return [String] Certificate CN (common name) embedded in the certificate signature.\n attribute :cert_cn\n validates :cert_cn, presence: true, type: String\n\n # @return [String] Undersigning authority (CA) that MUST already be presents on the device.\n attribute :signed_by\n validates :signed_by, presence: true, type: String\n\n # @return [String, nil] Number of bits used by the RSA algorithm for the certificate generation.\n attribute :rsa_nbits\n validates :rsa_nbits, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6395294070243835, "alphanum_fraction": 0.6498823761940002, "avg_line_length": 42.367347717285156, "blob_id": "616eb98722335ab409a6425e4a123155496009b8", "content_id": "0c2c74863f10363bdfce141bafca4aefedaf30e5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2125, "license_type": "permissive", "max_line_length": 153, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/net_tools/snmp_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Retrieve facts for a device using SNMP, the facts will be inserted to the ansible_facts key.\n class Snmp_facts < Base\n # @return [String] Set to target snmp server (normally {{inventory_hostname}})\n attribute :host\n validates :host, presence: true, type: String\n\n # @return [:v2, :v2c, :v3] SNMP Version to use, v2/v2c or v3\n attribute :version\n validates :version, presence: true, expression_inclusion: {:in=>[:v2, :v2c, :v3], :message=>\"%{value} needs to be :v2, :v2c, :v3\"}\n\n # @return [String, nil] The SNMP community string, required if version is v2/v2c\n attribute :community\n validates :community, type: String\n\n # @return [:authPriv, :authNoPriv, nil] Authentication level, required if version is v3\n attribute :level\n validates :level, expression_inclusion: {:in=>[:authPriv, :authNoPriv], :message=>\"%{value} needs to be :authPriv, :authNoPriv\"}, allow_nil: true\n\n # @return [String, nil] Username for SNMPv3, required if version is v3\n attribute :username\n validates :username, type: String\n\n # @return [:md5, :sha, nil] Hashing algorithm, required if version is v3\n attribute :integrity\n validates :integrity, expression_inclusion: {:in=>[:md5, :sha], :message=>\"%{value} needs to be :md5, :sha\"}, allow_nil: true\n\n # @return [String, nil] Authentication key, required if version is v3\n attribute :authkey\n validates :authkey, type: String\n\n # @return [:des, :aes, nil] Encryption algorithm, required if level is authPriv\n attribute :privacy\n validates :privacy, expression_inclusion: {:in=>[:des, :aes], :message=>\"%{value} needs to be :des, :aes\"}, allow_nil: true\n\n # @return [String, nil] Encryption key, required if version is authPriv\n attribute :privkey\n validates :privkey, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6573511362075806, "alphanum_fraction": 0.6646415591239929, "avg_line_length": 40.150001525878906, "blob_id": "577c9ce04f41c1276d7bed241b99f3b59dcdf59a", "content_id": "a3dc9288c302271e8b9fb34ae38b60b402b01588", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2469, "license_type": "permissive", "max_line_length": 143, "num_lines": 60, "path": "/lib/ansible/ruby/modules/generated/system/java_cert.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This is a wrapper module around keytool. Which can be used to import/remove certificates from a given java keystore.\n class Java_cert < Base\n # @return [String, nil] Basic URL to fetch SSL certificate from. One of cert_url or cert_path is required to load certificate.\n attribute :cert_url\n validates :cert_url, type: String\n\n # @return [Integer, nil] Port to connect to URL. This will be used to create server URL:PORT\n attribute :cert_port\n validates :cert_port, type: Integer\n\n # @return [Object, nil] Local path to load certificate from. One of cert_url or cert_path is required to load certificate.\n attribute :cert_path\n\n # @return [String, nil] Imported certificate alias.\n attribute :cert_alias\n validates :cert_alias, type: String\n\n # @return [String, nil] Local path to load PKCS12 keystore from.\n attribute :pkcs12_path\n validates :pkcs12_path, type: String\n\n # @return [String, nil] Password for importing from PKCS12 keystore.\n attribute :pkcs12_password\n validates :pkcs12_password, type: String\n\n # @return [Integer, nil] Alias in the PKCS12 keystore.\n attribute :pkcs12_alias\n validates :pkcs12_alias, type: Integer\n\n # @return [String, nil] Path to keystore.\n attribute :keystore_path\n validates :keystore_path, type: String\n\n # @return [String] Keystore password.\n attribute :keystore_pass\n validates :keystore_pass, presence: true, type: String\n\n # @return [Boolean, nil] Create keystore if it doesn't exist\n attribute :keystore_create\n validates :keystore_create, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] Path to keytool binary if not used we search in PATH for it.\n attribute :executable\n validates :executable, type: String\n\n # @return [:absent, :present, nil] Defines action which can be either certificate import or removal.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6994028091430664, "alphanum_fraction": 0.7062596678733826, "avg_line_length": 59.279998779296875, "blob_id": "b7d8c8cef92a531bc889fc9dc0be008134477ddd", "content_id": "ad2871a46b7d83951d019d352061e5517801abaf", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4521, "license_type": "permissive", "max_line_length": 630, "num_lines": 75, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_gslb.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure Gslb object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_gslb < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Object, nil] Max retries after which the remote site is treated as a fresh start.,In fresh start all the configs are downloaded.,Allowed values are 1-1024.,Default value when not specified in API or module is interpreted by Avi Controller as 20.\n attribute :clear_on_max_retries\n\n # @return [Object, nil] Group to specify if the client ip addresses are public or private.,Field introduced in 17.1.2.\n attribute :client_ip_addr_group\n\n # @return [Object, nil] User defined description for the object.\n attribute :description\n\n # @return [Object, nil] Sub domain configuration for the gslb.,Gslb service's fqdn must be a match one of these subdomains.\n attribute :dns_configs\n\n # @return [Symbol, nil] This field indicates that this object is replicated across gslb federation.,Field introduced in 17.1.3.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :is_federated\n validates :is_federated, type: Symbol\n\n # @return [Object] Mark this site as leader of gslb configuration.,This site is the one among the avi sites.\n attribute :leader_cluster_uuid\n validates :leader_cluster_uuid, presence: true\n\n # @return [Symbol, nil] This field disables the configuration operations on the leader for all federated objects.,Cud operations on gslb, gslbservice, gslbgeodbprofile and other federated objects will be rejected.,The rest-api disabling helps in upgrade scenarios where we don't want configuration sync operations to the gslb member when the member is being,upgraded.,This configuration programmatically blocks the leader from accepting new gslb configuration when member sites are undergoing upgrade.,Field introduced in 17.2.1.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :maintenance_mode\n validates :maintenance_mode, type: Symbol\n\n # @return [String] Name for the gslb object.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Frequency with which group members communicate.,Allowed values are 1-3600.,Default value when not specified in API or module is interpreted by Avi Controller as 15.,Units(SEC).\n attribute :send_interval\n\n # @return [Object, nil] Select avi site member belonging to this gslb.\n attribute :sites\n\n # @return [Object, nil] It is a reference to an object of type tenant.\n attribute :tenant_ref\n\n # @return [Object, nil] Third party site member belonging to this gslb.,Field introduced in 17.1.1.\n attribute :third_party_sites\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Uuid of the gslb object.\n attribute :uuid\n\n # @return [Object, nil] The view-id is used in change-leader mode to differentiate partitioned groups while they have the same gslb namespace.,Each partitioned group will be able to operate independently by using the view-id.,Default value when not specified in API or module is interpreted by Avi Controller as 0.\n attribute :view_id\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7046716809272766, "alphanum_fraction": 0.7046716809272766, "avg_line_length": 67.02222442626953, "blob_id": "e9b50b134de0389d500ebf4e9f0bb4e14f8c8806", "content_id": "0bd6601cb6911668a18504f1ba320229c6a63dfa", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3061, "license_type": "permissive", "max_line_length": 584, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage user accounts and user attributes on a BIG-IP. Typically this module operates only on the REST API users and not the CLI users. When specifying C(root), you may only change the password. Your other parameters will be ignored in this case. Changing the C(root) password is not an idempotent operation. Therefore, it will change it every time this module attempts to change it.\n class Bigip_user < Base\n # @return [String, nil] Full name of the user.\n attribute :full_name\n validates :full_name, type: String\n\n # @return [String] Name of the user to create, remove or modify.,The C(root) user may not be removed.\n attribute :username_credential\n validates :username_credential, presence: true, type: String\n\n # @return [String, nil] Set the users password to this unencrypted value. C(password_credential) is required when creating a new account.\n attribute :password_credential\n validates :password_credential, type: String\n\n # @return [:bash, :none, :tmsh, nil] Optionally set the users shell.\n attribute :shell\n validates :shell, expression_inclusion: {:in=>[:bash, :none, :tmsh], :message=>\"%{value} needs to be :bash, :none, :tmsh\"}, allow_nil: true\n\n # @return [String, nil] Specifies the administrative partition to which the user has access. C(partition_access) is required when creating a new account. Should be in the form \"partition:role\". Valid roles include C(acceleration-policy-editor), C(admin), C(application-editor), C(auditor) C(certificate-manager), C(guest), C(irule-manager), C(manager), C(no-access) C(operator), C(resource-admin), C(user-manager), C(web-application-security-administrator), and C(web-application-security-editor). Partition portion of tuple should be an existing partition or the value 'all'.\n attribute :partition_access\n validates :partition_access, type: String\n\n # @return [:present, :absent, nil] Whether the account should exist or not, taking action if the state is different from what is stated.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:always, :on_create, nil] C(always) will allow to update passwords if the user chooses to do so. C(on_create) will only set the password for newly created users. When C(username_credential) is C(root), this value will be forced to C(always).\n attribute :update_password\n validates :update_password, expression_inclusion: {:in=>[:always, :on_create], :message=>\"%{value} needs to be :always, :on_create\"}, allow_nil: true\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7062937021255493, "alphanum_fraction": 0.7062937021255493, "avg_line_length": 52.625, "blob_id": "74a5fd53367472a3207c8b8d38b928f23188ab14", "content_id": "4427b482796409919dcfc3aeaf18b4a93022d3e1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1287, "license_type": "permissive", "max_line_length": 277, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/lambda_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gathers various details related to Lambda functions, including aliases, versions and event source mappings. Use module M(lambda) to manage the lambda function itself, M(lambda_alias) to manage function aliases and M(lambda_event) to manage lambda event source mappings.\n class Lambda_facts < Base\n # @return [:aliases, :all, :config, :mappings, :policy, :versions] Specifies the resource type for which to gather facts. Leave blank to retrieve all facts.\n attribute :query\n validates :query, presence: true, expression_inclusion: {:in=>[:aliases, :all, :config, :mappings, :policy, :versions], :message=>\"%{value} needs to be :aliases, :all, :config, :mappings, :policy, :versions\"}\n\n # @return [String, nil] The name of the lambda function for which facts are requested.\n attribute :function_name\n validates :function_name, type: String\n\n # @return [Object, nil] For query type 'mappings', this is the Amazon Resource Name (ARN) of the Amazon Kinesis or DynamoDB stream.\n attribute :event_source_arn\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7014157176017761, "alphanum_fraction": 0.7022737264633179, "avg_line_length": 50.79999923706055, "blob_id": "bc1a9305c9327c846fdac223e99dec80fd8f31f1", "content_id": "2320583713bb35d39dcbd7352b42eb3569f1aac4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2331, "license_type": "permissive", "max_line_length": 229, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_eip.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can allocate or release an EIP.\n # This module can associate/disassociate an EIP with instances or network interfaces.\n class Ec2_eip < Base\n # @return [String, nil] The id of the device for the EIP. Can be an EC2 Instance id or Elastic Network Interface (ENI) id.\n attribute :device_id\n validates :device_id, type: String\n\n # @return [String, nil] The IP address of a previously allocated EIP.,If present and device is specified, the EIP is associated with the device.,If absent and device is specified, the EIP is disassociated from the device.\n attribute :public_ip\n validates :public_ip, type: String\n\n # @return [:present, :absent, nil] If present, allocate an EIP or associate an existing EIP with a device.,If absent, disassociate the EIP from the device and optionally release it.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Allocate an EIP inside a VPC or not. Required if specifying an ENI.\n attribute :in_vpc\n validates :in_vpc, type: String\n\n # @return [String, nil] Reuse an EIP that is not associated to a device (when available), instead of allocating a new one.\n attribute :reuse_existing_ip_allowed\n validates :reuse_existing_ip_allowed, type: String\n\n # @return [String, nil] whether or not to automatically release the EIP when it is disassociated\n attribute :release_on_disassociation\n validates :release_on_disassociation, type: String\n\n # @return [Object, nil] The primary or secondary private IP address to associate with the Elastic IP address.\n attribute :private_ip_address\n\n # @return [String, nil] Specify this option to allow an Elastic IP address that is already associated with another network interface or instance to be re-associated with the specified instance or interface.\n attribute :allow_reassociation\n validates :allow_reassociation, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6578947305679321, "alphanum_fraction": 0.6616541147232056, "avg_line_length": 35.68965530395508, "blob_id": "d5bf552a328f91ab18b5da52fc4e331aae6413f3", "content_id": "23a9aa5da44161098161633add549a32d1b7e9fd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1064, "license_type": "permissive", "max_line_length": 143, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_ntp_options.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages NTP options, e.g. authoritative server and logging.\n class Nxos_ntp_options < Base\n # @return [Symbol, nil] Sets whether the device is an authoritative NTP server.\n attribute :master\n validates :master, type: Symbol\n\n # @return [Integer, nil] If C(master=true), an optional stratum can be supplied (1-15). The device default is 8.\n attribute :stratum\n validates :stratum, type: Integer\n\n # @return [Symbol, nil] Sets whether NTP logging is enabled on the device.\n attribute :logging\n validates :logging, type: Symbol\n\n # @return [:present, :absent, nil] Manage the state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6661698818206787, "alphanum_fraction": 0.6676602363586426, "avg_line_length": 41.82978820800781, "blob_id": "9e686c3a6ab04bbee6d5c51e7ac5d34a255a5661", "content_id": "22d053b8437504aef00f4b994ec05a877290e34b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2013, "license_type": "permissive", "max_line_length": 143, "num_lines": 47, "path": "/lib/ansible/ruby/modules/generated/cloud/profitbricks/profitbricks_nic.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows you to create or restore a volume snapshot. This module has a dependency on profitbricks >= 1.0.0\n class Profitbricks_nic < Base\n # @return [String] The datacenter in which to operate.\n attribute :datacenter\n validates :datacenter, presence: true, type: String\n\n # @return [String] The server name or ID.\n attribute :server\n validates :server, presence: true, type: String\n\n # @return [String] The name or ID of the NIC. This is only required on deletes, but not on create.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Integer] The LAN to place the NIC on. You can pass a LAN that doesn't exist and it will be created. Required on create.\n attribute :lan\n validates :lan, presence: true, type: Integer\n\n # @return [Object, nil] The ProfitBricks username. Overrides the PB_SUBSCRIPTION_ID environment variable.\n attribute :subscription_user\n\n # @return [Object, nil] THe ProfitBricks password. Overrides the PB_PASSWORD environment variable.\n attribute :subscription_password\n\n # @return [:yes, :no, nil] wait for the operation to complete before returning\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] how long before wait gives up, in seconds\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [:present, :absent, nil] Indicate desired state of the resource\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7194204330444336, "alphanum_fraction": 0.723321259021759, "avg_line_length": 78.75555419921875, "blob_id": "f04abc355d8f212880a6e2e8221c1344870a84d3", "content_id": "a1166ab83da13be8109c92810fd312c604ac5178", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3589, "license_type": "permissive", "max_line_length": 541, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/windows/win_updates.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Searches, downloads, and installs Windows updates synchronously by automating the Windows Update client.\n class Win_updates < Base\n # @return [Array<String>, String, nil] A list of update titles or KB numbers that can be used to specify which updates are to be excluded from installation.,If an available update does match one of the entries, then it is skipped and not installed.,Each entry can either be the KB article or Update title as a regex according to the PowerShell regex rules.\n attribute :blacklist\n validates :blacklist, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] A scalar or list of categories to install updates from\n attribute :category_names\n validates :category_names, type: TypeGeneric.new(String)\n\n # @return [:yes, :no, nil] Ansible will automatically reboot the remote host if it is required and continue to install updates after the reboot.,This can be used instead of using a M(win_reboot) task after this one and ensures all updates for that category is installed in one go.,Async does not work when C(reboot=True).\n attribute :reboot\n validates :reboot, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] The time in seconds to wait until the host is back online from a reboot.,This is only used if C(reboot=True) and a reboot is required.\n attribute :reboot_timeout\n validates :reboot_timeout, type: Integer\n\n # @return [:installed, :searched, nil] Controls whether found updates are returned as a list or actually installed.,This module also supports Ansible check mode, which has the same effect as setting state=searched\n attribute :state\n validates :state, expression_inclusion: {:in=>[:installed, :searched], :message=>\"%{value} needs to be :installed, :searched\"}, allow_nil: true\n\n # @return [String, nil] If set, C(win_updates) will append update progress to the specified file. The directory must already exist.\n attribute :log_path\n validates :log_path, type: String\n\n # @return [Array<String>, String, nil] A list of update titles or KB numbers that can be used to specify which updates are to be searched or installed.,If an available update does not match one of the entries, then it is skipped and not installed.,Each entry can either be the KB article or Update title as a regex according to the PowerShell regex rules.,The whitelist is only validated on updates that were found based on I(category_names). It will not force the module to install an update if it was not in the category specified.\n attribute :whitelist\n validates :whitelist, type: TypeGeneric.new(String)\n\n # @return [:yes, :no, nil] Will not auto elevate the remote process with I(become) and use a scheduled task instead.,Set this to C(yes) when using this module with async on Server 2008, 2008 R2, or Windows 7, or on Server 2008 that is not authenticated with basic or credssp.,Can also be set to C(yes) on newer hosts where become does not work due to further privilege restrictions from the OS defaults.\n attribute :use_scheduled_task\n validates :use_scheduled_task, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7208980917930603, "alphanum_fraction": 0.7260794639587402, "avg_line_length": 71.375, "blob_id": "79931e1b67a5e38008563eca8338638110109bcb", "content_id": "c30c3135bbf4eb66f73855f180ef25cb06142be2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2895, "license_type": "permissive", "max_line_length": 410, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_compute_address.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Represents an Address resource.\n # Each virtual machine instance has an ephemeral internal IP address and, optionally, an external IP address. To communicate between instances on the same network, you can use an instance's internal IP address. To communicate with the Internet and instances outside of the same network, you must specify the instance's external IP address.\n # Internal IP addresses are ephemeral and only belong to an instance for the lifetime of the instance; if the instance is deleted and recreated, the instance is assigned a new internal IP address, either by Compute Engine or by you. External IP addresses can be either ephemeral or static.\n class Gcp_compute_address < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] The static external IP address represented by this resource. Only IPv4 is supported. An address may only be specified for INTERNAL address types. The IP address must be inside the specified subnetwork, if any.\n attribute :address\n\n # @return [:INTERNAL, :EXTERNAL, nil] The type of address to reserve, either INTERNAL or EXTERNAL.,If unspecified, defaults to EXTERNAL.\n attribute :address_type\n validates :address_type, expression_inclusion: {:in=>[:INTERNAL, :EXTERNAL], :message=>\"%{value} needs to be :INTERNAL, :EXTERNAL\"}, allow_nil: true\n\n # @return [Object, nil] An optional description of this resource.\n attribute :description\n\n # @return [String] Name of the resource. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] The URL of the subnetwork in which to reserve the address. If an IP address is specified, it must be within the subnetwork's IP range.,This field can only be used with INTERNAL type with GCE_ENDPOINT/DNS_RESOLVER purposes.\n attribute :subnetwork\n\n # @return [String] URL of the region where the regional address resides.,This field is not applicable to global addresses.\n attribute :region\n validates :region, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6582220196723938, "alphanum_fraction": 0.6582220196723938, "avg_line_length": 39.96226501464844, "blob_id": "310f9956a220c84f7152e039d0b825a7acde2de1", "content_id": "d21f7c61464c5c898766039290ac7e4f5b0f2f11", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2171, "license_type": "permissive", "max_line_length": 159, "num_lines": 53, "path": "/lib/ansible/ruby/modules/generated/cloud/ovh/ovh_ip_loadbalancing_backend.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage OVH (French European hosting provider) LoadBalancing IP backends\n class Ovh_ip_loadbalancing_backend < Base\n # @return [String] Name of the LoadBalancing internal name (ip-X.X.X.X)\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] The IP address of the backend to update / modify / delete\n attribute :backend\n validates :backend, presence: true, type: String\n\n # @return [:present, :absent, nil] Determines whether the backend is to be created/modified or deleted\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:none, :http, :icmp, :oco, nil] Determines the type of probe to use for this backend\n attribute :probe\n validates :probe, expression_inclusion: {:in=>[:none, :http, :icmp, :oco], :message=>\"%{value} needs to be :none, :http, :icmp, :oco\"}, allow_nil: true\n\n # @return [Integer, nil] Determines the weight for this backend\n attribute :weight\n validates :weight, type: Integer\n\n # @return [String] The endpoint to use ( for instance ovh-eu)\n attribute :endpoint\n validates :endpoint, presence: true, type: String\n\n # @return [String] The applicationKey to use\n attribute :application_key\n validates :application_key, presence: true, type: String\n\n # @return [String] The application secret to use\n attribute :application_secret\n validates :application_secret, presence: true, type: String\n\n # @return [String] The consumer key to use\n attribute :consumer_key\n validates :consumer_key, presence: true, type: String\n\n # @return [Integer, nil] The timeout in seconds used to wait for a task to be completed.\n attribute :timeout\n validates :timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6906976699829102, "alphanum_fraction": 0.6982558369636536, "avg_line_length": 58.31034469604492, "blob_id": "8f2b867018b31b04925bbb2c1ef3017b154d6bfb", "content_id": "170b25b59dff78de0c3b5f60b28773e32f53f9fb", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1720, "license_type": "permissive", "max_line_length": 552, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_guest_tools_wait.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to wait for VMware tools to become available on the given VM and return facts.\n class Vmware_guest_tools_wait < Base\n # @return [String, nil] Name of the VM for which to wait until the tools become available.,This is required if uuid is not supplied.\n attribute :name\n validates :name, type: String\n\n # @return [:first, :last, nil] If multiple VMs match the name, use the first or last found.\n attribute :name_match\n validates :name_match, expression_inclusion: {:in=>[:first, :last], :message=>\"%{value} needs to be :first, :last\"}, allow_nil: true\n\n # @return [String, nil] Destination folder, absolute or relative path to find an existing guest.,This is required only, if multiple VMs with same C(name) is found.,The folder should include the datacenter. ESX's datacenter is C(ha-datacenter).,Examples:, folder: /ha-datacenter/vm, folder: ha-datacenter/vm, folder: /datacenter1/vm, folder: datacenter1/vm, folder: /datacenter1/vm/folder1, folder: datacenter1/vm/folder1, folder: /folder1/datacenter1/vm, folder: folder1/datacenter1/vm, folder: /folder1/datacenter1/vm/folder2\n attribute :folder\n validates :folder, type: String\n\n # @return [String, nil] UUID of the VM for which to wait until the tools become available, if known. This is VMware's unique identifier.,This is required, if C(name) is not supplied.\n attribute :uuid\n validates :uuid, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.45412418246269226, "alphanum_fraction": 0.4569045305252075, "avg_line_length": 20.156862258911133, "blob_id": "10d86c8e57274bc142feef80275536e85f9c342d", "content_id": "3704a5ca9a16272342541cf5febfdb5321ed5946", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1079, "license_type": "permissive", "max_line_length": 71, "num_lines": 51, "path": "/lib/ansible/ruby/modules/custom/cloud/core/docker/docker_container_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# see LICENSE.txt in project root\nrequire 'spec_helper'\n\ndescribe Ansible::Ruby::Modules::Docker_container do\n subject(:mod) do\n Ansible::Ruby::Modules::Docker_container.new name: 'the_container',\n image: 'centos:7',\n volumes: volumes\n end\n\n describe '#to_h' do\n subject { mod.to_h }\n\n context 'no flags' do\n let(:volumes) do\n {\n '/stuff' => '/howdy'\n }\n end\n\n it do\n is_expected.to eq docker_container: {\n name: 'the_container',\n image: 'centos:7',\n volumes: ['/stuff:/howdy']\n }\n end\n end\n\n context 'flags' do\n let(:volumes) do\n {\n '/stuff' => {\n flags: 'Z',\n path: '/howdy'\n }\n }\n end\n\n it do\n is_expected.to eq docker_container: {\n name: 'the_container',\n image: 'centos:7',\n volumes: ['/stuff:/howdy:Z']\n }\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6746031641960144, "alphanum_fraction": 0.6772486567497253, "avg_line_length": 38.10344696044922, "blob_id": "6d9c2ec9a85365a0a9ff28bbdb2821b5374db04f", "content_id": "31c70c89afd6348f0ebe17b855f8a4860f1aea43", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1134, "license_type": "permissive", "max_line_length": 143, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ecs_attribute.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update or delete ECS container instance attributes.\n class Ecs_attribute < Base\n # @return [String] The short name or full Amazon Resource Name (ARN) of the cluster that contains the resource to apply attributes.\n attribute :cluster\n validates :cluster, presence: true, type: String\n\n # @return [:present, :absent, nil] The desired state of the attributes.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash] List of attributes.\n attribute :attributes\n validates :attributes, presence: true, type: TypeGeneric.new(Hash)\n\n # @return [String] EC2 instance ID of ECS cluster container instance.\n attribute :ec2_instance_id\n validates :ec2_instance_id, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6962847113609314, "alphanum_fraction": 0.6962847113609314, "avg_line_length": 77.3859634399414, "blob_id": "dee572df3e6a573821c9eea9b0ef48219b41e885", "content_id": "3979a926c7d19ae1a9271c8a7b28eac7f79dde71", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4468, "license_type": "permissive", "max_line_length": 789, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcdns_record.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates or removes resource records in Google Cloud DNS.\n class Gcdns_record < Base\n # @return [:present, :absent, nil] Whether the given resource record should or should not be present.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The fully-qualified domain name of the resource record.\n attribute :record\n validates :record, presence: true, type: String\n\n # @return [String, nil] The DNS domain name of the zone (e.g., example.com).,One of either I(zone) or I(zone_id) must be specified as an option, or the module will fail.,If both I(zone) and I(zone_id) are specified, I(zone_id) will be used.\n attribute :zone\n validates :zone, type: String\n\n # @return [String, nil] The Google Cloud ID of the zone (e.g., example-com).,One of either I(zone) or I(zone_id) must be specified as an option, or the module will fail.,These usually take the form of domain names with the dots replaced with dashes. A zone ID will never have any dots in it.,I(zone_id) can be faster than I(zone) in projects with a large number of zones.,If both I(zone) and I(zone_id) are specified, I(zone_id) will be used.\n attribute :zone_id\n validates :zone_id, type: String\n\n # @return [:A, :AAAA, :CNAME, :SRV, :TXT, :SOA, :NS, :MX, :SPF, :PTR] The type of resource record to add.\n attribute :type\n validates :type, presence: true, expression_inclusion: {:in=>[:A, :AAAA, :CNAME, :SRV, :TXT, :SOA, :NS, :MX, :SPF, :PTR], :message=>\"%{value} needs to be :A, :AAAA, :CNAME, :SRV, :TXT, :SOA, :NS, :MX, :SPF, :PTR\"}\n\n # @return [Array<String>, String, nil] The record_data to use for the resource record.,I(record_data) must be specified if I(state) is C(present) or I(overwrite) is C(True), or the module will fail.,Valid record_data vary based on the record's I(type). In addition, resource records that contain a DNS domain name in the value field (e.g., CNAME, PTR, SRV, .etc) MUST include a trailing dot in the value.,Individual string record_data for TXT records must be enclosed in double quotes.,For resource records that have the same name but different record_data (e.g., multiple A records), they must be defined as multiple list entries in a single record.\n attribute :record_data\n validates :record_data, type: TypeGeneric.new(String)\n\n # @return [Integer, nil] The amount of time in seconds that a resource record will remain cached by a caching resolver.\n attribute :ttl\n validates :ttl, type: Integer\n\n # @return [:yes, :no, nil] Whether an attempt to overwrite an existing record should succeed or fail. The behavior of this option depends on I(state).,If I(state) is C(present) and I(overwrite) is C(True), this module will replace an existing resource record of the same name with the provided I(record_data). If I(state) is C(present) and I(overwrite) is C(False), this module will fail if there is an existing resource record with the same name and type, but different resource data.,If I(state) is C(absent) and I(overwrite) is C(True), this module will remove the given resource record unconditionally. If I(state) is C(absent) and I(overwrite) is C(False), this module will fail if the provided record_data do not match exactly with the existing resource record's record_data.\n attribute :overwrite\n validates :overwrite, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] The e-mail address for a service account with access to Google Cloud DNS.\n attribute :service_account_email\n\n # @return [Object, nil] The path to the PEM file associated with the service account email.,This option is deprecated and may be removed in a future release. Use I(credentials_file) instead.\n attribute :pem_file\n\n # @return [Object, nil] The path to the JSON file associated with the service account email.\n attribute :credentials_file\n\n # @return [Object, nil] The Google Cloud Platform project ID to use.\n attribute :project_id\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6844611763954163, "alphanum_fraction": 0.6859649419784546, "avg_line_length": 75.73076629638672, "blob_id": "1ba1c62104699cfb3201ddea3fb8e6bc7ca775d3", "content_id": "5d2fbd3b7696c94c9c273009aff4414c03008160", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3990, "license_type": "permissive", "max_line_length": 434, "num_lines": 52, "path": "/lib/ansible/ruby/modules/generated/packaging/os/zypper.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage packages on SUSE and openSUSE using the zypper and rpm tools.\n class Zypper < Base\n # @return [String] Package name C(name) or package specifier or a list of either.,Can include a version like C(name=1.0), C(name>3.4) or C(name<=2.7). If a version is given, C(oldpackage) is implied and zypper is allowed to update the package within the version range given.,You can also pass a url or a local path to a rpm file.,When using state=latest, this can be '*', which updates all installed packages.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :latest, :absent, :\"dist-upgrade\", nil] C(present) will make sure the package is installed. C(latest) will make sure the latest version of the package is installed. C(absent) will make sure the specified package is not installed. C(dist-upgrade) will make sure the latest version of all installed packages from all enabled repositories is installed.,When using C(dist-upgrade), I(name) should be C('*').\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :latest, :absent, :\"dist-upgrade\"], :message=>\"%{value} needs to be :present, :latest, :absent, :\\\"dist-upgrade\\\"\"}, allow_nil: true\n\n # @return [:package, :patch, :pattern, :product, :srcpackage, :application, nil] The type of package to be operated on.\n attribute :type\n validates :type, expression_inclusion: {:in=>[:package, :patch, :pattern, :product, :srcpackage, :application], :message=>\"%{value} needs to be :package, :patch, :pattern, :product, :srcpackage, :application\"}, allow_nil: true\n\n # @return [Object, nil] Add additional global target options to C(zypper).,Options should be supplied in a single line as if given in the command line.\n attribute :extra_args_precommand\n\n # @return [:yes, :no, nil] Whether to disable to GPG signature checking of the package signature being installed. Has an effect only if state is I(present) or I(latest).\n attribute :disable_gpg_check\n validates :disable_gpg_check, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Corresponds to the C(--no-recommends) option for I(zypper). Default behavior (C(yes)) modifies zypper's default behavior; C(no) does install recommended packages.\n attribute :disable_recommends\n validates :disable_recommends, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Adds C(--force) option to I(zypper). Allows to downgrade packages and change vendor or architecture.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Run the equivalent of C(zypper refresh) before the operation. Disabled in check mode.\n attribute :update_cache\n validates :update_cache, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Adds C(--oldpackage) option to I(zypper). Allows to downgrade packages with less side-effects than force. This is implied as soon as a version is specified as part of the package name.\n attribute :oldpackage\n validates :oldpackage, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Add additional options to C(zypper) command.,Options should be supplied in a single line as if given in the command line.\n attribute :extra_args\n validates :extra_args, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6759160161018372, "alphanum_fraction": 0.6780505180358887, "avg_line_length": 53.05769348144531, "blob_id": "ce7ba992021f17e8ebb29f55d2416785ee5c2c9b", "content_id": "759699c97fd8cb10304f07dfd0336f105095a84d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2811, "license_type": "permissive", "max_line_length": 287, "num_lines": 52, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_affinity_groups.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module manage affinity groups in oVirt/RHV. It can also manage assignments of those groups to VMs.\n class Ovirt_affinity_group < Base\n # @return [String] Name of the affinity group to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, nil] Should the affinity group be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] Name of the cluster of the affinity group.\n attribute :cluster\n validates :cluster, type: String\n\n # @return [Object, nil] Description of the affinity group.\n attribute :description\n\n # @return [Symbol, nil] If I(yes) VM cannot start on host if it does not satisfy the C(host_rule).,This parameter is support since oVirt/RHV 4.1 version.\n attribute :host_enforcing\n validates :host_enforcing, type: Symbol\n\n # @return [:negative, :positive, nil] If I(positive) I(all) VMs in this group should run on the this host.,If I(negative) I(no) VMs in this group should run on the this host.,This parameter is support since oVirt/RHV 4.1 version.\n attribute :host_rule\n validates :host_rule, expression_inclusion: {:in=>[:negative, :positive], :message=>\"%{value} needs to be :negative, :positive\"}, allow_nil: true\n\n # @return [Symbol, nil] If I(yes) VM cannot start if it does not satisfy the C(vm_rule).\n attribute :vm_enforcing\n validates :vm_enforcing, type: Symbol\n\n # @return [:disabled, :negative, :positive, nil] If I(positive) I(all) VMs in this group should run on the host defined by C(host_rule).,If I(negative) I(no) VMs in this group should run on the host defined by C(host_rule).,If I(disabled) this affinity group doesn't take effect.\n attribute :vm_rule\n validates :vm_rule, expression_inclusion: {:in=>[:disabled, :negative, :positive], :message=>\"%{value} needs to be :disabled, :negative, :positive\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] List of the VMs names, which should have assigned this affinity group.\n attribute :vms\n validates :vms, type: TypeGeneric.new(String, NilClass)\n\n # @return [Array<String>, String, nil] List of the hosts names, which should have assigned this affinity group.,This parameter is support since oVirt/RHV 4.1 version.\n attribute :hosts\n validates :hosts, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7270415425300598, "alphanum_fraction": 0.7380616068840027, "avg_line_length": 79.43181610107422, "blob_id": "a3aed5a0a8238a405949369b11c30365f5178c31", "content_id": "f27d7358773c58cec8052be7d6e42382ed437288", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3539, "license_type": "permissive", "max_line_length": 475, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_compute_subnetwork.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # A VPC network is a virtual version of the traditional physical networks that exist within and between physical data centers. A VPC network provides connectivity for your Compute Engine virtual machine (VM) instances, Container Engine containers, App Engine Flex services, and other network-related resources.\n # Each GCP project contains one or more VPC networks. Each VPC network is a global entity spanning all GCP regions. This global VPC network allows VM instances and other resources to communicate with each other via internal, private IP addresses.\n # Each VPC network is subdivided into subnets, and each subnet is contained within a single region. You can have more than one subnet in a region for a given VPC network. Each subnet has a contiguous private RFC1918 IP space. You create instances, containers, and the like in these subnets.\n # When you create an instance, you must create it in a subnet, and the instance draws its internal IP address from that subnet.\n # Virtual machine (VM) instances in a VPC network can communicate with instances in all other subnets of the same VPC network, regardless of region, using their RFC1918 private IP addresses. You can isolate portions of the network, even entire subnets, using firewall rules.\n class Gcp_compute_subnetwork < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] An optional description of this resource. Provide this property when you create the resource. This field can be set only at resource creation time.\n attribute :description\n\n # @return [String] The range of internal addresses that are owned by this subnetwork.,Provide this property when you create the subnetwork. For example, 10.0.0.0/8 or 192.168.0.0/16. Ranges must be unique and non-overlapping within a network. Only IPv4 is supported.\n attribute :ip_cidr_range\n validates :ip_cidr_range, presence: true, type: String\n\n # @return [String] The name of the resource, provided by the client when initially creating the resource. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] The network this subnet belongs to.,Only networks that are in the distributed mode can have subnetworks.\n attribute :network\n validates :network, presence: true, type: String\n\n # @return [Symbol, nil] Whether the VMs in this subnet can access Google services without assigned external IP addresses.\n attribute :private_ip_google_access\n validates :private_ip_google_access, type: Symbol\n\n # @return [String] URL of the GCP region for this subnetwork.\n attribute :region\n validates :region, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6479052305221558, "alphanum_fraction": 0.6479052305221558, "avg_line_length": 44.44230651855469, "blob_id": "10c427eb24664bfe3a82af22894bc372a0a90edd", "content_id": "c1215c03c01e183f7eb78756fae31d3e921ef368", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2363, "license_type": "permissive", "max_line_length": 221, "num_lines": 52, "path": "/lib/ansible/ruby/modules/generated/net_tools/netcup_dns.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages DNS records via the Netcup API, see the docs U(https://ccp.netcup.net/run/webservice/servers/endpoint.php)\n class Netcup_dns < Base\n # @return [String] API key for authentification, must be obtained via the netcup CCP (U(https://ccp.netcup.net))\n attribute :api_key\n validates :api_key, presence: true, type: String\n\n # @return [String] API password for authentification, must be obtained via the netcup CCP (https://ccp.netcup.net)\n attribute :api_password\n validates :api_password, presence: true, type: String\n\n # @return [String] Netcup customer id\n attribute :customer_id\n validates :customer_id, presence: true, type: String\n\n # @return [String] Domainname the records should be added / removed\n attribute :domain\n validates :domain, presence: true, type: String\n\n # @return [String, nil] Record to add or delete, supports wildcard (*). Default is C(@) (e.g. the zone name)\n attribute :record\n validates :record, type: String\n\n # @return [:A, :AAAA, :MX, :CNAME, :CAA, :SRV, :TXT, :TLSA, :NS, :DS] Record type\n attribute :type\n validates :type, presence: true, expression_inclusion: {:in=>[:A, :AAAA, :MX, :CNAME, :CAA, :SRV, :TXT, :TLSA, :NS, :DS], :message=>\"%{value} needs to be :A, :AAAA, :MX, :CNAME, :CAA, :SRV, :TXT, :TLSA, :NS, :DS\"}\n\n # @return [String] Record value\n attribute :value\n validates :value, presence: true, type: String\n\n # @return [Symbol, nil] Whether the record should be the only one for that record type and record name. Only use with C(state=present),This will delete all other records with the same record name and type.\n attribute :solo\n validates :solo, type: Symbol\n\n # @return [Object, nil] Record priority. Required for C(type=MX)\n attribute :priority\n\n # @return [:present, :absent, nil] Whether the record should exist or not\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.669905960559845, "alphanum_fraction": 0.6736677289009094, "avg_line_length": 55.96428680419922, "blob_id": "6b8381c9a28b2868dbe9c74097277d3f1322726d", "content_id": "84e2452e8be1e4ea5db439c613b3fc524f33ed54", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3190, "license_type": "permissive", "max_line_length": 357, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_vpc_route_table.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage route tables for AWS virtual private clouds\n class Ec2_vpc_route_table < Base\n # @return [:tag, :id, nil] Look up route table by either tags or by route table ID. Non-unique tag lookup will fail. If no tags are specified then no lookup for an existing route table is performed and a new route table will be created. To change tags of a route table you must look up by id.\n attribute :lookup\n validates :lookup, expression_inclusion: {:in=>[:tag, :id], :message=>\"%{value} needs to be :tag, :id\"}, allow_nil: true\n\n # @return [Object, nil] Enable route propagation from virtual gateways specified by ID.\n attribute :propagating_vgw_ids\n\n # @return [:yes, :no, nil] Purge existing routes that are not found in routes.\n attribute :purge_routes\n validates :purge_routes, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Purge existing subnets that are not found in subnets. Ignored unless the subnets option is supplied.\n attribute :purge_subnets\n validates :purge_subnets, type: String\n\n # @return [:yes, :no, nil] Purge existing tags that are not found in route table\n attribute :purge_tags\n validates :purge_tags, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] The ID of the route table to update or delete.\n attribute :route_table_id\n validates :route_table_id, type: String\n\n # @return [Array<Hash>, Hash, nil] List of routes in the route table. Routes are specified as dicts containing the keys 'dest' and one of 'gateway_id', 'instance_id', 'network_interface_id', or 'vpc_peering_connection_id'. If 'gateway_id' is specified, you can refer to the VPC's IGW by using the value 'igw'. Routes are required for present states.\n attribute :routes\n validates :routes, type: TypeGeneric.new(Hash)\n\n # @return [:present, :absent, nil] Create or destroy the VPC route table\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] An array of subnets to add to this route table. Subnets may be specified by either subnet ID, Name tag, or by a CIDR such as '10.0.0.0/24'.\n attribute :subnets\n validates :subnets, type: TypeGeneric.new(String)\n\n # @return [Hash, nil] A dictionary of resource tags of the form: { tag1: value1, tag2: value2 }. Tags are used to uniquely identify route tables within a VPC when the route_table_id is not supplied.\\r\\n\n attribute :tags\n validates :tags, type: Hash\n\n # @return [String] VPC ID of the VPC in which to create the route table.\n attribute :vpc_id\n validates :vpc_id, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6685393452644348, "avg_line_length": 45.842105865478516, "blob_id": "93adc1d9643d5e23d26e8dc3acfe687782a199a0", "content_id": "152467b71664b3a0b3ee78b7bdd27df15bb40b28", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2670, "license_type": "permissive", "max_line_length": 155, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/network/junos/junos_l2_interface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of Layer-2 interface on Juniper JUNOS network devices.\n class Junos_l2_interface < Base\n # @return [String, nil] Name of the interface excluding any logical unit number.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] Description of Interface.\n attribute :description\n validates :description, type: String\n\n # @return [Array<Hash>, Hash, nil] List of Layer-2 interface definitions.\n attribute :aggregate\n validates :aggregate, type: TypeGeneric.new(Hash)\n\n # @return [:access, :trunk, nil] Mode in which interface needs to be configured.\n attribute :mode\n validates :mode, expression_inclusion: {:in=>[:access, :trunk], :message=>\"%{value} needs to be :access, :trunk\"}, allow_nil: true\n\n # @return [String, nil] Configure given VLAN in access port. The value of C(access_vlan) should be vlan name.\n attribute :access_vlan\n validates :access_vlan, type: String\n\n # @return [Array<String>, String, nil] List of VLAN names to be configured in trunk port. The value of C(trunk_vlans) should be list of vlan names.\n attribute :trunk_vlans\n validates :trunk_vlans, type: TypeGeneric.new(String)\n\n # @return [Integer, nil] Native VLAN to be configured in trunk port. The value of C(native_vlan) should be vlan id.\n attribute :native_vlan\n validates :native_vlan, type: Integer\n\n # @return [Boolean, nil] True if your device has Enhanced Layer 2 Software (ELS).\n attribute :enhanced_layer\n validates :enhanced_layer, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Integer, nil] Logical interface number. Value of C(unit) should be of type integer.\n attribute :unit\n validates :unit, type: Integer\n\n # @return [:present, :absent, nil] State of the Layer-2 Interface configuration.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Boolean, nil] Specifies whether or not the configuration is active or deactivated\n attribute :active\n validates :active, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6793187260627747, "alphanum_fraction": 0.7092457413673401, "avg_line_length": 66.3770523071289, "blob_id": "d6d08feb148cab953a259ac059d2a5531d80fb9e", "content_id": "9b5d00b067ede498e3671d927437f35624458bac", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4110, "license_type": "permissive", "max_line_length": 865, "num_lines": 61, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_device_httpd.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages HTTPD related settings on the BIG-IP. These settings are interesting to change when you want to set GUI timeouts and other TMUI related settings.\n class Bigip_device_httpd < Base\n # @return [Object, nil] Specifies, if you have enabled HTTPD access, the IP address or address range for other systems that can communicate with this system.,To specify all addresses, use the value C(all).,IP address can be specified, such as 172.27.1.10.,IP rangees can be specified, such as 172.27.*.* or 172.27.0.0/255.255.0.0.\n attribute :allow\n\n # @return [String, nil] Sets the BIG-IP authentication realm name.\n attribute :auth_name\n validates :auth_name, type: String\n\n # @return [Integer, nil] Sets the GUI timeout for automatic logout, in seconds.\n attribute :auth_pam_idle_timeout\n validates :auth_pam_idle_timeout, type: Integer\n\n # @return [Symbol, nil] Sets the authPamValidateIp setting.\n attribute :auth_pam_validate_ip\n validates :auth_pam_validate_ip, type: Symbol\n\n # @return [Symbol, nil] Sets whether or not the BIG-IP dashboard will timeout.\n attribute :auth_pam_dashboard_timeout\n validates :auth_pam_dashboard_timeout, type: Symbol\n\n # @return [Object, nil] Sets the timeout of FastCGI.\n attribute :fast_cgi_timeout\n\n # @return [Symbol, nil] Sets whether or not to display the hostname, if possible.\n attribute :hostname_lookup\n validates :hostname_lookup, type: Symbol\n\n # @return [:alert, :crit, :debug, :emerg, :error, :info, :notice, :warn, nil] Sets the minimum httpd log level.\n attribute :log_level\n validates :log_level, expression_inclusion: {:in=>[:alert, :crit, :debug, :emerg, :error, :info, :notice, :warn], :message=>\"%{value} needs to be :alert, :crit, :debug, :emerg, :error, :info, :notice, :warn\"}, allow_nil: true\n\n # @return [Object, nil] Sets the maximum number of clients that can connect to the GUI at once.\n attribute :max_clients\n\n # @return [Symbol, nil] Whether or not to redirect http requests to the GUI to https.\n attribute :redirect_http_to_https\n validates :redirect_http_to_https, type: Symbol\n\n # @return [Object, nil] The HTTPS port to listen on.\n attribute :ssl_port\n\n # @return [Array<String>, String, nil] Specifies the ciphers that the system uses.,The values in the suite are separated by colons (:).,Can be specified in either a string or list form. The list form is the recommended way to provide the cipher suite. See examples for usage.,Use the value C(default) to set the cipher suite to the system default. This value is equivalent to specifying a list of C(ECDHE-RSA-AES128-GCM-SHA256, ECDHE-RSA-AES256-GCM-SHA384,ECDHE-RSA-AES128-SHA,ECDHE-RSA-AES256-SHA, ECDHE-RSA-AES128-SHA256,ECDHE-RSA-AES256-SHA384,ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES256-GCM-SHA384,ECDHE-ECDSA-AES128-SHA,ECDHE-ECDSA-AES256-SHA, ECDHE-ECDSA-AES128-SHA256,ECDHE-ECDSA-AES256-SHA384,AES128-GCM-SHA256, AES256-GCM-SHA384,AES128-SHA,AES256-SHA,AES128-SHA256,AES256-SHA256, ECDHE-RSA-DES-CBC3-SHA,ECDHE-ECDSA-DES-CBC3-SHA,DES-CBC3-SHA).\n attribute :ssl_cipher_suite\n validates :ssl_cipher_suite, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] The list of SSL protocols to accept on the management console.,A space-separated list of tokens in the format accepted by the Apache mod_ssl SSLProtocol directive.,Can be specified in either a string or list form. The list form is the recommended way to provide the cipher suite. See examples for usage.,Use the value C(default) to set the SSL protocols to the system default. This value is equivalent to specifying a list of C(all,-SSLv2,-SSLv3).\n attribute :ssl_protocols\n validates :ssl_protocols, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6703469753265381, "alphanum_fraction": 0.6703469753265381, "avg_line_length": 35.228572845458984, "blob_id": "64dc633ae05e80215662eb7da0b21d9c8d3bf3ad", "content_id": "739c1f6b4d51e6b384370a3d1f0ef678df114ba6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1268, "license_type": "permissive", "max_line_length": 143, "num_lines": 35, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_volume_snapshot.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or Delete cinder block storage volume snapshots\n class Os_volume_snapshot < Base\n # @return [Object] Name of the snapshot\n attribute :display_name\n validates :display_name, presence: true\n\n # @return [Object, nil] String describing the snapshot\n attribute :display_description\n\n # @return [Object] The volume name or id to create/delete the snapshot\n attribute :volume\n validates :volume, presence: true\n\n # @return [Symbol, nil] Allows or disallows snapshot of a volume to be created when the volume is attached to an instance.\n attribute :force\n validates :force, type: Symbol\n\n # @return [:present, :absent, nil] Should the resource be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Availability zone in which to create the snapshot.\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6707317233085632, "alphanum_fraction": 0.673054575920105, "avg_line_length": 42.04999923706055, "blob_id": "1654fce8183ac4a2de06455a7990121259c9ea1a", "content_id": "e38056aa6caca39929f75d368990a1ce8dd17952", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1722, "license_type": "permissive", "max_line_length": 208, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/route53_zone.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates and deletes Route53 private and public zones\n class Route53_zone < Base\n # @return [String] The DNS zone record (eg: foo.com.)\n attribute :zone\n validates :zone, presence: true, type: String\n\n # @return [:present, :absent, nil] whether or not the zone should exist or not\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] The VPC ID the zone should be a part of (if this is going to be a private zone)\n attribute :vpc_id\n validates :vpc_id, type: String\n\n # @return [String, nil] The VPC Region the zone should be a part of (if this is going to be a private zone)\n attribute :vpc_region\n validates :vpc_region, type: String\n\n # @return [String, nil] Comment associated with the zone\n attribute :comment\n validates :comment, type: String\n\n # @return [Object, nil] The unique zone identifier you want to delete or \"all\" if there are many zones with the same domain name. Required if there are multiple zones identified with the above options\n attribute :hosted_zone_id\n\n # @return [String, nil] The reusable delegation set ID to be associated with the zone. Note that you can't associate a reusable delegation set with a private hosted zone.\n attribute :delegation_set_id\n validates :delegation_set_id, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6787072420120239, "alphanum_fraction": 0.6787072420120239, "avg_line_length": 52.49152374267578, "blob_id": "b72bc2f22428c6af38c155af92119de07f9ae79f", "content_id": "6aa0eb2ac16eb926b948faa0f65beac0c4a2cf9b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3156, "license_type": "permissive", "max_line_length": 290, "num_lines": 59, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_external_providers.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Module to manage external providers in oVirt/RHV\n class Ovirt_external_provider < Base\n # @return [String, nil] Name of the external provider to manage.\n attribute :name\n validates :name, type: String\n\n # @return [:present, :absent, nil] Should the external be present or absent,When you are using absent for I(os_volume), you need to make sure that SD is not attached to the data center!\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Description of the external provider.\n attribute :description\n\n # @return [:os_image, :network, :os_volume, :foreman, nil] Type of the external provider.\n attribute :type\n validates :type, expression_inclusion: {:in=>[:os_image, :network, :os_volume, :foreman], :message=>\"%{value} needs to be :os_image, :network, :os_volume, :foreman\"}, allow_nil: true\n\n # @return [String, nil] URL where external provider is hosted.,Applicable for those types: I(os_image), I(os_volume), I(network) and I(foreman).\n attribute :url\n validates :url, type: String\n\n # @return [String, nil] Username to be used for login to external provider.,Applicable for all types.\n attribute :username\n validates :username, type: String\n\n # @return [Integer, nil] Password of the user specified in C(username) parameter.,Applicable for all types.\n attribute :password\n validates :password, type: Integer\n\n # @return [Object, nil] Name of the tenant.,Applicable for those types: I(os_image), I(os_volume) and I(network).\n attribute :tenant_name\n\n # @return [Object, nil] Keystone authentication URL of the openstack provider.,Applicable for those types: I(os_image), I(os_volume) and I(network).\n attribute :authentication_url\n\n # @return [Object, nil] Name of the data center where provider should be attached.,Applicable for those type: I(os_volume).\n attribute :data_center\n\n # @return [Object, nil] Specify if the network should be read only.,Applicable if C(type) is I(network).\n attribute :read_only\n\n # @return [:external, :neutron, nil] Type of the external network provider either external (for example OVN) or neutron.,Applicable if C(type) is I(network).\n attribute :network_type\n validates :network_type, expression_inclusion: {:in=>[:external, :neutron], :message=>\"%{value} needs to be :external, :neutron\"}, allow_nil: true\n\n # @return [Object, nil] List of authentication keys. Each key is represented by dict like {'uuid': 'our-uuid', 'value': 'YourSecretValue=='},When you will not pass these keys and there are already some of them defined in the system they will be removed.,Applicable for I(os_volume).\n attribute :authentication_keys\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6831812262535095, "alphanum_fraction": 0.683833122253418, "avg_line_length": 50.13333511352539, "blob_id": "d52aea42cc116435f9711fe92f7c5dabc096479d", "content_id": "327e61a9a14ab037123c342114cedd039d19f8b9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1534, "license_type": "permissive", "max_line_length": 316, "num_lines": 30, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_lc_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gather facts about AWS Autoscaling Launch Configurations\n class Ec2_lc_facts < Base\n # @return [Object, nil] A name or a list of name to match.\n attribute :name\n\n # @return [:launch_configuration_name, :image_id, :created_time, :instance_type, :kernel_id, :ramdisk_id, :key_name, nil] Optional attribute which with to sort the results.\n attribute :sort\n validates :sort, expression_inclusion: {:in=>[:launch_configuration_name, :image_id, :created_time, :instance_type, :kernel_id, :ramdisk_id, :key_name], :message=>\"%{value} needs to be :launch_configuration_name, :image_id, :created_time, :instance_type, :kernel_id, :ramdisk_id, :key_name\"}, allow_nil: true\n\n # @return [:ascending, :descending, nil] Order in which to sort results.,Only used when the 'sort' parameter is specified.\n attribute :sort_order\n validates :sort_order, expression_inclusion: {:in=>[:ascending, :descending], :message=>\"%{value} needs to be :ascending, :descending\"}, allow_nil: true\n\n # @return [Object, nil] Which result to start with (when sorting).,Corresponds to Python slice notation.\n attribute :sort_start\n\n # @return [Object, nil] Which result to end with (when sorting).,Corresponds to Python slice notation.\n attribute :sort_end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6880415678024292, "alphanum_fraction": 0.6880415678024292, "avg_line_length": 32.94117736816406, "blob_id": "1fc1da31138b0589513ca5f549eaa702e9d8ab54", "content_id": "7843aaf17b58cb1fda175636eaddaa8ab408dd86", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 577, "license_type": "permissive", "max_line_length": 174, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/net_tools/ldap/ldap_passwd.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Set a password for an LDAP entry. This module only asserts that a given password is valid for a given entry. To assert the existence of an entry, see M(ldap_entry).\n class Ldap_passwd < Base\n # @return [String] The (plaintext) password to be set for I(dn).\n attribute :passwd\n validates :passwd, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6376582384109497, "alphanum_fraction": 0.6518987417221069, "avg_line_length": 36.17647171020508, "blob_id": "e3e535fa4e5e037963753d7169e400d0f8054110", "content_id": "2e345fb71ea336092329bd823b2e6a362049b6c1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 632, "license_type": "permissive", "max_line_length": 203, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/cloud/scaleway/scaleway_image_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gather facts about the Scaleway images available.\n class Scaleway_image_facts < Base\n # @return [:ams1, :\"EMEA-NL-EVS\", :par1, :\"EMEA-FR-PAR1\"] Scaleway compute zone\n attribute :region\n validates :region, presence: true, expression_inclusion: {:in=>[:ams1, :\"EMEA-NL-EVS\", :par1, :\"EMEA-FR-PAR1\"], :message=>\"%{value} needs to be :ams1, :\\\"EMEA-NL-EVS\\\", :par1, :\\\"EMEA-FR-PAR1\\\"\"}\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6592877507209778, "alphanum_fraction": 0.662175178527832, "avg_line_length": 34.82758712768555, "blob_id": "d146742462ed66f8e90346716b88d885bd418b71", "content_id": "c71d5bf37fef994c416423dd8b30d9289aa8c414", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1039, "license_type": "permissive", "max_line_length": 143, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/s3_logging.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage logging facility of an s3 bucket in AWS\n class S3_logging < Base\n # @return [String] Name of the s3 bucket.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Enable or disable logging.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] The bucket to log to. Required when state=present.\n attribute :target_bucket\n validates :target_bucket, type: String\n\n # @return [String, nil] The prefix that should be prepended to the generated log files written to the target_bucket.\n attribute :target_prefix\n validates :target_prefix, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6508688926696777, "alphanum_fraction": 0.6508688926696777, "avg_line_length": 44.21428680419922, "blob_id": "51b3cf8c2f9297856b82b0b42c6bfbd28df36014", "content_id": "5c6a78261a37e5d295c04c2b0b0931d1b5faa453", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1266, "license_type": "permissive", "max_line_length": 248, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/ansible_tower/tower_job_list.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # List Ansible Tower jobs. See U(https://www.ansible.com/tower) for an overview.\n class Tower_job_list < Base\n # @return [:pending, :waiting, :running, :error, :failed, :canceled, :successful, nil] Only list jobs with this status.\n attribute :status\n validates :status, expression_inclusion: {:in=>[:pending, :waiting, :running, :error, :failed, :canceled, :successful], :message=>\"%{value} needs to be :pending, :waiting, :running, :error, :failed, :canceled, :successful\"}, allow_nil: true\n\n # @return [Object, nil] Page number of the results to fetch.\n attribute :page\n\n # @return [:yes, :no, nil] Fetch all the pages and return a single result.\n attribute :all_pages\n validates :all_pages, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Hash, nil] Query used to further filter the list of jobs. C({\"foo\":\"bar\"}) will be passed at C(?foo=bar)\n attribute :query\n validates :query, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6888349652290344, "alphanum_fraction": 0.6949514746665955, "avg_line_length": 70.03448486328125, "blob_id": "788b753afae370d27d4cf45b4850b72ee28a0b05", "content_id": "4d8ad7a2fc4fd60073f6ca5299442962a2fb38ec", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 10300, "license_type": "permissive", "max_line_length": 455, "num_lines": 145, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/rds.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates, deletes, or modifies rds instances. When creating an instance it can be either a new instance or a read-only replica of an existing instance. This module has a dependency on python-boto >= 2.5. The 'promote' command requires boto >= 2.18.0. Certain features such as tags rely on boto.rds2 (boto >= 2.26.0)\n class Rds < Base\n # @return [:create, :replicate, :delete, :facts, :modify, :promote, :snapshot, :reboot, :restore] Specifies the action to take. The 'reboot' option is available starting at version 2.0\n attribute :command\n validates :command, presence: true, expression_inclusion: {:in=>[:create, :replicate, :delete, :facts, :modify, :promote, :snapshot, :reboot, :restore], :message=>\"%{value} needs to be :create, :replicate, :delete, :facts, :modify, :promote, :snapshot, :reboot, :restore\"}\n\n # @return [String, nil] Database instance identifier. Required except when using command=facts or command=delete on just a snapshot\n attribute :instance_name\n validates :instance_name, type: String\n\n # @return [String, nil] Name of the database to replicate. Used only when command=replicate.\n attribute :source_instance\n validates :source_instance, type: String\n\n # @return [:mariadb, :MySQL, :\"oracle-se1\", :\"oracle-se2\", :\"oracle-se\", :\"oracle-ee\", :\"sqlserver-ee\", :\"sqlserver-se\", :\"sqlserver-ex\", :\"sqlserver-web\", :postgres, :aurora, nil] The type of database. Used only when command=create.,mariadb was added in version 2.2\n attribute :db_engine\n validates :db_engine, expression_inclusion: {:in=>[:mariadb, :MySQL, :\"oracle-se1\", :\"oracle-se2\", :\"oracle-se\", :\"oracle-ee\", :\"sqlserver-ee\", :\"sqlserver-se\", :\"sqlserver-ex\", :\"sqlserver-web\", :postgres, :aurora], :message=>\"%{value} needs to be :mariadb, :MySQL, :\\\"oracle-se1\\\", :\\\"oracle-se2\\\", :\\\"oracle-se\\\", :\\\"oracle-ee\\\", :\\\"sqlserver-ee\\\", :\\\"sqlserver-se\\\", :\\\"sqlserver-ex\\\", :\\\"sqlserver-web\\\", :postgres, :aurora\"}, allow_nil: true\n\n # @return [Integer, nil] Size in gigabytes of the initial storage for the DB instance. Used only when command=create or command=modify.\n attribute :size\n validates :size, type: Integer\n\n # @return [String, nil] The instance type of the database. Must be specified when command=create. Optional when command=replicate, command=modify or command=restore. If not specified then the replica inherits the same instance type as the source instance.\n attribute :instance_type\n validates :instance_type, type: String\n\n # @return [String, nil] Master database username. Used only when command=create.\n attribute :username\n validates :username, type: String\n\n # @return [String, nil] Password for the master database username. Used only when command=create or command=modify.\n attribute :password\n validates :password, type: String\n\n # @return [String] The AWS region to use. If not specified then the value of the EC2_REGION environment variable, if any, is used.\n attribute :region\n validates :region, presence: true, type: String\n\n # @return [Object, nil] Name of a database to create within the instance. If not specified then no database is created. Used only when command=create.\n attribute :db_name\n\n # @return [Object, nil] Version number of the database engine to use. Used only when command=create. If not specified then the current Amazon RDS default engine version is used\n attribute :engine_version\n\n # @return [Object, nil] Name of the DB parameter group to associate with this instance. If omitted then the RDS default DBParameterGroup will be used. Used only when command=create or command=modify.\n attribute :parameter_group\n\n # @return [:\"license-included\", :\"bring-your-own-license\", :\"general-public-license\", :\"postgresql-license\", nil] The license model for this DB instance. Used only when command=create or command=restore.\n attribute :license_model\n validates :license_model, expression_inclusion: {:in=>[:\"license-included\", :\"bring-your-own-license\", :\"general-public-license\", :\"postgresql-license\"], :message=>\"%{value} needs to be :\\\"license-included\\\", :\\\"bring-your-own-license\\\", :\\\"general-public-license\\\", :\\\"postgresql-license\\\"\"}, allow_nil: true\n\n # @return [Symbol, nil] Specifies if this is a Multi-availability-zone deployment. Can not be used in conjunction with zone parameter. Used only when command=create or command=modify.\n attribute :multi_zone\n validates :multi_zone, type: Symbol\n\n # @return [Object, nil] Specifies the number of IOPS for the instance. Used only when command=create or command=modify. Must be an integer greater than 1000.\n attribute :iops\n\n # @return [Object, nil] Comma separated list of one or more security groups. Used only when command=create or command=modify.\n attribute :security_groups\n\n # @return [String, nil] Comma separated list of one or more vpc security group ids. Also requires `subnet` to be specified. Used only when command=create or command=modify.\n attribute :vpc_security_groups\n validates :vpc_security_groups, type: String\n\n # @return [Integer, nil] Port number that the DB instance uses for connections. Used only when command=create or command=replicate.,Prior to 2.0 it always defaults to null and the API would use 3306, it had to be set to other DB default values when not using MySql. Starting at 2.0 it automatically defaults to what is expected for each C(db_engine).\n attribute :port\n validates :port, type: Integer\n\n # @return [:yes, :no, nil] Indicates that minor version upgrades should be applied automatically. Used only when command=create or command=replicate.\n attribute :upgrade\n validates :upgrade, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] The name of the option group to use. If not specified then the default option group is used. Used only when command=create.\n attribute :option_group\n\n # @return [Object, nil] Maintenance window in format of ddd:hh24:mi-ddd:hh24:mi. (Example: Mon:22:00-Mon:23:15) If not specified then a random maintenance window is assigned. Used only when command=create or command=modify.\\r\\n\n attribute :maint_window\n\n # @return [Object, nil] Backup window in format of hh24:mi-hh24:mi. If not specified then a random backup window is assigned. Used only when command=create or command=modify.\n attribute :backup_window\n\n # @return [Object, nil] Number of days backups are retained. Set to 0 to disable backups. Default is 1 day. Valid range: 0-35. Used only when command=create or command=modify.\\r\\n\n attribute :backup_retention\n\n # @return [String, nil] availability zone in which to launch the instance. Used only when command=create, command=replicate or command=restore.\n attribute :zone\n validates :zone, type: String\n\n # @return [String, nil] VPC subnet group. If specified then a VPC instance is created. Used only when command=create.\n attribute :subnet\n validates :subnet, type: String\n\n # @return [String, nil] Name of snapshot to take. When command=delete, if no snapshot name is provided then no snapshot is taken. If used with command=delete with no instance_name, the snapshot is deleted. Used with command=facts, command=delete or command=snapshot.\n attribute :snapshot\n validates :snapshot, type: String\n\n # @return [Object, nil] AWS secret key. If not set then the value of the AWS_SECRET_KEY environment variable is used.\n attribute :aws_secret_key\n\n # @return [Object, nil] AWS access key. If not set then the value of the AWS_ACCESS_KEY environment variable is used.\n attribute :aws_access_key\n\n # @return [:yes, :no, nil] When command=create, replicate, modify or restore then wait for the database to enter the 'available' state. When command=delete wait for the database to be terminated.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] how long before wait gives up, in seconds\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [:yes, :no, nil] Used only when command=modify. If enabled, the modifications will be applied as soon as possible rather than waiting for the next preferred maintenance window.\n attribute :apply_immediately\n validates :apply_immediately, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Used only when command=reboot. If enabled, the reboot is done using a MultiAZ failover.\n attribute :force_failover\n validates :force_failover, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Name to rename an instance to. Used only when command=modify.\n attribute :new_instance_name\n validates :new_instance_name, type: String\n\n # @return [Object, nil] Associate the DB instance with a specified character set. Used with command=create.\n attribute :character_set_name\n\n # @return [Boolean, nil] explicitly set whether the resource should be publicly accessible or not. Used with command=create, command=replicate. Requires boto >= 2.26.0\n attribute :publicly_accessible\n validates :publicly_accessible, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Hash, nil] tags dict to apply to a resource. Used with command=create, command=replicate, command=restore. Requires boto >= 2.26.0\n attribute :tags\n validates :tags, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7290583252906799, "alphanum_fraction": 0.7290583252906799, "avg_line_length": 79.51162719726562, "blob_id": "7838d3968e53f956f6c2640be4740740de50b159", "content_id": "164d29ff1dcef3b1a085af2890f1b367f187516e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3462, "license_type": "permissive", "max_line_length": 477, "num_lines": 43, "path": "/lib/ansible/ruby/modules/generated/windows/win_audit_rule.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Used to apply audit rules to files, folders or registry keys.\n # Once applied, it will begin recording the user who performed the operation defined into the Security Log in the Event viewer.\n # The behavior is designed to ignore inherited rules since those cannot be adjusted without first disabling the inheritance behavior. It will still print inherited rules in the output though for debugging purposes.\n class Win_audit_rule < Base\n # @return [String] Path to the file, folder, or registry key.,Registry paths should be in Powershell format, beginning with an abbreviation for the root such as, 'hklm:\\software'.\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [String] The user or group to adjust rules for.\n attribute :user\n validates :user, presence: true, type: String\n\n # @return [Array<String>, String] Comma separated list of the rights desired. Only required for adding a rule.,If I(path) is a file or directory, rights can be any right under MSDN FileSystemRights U(https://msdn.microsoft.com/en-us/library/system.security.accesscontrol.filesystemrights.aspx).,If I(path) is a registry key, rights can be any right under MSDN RegistryRights U(https://msdn.microsoft.com/en-us/library/system.security.accesscontrol.registryrights.aspx).\n attribute :rights\n validates :rights, presence: true, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] Defines what objects inside of a folder or registry key will inherit the settings.,If you are setting a rule on a file, this value has to be changed to C(none).,For more information on the choices see MSDN PropagationFlags enumeration at U(https://msdn.microsoft.com/en-us/library/system.security.accesscontrol.inheritanceflags.aspx).\n attribute :inheritance_flags\n validates :inheritance_flags, type: TypeGeneric.new(String)\n\n # @return [:None, :InherityOnly, :NoPropagateInherit, nil] Propagation flag on the audit rules.,This value is ignored when the path type is a file.,For more information on the choices see MSDN PropagationFlags enumeration at U(https://msdn.microsoft.com/en-us/library/system.security.accesscontrol.propagationflags.aspx).\n attribute :propagation_flags\n validates :propagation_flags, expression_inclusion: {:in=>[:None, :InherityOnly, :NoPropagateInherit], :message=>\"%{value} needs to be :None, :InherityOnly, :NoPropagateInherit\"}, allow_nil: true\n\n # @return [:Failure, :Success] Defines whether to log on failure, success, or both.,To log both define as comma separated list \"Success, Failure\".\n attribute :audit_flags\n validates :audit_flags, presence: true, expression_inclusion: {:in=>[:Failure, :Success], :message=>\"%{value} needs to be :Failure, :Success\"}\n\n # @return [:absent, :present, nil] Whether the rule should be C(present) or C(absent).,For absent, only I(path), I(user), and I(state) are required.,Specifying C(absent) will remove all rules matching the defined I(user).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6951388716697693, "alphanum_fraction": 0.6951388716697693, "avg_line_length": 42.6363639831543, "blob_id": "64afa7af3106f4e145fe3288ca699cd0890f853a", "content_id": "d1d3f7d4a66cc44a1d09b6f85344766f06932137", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1440, "license_type": "permissive", "max_line_length": 264, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_ironic_inspect.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Requests Ironic to set a node into inspect state in order to collect metadata regarding the node. This command may be out of band or in-band depending on the ironic driver configuration. This is only possible on nodes in 'manageable' and 'available' state.\n class Os_ironic_inspect < Base\n # @return [Object, nil] unique mac address that is used to attempt to identify the host.\n attribute :mac\n\n # @return [Object, nil] globally unique identifier (UUID) to identify the host.\n attribute :uuid\n\n # @return [String, nil] unique name identifier to identify the host in Ironic.\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] If noauth mode is utilized, this is required to be set to the endpoint URL for the Ironic API. Use with \"auth\" and \"auth_type\" settings set to None.\n attribute :ironic_url\n\n # @return [Integer, nil] A timeout in seconds to tell the role to wait for the node to complete introspection if wait is set to True.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7027955055236816, "alphanum_fraction": 0.7027955055236816, "avg_line_length": 55.63888931274414, "blob_id": "40c7f5b3e0b15faca1f4e68070a9b4c3fedcd96b", "content_id": "5791576a710bf7ec93d9182a4d4d96b989060457", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2039, "license_type": "permissive", "max_line_length": 312, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_firewall_dos_profile.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages AFM Denial of Service (DoS) profiles on a BIG-IP. To manage the vectors associated with a DoS profile, refer to the C(bigip_firewall_dos_vector) module.\n class Bigip_firewall_dos_profile < Base\n # @return [String] Specifies the name of the profile.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The description of the DoS profile.\n attribute :description\n validates :description, type: String\n\n # @return [Object, nil] The default whitelist address list for the system to use to determine which IP addresses are legitimate.,The system does not examine traffic from the IP addresses in the list when performing DoS prevention.,To define a new whitelist, use the C(bigip_firewall_address_list) module.\n attribute :default_whitelist\n\n # @return [:low, :medium, :high, nil] Specifies the threshold sensitivity for the DoS profile.,Thresholds for detecting attacks are higher when sensitivity is C(low), and lower when sensitivity is C(high).,When creating a new profile, if this parameter is not specified, the default is C(medium).\n attribute :threshold_sensitivity\n validates :threshold_sensitivity, expression_inclusion: {:in=>[:low, :medium, :high], :message=>\"%{value} needs to be :low, :medium, :high\"}, allow_nil: true\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [:present, :absent, nil] When C(present), ensures that the resource exists.,When C(absent), ensures the resource is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6829599738121033, "alphanum_fraction": 0.6829599738121033, "avg_line_length": 42.32352828979492, "blob_id": "655de9ca427805f1db49f714bfd1970e105aa622", "content_id": "44e3e75e7c04840d47acd3a2648d85093a08d504", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1473, "license_type": "permissive", "max_line_length": 218, "num_lines": 34, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_maintenancemode.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used for placing a ESXi host into maintenance mode.\n # Support for VSAN compliant maintenance mode when selected.\n class Vmware_maintenancemode < Base\n # @return [String] Name of the host as defined in vCenter.\n attribute :esxi_hostname\n validates :esxi_hostname, presence: true, type: String\n\n # @return [:ensureObjectAccessibility, :evacuateAllData, :noAction, nil] Specify which VSAN compliant mode to enter.\n attribute :vsan\n validates :vsan, expression_inclusion: {:in=>[:ensureObjectAccessibility, :evacuateAllData, :noAction], :message=>\"%{value} needs to be :ensureObjectAccessibility, :evacuateAllData, :noAction\"}, allow_nil: true\n\n # @return [Symbol, nil] If set to C(True), evacuate all powered off VMs.\n attribute :evacuate\n validates :evacuate, type: Symbol\n\n # @return [Integer, nil] Specify a timeout for the operation.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [:present, :absent, nil] Enter or exit maintenance mode.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6722933650016785, "alphanum_fraction": 0.6740396022796631, "avg_line_length": 43.0512809753418, "blob_id": "d8b01d924394bff0264b42ec193c8d3253e3ab26", "content_id": "d02b0c0d7bf877df49e940f7e3120be51fb778d4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1718, "license_type": "permissive", "max_line_length": 176, "num_lines": 39, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_user_role.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Grant and revoke roles in either project or domain context for OpenStack Identity Users.\n class Os_user_role < Base\n # @return [String] Name or ID for the role.\n attribute :role\n validates :role, presence: true, type: String\n\n # @return [String, nil] Name or ID for the user. If I(user) is not specified, then I(group) is required. Both may not be specified.\n attribute :user\n validates :user, type: String\n\n # @return [Object, nil] Name or ID for the group. Valid only with keystone version 3. If I(group) is not specified, then I(user) is required. Both may not be specified.\n attribute :group\n\n # @return [String, nil] Name or ID of the project to scope the role association to. If you are using keystone version 2, then this value is required.\n attribute :project\n validates :project, type: String\n\n # @return [String, nil] ID of the domain to scope the role association to. Valid only with keystone version 3, and required if I(project) is not specified.\n attribute :domain\n validates :domain, type: String\n\n # @return [:present, :absent, nil] Should the roles be present or absent on the user.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6639935970306396, "alphanum_fraction": 0.6639935970306396, "avg_line_length": 36.787879943847656, "blob_id": "861b14ecd4bb3f8df7bc786bb57b37a43c4524d6", "content_id": "31fdf13de4d3c7016ff03c842972c44e3eb9bee8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1247, "license_type": "permissive", "max_line_length": 143, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/network/onyx/onyx_mlag_vip.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of MLAG virtual IPs on Mellanox ONYX network devices.\n class Onyx_mlag_vip < Base\n # @return [String, nil] Virtual IP address of the MLAG. Required if I(state=present).\n attribute :ipaddress\n validates :ipaddress, type: String\n\n # @return [String, nil] MLAG group name. Required if I(state=present).\n attribute :group_name\n validates :group_name, type: String\n\n # @return [String, nil] MLAG system MAC address. Required if I(state=present).\n attribute :mac_address\n validates :mac_address, type: String\n\n # @return [:present, :absent, nil] MLAG VIP state.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Integer, nil] Delay interval, in seconds, waiting for the changes on mlag VIP to take effect.\n attribute :delay\n validates :delay, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6763717532157898, "alphanum_fraction": 0.6763717532157898, "avg_line_length": 34.720001220703125, "blob_id": "da27365af49a96b48e60c05e632c5c2cf3b692cf", "content_id": "0badda59878dea79a599e65bfee940cbc92602a0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 893, "license_type": "permissive", "max_line_length": 143, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/network/illumos/dladm_etherstub.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or delete etherstubs on Solaris/illumos systems.\n class Dladm_etherstub < Base\n # @return [String] Etherstub name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Symbol, nil] Specifies that the etherstub is temporary. Temporary etherstubs do not persist across reboots.\n attribute :temporary\n validates :temporary, type: Symbol\n\n # @return [:present, :absent, nil] Create or delete Solaris/illumos etherstub.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6633166074752808, "alphanum_fraction": 0.6934673190116882, "avg_line_length": 21.11111068725586, "blob_id": "6e112c8dd350ceaf97bdcd477925f68448f04653", "content_id": "ff468d76c263bf62d270b2dac39287b7c24ea43d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 199, "license_type": "permissive", "max_line_length": 45, "num_lines": 9, "path": "/Gemfile", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\nsource 'https://rubygems.org'\ngemspec\n\ngem 'rspec'\ngem 'rake'\ngem 'rubocop', '0.69', require: false\ngem 'reek', '~> 5.4.0'\ngem 'codeclimate-test-reporter', require: nil\n" }, { "alpha_fraction": 0.7400029897689819, "alphanum_fraction": 0.7400029897689819, "avg_line_length": 99.40298461914062, "blob_id": "3feb3fea23f61af915b31cd12ccacc21d65c7b40", "content_id": "ebf3cc760df0bbe3b482d6d30f1075e1ce81cb84", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6727, "license_type": "permissive", "max_line_length": 818, "num_lines": 67, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_profile_dns.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage DNS profiles on a BIG-IP. Many DNS profiles; each with their own adjustments to the standard C(dns) profile. Users of this module should be aware that many of the adjustable knobs have no module default. Instead, the default is assigned by the BIG-IP system itself which, in most cases, is acceptable.\n class Bigip_profile_dns < Base\n # @return [String] Specifies the name of the DNS profile.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Specifies the profile from which this profile inherits settings.,When creating a new profile, if this parameter is not specified, the default is the system-supplied C(dns) profile.\n attribute :parent\n\n # @return [Symbol, nil] Specifies whether the DNS Express engine is enabled.,When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.,The DNS Express engine receives zone transfers from the authoritative DNS server for the zone. If the C(enable_zone_transfer) setting is also C(yes) on this profile, the DNS Express engine also responds to zone transfer requests made by the nameservers configured as zone transfer clients for the DNS Express zone.\n attribute :enable_dns_express\n validates :enable_dns_express, type: Symbol\n\n # @return [Symbol, nil] Specifies whether the system answers zone transfer requests for a DNS zone created on the system.,When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.,The C(enable_dns_express) and C(enable_zone_transfer) settings on a DNS profile affect how the system responds to zone transfer requests.,When the C(enable_dns_express) and C(enable_zone_transfer) settings are both C(yes), if a zone transfer request matches a DNS Express zone, then DNS Express answers the request.,When the C(enable_dns_express) setting is C(no) and the C(enable_zone_transfer) setting is C(yes), the BIG-IP system processes zone transfer requests based on the last action and answers the request from local BIND or a pool member.\n attribute :enable_zone_transfer\n validates :enable_zone_transfer, type: Symbol\n\n # @return [Symbol, nil] Specifies whether the system signs responses with DNSSEC keys and replies to DNSSEC specific queries (e.g., DNSKEY query type).,When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.\n attribute :enable_dnssec\n validates :enable_dnssec, type: Symbol\n\n # @return [Symbol, nil] Specifies whether the system uses Global Traffic Manager to manage the response.,When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.\n attribute :enable_gtm\n validates :enable_gtm, type: Symbol\n\n # @return [Symbol, nil] Specifies whether to process client-side DNS packets with Recursion Desired set in the header.,When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.,If set to C(no), processing of the packet is subject to the unhandled-query-action option.\n attribute :process_recursion_desired\n validates :process_recursion_desired, type: Symbol\n\n # @return [Symbol, nil] Specifies whether the system forwards non-wide IP queries to the local BIND server on the BIG-IP system.,For best performance, disable this setting when using a DNS cache.,When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.\n attribute :use_local_bind\n validates :use_local_bind, type: Symbol\n\n # @return [Symbol, nil] Specifies whether DNS firewall capability is enabled.,When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.\n attribute :enable_dns_firewall\n validates :enable_dns_firewall, type: Symbol\n\n # @return [Symbol, nil] Specifies whether the system caches DNS responses.,When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.,When C(yes), the BIG-IP system caches DNS responses handled by the virtual servers associated with this profile. When you enable this setting, you must also specify a value for C(cache_name).,When C(no), the BIG-IP system does not cache DNS responses handled by the virtual servers associated with this profile. However, the profile retains the association with the DNS cache in the C(cache_name) parameter. Disable this setting when you want to debug the system.\n attribute :enable_cache\n validates :enable_cache, type: Symbol\n\n # @return [Object, nil] Specifies the user-created cache that the system uses to cache DNS responses.,When you select a cache for the system to use, you must also set C(enable_dns_cache) to C(yes)\n attribute :cache_name\n\n # @return [:allow, :drop, :reject, :hint, :\"no-error\", nil] Specifies the action to take when a query does not match a Wide IP or a DNS Express Zone.,When C(allow), the BIG-IP system forwards queries to a DNS server or pool member. If a pool is not associated with a listener and the Use BIND Server on BIG-IP setting is set to Enabled, requests are forwarded to the local BIND server.,When C(drop), the BIG-IP system does not respond to the query.,When C(reject), the BIG-IP system returns the query with the REFUSED return code.,When C(hint), the BIG-IP system returns the query with a list of root name servers.,When C(no-error), the BIG-IP system returns the query with the NOERROR return code.,When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.\n attribute :unhandled_query_action\n validates :unhandled_query_action, expression_inclusion: {:in=>[:allow, :drop, :reject, :hint, :\"no-error\"], :message=>\"%{value} needs to be :allow, :drop, :reject, :hint, :\\\"no-error\\\"\"}, allow_nil: true\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [:present, :absent, nil] When C(present), ensures that the profile exists.,When C(absent), ensures the profile is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7438603043556213, "alphanum_fraction": 0.7473167181015015, "avg_line_length": 92.16949462890625, "blob_id": "abc90499163f62a992981b178de9ab037f7c7d85", "content_id": "19b5bc5260c18f23918819462adbafe11877034a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5497, "license_type": "permissive", "max_line_length": 847, "num_lines": 59, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_compute_disk.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Persistent disks are durable storage devices that function similarly to the physical disks in a desktop or a server. Compute Engine manages the hardware behind these devices to ensure data redundancy and optimize performance for you. Persistent disks are available as either standard hard disk drives (HDD) or solid-state drives (SSD).\n # Persistent disks are located independently from your virtual machine instances, so you can detach or move persistent disks to keep your data even after you delete your instances. Persistent disk performance scales automatically with size, so you can resize your existing persistent disks or add more persistent disks to an instance to meet your performance and storage space requirements.\n # Add a persistent disk to your instance when you need reliable and affordable storage with consistent performance characteristics.\n class Gcp_compute_disk < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] An optional description of this resource. Provide this property when you create the resource.\n attribute :description\n\n # @return [Object, nil] Labels to apply to this disk. A list of key->value pairs.\n attribute :labels\n\n # @return [Object, nil] Any applicable publicly visible licenses.\n attribute :licenses\n\n # @return [String] Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Integer, nil] Size of the persistent disk, specified in GB. You can specify this field when creating a persistent disk using the sourceImage or sourceSnapshot parameter, or specify it alone to create an empty persistent disk.,If you specify this field along with sourceImage or sourceSnapshot, the value of sizeGb must not be less than the size of the sourceImage or the size of the snapshot.\n attribute :size_gb\n validates :size_gb, type: Integer\n\n # @return [Object, nil] URL of the disk type resource describing which disk type to use to create the disk. Provide this when creating the disk.\n attribute :type\n\n # @return [Object, nil] The source image used to create this disk. If the source image is deleted, this field will not be set.,To create a disk with one of the public operating system images, specify the image by its family name. For example, specify family/debian-8 to use the latest Debian 8 image: projects/debian-cloud/global/images/family/debian-8 Alternatively, use a specific version of a public operating system image: projects/debian-cloud/global/images/debian-8-jessie-vYYYYMMDD To create a disk with a private image that you created, specify the image name in the following format: global/images/my-private-image You can also specify a private image by its image family, which returns the latest version of the image in that family. Replace the image name with family/family-name: global/images/family/my-private-family .\n attribute :source_image\n\n # @return [String] A reference to the zone where the disk resides.\n attribute :zone\n validates :zone, presence: true, type: String\n\n # @return [Object, nil] The customer-supplied encryption key of the source image. Required if the source image is protected by a customer-supplied encryption key.\n attribute :source_image_encryption_key\n\n # @return [Hash, nil] Encrypts the disk using a customer-supplied encryption key.,After you encrypt a disk with a customer-supplied key, you must provide the same key if you use the disk later (e.g. to create a disk snapshot or an image, or to attach the disk to a virtual machine).,Customer-supplied encryption keys do not protect access to metadata of the disk.,If you do not provide an encryption key when creating the disk, then the disk will be encrypted using an automatically generated key and you do not need to provide a key to use the disk later.\n attribute :disk_encryption_key\n validates :disk_encryption_key, type: Hash\n\n # @return [Object, nil] The source snapshot used to create this disk. You can provide this as a partial or full URL to the resource. For example, the following are valid values: * `U(https://www.googleapis.com/compute/v1/projects/project/global/snapshots/snapshot`) * `projects/project/global/snapshots/snapshot` * `global/snapshots/snapshot` .\n attribute :source_snapshot\n\n # @return [Object, nil] The customer-supplied encryption key of the source snapshot. Required if the source snapshot is protected by a customer-supplied encryption key.\n attribute :source_snapshot_encryption_key\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6909871101379395, "alphanum_fraction": 0.7011987566947937, "avg_line_length": 65.2450942993164, "blob_id": "17d44cef249c59b9711c587e95d62bb5764ff41b", "content_id": "2087898d4426cf2f47c11966207f66513d11b0b2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6757, "license_type": "permissive", "max_line_length": 630, "num_lines": 102, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/elb_target_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage an AWS Elastic Load Balancer target group. See U(http://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-target-groups.html) or U(http://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-target-groups.html) for details.\n class Elb_target_group < Base\n # @return [Object, nil] The amount time for Elastic Load Balancing to wait before changing the state of a deregistering target from draining to unused. The range is 0-3600 seconds.\n attribute :deregistration_delay_timeout\n\n # @return [:http, :https, :tcp, nil] The protocol the load balancer uses when performing health checks on targets.\n attribute :health_check_protocol\n validates :health_check_protocol, expression_inclusion: {:in=>[:http, :https, :tcp], :message=>\"%{value} needs to be :http, :https, :tcp\"}, allow_nil: true\n\n # @return [String, nil] The port the load balancer uses when performing health checks on targets. Can be set to 'traffic-port' to match target port.\n attribute :health_check_port\n validates :health_check_port, type: String\n\n # @return [String, nil] The ping path that is the destination on the targets for health checks. The path must be defined in order to set a health check.\n attribute :health_check_path\n validates :health_check_path, type: String\n\n # @return [Object, nil] The approximate amount of time, in seconds, between health checks of an individual target.\n attribute :health_check_interval\n\n # @return [Object, nil] The amount of time, in seconds, during which no response from a target means a failed health check.\n attribute :health_check_timeout\n\n # @return [Object, nil] The number of consecutive health checks successes required before considering an unhealthy target healthy.\n attribute :healthy_threshold_count\n\n # @return [Boolean, nil] Whether or not to alter existing targets in the group to match what is passed with the module\n attribute :modify_targets\n validates :modify_targets, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String] The name of the target group.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Integer, nil] The port on which the targets receive traffic. This port is used unless you specify a port override when registering the target. Required if I(state) is C(present).\n attribute :port\n validates :port, type: Integer\n\n # @return [:http, :https, :tcp, nil] The protocol to use for routing traffic to the targets. Required when I(state) is C(present).\n attribute :protocol\n validates :protocol, expression_inclusion: {:in=>[:http, :https, :tcp], :message=>\"%{value} needs to be :http, :https, :tcp\"}, allow_nil: true\n\n # @return [Boolean, nil] If yes, existing tags will be purged from the resource to match exactly what is defined by I(tags) parameter. If the tag parameter is not set then tags will not be modified.\n attribute :purge_tags\n validates :purge_tags, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:present, :absent] Create or destroy the target group.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [Symbol, nil] Indicates whether sticky sessions are enabled.\n attribute :stickiness_enabled\n validates :stickiness_enabled, type: Symbol\n\n # @return [Object, nil] The time period, in seconds, during which requests from a client should be routed to the same target. After this time period expires, the load balancer-generated cookie is considered stale. The range is 1 second to 1 week (604800 seconds).\n attribute :stickiness_lb_cookie_duration\n\n # @return [String, nil] The type of sticky sessions. The possible value is lb_cookie.\n attribute :stickiness_type\n validates :stickiness_type, type: String\n\n # @return [Array<Integer>, Integer, nil] The HTTP codes to use when checking for a successful response from a target. You can specify multiple values (for example, \"200,202\") or a range of values (for example, \"200-299\").\n attribute :successful_response_codes\n validates :successful_response_codes, type: TypeGeneric.new(Integer)\n\n # @return [Object, nil] A dictionary of one or more tags to assign to the target group.\n attribute :tags\n\n # @return [:instance, :ip, nil] The type of target that you must specify when registering targets with this target group. The possible values are C(instance) (targets are specified by instance ID) or C(ip) (targets are specified by IP address). Note that you can't specify targets for a target group using both instance IDs and IP addresses. If the target type is ip, specify IP addresses from the subnets of the virtual private cloud (VPC) for the target group, the RFC 1918 range (10.0.0.0/8, 172.16.0.0/12, and 192.168.0.0/16), and the RFC 6598 range (100.64.0.0/10). You can't specify publicly routable IP addresses.\n attribute :target_type\n validates :target_type, expression_inclusion: {:in=>[:instance, :ip], :message=>\"%{value} needs to be :instance, :ip\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash, nil] A list of targets to assign to the target group. This parameter defaults to an empty list. Unless you set the 'modify_targets' parameter then all existing targets will be removed from the group. The list should be an Id and a Port parameter. See the Examples for detail.\n attribute :targets\n validates :targets, type: TypeGeneric.new(Hash)\n\n # @return [Object, nil] The number of consecutive health check failures required before considering a target unhealthy.\n attribute :unhealthy_threshold_count\n\n # @return [String, nil] The identifier of the virtual private cloud (VPC). Required when I(state) is C(present).\n attribute :vpc_id\n validates :vpc_id, type: String\n\n # @return [Symbol, nil] Whether or not to wait for the target group.\n attribute :wait\n validates :wait, type: Symbol\n\n # @return [Integer, nil] The time to wait for the target group.\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6990291476249695, "alphanum_fraction": 0.6990291476249695, "avg_line_length": 56.01785659790039, "blob_id": "d48edac674cbe836d1bed5808fb8518894f6e5c1", "content_id": "8b4c0200dbd25aee20b4ae5a3bad549a67b7f235", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3193, "license_type": "permissive", "max_line_length": 259, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/network/radware/vdirect_file.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Uploads a new or updates an existing configuration template or workflow template into the Radware vDirect server. All parameters may be set as environment variables.\n class Vdirect_file < Base\n # @return [String] Primary vDirect server IP address, may be set as VDIRECT_IP environment variable.\n attribute :vdirect_ip\n validates :vdirect_ip, presence: true, type: String\n\n # @return [String] vDirect server username, may be set as VDIRECT_USER environment variable.\n attribute :vdirect_user\n validates :vdirect_user, presence: true, type: String\n\n # @return [String] vDirect server password, may be set as VDIRECT_PASSWORD environment variable.\n attribute :vdirect_password\n validates :vdirect_password, presence: true, type: String\n\n # @return [Object, nil] Secondary vDirect server IP address, may be set as VDIRECT_SECONDARY_IP environment variable.\n attribute :vdirect_secondary_ip\n\n # @return [:yes, :no, nil] Wait for async operation to complete, may be set as VDIRECT_WAIT environment variable.\n attribute :vdirect_wait\n validates :vdirect_wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] vDirect server HTTPS port number, may be set as VDIRECT_HTTPS_PORT environment variable.\n attribute :vdirect_https_port\n validates :vdirect_https_port, type: Integer\n\n # @return [Integer, nil] vDirect server HTTP port number, may be set as VDIRECT_HTTP_PORT environment variable.\n attribute :vdirect_http_port\n validates :vdirect_http_port, type: Integer\n\n # @return [Integer, nil] Amount of time to wait for async operation completion [seconds],,may be set as VDIRECT_TIMEOUT environment variable.\n attribute :vdirect_timeout\n validates :vdirect_timeout, type: Integer\n\n # @return [:yes, :no, nil] If C(no), an HTTP connection will be used instead of the default HTTPS connection,,may be set as VDIRECT_HTTPS or VDIRECT_USE_SSL environment variable.\n attribute :vdirect_use_ssl\n validates :vdirect_use_ssl, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated,,may be set as VDIRECT_VALIDATE_CERTS or VDIRECT_VERIFY environment variable.,This should only set to C(no) used on personally controlled sites using self-signed certificates.\n attribute :vdirect_validate_certs\n validates :vdirect_validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String] vDirect runnable file name to be uploaded.,May be velocity configuration template (.vm) or workflow template zip file (.zip).\n attribute :file_name\n validates :file_name, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6606184244155884, "alphanum_fraction": 0.6608740091323853, "avg_line_length": 48.531646728515625, "blob_id": "b5819d7bc152fc2f68e4bf90fbba55016c3dceff", "content_id": "42610de1585635e10a1ea5a5a3fdd191641cf93c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3913, "license_type": "permissive", "max_line_length": 268, "num_lines": 79, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_iso.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Register and remove ISO images.\n class Cs_iso < Base\n # @return [String] Name of the ISO.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Display text of the ISO.,If not specified, C(name) will be used.\n attribute :display_text\n\n # @return [String, nil] URL where the ISO can be downloaded from. Required if C(state) is present.\n attribute :url\n validates :url, type: String\n\n # @return [String, nil] Name of the OS that best represents the OS of this ISO. If the iso is bootable this parameter needs to be passed. Required if C(state) is present.\n attribute :os_type\n validates :os_type, type: String\n\n # @return [Symbol, nil] This flag is used for searching existing ISOs. If set to C(yes), it will only list ISO ready for deployment e.g. successfully downloaded and installed. Recommended to set it to C(no).\n attribute :is_ready\n validates :is_ready, type: Symbol\n\n # @return [Object, nil] Register the ISO to be publicly available to all users. Only used if C(state) is present.\n attribute :is_public\n\n # @return [Object, nil] Register the ISO to be featured. Only used if C(state) is present.\n attribute :is_featured\n\n # @return [Object, nil] Register the ISO having XS/VMWare tools installed inorder to support dynamic scaling of VM cpu/memory. Only used if C(state) is present.\n attribute :is_dynamically_scalable\n\n # @return [String, nil] The MD5 checksum value of this ISO. If set, we search by checksum instead of name.\n attribute :checksum\n validates :checksum, type: String\n\n # @return [Object, nil] Register the ISO to be bootable. Only used if C(state) is present.\n attribute :bootable\n\n # @return [Object, nil] Domain the ISO is related to.\n attribute :domain\n\n # @return [Object, nil] Account the ISO is related to.\n attribute :account\n\n # @return [Object, nil] Name of the project the ISO to be registered in.\n attribute :project\n\n # @return [Object, nil] Name of the zone you wish the ISO to be registered or deleted from.,If not specified, first zone found will be used.\n attribute :zone\n\n # @return [:yes, :no, nil] Whether the ISO should be synced or removed across zones.,Mutually exclusive with C(zone).\n attribute :cross_zones\n validates :cross_zones, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:featured, :self, :selfexecutable, :sharedexecutable, :executable, :community, nil] Name of the filter used to search for the ISO.\n attribute :iso_filter\n validates :iso_filter, expression_inclusion: {:in=>[:featured, :self, :selfexecutable, :sharedexecutable, :executable, :community], :message=>\"%{value} needs to be :featured, :self, :selfexecutable, :sharedexecutable, :executable, :community\"}, allow_nil: true\n\n # @return [:present, :absent, nil] State of the ISO.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Poll async jobs until job has finished.\n attribute :poll_async\n validates :poll_async, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] List of tags. Tags are a list of dictionaries having keys C(key) and C(value).,To delete all tags, set a empty list e.g. C(tags: []).\n attribute :tags\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6726177930831909, "alphanum_fraction": 0.6757317781448364, "avg_line_length": 47.16999816894531, "blob_id": "f1aa19a6dbf06f63b07cbf6a198034ee79dde589", "content_id": "ab5d0a817c4d06047dd5b9e4d2e4385c58779499", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4817, "license_type": "permissive", "max_line_length": 329, "num_lines": 100, "path": "/lib/ansible/ruby/modules/generated/cloud/oneandone/oneandone_monitoring_policy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, remove, update monitoring policies (and add/remove ports, processes, and servers). This module has a dependency on 1and1 >= 1.0\n class Oneandone_monitoring_policy < Base\n # @return [:present, :absent, :update, nil] Define a monitoring policy's state to create, remove, update.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :update], :message=>\"%{value} needs to be :present, :absent, :update\"}, allow_nil: true\n\n # @return [String] Authenticating API token provided by 1&1.\n attribute :auth_token\n validates :auth_token, presence: true, type: String\n\n # @return [Object, nil] Custom API URL. Overrides the ONEANDONE_API_URL environement variable.\n attribute :api_url\n\n # @return [String] Monitoring policy name used with present state. Used as identifier (id or name) when used with absent state. maxLength=128\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] The identifier (id or name) of the monitoring policy used with update state.\n attribute :monitoring_policy\n validates :monitoring_policy, presence: true, type: String\n\n # @return [Boolean] Set true for using agent.\n attribute :agent\n validates :agent, presence: true, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}\n\n # @return [String] User's email. maxLength=128\n attribute :email\n validates :email, presence: true, type: String\n\n # @return [String, nil] Monitoring policy description. maxLength=256\n attribute :description\n validates :description, type: String\n\n # @return [Array<Hash>, Hash] Monitoring policy thresholds. Each of the suboptions have warning and critical, which both have alert and value suboptions. Warning is used to set limits for warning alerts, critical is used to set critical alerts. alert enables alert, and value is used to advise when the value is exceeded.\n attribute :thresholds\n validates :thresholds, presence: true, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash] Array of ports that will be monitoring.\n attribute :ports\n validates :ports, presence: true, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash] Array of processes that will be monitoring.\n attribute :processes\n validates :processes, presence: true, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash, nil] Ports to add to the monitoring policy.\n attribute :add_ports\n validates :add_ports, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash, nil] Processes to add to the monitoring policy.\n attribute :add_processes\n validates :add_processes, type: TypeGeneric.new(Hash)\n\n # @return [Array<String>, String, nil] Servers to add to the monitoring policy.\n attribute :add_servers\n validates :add_servers, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] Ports to remove from the monitoring policy.\n attribute :remove_ports\n validates :remove_ports, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] Processes to remove from the monitoring policy.\n attribute :remove_processes\n validates :remove_processes, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] Servers to remove from the monitoring policy.\n attribute :remove_servers\n validates :remove_servers, type: TypeGeneric.new(String)\n\n # @return [Array<Hash>, Hash, nil] Ports to be updated on the monitoring policy.\n attribute :update_ports\n validates :update_ports, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash, nil] Processes to be updated on the monitoring policy.\n attribute :update_processes\n validates :update_processes, type: TypeGeneric.new(Hash)\n\n # @return [:yes, :no, nil] wait for the instance to be in state 'running' before returning\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] how long before wait gives up, in seconds\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [Integer, nil] Defines the number of seconds to wait when using the _wait_for methods\n attribute :wait_interval\n validates :wait_interval, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.630940318107605, "alphanum_fraction": 0.6496461033821106, "avg_line_length": 42.9555549621582, "blob_id": "1d0d3af213aaf5568ff197116333644a0bfbabaa", "content_id": "8e91adde5146654c8d4c70b128cee6e4ca695670", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1978, "license_type": "permissive", "max_line_length": 194, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/cloud/rackspace/rax_cdb.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # creates / deletes or resize a Rackspace Cloud Databases instance and optionally waits for it to be 'running'. The name option needs to be unique since it's used to identify the instance.\n class Rax_cdb < Base\n # @return [String, nil] Name of the databases server instance\n attribute :name\n validates :name, type: String\n\n # @return [Integer, nil] flavor to use for the instance 1 to 6 (i.e. 512MB to 16GB)\n attribute :flavor\n validates :flavor, type: Integer\n\n # @return [Integer, nil] Volume size of the database 1-150GB\n attribute :volume\n validates :volume, type: Integer\n\n # @return [String, nil] type of instance (i.e. MySQL, MariaDB, Percona)\n attribute :cdb_type\n validates :cdb_type, type: String\n\n # @return [5.1, 5.6, 10, nil] version of database (MySQL supports 5.1 and 5.6, MariaDB supports 10, Percona supports 5.6)\n attribute :cdb_version\n validates :cdb_version, expression_inclusion: {:in=>[5.1, 5.6, 10], :message=>\"%{value} needs to be 5.1, 5.6, 10\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Indicate desired state of the resource\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:yes, :no, nil] wait for the instance to be in state 'running' before returning\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] how long before wait gives up, in seconds\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6733333468437195, "alphanum_fraction": 0.6733333468437195, "avg_line_length": 25.47058868408203, "blob_id": "67221922c1a6530668a68c11eeb82847b5280b27", "content_id": "c7b90ccdb746b927113ffd6770ed66f0c74ee2ca", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 450, "license_type": "permissive", "max_line_length": 70, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_waf_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Retrieve facts for WAF ACLs, Rule , Conditions and Filters.\n class Aws_waf_facts < Base\n # @return [String, nil] The name of a Web Application Firewall\n attribute :name\n validates :name, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.685055136680603, "alphanum_fraction": 0.685055136680603, "avg_line_length": 48.849998474121094, "blob_id": "5ab5b61d0b2c59ff90a954e345180ecbdaa96528", "content_id": "0e7c02f37f562acd24a6d8fa5c22d70780d9d185", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1994, "license_type": "permissive", "max_line_length": 341, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/gunicorn.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Starts gunicorn with the parameters specified. Common settings for gunicorn configuration are supported. For additional configuration use a config file See U(https://gunicorn-docs.readthedocs.io/en/latest/settings.html) for more options. It's recommended to always use the chdir option to avoid problems with the location of the app.\n class Gunicorn < Base\n # @return [String] The app module. A name refers to a WSGI callable that should be found in the specified module.\n attribute :app\n validates :app, presence: true, type: String\n\n # @return [String, nil] Path to the virtualenv directory.\n attribute :venv\n validates :venv, type: String\n\n # @return [Object, nil] Path to the gunicorn configuration file.\n attribute :config\n\n # @return [String, nil] Chdir to specified directory before apps loading.\n attribute :chdir\n validates :chdir, type: String\n\n # @return [String, nil] A filename to use for the PID file. If not set and not found on the configuration file a tmp pid file will be created to check a successful run of gunicorn.\n attribute :pid\n validates :pid, type: String\n\n # @return [:sync, :eventlet, :gevent, :\"tornado \", :gthread, :gaiohttp, nil] The type of workers to use. The default class (sync) should handle most \"normal\" types of workloads.\n attribute :worker\n validates :worker, expression_inclusion: {:in=>[:sync, :eventlet, :gevent, :\"tornado \", :gthread, :gaiohttp], :message=>\"%{value} needs to be :sync, :eventlet, :gevent, :\\\"tornado \\\", :gthread, :gaiohttp\"}, allow_nil: true\n\n # @return [String, nil] Switch worker processes to run as this user.\n attribute :user\n validates :user, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6614143252372742, "alphanum_fraction": 0.6667947769165039, "avg_line_length": 43.86206817626953, "blob_id": "9ad15bc577d1a9c84a66c288ce02f4f4f589a736", "content_id": "e4283e82769918df39fdeadcde57f4dc6992c288", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2602, "license_type": "permissive", "max_line_length": 225, "num_lines": 58, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_port.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add, Update or Remove ports from an OpenStack cloud. A I(state) of 'present' will ensure the port is created or updated if required.\n class Os_port < Base\n # @return [String] Network ID or name this port belongs to.\n attribute :network\n validates :network, presence: true, type: String\n\n # @return [String, nil] Name that has to be given to the port.\n attribute :name\n validates :name, type: String\n\n # @return [Array<Hash>, Hash, nil] Desired IP and/or subnet for this port. Subnet is referenced by subnet_id and IP is referenced by ip_address.\n attribute :fixed_ips\n validates :fixed_ips, type: TypeGeneric.new(Hash)\n\n # @return [Object, nil] Sets admin state.\n attribute :admin_state_up\n\n # @return [Object, nil] MAC address of this port.\n attribute :mac_address\n\n # @return [Array<String>, String, nil] Security group(s) ID(s) or name(s) associated with the port (comma separated string or YAML list)\n attribute :security_groups\n validates :security_groups, type: TypeGeneric.new(String)\n\n # @return [String, nil] Do not associate a security group with this port.\n attribute :no_security_groups\n validates :no_security_groups, type: String\n\n # @return [Object, nil] Allowed address pairs list. Allowed address pairs are supported with dictionary structure. e.g. allowed_address_pairs: - ip_address: 10.1.0.12 mac_address: ab:cd:ef:12:34:56 - ip_address: ...\n attribute :allowed_address_pairs\n\n # @return [Object, nil] Extra dhcp options to be assigned to this port. Extra options are supported with dictionary structure. e.g. extra_dhcp_opts: - opt_name: opt name1 opt_value: value1 - opt_name: ...\n attribute :extra_dhcp_opts\n\n # @return [Object, nil] The ID of the entity that uses this port.\n attribute :device_owner\n\n # @return [Object, nil] Device ID of device using this port.\n attribute :device_id\n\n # @return [:present, :absent, nil] Should the resource be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6650442481040955, "alphanum_fraction": 0.672123908996582, "avg_line_length": 44.20000076293945, "blob_id": "f43444b6147cf58597816339d793ed3adb660b4a", "content_id": "b6911b3f6bcbb366f7e727272c14612b5dff793d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2260, "license_type": "permissive", "max_line_length": 270, "num_lines": 50, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_quotas.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Module to manage datacenter quotas in oVirt/RHV\n class Ovirt_quota < Base\n # @return [String] Name of the quota to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Should the quota be present/absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] Name of the datacenter where quota should be managed.\n attribute :data_center\n validates :data_center, presence: true, type: String\n\n # @return [Object, nil] Description of the quota to manage.\n attribute :description\n\n # @return [Object, nil] Cluster threshold(soft limit) defined in percentage (0-100).\n attribute :cluster_threshold\n\n # @return [Object, nil] Cluster grace(hard limit) defined in percentage (1-100).\n attribute :cluster_grace\n\n # @return [Integer, nil] Storage threshold(soft limit) defined in percentage (0-100).\n attribute :storage_threshold\n validates :storage_threshold, type: Integer\n\n # @return [Integer, nil] Storage grace(hard limit) defined in percentage (1-100).\n attribute :storage_grace\n validates :storage_grace, type: Integer\n\n # @return [Array<Hash>, Hash, nil] List of dictionary of cluster limits, which is valid to specific cluster.,If cluster isn't specified it's valid to all clusters in system:,C(cluster) - Name of the cluster.,C(memory) - Memory limit (in GiB).,C(cpu) - CPU limit.\n attribute :clusters\n validates :clusters, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash, nil] List of dictionary of storage limits, which is valid to specific storage.,If storage isn't specified it's valid to all storages in system:,C(storage) - Name of the storage.,C(size) - Size limit (in GiB).\n attribute :storages\n validates :storages, type: TypeGeneric.new(Hash)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6854745149612427, "alphanum_fraction": 0.6892361044883728, "avg_line_length": 53, "blob_id": "5eb5fcb545fd2128c6582b316faf1dfe4d7989c4", "content_id": "0e12abefcd96f2716552f21ff3f6ff72b56e1dab", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3456, "license_type": "permissive", "max_line_length": 506, "num_lines": 64, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_vm_shell.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Module allows user to run common system administration commands in the guest operating system.\n class Vmware_vm_shell < Base\n # @return [String, nil] The datacenter hosting the virtual machine.,If set, it will help to speed up virtual machine search.\n attribute :datacenter\n validates :datacenter, type: String\n\n # @return [Object, nil] The cluster hosting the virtual machine.,If set, it will help to speed up virtual machine search.\n attribute :cluster\n\n # @return [String, nil] Destination folder, absolute or relative path to find an existing guest or create the new guest.,The folder should include the datacenter. ESX's datacenter is ha-datacenter.,Examples:, folder: /ha-datacenter/vm, folder: ha-datacenter/vm, folder: /datacenter1/vm, folder: datacenter1/vm, folder: /datacenter1/vm/folder1, folder: datacenter1/vm/folder1, folder: /folder1/datacenter1/vm, folder: folder1/datacenter1/vm, folder: /folder1/datacenter1/vm/folder2\n attribute :folder\n validates :folder, type: String\n\n # @return [String] Name of the virtual machine to work with.\n attribute :vm_id\n validates :vm_id, presence: true, type: String\n\n # @return [:uuid, :dns_name, :inventory_path, :vm_name, nil] The VMware identification method by which the virtual machine will be identified.\n attribute :vm_id_type\n validates :vm_id_type, expression_inclusion: {:in=>[:uuid, :dns_name, :inventory_path, :vm_name], :message=>\"%{value} needs to be :uuid, :dns_name, :inventory_path, :vm_name\"}, allow_nil: true\n\n # @return [String] The user to login-in to the virtual machine.\n attribute :vm_username\n validates :vm_username, presence: true, type: String\n\n # @return [String] The password used to login-in to the virtual machine.\n attribute :vm_password\n validates :vm_password, presence: true, type: String\n\n # @return [String] The absolute path to the program to start.,On Linux, shell is executed via bash.\n attribute :vm_shell\n validates :vm_shell, presence: true, type: String\n\n # @return [String, nil] The argument to the program.,The characters which must be escaped to the shell also be escaped on the command line provided.\n attribute :vm_shell_args\n validates :vm_shell_args, type: String\n\n # @return [Array<String>, String, nil] Comma separated list of environment variable, specified in the guest OS notation.\n attribute :vm_shell_env\n validates :vm_shell_env, type: TypeGeneric.new(String)\n\n # @return [String, nil] The current working directory of the application from which it will be run.\n attribute :vm_shell_cwd\n validates :vm_shell_cwd, type: String\n\n # @return [Symbol, nil] If set to C(True), module will wait for process to complete in the given virtual machine.\n attribute :wait_for_process\n validates :wait_for_process, type: Symbol\n\n # @return [Integer, nil] Timeout in seconds.,If set to positive integers, then C(wait_for_process) will honor this parameter and will exit after this timeout.\n attribute :timeout\n validates :timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6588678956031799, "alphanum_fraction": 0.6588678956031799, "avg_line_length": 46.32143020629883, "blob_id": "bff94288ce93d5c756e4f139a11867e0e986792f", "content_id": "7a82181d6be389335e56fccc19dc696b42416f4b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2650, "license_type": "permissive", "max_line_length": 238, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/windows/win_share.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add, modify or remove Windows share and set share permissions.\n class Win_share < Base\n # @return [String] Share name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] Share directory.\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [:absent, :present, nil] Specify whether to add C(present) or remove C(absent) the specified share.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] Share description.\n attribute :description\n validates :description, type: String\n\n # @return [:yes, :no, nil] Specify whether to allow or deny file listing, in case user has no permission on share. Also known as Access-Based Enumeration.\n attribute :list\n validates :list, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Specify user list that should get read access on share, separated by comma.\n attribute :read\n validates :read, type: String\n\n # @return [Object, nil] Specify user list that should get read and write access on share, separated by comma.\n attribute :change\n\n # @return [Array<String>, String, nil] Specify user list that should get full access on share, separated by comma.\n attribute :full\n validates :full, type: TypeGeneric.new(String)\n\n # @return [String, nil] Specify user list that should get no access, regardless of implied access on share, separated by comma.\n attribute :deny\n validates :deny, type: String\n\n # @return [:BranchCache, :Documents, :Manual, :None, :Programs, :Unknown, nil] Set the CachingMode for this share.\n attribute :caching_mode\n validates :caching_mode, expression_inclusion: {:in=>[:BranchCache, :Documents, :Manual, :None, :Programs, :Unknown], :message=>\"%{value} needs to be :BranchCache, :Documents, :Manual, :None, :Programs, :Unknown\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Sets whether to encrypt the traffic to the share or not.\n attribute :encrypt\n validates :encrypt, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.678987979888916, "alphanum_fraction": 0.6822178363800049, "avg_line_length": 66.14457702636719, "blob_id": "6186fa3e5c1a19c4b7ead879eb295edfd877d1cb", "content_id": "f3720f266b1394f263836acb06e02712496fcb68", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5573, "license_type": "permissive", "max_line_length": 456, "num_lines": 83, "path": "/lib/ansible/ruby/modules/generated/system/cron.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Use this module to manage crontab and environment variables entries. This module allows you to create environment variables and named crontab entries, update, or delete them.\n # When crontab jobs are managed: the module includes one line with the description of the crontab entry C(\"#Ansible: <name>\") corresponding to the \"name\" passed to the module, which is used by future ansible/module calls to find/check the state. The \"name\" parameter should be unique, and changing the \"name\" value will result in a new cron task being created (or a different one being removed).\n # When environment variables are managed: no comment line is added, but, when the module needs to find/check the state, it uses the \"name\" parameter to find the environment variable definition line.\n # When using symbols such as %, they must be properly escaped.\n class Cron < Base\n # @return [String, nil] Description of a crontab entry or, if env is set, the name of environment variable. Required if state=absent. Note that if name is not set and state=present, then a new crontab entry will always be created, regardless of existing ones.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] The specific user whose crontab should be modified.\n attribute :user\n validates :user, type: String\n\n # @return [String, nil] The command to execute or, if env is set, the value of environment variable. The command should not contain line breaks. Required if state=present.\n attribute :job\n validates :job, type: String\n\n # @return [:absent, :present, nil] Whether to ensure the job or environment variable is present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] If specified, uses this file instead of an individual user's crontab. If this is a relative path, it is interpreted with respect to /etc/cron.d. (If it is absolute, it will typically be /etc/crontab). Many linux distros expect (and some require) the filename portion to consist solely of upper- and lower-case letters, digits, underscores, and hyphens. To use the C(cron_file) parameter you must specify the C(user) as well.\n attribute :cron_file\n validates :cron_file, type: String\n\n # @return [:yes, :no, nil] If set, create a backup of the crontab before it is modified. The location of the backup is returned in the C(backup_file) variable by this module.\n attribute :backup\n validates :backup, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Minute when the job should run ( 0-59, *, */2, etc )\n attribute :minute\n validates :minute, type: String\n\n # @return [String, nil] Hour when the job should run ( 0-23, *, */2, etc )\n attribute :hour\n validates :hour, type: String\n\n # @return [String, nil] Day of the month the job should run ( 1-31, *, */2, etc )\n attribute :day\n validates :day, type: String\n\n # @return [String, nil] Month of the year the job should run ( 1-12, *, */2, etc )\n attribute :month\n validates :month, type: String\n\n # @return [String, nil] Day of the week that the job should run ( 0-6 for Sunday-Saturday, *, etc )\n attribute :weekday\n validates :weekday, type: String\n\n # @return [:yes, :no, nil] If the job should be run at reboot. This option is deprecated. Users should use special_time.\n attribute :reboot\n validates :reboot, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:reboot, :yearly, :annually, :monthly, :weekly, :daily, :hourly, nil] Special time specification nickname.\n attribute :special_time\n validates :special_time, expression_inclusion: {:in=>[:reboot, :yearly, :annually, :monthly, :weekly, :daily, :hourly], :message=>\"%{value} needs to be :reboot, :yearly, :annually, :monthly, :weekly, :daily, :hourly\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If the job should be disabled (commented out) in the crontab.,Only has effect if C(state=present).\n attribute :disabled\n validates :disabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If set, manages a crontab's environment variable. New variables are added on top of crontab. \"name\" and \"value\" parameters are the name and the value of environment variable.\n attribute :env\n validates :env, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Used with C(state=present) and C(env). If specified, the environment variable will be inserted after the declaration of specified environment variable.\n attribute :insertafter\n validates :insertafter, type: String\n\n # @return [Object, nil] Used with C(state=present) and C(env). If specified, the environment variable will be inserted before the declaration of specified environment variable.\n attribute :insertbefore\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7062228918075562, "alphanum_fraction": 0.7062228918075562, "avg_line_length": 33.54999923706055, "blob_id": "85e6fa85eef501a3188e269f3697b162e695d17b", "content_id": "83f4c14c8d99358471b385af703ad8f675cb7381", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 691, "license_type": "permissive", "max_line_length": 187, "num_lines": 20, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/rds_instance_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # obtain facts about one or more RDS instances\n class Rds_instance_facts < Base\n # @return [String, nil] The RDS instance's unique identifier.\n attribute :db_instance_identifier\n validates :db_instance_identifier, type: String\n\n # @return [Object, nil] A filter that specifies one or more DB instances to describe. See U(https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_DescribeDBInstances.html)\n attribute :filters\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7105427384376526, "alphanum_fraction": 0.7105427384376526, "avg_line_length": 54.27586364746094, "blob_id": "1feb80938f1d7b0ee37e85a62b6aa4f83d6570d2", "content_id": "289cbd7eb17f3e5ec5e82f31785bda7bf2e3b0fc", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1603, "license_type": "permissive", "max_line_length": 274, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/network/junos/junos_rpc.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Sends a request to the remote device running JUNOS to execute the specified RPC using the NetConf transport. The reply is then returned to the playbook in the C(xml) key. If an alternate output format is requested, the reply is transformed to the requested output.\n class Junos_rpc < Base\n # @return [String] The C(rpc) argument specifies the RPC call to send to the remote devices to be executed. The RPC Reply message is parsed and the contents are returned to the playbook.\n attribute :rpc\n validates :rpc, presence: true, type: String\n\n # @return [Hash, nil] The C(args) argument provides a set of arguments for the RPC call and are encoded in the request message. This argument accepts a set of key=value arguments.\n attribute :args\n validates :args, type: Hash\n\n # @return [Hash, nil] The C(attrs) arguments defines a list of attributes and their values to set for the RPC call. This accepts a dictionary of key-values.\n attribute :attrs\n validates :attrs, type: Hash\n\n # @return [String, nil] The C(output) argument specifies the desired output of the return data. This argument accepts one of C(xml), C(text), or C(json). For C(json), the JUNOS device must be running a version of software that supports native JSON output.\n attribute :output\n validates :output, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6568440794944763, "alphanum_fraction": 0.6568440794944763, "avg_line_length": 41.08000183105469, "blob_id": "599813a1d968658560012aeb44ef08381cf06b67", "content_id": "a1d814c301d0f56b850a68590cd9d5bc5a5e3244", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2104, "license_type": "permissive", "max_line_length": 183, "num_lines": 50, "path": "/lib/ansible/ruby/modules/generated/identity/ipa/ipa_vault.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add, modify and delete vaults and secret vaults.\n # KRA service should be enabled to use this module.\n class Ipa_vault < Base\n # @return [Object] Vault name.,Can not be changed as it is the unique identifier.\n attribute :cn\n validates :cn, presence: true\n\n # @return [String, nil] Description.\n attribute :description\n validates :description, type: String\n\n # @return [:standard, :symmetric, :asymmetric] Vault types are based on security level.\n attribute :ipavaulttype\n validates :ipavaulttype, presence: true, expression_inclusion: {:in=>[:standard, :symmetric, :asymmetric], :message=>\"%{value} needs to be :standard, :symmetric, :asymmetric\"}\n\n # @return [Object, nil] Public key.\n attribute :ipavaultpublickey\n\n # @return [Object, nil] Vault Salt.\n attribute :ipavaultsalt\n\n # @return [Object, nil] Any user can own one or more user vaults.,Mutually exclusive with service.\n attribute :username\n\n # @return [Object, nil] Any service can own one or more service vaults.,Mutually exclusive with user.\n attribute :service\n\n # @return [:present, :absent, nil] State to ensure.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:True, :False, nil] Force replace the existant vault on IPA server.\n attribute :replace\n validates :replace, expression_inclusion: {:in=>[:True, :False], :message=>\"%{value} needs to be :True, :False\"}, allow_nil: true\n\n # @return [Boolean, nil] Validate IPA server certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7224947214126587, "alphanum_fraction": 0.7227283120155334, "avg_line_length": 81.32691955566406, "blob_id": "3b465d202b681e29895e68b7e626b938121097bd", "content_id": "1bd9b9100584491623be6b9dbef9827d321c9b5c", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4281, "license_type": "permissive", "max_line_length": 769, "num_lines": 52, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_gtm_pool_member.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages a variety of settings on GTM pool members. The settings that can be adjusted with this module are much more broad that what can be done in the C(bigip_gtm_pool) module. The pool module is intended to allow you to adjust the member order in the pool, not the various settings of the members. The C(bigip_gtm_pool_member) module should be used to adjust all of the other settings.\n class Bigip_gtm_pool_member < Base\n # @return [Object] Specifies the name of the GTM virtual server which is assigned to the specified C(server).\n attribute :virtual_server\n validates :virtual_server, presence: true\n\n # @return [Object] Specifies the GTM server which contains the C(virtual_server).\n attribute :server_name\n validates :server_name, presence: true\n\n # @return [:a, :aaaa, :cname, :mx, :naptr, :srv] The type of GTM pool that the member is in.\n attribute :type\n validates :type, presence: true, expression_inclusion: {:in=>[:a, :aaaa, :cname, :mx, :naptr, :srv], :message=>\"%{value} needs to be :a, :aaaa, :cname, :mx, :naptr, :srv\"}\n\n # @return [Object] Name of the GTM pool.\n attribute :pool\n validates :pool, presence: true\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [Object, nil] Specifies the order in which the member will appear in the pool.,The system uses this number with load balancing methods that involve prioritizing pool members, such as the Ratio load balancing method.,When creating a new member using this module, if the C(member_order) parameter is not specified, it will default to C(0) (first member in the pool).\n attribute :member_order\n\n # @return [Object, nil] Specifies the monitor assigned to this pool member.,Pool members only support a single monitor.,If the C(port) of the C(gtm_virtual_server) is C(*), the accepted values of this parameter will be affected.,When creating a new pool member, if this parameter is not specified, the default of C(default) will be used.,To remove the monitor from the pool member, use the value C(none).,For pool members created on different partitions, you can also specify the full path to the Common monitor. For example, C(/Common/tcp).\n attribute :monitor\n\n # @return [Object, nil] Specifies the weight of the pool member for load balancing purposes.\n attribute :ratio\n\n # @return [Object, nil] The description of the pool member.\n attribute :description\n\n # @return [Object, nil] Specifies resource thresholds or limit requirements at the pool member level.,When you enable one or more limit settings, the system then uses that data to take members in and out of service.,You can define limits for any or all of the limit settings. However, when a member does not meet the resource threshold limit requirement, the system marks the member as unavailable and directs load-balancing traffic to another resource.\n attribute :limits\n\n # @return [:present, :absent, :enabled, :disabled, nil] Pool member state. When C(present), ensures that the pool member is created and enabled. When C(absent), ensures that the pool member is removed from the system. When C(enabled) or C(disabled), ensures that the pool member is enabled or disabled (respectively) on the remote device.,It is recommended that you use the C(members) parameter of the C(bigip_gtm_pool) module when adding and removing members and it provides an easier way of specifying order. If this is not possible, then the C(state) parameter here should be used.,Remember that the order of the members will be affected if you add or remove them using this method. To some extent, this can be controlled using the C(member_order) parameter.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :enabled, :disabled], :message=>\"%{value} needs to be :present, :absent, :enabled, :disabled\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6650273203849792, "alphanum_fraction": 0.6650273203849792, "avg_line_length": 45.92307662963867, "blob_id": "a7953a25d4fddbc7ef668930c3916d6958e65758", "content_id": "743f28917423f329813be2dc838abe8d25ba7a5a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1830, "license_type": "permissive", "max_line_length": 205, "num_lines": 39, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_kms.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage role/user access to a KMS key. Not designed for encrypting/decrypting.\n class Aws_kms < Base\n # @return [:grant, :deny] Grant or deny access.\n attribute :mode\n validates :mode, presence: true, expression_inclusion: {:in=>[:grant, :deny], :message=>\"%{value} needs to be :grant, :deny\"}\n\n # @return [String, nil] Alias label to the key. One of C(key_alias) or C(key_arn) are required.\n attribute :key_alias\n validates :key_alias, type: String\n\n # @return [Object, nil] Full ARN to the key. One of C(key_alias) or C(key_arn) are required.\n attribute :key_arn\n\n # @return [String, nil] Role to allow/deny access. One of C(role_name) or C(role_arn) are required.\n attribute :role_name\n validates :role_name, type: String\n\n # @return [Object, nil] ARN of role to allow/deny access. One of C(role_name) or C(role_arn) are required.\n attribute :role_arn\n\n # @return [Array<String>, String, nil] List of grants to give to user/role. Likely \"role,role grant\" or \"role,role grant,admin\". Required when C(mode=grant).\n attribute :grant_types\n validates :grant_types, type: TypeGeneric.new(String)\n\n # @return [Boolean, nil] If adding/removing a role and invalid grantees are found, remove them. These entries will cause an update to fail in all known cases.,Only cleans if changes are being made.\n attribute :clean_invalid_entries\n validates :clean_invalid_entries, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7297794222831726, "alphanum_fraction": 0.7297794222831726, "avg_line_length": 31, "blob_id": "0053b53e05150ea6fb92cc19a5611e6c985bdd57", "content_id": "e0f65f375a3e3cd8767204900c54c4d0bab9a8a7", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 544, "license_type": "permissive", "max_line_length": 123, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_local_user_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to gather facts about users present on the given ESXi host system in VMware infrastructure.\n # All variables and VMware object names are case sensitive.\n # User must hold the 'Authorization.ModifyPermissions' privilege to invoke this module.\n class Vmware_local_user_facts < Base\n\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7050885558128357, "alphanum_fraction": 0.7109923958778381, "avg_line_length": 62.51785659790039, "blob_id": "a9ed4f1005741ee4566f4e8c316d3549bdd2e769", "content_id": "e1f1a846384dca99c9311514aa35503cf76ed064", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3557, "license_type": "permissive", "max_line_length": 339, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/network/netscaler/netscaler_server.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage server entities configuration.\n # This module is intended to run either on the ansible control node or a bastion (jumpserver) with access to the actual netscaler instance.\n class Netscaler_server < Base\n # @return [String, nil] Name for the server.,Must begin with an ASCII alphabetic or underscore C(_) character, and must contain only ASCII alphanumeric, underscore C(_), hash C(#), period C(.), space C( ), colon C(:), at C(@), equals C(=), and hyphen C(-) characters.,Can be changed after the name is created.,Minimum length = 1\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] IPv4 or IPv6 address of the server. If you create an IP address based server, you can specify the name of the server, instead of its IP address, when creating a service. Note: If you do not create a server entry, the server IP address that you enter when you create a service becomes the name of the server.\n attribute :ipaddress\n validates :ipaddress, type: String\n\n # @return [Object, nil] Domain name of the server. For a domain based configuration, you must create the server first.,Minimum length = 1\n attribute :domain\n\n # @return [Object, nil] IP address used to transform the server's DNS-resolved IP address.\n attribute :translationip\n\n # @return [Object, nil] The netmask of the translation ip.\n attribute :translationmask\n\n # @return [Integer, nil] Time, in seconds, for which the NetScaler appliance must wait, after DNS resolution fails, before sending the next DNS query to resolve the domain name.,Minimum value = C(5),Maximum value = C(20939)\n attribute :domainresolveretry\n validates :domainresolveretry, type: Integer\n\n # @return [Symbol, nil] Support IPv6 addressing mode. If you configure a server with the IPv6 addressing mode, you cannot use the server in the IPv4 addressing mode.\n attribute :ipv6address\n validates :ipv6address, type: Symbol\n\n # @return [Object, nil] Any information about the server.\n attribute :comment\n\n # @return [Object, nil] Integer value that uniquely identifies the traffic domain in which you want to configure the entity. If you do not specify an ID, the entity becomes part of the default traffic domain, which has an ID of 0.,Minimum value = C(0),Maximum value = C(4094)\n attribute :td\n\n # @return [Symbol, nil] Shut down gracefully, without accepting any new connections, and disabling each service when all of its connections are closed.,This option is meaningful only when setting the I(disabled) option to C(true)\n attribute :graceful\n validates :graceful, type: Symbol\n\n # @return [Object, nil] Time, in seconds, after which all the services configured on the server are disabled.,This option is meaningful only when setting the I(disabled) option to C(true)\n attribute :delay\n\n # @return [Symbol, nil] When set to C(true) the server state will be set to C(disabled).,When set to C(false) the server state will be set to C(enabled).,Note that due to limitations of the underlying NITRO API a C(disabled) state change alone does not cause the module result to report a changed status.\n attribute :disabled\n validates :disabled, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6766990423202515, "alphanum_fraction": 0.6805825233459473, "avg_line_length": 40.20000076293945, "blob_id": "0e93457776fe4c97cd802f046edc40be832e137e", "content_id": "7e8904e5a512fc419fa9ec94c3be9bd98b9694d8", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1030, "license_type": "permissive", "max_line_length": 222, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_job_schedule.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create/Delete/Modify_minute job-schedules on ONTAP\n class Na_ontap_job_schedule < Base\n # @return [:present, :absent, nil] Whether the specified job schedule should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The name of the job-schedule to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The minute(s) of each hour when the job should be run. Job Manager cron scheduling minute. -1 represents all minutes and only supported for cron schedule create and modify. Range is [-1..59]\n attribute :job_minutes\n validates :job_minutes, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6400886178016663, "alphanum_fraction": 0.6400886178016663, "avg_line_length": 30.13793182373047, "blob_id": "a12d345627e3f235ccf3e224f46c62ede55aca5c", "content_id": "5b921a8ad4d77b7de1837536f3f2bd95566e267c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 903, "license_type": "permissive", "max_line_length": 142, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/storage/ibm/ibm_sa_vol.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module creates or deletes volumes to be used on IBM Spectrum Accelerate storage systems.\n class Ibm_sa_vol < Base\n # @return [String] Volume name.\n attribute :vol\n validates :vol, presence: true, type: String\n\n # @return [String, nil] Volume pool.\n attribute :pool\n validates :pool, type: String\n\n # @return [:present, :absent] Volume state.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [Integer, nil] Volume size.\n attribute :size\n validates :size, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6382828950881958, "alphanum_fraction": 0.6382828950881958, "avg_line_length": 33.65853500366211, "blob_id": "8040910f370100169a01e5666b528c8e2b04781d", "content_id": "1e188f374892ca1e87c081d85eef2a73da54940c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1421, "license_type": "permissive", "max_line_length": 131, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/clustering/znode.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, delete, retrieve, and update znodes using ZooKeeper.\n class Znode < Base\n # @return [String] A list of ZooKeeper servers (format '[server]:[port]').\n attribute :hosts\n validates :hosts, presence: true, type: String\n\n # @return [String] The path of the znode.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The value assigned to the znode.\n attribute :value\n validates :value, type: String\n\n # @return [String, nil] An operation to perform. Mutually exclusive with state.\n attribute :op\n validates :op, type: String\n\n # @return [String, nil] The state to enforce. Mutually exclusive with op.\n attribute :state\n validates :state, type: String\n\n # @return [Integer, nil] The amount of time to wait for a node to appear.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [:yes, :no, nil] Recursively delete node and all its children.\n attribute :recursive\n validates :recursive, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7090739011764526, "alphanum_fraction": 0.7090739011764526, "avg_line_length": 41.7599983215332, "blob_id": "fc35d62e5bc8ebde0e34075ba7dd911fc51dc29b", "content_id": "ba2161ec8c5b414fe6bf9d779386f8f68f789900", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1069, "license_type": "permissive", "max_line_length": 191, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/network/ftd/ftd_file_download.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Downloads files from Cisco FTD devices including pending changes, disk files, certificates, troubleshoot reports, and backups.\n class Ftd_file_download < Base\n # @return [String] The name of the operation to execute.,Only operations that return a file can be used in this module.\n attribute :operation\n validates :operation, presence: true, type: String\n\n # @return [Hash, nil] Key-value pairs that should be sent as path parameters in a REST API call.\n attribute :path_params\n validates :path_params, type: Hash\n\n # @return [String] Absolute path of where to download the file to.,If destination is a directory, the module uses a filename from 'Content-Disposition' header specified by the server.\n attribute :destination\n validates :destination, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6820949912071228, "alphanum_fraction": 0.6820949912071228, "avg_line_length": 45.47169876098633, "blob_id": "d918be46009498cc814129efcbba500f576c7d5e", "content_id": "92b197b6e34643d64f63555edc11b34ff1208ddb", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2463, "license_type": "permissive", "max_line_length": 177, "num_lines": 53, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_acs.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and delete an Azure Container Service Instance.\n class Azure_rm_acs < Base\n # @return [String] Name of a resource group where the Container Services exists or will be created.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] Name of the Container Services instance.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, nil] Assert the state of the ACS. Use 'present' to create or update an ACS and 'absent' to delete it.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] Valid azure location. Defaults to location of the resource group.\n attribute :location\n validates :location, type: String\n\n # @return [:DCOS, :Kubernetes, :Swarm] Specifies the Container Orchestration Platform to use. Currently can be either DCOS, Kubernetes or Swarm.\n attribute :orchestration_platform\n validates :orchestration_platform, presence: true, expression_inclusion: {:in=>[:DCOS, :Kubernetes, :Swarm], :message=>\"%{value} needs to be :DCOS, :Kubernetes, :Swarm\"}\n\n # @return [Array<Hash>, Hash] Master profile suboptions.\n attribute :master_profile\n validates :master_profile, presence: true, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash] The linux profile suboptions.\n attribute :linux_profile\n validates :linux_profile, presence: true, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash] The agent pool profile suboptions.\n attribute :agent_pool_profiles\n validates :agent_pool_profiles, presence: true, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash, nil] The service principal suboptions.\n attribute :service_principal\n validates :service_principal, type: TypeGeneric.new(Hash)\n\n # @return [Symbol] Should VM Diagnostics be enabled for the Container Service VM's.\n attribute :diagnostics_profile\n validates :diagnostics_profile, presence: true, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6529411673545837, "alphanum_fraction": 0.6567226648330688, "avg_line_length": 44.769229888916016, "blob_id": "155eec4346f937a2614121521ecaa3cef811894b", "content_id": "b76466ebadbc506b2dc9ffae8373a6642f8fd16e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2380, "license_type": "permissive", "max_line_length": 227, "num_lines": 52, "path": "/lib/ansible/ruby/modules/generated/cloud/rackspace/rax_dns_record.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage DNS records on Rackspace Cloud DNS\n class Rax_dns_record < Base\n # @return [Object, nil] Brief description of the domain. Maximum length of 160 characters\n attribute :comment\n\n # @return [Object] IP address for A/AAAA record, FQDN for CNAME/MX/NS, or text data for SRV/TXT\n attribute :data\n validates :data, presence: true\n\n # @return [Object, nil] Domain name to create the record in. This is an invalid option when type=PTR\n attribute :domain\n\n # @return [Object, nil] Load Balancer ID to create a PTR record for. Only used with type=PTR\n attribute :loadbalancer\n\n # @return [String] FQDN record name to create\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Boolean, nil] Add new records if data doesn't match, instead of updating existing record with matching name. If there are already multiple records with matching name and overwrite=true, this module will fail.\n attribute :overwrite\n validates :overwrite, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] Required for MX and SRV records, but forbidden for other record types. If specified, must be an integer from 0 to 65535.\n attribute :priority\n\n # @return [Object, nil] Server ID to create a PTR record for. Only used with type=PTR\n attribute :server\n\n # @return [:present, :absent, nil] Indicate desired state of the resource\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Integer, nil] Time to live of record in seconds\n attribute :ttl\n validates :ttl, type: Integer\n\n # @return [:A, :AAAA, :CNAME, :MX, :NS, :SRV, :TXT, :PTR] DNS record type\n attribute :type\n validates :type, presence: true, expression_inclusion: {:in=>[:A, :AAAA, :CNAME, :MX, :NS, :SRV, :TXT, :PTR], :message=>\"%{value} needs to be :A, :AAAA, :CNAME, :MX, :NS, :SRV, :TXT, :PTR\"}\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6661595106124878, "alphanum_fraction": 0.6687676310539246, "avg_line_length": 55.802467346191406, "blob_id": "ce9d3c88d300e0ce87ede9cc072528a9f3fa3b0f", "content_id": "43e8000e16d03cde2aa856c053e6fb76c98d4590", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4601, "license_type": "permissive", "max_line_length": 324, "num_lines": 81, "path": "/lib/ansible/ruby/modules/generated/source_control/gitlab_project.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # When the project does not exist in Gitlab, it will be created.\n # When the project does exists and state=absent, the project will be deleted.\n # When changes are made to the project, the project will be updated.\n class Gitlab_project < Base\n # @return [String] Url of Gitlab server, with protocol (http or https).\n attribute :server_url\n validates :server_url, presence: true, type: String\n\n # @return [:yes, :no, nil] When using https if SSL certificate needs to be verified.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Gitlab user name.\n attribute :login_user\n validates :login_user, type: String\n\n # @return [String, nil] Gitlab password for login_user\n attribute :login_password\n validates :login_password, type: String\n\n # @return [String, nil] Gitlab token for logging in.\n attribute :login_token\n validates :login_token, type: String\n\n # @return [String, nil] The name of the group of which this projects belongs to.,When not provided, project will belong to user which is configured in 'login_user' or 'login_token',When provided with username, project will be created for this user. 'login_user' or 'login_token' needs admin rights.\n attribute :group\n validates :group, type: String\n\n # @return [String] The name of the project\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] The path of the project you want to create, this will be server_url/<group>/path,If not supplied, name will be used.\n attribute :path\n\n # @return [Object, nil] An description for the project.\n attribute :description\n\n # @return [:yes, :no, nil] Whether you want to create issues or not.,Possible values are true and false.\n attribute :issues_enabled\n validates :issues_enabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If merge requests can be made or not.,Possible values are true and false.\n attribute :merge_requests_enabled\n validates :merge_requests_enabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If an wiki for this project should be available or not.,Possible values are true and false.\n attribute :wiki_enabled\n validates :wiki_enabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If creating snippets should be available or not.,Possible values are true and false.\n attribute :snippets_enabled\n validates :snippets_enabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If the project is public available or not.,Setting this to true is same as setting visibility_level to 20.,Possible values are true and false.\n attribute :public\n validates :public, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Private. visibility_level is 0. Project access must be granted explicitly for each user.,Internal. visibility_level is 10. The project can be cloned by any logged in user.,Public. visibility_level is 20. The project can be cloned without any authentication.,Possible values are 0, 10 and 20.\n attribute :visibility_level\n validates :visibility_level, type: Integer\n\n # @return [:yes, :no, nil] Git repository which will be imported into gitlab.,Gitlab server needs read access to this git repository.\n attribute :import_url\n validates :import_url, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, nil] create or delete project.,Possible values are present and absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6608433723449707, "alphanum_fraction": 0.6891566514968872, "avg_line_length": 49.30303192138672, "blob_id": "142f2a4c0c3b00a4d1c515d4c530c8ea09f49b8b", "content_id": "470c9fdb858b4be82e73a385f18eb3cc87eab466", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1660, "license_type": "permissive", "max_line_length": 210, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/network/eos/eos_l3_interface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of L3 interfaces on Arista EOS network devices.\n class Eos_l3_interface < Base\n # @return [String, nil] Name of the L3 interface to be configured eg. ethernet1\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] IPv4 address to be set for the L3 interface mentioned in I(name) option. The address format is <ipv4 address>/<mask>, the mask is number in range 0-32 eg. 192.168.0.1/24\n attribute :ipv4\n validates :ipv4, type: String\n\n # @return [String, nil] IPv6 address to be set for the L3 interface mentioned in I(name) option. The address format is <ipv6 address>/<mask>, the mask is number in range 0-128 eg. fd5d:12c9:2201:1::1/64\n attribute :ipv6\n validates :ipv6, type: String\n\n # @return [Array<Hash>, Hash, nil] List of L3 interfaces definitions. Each of the entry in aggregate list should define name of interface C(name) and a optional C(ipv4) or C(ipv6) address.\n attribute :aggregate\n validates :aggregate, type: TypeGeneric.new(Hash)\n\n # @return [:present, :absent, nil] State of the L3 interface configuration. It indicates if the configuration should be present or absent on remote device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6727941036224365, "alphanum_fraction": 0.6727941036224365, "avg_line_length": 26.200000762939453, "blob_id": "c94728d16e59709dba25833f133242b3e30747d0", "content_id": "6334423df204c308830e5ee0760e5f4335067922", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 544, "license_type": "permissive", "max_line_length": 76, "num_lines": 20, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_image_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Retrieve facts about a image image from OpenStack.\n class Os_image_facts < Base\n # @return [String, nil] Name or ID of the image\n attribute :image\n validates :image, type: String\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6521739363670349, "alphanum_fraction": 0.6541805863380432, "avg_line_length": 38.342105865478516, "blob_id": "267b23d3c509dd549a50cd013afde0fe0ef49ff5", "content_id": "0e8beb2c4935d483ac0a1d4c6008261c4512c734", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1495, "license_type": "permissive", "max_line_length": 143, "num_lines": 38, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_role_permission.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and remove CloudStack role permissions.\n # Managing role permissions only supported in CloudStack >= 4.9.\n class Cs_role_permission < Base\n # @return [String] The API name of the permission.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] Name or ID of the role.\n attribute :role\n validates :role, presence: true, type: String\n\n # @return [:allow, :deny, nil] The rule permission, allow or deny. Defaulted to deny.\n attribute :permission\n validates :permission, expression_inclusion: {:in=>[:allow, :deny], :message=>\"%{value} needs to be :allow, :deny\"}, allow_nil: true\n\n # @return [:present, :absent, nil] State of the role permission.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] The description of the role permission.\n attribute :description\n validates :description, type: String\n\n # @return [Integer, nil] The parent role permission uuid. use 0 to move this rule at the top of the list.\n attribute :parent\n validates :parent, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6453264951705933, "alphanum_fraction": 0.6453264951705933, "avg_line_length": 36.19047546386719, "blob_id": "bf8acf8f48b29727b6488938e5064425002ac489", "content_id": "a0205ddbdff12f2c6703c09ffdbc3f9314037a37", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 781, "license_type": "permissive", "max_line_length": 222, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_netconf.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Sends an arbitrary netconf command on HUAWEI CloudEngine switches.\n class Ce_netconf < Base\n # @return [:get, :\"edit-config\", :\"execute-action\", :\"execute-cli\"] The type of rpc.\n attribute :rpc\n validates :rpc, presence: true, expression_inclusion: {:in=>[:get, :\"edit-config\", :\"execute-action\", :\"execute-cli\"], :message=>\"%{value} needs to be :get, :\\\"edit-config\\\", :\\\"execute-action\\\", :\\\"execute-cli\\\"\"}\n\n # @return [Object] The config xml string.\n attribute :cfg_xml\n validates :cfg_xml, presence: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6724137663841248, "alphanum_fraction": 0.6724137663841248, "avg_line_length": 33, "blob_id": "c10e5c93b09923b017d8e7c60d85eb3a3c5dc844", "content_id": "e680579c3582cd542867e579bfbaf5d0c9a38a93", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 986, "license_type": "permissive", "max_line_length": 77, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_elementsw_snapshot_restore.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Element OS Cluster restore snapshot to volume.\n class Na_elementsw_snapshot_restore < Base\n # @return [String] ID or Name of source active volume.\n attribute :src_volume_id\n validates :src_volume_id, presence: true, type: String\n\n # @return [String] ID or Name of an existing snapshot.\n attribute :src_snapshot_id\n validates :src_snapshot_id, presence: true, type: String\n\n # @return [String] New Name of destination for restoring the snapshot\n attribute :dest_volume_name\n validates :dest_volume_name, presence: true, type: String\n\n # @return [String] Account ID or Name of Parent/Source Volume.\n attribute :account_id\n validates :account_id, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6740056872367859, "alphanum_fraction": 0.6740056872367859, "avg_line_length": 40.411766052246094, "blob_id": "e3a0142663cf5c626d90624e235397bd9bae7bc1", "content_id": "91122f48bd41ed77cb70ccfc87e6b0030db2254b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1408, "license_type": "permissive", "max_line_length": 172, "num_lines": 34, "path": "/lib/ansible/ruby/modules/generated/cloud/centurylink/clc_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or delete Server Groups at Centurylink Centurylink Cloud\n class Clc_group < Base\n # @return [String] The name of the Server Group\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] A description of the Server Group\n attribute :description\n\n # @return [Object, nil] The parent group of the server group. If parent is not provided, it creates the group at top level.\n attribute :parent\n\n # @return [Object, nil] Datacenter to create the group in. If location is not provided, the group gets created in the default datacenter associated with the account\n attribute :location\n\n # @return [:present, :absent, nil] Whether to create or delete the group\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Boolean, nil] Whether to wait for the tasks to finish before returning.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6527718305587769, "alphanum_fraction": 0.6527718305587769, "avg_line_length": 44.6274528503418, "blob_id": "037a384f4942cffeda93c99d4de22b3055924c9c", "content_id": "4132bd77fb2256287e838c3aba50b6b263c5d248", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2327, "license_type": "permissive", "max_line_length": 159, "num_lines": 51, "path": "/lib/ansible/ruby/modules/generated/windows/win_pagefile.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Query current pagefile configuration.\n # Enable/Disable AutomaticManagedPagefile.\n # Create new or override pagefile configuration.\n class Win_pagefile < Base\n # @return [String, nil] The drive of the pagefile.\n attribute :drive\n validates :drive, type: String\n\n # @return [Integer, nil] The initial size of the pagefile in megabytes.\n attribute :initial_size\n validates :initial_size, type: Integer\n\n # @return [Integer, nil] The maximum size of the pagefile in megabytes.\n attribute :maximum_size\n validates :maximum_size, type: Integer\n\n # @return [:yes, :no, nil] Override the current pagefile on the drive.\n attribute :override\n validates :override, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Configures current pagefile to be managed by the system.\n attribute :system_managed\n validates :system_managed, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Symbol, nil] Configures AutomaticManagedPagefile for the entire system.\n attribute :automatic\n validates :automatic, type: Symbol\n\n # @return [:yes, :no, nil] Remove all pagefiles in the system, not including automatic managed.\n attribute :remove_all\n validates :remove_all, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Use Test-Path on the drive to make sure the drive is accessible before creating the pagefile.\n attribute :test_path\n validates :test_path, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:absent, :present, :query, nil] State of the pagefile.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6814530491828918, "alphanum_fraction": 0.6842473149299622, "avg_line_length": 51.05454635620117, "blob_id": "fe6ac0a3c88580d67e36419b59c6683fe4fc3146", "content_id": "7ab4645656fa28bbfebb99ac5261d58effc000e5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2863, "license_type": "permissive", "max_line_length": 290, "num_lines": 55, "path": "/lib/ansible/ruby/modules/generated/network/illumos/flowadm.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create/modify/remove networking bandwidth and associated resources for a type of traffic on a particular link.\n class Flowadm < Base\n # @return [String] - A flow is defined as a set of attributes based on Layer 3 and Layer 4 headers, which can be used to identify a protocol, service, or a zone.\\r\\n\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Specifiies a link to configure flow on.\n attribute :link\n validates :link, type: String\n\n # @return [Object, nil] Identifies a network flow by the local IP address.\n attribute :local_ip\n\n # @return [Object, nil] Identifies a network flow by the remote IP address.\n attribute :remote_ip\n\n # @return [String, nil] - Specifies a Layer 4 protocol to be used. It is typically used in combination with I(local_port) to identify the service that needs special attention.\\r\\n\n attribute :transport\n validates :transport, type: String\n\n # @return [Integer, nil] Identifies a service specified by the local port.\n attribute :local_port\n validates :local_port, type: Integer\n\n # @return [String, nil] - Identifies the 8-bit differentiated services field (as defined in RFC 2474). The optional dsfield_mask is used to state the bits of interest in the differentiated services field when comparing with the dsfield value. Both values must be in hexadecimal.\\r\\n\n attribute :dsfield\n validates :dsfield, type: String\n\n # @return [String, nil] - Sets the full duplex bandwidth for the flow. The bandwidth is specified as an integer with one of the scale suffixes(K, M, or G for Kbps, Mbps, and Gbps). If no units are specified, the input value will be read as Mbps.\\r\\n\n attribute :maxbw\n validates :maxbw, type: String\n\n # @return [:low, :medium, :high, nil] Sets the relative priority for the flow.\n attribute :priority\n validates :priority, expression_inclusion: {:in=>[:low, :medium, :high], :message=>\"%{value} needs to be :low, :medium, :high\"}, allow_nil: true\n\n # @return [Symbol, nil] Specifies that the configured flow is temporary. Temporary flows do not persist across reboots.\n attribute :temporary\n validates :temporary, type: Symbol\n\n # @return [:absent, :present, :resetted, nil] Create/delete/enable/disable an IP address on the network interface.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :resetted], :message=>\"%{value} needs to be :absent, :present, :resetted\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6832901835441589, "alphanum_fraction": 0.6856649518013, "avg_line_length": 70.26153564453125, "blob_id": "1768064326afe857f8ff9ff44da574b066a608e4", "content_id": "dae8657a40cd248352b75548750431e98a71850d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4632, "license_type": "permissive", "max_line_length": 386, "num_lines": 65, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_filter_entry.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage filter entries for a filter on Cisco ACI fabrics.\n class Aci_filter_entry < Base\n # @return [:arp_reply, :arp_request, :unspecified, nil] The arp flag to use when the ether_type is arp.,The APIC defaults to C(unspecified) when unset during creation.\n attribute :arp_flag\n validates :arp_flag, expression_inclusion: {:in=>[:arp_reply, :arp_request, :unspecified], :message=>\"%{value} needs to be :arp_reply, :arp_request, :unspecified\"}, allow_nil: true\n\n # @return [Object, nil] Description for the Filter Entry.\n attribute :description\n\n # @return [Object, nil] Used to set both destination start and end ports to the same value when ip_protocol is tcp or udp.,Accepted values are any valid TCP/UDP port range.,The APIC defaults to C(unspecified) when unset during creation.\n attribute :dst_port\n\n # @return [Object, nil] Used to set the destination end port when ip_protocol is tcp or udp.,Accepted values are any valid TCP/UDP port range.,The APIC defaults to C(unspecified) when unset during creation.\n attribute :dst_port_end\n\n # @return [Object, nil] Used to set the destination start port when ip_protocol is tcp or udp.,Accepted values are any valid TCP/UDP port range.,The APIC defaults to C(unspecified) when unset during creation.\n attribute :dst_port_start\n\n # @return [String, nil] Then name of the Filter Entry.\n attribute :entry\n validates :entry, type: String\n\n # @return [:arp, :fcoe, :ip, :mac_security, :mpls_ucast, :trill, :unspecified, nil] The Ethernet type.,The APIC defaults to C(unspecified) when unset during creation.\n attribute :ether_type\n validates :ether_type, expression_inclusion: {:in=>[:arp, :fcoe, :ip, :mac_security, :mpls_ucast, :trill, :unspecified], :message=>\"%{value} needs to be :arp, :fcoe, :ip, :mac_security, :mpls_ucast, :trill, :unspecified\"}, allow_nil: true\n\n # @return [String, nil] The name of Filter that the entry should belong to.\n attribute :filter\n validates :filter, type: String\n\n # @return [:dst_unreachable, :echo, :echo_reply, :src_quench, :time_exceeded, :unspecified, nil] ICMPv4 message type; used when ip_protocol is icmp.,The APIC defaults to C(unspecified) when unset during creation.\n attribute :icmp_msg_type\n validates :icmp_msg_type, expression_inclusion: {:in=>[:dst_unreachable, :echo, :echo_reply, :src_quench, :time_exceeded, :unspecified], :message=>\"%{value} needs to be :dst_unreachable, :echo, :echo_reply, :src_quench, :time_exceeded, :unspecified\"}, allow_nil: true\n\n # @return [:dst_unreachable, :echo_request, :echo_reply, :neighbor_advertisement, :neighbor_solicitation, :redirect, :time_exceeded, :unspecified, nil] ICMPv6 message type; used when ip_protocol is icmpv6.,The APIC defaults to C(unspecified) when unset during creation.\n attribute :icmp6_msg_type\n validates :icmp6_msg_type, expression_inclusion: {:in=>[:dst_unreachable, :echo_request, :echo_reply, :neighbor_advertisement, :neighbor_solicitation, :redirect, :time_exceeded, :unspecified], :message=>\"%{value} needs to be :dst_unreachable, :echo_request, :echo_reply, :neighbor_advertisement, :neighbor_solicitation, :redirect, :time_exceeded, :unspecified\"}, allow_nil: true\n\n # @return [:eigrp, :egp, :icmp, :icmpv6, :igmp, :igp, :l2tp, :ospfigp, :pim, :tcp, :udp, :unspecified, nil] The IP Protocol type when ether_type is ip.,The APIC defaults to C(unspecified) when unset during creation.\n attribute :ip_protocol\n validates :ip_protocol, expression_inclusion: {:in=>[:eigrp, :egp, :icmp, :icmpv6, :igmp, :igp, :l2tp, :ospfigp, :pim, :tcp, :udp, :unspecified], :message=>\"%{value} needs to be :eigrp, :egp, :icmp, :icmpv6, :igmp, :igp, :l2tp, :ospfigp, :pim, :tcp, :udp, :unspecified\"}, allow_nil: true\n\n # @return [:absent, :present, :query, nil] present, absent, query\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n\n # @return [Symbol, nil] Determines the statefulness of the filter entry.\n attribute :stateful\n validates :stateful, type: Symbol\n\n # @return [String, nil] The name of the tenant.\n attribute :tenant\n validates :tenant, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7011834383010864, "alphanum_fraction": 0.7021695971488953, "avg_line_length": 47.28571319580078, "blob_id": "28bc78fd9e883cadcfbd88047b53bf5246059347", "content_id": "5204c5408a5963c3cb47a6703a611b174948c85f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1014, "license_type": "permissive", "max_line_length": 346, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_kms_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gather facts about AWS KMS keys including tags and grants\n class Aws_kms_facts < Base\n # @return [Hash, nil] A dict of filters to apply. Each dict item consists of a filter key and a filter value. The filters aren't natively supported by boto3, but are supported to provide similar functionality to other modules. Standard tag filters (C(tag-key), C(tag-value) and C(tag:tagName)) are available, as are C(key-id) and C(alias)\n attribute :filters\n validates :filters, type: Hash\n\n # @return [Boolean, nil] Whether to get full details (tags, grants etc.) of keys pending deletion\n attribute :pending_deletion\n validates :pending_deletion, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5537634491920471, "alphanum_fraction": 0.6048387289047241, "avg_line_length": 20.882352828979492, "blob_id": "7d30d95f3077c89893b92eaca08a277e7567b3ef", "content_id": "ca2a4bf92c3f16e031636c4a8f3d51e6e5c5ee0d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 372, "license_type": "permissive", "max_line_length": 52, "num_lines": 17, "path": "/examples/webservers.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nplay 'webserver install' do\n local_host\n\n task 'EC2 load balancer' do\n ec2_elb_lb do\n state :present\n name 'lb-01'\n security_group_ids %w[sg-3c4fca59 sg-cabcc0ad]\n listeners protocol: 'http',\n load_balancer_port: 80,\n instance_port: 80\n subnets 'subnet-637e594b'\n end\n end\nend\n" }, { "alpha_fraction": 0.6724919080734253, "alphanum_fraction": 0.6724919080734253, "avg_line_length": 40.75675582885742, "blob_id": "be225fbb70cf4d40c79ee53ed1892dbf1dcd403d", "content_id": "3f5696a385ceac1eef7d9f84e0a7ee8dd1be5128", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1545, "license_type": "permissive", "max_line_length": 159, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/network/illumos/ipadm_ifprop.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Modify IP interface properties on Solaris/illumos systems.\n class Ipadm_ifprop < Base\n # @return [String] Specifies the IP interface we want to manage.\n attribute :interface\n validates :interface, presence: true, type: String\n\n # @return [String] Specifies the procotol for which we want to manage properties.\n attribute :protocol\n validates :protocol, presence: true, type: String\n\n # @return [String] Specifies the name of the property we want to manage.\n attribute :property\n validates :property, presence: true, type: String\n\n # @return [String, nil] Specifies the value we want to set for the property.\n attribute :value\n validates :value, type: String\n\n # @return [Boolean, nil] Specifies that the property value is temporary. Temporary property values do not persist across reboots.\n attribute :temporary\n validates :temporary, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:present, :absent, :reset, nil] Set or reset the property value.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :reset], :message=>\"%{value} needs to be :present, :absent, :reset\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6941646933555603, "alphanum_fraction": 0.6963862776756287, "avg_line_length": 63.30476379394531, "blob_id": "0b0eb67ae70b223991e9416a802b00b1b53a5c09", "content_id": "c543f50a8af778b7fe0ae5744b701e206d22418e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6752, "license_type": "permissive", "max_line_length": 646, "num_lines": 105, "path": "/lib/ansible/ruby/modules/generated/cloud/opennebula/one_vm.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages OpenNebula instances\n class One_vm < Base\n # @return [Object, nil] URL of the OpenNebula RPC server.,It is recommended to use HTTPS so that the username/password are not,transferred over the network unencrypted.,If not set then the value of the C(ONE_URL) environment variable is used.\n attribute :api_url\n\n # @return [Object, nil] Name of the user to login into the OpenNebula RPC server. If not set,then the value of the C(ONE_USERNAME) environment variable is used.\n attribute :api_username\n\n # @return [Object, nil] Password of the user to login into OpenNebula RPC server. If not set\n attribute :api_password\n\n # @return [String, nil] Name of VM template to use to create a new instace\n attribute :template_name\n validates :template_name, type: String\n\n # @return [Integer, nil] ID of a VM template to use to create a new instance\n attribute :template_id\n validates :template_id, type: Integer\n\n # @return [Array<Integer>, Integer, nil] A list of instance ids used for states':' C(absent), C(running), C(rebooted), C(poweredoff)\n attribute :instance_ids\n validates :instance_ids, type: TypeGeneric.new(Integer)\n\n # @return [:present, :absent, :running, :rebooted, :poweredoff, nil] C(present) - create instances from a template specified with C(template_id)/C(template_name).,C(running) - run instances,C(poweredoff) - power-off instances,C(rebooted) - reboot instances,C(absent) - terminate instances\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :running, :rebooted, :poweredoff], :message=>\"%{value} needs to be :present, :absent, :running, :rebooted, :poweredoff\"}, allow_nil: true\n\n # @return [Symbol, nil] Reboot, power-off or terminate instances C(hard)\n attribute :hard\n validates :hard, type: Symbol\n\n # @return [Boolean, nil] Wait for the instance to reach its desired state before returning. Keep,in mind if you are waiting for instance to be in running state it,doesn't mean that you will be able to SSH on that machine only that,boot process have started on that instance, see 'wait_for' example for,details.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Integer, nil] How long before wait gives up, in seconds\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [Object, nil] A dictionary of key/value attributes to add to new instances, or for,setting C(state) of instances with these attributes.,Keys are case insensitive and OpenNebula automatically converts them to upper case.,Be aware C(NAME) is a special attribute which sets the name of the VM when it's deployed.,C(#) character(s) can be appended to the C(NAME) and the module will automatically add,indexes to the names of VMs.,For example':' C(NAME':' foo-###) would create VMs with names C(foo-000), C(foo-001),...,When used with C(count_attributes) and C(exact_count) the module will,match the base name without the index part.\n attribute :attributes\n\n # @return [Object, nil] A list of labels to associate with new instances, or for setting,C(state) of instances with these labels.\n attribute :labels\n\n # @return [Hash, nil] A dictionary of key/value attributes that can only be used with,C(exact_count) to determine how many nodes based on a specific,attributes criteria should be deployed. This can be expressed in,multiple ways and is shown in the EXAMPLES section.\n attribute :count_attributes\n validates :count_attributes, type: Hash\n\n # @return [Array<String>, String, nil] A list of labels that can only be used with C(exact_count) to determine,how many nodes based on a specific labels criteria should be deployed.,This can be expressed in multiple ways and is shown in the EXAMPLES,section.\n attribute :count_labels\n validates :count_labels, type: TypeGeneric.new(String)\n\n # @return [Integer, nil] Number of instances to launch\n attribute :count\n validates :count, type: Integer\n\n # @return [Integer, nil] Indicates how many instances that match C(count_attributes) and,C(count_labels) parameters should be deployed. Instances are either,created or terminated based on this value.,NOTE':' Instances with the least IDs will be terminated first.\n attribute :exact_count\n validates :exact_count, type: Integer\n\n # @return [Integer, nil] Set permission mode of the instance in octet format, e.g. C(600) to give owner C(use) and C(manage) and nothing to group and others.\n attribute :mode\n validates :mode, type: Integer\n\n # @return [Object, nil] ID of the user which will be set as the owner of the instance\n attribute :owner_id\n\n # @return [Integer, nil] ID of the group which will be set as the group of the instance\n attribute :group_id\n validates :group_id, type: Integer\n\n # @return [String, nil] The size of the memory for new instances (in MB, GB, ...)\n attribute :memory\n validates :memory, type: String\n\n # @return [String, nil] The size of the disk created for new instances (in MB, GB, TB,...).,NOTE':' This option can be used only if the VM template specified with,C(template_id)/C(template_name) has exactly one disk.\n attribute :disk_size\n validates :disk_size, type: String\n\n # @return [Object, nil] Percentage of CPU divided by 100 required for the new instance. Half a,processor is written 0.5.\n attribute :cpu\n\n # @return [Integer, nil] Number of CPUs (cores) new VM will have.\n attribute :vcpu\n validates :vcpu, type: Integer\n\n # @return [Object, nil] A list of dictionaries with network parameters. See examples for more details.\n attribute :networks\n\n # @return [Hash, nil] Creates an image from a VM disk.,It is a dictionary where you have to specife C(name) of the new image.,Optionally you can specife C(disk_id) of the disk you want to save. By default C(disk_id) is 0.,I(NOTE)':' This operation will only be performed on the first VM (if more than one VM ID is passed),and the VM has to be in the C(poweredoff) state.,Also this operation will fail if an image with specified C(name) already exists.\n attribute :disk_saveas\n validates :disk_saveas, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6352078914642334, "alphanum_fraction": 0.6381992101669312, "avg_line_length": 51.234375, "blob_id": "901430e20159e79f2dfb695ceb321b419dbde126", "content_id": "59026aa1e697e517112c7ad75e0156104d2a60fc", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6686, "license_type": "permissive", "max_line_length": 178, "num_lines": 128, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/ansible_tower/tower_job_template.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, or destroy Ansible Tower job templates. See U(https://www.ansible.com/tower) for an overview.\n class Tower_job_template < Base\n # @return [String] Name to use for the job template.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Description to use for the job template.\n attribute :description\n\n # @return [:run, :check, :scan] The job type to use for the job template.\n attribute :job_type\n validates :job_type, presence: true, expression_inclusion: {:in=>[:run, :check, :scan], :message=>\"%{value} needs to be :run, :check, :scan\"}\n\n # @return [String, nil] Name of the inventory to use for the job template.\n attribute :inventory\n validates :inventory, type: String\n\n # @return [String] Name of the project to use for the job template.\n attribute :project\n validates :project, presence: true, type: String\n\n # @return [String] Path to the playbook to use for the job template within the project provided.\n attribute :playbook\n validates :playbook, presence: true, type: String\n\n # @return [String, nil] Name of the credential to use for the job template.\n attribute :credential\n validates :credential, type: String\n\n # @return [Object, nil] Name of the vault credential to use for the job template.\n attribute :vault_credential\n\n # @return [Object, nil] The number of parallel or simultaneous processes to use while executing the playbook.\n attribute :forks\n\n # @return [Object, nil] A host pattern to further constrain the list of hosts managed or affected by the playbook\n attribute :limit\n\n # @return [0, 1, 2, 3, 4, nil] Control the output level Ansible produces as the playbook runs. 0 - Normal, 1 - Verbose, 2 - More Verbose, 3 - Debug, 4 - Connection Debug.\n attribute :verbosity\n validates :verbosity, expression_inclusion: {:in=>[0, 1, 2, 3, 4], :message=>\"%{value} needs to be 0, 1, 2, 3, 4\"}, allow_nil: true\n\n # @return [Object, nil] Path to the C(extra_vars) YAML file.\n attribute :extra_vars_path\n\n # @return [Object, nil] Comma separated list of the tags to use for the job template.\n attribute :job_tags\n\n # @return [:yes, :no, nil] Enable forcing playbook handlers to run even if a task fails.\n attribute :force_handlers_enabled\n validates :force_handlers_enabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Comma separated list of the tags to skip for the job template.\n attribute :skip_tags\n\n # @return [Object, nil] Start the playbook at the task matching this name.\n attribute :start_at_task\n\n # @return [:yes, :no, nil] Enable use of fact caching for the job template.\n attribute :fact_caching_enabled\n validates :fact_caching_enabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Allow provisioning callbacks using this host config key.\n attribute :host_config_key\n\n # @return [:yes, :no, nil] Prompt user to enable diff mode (show changes) to files when supported by modules.\n attribute :ask_diff_mode\n validates :ask_diff_mode, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Prompt user for (extra_vars) on launch.\n attribute :ask_extra_vars\n validates :ask_extra_vars, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Prompt user for a limit on launch.\n attribute :ask_limit\n validates :ask_limit, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Prompt user for job tags on launch.\n attribute :ask_tags\n validates :ask_tags, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Prompt user for job tags to skip on launch.\n attribute :ask_skip_tags\n validates :ask_skip_tags, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Prompt user for job type on launch.\n attribute :ask_job_type\n validates :ask_job_type, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Prompt user to choose a verbosity level on launch.\n attribute :ask_verbosity\n validates :ask_verbosity, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Propmt user for inventory on launch.\n attribute :ask_inventory\n validates :ask_inventory, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Prompt user for credential on launch.\n attribute :ask_credential\n validates :ask_credential, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Enable a survey on the job template.\n attribute :survey_enabled\n validates :survey_enabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Activate privilege escalation.\n attribute :become_enabled\n validates :become_enabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Allow simultaneous runs of the job template.\n attribute :concurrent_jobs_enabled\n validates :concurrent_jobs_enabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7168857455253601, "alphanum_fraction": 0.7184024453163147, "avg_line_length": 52.4594612121582, "blob_id": "a7e8c0307f2264e61a2f094a2434ecfeddfbb763", "content_id": "a26da409c27d1563335b98774173cae0cb50e25e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1978, "license_type": "permissive", "max_line_length": 266, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/system/reboot.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Reboot a machine, wait for it to go down, come back up, and respond to commands.\n class Reboot < Base\n # @return [Integer, nil] Seconds for shutdown to wait before requesting reboot.,On Linux, macOS, and OpenBSD this is converted to minutes and rounded down. If less than 60, it will be set to 0.,On Solaris and FreeBSD this will be seconds.\n attribute :pre_reboot_delay\n validates :pre_reboot_delay, type: Integer\n\n # @return [Integer, nil] Seconds to wait after the reboot was successful and the connection was re-established.,This is useful if you want wait for something to settle despite your connection already working.\n attribute :post_reboot_delay\n validates :post_reboot_delay, type: Integer\n\n # @return [Integer, nil] Maximum seconds to wait for machine to reboot and respond to a test command.,This timeout is evaluated separately for both network connection and test command success so the maximum execution time for the module is twice this amount.\n attribute :reboot_timeout\n validates :reboot_timeout, type: Integer\n\n # @return [Integer, nil] Maximum seconds to wait for a successful connection to the managed hosts before trying again.,If unspecified, the default setting for the underlying connection plugin is used.\n attribute :connect_timeout\n validates :connect_timeout, type: Integer\n\n # @return [String, nil] Command to run on the rebooted host and expect success from to determine the machine is ready for further tasks.\n attribute :test_command\n validates :test_command, type: String\n\n # @return [String, nil] Message to display to users before reboot.\n attribute :msg\n validates :msg, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6766355037689209, "alphanum_fraction": 0.6766355037689209, "avg_line_length": 30.47058868408203, "blob_id": "ef8296da52c8b501e9d0551678b4675234ad9f51", "content_id": "533066065bfde7623001dc8c9a8f85419fbb62f2", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 535, "license_type": "permissive", "max_line_length": 119, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_gather_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows you to gather various information about ONTAP configuration\n class Na_ontap_gather_facts < Base\n # @return [:info, nil] Returns \"info\"\n attribute :state\n validates :state, expression_inclusion: {:in=>[:info], :message=>\"%{value} needs to be :info\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.671039342880249, "alphanum_fraction": 0.6775983572006226, "avg_line_length": 54.05555725097656, "blob_id": "fcedbe3de221932e284189f4a8078ffcf5c0f252", "content_id": "52de85f41ad2e281d3e73be80c0be0500fdc4b30", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1982, "license_type": "permissive", "max_line_length": 199, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/system/gconftool2.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows for the manipulation of GNOME 2 Configuration via gconftool-2. Please see the gconftool-2(1) man pages for more details.\n class Gconftool2 < Base\n # @return [String] A GConf preference key is an element in the GConf repository that corresponds to an application preference. See man gconftool-2(1)\n attribute :key\n validates :key, presence: true, type: String\n\n # @return [String, nil] Preference keys typically have simple values such as strings, integers, or lists of strings and integers. This is ignored if the state is \"get\". See man gconftool-2(1)\n attribute :value\n validates :value, type: String\n\n # @return [:bool, :float, :int, :string, nil] The type of value being set. This is ignored if the state is \"get\".\n attribute :value_type\n validates :value_type, expression_inclusion: {:in=>[:bool, :float, :int, :string], :message=>\"%{value} needs to be :bool, :float, :int, :string\"}, allow_nil: true\n\n # @return [:absent, :get, :present] The action to take upon the key/value.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:absent, :get, :present], :message=>\"%{value} needs to be :absent, :get, :present\"}\n\n # @return [Object, nil] Specify a configuration source to use rather than the default path. See man gconftool-2(1)\n attribute :config_source\n\n # @return [:yes, :no, nil] Access the config database directly, bypassing server. If direct is specified then the config_source must be specified as well. See man gconftool-2(1)\n attribute :direct\n validates :direct, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6869429349899292, "alphanum_fraction": 0.6885026693344116, "avg_line_length": 51.1860466003418, "blob_id": "a66024f49aee7199203965597d535e2a9f2717ee", "content_id": "72762bedd8d40b417d5cf9c209cb002e33b3adab", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4488, "license_type": "permissive", "max_line_length": 461, "num_lines": 86, "path": "/lib/ansible/ruby/modules/generated/packaging/os/redhat_subscription.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage registration and subscription to the Red Hat Subscription Management entitlement platform using the C(subscription-manager) command\n class Redhat_subscription < Base\n # @return [:present, :absent, nil] whether to register and subscribe (C(present)), or unregister (C(absent)) a system\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] access.redhat.com or Sat6 username\n attribute :username\n validates :username, type: String\n\n # @return [String, nil] access.redhat.com or Sat6 password\n attribute :password\n validates :password, type: String\n\n # @return [Object, nil] Specify an alternative Red Hat Subscription Management or Sat6 server\n attribute :server_hostname\n\n # @return [Object, nil] Enable or disable https server certificate verification when connecting to C(server_hostname)\n attribute :server_insecure\n\n # @return [Object, nil] Specify CDN baseurl\n attribute :rhsm_baseurl\n\n # @return [Object, nil] Specify an alternative location for a CA certificate for CDN\n attribute :rhsm_repo_ca_cert\n\n # @return [Object, nil] Specify a HTTP proxy hostname\n attribute :server_proxy_hostname\n\n # @return [Object, nil] Specify a HTTP proxy port\n attribute :server_proxy_port\n\n # @return [Object, nil] Specify a user for HTTP proxy with basic authentication\n attribute :server_proxy_user\n\n # @return [Object, nil] Specify a password for HTTP proxy with basic authentication\n attribute :server_proxy_password\n\n # @return [:yes, :no, nil] Upon successful registration, auto-consume available subscriptions,Added in favor of deprecated autosubscribe in 2.5.\n attribute :auto_attach\n validates :auto_attach, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] supply an activation key for use with registration\n attribute :activationkey\n validates :activationkey, type: String\n\n # @return [Integer, nil] Organization ID to use in conjunction with activationkey\n attribute :org_id\n validates :org_id, type: Integer\n\n # @return [String, nil] Register with a specific environment in the destination org. Used with Red Hat Satellite 6.x or Katello\n attribute :environment\n validates :environment, type: String\n\n # @return [String, nil] Specify a subscription pool name to consume. Regular expressions accepted. Use I(pool_ids) instead if\\r\\npossible, as it is much faster. Mutually exclusive with I(pool_ids).\\r\\n\n attribute :pool\n validates :pool, type: String\n\n # @return [Object, nil] Specify subscription pool IDs to consume. Prefer over I(pool) when possible as it is much faster.\\r\\nA pool ID may be specified as a C(string) - just the pool ID (ex. C(0123456789abcdef0123456789abcdef)),\\r\\nor as a C(dict) with the pool ID as the key, and a quantity as the value (ex.\\r\\nC(0123456789abcdef0123456789abcdef: 2). If the quantity is provided, it is used to consume multiple\\r\\nentitlements from a pool (the pool must support this). Mutually exclusive with I(pool).\\r\\n\n attribute :pool_ids\n\n # @return [Object, nil] The type of unit to register, defaults to system\n attribute :consumer_type\n\n # @return [Object, nil] Name of the system to register, defaults to the hostname\n attribute :consumer_name\n\n # @return [String, nil] References an existing consumer ID to resume using a previous registration\\r\\nfor this system. If the system's identity certificate is lost or corrupted,\\r\\nthis option allows it to resume using its previous identity and subscriptions.\\r\\nThe default is to not specify a consumer ID so a new ID is created.\\r\\n\n attribute :consumer_id\n validates :consumer_id, type: String\n\n # @return [:yes, :no, nil] Register the system even if it is already registered\n attribute :force_register\n validates :force_register, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6344085931777954, "alphanum_fraction": 0.6774193644523621, "avg_line_length": 12.285714149475098, "blob_id": "75a358cb91b669ba16126e4dae6d02c1a22464be", "content_id": "82ac2c25aee822c487519eb9d61fb52fa749b6c5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 93, "license_type": "permissive", "max_line_length": 29, "num_lines": 7, "path": "/lib/ansible/ruby/version.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nmodule Ansible\n module Ruby\n VERSION = '1.0.30'\n end\nend\n" }, { "alpha_fraction": 0.6921241283416748, "alphanum_fraction": 0.7004773020744324, "avg_line_length": 32.52000045776367, "blob_id": "36b5cfd2001a1b9267455e7b44d5acac3a9186cc", "content_id": "91877b2ca2190ee585ec440ce354211cba0c41ef", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 838, "license_type": "permissive", "max_line_length": 144, "num_lines": 25, "path": "/lib/ansible/ruby/modules/custom/cloud/core/amazon/ec2_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# VALIDATED_CHECKSUM: Qugq+Yo7e4/+12FuTIHDTMvSslvWoqvS0gxhmagEBco=\n\n# See LICENSE.txt for license\n\nrequire 'ansible/ruby/modules/generated/cloud/amazon/ec2_group'\nrequire 'ansible/ruby/modules/helpers/aws'\n\nmodule Ansible\n module Ruby\n module Modules\n class Ec2_group\n include Helpers::Aws\n\n remove_existing_validations :vpc_id\n validates :vpc_id, type: String\n remove_existing_validations :purge_rules\n remove_existing_validations :purge_rules_egress\n validates :purge_rules, expression_inclusion: { in: [true, false], message: '%{value} needs to be true, false' }, allow_nil: true\n validates :purge_rules_egress, expression_inclusion: { in: [true, false], message: '%{value} needs to be true, false' }, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6790966391563416, "alphanum_fraction": 0.680672287940979, "avg_line_length": 46.599998474121094, "blob_id": "48bc46df60dd03c0ef5cb0435f867a186d5b0208", "content_id": "ca6215e27e89bb7df382e1c99110ffcfdca98607", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1904, "license_type": "permissive", "max_line_length": 227, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcspanner.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create and Delete Instances/Databases on Spanner. See U(https://cloud.google.com/spanner/docs) for an overview.\n class Gcspanner < Base\n # @return [String] Configuration the instance should use.,Examples are us-central1, asia-east1 and europe-west1.\n attribute :configuration\n validates :configuration, presence: true, type: String\n\n # @return [String] GCP spanner instance name.\n attribute :instance_id\n validates :instance_id, presence: true, type: String\n\n # @return [String, nil] Name of database contained on the instance.\n attribute :database_name\n validates :database_name, type: String\n\n # @return [:yes, :no, nil] To delete an instance, this argument must exist and be true (along with state being equal to absent).\n attribute :force_instance_delete\n validates :force_instance_delete, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Name of Instance to display.,If not specified, instance_id will be used instead.\n attribute :instance_display_name\n\n # @return [Integer, nil] Number of nodes in the instance.\n attribute :node_count\n validates :node_count, type: Integer\n\n # @return [:absent, :present, nil] State of the instance or database. Applies to the most granular resource.,If a C(database_name) is specified we remove it.,If only C(instance_id) is specified, that is what is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6724231243133545, "alphanum_fraction": 0.6724231243133545, "avg_line_length": 45.32500076293945, "blob_id": "cac77361a300c1fbe44678efd2c5e02902b866d9", "content_id": "80f41bd5fa49c3f42b404ae7146d5eb1d3ee3e47", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1853, "license_type": "permissive", "max_line_length": 267, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_route.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update or delete a route.\n class Azure_rm_route < Base\n # @return [String] name of resource group.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] name of the route.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, nil] Assert the state of the route. Use 'present' to create or update and 'absent' to delete.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] The destination CIDR to which the route applies.\n attribute :address_prefix\n validates :address_prefix, type: String\n\n # @return [:virtual_network_gateway, :vnet_local, :internet, :virtual_appliance, :none, nil] The type of Azure hop the packet should be sent to.\n attribute :next_hop_type\n validates :next_hop_type, expression_inclusion: {:in=>[:virtual_network_gateway, :vnet_local, :internet, :virtual_appliance, :none], :message=>\"%{value} needs to be :virtual_network_gateway, :vnet_local, :internet, :virtual_appliance, :none\"}, allow_nil: true\n\n # @return [Object, nil] The IP address packets should be forwarded to.,Next hop values are only allowed in routes where the next hop type is VirtualAppliance.\n attribute :next_hop_ip_address\n\n # @return [String] The name of the route table.\n attribute :route_table_name\n validates :route_table_name, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6851089000701904, "alphanum_fraction": 0.6868746280670166, "avg_line_length": 57.58620834350586, "blob_id": "dbcf415d8b1af1628ab1222e0c70fd0b04063229", "content_id": "4a07b50dc37bf4b44ca89e134f49dccb9a35ed42", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1699, "license_type": "permissive", "max_line_length": 248, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/packaging/os/layman.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Uses Layman to manage an additional repositories for the Portage package manager on Gentoo Linux. Please note that Layman must be installed on a managed node prior using this module.\n class Layman < Base\n # @return [String] The overlay id to install, synchronize, or uninstall. Use 'ALL' to sync all of the installed overlays (can be used only when C(state=updated)).\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] An URL of the alternative overlays list that defines the overlay to install. This list will be fetched and saved under C(${overlay_defs})/${name}.xml), where C(overlay_defs) is readed from the Layman's configuration.\n attribute :list_url\n validates :list_url, type: String\n\n # @return [:present, :absent, :updated, nil] Whether to install (C(present)), sync (C(updated)), or uninstall (C(absent)) the overlay.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :updated], :message=>\"%{value} needs to be :present, :absent, :updated\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated. This should only be set to C(no) when no other option exists. Prior to 1.9.3 the code defaulted to C(no).\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.644499659538269, "alphanum_fraction": 0.6643878221511841, "avg_line_length": 38.24390411376953, "blob_id": "92c250d09a8bf2720809c07a1c31696ec827cded", "content_id": "372f4f5afb3c4219c55703f4e153adc9c7322daf", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1609, "license_type": "permissive", "max_line_length": 158, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/notification/catapult.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows notifications to be sent using sms / mms via the catapult bandwidth api.\n class Catapult < Base\n # @return [String] One of your catapult telephone numbers the message should come from (must be in E.164 format, like C(+19195551212)).\n attribute :src\n validates :src, presence: true, type: String\n\n # @return [String, Array<Integer>, Integer] The phone number or numbers the message should be sent to (must be in E.164 format, like C(+19195551212)).\n attribute :dest\n validates :dest, presence: true, type: TypeGeneric.new(Integer)\n\n # @return [String] The contents of the text message (must be 2048 characters or less).\n attribute :msg\n validates :msg, presence: true, type: String\n\n # @return [String, nil] For MMS messages, a media url to the location of the media to be sent with the message.\n attribute :media\n validates :media, type: String\n\n # @return [String] User Id from Api account page.\n attribute :user_id\n validates :user_id, presence: true, type: String\n\n # @return [String] Api Token from Api account page.\n attribute :api_token\n validates :api_token, presence: true, type: String\n\n # @return [String] Api Secret from Api account page.\n attribute :api_secret\n validates :api_secret, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.722533643245697, "alphanum_fraction": 0.7298206090927124, "avg_line_length": 80.09091186523438, "blob_id": "f9134723e8d6d8f3318d621bd1b8900b9310a158", "content_id": "e49703206b2f23b198f6bb1c35657b42661fea78", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1784, "license_type": "permissive", "max_line_length": 874, "num_lines": 22, "path": "/lib/ansible/ruby/modules/generated/clustering/k8s/k8s.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Use the OpenShift Python client to perform CRUD operations on K8s objects.\n # Pass the object definition from a source file or inline. See examples for reading files and using Jinja templates.\n # Access to the full range of K8s APIs.\n # Use the M(k8s_facts) module to obtain a list of items about an object of type C(kind)\n # Authenticate using either a config file, certificates, password or token.\n # Supports check mode.\n class K8s < Base\n # @return [:json, :merge, :\"strategic-merge\", nil] Whether to override the default patch merge approach with a specific type. By the default, the strategic merge will typically be used.,For example, Custom Resource Definitions typically aren't updatable by the usual strategic merge. You may want to use C(merge) if you see \"strategic merge patch format is not supported\",See U(https://kubernetes.io/docs/tasks/run-application/update-api-object-kubectl-patch/#use-a-json-merge-patch-to-update-a-deployment),Requires openshift >= 0.6.2,If more than one merge_type is given, the merge_types will be tried in order,If openshift >= 0.6.2, this defaults to C(['strategic-merge', 'merge']), which is ideal for using the same parameters on resource kinds that combine Custom Resources and built-in resources. For openshift < 0.6.2, the default is simply C(strategic-merge).\n attribute :merge_type\n validates :merge_type, expression_inclusion: {:in=>[:json, :merge, :\"strategic-merge\"], :message=>\"%{value} needs to be :json, :merge, :\\\"strategic-merge\\\"\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6466985940933228, "alphanum_fraction": 0.6514909267425537, "avg_line_length": 48.421051025390625, "blob_id": "4b504e9f616becfa9a72905e424963b86612f5e9", "content_id": "1128b136af85befe7f3ef083b2fe0fa72bdc34c3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3756, "license_type": "permissive", "max_line_length": 278, "num_lines": 76, "path": "/lib/ansible/ruby/modules/generated/network/meraki/meraki_switchport.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows for management of switchports settings for Meraki MS switches.\n class Meraki_switchport < Base\n # @return [:query, :present, nil] Specifies whether a switchport should be queried or modified.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:query, :present], :message=>\"%{value} needs to be :query, :present\"}, allow_nil: true\n\n # @return [Object, nil] Number of the access policy to apply.,Only applicable to access port types.\n attribute :access_policy_number\n\n # @return [String, nil] List of VLAN numbers to be allowed on switchport.\n attribute :allowed_vlans\n validates :allowed_vlans, type: String\n\n # @return [Boolean, nil] Whether a switchport should be enabled or disabled.\n attribute :enabled\n validates :enabled, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Symbol, nil] Isolation status of switchport.\n attribute :isolation_enabled\n validates :isolation_enabled, type: Symbol\n\n # @return [:\"Auto negotiate\", :\"100Megabit (auto)\", :\"100 Megabit full duplex (forced)\", nil] Link speed for the switchport.\n attribute :link_negotiation\n validates :link_negotiation, expression_inclusion: {:in=>[:\"Auto negotiate\", :\"100Megabit (auto)\", :\"100 Megabit full duplex (forced)\"], :message=>\"%{value} needs to be :\\\"Auto negotiate\\\", :\\\"100Megabit (auto)\\\", :\\\"100 Megabit full duplex (forced)\\\"\"}, allow_nil: true\n\n # @return [String, nil] Switchport description.\n attribute :name\n validates :name, type: String\n\n # @return [Integer, nil] Port number.\n attribute :number\n validates :number, type: Integer\n\n # @return [Boolean, nil] Enable or disable Power Over Ethernet on a port.\n attribute :poe_enabled\n validates :poe_enabled, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Enable or disable Rapid Spanning Tree Protocol on a port.\n attribute :rstp_enabled\n validates :rstp_enabled, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] Serial nubmer of the switch.\n attribute :serial\n validates :serial, type: String\n\n # @return [:disabled, :\"root guard\", :\"bpdu guard\", :\"loop guard\", nil] Set state of STP guard.\n attribute :stp_guard\n validates :stp_guard, expression_inclusion: {:in=>[:disabled, :\"root guard\", :\"bpdu guard\", :\"loop guard\"], :message=>\"%{value} needs to be :disabled, :\\\"root guard\\\", :\\\"bpdu guard\\\", :\\\"loop guard\\\"\"}, allow_nil: true\n\n # @return [String, nil] Space delimited list of tags to assign to a port.\n attribute :tags\n validates :tags, type: String\n\n # @return [:access, :trunk, nil] Set port type.\n attribute :type\n validates :type, expression_inclusion: {:in=>[:access, :trunk], :message=>\"%{value} needs to be :access, :trunk\"}, allow_nil: true\n\n # @return [Integer, nil] VLAN number assigned to port.,If a port is of type trunk, the specified VLAN is the native VLAN.\n attribute :vlan\n validates :vlan, type: Integer\n\n # @return [Integer, nil] VLAN number assigned to a port for voice traffic.,Only applicable to access port type.\n attribute :voice_vlan\n validates :voice_vlan, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6435872316360474, "alphanum_fraction": 0.6461149454116821, "avg_line_length": 33.729007720947266, "blob_id": "6986f59e2def0b1f9b07c33a4c93b758212ab329", "content_id": "770ec08f3a827cf4b4a371a31f5cc5d7e7329565", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 9099, "license_type": "permissive", "max_line_length": 134, "num_lines": 262, "path": "/Rakefile", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'bundler/gem_tasks'\nrequire 'rspec/core/rake_task'\nrequire 'rubocop/rake_task'\nrequire 'reek/rake/task'\nrequire 'ansible/ruby/rake/tasks'\nrequire_relative 'util/parser'\nrequire 'digest'\nrequire 'json'\n$: << '.'\n\ntask default: %i[spec\n report_coverage\n update_modules\n rubocop\n compile_examples\n verify_custom_mods]\n\ntask :report_coverage do\n sh 'codeclimate-test-reporter' if ENV['TRAVIS']\nend\n\ndesc 'Run specs'\nRSpec::Core::RakeTask.new :spec do |task|\n task.pattern = 'lib/**/*_spec.rb,util/**/*_spec.rb'\nend\n\ndesc 'Runs Rubocop'\nRuboCop::RakeTask.new do |task|\n task.options = %w[-D -S]\nend\n\ndesc 'Runs Reek stuff'\nReek::Rake::Task.new do |task|\n # rake task overrides all config.reek exclusions, which is annoying and it won't let us set a FileList directly\n files = FileList['**/*.rb']\n .exclude('vendor/**/*') # Travis stuff\n task.instance_variable_set :@source_files, files\nend\n\ntask :python_dependencies do\n sh 'pip3 install ansible==2.7.1 ansible-lint'\nend\n\ndesc 'Compiles examples'\ntask :compile_examples do\n Dir.chdir 'examples' do\n tasks = %w[ami block command default]\n clean_compile = tasks.map { |task| \"#{task}_clean\" } + tasks.map { |task| \"#{task}_compile\" }\n sh \"rake --trace #{clean_compile.join ' '}\"\n end\nend\n\ndesc 'Runs a check against generated playbooks'\ntask ansible_lint: %i[compile_examples python_dependencies] do\n ansible_lint_dir = `python3 util/get_ansible_lint.py`.strip\n puts \"Ansible lint directory #{ansible_lint_dir}\"\n playbooks = FileList['examples/**/*.yml'].join ' '\n sh \"python3 #{ansible_lint_dir}/__init__.py -v #{playbooks}\"\nend\n\nno_examples_ok = [\n 'async_status.py', # none exist\n 'nmcli.py', # complex examples\n 'slurp.py' # no examples that aren't command lines\n]\nSKIP_EXAMPLES_REGEX = no_examples_ok.map { |text| Regexp.new text }\n\ndef skip_example?(file)\n SKIP_EXAMPLES_REGEX.any? { |regex| regex.match(file) }\nend\n\ndef get_yaml(file)\n python = File.read file\n metadata_json = /^ANSIBLE_METADATA = (.*?\\})/m.match(python).captures[0]\n metadata_json = metadata_json.gsub(\"'\", '\"')\n metadata = JSON.parse(metadata_json)\n if metadata['status'].include? 'removed'\n puts \"Skipping #{file} because it has removed status\"\n return nil\n end\n match = /^DOCUMENTATION.*?['\"]{3}(.*?)['\"]{3}/m.match(python)\n raise \"Unable to find description in #{file}\" unless match\n\n description = match[1]\n match = /^EXAMPLES.*?['\"]{3}(.*?)['\"]{3}/m.match(python)\n examples = if match\n match[1]\n else\n raise \"Unable to find examples in #{file}\" unless skip_example?(file)\n end\n [description, examples]\nend\n\ndesc 'Update/generate Ruby modules from Ansible modules'\ntask update_modules: %i[generate_modules verify_checksums]\n\nNEW_CHECKSUMS = 'util/checksums_new.json'\ntask generate_modules: :python_dependencies do\n generated_dir = 'lib/ansible/ruby/modules/generated'\n sh \"rm -rf #{generated_dir}\"\n mkdir generated_dir\n cp 'lib/ansible/ruby/modules/rubocop_generated.yml',\n \"#{generated_dir}/.rubocop.yml\"\n ansible_dir = `python3 util/get_ansible.py`.strip\n puts \"Ansible directory #{ansible_dir}\"\n modules_dir = Pathname.new(File.join(ansible_dir, 'modules'))\n files = if ENV['FILE']\n [ENV['FILE']]\n else\n FileList[File.join(ansible_dir, 'modules/**/*.py')]\n .exclude(/__init__.py/)\n .exclude(/include_vars.py/)\n .exclude(/async_wrapper.py/)\n .exclude(/netscaler_lb_vserver.py/) # TODO: Fix these modules\n .exclude(/netscaler_lb_monitor.py/) # TODO: Fix these modules\n end\n processed_files = []\n checksums = {}\n fails = {}\n files.each do |file|\n for_file = []\n out = StringIO.new\n $stderr = out\n begin\n for_file << 'Retrieving description and example'\n results = get_yaml file\n next unless results\n\n description, example = results\n for_file << 'Parsing YAML'\n example_fail_is_ok = skip_example?(file)\n ruby_result = Ansible::Ruby::Parser.from_yaml_string description,\n example,\n example_fail_is_ok\n python_dir = File.dirname(file)\n ruby_filename = File.basename(file, '.py') + '.rb'\n # don't want leading _ in front of stuff\n ruby_filename.gsub!(/^_/, '')\n module_path = Pathname.new(python_dir).relative_path_from(modules_dir)\n ruby_path = File.join('lib/ansible/ruby/modules/generated', module_path, ruby_filename)\n mkdir_p File.dirname(ruby_path)\n for_file << \"Writing Ruby code to #{ruby_path}\"\n processed_files << ruby_path\n raise \"We've already processed a module by this name!\" if checksums.include? ruby_filename\n\n checksums[ruby_filename] = Digest::SHA256.base64digest ruby_result\n File.write ruby_path, ruby_result\n rescue StandardError => e\n for_file << $stderr.string\n fails[file] = {\n exception: e,\n output: for_file.join(\"\\n\")\n }\n raise \"File #{file}\" + fails[file].to_s if ENV['STOP_AFTER_ONE']\n ensure\n $stderr = STDERR\n end\n end\n\n fails.each do |file, details|\n puts \"Failed file #{file}\"\n puts details[:output]\n exception = details[:exception]\n puts exception\n puts exception.backtrace\n puts '-----------------------------------'\n end\n\n puts \"#{processed_files.length} modules successfully processed. #{fails.length} failures\"\n raise '1 or more files failed' if fails.any?\n\n base_dir = Pathname.new('lib')\n puts 'Writing checksums'\n File.write NEW_CHECKSUMS, JSON.pretty_generate(checksums)\n puts 'Writing requires'\n File.open 'lib/ansible/ruby/modules/all.rb', 'w' do |file|\n file << <<~HEADER\n # frozen_string_literal: true\n # Generated file, DO NOT EDIT!\n\n ansible_mod = Ansible::Ruby::Modules\n\n HEADER\n overridden_modules = []\n processed_files.each do |ruby, _|\n relative = Pathname.new(ruby).relative_path_from(base_dir)\n without_extension = relative.to_s.gsub(/\\.rb$/, '')\n klass_name = File.basename without_extension\n custom_modules = FileList[\"lib/ansible/ruby/modules/custom/**/#{File.basename(relative)}\"]\n if custom_modules.any?\n custom_module = custom_modules[0]\n overridden_modules << custom_module\n file << \"# Using custom module\\n\"\n without_extension = Pathname.new(custom_module).relative_path_from(base_dir).to_s\n without_extension = without_extension.gsub(/\\.rb$/, '')\n end\n file << \"ansible_mod.autoload(:#{klass_name.capitalize}, '#{without_extension}')\\n\"\n end\n (FileList['lib/ansible/ruby/modules/custom/**/*.rb'].exclude('**/*_spec.rb') - overridden_modules).each do |mod|\n relative = Pathname.new(mod).relative_path_from(base_dir)\n without_extension = relative.to_s.gsub(/\\.rb$/, '')\n klass_name = File.basename without_extension\n file << \"ansible_mod.autoload(:#{klass_name.capitalize}, '#{without_extension}')\\n\"\n end\n end\nend\n\ndef custom_module_files\n FileList['lib/ansible/ruby/modules/custom/**/*.rb'].exclude('**/*_spec.rb')\nend\n\ntask :verify_checksums do\n existing_sums = 'util/checksums_existing.json'\n new_checksums = JSON.parse File.read(NEW_CHECKSUMS)\n valid_custom_checksums = Hash[custom_module_files.map do |filename|\n file_contents = File.read filename\n module_only = File.basename(filename)\n match = /# VALIDATED_CHECKSUM: (.*)$/.match(file_contents)\n validated_checksum = match && match[1]\n unless validated_checksum\n validated_checksum = new_checksums[module_only]\n # No need for empty checksums\n if validated_checksum\n puts \"Adding checksum to #{filename}\"\n lines = file_contents.split \"\\n\"\n index = lines.find_index '# frozen_string_literal: true'\n lines.insert index + 1, \"# VALIDATED_CHECKSUM: #{validated_checksum}\"\n # trailing new line for file\n lines << ''\n File.write filename, lines.join(\"\\n\")\n end\n end\n [module_only, validated_checksum]\n end]\n\n problems = new_checksums.map do |changed_file, new_checksum|\n next unless valid_custom_checksums.include? changed_file\n\n existing_checksum = valid_custom_checksums[changed_file]\n next unless existing_checksum != new_checksum\n\n \"Module #{changed_file} - old checksum - #{existing_checksum} - new checksum #{new_checksum}\"\n end.compact\n\n if problems.any?\n puts 'The following files have been customized and the generated module has changed.'\n puts 'Once you have validated the changes, remove the # VALIDATED_CHECKSUM line at the top of your source file and run this again'\n puts problems.join \"\\n\"\n raise 'Failed checksum'\n end\n mv NEW_CHECKSUMS, existing_sums\nend\n\ndesc 'Verify custom modules all require properly'\ntask :verify_custom_mods do\n custom_module_files.each do |file|\n puts \"Verifying we can require custom file #{file}\"\n require file\n end\nend\n" }, { "alpha_fraction": 0.6711239218711853, "alphanum_fraction": 0.6714624166488647, "avg_line_length": 44.4461555480957, "blob_id": "5cdd65a46fc963fc3832693bd3a133374babec75", "content_id": "cdc6f99061ce5d386a287c4129bcdbd42bd27b4d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5908, "license_type": "permissive", "max_line_length": 310, "num_lines": 130, "path": "/lib/ansible/ruby/modules/generated/network/panos/panos_security_rule.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Security policies allow you to enforce rules and take action, and can be as general or specific as needed. The policy rules are compared against the incoming traffic in sequence, and because the first rule that matches the traffic is applied, the more specific rules must precede the more general ones.\n class Panos_security_rule < Base\n # @return [String] IP address (or hostname) of PAN-OS device being configured.\n attribute :ip_address\n validates :ip_address, presence: true, type: String\n\n # @return [String, nil] Username credentials to use for auth unless I(api_key) is set.\n attribute :username\n validates :username, type: String\n\n # @return [String] Password credentials to use for auth unless I(api_key) is set.\n attribute :password\n validates :password, presence: true, type: String\n\n # @return [String, nil] API key that can be used instead of I(username)/I(password) credentials.\n attribute :api_key\n validates :api_key, type: String\n\n # @return [String, nil] The action to be taken. Supported values are I(add)/I(update)/I(find)/I(delete).\n attribute :operation\n validates :operation, type: String\n\n # @return [String] Name of the security rule.\n attribute :rule_name\n validates :rule_name, presence: true, type: String\n\n # @return [String, nil] Type of security rule (version 6.1 of PanOS and above).\n attribute :rule_type\n validates :rule_type, type: String\n\n # @return [String, nil] Description for the security rule.\n attribute :description\n validates :description, type: String\n\n # @return [Array<String>, String, nil] Administrative tags that can be added to the rule. Note, tags must be already defined.\n attribute :tag_name\n validates :tag_name, type: TypeGeneric.new(String)\n\n # @return [String, nil] List of source zones.\n attribute :source_zone\n validates :source_zone, type: String\n\n # @return [String, nil] List of destination zones.\n attribute :destination_zone\n validates :destination_zone, type: String\n\n # @return [String, nil] List of source addresses.\n attribute :source_ip\n validates :source_ip, type: String\n\n # @return [String, nil] Use users to enforce policy for individual users or a group of users.\n attribute :source_user\n validates :source_user, type: String\n\n # @return [String, nil] - If you are using GlobalProtect with host information profile (HIP) enabled, you can also base the policy on information collected by GlobalProtect. For example, the user access level can be determined HIP that notifies the firewall about the user's local configuration.\\r\\n\n attribute :hip_profiles\n validates :hip_profiles, type: String\n\n # @return [String, nil] List of destination addresses.\n attribute :destination_ip\n validates :destination_ip, type: String\n\n # @return [String, nil] List of applications.\n attribute :application\n validates :application, type: String\n\n # @return [String, nil] List of services.\n attribute :service\n validates :service, type: String\n\n # @return [Boolean, nil] Whether to log at session start.\n attribute :log_start\n validates :log_start, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Whether to log at session end.\n attribute :log_end\n validates :log_end, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] Action to apply once rules maches.\n attribute :action\n validates :action, type: String\n\n # @return [Object, nil] - Security profile group that is already defined in the system. This property supersedes antivirus, vulnerability, spyware, url_filtering, file_blocking, data_filtering, and wildfire_analysis properties.\\r\\n\n attribute :group_profile\n\n # @return [String, nil] Name of the already defined antivirus profile.\n attribute :antivirus\n validates :antivirus, type: String\n\n # @return [String, nil] Name of the already defined vulnerability profile.\n attribute :vulnerability\n validates :vulnerability, type: String\n\n # @return [String, nil] Name of the already defined spyware profile.\n attribute :spyware\n validates :spyware, type: String\n\n # @return [String, nil] Name of the already defined url_filtering profile.\n attribute :url_filtering\n validates :url_filtering, type: String\n\n # @return [Object, nil] Name of the already defined file_blocking profile.\n attribute :file_blocking\n\n # @return [Object, nil] Name of the already defined data_filtering profile.\n attribute :data_filtering\n\n # @return [String, nil] Name of the already defined wildfire_analysis profile.\n attribute :wildfire_analysis\n validates :wildfire_analysis, type: String\n\n # @return [String, nil] - Device groups are used for the Panorama interaction with Firewall(s). The group must exists on Panorama. If device group is not define we assume that we are contacting Firewall.\\r\\n\n attribute :devicegroup\n validates :devicegroup, type: String\n\n # @return [:yes, :no, nil] Commit configuration if changed.\n attribute :commit\n validates :commit, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.73081374168396, "alphanum_fraction": 0.73081374168396, "avg_line_length": 67.2368392944336, "blob_id": "ccc0eac9bb1e76b46ca2efae5b418e44e43f43f2", "content_id": "9998323744827692f33a8d644bef7afb64598042", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2593, "license_type": "permissive", "max_line_length": 300, "num_lines": 38, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_system.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of node system attributes on Cisco NXOS devices. It provides an option to configure host system parameters or remove those parameters from the device active configuration.\n class Nxos_system < Base\n # @return [String, nil] Configure the device hostname parameter. This option takes an ASCII string value or keyword 'default'\n attribute :hostname\n validates :hostname, type: String\n\n # @return [String, nil] Configures the default domain name suffix to be used when referencing this node by its FQDN. This argument accepts either a list of domain names or a list of dicts that configure the domain name and VRF name or keyword 'default'. See examples.\n attribute :domain_name\n validates :domain_name, type: String\n\n # @return [Object, nil] Enables or disables the DNS lookup feature in Cisco NXOS. This argument accepts boolean values. When enabled, the system will try to resolve hostnames using DNS and when disabled, hostnames will not be resolved.\n attribute :domain_lookup\n\n # @return [Object, nil] Configures a list of domain name suffixes to search when performing DNS name resolution. This argument accepts either a list of domain names or a list of dicts that configure the domain name and VRF name or keyword 'default'. See examples.\n attribute :domain_search\n\n # @return [Array<String>, String, nil] List of DNS name servers by IP address to use to perform name resolution lookups. This argument accepts either a list of DNS servers or a list of hashes that configure the name server and VRF name or keyword 'default'. See examples.\n attribute :name_servers\n validates :name_servers, type: TypeGeneric.new(String, Hash)\n\n # @return [Object, nil] Specifies the mtu, must be an integer or keyword 'default'.\n attribute :system_mtu\n\n # @return [:present, :absent, nil] State of the configuration values in the device's current active configuration. When set to I(present), the values should be configured in the device active configuration and when set to I(absent) the values should not be in the device active configuration\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6812002062797546, "alphanum_fraction": 0.6812002062797546, "avg_line_length": 49.78571319580078, "blob_id": "e6998ae96d019105c70cb0581615fbabd47af928", "content_id": "295f642cd9429eeeadddbe21eb3568551e752eef", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2133, "license_type": "permissive", "max_line_length": 250, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/cloud/opennebula/one_image.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages OpenNebula images\n class One_image < Base\n # @return [Object, nil] URL of the OpenNebula RPC server.,It is recommended to use HTTPS so that the username/password are not,transferred over the network unencrypted.,If not set then the value of the C(ONE_URL) environment variable is used.\n attribute :api_url\n\n # @return [Object, nil] Name of the user to login into the OpenNebula RPC server. If not set,then the value of the C(ONE_USERNAME) environment variable is used.\n attribute :api_username\n\n # @return [Object, nil] Password of the user to login into OpenNebula RPC server. If not set,then the value of the C(ONE_PASSWORD) environment variable is used.\n attribute :api_password\n\n # @return [Integer, String, nil] A C(id) of the image you would like to manage.\n attribute :id\n validates :id, type: MultipleTypes.new(Integer, String)\n\n # @return [String, nil] A C(name) of the image you would like to manage.\n attribute :name\n validates :name, type: String\n\n # @return [:present, :absent, :cloned, :renamed, nil] C(present) - state that is used to manage the image,C(absent) - delete the image,C(cloned) - clone the image,C(renamed) - rename the image to the C(new_name)\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :cloned, :renamed], :message=>\"%{value} needs to be :present, :absent, :cloned, :renamed\"}, allow_nil: true\n\n # @return [Symbol, nil] Whether the image should be enabled or disabled.\n attribute :enabled\n validates :enabled, type: Symbol\n\n # @return [String, nil] A name that will be assigned to the existing or new image.,In the case of cloning, by default C(new_name) will take the name of the origin image with the prefix 'Copy of'.\n attribute :new_name\n validates :new_name, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7235820293426514, "alphanum_fraction": 0.7246079444885254, "avg_line_length": 85.3670883178711, "blob_id": "90187d63e7feaf4a8f4663857f6ecc1553952d62", "content_id": "ac0de22575835f5b3516cba468b8b75951f5f8b5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6823, "license_type": "permissive", "max_line_length": 953, "num_lines": 79, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_sqldatabase.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and delete instance of SQL Database.\n class Azure_rm_sqldatabase < Base\n # @return [String] The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] The name of the server.\n attribute :server_name\n validates :server_name, presence: true, type: String\n\n # @return [String] The name of the database to be operated on (updated or created).\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Resource location. If not set, location from the resource group will be used as C(default).\n attribute :location\n validates :location, type: String\n\n # @return [Object, nil] The collation of the database. If I(create_mode) is not C(default), this value is ignored.\n attribute :collation\n\n # @return [:copy, :default, :non_readable_secondary, :online_secondary, :point_in_time_restore, :recovery, :restore, :restore_long_term_retention_backup, nil] Specifies the mode of database creation.,C(default): regular database creation.,C(copy): creates a database as a copy of an existing database.,C(online_secondary)/C(non_readable_secondary): creates a database as a (readable or nonreadable) secondary replica of an existing database.,C(point_in_time_restore): Creates a database by restoring a point in time backup of an existing database.,C(recovery): Creates a database by restoring a geo-replicated backup.,C(restore): Creates a database by restoring a backup of a deleted database.,C(restore_long_term_retention_backup): Creates a database by restoring from a long term retention vault.,C(copy), C(non_readable_secondary), C(online_secondary) and C(restore_long_term_retention_backup) are not supported for C(data_warehouse) edition.\n attribute :create_mode\n validates :create_mode, expression_inclusion: {:in=>[:copy, :default, :non_readable_secondary, :online_secondary, :point_in_time_restore, :recovery, :restore, :restore_long_term_retention_backup], :message=>\"%{value} needs to be :copy, :default, :non_readable_secondary, :online_secondary, :point_in_time_restore, :recovery, :restore, :restore_long_term_retention_backup\"}, allow_nil: true\n\n # @return [String, nil] Required unless I(create_mode) is C(default) or C(restore_long_term_retention_backup).,Specifies the resource ID of the source database\n attribute :source_database_id\n validates :source_database_id, type: String\n\n # @return [Object, nil] Required if I(create_mode) is C(restore) and I(source_database_id) is the deleted database's original resource id when it existed (as opposed to its current restorable dropped database id), then this value is required. Specifies the time that the database was deleted.\n attribute :source_database_deletion_date\n\n # @return [Object, nil] Required if I(create_mode) is C(point_in_time_restore), this value is required. If I(create_mode) is C(restore), this value is optional. Specifies the point in time (ISO8601 format) of the source database that will be restored to create the new database. Must be greater than or equal to the source database's earliestRestoreDate value.\n attribute :restore_point_in_time\n\n # @return [Object, nil] Required if I(create_mode) is C(restore_long_term_retention_backup), then this value is required. Specifies the resource ID of the recovery point to restore from.\n attribute :recovery_services_recovery_point_resource_id\n\n # @return [:web, :business, :basic, :standard, :premium, :free, :stretch, :data_warehouse, :system, :system2, nil] The edition of the database. The DatabaseEditions enumeration contains all the valid editions. If I(create_mode) is C(non_readable_secondary) or C(online_secondary), this value is ignored. To see possible values, query the capabilities API (/subscriptions/{subscriptionId}/providers/Microsoft.Sql/locations/{locationID}/capabilities) referred to by operationId: 'Capabilities_ListByLocation.'.\n attribute :edition\n validates :edition, expression_inclusion: {:in=>[:web, :business, :basic, :standard, :premium, :free, :stretch, :data_warehouse, :system, :system2], :message=>\"%{value} needs to be :web, :business, :basic, :standard, :premium, :free, :stretch, :data_warehouse, :system, :system2\"}, allow_nil: true\n\n # @return [Object, nil] The max size of the database expressed in bytes. If I(create_mode) is not C(default), this value is ignored. To see possible values, query the capabilities API (/subscriptions/{subscriptionId}/providers/Microsoft.Sql/locations/{locationID}/capabilities) referred to by operationId: 'Capabilities_ListByLocation.'\n attribute :max_size_bytes\n\n # @return [Object, nil] The name of the elastic pool the database is in. Not supported for C(data_warehouse) edition.\n attribute :elastic_pool_name\n\n # @return [Symbol, nil] If the database is a geo-secondary, indicates whether read-only connections are allowed to this database or not. Not supported for C(data_warehouse) edition.\n attribute :read_scale\n validates :read_scale, type: Symbol\n\n # @return [:adventure_works_lt, nil] Indicates the name of the sample schema to apply when creating this database. If I(create_mode) is not C(default), this value is ignored. Not supported for C(data_warehouse) edition.\n attribute :sample_name\n validates :sample_name, expression_inclusion: {:in=>[:adventure_works_lt], :message=>\"%{value} needs to be :adventure_works_lt\"}, allow_nil: true\n\n # @return [Symbol, nil] Is this database is zone redundant? It means the replicas of this database will be spread across multiple availability zones.\n attribute :zone_redundant\n validates :zone_redundant, type: Symbol\n\n # @return [Symbol, nil] SQL Database will be updated if given parameters differ from existing resource state.,To force SQL Database update in any circumstances set this parameter to True.\n attribute :force_update\n validates :force_update, type: Symbol\n\n # @return [:absent, :present, nil] Assert the state of the SQL Database. Use 'present' to create or update an SQL Database and 'absent' to delete it.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6908923387527466, "alphanum_fraction": 0.6908923387527466, "avg_line_length": 26.871795654296875, "blob_id": "61253d8d8bf2b5860d73826a3a62b2213f4d631d", "content_id": "7f8b5194365fec79ac926714933331113425003b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1087, "license_type": "permissive", "max_line_length": 123, "num_lines": 39, "path": "/lib/ansible/ruby/models/type_validator.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# See LICENSE.txt for license\n\nclass TypeValidator < ActiveModel::EachValidator\n def validate_each(record, attribute, value)\n # Don't worry about this case, different validator\n return if value.is_a? NilClass\n\n # We won't know until runtime what the type is\n return if value.is_a? Ansible::Ruby::Models::JinjaExpression\n\n failed = perform_validation(attribute, value)\n return unless failed\n\n failed = custom_error(value) if options[:message]\n record.errors[attribute] << failed\n end\n\n private\n\n def expected_type\n options[:type] || options[:with]\n end\n\n def perform_validation(attribute, value)\n case expected_type\n when TypeGeneric, MultipleTypes\n expected_type.error(attribute, value) unless expected_type.valid? value\n else\n \"Attribute #{attribute} expected to be a #{expected_type} but was a #{value.class}\" unless value.is_a?(expected_type)\n end\n end\n\n def custom_error(value)\n options[:message].gsub('%{value}', value.to_s)\n .gsub('%{type}', value.class.name)\n end\nend\n" }, { "alpha_fraction": 0.6766743659973145, "alphanum_fraction": 0.6766743659973145, "avg_line_length": 51.80487823486328, "blob_id": "c1ccda3da11f29eeec90f5d958aa02aa8fff1c05", "content_id": "318a58be911c2dcfc67652483da1e8f0035ae805", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2165, "license_type": "permissive", "max_line_length": 254, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_vm_vm_drs_rule.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to configure VMware DRS Affinity rule for virtual machine in given cluster.\n class Vmware_vm_vm_drs_rule < Base\n # @return [String] Desired cluster name where virtual machines are present for the DRS rule.\n attribute :cluster_name\n validates :cluster_name, presence: true, type: String\n\n # @return [Array<String>, String, nil] List of virtual machines name for which DRS rule needs to be applied.,Required if C(state) is set to C(present).\n attribute :vms\n validates :vms, type: TypeGeneric.new(String)\n\n # @return [String] The name of the DRS rule to manage.\n attribute :drs_rule_name\n validates :drs_rule_name, presence: true, type: String\n\n # @return [Symbol, nil] If set to C(True), the DRS rule will be enabled.,Effective only if C(state) is set to C(present).\n attribute :enabled\n validates :enabled, type: Symbol\n\n # @return [Symbol, nil] If set to C(True), the DRS rule will be mandatory.,Effective only if C(state) is set to C(present).\n attribute :mandatory\n validates :mandatory, type: Symbol\n\n # @return [Boolean, nil] If set to C(True), the DRS rule will be an Affinity rule.,If set to C(False), the DRS rule will be an Anti-Affinity rule.,Effective only if C(state) is set to C(present).\n attribute :affinity_rule\n validates :affinity_rule, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:present, :absent, nil] If set to C(present), then the DRS rule is created if not present.,If set to C(present), then the DRS rule is deleted and created if present already.,If set to C(absent), then the DRS rule is deleted if present.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6721581816673279, "alphanum_fraction": 0.6721581816673279, "avg_line_length": 27.904762268066406, "blob_id": "7785e05eaa013c970ed6d7f3f1e78738a345a06f", "content_id": "a696d7c6340c3ff31c3988cbc1b8643966d1f543", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 607, "license_type": "permissive", "max_line_length": 94, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_scheduling_policy_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Retrieve facts about one or more oVirt scheduling policies.\n class Ovirt_scheduling_policy_facts < Base\n # @return [Object] ID of the scheduling policy.\n attribute :id\n validates :id, presence: true\n\n # @return [String, nil] Name of the scheduling policy, can be used as glob expression.\n attribute :name\n validates :name, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7259852290153503, "alphanum_fraction": 0.7317323684692383, "avg_line_length": 86, "blob_id": "e32ad17cd2f7002e991debe528c5eafb6a33db74", "content_id": "263790f96c7af1b91f31ee9d3d3f3e22e3e0aa26", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4872, "license_type": "permissive", "max_line_length": 651, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/windows/win_package.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Installs or uninstalls a package in either an MSI or EXE format.\n # These packages can be sources from the local file system, network file share or a url.\n # Please read the notes section around some caveats with this module.\n class Win_package < Base\n # @return [Array<String>, String, nil] Any arguments the installer needs to either install or uninstall the package.,If the package is an MSI do not supply the C(/qn), C(/log) or C(/norestart) arguments.,As of Ansible 2.5, this parameter can be a list of arguments and the module will escape the arguments as necessary, it is recommended to use a string when dealing with MSI packages due to the unique escaping issues with msiexec.\n attribute :arguments\n validates :arguments, type: TypeGeneric.new(String)\n\n # @return [String, nil] Will check the existance of the path specified and use the result to determine whether the package is already installed.,You can use this in conjunction with C(product_id) and other C(creates_*).\n attribute :creates_path\n validates :creates_path, type: String\n\n # @return [Object, nil] Will check the existing of the service specified and use the result to determine whether the package is already installed.,You can use this in conjunction with C(product_id) and other C(creates_*).\n attribute :creates_service\n\n # @return [Float, nil] Will check the file version property of the file at C(creates_path) and use the result to determine whether the package is already installed.,C(creates_path) MUST be set and is a file.,You can use this in conjunction with C(product_id) and other C(creates_*).\n attribute :creates_version\n validates :creates_version, type: Float\n\n # @return [Array<String>, String, nil] One or more return codes from the package installation that indicates success.,Before Ansible 2.4 this was just 0 but since 2.4 this is both C(0) and C(3010).,A return code of C(3010) usually means that a reboot is required, the C(reboot_required) return value is set if the return code is C(3010).\n attribute :expected_return_code\n validates :expected_return_code, type: TypeGeneric.new(String)\n\n # @return [Object, nil] The password for C(user_name), must be set when C(user_name) is.\n attribute :password\n\n # @return [String, nil] Location of the package to be installed or uninstalled.,This package can either be on the local file system, network share or a url.,If the path is on a network share and the current WinRM transport doesn't support credential delegation, then C(user_name) and C(user_password) must be set to access the file.,There are cases where this file will be copied locally to the server so it can access it, see the notes for more info.,If C(state=present) then this value MUST be set.,If C(state=absent) then this value does not need to be set if C(product_id) is.\n attribute :path\n validates :path, type: String\n\n # @return [String, nil] The product id of the installed packaged.,This is used for checking whether the product is already installed and getting the uninstall information if C(state=absent).,You can find product ids for installed programs in the Windows registry editor either at C(HKLM:Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall) or for 32 bit programs at C(HKLM:Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall).,This SHOULD be set when the package is not an MSI, or the path is a url or a network share and credential delegation is not being used. The C(creates_*) options can be used instead but is not recommended.\n attribute :product_id\n validates :product_id, type: String\n\n # @return [String, nil] Whether to install or uninstall the package.,The module uses C(product_id) and whether it exists at the registry path to see whether it needs to install or uninstall the package.\n attribute :state\n validates :state, type: String\n\n # @return [Object, nil] Username of an account with access to the package if it is located on a file share.,This is only needed if the WinRM transport is over an auth method that does not support credential delegation like Basic or NTLM.\n attribute :username\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.,Before Ansible 2.4 this defaulted to C(no).\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6903954744338989, "alphanum_fraction": 0.694915235042572, "avg_line_length": 54.3125, "blob_id": "292dec1e5b419f905608a3f8bd88c92c4c1487b5", "content_id": "130280a8aab66c8b1781b25f95b7e744c70dd290", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3540, "license_type": "permissive", "max_line_length": 377, "num_lines": 64, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_vmkernel.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to manage the VMWare VMKernel interface (also known as Virtual NICs) of host system.\n # This module assumes that the host is already configured with Portgroup and vSwitch.\n class Vmware_vmkernel < Base\n # @return [String, nil] The name of the vSwitch where to add the VMKernel interface.,Required parameter only if C(state) is set to C(present).,Optional parameter from version 2.5 and onwards.\n attribute :vswitch_name\n validates :vswitch_name, type: String\n\n # @return [String] The name of the port group for the VMKernel interface.\n attribute :portgroup_name\n validates :portgroup_name, presence: true, type: String\n\n # @return [Hash, nil] A dictionary of network details.,Following parameter is required:, - C(type) (string): Type of IP assignment (either C(dhcp) or C(static)).,Following parameters are required in case of C(type) is set to C(static), - C(ip_address) (string): Static IP address (implies C(type: static))., - C(subnet_mask) (string): Static netmask required for C(ip).\n attribute :network\n validates :network, type: Hash\n\n # @return [Object, nil] The IP Address for the VMKernel interface.,Use C(network) parameter with C(ip_address) instead.,Deprecated option, will be removed in version 2.9.\n attribute :ip_address\n\n # @return [Object, nil] The Subnet Mask for the VMKernel interface.,Use C(network) parameter with C(subnet_mask) instead.,Deprecated option, will be removed in version 2.9.\n attribute :subnet_mask\n\n # @return [String, nil] The VLAN ID for the VMKernel interface.,Required parameter only if C(state) is set to C(present).,Optional parameter from version 2.5 and onwards.\n attribute :vlan_id\n validates :vlan_id, type: String\n\n # @return [Integer, nil] The MTU for the VMKernel interface.,The default value of 1500 is valid from version 2.5 and onwards.\n attribute :mtu\n validates :mtu, type: Integer\n\n # @return [Symbol, nil] Enable the VMKernel interface for VSAN traffic.\n attribute :enable_vsan\n validates :enable_vsan, type: Symbol\n\n # @return [Symbol, nil] Enable the VMKernel interface for vMotion traffic.\n attribute :enable_vmotion\n validates :enable_vmotion, type: Symbol\n\n # @return [Symbol, nil] Enable the VMKernel interface for Management traffic.\n attribute :enable_mgmt\n validates :enable_mgmt, type: Symbol\n\n # @return [Symbol, nil] Enable the VMKernel interface for Fault Tolerance traffic.\n attribute :enable_ft\n validates :enable_ft, type: Symbol\n\n # @return [:present, :absent, nil] If set to C(present), VMKernel is created with the given specifications.,If set to C(absent), VMKernel is removed from the given configurations.,If set to C(present) and VMKernel exists then VMKernel configurations are updated.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object] Name of ESXi host to which VMKernel is to be managed.,From version 2.5 onwards, this parameter is required.\n attribute :esxi_hostname\n validates :esxi_hostname, presence: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6798088550567627, "alphanum_fraction": 0.6798088550567627, "avg_line_length": 32.47999954223633, "blob_id": "95da7c26a09a35d81a6d88feb14042f0c7a7c322", "content_id": "78f4f66f7b83047e9eb9324d07cab5603ac00fe9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 837, "license_type": "permissive", "max_line_length": 162, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_postgresqldatabase_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Get facts of PostgreSQL Database.\n class Azure_rm_postgresqldatabase_facts < Base\n # @return [String] The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] The name of the server.\n attribute :server_name\n validates :server_name, presence: true, type: String\n\n # @return [String, nil] The name of the database.\n attribute :name\n validates :name, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6992513537406921, "alphanum_fraction": 0.7035704255104065, "avg_line_length": 66.4368896484375, "blob_id": "7e90a002b09965ef83d70ff89b539bf931d4ce70", "content_id": "d3b095b63023f39ab806c8529a50b3a34b6e0009", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6946, "license_type": "permissive", "max_line_length": 607, "num_lines": 103, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_loadbalancer.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and delete Azure load balancers\n class Azure_rm_loadbalancer < Base\n # @return [String] Name of a resource group where the load balancer exists or will be created.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] Name of the load balancer.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, nil] Assert the state of the load balancer. Use C(present) to create/update a load balancer, or C(absent) to delete one.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [Object, nil] Valid azure location. Defaults to location of the resource group.\n attribute :location\n\n # @return [:Basic, :Standard, nil] The load balancer SKU.\n attribute :sku\n validates :sku, expression_inclusion: {:in=>[:Basic, :Standard], :message=>\"%{value} needs to be :Basic, :Standard\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash, nil] List of frontend IPs to be used\n attribute :frontend_ip_configurations\n validates :frontend_ip_configurations, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash, nil] List of backend address pools\n attribute :backend_address_pools\n validates :backend_address_pools, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash, nil] List of probe definitions used to check endpoint health.\n attribute :probes\n validates :probes, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash, nil] Defines an external port range for inbound NAT to a single backend port on NICs associated with a load balancer.,Inbound NAT rules are created automatically for each NIC associated with the Load Balancer using an external port from this range.,Defining an Inbound NAT pool on your Load Balancer is mutually exclusive with defining inbound Nat rules.,Inbound NAT pools are referenced from virtual machine scale sets.,NICs that are associated with individual virtual machines cannot reference an inbound NAT pool.,They have to reference individual inbound NAT rules.\n attribute :inbound_nat_pools\n validates :inbound_nat_pools, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash, nil] Object collection representing the load balancing rules Gets the provisioning.\n attribute :load_balancing_rules\n validates :load_balancing_rules, type: TypeGeneric.new(Hash)\n\n # @return [Object, nil] (deprecated) Name of an existing public IP address object to associate with the security group.,This option has been deprecated, and will be removed in 2.9. Use I(frontend_ip_configurations) instead.\n attribute :public_ip_address_name\n\n # @return [Object, nil] (deprecated) The port that the health probe will use.,This option has been deprecated, and will be removed in 2.9. Use I(probes) instead.\n attribute :probe_port\n\n # @return [:Tcp, :Http, nil] (deprecated) The protocol to use for the health probe.,This option has been deprecated, and will be removed in 2.9. Use I(probes) instead.\n attribute :probe_protocol\n validates :probe_protocol, expression_inclusion: {:in=>[:Tcp, :Http], :message=>\"%{value} needs to be :Tcp, :Http\"}, allow_nil: true\n\n # @return [Integer, nil] (deprecated) Time (in seconds) between endpoint health probes.,This option has been deprecated, and will be removed in 2.9. Use I(probes) instead.\n attribute :probe_interval\n validates :probe_interval, type: Integer\n\n # @return [Integer, nil] (deprecated) The amount of probe failures for the load balancer to make a health determination.,This option has been deprecated, and will be removed in 2.9. Use I(probes) instead.\n attribute :probe_fail_count\n validates :probe_fail_count, type: Integer\n\n # @return [Object, nil] (deprecated) The URL that an HTTP probe will use (only relevant if probe_protocol is set to Http).,This option has been deprecated, and will be removed in 2.9. Use I(probes) instead.\n attribute :probe_request_path\n\n # @return [:Tcp, :Udp, nil] (deprecated) The protocol (TCP or UDP) that the load balancer will use.,This option has been deprecated, and will be removed in 2.9. Use I(load_balancing_rules) instead.\n attribute :protocol\n validates :protocol, expression_inclusion: {:in=>[:Tcp, :Udp], :message=>\"%{value} needs to be :Tcp, :Udp\"}, allow_nil: true\n\n # @return [:Default, :SourceIP, :SourceIPProtocol, nil] (deprecated) The type of load distribution that the load balancer will employ.,This option has been deprecated, and will be removed in 2.9. Use I(load_balancing_rules) instead.\n attribute :load_distribution\n validates :load_distribution, expression_inclusion: {:in=>[:Default, :SourceIP, :SourceIPProtocol], :message=>\"%{value} needs to be :Default, :SourceIP, :SourceIPProtocol\"}, allow_nil: true\n\n # @return [Object, nil] (deprecated) Frontend port that will be exposed for the load balancer.,This option has been deprecated, and will be removed in 2.9. Use I(load_balancing_rules) instead.\n attribute :frontend_port\n\n # @return [Object, nil] (deprecated) Backend port that will be exposed for the load balancer.,This option has been deprecated, and will be removed in 2.9. Use I(load_balancing_rules) instead.\n attribute :backend_port\n\n # @return [Integer, nil] (deprecated) Timeout for TCP idle connection in minutes.,This option has been deprecated, and will be removed in 2.9. Use I(load_balancing_rules) instead.\n attribute :idle_timeout\n validates :idle_timeout, type: Integer\n\n # @return [Object, nil] (deprecated) Start of the port range for a NAT pool.,This option has been deprecated, and will be removed in 2.9. Use I(inbound_nat_pools) instead.\n attribute :natpool_frontend_port_start\n\n # @return [Object, nil] (deprecated) End of the port range for a NAT pool.,This option has been deprecated, and will be removed in 2.9. Use I(inbound_nat_pools) instead.\n attribute :natpool_frontend_port_end\n\n # @return [Object, nil] (deprecated) Backend port used by the NAT pool.,This option has been deprecated, and will be removed in 2.9. Use I(inbound_nat_pools) instead.\n attribute :natpool_backend_port\n\n # @return [Object, nil] (deprecated) The protocol for the NAT pool.,This option has been deprecated, and will be removed in 2.9. Use I(inbound_nat_pools) instead.\n attribute :natpool_protocol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6469907164573669, "alphanum_fraction": 0.6493055820465088, "avg_line_length": 38.272727966308594, "blob_id": "9f91729a94aa0dcdefb7274f4b7972dd9a3d3941", "content_id": "402bd72dc47245cc35a77abd433b1babe836fa6f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1728, "license_type": "permissive", "max_line_length": 163, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/database/misc/kibana_plugin.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages Kibana plugins.\n class Kibana_plugin < Base\n # @return [String] Name of the plugin to install\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Desired state of a plugin.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Set exact URL to download the plugin from. For local file, prefix its absolute path with file://\n attribute :url\n\n # @return [String, nil] Timeout setting: 30s, 1m, 1h...\n attribute :timeout\n validates :timeout, type: String\n\n # @return [String, nil] Location of the plugin binary\n attribute :plugin_bin\n validates :plugin_bin, type: String\n\n # @return [String, nil] Your configured plugin directory specified in Kibana\n attribute :plugin_dir\n validates :plugin_dir, type: String\n\n # @return [String, nil] Version of the plugin to be installed. If plugin exists with previous version, it will NOT be updated if C(force) is not set to yes\n attribute :version\n validates :version, type: String\n\n # @return [:yes, :no, nil] Delete and re-install the plugin. Can be useful for plugins update\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7069848775863647, "alphanum_fraction": 0.7137270569801331, "avg_line_length": 77.89361572265625, "blob_id": "c394b6553971fcd092543cdcfbe9f53edcbb8319", "content_id": "b05fa0993470844377556d658c73d9ecb659b87a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 7416, "license_type": "permissive", "max_line_length": 481, "num_lines": 94, "path": "/lib/ansible/ruby/modules/generated/network/netscaler/netscaler_gslb_service.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage gslb service entities in Netscaler.\n class Netscaler_gslb_service < Base\n # @return [String, nil] Name for the GSLB service. Must begin with an ASCII alphanumeric or underscore C(_) character, and must contain only ASCII alphanumeric, underscore C(_), hash C(#), period C(.), space, colon C(:), at C(@), equals C(=), and hyphen C(-) characters. Can be changed after the GSLB service is created.,,Minimum length = 1\n attribute :servicename\n validates :servicename, type: String\n\n # @return [String, nil] Canonical name of the GSLB service. Used in CNAME-based GSLB.,Minimum length = 1\n attribute :cnameentry\n validates :cnameentry, type: String\n\n # @return [Object, nil] Name of the server hosting the GSLB service.,Minimum length = 1\n attribute :servername\n\n # @return [:HTTP, :FTP, :TCP, :UDP, :SSL, :SSL_BRIDGE, :SSL_TCP, :NNTP, :ANY, :SIP_UDP, :SIP_TCP, :SIP_SSL, :RADIUS, :RDP, :RTSP, :MYSQL, :MSSQL, :ORACLE, nil] Type of service to create.\n attribute :servicetype\n validates :servicetype, expression_inclusion: {:in=>[:HTTP, :FTP, :TCP, :UDP, :SSL, :SSL_BRIDGE, :SSL_TCP, :NNTP, :ANY, :SIP_UDP, :SIP_TCP, :SIP_SSL, :RADIUS, :RDP, :RTSP, :MYSQL, :MSSQL, :ORACLE], :message=>\"%{value} needs to be :HTTP, :FTP, :TCP, :UDP, :SSL, :SSL_BRIDGE, :SSL_TCP, :NNTP, :ANY, :SIP_UDP, :SIP_TCP, :SIP_SSL, :RADIUS, :RDP, :RTSP, :MYSQL, :MSSQL, :ORACLE\"}, allow_nil: true\n\n # @return [Object, nil] Port on which the load balancing entity represented by this GSLB service listens.,Minimum value = 1,Range 1 - 65535,* in CLI is represented as 65535 in NITRO API\n attribute :port\n\n # @return [Object, nil] The public IP address that a NAT device translates to the GSLB service's private IP address. Optional.\n attribute :publicip\n\n # @return [Object, nil] The public port associated with the GSLB service's public IP address. The port is mapped to the service's private port number. Applicable to the local GSLB service. Optional.\n attribute :publicport\n\n # @return [Object, nil] The maximum number of open connections that the service can support at any given time. A GSLB service whose connection count reaches the maximum is not considered when a GSLB decision is made, until the connection count drops below the maximum.,Minimum value = C(0),Maximum value = C(4294967294)\n attribute :maxclient\n\n # @return [Symbol, nil] Monitor the health of the GSLB service.\n attribute :healthmonitor\n validates :healthmonitor, type: Symbol\n\n # @return [String, nil] Name of the GSLB site to which the service belongs.,Minimum length = 1\n attribute :sitename\n validates :sitename, type: String\n\n # @return [:enabled, :disabled, nil] In the request that is forwarded to the GSLB service, insert a header that stores the client's IP address. Client IP header insertion is used in connection-proxy based site persistence.\n attribute :cip\n validates :cip, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [Object, nil] Name for the HTTP header that stores the client's IP address. Used with the Client IP option. If client IP header insertion is enabled on the service and a name is not specified for the header, the NetScaler appliance uses the name specified by the cipHeader parameter in the set ns param command or, in the GUI, the Client IP Header parameter in the Configure HTTP Parameters dialog box.,Minimum length = 1\n attribute :cipheader\n\n # @return [:ConnectionProxy, :HTTPRedirect, :NONE, nil] Use cookie-based site persistence. Applicable only to C(HTTP) and C(SSL) GSLB services.\n attribute :sitepersistence\n validates :sitepersistence, expression_inclusion: {:in=>[:ConnectionProxy, :HTTPRedirect, :NONE], :message=>\"%{value} needs to be :ConnectionProxy, :HTTPRedirect, :NONE\"}, allow_nil: true\n\n # @return [Object, nil] The site's prefix string. When the service is bound to a GSLB virtual server, a GSLB site domain is generated internally for each bound service-domain pair by concatenating the site prefix of the service and the name of the domain. If the special string NONE is specified, the site-prefix string is unset. When implementing HTTP redirect site persistence, the NetScaler appliance redirects GSLB requests to GSLB services by using their site domains.\n attribute :siteprefix\n\n # @return [Object, nil] Idle time, in seconds, after which a client connection is terminated. Applicable if connection proxy based site persistence is used.,Minimum value = 0,Maximum value = 31536000\n attribute :clttimeout\n\n # @return [Object, nil] Integer specifying the maximum bandwidth allowed for the service. A GSLB service whose bandwidth reaches the maximum is not considered when a GSLB decision is made, until its bandwidth consumption drops below the maximum.\n attribute :maxbandwidth\n\n # @return [:enabled, :disabled, nil] Flush all active transactions associated with the GSLB service when its state transitions from UP to DOWN. Do not enable this option for services that must complete their transactions. Applicable if connection proxy based site persistence is used.\n attribute :downstateflush\n validates :downstateflush, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [Object, nil] Maximum number of SSL VPN users that can be logged on concurrently to the VPN virtual server that is represented by this GSLB service. A GSLB service whose user count reaches the maximum is not considered when a GSLB decision is made, until the count drops below the maximum.,Minimum value = C(0),Maximum value = C(65535)\n attribute :maxaaausers\n\n # @return [Object, nil] Monitoring threshold value for the GSLB service. If the sum of the weights of the monitors that are bound to this GSLB service and are in the UP state is not equal to or greater than this threshold value, the service is marked as DOWN.,Minimum value = C(0),Maximum value = C(65535)\n attribute :monthreshold\n\n # @return [Object, nil] Unique hash identifier for the GSLB service, used by hash based load balancing methods.,Minimum value = C(1)\n attribute :hashid\n\n # @return [Object, nil] Any comments that you might want to associate with the GSLB service.\n attribute :comment\n\n # @return [:enabled, :disabled, nil] Enable logging appflow flow information.\n attribute :appflowlog\n validates :appflowlog, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [Object, nil] IP address for the GSLB service. Should represent a load balancing, content switching, or VPN virtual server on the NetScaler appliance, or the IP address of another load balancing device.\n attribute :ipaddress\n\n # @return [Object, nil] Bind monitors to this gslb service\n attribute :monitor_bindings\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6638044714927673, "alphanum_fraction": 0.6638044714927673, "avg_line_length": 41.05555725097656, "blob_id": "a9d97c8118e136124c41397c094a398f39d7249a", "content_id": "968e4a9321c85bfd4927456679674628143db2a3", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1514, "license_type": "permissive", "max_line_length": 146, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_cli_alias.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows for managing both private and shared aliases on a BIG-IP.\n class Bigip_cli_alias < Base\n # @return [String] Specifies the name of the alias.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:private, :shared, nil] The scope of the alias; whether it is shared on the system, or usable only for the user who created it.\n attribute :scope\n validates :scope, expression_inclusion: {:in=>[:private, :shared], :message=>\"%{value} needs to be :private, :shared\"}, allow_nil: true\n\n # @return [String, nil] The command to alias.\n attribute :command\n validates :command, type: String\n\n # @return [Object, nil] Description of the alias.\n attribute :description\n\n # @return [String, nil] Device partition to manage resources on.,This parameter is disregarded when the C(scope) is C(private).\n attribute :partition\n validates :partition, type: String\n\n # @return [:present, :absent, nil] When C(present), ensures that the resource exists.,When C(absent), ensures the resource is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6909799575805664, "alphanum_fraction": 0.6909799575805664, "avg_line_length": 46.26315689086914, "blob_id": "8ed045d63bd806482a2e09ca66dfbc09d61ca956", "content_id": "2e727c97b398315dd9e6feff7cf29d79e320f252", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1796, "license_type": "permissive", "max_line_length": 225, "num_lines": 38, "path": "/lib/ansible/ruby/modules/generated/windows/win_shell.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The C(win_shell) module takes the command name followed by a list of space-delimited arguments. It is similar to the M(win_command) module, but runs the command via a shell (defaults to PowerShell) on the target host.\n # For non-Windows targets, use the M(shell) module instead.\n class Win_shell < Base\n # @return [Object] The C(win_shell) module takes a free form command to run.,There is no parameter actually named 'free form'. See the examples!\n attribute :free_form\n validates :free_form, presence: true\n\n # @return [String, nil] A path or path filter pattern; when the referenced path exists on the target host, the task will be skipped.\n attribute :creates\n validates :creates, type: String\n\n # @return [String, nil] A path or path filter pattern; when the referenced path B(does not) exist on the target host, the task will be skipped.\n attribute :removes\n validates :removes, type: String\n\n # @return [String, nil] Set the specified path as the current working directory before executing a command\n attribute :chdir\n validates :chdir, type: String\n\n # @return [String, nil] Change the shell used to execute the command (eg, C(cmd)).,The target shell must accept a C(/c) parameter followed by the raw command line to be executed.\n attribute :executable\n validates :executable, type: String\n\n # @return [String, nil] Set the stdin of the command directly to the specified value.\n attribute :stdin\n validates :stdin, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7208480834960938, "alphanum_fraction": 0.7214905023574829, "avg_line_length": 73.11904907226562, "blob_id": "9f5e0d5b701bcde3ce2c48f94ce8978d39e87088", "content_id": "961888f3e34b22dbdc73c8b2634790ad965945ab", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3113, "license_type": "permissive", "max_line_length": 510, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/windows/win_acl.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove rights/permissions for a given user or group for the specified file, folder, registry key or AppPool identifies.\n # If adding ACL's for AppPool identities (available since 2.3), the Windows Feature \"Web-Scripting-Tools\" must be enabled.\n class Win_acl < Base\n # @return [String] The path to the file or directory.\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [String] User or Group to add specified rights to act on src file/folder or registry key.\n attribute :user\n validates :user, presence: true, type: String\n\n # @return [:absent, :present, nil] Specify whether to add C(present) or remove C(absent) the specified access rule.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:allow, :deny] Specify whether to allow or deny the rights specified.\n attribute :type\n validates :type, presence: true, expression_inclusion: {:in=>[:allow, :deny], :message=>\"%{value} needs to be :allow, :deny\"}\n\n # @return [Array<String>, String] The rights/permissions that are to be allowed/denied for the specified user or group for the item at C(path).,If C(path) is a file or directory, rights can be any right under MSDN FileSystemRights U(https://msdn.microsoft.com/en-us/library/system.security.accesscontrol.filesystemrights.aspx).,If C(path) is a registry key, rights can be any right under MSDN RegistryRights U(https://msdn.microsoft.com/en-us/library/system.security.accesscontrol.registryrights.aspx).\n attribute :rights\n validates :rights, presence: true, type: TypeGeneric.new(String)\n\n # @return [:ContainerInherit, :ObjectInherit, nil] Inherit flags on the ACL rules.,Can be specified as a comma separated list, e.g. C(ContainerInherit), C(ObjectInherit).,For more information on the choices see MSDN InheritanceFlags enumeration at U(https://msdn.microsoft.com/en-us/library/system.security.accesscontrol.inheritanceflags.aspx).,Defaults to C(ContainerInherit, ObjectInherit) for Directories.\n attribute :inherit\n validates :inherit, expression_inclusion: {:in=>[:ContainerInherit, :ObjectInherit], :message=>\"%{value} needs to be :ContainerInherit, :ObjectInherit\"}, allow_nil: true\n\n # @return [:InheritOnly, :None, :NoPropagateInherit, nil] Propagation flag on the ACL rules.,For more information on the choices see MSDN PropagationFlags enumeration at U(https://msdn.microsoft.com/en-us/library/system.security.accesscontrol.propagationflags.aspx).\n attribute :propagation\n validates :propagation, expression_inclusion: {:in=>[:InheritOnly, :None, :NoPropagateInherit], :message=>\"%{value} needs to be :InheritOnly, :None, :NoPropagateInherit\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6921675801277161, "alphanum_fraction": 0.6921675801277161, "avg_line_length": 42.91999816894531, "blob_id": "3cf5a68a831b9e721bffe4a6dbb87cc1e80b77ad", "content_id": "5e3c67dce5a7b506f869ce4e69a8e5bb8c278542", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1098, "license_type": "permissive", "max_line_length": 159, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_interface_selector_to_switch_policy_leaf_profile.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Bind interface selector profiles to switch policy leaf profiles on Cisco ACI fabrics.\n class Aci_interface_selector_to_switch_policy_leaf_profile < Base\n # @return [String, nil] Name of the Leaf Profile to which we add a Selector.\n attribute :leaf_profile\n validates :leaf_profile, type: String\n\n # @return [String, nil] Name of Interface Profile Selector to be added and associated with the Leaf Profile.\n attribute :interface_selector\n validates :interface_selector, type: String\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.705920934677124, "alphanum_fraction": 0.7069050073623657, "avg_line_length": 59.366336822509766, "blob_id": "1f1e701756dccd1ad9d1b678e3e87037daebbe50", "content_id": "f6ea181ca17ba9229973dc50c86fa005c6bd3ecb", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6097, "license_type": "permissive", "max_line_length": 305, "num_lines": 101, "path": "/lib/ansible/ruby/modules/generated/database/proxysql/proxysql_query_rules.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The M(proxysql_query_rules) module modifies query rules using the proxysql admin interface.\n class Proxysql_query_rules < Base\n # @return [Object, nil] The unique id of the rule. Rules are processed in rule_id order.\n attribute :rule_id\n\n # @return [Integer, nil] A rule with I(active) set to C(False) will be tracked in the database, but will be never loaded in the in-memory data structures.\n attribute :active\n validates :active, type: Integer\n\n # @return [String, nil] Filtering criteria matching username. If I(username) is non-NULL, a query will match only if the connection is made with the correct username.\n attribute :username\n validates :username, type: String\n\n # @return [Object, nil] Filtering criteria matching schemaname. If I(schemaname) is non-NULL, a query will match only if the connection uses schemaname as its default schema.\n attribute :schemaname\n\n # @return [Object, nil] Used in combination with I(flagOUT) and I(apply) to create chains of rules.\n attribute :flagIN\n\n # @return [Object, nil] Match traffic from a specific source.\n attribute :client_addr\n\n # @return [Object, nil] Match incoming traffic on a specific local IP.\n attribute :proxy_addr\n\n # @return [Object, nil] Match incoming traffic on a specific local port.\n attribute :proxy_port\n\n # @return [Object, nil] Match queries with a specific digest, as returned by stats_mysql_query_digest.digest.\n attribute :digest\n\n # @return [Object, nil] Regular expression that matches the query digest. The dialect of regular expressions used is that of re2 - https://github.com/google/re2\n attribute :match_digest\n\n # @return [String, nil] Regular expression that matches the query text. The dialect of regular expressions used is that of re2 - https://github.com/google/re2\n attribute :match_pattern\n validates :match_pattern, type: String\n\n # @return [Object, nil] If I(negate_match_pattern) is set to C(True), only queries not matching the query text will be considered as a match. This acts as a NOT operator in front of the regular expression matching against match_pattern.\n attribute :negate_match_pattern\n\n # @return [Object, nil] Used in combination with I(flagIN) and apply to create chains of rules. When set, I(flagOUT) signifies the I(flagIN) to be used in the next chain of rules.\n attribute :flagOUT\n\n # @return [Object, nil] This is the pattern with which to replace the matched pattern. Note that this is optional, and when omitted, the query processor will only cache, route, or set other parameters without rewriting.\n attribute :replace_pattern\n\n # @return [Integer, nil] Route matched queries to this hostgroup. This happens unless there is a started transaction and the logged in user has I(transaction_persistent) set to C(True) (see M(proxysql_mysql_users)).\n attribute :destination_hostgroup\n validates :destination_hostgroup, type: Integer\n\n # @return [Object, nil] The number of milliseconds for which to cache the result of the query. Note in ProxySQL 1.1 I(cache_ttl) was in seconds.\n attribute :cache_ttl\n\n # @return [Object, nil] The maximum timeout in milliseconds with which the matched or rewritten query should be executed. If a query run for longer than the specific threshold, the query is automatically killed. If timeout is not specified, the global variable mysql-default_query_timeout applies.\n attribute :timeout\n\n # @return [Integer, nil] The maximum number of times a query needs to be re-executed in case of detected failure during the execution of the query. If retries is not specified, the global variable mysql-query_retries_on_failure applies.\n attribute :retries\n validates :retries, type: Integer\n\n # @return [Object, nil] Number of milliseconds to delay the execution of the query. This is essentially a throttling mechanism and QoS, and allows a way to give priority to queries over others. This value is added to the mysql-default_query_delay global variable that applies to all queries.\n attribute :delay\n\n # @return [Object, nil] Enables query mirroring. If set I(mirror_flagOUT) can be used to evaluates the mirrored query against the specified chain of rules.\n attribute :mirror_flagOUT\n\n # @return [Object, nil] Enables query mirroring. If set I(mirror_hostgroup) can be used to mirror queries to the same or different hostgroup.\n attribute :mirror_hostgroup\n\n # @return [Object, nil] Query will be blocked, and the specified error_msg will be returned to the client.\n attribute :error_msg\n\n # @return [Object, nil] Query will be logged.\n attribute :log\n\n # @return [Object, nil] Used in combination with I(flagIN) and I(flagOUT) to create chains of rules. Setting apply to True signifies the last rule to be applied.\n attribute :apply\n\n # @return [Object, nil] Free form text field, usable for a descriptive comment of the query rule.\n attribute :comment\n\n # @return [:present, :absent, nil] When C(present) - adds the rule, when C(absent) - removes the rule.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Boolean, nil] By default we avoid deleting more than one schedule in a single batch, however if you need this behaviour and you're not concerned about the schedules deleted, you can set I(force_delete) to C(True).\n attribute :force_delete\n validates :force_delete, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6885698437690735, "alphanum_fraction": 0.692987322807312, "avg_line_length": 52.264705657958984, "blob_id": "a45082826ae1a88eb8637d5114591624ceeec3a9", "content_id": "9dded5d3f43297d832f66b214ccc35da4da4b7ec", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1811, "license_type": "permissive", "max_line_length": 203, "num_lines": 34, "path": "/lib/ansible/ruby/modules/generated/windows/win_defrag.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Locates and consolidates fragmented files on local volumes to improve system performance.\n # More information regarding C(win_defrag) is available from: U(https://technet.microsoft.com/en-us/library/cc731650(v=ws.11).aspx)\n class Win_defrag < Base\n # @return [Array<String>, String, nil] A list of drive letters or mount point paths of the volumes to be defragmented.,If this parameter is omitted, all volumes (not excluded) will be fragmented.\n attribute :include_volumes\n validates :include_volumes, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] A list of drive letters or mount point paths to exclude from defragmentation.\n attribute :exclude_volumes\n validates :exclude_volumes, type: TypeGeneric.new(String)\n\n # @return [Boolean, nil] Perform free space consolidation on the specified volumes.\n attribute :freespace_consolidation\n validates :freespace_consolidation, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:low, :normal, nil] Run the operation at low or normal priority.\n attribute :priority\n validates :priority, expression_inclusion: {:in=>[:low, :normal], :message=>\"%{value} needs to be :low, :normal\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Run the operation on each volume in parallel in the background.\n attribute :parallel\n validates :parallel, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6632801294326782, "alphanum_fraction": 0.6632801294326782, "avg_line_length": 31.809524536132812, "blob_id": "d3ba788fd2e451bf8f74bc439012ef83cf3361d0", "content_id": "44dd4b7641b9523912c1c0e0a54a33c2f70db7eb", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 689, "license_type": "permissive", "max_line_length": 147, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_feature.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Offers ability to enable and disable features in NX-OS.\n class Nxos_feature < Base\n # @return [String] Name of feature.\n attribute :feature\n validates :feature, presence: true, type: String\n\n # @return [:enabled, :disabled, nil] Desired state of the feature.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6604892611503601, "alphanum_fraction": 0.6604892611503601, "avg_line_length": 39.878787994384766, "blob_id": "cb821f39d2f60c82bb150cbec820a7d04b66e871", "content_id": "f83ed5595fbb7dd7c6281cdeee886c126cfcdc2c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1349, "license_type": "permissive", "max_line_length": 143, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/network/illumos/dladm_vlan.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or delete VLAN interfaces on Solaris/illumos systems.\n class Dladm_vlan < Base\n # @return [String] VLAN interface name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] VLAN underlying link name.\n attribute :link\n validates :link, presence: true, type: String\n\n # @return [Boolean, nil] Specifies that the VLAN interface is temporary. Temporary VLANs do not persist across reboots.\n attribute :temporary\n validates :temporary, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] VLAN ID value for VLAN interface.\n attribute :vlan_id\n validates :vlan_id, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Create or delete Solaris/illumos VNIC.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6935483813285828, "alphanum_fraction": 0.698924720287323, "avg_line_length": 52.842105865478516, "blob_id": "e6bf27cb0053f6f6df1e9e14bec697eb83393d6a", "content_id": "d818f6d4cb83b4cdb1d0c841adc33be7002c0519", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4092, "license_type": "permissive", "max_line_length": 287, "num_lines": 76, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/lambda.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows for the management of Lambda functions.\n class Lambda < Base\n # @return [String] The name you want to assign to the function you are uploading. Cannot be changed.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Create or delete Lambda function\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] The runtime environment for the Lambda function you are uploading. Required when creating a function. Use parameters as described in boto3 docs. Current example runtime environments are nodejs, nodejs4.3, java8 or python2.7,Required when C(state=present)\n attribute :runtime\n validates :runtime, type: String\n\n # @return [String, nil] The Amazon Resource Name (ARN) of the IAM role that Lambda assumes when it executes your function to access any other Amazon Web Services (AWS) resources. You may use the bare ARN if the role belongs to the same AWS account.,Required when C(state=present)\n attribute :role\n validates :role, type: String\n\n # @return [String, nil] The function within your code that Lambda calls to begin execution\n attribute :handler\n validates :handler, type: String\n\n # @return [String, nil] A .zip file containing your deployment package,If C(state=present) then either zip_file or s3_bucket must be present.\n attribute :zip_file\n validates :zip_file, type: String\n\n # @return [Object, nil] Amazon S3 bucket name where the .zip file containing your deployment package is stored,If C(state=present) then either zip_file or s3_bucket must be present.,s3_bucket and s3_key are required together\n attribute :s3_bucket\n\n # @return [Object, nil] The Amazon S3 object (the deployment package) key name you want to upload,s3_bucket and s3_key are required together\n attribute :s3_key\n\n # @return [Object, nil] The Amazon S3 object (the deployment package) version you want to upload.\n attribute :s3_object_version\n\n # @return [Object, nil] A short, user-defined function description. Lambda does not use this value. Assign a meaningful description as you see fit.\n attribute :description\n\n # @return [Integer, nil] The function maximum execution time in seconds after which Lambda should terminate the function.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [Integer, nil] The amount of memory, in MB, your Lambda function is given\n attribute :memory_size\n validates :memory_size, type: Integer\n\n # @return [Array<String>, String, nil] List of subnet IDs to run Lambda function in. Use this option if you need to access resources in your VPC. Leave empty if you don't want to run the function in a VPC.\n attribute :vpc_subnet_ids\n validates :vpc_subnet_ids, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] List of VPC security group IDs to associate with the Lambda function. Required when vpc_subnet_ids is used.\n attribute :vpc_security_group_ids\n validates :vpc_security_group_ids, type: TypeGeneric.new(String)\n\n # @return [String, nil] A dictionary of environment variables the Lambda function is given.\n attribute :environment_variables\n validates :environment_variables, type: String\n\n # @return [Object, nil] The parent object that contains the target Amazon Resource Name (ARN) of an Amazon SQS queue or Amazon SNS topic.\n attribute :dead_letter_arn\n\n # @return [Hash, nil] tag dict to apply to the function (requires botocore 1.5.40 or above)\n attribute :tags\n validates :tags, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7142447829246521, "alphanum_fraction": 0.714818000793457, "avg_line_length": 66.09615325927734, "blob_id": "e519f7abde925a307d0b1a91a3bcaa2c66df9dd0", "content_id": "d430dd0bba60a7fc802ba1849e8fd723ccb34a80", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3489, "license_type": "permissive", "max_line_length": 429, "num_lines": 52, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_file_copy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module supports two different workflows for copying a file to flash (or bootflash) on NXOS devices. Files can either be (1) pushed from the Ansible controller to the device or (2) pulled from a remote SCP file server to the device. File copies are initiated from the NXOS device to the remote SCP server. This module only supports the use of connection C(network_cli) or C(Cli) transport with connection C(local).\n class Nxos_file_copy < Base\n # @return [String, nil] When (file_pull is False) this is the path to the local file on the Ansible controller. The local directory must exist.,When (file_pull is True) this is the file name used on the NXOS device.\n attribute :local_file\n validates :local_file, type: String\n\n # @return [String, nil] When (file_pull is False) this is the remote file path on the NXOS device. If omitted, the name of the local file will be used. The remote directory must exist.,When (file_pull is True) this is the full path to the file on the remote SCP server to be copied to the NXOS device.\n attribute :remote_file\n validates :remote_file, type: String\n\n # @return [String, nil] The remote file system of the device. If omitted, devices that support a I(file_system) parameter will use their default values.\n attribute :file_system\n validates :file_system, type: String\n\n # @return [Integer, nil] SSH port to connect to server during transfer of file\n attribute :connect_ssh_port\n validates :connect_ssh_port, type: Integer\n\n # @return [Symbol, nil] When (False) file is copied from the Ansible controller to the NXOS device.,When (True) file is copied from a remote SCP server to the NXOS device. In this mode, the file copy is initiated from the NXOS device.,If the file is already present on the device it will be overwritten and therefore the operation is NOT idempotent.\n attribute :file_pull\n validates :file_pull, type: Symbol\n\n # @return [Object, nil] When (file_pull is True) file is copied from a remote SCP server to the NXOS device, and written to this directory on the NXOS device. If the directory does not exist, it will be created under the file_system. This is an optional parameter.,When (file_pull is False), this not used.\n attribute :local_file_directory\n\n # @return [Integer, nil] Use this parameter to set timeout in seconds, when transferring large files or when the network is slow.\n attribute :file_pull_timeout\n validates :file_pull_timeout, type: Integer\n\n # @return [String, nil] The remote scp server address which is used to pull the file. This is required if file_pull is True.\n attribute :remote_scp_server\n validates :remote_scp_server, type: String\n\n # @return [String, nil] The remote scp server username which is used to pull the file. This is required if file_pull is True.\n attribute :remote_scp_server_user\n validates :remote_scp_server_user, type: String\n\n # @return [String, nil] The remote scp server password which is used to pull the file. This is required if file_pull is True.\n attribute :remote_scp_server_password\n validates :remote_scp_server_password, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7096455097198486, "alphanum_fraction": 0.7116226553916931, "avg_line_length": 88.6329116821289, "blob_id": "2ab940b892a4a5c1591593a036ae5dcae934e56b", "content_id": "ea43e3637c6d63687e35300475c47a82f9386d07", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 7089, "license_type": "permissive", "max_line_length": 682, "num_lines": 79, "path": "/lib/ansible/ruby/modules/generated/remote_management/ucs/ucs_vnic_template.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configures vNIC templates on Cisco UCS Manager.\n # Examples can be used with the UCS Platform Emulator U(https://communities.cisco.com/ucspe).\n class Ucs_vnic_template < Base\n # @return [:present, :absent, nil] If C(present), will verify vNIC templates are present and will create if needed.,If C(absent), will verify vNIC templates are absent and will delete if needed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The name of the vNIC template.,This name can be between 1 and 16 alphanumeric characters.,You cannot use spaces or any special characters other than - (hyphen), \"_\" (underscore), : (colon), and . (period).,You cannot change this name after the template is created.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] A user-defined description of the vNIC template.,Enter up to 256 characters.,You can use any characters or spaces except the following:,` (accent mark), (backslash), ^ (carat), \" (double quote), = (equal sign), > (greater than), < (less than), or ' (single quote).\n attribute :description\n\n # @return [:A, :B, :\"A-B\", :\"B-A\", nil] The Fabric ID field specifying the fabric interconnect associated with vNICs created from this template.,If you want fabric failover enabled on vNICs created from this template, use of of the following:\",A-B to use Fabric A by default with failover enabled.,B-A to use Fabric B by default with failover enabled.,Do not enable vNIC fabric failover under the following circumstances:,- If the Cisco UCS domain is running in Ethernet switch mode. vNIC fabric failover is not supported in that mode.,- If you plan to associate one or more vNICs created from this template to a server with an adapter that does not support fabric failover.\n attribute :fabric\n validates :fabric, expression_inclusion: {:in=>[:A, :B, :\"A-B\", :\"B-A\"], :message=>\"%{value} needs to be :A, :B, :\\\"A-B\\\", :\\\"B-A\\\"\"}, allow_nil: true\n\n # @return [:none, :primary, :secondary, nil] The Redundancy Type used for vNIC redundancy pairs during fabric failover.,This can be one of the following:,primary — Creates configurations that can be shared with the Secondary template.,secondary — All shared configurations are inherited from the Primary template.,none - Legacy vNIC template behavior. Select this option if you do not want to use redundancy.\n attribute :redundancy_type\n validates :redundancy_type, expression_inclusion: {:in=>[:none, :primary, :secondary], :message=>\"%{value} needs to be :none, :primary, :secondary\"}, allow_nil: true\n\n # @return [Object, nil] The Peer Redundancy Template.,The name of the vNIC template sharing a configuration with this template.,If the redundancy_type is primary, the name of the secondary template should be provided.,If the redundancy_type is secondary, the name of the primary template should be provided.,Secondary templates can only configure non-shared properties (name, description, and mac_pool).\n attribute :peer_redundancy_template\n\n # @return [String, nil] The possible target for vNICs created from this template.,The target determines whether or not Cisco UCS Manager automatically creates a VM-FEX port profile with the appropriate settings for the vNIC template.,This can be one of the following:,adapter — The vNICs apply to all adapters. No VM-FEX port profile is created if you choose this option.,vm - The vNICs apply to all virtual machines. A VM-FEX port profile is created if you choose this option.\n attribute :target\n validates :target, type: String\n\n # @return [:\"initial-template\", :\"updating-template\", nil] The Template Type field.,This can be one of the following:,initial-template — vNICs created from this template are not updated if the template changes.,updating-template - vNICs created from this template are updated if the template changes.\n attribute :template_type\n validates :template_type, expression_inclusion: {:in=>[:\"initial-template\", :\"updating-template\"], :message=>\"%{value} needs to be :\\\"initial-template\\\", :\\\"updating-template\\\"\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash, nil] List of VLANs used by the vNIC template.,Each list element has the following suboptions:,= name, The name of the VLAN (required).,- native, Designates the VLAN as a native VLAN. Only one VLAN in the list can be a native VLAN., [choices: 'no', 'yes'], [Default: 'no'],- state, If present, will verify VLAN is present on template., If absent, will verify VLAN is absent on template., choices: [present, absent], default: present\n attribute :vlans_list\n validates :vlans_list, type: TypeGeneric.new(Hash)\n\n # @return [:\"vnic-name\", :\"user-defined\", nil] CDN Source field.,This can be one of the following options:,vnic-name - Uses the vNIC template name of the vNIC instance as the CDN name. This is the default option.,user-defined - Uses a user-defined CDN name for the vNIC template. If this option is chosen, cdn_name must also be provided.\n attribute :cdn_source\n validates :cdn_source, expression_inclusion: {:in=>[:\"vnic-name\", :\"user-defined\"], :message=>\"%{value} needs to be :\\\"vnic-name\\\", :\\\"user-defined\\\"\"}, allow_nil: true\n\n # @return [Object, nil] CDN Name used when cdn_source is set to user-defined.\n attribute :cdn_name\n\n # @return [String, nil] The MTU field.,The maximum transmission unit, or packet size, that vNICs created from this vNIC template should use.,Enter a string between '1500' and '9000'.,If the vNIC template has an associated QoS policy, the MTU specified here must be equal to or less than the MTU specified in the QoS system class.\n attribute :mtu\n validates :mtu, type: String\n\n # @return [Object, nil] The MAC address pool that vNICs created from this vNIC template should use.\n attribute :mac_pool\n\n # @return [Object, nil] The quality of service (QoS) policy that vNICs created from this vNIC template should use.\n attribute :qos_policy\n\n # @return [Object, nil] The network control policy that vNICs created from this vNIC template should use.\n attribute :network_control_policy\n\n # @return [Object, nil] The LAN pin group that vNICs created from this vNIC template should use.\n attribute :pin_group\n\n # @return [String, nil] The statistics collection policy that vNICs created from this vNIC template should use.\n attribute :stats_policy\n validates :stats_policy, type: String\n\n # @return [String, nil] Org dn (distinguished name)\n attribute :org_dn\n validates :org_dn, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.695852518081665, "alphanum_fraction": 0.695852518081665, "avg_line_length": 53.25, "blob_id": "f6ad93318cd3c22de18ff6d5a0dade70fffadbd3", "content_id": "3f046283a350d73eadd629e3c0963de7ce69ab17", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1736, "license_type": "permissive", "max_line_length": 266, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/utilities/logic/pause.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Pauses playbook execution for a set amount of time, or until a prompt is acknowledged. All parameters are optional. The default behavior is to pause with a prompt.\n # To pause/wait/sleep per host, use the M(wait_for) module.\n # You can use C(ctrl+c) if you wish to advance a pause earlier than it is set to expire or if you need to abort a playbook run entirely. To continue early press C(ctrl+c) and then C(c). To abort a playbook press C(ctrl+c) and then C(a).\n # The pause module integrates into async/parallelized playbooks without any special considerations (see Rolling Updates). When using pauses with the C(serial) playbook parameter (as in rolling updates) you are only prompted once for the current group of hosts.\n # This module is also supported for Windows targets.\n class Pause < Base\n # @return [Integer, nil] A positive number of minutes to pause for.\n attribute :minutes\n validates :minutes, type: Integer\n\n # @return [Object, nil] A positive number of seconds to pause for.\n attribute :seconds\n\n # @return [String, nil] Optional text to use for the prompt message.\n attribute :prompt\n validates :prompt, type: String\n\n # @return [:yes, :no, nil] Controls whether or not keyboard input is shown when typing.,Has no effect if 'seconds' or 'minutes' is set.\n attribute :echo\n validates :echo, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6769265532493591, "alphanum_fraction": 0.6784992218017578, "avg_line_length": 64.45587921142578, "blob_id": "96f57d44ec2b8453b3921e5ee36aaae49f3f6d09", "content_id": "4dd43d8b7e60a8bdb08dbbfc7217a35ed10b335a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4451, "license_type": "permissive", "max_line_length": 368, "num_lines": 68, "path": "/lib/ansible/ruby/modules/generated/files/find.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Return a list of files based on specific criteria. Multiple criteria are AND'd together.\n # For Windows targets, use the M(win_find) module instead.\n class Find < Base\n # @return [String, Integer, nil] Select files whose age is equal to or greater than the specified time. Use a negative age to find files equal to or less than the specified time. You can choose seconds, minutes, hours, days, or weeks by specifying the first letter of any of those words (e.g., \"1w\").\n attribute :age\n validates :age, type: MultipleTypes.new(String, Integer)\n\n # @return [String, nil] One or more (shell or regex) patterns, which type is controlled by C(use_regex) option.,The patterns restrict the list of files to be returned to those whose basenames match at least one of the patterns specified. Multiple patterns can be specified using a list.\n attribute :patterns\n validates :patterns, type: String\n\n # @return [Array<String>, String, nil] One or more (shell or regex) patterns, which type is controlled by C(use_regex) option.,Items matching an C(excludes) pattern are culled from C(patterns) matches. Multiple patterns can be specified using a list.\n attribute :excludes\n validates :excludes, type: TypeGeneric.new(String)\n\n # @return [Object, nil] One or more regex patterns which should be matched against the file content.\n attribute :contains\n\n # @return [String] List of paths of directories to search. All paths must be fully qualified.\n attribute :paths\n validates :paths, presence: true, type: String\n\n # @return [:any, :directory, :file, :link, nil] Type of file to select.,The 'link' and 'any' choices were added in version 2.3.\n attribute :file_type\n validates :file_type, expression_inclusion: {:in=>[:any, :directory, :file, :link], :message=>\"%{value} needs to be :any, :directory, :file, :link\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If target is a directory, recursively descend into the directory looking for files.\n attribute :recurse\n validates :recurse, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Select files whose size is equal to or greater than the specified size. Use a negative size to find files equal to or less than the specified size. Unqualified values are in bytes but b, k, m, g, and t can be appended to specify bytes, kilobytes, megabytes, gigabytes, and terabytes, respectively. Size is not evaluated for directories.\n attribute :size\n validates :size, type: String\n\n # @return [:atime, :ctime, :mtime, nil] Choose the file property against which we compare age.\n attribute :age_stamp\n validates :age_stamp, expression_inclusion: {:in=>[:atime, :ctime, :mtime], :message=>\"%{value} needs to be :atime, :ctime, :mtime\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Set this to true to include hidden files, otherwise they'll be ignored.\n attribute :hidden\n validates :hidden, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Set this to true to follow symlinks in path for systems with python 2.6+.\n attribute :follow\n validates :follow, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Set this to true to retrieve a file's sha1 checksum.\n attribute :get_checksum\n validates :get_checksum, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If false, the patterns are file globs (shell). If true, they are python regexes.\n attribute :use_regex\n validates :use_regex, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Set the maximum number of levels to decend into. Setting recurse to false will override this value, which is effectively depth 1. Default is unlimited depth.\n attribute :depth\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5990666151046753, "alphanum_fraction": 0.5990666151046753, "avg_line_length": 33.661766052246094, "blob_id": "716a6284e739680e0c9698648dbc4cf2ef17fd15", "content_id": "06c7c1837c4b5d002b9d3ba8d6c108ceb9b99829", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2357, "license_type": "permissive", "max_line_length": 115, "num_lines": 68, "path": "/lib/ansible/ruby/models/play.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'ansible/ruby/models/base'\nrequire 'ansible/ruby/models/tasks'\n\nmodule Ansible\n module Ruby\n module Models\n class Play < Base\n attribute :hosts\n validates :hosts, presence: true, type: TypeGeneric.new(String)\n attribute :vars\n validates :vars, type: Hash\n attribute :become\n validates :become, type: MultipleTypes.new(TrueClass, FalseClass)\n attribute :become_user\n validates :become_user, type: String\n attribute :ignore_errors\n validates :ignore_errors, type: MultipleTypes.new(TrueClass, FalseClass)\n attribute :no_log\n validates :no_log, type: MultipleTypes.new(TrueClass, FalseClass)\n attribute :name\n validates :name, type: String\n attribute :tasks\n validates :tasks, type: Tasks\n attribute :roles\n attribute :tags\n attribute :connection\n validates :connection,\n allow_nil: true,\n inclusion: { in: %i[local docker ssh], message: '%{value} needs to be :local, :docker, or :ssh' }\n attribute :user\n validates :user, type: String\n attribute :serial\n validates :serial, type: Integer\n attribute :gather_facts\n validates :gather_facts, type: MultipleTypes.new(TrueClass, FalseClass)\n validate :validate_roles_tasks\n\n def to_h\n result = super\n hosts = result.delete :hosts\n tasks = result.delete :items\n roles = result.delete :roles\n name = result.delete :name\n # Be consistent with Ansible order\n new_result = {\n hosts: [*hosts].join(':') # Ansible doesn't specify this as an array\n }\n new_result[:name] = name if name\n new_result[:tasks] = tasks.is_a?(Array) ? tasks : [tasks] if tasks # ensure we have an array\n new_result[:roles] = [*roles] if roles # ensure we have an array\n result.each do |key, value|\n new_result[key] = value\n end\n new_result\n end\n\n private\n\n def validate_roles_tasks\n errors.add :tasks, 'Cannot supply both tasks and roles!' if roles && tasks\n errors.add :tasks, 'Must supply either task(s) or role(s)!' unless roles || tasks\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6711327433586121, "alphanum_fraction": 0.6723507642745972, "avg_line_length": 41.10256576538086, "blob_id": "2ee8353c02eb6c3558eeac3d72f1a60266aa49f7", "content_id": "578a36b66ad0ece83ae98f17f3fadd8654a49468", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1642, "license_type": "permissive", "max_line_length": 265, "num_lines": 39, "path": "/lib/ansible/ruby/modules/generated/network/meraki/meraki_mx_l3_firewall.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows for creation, management, and visibility into layer 3 firewalls implemented on Meraki MX firewalls.\n class Meraki_mx_l3_firewall < Base\n # @return [:present, :query, nil] Create or modify an organization.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :query], :message=>\"%{value} needs to be :present, :query\"}, allow_nil: true\n\n # @return [String, nil] Name of organization.,If C(clone) is specified, C(org_name) is the name of the new organization.\n attribute :org_name\n validates :org_name, type: String\n\n # @return [Object, nil] ID of organization.\n attribute :org_id\n\n # @return [String, nil] Name of network which MX firewall is in.\n attribute :net_name\n validates :net_name, type: String\n\n # @return [Object, nil] ID of network which MX firewall is in.\n attribute :net_id\n\n # @return [Array<Hash>, Hash, nil] List of firewall rules.\n attribute :rules\n validates :rules, type: TypeGeneric.new(Hash)\n\n # @return [Symbol, nil] Whether to log hits against the default firewall rule.,Only applicable if a syslog server is specified against the network.,This is not shown in response from Meraki. Instead, refer to the C(syslog_enabled) value in the default rule.\n attribute :syslog_default_rule\n validates :syslog_default_rule, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6787233948707581, "alphanum_fraction": 0.6787233948707581, "avg_line_length": 46, "blob_id": "7c378f9039557bf09f1f69e34dbe65bfb7a83ac2", "content_id": "657c4f0974f2b86efd6eda30ed4ed30471090733", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1880, "license_type": "permissive", "max_line_length": 261, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_config_rule.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Module manages AWS Config rules\n class Aws_config_rule < Base\n # @return [String] The name of the AWS Config resource.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Whether the Config rule should be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] The description that you provide for the AWS Config rule.\n attribute :description\n validates :description, type: String\n\n # @return [Hash, nil] Defines which resources can trigger an evaluation for the rule.\n attribute :scope\n validates :scope, type: Hash\n\n # @return [Hash, nil] Provides the rule owner (AWS or customer), the rule identifier, and the notifications that cause the function to evaluate your AWS resources.\n attribute :source\n validates :source, type: Hash\n\n # @return [Object, nil] A string, in JSON format, that is passed to the AWS Config rule Lambda function.\n attribute :input_parameters\n\n # @return [:One_Hour, :Three_Hours, :Six_Hours, :Twelve_Hours, :TwentyFour_Hours, nil] The maximum frequency with which AWS Config runs evaluations for a rule.\n attribute :execution_frequency\n validates :execution_frequency, expression_inclusion: {:in=>[:One_Hour, :Three_Hours, :Six_Hours, :Twelve_Hours, :TwentyFour_Hours], :message=>\"%{value} needs to be :One_Hour, :Three_Hours, :Six_Hours, :Twelve_Hours, :TwentyFour_Hours\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6675191521644592, "alphanum_fraction": 0.6675191521644592, "avg_line_length": 34.54545593261719, "blob_id": "8f5996f5d1d529c68bc09aa2cc13cbdbd39f6b56", "content_id": "0141210ff66cee0c75e8495413ea0034eda3b1a0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 782, "license_type": "permissive", "max_line_length": 143, "num_lines": 22, "path": "/lib/ansible/ruby/modules/generated/monitoring/zabbix/zabbix_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create host groups if they do not exist.\n # Delete existing host groups if they exist.\n class Zabbix_group < Base\n # @return [:present, :absent, nil] Create or delete host group.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Array<String>, String] List of host groups to create or delete.\n attribute :host_groups\n validates :host_groups, presence: true, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6645962595939636, "alphanum_fraction": 0.6645962595939636, "avg_line_length": 43.19607925415039, "blob_id": "b39be423cc9b8907c8eab7c7c5dbb5b868dbfee9", "content_id": "c5f2f80374fc1a93c44d1cdb0e70d3503806d478", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2254, "license_type": "permissive", "max_line_length": 267, "num_lines": 51, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage OpenStack Identity users. Users can be created, updated or deleted using this module. A user will be updated if I(name) matches an existing user and I(state) is present. The value for I(name) cannot be updated without deleting and re-creating the user.\n class Os_user < Base\n # @return [String] Username for the user\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Password for the user\n attribute :password\n validates :password, type: String\n\n # @return [:always, :on_create, nil] C(always) will attempt to update password. C(on_create) will only set the password for newly created users.\n attribute :update_password\n validates :update_password, expression_inclusion: {:in=>[:always, :on_create], :message=>\"%{value} needs to be :always, :on_create\"}, allow_nil: true\n\n # @return [String, nil] Email address for the user\n attribute :email\n validates :email, type: String\n\n # @return [Object, nil] Description about the user\n attribute :description\n\n # @return [String, nil] Project name or ID that the user should be associated with by default\n attribute :default_project\n validates :default_project, type: String\n\n # @return [String, nil] Domain to create the user in if the cloud supports domains\n attribute :domain\n validates :domain, type: String\n\n # @return [:yes, :no, nil] Is the user enabled\n attribute :enabled\n validates :enabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Should the resource be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6633211970329285, "alphanum_fraction": 0.6633211970329285, "avg_line_length": 34.35483932495117, "blob_id": "623f155cfa3af38a2a5ae7ed940ad0e758fd4e05", "content_id": "184346cbfcd6f16d692b40e41e284ff725a08d15", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1096, "license_type": "permissive", "max_line_length": 143, "num_lines": 31, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_server_volume.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Attach or Detach volumes from OpenStack VM's\n class Os_server_volume < Base\n # @return [:present, :absent, nil] Should the resource be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object] Name or ID of server you want to attach a volume to\n attribute :server\n validates :server, presence: true\n\n # @return [Object] Name or id of volume you want to attach to a server\n attribute :volume\n validates :volume, presence: true\n\n # @return [Object, nil] Device you want to attach. Defaults to auto finding a device name.\n attribute :device\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6772334575653076, "alphanum_fraction": 0.6829971075057983, "avg_line_length": 45.89189147949219, "blob_id": "d78482605e18bea639479515fb81c6d62fe50b32", "content_id": "6c455aae412f73d3c8733ca245077095592f896f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1735, "license_type": "permissive", "max_line_length": 210, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_sqlfirewallrule.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and delete instance of Firewall Rule.\n class Azure_rm_sqlfirewallrule < Base\n # @return [String] The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] The name of the server.\n attribute :server_name\n validates :server_name, presence: true, type: String\n\n # @return [String] The name of the firewall rule.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The start IP address of the firewall rule. Must be IPv4 format. Use value C(0.0.0.0) to represent all Azure-internal IP addresses.\n attribute :start_ip_address\n validates :start_ip_address, type: String\n\n # @return [String, nil] The end IP address of the firewall rule. Must be IPv4 format. Must be greater than or equal to startIpAddress. Use value C(0.0.0.0) to represe nt all Azure-internal IP addresses.\n attribute :end_ip_address\n validates :end_ip_address, type: String\n\n # @return [:absent, :present, nil] Assert the state of the SQL Database. Use 'present' to create or update an SQL Database and 'absent' to delete it.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6568807363510132, "alphanum_fraction": 0.6568807363510132, "avg_line_length": 40.92307662963867, "blob_id": "accde593cb45a9c7fdcf2375bfefa1b3368426ce", "content_id": "d41f056011246ff7f7086154db1b76e25e3217ac", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1635, "license_type": "permissive", "max_line_length": 172, "num_lines": 39, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_firmware_source.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage firmware image sources on Cisco ACI fabrics.\n class Aci_firmware_source < Base\n # @return [String] The identifying name for the outside source of images, such as an HTTP or SCP server.\n attribute :source\n validates :source, presence: true, type: String\n\n # @return [Integer, nil] Polling interval in minutes.\n attribute :polling_interval\n validates :polling_interval, type: Integer\n\n # @return [:http, :local, :scp, :usbkey, nil] The Firmware download protocol.\n attribute :url_protocol\n validates :url_protocol, expression_inclusion: {:in=>[:http, :local, :scp, :usbkey], :message=>\"%{value} needs to be :http, :local, :scp, :usbkey\"}, allow_nil: true\n\n # @return [String, nil] The firmware URL for the image(s) on the source.\n attribute :url\n validates :url, type: String\n\n # @return [Object, nil] The Firmware password or key string.\n attribute :url_password\n\n # @return [Object, nil] The username for the source.\n attribute :url_username\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6800000071525574, "alphanum_fraction": 0.6800000071525574, "avg_line_length": 13.285714149475098, "blob_id": "32aaf62ec049c37a610279bef4e8f91f7dee7324", "content_id": "0cfaad163ac6c64f30969b799b66f93120078178", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 100, "license_type": "permissive", "max_line_length": 29, "num_lines": 7, "path": "/examples/command.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nplay 'command fun' do\n local_host\n\n role 'dummy', when: 'true'\nend\n" }, { "alpha_fraction": 0.6865423321723938, "alphanum_fraction": 0.6868754029273987, "avg_line_length": 68.0114974975586, "blob_id": "b4013d5d701b29b761b72f2b68eaba7cee66cdc7", "content_id": "460b85fe5749608b81d4c263dbf3f4d12965b5fa", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6004, "license_type": "permissive", "max_line_length": 467, "num_lines": 87, "path": "/lib/ansible/ruby/modules/generated/cloud/docker/docker_service.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Consumes docker compose to start, shutdown and scale services.\n # Works with compose versions 1 and 2.\n # Compose can be read from a docker-compose.yml (or .yaml) file or inline using the C(definition) option.\n # See the examples for more details.\n # Supports check mode.\n class Docker_service < Base\n # @return [Object, nil] Path to a directory containing a docker-compose.yml or docker-compose.yaml file.,Mutually exclusive with C(definition).,Required when no C(definition) is provided.\n attribute :project_src\n\n # @return [Object, nil] Provide a project name. If not provided, the project name is taken from the basename of C(project_src).,Required when C(definition) is provided.\n attribute :project_name\n\n # @return [Object, nil] List of file names relative to C(project_src). Overrides docker-compose.yml or docker-compose.yaml.,Files are loaded and merged in the order given.\n attribute :files\n\n # @return [:absent, :present, nil] Desired state of the project.,Specifying I(present) is the same as running I(docker-compose up).,Specifying I(absent) is the same as running I(docker-compose down).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [Object, nil] When C(state) is I(present) run I(docker-compose up) on a subset of services.\n attribute :services\n\n # @return [Object, nil] When C(state) is I(present) scale services. Provide a dictionary of key/value pairs where the key is the name of the service and the value is an integer count for the number of containers.\n attribute :scale\n\n # @return [:yes, :no, nil] When C(state) is I(present) specify whether or not to include linked services.\n attribute :dependencies\n validates :dependencies, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Provide docker-compose yaml describing one or more services, networks and volumes.,Mutually exclusive with C(project_src) and C(files).\n attribute :definition\n\n # @return [:yes, :no, nil] Whether or not to check the Docker daemon's hostname against the name provided in the client certificate.\n attribute :hostname_check\n validates :hostname_check, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:always, :never, :smart, nil] By default containers will be recreated when their configuration differs from the service definition.,Setting to I(never) ignores configuration differences and leaves existing containers unchanged.,Setting to I(always) forces recreation of all existing containers.\n attribute :recreate\n validates :recreate, expression_inclusion: {:in=>[:always, :never, :smart], :message=>\"%{value} needs to be :always, :never, :smart\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Use with state I(present) to always build images prior to starting the application.,Same as running docker-compose build with the pull option.,Images will only be rebuilt if Docker detects a change in the Dockerfile or build directory contents.,Use the C(nocache) option to ignore the image cache when performing the build.,If an existing image is replaced, services using the image will be recreated unless C(recreate) is I(never).\n attribute :build\n validates :build, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Use with state I(present) to always pull images prior to starting the application.,Same as running docker-compose pull.,When a new image is pulled, services using the image will be recreated unless C(recreate) is I(never).\n attribute :pull\n validates :pull, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Use with the build option to ignore the cache during the image build process.\n attribute :nocache\n validates :nocache, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:all, :local, nil] Use with state I(absent) to remove the all images or only local images.\n attribute :remove_images\n validates :remove_images, expression_inclusion: {:in=>[:all, :local], :message=>\"%{value} needs to be :all, :local\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Use with state I(absent) to remove data volumes.\n attribute :remove_volumes\n validates :remove_volumes, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Use with state I(present) to leave the containers in an exited or non-running state.\n attribute :stopped\n validates :stopped, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Use with state I(present) to restart all containers.\n attribute :restarted\n validates :restarted, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Symbol, nil] Remove containers for services not defined in the compose file.\n attribute :remove_orphans\n validates :remove_orphans, type: Symbol\n\n # @return [Integer, nil] timeout in seconds for container shutdown when attached or when containers are already running.\n attribute :timeout\n validates :timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.671999990940094, "alphanum_fraction": 0.679578959941864, "avg_line_length": 51.77777862548828, "blob_id": "6210f53dabfdcc4ad643fcc9e26b9271d667bb02", "content_id": "3c717a2aa6632048a4486ab8de938d4dbece9d2d", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2375, "license_type": "permissive", "max_line_length": 449, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_snmp_trap.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manipulate SNMP trap information on a BIG-IP.\n class Bigip_snmp_trap < Base\n # @return [String] Name of the SNMP configuration endpoint.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [1, :\"2c\", nil] Specifies to which Simple Network Management Protocol (SNMP) version the trap destination applies.\n attribute :snmp_version\n validates :snmp_version, expression_inclusion: {:in=>[1, :\"2c\"], :message=>\"%{value} needs to be 1, :\\\"2c\\\"\"}, allow_nil: true\n\n # @return [String, nil] Specifies the community name for the trap destination.\n attribute :community\n validates :community, type: String\n\n # @return [String, nil] Specifies the address for the trap destination. This can be either an IP address or a hostname.\n attribute :destination\n validates :destination, type: String\n\n # @return [Integer, nil] Specifies the port for the trap destination.\n attribute :port\n validates :port, type: Integer\n\n # @return [:other, :management, :default, nil] Specifies the name of the trap network. This option is not supported in versions of BIG-IP < 12.1.0. If used on versions < 12.1.0, it will simply be ignored.,The value C(default) was removed in BIG-IP version 13.1.0. Specifying this value when configuring a BIG-IP will cause the module to stop and report an error. The usual remedy is to choose one of the other options, such as C(management).\n attribute :network\n validates :network, expression_inclusion: {:in=>[:other, :management, :default], :message=>\"%{value} needs to be :other, :management, :default\"}, allow_nil: true\n\n # @return [:present, :absent, nil] When C(present), ensures that the resource exists.,When C(absent), ensures that the resource does not exist.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6464088559150696, "alphanum_fraction": 0.6464088559150696, "avg_line_length": 31.909090042114258, "blob_id": "520cdfc8b4ad1707c02a94867c183eab367f642e", "content_id": "9c5ad6f7b9868157841255548e7ae23805854c84", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1086, "license_type": "permissive", "max_line_length": 142, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/monitoring/pingdom.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module will let you pause/unpause Pingdom alerts\n class Pingdom < Base\n # @return [:running, :paused] Define whether or not the check should be running or paused.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:running, :paused], :message=>\"%{value} needs to be :running, :paused\"}\n\n # @return [Integer] Pingdom ID of the check.\n attribute :checkid\n validates :checkid, presence: true, type: Integer\n\n # @return [String] Pingdom user ID.\n attribute :uid\n validates :uid, presence: true, type: String\n\n # @return [String] Pingdom user password.\n attribute :passwd\n validates :passwd, presence: true, type: String\n\n # @return [String] Pingdom API key.\n attribute :key\n validates :key, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6934145092964172, "alphanum_fraction": 0.6934145092964172, "avg_line_length": 53.75757598876953, "blob_id": "09154ca2d1153706fb48160e9a1861747404cd3a", "content_id": "5bebb1d9e30aa486914bc784c89f3ba8a3e6e53e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3614, "license_type": "permissive", "max_line_length": 192, "num_lines": 66, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_ospf_vrf.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages a VRF for an OSPF router.\n class Nxos_ospf_vrf < Base\n # @return [String, nil] Name of the resource instance. Valid value is a string. The name 'default' is a valid VRF representing the global OSPF.\n attribute :vrf\n validates :vrf, type: String\n\n # @return [Integer] Name of the OSPF instance.\n attribute :ospf\n validates :ospf, presence: true, type: Integer\n\n # @return [Object, nil] Router Identifier (ID) of the OSPF router VRF instance.\n attribute :router_id\n\n # @return [Object, nil] Specify the default Metric value. Valid values are an integer or the keyword 'default'.\n attribute :default_metric\n\n # @return [:log, :detail, :default, nil] Controls the level of log messages generated whenever a neighbor changes state. Valid values are 'log', 'detail', and 'default'.\n attribute :log_adjacency\n validates :log_adjacency, expression_inclusion: {:in=>[:log, :detail, :default], :message=>\"%{value} needs to be :log, :detail, :default\"}, allow_nil: true\n\n # @return [Integer, nil] Specify the start interval for rate-limiting Link-State Advertisement (LSA) generation. Valid values are an integer, in milliseconds, or the keyword 'default'.\n attribute :timer_throttle_lsa_start\n validates :timer_throttle_lsa_start, type: Integer\n\n # @return [Integer, nil] Specify the hold interval for rate-limiting Link-State Advertisement (LSA) generation. Valid values are an integer, in milliseconds, or the keyword 'default'.\n attribute :timer_throttle_lsa_hold\n validates :timer_throttle_lsa_hold, type: Integer\n\n # @return [Integer, nil] Specify the max interval for rate-limiting Link-State Advertisement (LSA) generation. Valid values are an integer, in milliseconds, or the keyword 'default'.\n attribute :timer_throttle_lsa_max\n validates :timer_throttle_lsa_max, type: Integer\n\n # @return [Integer, nil] Specify initial Shortest Path First (SPF) schedule delay. Valid values are an integer, in milliseconds, or the keyword 'default'.\n attribute :timer_throttle_spf_start\n validates :timer_throttle_spf_start, type: Integer\n\n # @return [Integer, nil] Specify minimum hold time between Shortest Path First (SPF) calculations. Valid values are an integer, in milliseconds, or the keyword 'default'.\n attribute :timer_throttle_spf_hold\n validates :timer_throttle_spf_hold, type: Integer\n\n # @return [Integer, nil] Specify the maximum wait time between Shortest Path First (SPF) calculations. Valid values are an integer, in milliseconds, or the keyword 'default'.\n attribute :timer_throttle_spf_max\n validates :timer_throttle_spf_max, type: Integer\n\n # @return [Object, nil] Specifies the reference bandwidth used to assign OSPF cost. Valid values are an integer, in Mbps, or the keyword 'default'.\n attribute :auto_cost\n\n # @return [Symbol, nil] Setting to C(yes) will suppress routing update on interface.\n attribute :passive_interface\n validates :passive_interface, type: Symbol\n\n # @return [:present, :absent, nil] State of ospf vrf configuration.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6872549057006836, "alphanum_fraction": 0.6892156600952148, "avg_line_length": 39.79999923706055, "blob_id": "644ae592b687536479faa0659162b8dbb64fa5c0", "content_id": "65b3f6761e5411bf35b235e7f4351eb762812bc9", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1020, "license_type": "permissive", "max_line_length": 163, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_software_update.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage the software update settings of a BIG-IP.\n class Bigip_software_update < Base\n # @return [Symbol, nil] Specifies whether to automatically check for updates on the F5 Networks downloads server.\n attribute :auto_check\n validates :auto_check, type: Symbol\n\n # @return [Symbol, nil] Specifies whether to automatically send phone home data to the F5 Networks PhoneHome server.\n attribute :auto_phone_home\n validates :auto_phone_home, type: Symbol\n\n # @return [:daily, :monthly, :weekly, nil] Specifies the schedule for the automatic update check.\n attribute :frequency\n validates :frequency, expression_inclusion: {:in=>[:daily, :monthly, :weekly], :message=>\"%{value} needs to be :daily, :monthly, :weekly\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6619794368743896, "alphanum_fraction": 0.6619794368743896, "avg_line_length": 35.97999954223633, "blob_id": "a5cf1eefecab1b615e53e1f6442d5e99d2fe06e1", "content_id": "048779a0f9b84f716291159659d15782e0781402", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1849, "license_type": "permissive", "max_line_length": 143, "num_lines": 50, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/sqs_queue.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or delete AWS SQS queues.\n # Update attributes on existing queues.\n class Sqs_queue < Base\n # @return [:present, :absent, nil] Create or delete the queue\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] Name of the queue.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Integer, nil] The default visibility timeout in seconds.\n attribute :default_visibility_timeout\n validates :default_visibility_timeout, type: Integer\n\n # @return [Integer, nil] The message retention period in seconds.\n attribute :message_retention_period\n validates :message_retention_period, type: Integer\n\n # @return [Integer, nil] The maximum message size in bytes.\n attribute :maximum_message_size\n validates :maximum_message_size, type: Integer\n\n # @return [Integer, nil] The delivery delay in seconds.\n attribute :delivery_delay\n validates :delivery_delay, type: Integer\n\n # @return [Integer, nil] The receive message wait time in seconds.\n attribute :receive_message_wait_time\n validates :receive_message_wait_time, type: Integer\n\n # @return [String, nil] The json dict policy to attach to queue\n attribute :policy\n validates :policy, type: String\n\n # @return [Hash, nil] json dict with the redrive_policy (see example)\n attribute :redrive_policy\n validates :redrive_policy, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7305662035942078, "alphanum_fraction": 0.7329654693603516, "avg_line_length": 76.18518829345703, "blob_id": "5708554c2417fce8db494450fe572650963bcc0a", "content_id": "7af3cd7d3faf095f75cfc2737556faed66bdd039", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4168, "license_type": "permissive", "max_line_length": 504, "num_lines": 54, "path": "/lib/ansible/ruby/modules/generated/storage/purestorage/purefa_ds.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Set or erase configuration for the directory service. There is no facility to SSL certificates at this time. Use the FlashArray GUI for this additional configuration work.\n # To modify an existing directory service configuration you must first delete an exisitng configuration and then recreate with new settings.\n class Purefa_ds < Base\n # @return [:absent, :present, nil] Create or delete directory service configuration\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [Symbol, nil] Whether to enable or disable directory service support.\n attribute :enable\n validates :enable, type: Symbol\n\n # @return [String, nil] A list of up to 30 URIs of the directory servers. Each URI must include the scheme ldap:// or ldaps:// (for LDAP over SSL), a hostname, and a domain name or IP address. For example, ldap://ad.company.com configures the directory service with the hostname \"ad\" in the domain \"company.com\" while specifying the unencrypted LDAP protocol.\n attribute :uri\n validates :uri, type: String\n\n # @return [Array<String>, String] Sets the base of the Distinguished Name (DN) of the directory service groups. The base should consist of only Domain Components (DCs). The base_dn will populate with a default value when a URI is entered by parsing domain components from the URI. The base DN should specify DC= for each domain component and multiple DCs should be separated by commas.\n attribute :base_dn\n validates :base_dn, presence: true, type: TypeGeneric.new(String)\n\n # @return [String, nil] Sets the password of the bind_user user name account.\n attribute :bind_password\n validates :bind_password, type: String\n\n # @return [String, nil] Sets the user name that can be used to bind to and query the directory.,For Active Directory, enter the username - often referred to as sAMAccountName or User Logon Name - of the account that is used to perform directory lookups.,For OpenLDAP, enter the full DN of the user.\n attribute :bind_user\n validates :bind_user, type: String\n\n # @return [String, nil] Specifies where the configured groups are located in the directory tree. This field consists of Organizational Units (OUs) that combine with the base DN attribute and the configured group CNs to complete the full Distinguished Name of the groups. The group base should specify OU= for each OU and multiple OUs should be separated by commas. The order of OUs is important and should get larger in scope from left to right. Each OU should not exceed 64 characters in length.\n attribute :group_base\n validates :group_base, type: String\n\n # @return [String, nil] Sets the common Name (CN) of the configured directory service group containing users with read-only privileges on the FlashArray. This name should be just the Common Name of the group without the CN= specifier. Common Names should not exceed 64 characters in length.\n attribute :ro_group\n validates :ro_group, type: String\n\n # @return [String, nil] Sets the common Name (CN) of the configured directory service group containing administrators with storage-related privileges on the FlashArray. This name should be just the Common Name of the group without the CN= specifier. Common Names should not exceed 64 characters in length.\n attribute :sa_group\n validates :sa_group, type: String\n\n # @return [String, nil] Sets the common Name (CN) of the directory service group containing administrators with full privileges when managing the FlashArray. The name should be just the Common Name of the group without the CN= specifier. Common Names should not exceed 64 characters in length.\n attribute :aa_group\n validates :aa_group, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6591333746910095, "alphanum_fraction": 0.662531852722168, "avg_line_length": 44.620155334472656, "blob_id": "518af67a238460f1b2c70088b1c6eaab5dca870a", "content_id": "972c61bfee96a844bd1134d818ed8c6aa9ea4b84", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5885, "license_type": "permissive", "max_line_length": 245, "num_lines": 129, "path": "/lib/ansible/ruby/modules/generated/cloud/linode/linode.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage Linode Public Cloud instances and optionally wait for it to be 'running'.\n class Linode < Base\n # @return [:absent, :active, :deleted, :present, :restarted, :started, :stopped, nil] Indicate desired state of the resource\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :active, :deleted, :present, :restarted, :started, :stopped], :message=>\"%{value} needs to be :absent, :active, :deleted, :present, :restarted, :started, :stopped\"}, allow_nil: true\n\n # @return [String, nil] Linode API key\n attribute :api_key\n validates :api_key, type: String\n\n # @return [String] Name to give the instance (alphanumeric, dashes, underscore).,To keep sanity on the Linode Web Console, name is prepended with C(LinodeID_).\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Add the instance to a Display Group in Linode Manager.\n attribute :displaygroup\n validates :displaygroup, type: String\n\n # @return [Integer, nil] Unique ID of a linode server\n attribute :linode_id\n validates :linode_id, type: Integer\n\n # @return [Array<Hash>, Hash, nil] List of dictionaries for creating additional disks that are added to the Linode configuration settings.,Dictionary takes Size, Label, Type. Size is in MB.\n attribute :additional_disks\n validates :additional_disks, type: TypeGeneric.new(Hash)\n\n # @return [Symbol, nil] Set status of bandwidth in alerts.\n attribute :alert_bwin_enabled\n validates :alert_bwin_enabled, type: Symbol\n\n # @return [Integer, nil] Set threshold in MB of bandwidth in alerts.\n attribute :alert_bwin_threshold\n validates :alert_bwin_threshold, type: Integer\n\n # @return [Symbol, nil] Set status of bandwidth out alerts.\n attribute :alert_bwout_enabled\n validates :alert_bwout_enabled, type: Symbol\n\n # @return [Integer, nil] Set threshold in MB of bandwidth out alerts.\n attribute :alert_bwout_threshold\n validates :alert_bwout_threshold, type: Integer\n\n # @return [Symbol, nil] Set status of bandwidth quota alerts as percentage of network transfer quota.\n attribute :alert_bwquota_enabled\n validates :alert_bwquota_enabled, type: Symbol\n\n # @return [Integer, nil] Set threshold in MB of bandwidth quota alerts.\n attribute :alert_bwquota_threshold\n validates :alert_bwquota_threshold, type: Integer\n\n # @return [Symbol, nil] Set status of receiving CPU usage alerts.\n attribute :alert_cpu_enabled\n validates :alert_cpu_enabled, type: Symbol\n\n # @return [Integer, nil] Set percentage threshold for receiving CPU usage alerts. Each CPU core adds 100% to total.\n attribute :alert_cpu_threshold\n validates :alert_cpu_threshold, type: Integer\n\n # @return [Symbol, nil] Set status of receiving disk IO alerts.\n attribute :alert_diskio_enabled\n validates :alert_diskio_enabled, type: Symbol\n\n # @return [Integer, nil] Set threshold for average IO ops/sec over 2 hour period.\n attribute :alert_diskio_threshold\n validates :alert_diskio_threshold, type: Integer\n\n # @return [Integer, nil] Integer value for what day of the week to store weekly backups.\n attribute :backupweeklyday\n validates :backupweeklyday, type: Integer\n\n # @return [Integer, nil] plan to use for the instance (Linode plan)\n attribute :plan\n validates :plan, type: Integer\n\n # @return [1, 12, 24, nil] payment term to use for the instance (payment term in months)\n attribute :payment_term\n validates :payment_term, expression_inclusion: {:in=>[1, 12, 24], :message=>\"%{value} needs to be 1, 12, 24\"}, allow_nil: true\n\n # @return [String, nil] root password to apply to a new server (auto generated if missing)\n attribute :password\n validates :password, type: String\n\n # @return [:yes, :no, nil] Add private IPv4 address when Linode is created.\n attribute :private_ip\n validates :private_ip, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] SSH public key applied to root user\n attribute :ssh_pub_key\n validates :ssh_pub_key, type: String\n\n # @return [Integer, nil] swap size in MB\n attribute :swap\n validates :swap, type: Integer\n\n # @return [Integer, nil] distribution to use for the instance (Linode Distribution)\n attribute :distribution\n validates :distribution, type: Integer\n\n # @return [Integer, nil] datacenter to create an instance in (Linode Datacenter)\n attribute :datacenter\n validates :datacenter, type: Integer\n\n # @return [Integer, nil] kernel to use for the instance (Linode Kernel)\n attribute :kernel_id\n validates :kernel_id, type: Integer\n\n # @return [:yes, :no, nil] wait for the instance to be in state C(running) before returning\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] how long before wait gives up, in seconds\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [Boolean, nil] Set status of Lassie watchdog.\n attribute :watchdog\n validates :watchdog, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6718310117721558, "alphanum_fraction": 0.6718310117721558, "avg_line_length": 42.46938705444336, "blob_id": "73e6622dad3d17af29d6560293ef297945cef65e", "content_id": "4ea7a28ac3bfd0a431820be3a0136002425468cb", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2130, "license_type": "permissive", "max_line_length": 142, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/netapp_e_hostgroup.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update or destroy host groups on a NetApp E-Series storage array.\n class Netapp_e_hostgroup < Base\n # @return [String] The username to authenticate with the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_username\n validates :api_username, presence: true, type: String\n\n # @return [String] The password to authenticate with the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_password\n validates :api_password, presence: true, type: String\n\n # @return [String] The url to the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_url\n validates :api_url, presence: true, type: String\n\n # @return [Boolean, nil] Should https certificates be validated?\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String] The ID of the array to manage (as configured on the web services proxy).\n attribute :ssid\n validates :ssid, presence: true, type: String\n\n # @return [:present, :absent] Whether the specified host group should exist or not.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [Object, nil] The name of the host group to manage. Either this or C(id_num) must be supplied.\n attribute :name\n\n # @return [Object, nil] specify this when you need to update the name of a host group\n attribute :new_name\n\n # @return [Object, nil] The id number of the host group to manage. Either this or C(name) must be supplied.\n attribute :id\n\n # @return [Object, nil] a list of host names/labels to add to the group\n attribute :hosts\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6935218572616577, "alphanum_fraction": 0.6981256008148193, "avg_line_length": 71.4047622680664, "blob_id": "10603c0bfad70692d999573344eb4a3b19206399", "content_id": "f98d3cd124a37adb76ee09bfc0c76bfe17614ae5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3041, "license_type": "permissive", "max_line_length": 517, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_info_center_trap.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages information center trap configurations on HUAWEI CloudEngine switches.\n class Ce_info_center_trap < Base\n # @return [:present, :absent, nil] Specify desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:date_boot, :date_second, :date_tenthsecond, :date_millisecond, :shortdate_second, :shortdate_tenthsecond, :shortdate_millisecond, :formatdate_second, :formatdate_tenthsecond, :formatdate_millisecond, nil] Timestamp format of alarm information.\n attribute :trap_time_stamp\n validates :trap_time_stamp, expression_inclusion: {:in=>[:date_boot, :date_second, :date_tenthsecond, :date_millisecond, :shortdate_second, :shortdate_tenthsecond, :shortdate_millisecond, :formatdate_second, :formatdate_tenthsecond, :formatdate_millisecond], :message=>\"%{value} needs to be :date_boot, :date_second, :date_tenthsecond, :date_millisecond, :shortdate_second, :shortdate_tenthsecond, :shortdate_millisecond, :formatdate_second, :formatdate_tenthsecond, :formatdate_millisecond\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] Whether a trap buffer is enabled to output information.\n attribute :trap_buff_enable\n validates :trap_buff_enable, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [Object, nil] Size of a trap buffer. The value is an integer ranging from 0 to 1024. The default value is 256.\n attribute :trap_buff_size\n\n # @return [Object, nil] Module name of the rule. The value is a string of 1 to 31 case-insensitive characters. The default value is default. Please use lower-case letter, such as [aaa, acl, arp, bfd].\n attribute :module_name\n\n # @return [Object, nil] Number of a channel. The value is an integer ranging from 0 to 9. The default value is 0.\n attribute :channel_id\n\n # @return [:no_use, :true, :false, nil] Whether a device is enabled to output alarms.\n attribute :trap_enable\n validates :trap_enable, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:emergencies, :alert, :critical, :error, :warning, :notification, :informational, :debugging, nil] Trap level permitted to output.\n attribute :trap_level\n validates :trap_level, expression_inclusion: {:in=>[:emergencies, :alert, :critical, :error, :warning, :notification, :informational, :debugging], :message=>\"%{value} needs to be :emergencies, :alert, :critical, :error, :warning, :notification, :informational, :debugging\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6701030731201172, "alphanum_fraction": 0.6701030731201172, "avg_line_length": 35.7931022644043, "blob_id": "1d49a524ee81c70315723761447fc715e2a0c12c", "content_id": "d43a076c1a5f6fd1b6656e1bbae4a119d538b9e5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1067, "license_type": "permissive", "max_line_length": 142, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/monitoring/zabbix/zabbix_host_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows you to search for Zabbix host entries.\n class Zabbix_host_facts < Base\n # @return [String] Name of the host in Zabbix.,host_name is the unique identifier used and cannot be updated using this module.\n attribute :host_name\n validates :host_name, presence: true, type: String\n\n # @return [String, nil] Host interface IP of the host in Zabbix.\n attribute :host_ip\n validates :host_ip, type: String\n\n # @return [Symbol, nil] Find the exact match\n attribute :exact_match\n validates :exact_match, type: Symbol\n\n # @return [Boolean, nil] Remove duplicate host from host result\n attribute :remove_duplicate\n validates :remove_duplicate, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7010893225669861, "alphanum_fraction": 0.7041394114494324, "avg_line_length": 45.836734771728516, "blob_id": "b5252c8d27e7dbb2ff95f8ec0db77197a754e01f", "content_id": "0b1c618e290e3224db145d4599c86d70bbf86f2e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2295, "license_type": "permissive", "max_line_length": 219, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/monitoring/librato_annotation.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create an annotation event on the given annotation stream :name. If the annotation stream does not exist, it will be created automatically\n class Librato_annotation < Base\n # @return [String] Librato account username\n attribute :user\n validates :user, presence: true, type: String\n\n # @return [String] Librato account api key\n attribute :api_key\n validates :api_key, presence: true, type: String\n\n # @return [String, nil] The annotation stream name,If the annotation stream does not exist, it will be created automatically\n attribute :name\n validates :name, type: String\n\n # @return [String] The title of an annotation is a string and may contain spaces,The title should be a short, high-level summary of the annotation e.g. v45 Deployment\n attribute :title\n validates :title, presence: true, type: String\n\n # @return [String, nil] A string which describes the originating source of an annotation when that annotation is tracked across multiple members of a population\n attribute :source\n validates :source, type: String\n\n # @return [String, nil] The description contains extra meta-data about a particular annotation,The description should contain specifics on the individual annotation e.g. Deployed 9b562b2 shipped new feature foo!\n attribute :description\n validates :description, type: String\n\n # @return [Integer, nil] The unix timestamp indicating the time at which the event referenced by this annotation started\n attribute :start_time\n validates :start_time, type: Integer\n\n # @return [Integer, nil] The unix timestamp indicating the time at which the event referenced by this annotation ended,For events that have a duration, this is a useful way to annotate the duration of the event\n attribute :end_time\n validates :end_time, type: Integer\n\n # @return [Array<Hash>, Hash] See examples\n attribute :links\n validates :links, presence: true, type: TypeGeneric.new(Hash)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6306569576263428, "alphanum_fraction": 0.6306569576263428, "avg_line_length": 44.66666793823242, "blob_id": "7e475ee8277cbada48d19bc84d4a7f2c6eaa7dad", "content_id": "a4f4dee82658512b3f252f7b06f93113a763e08d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2055, "license_type": "permissive", "max_line_length": 307, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/net_tools/exoscale/exo_dns_record.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and delete records.\n class Exo_dns_record < Base\n # @return [String, nil] Name of the record.\n attribute :name\n validates :name, type: String\n\n # @return [String] Domain the record is related to.\n attribute :domain\n validates :domain, presence: true, type: String\n\n # @return [:A, :ALIAS, :CNAME, :MX, :SPF, :URL, :TXT, :NS, :SRV, :NAPTR, :PTR, :AAAA, :SSHFP, :HINFO, :POOL, nil] Type of the record.\n attribute :record_type\n validates :record_type, expression_inclusion: {:in=>[:A, :ALIAS, :CNAME, :MX, :SPF, :URL, :TXT, :NS, :SRV, :NAPTR, :PTR, :AAAA, :SSHFP, :HINFO, :POOL], :message=>\"%{value} needs to be :A, :ALIAS, :CNAME, :MX, :SPF, :URL, :TXT, :NS, :SRV, :NAPTR, :PTR, :AAAA, :SSHFP, :HINFO, :POOL\"}, allow_nil: true\n\n # @return [String, nil] Content of the record.,Required if C(state=present) or C(multiple=yes).\n attribute :content\n validates :content, type: String\n\n # @return [Integer, nil] TTL of the record in seconds.\n attribute :ttl\n validates :ttl, type: Integer\n\n # @return [Integer, nil] Priority of the record.\n attribute :prio\n validates :prio, type: Integer\n\n # @return [Symbol, nil] Whether there are more than one records with similar C(name) and C(record_type).,Only allowed for a few record types, e.g. C(record_type=A), C(record_type=NS) or C(record_type=MX).,C(content) will not be updated, instead it is used as a key to find existing records.\n attribute :multiple\n validates :multiple, type: Symbol\n\n # @return [:present, :absent, nil] State of the record.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6714285612106323, "alphanum_fraction": 0.6714285612106323, "avg_line_length": 41.77777862548828, "blob_id": "e65a673ab123fe1920d5c11d02f317c65f62cde1", "content_id": "f7be45105fecc8dcbf648eb2e405c8b443d11519", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1540, "license_type": "permissive", "max_line_length": 273, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_project.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage OpenStack Projects. Projects can be created, updated or deleted using this module. A project will be updated if I(name) matches an existing project and I(state) is present. The value for I(name) cannot be updated without deleting and re-creating the project.\n class Os_project < Base\n # @return [String] Name for the project\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Description for the project\n attribute :description\n validates :description, type: String\n\n # @return [String, nil] Domain id to create the project in if the cloud supports domains.\n attribute :domain_id\n validates :domain_id, type: String\n\n # @return [:yes, :no, nil] Is the project enabled\n attribute :enabled\n validates :enabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Should the resource be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6551724076271057, "alphanum_fraction": 0.6551724076271057, "avg_line_length": 29.115385055541992, "blob_id": "df473217ecef4e2089abd73a84fd81e70b094e8c", "content_id": "caa2dad75442334f575f89e41dc23ebbf8bb0f7a", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 783, "license_type": "permissive", "max_line_length": 83, "num_lines": 26, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_svm_options.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Modify ONTAP SVM Options\n # Only Options that appear on \"vserver options show\" can be set\n class Na_ontap_svm_options < Base\n # @return [String, nil] Name of the option.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] Value of the option.,Value must be in quote\n attribute :value\n validates :value, type: String\n\n # @return [String] The name of the vserver to which this option belongs to.\n attribute :vserver\n validates :vserver, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6425532102584839, "alphanum_fraction": 0.6425532102584839, "avg_line_length": 31.413793563842773, "blob_id": "7220997d1e8ec3e4574014337d5a5434e57a4bc6", "content_id": "14d44120a0a47b4c67d07c129f066dc90ee6c0b6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 940, "license_type": "permissive", "max_line_length": 143, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/database/influxdb/influxdb_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage InfluxDB users\n class Influxdb_user < Base\n # @return [String] Name of the user.\n attribute :user_name\n validates :user_name, presence: true, type: String\n\n # @return [String, nil] Password to be set for the user.\n attribute :user_password\n validates :user_password, type: String\n\n # @return [Symbol, nil] Whether the user should be in the admin role or not.\n attribute :admin\n validates :admin, type: Symbol\n\n # @return [:present, :absent, nil] State of the user.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6665476560592651, "alphanum_fraction": 0.6665476560592651, "avg_line_length": 44.918033599853516, "blob_id": "3461289a2471ce5ead24507b138b4ebf03f99173", "content_id": "3a5eef9549a78ae459f2a7cb20ae748ce073b4ed", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2801, "license_type": "permissive", "max_line_length": 208, "num_lines": 61, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_resource.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update or delete any Azure resource using Azure REST API.\n # This module gives access to resources that are not supported via Ansible modules.\n # Refer to https://docs.microsoft.com/en-us/rest/api/ regarding details related to specific resource REST API.\n class Azure_rm_resource < Base\n # @return [Object, nil] Azure RM Resource URL.\n attribute :url\n\n # @return [String] Specific API version to be used.\n attribute :api_version\n validates :api_version, presence: true, type: String\n\n # @return [String, nil] Provider type.,Required if URL is not specified.\n attribute :provider\n validates :provider, type: String\n\n # @return [String, nil] Resource group to be used.,Required if URL is not specified.\n attribute :resource_group\n validates :resource_group, type: String\n\n # @return [String, nil] Resource type.,Required if URL is not specified.\n attribute :resource_type\n validates :resource_type, type: String\n\n # @return [String, nil] Resource name.,Required if URL Is not specified.\n attribute :resource_name\n validates :resource_name, type: String\n\n # @return [Object, nil] List of subresources\n attribute :subresource\n\n # @return [String, nil] The body of the http request/response to the web service.\n attribute :body\n validates :body, type: String\n\n # @return [:GET, :PUT, :POST, :HEAD, :PATCH, :DELETE, :MERGE, nil] The HTTP method of the request or response. It MUST be uppercase.\n attribute :method\n validates :method, expression_inclusion: {:in=>[:GET, :PUT, :POST, :HEAD, :PATCH, :DELETE, :MERGE], :message=>\"%{value} needs to be :GET, :PUT, :POST, :HEAD, :PATCH, :DELETE, :MERGE\"}, allow_nil: true\n\n # @return [Integer, nil] A valid, numeric, HTTP status code that signifies success of the request. Can also be comma separated list of status codes.\n attribute :status_code\n validates :status_code, type: Integer\n\n # @return [Symbol, nil] If enabled, idempotency check will be done by using GET method first and then comparing with I(body)\n attribute :idempotency\n validates :idempotency, type: Symbol\n\n # @return [:absent, :present, nil] Assert the state of the resource. Use C(present) to create or update resource or C(absent) to delete resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.715881884098053, "alphanum_fraction": 0.716946005821228, "avg_line_length": 69.92453002929688, "blob_id": "08d5aa809733fee2db88455f801e8ab3bffd976f", "content_id": "b5560feea1d7e2c03afd66e81112840e1472cc27", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3759, "license_type": "permissive", "max_line_length": 487, "num_lines": 53, "path": "/lib/ansible/ruby/modules/generated/monitoring/nagios.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The C(nagios) module has two basic functions: scheduling downtime and toggling alerts for services or hosts.\n # All actions require the I(host) parameter to be given explicitly. In playbooks you can use the C({{inventory_hostname}}) variable to refer to the host the playbook is currently running on.\n # You can specify multiple services at once by separating them with commas, .e.g., C(services=httpd,nfs,puppet).\n # When specifying what service to handle there is a special service value, I(host), which will handle alerts/downtime for the I(host itself), e.g., C(service=host). This keyword may not be given with other services at the same time. I(Setting alerts/downtime for a host does not affect alerts/downtime for any of the services running on it.) To schedule downtime for all services on particular host use keyword \"all\", e.g., C(service=all).\n # When using the C(nagios) module you will need to specify your Nagios server using the C(delegate_to) parameter.\n class Nagios < Base\n # @return [:downtime, :delete_downtime, :enable_alerts, :disable_alerts, :silence, :unsilence, :silence_nagios, :unsilence_nagios, :command, :servicegroup_service_downtime, :servicegroup_host_downtime] Action to take.,servicegroup options were added in 2.0.,delete_downtime options were added in 2.2.\n attribute :action\n validates :action, presence: true, expression_inclusion: {:in=>[:downtime, :delete_downtime, :enable_alerts, :disable_alerts, :silence, :unsilence, :silence_nagios, :unsilence_nagios, :command, :servicegroup_service_downtime, :servicegroup_host_downtime], :message=>\"%{value} needs to be :downtime, :delete_downtime, :enable_alerts, :disable_alerts, :silence, :unsilence, :silence_nagios, :unsilence_nagios, :command, :servicegroup_service_downtime, :servicegroup_host_downtime\"}\n\n # @return [String, nil] Host to operate on in Nagios.\n attribute :host\n validates :host, type: String\n\n # @return [String, nil] Path to the nagios I(command file) (FIFO pipe). Only required if auto-detection fails.\n attribute :cmdfile\n validates :cmdfile, type: String\n\n # @return [String, nil] Author to leave downtime comments as. Only usable with the C(downtime) action.\n attribute :author\n validates :author, type: String\n\n # @return [String, nil] Comment for C(downtime) action.\n attribute :comment\n validates :comment, type: String\n\n # @return [Integer, nil] Minutes to schedule downtime for.,Only usable with the C(downtime) action.\n attribute :minutes\n validates :minutes, type: Integer\n\n # @return [Array<String>, String] What to manage downtime/alerts for. Separate multiple services with commas. C(service) is an alias for C(services). B(Required) option when using the C(downtime), C(enable_alerts), and C(disable_alerts) actions.\n attribute :services\n validates :services, presence: true, type: TypeGeneric.new(String)\n\n # @return [String, nil] The Servicegroup we want to set downtimes/alerts for. B(Required) option when using the C(servicegroup_service_downtime) amd C(servicegroup_host_downtime).\n attribute :servicegroup\n validates :servicegroup, type: String\n\n # @return [String] The raw command to send to nagios, which should not include the submitted time header or the line-feed B(Required) option when using the C(command) action.\n attribute :command\n validates :command, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6796671748161316, "alphanum_fraction": 0.6796671748161316, "avg_line_length": 41.733333587646484, "blob_id": "b2902f5ae42bd2d8e124bb124c8e9e6edc7af4f7", "content_id": "e5cef9235c61bd78867075b924e9683a9c2f7c2c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1923, "license_type": "permissive", "max_line_length": 160, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/network/junos/junos_static_route.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of static IP routes on Juniper JUNOS network devices.\n class Junos_static_route < Base\n # @return [String] Network address with prefix of the static route.\n attribute :address\n validates :address, presence: true, type: String\n\n # @return [String] Next hop IP of the static route.\n attribute :next_hop\n validates :next_hop, presence: true, type: String\n\n # @return [String, nil] Qualified next hop IP of the static route. Qualified next hops allow to associate preference with a particular next-hop address.\n attribute :qualified_next_hop\n validates :qualified_next_hop, type: String\n\n # @return [Integer, nil] Global admin preference of the static route.\n attribute :preference\n validates :preference, type: Integer\n\n # @return [Integer, nil] Assign preference for qualified next hop.\n attribute :qualified_preference\n validates :qualified_preference, type: Integer\n\n # @return [Array<Hash>, Hash, nil] List of static route definitions\n attribute :aggregate\n validates :aggregate, type: TypeGeneric.new(Hash)\n\n # @return [:present, :absent, nil] State of the static route configuration.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Boolean, nil] Specifies whether or not the configuration is active or deactivated\n attribute :active\n validates :active, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6897066235542297, "alphanum_fraction": 0.6897066235542297, "avg_line_length": 79.44000244140625, "blob_id": "9187f83bd24ebee4fd75e6136cca0e821f4bd0a2", "content_id": "223cc1353d63d918cc1e0c8e2c875773e5dda74c", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2011, "license_type": "permissive", "max_line_length": 456, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_provision.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage BIG-IP module provisioning. This module will only provision at the standard levels of Dedicated, Nominal, and Minimum.\n class Bigip_provision < Base\n # @return [:am, :afm, :apm, :asm, :avr, :cgnat, :fps, :gtm, :ilx, :lc, :ltm, :pem, :sam, :swg, :vcmp] The module to provision in BIG-IP.\n attribute :module\n validates :module, presence: true, expression_inclusion: {:in=>[:am, :afm, :apm, :asm, :avr, :cgnat, :fps, :gtm, :ilx, :lc, :ltm, :pem, :sam, :swg, :vcmp], :message=>\"%{value} needs to be :am, :afm, :apm, :asm, :avr, :cgnat, :fps, :gtm, :ilx, :lc, :ltm, :pem, :sam, :swg, :vcmp\"}\n\n # @return [:dedicated, :nominal, :minimum, nil] Sets the provisioning level for the requested modules. Changing the level for one module may require modifying the level of another module. For example, changing one module to C(dedicated) requires setting all others to C(none). Setting the level of a module to C(none) means that the module is not activated.,This parameter is not relevant to C(cgnat) and will not be applied to the C(cgnat) module.\n attribute :level\n validates :level, expression_inclusion: {:in=>[:dedicated, :nominal, :minimum], :message=>\"%{value} needs to be :dedicated, :nominal, :minimum\"}, allow_nil: true\n\n # @return [:present, :absent, nil] The state of the provisioned module on the system. When C(present), guarantees that the specified module is provisioned at the requested level provided that there are sufficient resources on the device (such as physical RAM) to support the provisioned module. When C(absent), de-provision the module.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7012448310852051, "alphanum_fraction": 0.7053942084312439, "avg_line_length": 52.55555725097656, "blob_id": "781063dba0412bc74fd482a07aea7cae3f399205", "content_id": "747f6974b2a06461ef814aa0f252acf22e330757", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1446, "license_type": "permissive", "max_line_length": 270, "num_lines": 27, "path": "/lib/ansible/ruby/modules/generated/windows/win_audit_policy_system.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Used to make changes to the system wide Audit Policy.\n # It is recommended to take a backup of the policies before adjusting them for the first time.\n # See this page for in depth information U(https://technet.microsoft.com/en-us/library/cc766468.aspx).\n class Win_audit_policy_system < Base\n # @return [String, nil] Single string value for the category you would like to adjust the policy on.,Cannot be used with I(subcategory). You must define one or the other.,Changing this setting causes all subcategories to be adjusted to the defined I(audit_type).\n attribute :category\n validates :category, type: String\n\n # @return [String, nil] Single string value for the subcategory you would like to adjust the policy on.,Cannot be used with I(category). You must define one or the other.\n attribute :subcategory\n validates :subcategory, type: String\n\n # @return [:failure, :none, :success] The type of event you would like to audit for.,Accepts a list. See examples.\n attribute :audit_type\n validates :audit_type, presence: true, expression_inclusion: {:in=>[:failure, :none, :success], :message=>\"%{value} needs to be :failure, :none, :success\"}\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7031019330024719, "alphanum_fraction": 0.7031019330024719, "avg_line_length": 38.82352828979492, "blob_id": "065f7d3073f309e849f1853e719f44e79945f15f", "content_id": "a0e93df217bfc58c87dbe7951a6bceb83a448cd8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 677, "license_type": "permissive", "max_line_length": 210, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/cloud/docker/docker_image_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Provide one or more image names, and the module will inspect each, returning an array of inspection results.\n class Docker_image_facts < Base\n # @return [Array<String>, String] An image name or a list of image names. Name format will be name[:tag] or repository/name[:tag], where tag is optional. If a tag is not provided, 'latest' will be used.\n attribute :name\n validates :name, presence: true, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6617375016212463, "alphanum_fraction": 0.6626617312431335, "avg_line_length": 36.31034469604492, "blob_id": "31f556db332ff6987b83c8240de683d9c80610ab", "content_id": "353a4fcf7006f7cef33bd35164d268922f2e5eb2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1082, "license_type": "permissive", "max_line_length": 143, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/vultr/vultr_network.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage networks on Vultr. A network cannot be updated. It needs to be deleted and re-created.\n class Vultr_network < Base\n # @return [String] Name of the network.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The CIDR IPv4 network block to be used when attaching servers to this network. Required if I(state=present).\n attribute :cidr\n validates :cidr, type: String\n\n # @return [String, nil] Region the network is deployed into. Required if I(state=present).\n attribute :region\n validates :region, type: String\n\n # @return [:present, :absent, nil] State of the network.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6578947305679321, "alphanum_fraction": 0.6578947305679321, "avg_line_length": 34.849056243896484, "blob_id": "ca0aa4e47c7d761801891755c0d13f3d09ec8f1a", "content_id": "7fdc3634ab97d4fde974d5734da9ed2bbddca12b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1900, "license_type": "permissive", "max_line_length": 125, "num_lines": 53, "path": "/lib/ansible/ruby/modules/generated/database/mongodb/mongodb_parameter.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Change an administrative parameter on a MongoDB server.\n class Mongodb_parameter < Base\n # @return [Object, nil] The username used to authenticate with\n attribute :login_user\n\n # @return [Object, nil] The password used to authenticate with\n attribute :login_password\n\n # @return [String, nil] The host running the database\n attribute :login_host\n validates :login_host, type: String\n\n # @return [Integer, nil] The port to connect to\n attribute :login_port\n validates :login_port, type: Integer\n\n # @return [Object, nil] The database where login credentials are stored\n attribute :login_database\n\n # @return [Object, nil] Replica set to connect to (automatically connects to primary for writes)\n attribute :replica_set\n\n # @return [Object] The name of the database to add/remove the user from\n attribute :database\n validates :database, presence: true\n\n # @return [:yes, :no, nil] Whether to use an SSL connection when connecting to the database\n attribute :ssl\n validates :ssl, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String] MongoDB administrative parameter to modify\n attribute :param\n validates :param, presence: true, type: String\n\n # @return [Integer] MongoDB administrative parameter value to set\n attribute :value\n validates :value, presence: true, type: Integer\n\n # @return [String, nil] Define the parameter value (str, int)\n attribute :param_type\n validates :param_type, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6603134274482727, "alphanum_fraction": 0.6649724841117859, "avg_line_length": 47.18367385864258, "blob_id": "95d5cae9300e2e00af9d99877381260a8bd1ccd7", "content_id": "c5542560e81a00c67c04cc585c05b0fc3148988b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2361, "license_type": "permissive", "max_line_length": 197, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/s3_bucket.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage S3 buckets in AWS, Ceph, Walrus and FakeS3\n class S3_bucket < Base\n # @return [:yes, :no, nil] When trying to delete a bucket, delete all keys (including versions and delete markers) in the bucket first (an s3 bucket must be empty for a successful deletion)\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String] Name of the s3 bucket\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The JSON policy as a string.\n attribute :policy\n validates :policy, type: String\n\n # @return [String, nil] S3 URL endpoint for usage with Ceph, Eucalypus, fakes3, etc. Otherwise assumes AWS\n attribute :s3_url\n validates :s3_url, type: String\n\n # @return [Boolean, nil] Enable API compatibility with Ceph. It takes into account the S3 API subset working with Ceph in order to provide the same module behaviour where possible.\n attribute :ceph\n validates :ceph, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:yes, :no, nil] With Requester Pays buckets, the requester instead of the bucket owner pays the cost of the request and the data download from the bucket.\n attribute :requester_pays\n validates :requester_pays, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Create or remove the s3 bucket\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Hash, nil] tags dict to apply to bucket\n attribute :tags\n validates :tags, type: Hash\n\n # @return [Symbol, nil] Whether versioning is enabled or disabled (note that once versioning is enabled, it can only be suspended)\n attribute :versioning\n validates :versioning, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6767207980155945, "alphanum_fraction": 0.6767207980155945, "avg_line_length": 43.58620834350586, "blob_id": "d683407ac473d394f79a9d4e8727522a2fe0d607", "content_id": "cb63aef3e6719ef73ff7f330a8268f3c6d70a863", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1293, "license_type": "permissive", "max_line_length": 175, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/system/getent.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Runs getent against one of it's various databases and returns information into the host's facts, in a getent_<database> prefixed variable.\n class Getent < Base\n # @return [String] The name of a getent database supported by the target system (passwd, group, hosts, etc).\n attribute :database\n validates :database, presence: true, type: String\n\n # @return [String, nil] Key from which to return values from the specified database, otherwise the full contents are returned.\n attribute :key\n validates :key, type: String\n\n # @return [String, nil] Character used to split the database values into lists/arrays such as ':' or '\t', otherwise it will try to pick one depending on the database.\n attribute :split\n validates :split, type: String\n\n # @return [:yes, :no, nil] If a supplied key is missing this will make the task fail if C(yes).\n attribute :fail_key\n validates :fail_key, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6619552373886108, "alphanum_fraction": 0.6619552373886108, "avg_line_length": 34.375, "blob_id": "1fee0f9cc3422fd40a1d7f2b301e0ed94a3ae764", "content_id": "40a7ba0ebe240a30d98cd338ad9d5a293bc58762", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 849, "license_type": "permissive", "max_line_length": 161, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/packaging/language/pear.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage PHP packages with the pear package manager.\n class Pear < Base\n # @return [Array<String>, String] Name of the package to install, upgrade, or remove.\n attribute :name\n validates :name, presence: true, type: TypeGeneric.new(String)\n\n # @return [:present, :absent, :latest, nil] Desired state of the package.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :latest], :message=>\"%{value} needs to be :present, :absent, :latest\"}, allow_nil: true\n\n # @return [Object, nil] Path to the pear executable\n attribute :executable\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6591892838478088, "alphanum_fraction": 0.6635183095932007, "avg_line_length": 46.05555725097656, "blob_id": "bed4fa0b23bbb6ad03c6396f1fb5bb10faeb12c3", "content_id": "8a3dfdc1066d51474a68519b9d6e4dde3eebc638", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2541, "license_type": "permissive", "max_line_length": 172, "num_lines": 54, "path": "/lib/ansible/ruby/modules/generated/monitoring/spectrum_device.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows you to create and delete devices in CA Spectrum U(https://www.ca.com/us/products/ca-spectrum.html).\n # Tested on CA Spectrum 9.4.2, 10.1.1 and 10.2.1\n class Spectrum_device < Base\n # @return [String] IP address of the device.,If a hostname is given, it will be resolved to the IP address.\n attribute :device\n validates :device, presence: true, type: String\n\n # @return [String, nil] SNMP community used for device discovery.,Required when C(state=present).\n attribute :community\n validates :community, type: String\n\n # @return [String] Landscape handle of the SpectroServer to which add or remove the device.\n attribute :landscape\n validates :landscape, presence: true, type: String\n\n # @return [:present, :absent, nil] On C(present) creates the device when it does not exist.,On C(absent) removes the device when it exists.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object] HTTP, HTTPS URL of the Oneclick server in the form (http|https)://host.domain[:port]\n attribute :url\n validates :url, presence: true\n\n # @return [Object] Oneclick user name.\n attribute :url_username\n validates :url_username, presence: true\n\n # @return [Object] Oneclick user password.\n attribute :url_password\n validates :url_password, presence: true\n\n # @return [:yes, :no, nil] if C(no), it will not use a proxy, even if one is defined in an environment variable on the target hosts.\n attribute :use_proxy\n validates :use_proxy, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] UDP port used for SNMP discovery.\n attribute :agentport\n validates :agentport, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6588124632835388, "alphanum_fraction": 0.6616399884223938, "avg_line_length": 35.58620834350586, "blob_id": "ea2369966b4848839cd8cb7770101b46e9aa18e6", "content_id": "3a7d72b58ee76d269c21aee67f403b33250eaffc", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1061, "license_type": "permissive", "max_line_length": 143, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/memset/memset_zone_domain.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage DNS zone domains in a Memset account.\n class Memset_zone_domain < Base\n # @return [:absent, :present, nil] Indicates desired state of resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String] The API key obtained from the Memset control panel.\n attribute :api_key\n validates :api_key, presence: true, type: String\n\n # @return [String] The zone domain name. Ensure this value has at most 250 characters.\n attribute :domain\n validates :domain, presence: true, type: String\n\n # @return [String] The zone to add the domain to (this must already exist).\n attribute :zone\n validates :zone, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.4927745759487152, "alphanum_fraction": 0.5067437291145325, "avg_line_length": 21.813186645507812, "blob_id": "3511914e1b17df4af464659b765797c3fd39c979", "content_id": "3e7a86bca33fab6fb44a127673509e9a2c933e25", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2076, "license_type": "permissive", "max_line_length": 108, "num_lines": 91, "path": "/lib/ansible/ruby/models/tasks_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'spec_helper'\nrequire 'ansible-ruby'\n\ndescribe Ansible::Ruby::Models::Tasks do\n before do\n stub_const('Ansible::Ruby::Modules::Ec2', module_klass)\n end\n\n let(:module_klass) do\n Class.new(Ansible::Ruby::Modules::Base) do\n attribute :foo\n validates :foo, presence: true\n end\n end\n\n let(:task1) do\n Ansible::Ruby::Models::Task.new name: 'do stuff on EC2',\n module: module_klass.new(foo: 123)\n end\n\n let(:task2) do\n Ansible::Ruby::Models::Task.new name: 'do more stuff on EC2',\n module: module_klass.new(foo: 456)\n end\n\n subject(:hash) { instance.to_h }\n\n context 'basic' do\n let(:instance) do\n Ansible::Ruby::Models::Tasks.new items: [task1, task2]\n end\n\n it do\n is_expected.to eq [\n {\n name: 'do stuff on EC2',\n ec2: {\n foo: 123\n }\n },\n {\n name: 'do more stuff on EC2',\n ec2: {\n foo: 456\n }\n }\n ]\n end\n end\n\n context 'inclusions' do\n let(:instance) do\n Ansible::Ruby::Models::Tasks.new items: [task1],\n inclusions: [Ansible::Ruby::Models::Inclusion.new(file: 'stuff.yml')]\n end\n\n it do\n is_expected.to eq [{\n include: 'stuff.yml'\n },\n {\n name: 'do stuff on EC2',\n ec2: {\n foo: 123\n }\n }]\n end\n end\n\n context 'no tasks' do\n let(:instance) do\n Ansible::Ruby::Models::Tasks.new\n end\n\n it 'should raise an error' do\n expect {instance.to_h}.to raise_error \"Validation failed: Items can't be blank\"\n end\n end\n\n context 'empty tasks' do\n let(:instance) do\n Ansible::Ruby::Models::Tasks.new items: []\n end\n\n it 'should raise an error' do\n expect {instance.to_h}.to raise_error \"Validation failed: Items can't be blank\"\n end\n end\nend\n" }, { "alpha_fraction": 0.6719608902931213, "alphanum_fraction": 0.6725717782974243, "avg_line_length": 44.47222137451172, "blob_id": "42f15590aaed5b22e3427b10ea1c101c3fb89595", "content_id": "75f2f1529fa9fc42f27733ba95dc2a06960e74ca", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1637, "license_type": "permissive", "max_line_length": 158, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/windows/win_unzip.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Unzips compressed files and archives.\n # Supports .zip files natively.\n # Supports other formats supported by the Powershell Community Extensions (PSCX) module (basically everything 7zip supports).\n # For non-Windows targets, use the M(unarchive) module instead.\n class Win_unzip < Base\n # @return [String] File to be unzipped (provide absolute path).\n attribute :src\n validates :src, presence: true, type: String\n\n # @return [String] Destination of zip file (provide absolute path of directory). If it does not exist, the directory will be created.\n attribute :dest\n validates :dest, presence: true, type: String\n\n # @return [:yes, :no, nil] Remove the zip file, after unzipping.\n attribute :delete_archive\n validates :delete_archive, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Recursively expand zipped files within the src file.,Setting to a value of C(yes) requires the PSCX module to be installed.\n attribute :recurse\n validates :recurse, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] If this file or directory exists the specified src will not be extracted.\n attribute :creates\n validates :creates, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6475609540939331, "alphanum_fraction": 0.6475609540939331, "avg_line_length": 39, "blob_id": "8b844b23565eb6cd191268b8ca447d1245022148", "content_id": "8e433b27631cf1e1d4fcda385cc665bc4c92e7fc", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1640, "license_type": "permissive", "max_line_length": 161, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/packaging/language/bower.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage bower packages with bower\n class Bower < Base\n # @return [String, nil] The name of a bower package to install\n attribute :name\n validates :name, type: String\n\n # @return [:yes, :no, nil] Install packages from local cache, if the packages were installed before\n attribute :offline\n validates :offline, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Install with --production flag\n attribute :production\n validates :production, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String] The base path where to install the bower packages\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [String, nil] Relative path to bower executable from install path\n attribute :relative_execpath\n validates :relative_execpath, type: String\n\n # @return [:present, :absent, :latest, nil] The state of the bower package\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :latest], :message=>\"%{value} needs to be :present, :absent, :latest\"}, allow_nil: true\n\n # @return [String, nil] The version to be installed\n attribute :version\n validates :version, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6639254093170166, "alphanum_fraction": 0.6639254093170166, "avg_line_length": 43.4878044128418, "blob_id": "24610cff06a71c27a86fbc01a66a7c4353b95457", "content_id": "7750d92c54fc010a89da4b8f915a67e2615919f8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1824, "license_type": "permissive", "max_line_length": 143, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/storage/purestorage/purefa_pg.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, delete or modify protection groups on Pure Storage FlashArrays.\n class Purefa_pg < Base\n # @return [String] The name of the protection group.\n attribute :pgroup\n validates :pgroup, presence: true, type: String\n\n # @return [:absent, :present, nil] Define whether the protection group should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] List of existing volumes to add to protection group.\n attribute :volume\n validates :volume, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] List of existing hosts to add to protection group.\n attribute :host\n validates :host, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] List of existing hostgroups to add to protection group.\n attribute :hostgroup\n validates :hostgroup, type: TypeGeneric.new(String)\n\n # @return [:yes, :no, nil] Define whether to eradicate the protection group on delete and leave in trash.\n attribute :eradicate\n validates :eradicate, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Define whether to enabled snapshots for the protection group.\n attribute :enabled\n validates :enabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6646153926849365, "alphanum_fraction": 0.6646153926849365, "avg_line_length": 38.79591751098633, "blob_id": "d0cca1df3f6351e561fd2e70ce51beedc98bc9b1", "content_id": "f36124d45e166b636c0dd141eca523a8eee4b489", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1950, "license_type": "permissive", "max_line_length": 246, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/notification/snow_record.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates/Deletes/Updates a single record in ServiceNow\n class Snow_record < Base\n # @return [String] The service now instance name\n attribute :instance\n validates :instance, presence: true, type: String\n\n # @return [String] User to connect to ServiceNow as\n attribute :username\n validates :username, presence: true, type: String\n\n # @return [String] Password for username\n attribute :password\n validates :password, presence: true, type: String\n\n # @return [String, nil] Table to query for records\n attribute :table\n validates :table, type: String\n\n # @return [:present, :absent] If C(present) is supplied with a C(number) argument, the module will attempt to update the record with the supplied data. If no such record exists, a new one will be created. C(absent) will delete a record.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [Hash, nil] key, value pairs of data to load into the record. See Examples. Required for C(state:present)\n attribute :data\n validates :data, type: Hash\n\n # @return [String, Integer, nil] Record number to update. Required for C(state:absent)\n attribute :number\n validates :number, type: MultipleTypes.new(String, Integer)\n\n # @return [String, nil] Changes the field that C(number) uses to find records\n attribute :lookup_field\n validates :lookup_field, type: String\n\n # @return [String, nil] Attach a file to the record\n attribute :attachment\n validates :attachment, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7164322137832642, "alphanum_fraction": 0.7186700701713562, "avg_line_length": 64.16666412353516, "blob_id": "5623827bb81223cc7a4d247f50993a0e99d04d91", "content_id": "a148edfc5496c58d56af3e2f098cbb1f8c122297", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3128, "license_type": "permissive", "max_line_length": 295, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_asg_lifecycle_hook.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # When no given Hook found, will create one.\n # In case Hook found, but provided parameters are differes, will update existing Hook.\n # In case state=absent and Hook exists, will delete it.\n class Ec2_asg_lifecycle_hook < Base\n # @return [:present, :absent, nil] Create or delete Lifecycle Hook. Present updates existing one or creates if not found.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The name of the lifecycle hook.\n attribute :lifecycle_hook_name\n validates :lifecycle_hook_name, presence: true, type: String\n\n # @return [String] The name of the Auto Scaling group to which you want to assign the lifecycle hook.\n attribute :autoscaling_group_name\n validates :autoscaling_group_name, presence: true, type: String\n\n # @return [:\"autoscaling:EC2_INSTANCE_TERMINATING\", :\"autoscaling:EC2_INSTANCE_LAUNCHING\"] The instance state to which you want to attach the lifecycle hook.\n attribute :transition\n validates :transition, presence: true, expression_inclusion: {:in=>[:\"autoscaling:EC2_INSTANCE_TERMINATING\", :\"autoscaling:EC2_INSTANCE_LAUNCHING\"], :message=>\"%{value} needs to be :\\\"autoscaling:EC2_INSTANCE_TERMINATING\\\", :\\\"autoscaling:EC2_INSTANCE_LAUNCHING\\\"\"}\n\n # @return [Object, nil] The ARN of the IAM role that allows the Auto Scaling group to publish to the specified notification target.\n attribute :role_arn\n\n # @return [Object, nil] The ARN of the notification target that Auto Scaling will use to notify you when an instance is in the transition state for the lifecycle hook. This target can be either an SQS queue or an SNS topic. If you specify an empty string, this overrides the current ARN.\n attribute :notification_target_arn\n\n # @return [Object, nil] Contains additional information that you want to include any time Auto Scaling sends a message to the notification target.\n attribute :notification_meta_data\n\n # @return [String, nil] The amount of time, in seconds, that can elapse before the lifecycle hook times out. When the lifecycle hook times out, Auto Scaling performs the default action. You can prevent the lifecycle hook from timing out by calling RecordLifecycleActionHeartbeat.\n attribute :heartbeat_timeout\n validates :heartbeat_timeout, type: String\n\n # @return [:ABANDON, :CONTINUE, nil] Defines the action the Auto Scaling group should take when the lifecycle hook timeout elapses or if an unexpected failure occurs. This parameter can be either CONTINUE or ABANDON.\n attribute :default_result\n validates :default_result, expression_inclusion: {:in=>[:ABANDON, :CONTINUE], :message=>\"%{value} needs to be :ABANDON, :CONTINUE\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7011632323265076, "alphanum_fraction": 0.7011632323265076, "avg_line_length": 70.22856903076172, "blob_id": "c781c5b6be7de06ffe2ce32eac31cdde4faf4264", "content_id": "0e0c14b05e1eb8b50cba6bdb1336ca1853948475", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2493, "license_type": "permissive", "max_line_length": 611, "num_lines": 35, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_host_powerstate.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to manage power states of host systems in given vCenter infrastructure.\n # User can set power state to 'power-down-to-standby', 'power-up-from-standby', 'shutdown-host' and 'reboot-host'.\n # State 'reboot-host', 'shutdown-host' and 'power-down-to-standby' are not supported by all the host systems.\n class Vmware_host_powerstate < Base\n # @return [:\"power-down-to-standby\", :\"power-up-from-standby\", :\"shutdown-host\", :\"reboot-host\", nil] Set the state of the host system.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:\"power-down-to-standby\", :\"power-up-from-standby\", :\"shutdown-host\", :\"reboot-host\"], :message=>\"%{value} needs to be :\\\"power-down-to-standby\\\", :\\\"power-up-from-standby\\\", :\\\"shutdown-host\\\", :\\\"reboot-host\\\"\"}, allow_nil: true\n\n # @return [String, nil] Name of the host system to work with.,This is required parameter if C(cluster_name) is not specified.\n attribute :esxi_hostname\n validates :esxi_hostname, type: String\n\n # @return [String, nil] Name of the cluster from which all host systems will be used.,This is required parameter if C(esxi_hostname) is not specified.\n attribute :cluster_name\n validates :cluster_name, type: String\n\n # @return [Symbol, nil] This parameter specify if the host should be proceeding with user defined powerstate regardless of whether it is in maintenance mode.,If C(state) set to C(reboot-host) and C(force) as C(true), then host system is rebooted regardless of whether it is in maintenance mode.,If C(state) set to C(shutdown-host) and C(force) as C(true), then host system is shutdown regardless of whether it is in maintenance mode.,If C(state) set to C(power-down-to-standby) and C(force) to C(true), then all powered off VMs will evacuated.,Not applicable if C(state) set to C(power-up-from-standby).\n attribute :force\n validates :force, type: Symbol\n\n # @return [Integer, nil] This parameter defines timeout for C(state) set to C(power-down-to-standby) or C(power-up-from-standby).,Ignored if C(state) set to C(reboot-host) or C(shutdown-host).,This parameter is defined in seconds.\n attribute :timeout\n validates :timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.681846559047699, "alphanum_fraction": 0.6837180256843567, "avg_line_length": 52.43333435058594, "blob_id": "5d423eb5090e9717649f6543f6ffb92b3bb7e8f2", "content_id": "664ae2e76e54adde9cd2ee542f9198a8b0204100", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3206, "license_type": "permissive", "max_line_length": 405, "num_lines": 60, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/jenkins_plugin.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Ansible module which helps to manage Jenkins plugins.\n class Jenkins_plugin < Base\n # @return [String, nil] Name of the Jenkins group on the OS.\n attribute :group\n validates :group, type: String\n\n # @return [String, nil] Home directory of the Jenkins user.\n attribute :jenkins_home\n validates :jenkins_home, type: String\n\n # @return [Object, nil] File mode applied on versioned plugins.\n attribute :mode\n\n # @return [String, nil] Plugin name.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] Name of the Jenkins user on the OS.\n attribute :owner\n validates :owner, type: String\n\n # @return [:absent, :present, :pinned, :unpinned, :enabled, :disabled, :latest, nil] Desired plugin state.,If the C(latest) is set, the check for new version will be performed every time. This is suitable to keep the plugin up-to-date.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :pinned, :unpinned, :enabled, :disabled, :latest], :message=>\"%{value} needs to be :absent, :present, :pinned, :unpinned, :enabled, :disabled, :latest\"}, allow_nil: true\n\n # @return [Integer, nil] Server connection timeout in secs.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [Integer, nil] Number of seconds after which a new copy of the I(update-center.json) file is downloaded. This is used to avoid the need to download the plugin to calculate its checksum when C(latest) is specified.,Set it to C(0) if no cache file should be used. In that case, the plugin file will always be downloaded to calculate its checksum when C(latest) is specified.\n attribute :updates_expiration\n validates :updates_expiration, type: Integer\n\n # @return [String, nil] URL of the Update Centre.,Used as the base URL to download the plugins and the I(update-center.json) JSON file.\n attribute :updates_url\n validates :updates_url, type: String\n\n # @return [String, nil] URL of the Jenkins server.\n attribute :url\n validates :url, type: String\n\n # @return [String, nil] Plugin version number.,If this option is specified, all plugin dependencies must be installed manually.,It might take longer to verify that the correct version is installed. This is especially true if a specific version number is specified.,Quote the version to prevent the value to be interpreted as float. For example if C(1.20) would be unquoted, it would become C(1.2).\n attribute :version\n validates :version, type: String\n\n # @return [:yes, :no, nil] Defines whether to install plugin dependencies.,This option takes effect only if the I(version) is not defined.\n attribute :with_dependencies\n validates :with_dependencies, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.41590264439582825, "alphanum_fraction": 0.4312385320663452, "avg_line_length": 30.740739822387695, "blob_id": "885b66c63d65a631e8ccb6298e23481aea7308ad", "content_id": "5eba66d4f97eca7b7c6d811cbe091238d6175df6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5999, "license_type": "permissive", "max_line_length": 111, "num_lines": 189, "path": "/lib/ansible/ruby/models/task_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'spec_helper'\nrequire 'ansible-ruby'\n\ndescribe Ansible::Ruby::Models::Task do\n before do\n stub_const('Ansible::Ruby::Modules::Ec2', module_klass)\n end\n\n let(:module_klass) do\n Class.new(Ansible::Ruby::Modules::Base) do\n attribute :foo\n validates :foo, presence: true\n attribute :bar\n end\n end\n\n subject(:hash) { instance.to_h }\n\n context 'basic' do\n let(:instance) do\n Ansible::Ruby::Models::Task.new name: 'do stuff on EC2',\n module: module_klass.new(foo: 123)\n end\n\n it do\n is_expected.to eq(name: 'do stuff on EC2',\n ec2: {\n foo: 123\n })\n end\n end\n\n context 'attributes' do\n let(:instance) do\n Ansible::Ruby::Models::Task.new name: 'do stuff on EC2',\n become: true,\n become_user: 'root',\n module: module_klass.new(foo: 123),\n notify: %w[handler1 handler2]\n end\n\n it do\n is_expected.to eq(name: 'do stuff on EC2',\n ec2: {\n foo: 123\n },\n become: true,\n become_user: 'root',\n notify: %w[handler1 handler2])\n end\n\n describe 'key order' do\n subject { hash.stringify_keys.keys }\n\n it { is_expected.to eq %w[name ec2 become become_user notify] }\n end\n end\n\n context 'block w/ rescue and always' do\n let(:instance) do\n block_tasks = [\n Ansible::Ruby::Models::Task.new(name: 'do stuff inside block',\n module: module_klass.new(foo: 123))\n ]\n rescue_tasks = [\n Ansible::Ruby::Models::Task.new(name: 'do stuff inside rescue',\n module: module_klass.new(foo: 456))\n ]\n always_tasks = [\n Ansible::Ruby::Models::Task.new(name: 'do stuff inside always',\n module: module_klass.new(foo: 456))\n ]\n Ansible::Ruby::Models::Task.new name: 'do stuff on EC2',\n block: Ansible::Ruby::Models::Block.new(tasks: block_tasks),\n rescue: Ansible::Ruby::Models::Block.new(tasks: rescue_tasks),\n always: Ansible::Ruby::Models::Block.new(tasks: always_tasks)\n end\n\n it do\n is_expected.to eq(name: 'do stuff on EC2',\n block: [\n name: 'do stuff inside block',\n ec2: {\n foo: 123\n }\n ],\n rescue: [\n name: 'do stuff inside rescue',\n ec2: {\n foo: 456\n }\n ],\n always: [\n name: 'do stuff inside always',\n ec2: {\n foo: 456\n }\n ])\n end\n end\n\n context 'local action' do\n let(:instance) do\n Ansible::Ruby::Models::Task.new name: 'do stuff on EC2',\n module: module_klass.new(foo: 123),\n local_action: true\n end\n\n it do\n is_expected.to eq(name: 'do stuff on EC2',\n local_action: {\n module: 'ec2',\n foo: 123\n })\n end\n end\n\n context 'single notify' do\n let(:instance) do\n Ansible::Ruby::Models::Task.new name: 'do stuff on EC2',\n module: module_klass.new(foo: 123),\n notify: 'handler1'\n end\n\n it do\n is_expected.to eq(name: 'do stuff on EC2',\n ec2: {\n foo: 123\n },\n notify: %w[handler1])\n end\n end\n\n context 'dict and items' do\n subject do\n Ansible::Ruby::Models::Task.new name: 'do stuff on EC2',\n module: module_klass.new(foo: 123),\n with_items: 'foo',\n with_dict: 'foo'\n end\n\n it { is_expected.to_not be_valid }\n it { is_expected.to have_errors with_items: 'Cannot use both with_items and with_dict!' }\n end\n\n context 'inclusion only' do\n let(:instance) do\n Ansible::Ruby::Models::Task.new name: 'do stuff on EC2',\n inclusion: Ansible::Ruby::Models::Inclusion.new(file: 'something.yml')\n end\n\n it do\n is_expected.to eq(name: 'do stuff on EC2',\n include: 'something.yml')\n end\n end\n\n context 'inclusion and module' do\n let(:instance) do\n Ansible::Ruby::Models::Task.new name: 'do stuff on EC2',\n inclusion: Ansible::Ruby::Models::Inclusion.new(file: 'something.yml'),\n module: module_klass.new(foo: 123)\n end\n\n it 'should raise an error' do\n expect {instance.to_h}.to raise_error %r{You must either use an include or a module/block but not both.*}\n end\n end\n\n context 'vars' do\n let(:instance) do\n Ansible::Ruby::Models::Task.new name: 'do stuff on EC2',\n module: module_klass.new(foo: 123),\n vars: { howdy: 123 }\n end\n\n it do\n is_expected.to eq(name: 'do stuff on EC2',\n ec2: {\n foo: 123\n },\n vars: {\n howdy: 123\n })\n end\n end\nend\n" }, { "alpha_fraction": 0.6947429776191711, "alphanum_fraction": 0.7008422613143921, "avg_line_length": 69.26530456542969, "blob_id": "a837a289cff315c1426ce948e8d6113d281e6129", "content_id": "25c05e560f31861e0af1fa720796c8fb894611cc", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3443, "license_type": "permissive", "max_line_length": 563, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_host.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to add / remove / reconnect an ESXi host to / from vCenter.\n class Vmware_host < Base\n # @return [String] Name of the datacenter to add the host.,Aliases added in version 2.6.\n attribute :datacenter_name\n validates :datacenter_name, presence: true, type: String\n\n # @return [String, nil] Name of the cluster to add the host.,If C(folder) is not set, then this parameter is required.,Aliases added in version 2.6.\n attribute :cluster_name\n validates :cluster_name, type: String\n\n # @return [String, nil] Name of the folder under which host to add.,If C(cluster_name) is not set, then this parameter is required.,For example, if there is a datacenter 'dc1' under folder called 'Site1' then, this value will be '/Site1/dc1/host'.,Here 'host' is an invisible folder under VMware Web Client.,Another example, if there is a nested folder structure like '/myhosts/india/pune' under datacenter 'dc2', then C(folder) value will be '/dc2/host/myhosts/india/pune'.,Other Examples: , - '/Site2/dc2/Asia-Cluster/host', - '/dc3/Asia-Cluster/host'\n attribute :folder\n validates :folder, type: String\n\n # @return [Boolean, nil] If set to C(True), then the host should be connected as soon as it is added.,This parameter is ignored if state is set to a value other than C(present).\n attribute :add_connected\n validates :add_connected, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String] ESXi hostname to manage.\n attribute :esxi_hostname\n validates :esxi_hostname, presence: true, type: String\n\n # @return [String, nil] ESXi username.,Required for adding a host.,Optional for reconnect.,Unused for removing.,No longer a required parameter from version 2.5.\n attribute :esxi_username\n validates :esxi_username, type: String\n\n # @return [String, nil] ESXi password.,Required for adding a host.,Optional for reconnect.,Unused for removing.,No longer a required parameter from version 2.5.\n attribute :esxi_password\n validates :esxi_password, type: String\n\n # @return [:present, :absent, :add_or_reconnect, :reconnect, nil] If set to C(present), then add the host if host is absent.,If set to C(present), then do nothing if host already exists.,If set to C(absent), then remove the host if host is present.,If set to C(absent), then do nothing if host already does not exists.,If set to C(add_or_reconnect), then add the host if it's absent else reconnect it.,If set to C(reconnect), then reconnect the host if it's present else fail.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :add_or_reconnect, :reconnect], :message=>\"%{value} needs to be :present, :absent, :add_or_reconnect, :reconnect\"}, allow_nil: true\n\n # @return [String, nil] Specifying the hostsystem certificate's thumbprint.,Use following command to get hostsystem certificate's thumbprint - ,# openssl x509 -in /etc/vmware/ssl/rui.crt -fingerprint -sha1 -noout\n attribute :esxi_ssl_thumbprint\n validates :esxi_ssl_thumbprint, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 15.875, "blob_id": "c6f603b8f04f7cf0ca2954fe30532055a572f1b3", "content_id": "cd95b44757cd63ffe42748ac46c34e2593de71b0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 270, "license_type": "permissive", "max_line_length": 39, "num_lines": 16, "path": "/lib/ansible/ruby/models/handler.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# see LICENSE.txt in project root\n\nrequire 'ansible/ruby/models/task'\n\nmodule Ansible\n module Ruby\n module Models\n class Handler < Task\n attribute :listen\n validates :listen, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6830249428749084, "alphanum_fraction": 0.6838294267654419, "avg_line_length": 53.043479919433594, "blob_id": "4ce0c260f0589f83569e34f2236188db90dc8e25", "content_id": "0671f5a6e55a3aa089aec063ee8f9edc6a18a684", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2486, "license_type": "permissive", "max_line_length": 437, "num_lines": 46, "path": "/lib/ansible/ruby/modules/generated/utilities/logic/include_role.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Loads and executes a role as a task dynamically. This frees roles from the `roles:` directive and allows them to be treated more as tasks.\n # Unlike M(import_role), most keywords, including loops and conditionals, apply to this statement.\n # This module is also supported for Windows targets.\n class Include_role < Base\n # @return [Hash, nil] Accepts a hash of task keywords (e.g. C(tags), C(become)) that will be applied to the tasks within the include.\n attribute :apply\n validates :apply, type: Hash\n\n # @return [String] The name of the role to be executed.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] File to load from a role's C(tasks/) directory.\n attribute :tasks_from\n validates :tasks_from, type: String\n\n # @return [String, nil] File to load from a role's C(vars/) directory.\n attribute :vars_from\n validates :vars_from, type: String\n\n # @return [String, nil] File to load from a role's C(defaults/) directory.\n attribute :defaults_from\n validates :defaults_from, type: String\n\n # @return [:yes, :no, nil] Overrides the role's metadata setting to allow using a role more than once with the same parameters.\n attribute :allow_duplicates\n validates :allow_duplicates, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] This option is a no op, and the functionality described in previous versions was not implemented. This option will be removed in Ansible v2.8.\n attribute :private\n\n # @return [:yes, :no, nil] This option dictates whether the role's C(vars) and C(defaults) are exposed to the playbook. If set to C(yes) the variables will be available to tasks following the C(include_role) task. This functionality differs from standard variable exposure for roles listed under the C(roles) header or C(import_role) as they are exposed at playbook parsing time, and available to earlier roles and tasks as well.\n attribute :public\n validates :public, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.658169150352478, "alphanum_fraction": 0.658169150352478, "avg_line_length": 21.710525512695312, "blob_id": "1fdf26a27e01130db27858a80d42d2269402aa59", "content_id": "6b0af526e7c7be274359e821b526740c8b69056c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 863, "license_type": "permissive", "max_line_length": 95, "num_lines": 38, "path": "/spec/support/contexts/rake.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'spec_helper'\nrequire 'ansible/ruby/rake/compile'\n\nRSpec.shared_context :rake_testing do\n before do\n Rake::Task.clear\n task = Ansible::Ruby::Rake::Compile\n instance_var = :'@rule_done'\n task.remove_instance_variable(instance_var) if task.instance_variable_defined? instance_var\n end\n\n let(:rake_dir) { 'spec/rake/no_nested_tasks' }\n\n around do |example|\n Dir.chdir rake_dir do\n clean = Dir.glob('**/*.yml')\n puts \"Cleaning up #{clean} before test\"\n FileUtils.rm_rf clean\n example.run\n end\n end\nend\n\nRSpec.shared_context :rake_invoke do\n before { execute_task }\n\n subject(:rake_result) { {} }\n\n def execute_task\n commands = rake_result[:commands] = []\n allow(task).to receive(:sh) do |command, _|\n commands << command\n end\n Rake::Task[:default].invoke\n end\nend\n" }, { "alpha_fraction": 0.6576659083366394, "alphanum_fraction": 0.6599542498588562, "avg_line_length": 38.727272033691406, "blob_id": "71c52d1929b64de6fe46cb2f0398434bc768a094", "content_id": "22fb805c919b8ef0f6365001c38d437d83f2259d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2185, "license_type": "permissive", "max_line_length": 137, "num_lines": 55, "path": "/lib/ansible/ruby/modules/generated/notification/sendgrid.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Sends an email with a SendGrid account through their API, not through the SMTP service.\n class Sendgrid < Base\n # @return [String, nil] username for logging into the SendGrid account.,Since 2.2 it is only required if api_key is not supplied.\n attribute :username\n validates :username, type: String\n\n # @return [String, nil] password that corresponds to the username,Since 2.2 it is only required if api_key is not supplied.\n attribute :password\n validates :password, type: String\n\n # @return [String] the address in the \"from\" field for the email\n attribute :from_address\n validates :from_address, presence: true, type: String\n\n # @return [Array<String>, String] a list with one or more recipient email addresses\n attribute :to_addresses\n validates :to_addresses, presence: true, type: TypeGeneric.new(String)\n\n # @return [String] the desired subject for the email\n attribute :subject\n validates :subject, presence: true, type: String\n\n # @return [Object, nil] sendgrid API key to use instead of username/password\n attribute :api_key\n\n # @return [Object, nil] a list of email addresses to cc\n attribute :cc\n\n # @return [Object, nil] a list of email addresses to bcc\n attribute :bcc\n\n # @return [Object, nil] a list of relative or explicit paths of files you want to attach (7MB limit as per SendGrid docs)\n attribute :attachments\n\n # @return [Object, nil] the name you want to appear in the from field, i.e 'John Doe'\n attribute :from_name\n\n # @return [:yes, :no, nil] whether the body is html content that should be rendered\n attribute :html_body\n validates :html_body, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] a dict to pass on as headers\n attribute :headers\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6959553956985474, "alphanum_fraction": 0.6959553956985474, "avg_line_length": 33.14285659790039, "blob_id": "f6ee7381642952d6c8c3431e9f0f08446c98b18f", "content_id": "405ba40b4715793898b6aff1b4e3e14249c5b591", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 717, "license_type": "permissive", "max_line_length": 135, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/network/fortios/fortios_config.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides management of FortiOS Devices configuration.\n class Fortios_config < Base\n # @return [String, nil] The I(src) argument provides a path to the configuration template to load into the remote device.\n attribute :src\n validates :src, type: String\n\n # @return [String, nil] Only for partial backup, you can restrict by giving expected configuration path (ex. firewall address).\n attribute :filter\n validates :filter, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.676086962223053, "alphanum_fraction": 0.676086962223053, "avg_line_length": 26.058822631835938, "blob_id": "19744a1208b278bfd42ce1e120ece0564992af46", "content_id": "f12917a99c1869816613c0e20429f87051ad29b1", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 460, "license_type": "permissive", "max_line_length": 85, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_disks.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Assign all or part of disks to nodes.\n class Na_ontap_disks < Base\n # @return [String] It specifies the node to assign all visible unowned disks.\n attribute :node\n validates :node, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6605298519134521, "alphanum_fraction": 0.6627750396728516, "avg_line_length": 42.66666793823242, "blob_id": "e4c1e705ae77697e12048e94d11b749aed6d53cc", "content_id": "425fc2150748e17a527f1074d928e6afe5615dc7", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2227, "license_type": "permissive", "max_line_length": 315, "num_lines": 51, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_host_pm.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Module to manage power management of hosts in oVirt/RHV.\n class Ovirt_host_pm < Base\n # @return [String] Name of the host to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Should the host be present/absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Address of the power management interface.\n attribute :address\n validates :address, type: String\n\n # @return [String, nil] Username to be used to connect to power management interface.\n attribute :username\n validates :username, type: String\n\n # @return [String, nil] Password of the user specified in C(username) parameter.\n attribute :password\n validates :password, type: String\n\n # @return [String, nil] Type of the power management. oVirt/RHV predefined values are I(drac5), I(ipmilan), I(rsa), I(bladecenter), I(alom), I(apc), I(apc_snmp), I(eps), I(wti), I(rsb), I(cisco_ucs), I(drac7), I(hpblade), I(ilo), I(ilo2), I(ilo3), I(ilo4), I(ilo_ssh), but user can have defined custom type.\n attribute :type\n validates :type, type: String\n\n # @return [Integer, nil] Power management interface port.\n attribute :port\n validates :port, type: Integer\n\n # @return [Hash, nil] Dictionary of additional fence agent options (including Power Management slot).,Additional information about options can be found at U(https://github.com/ClusterLabs/fence-agents/blob/master/doc/FenceAgentAPI.md).\n attribute :options\n validates :options, type: Hash\n\n # @return [Object, nil] If I(true) options will be encrypted when send to agent.\n attribute :encrypt_options\n\n # @return [Object, nil] Integer value specifying, by default it's added at the end.\n attribute :order\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6483350396156311, "alphanum_fraction": 0.6483350396156311, "avg_line_length": 37.11538314819336, "blob_id": "8346d051d7d69fe32a891217bcbd697e2f3beffe", "content_id": "0194df1abe44ee6aa153ad08f553ef761b456262", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1982, "license_type": "permissive", "max_line_length": 142, "num_lines": 52, "path": "/lib/ansible/ruby/modules/generated/net_tools/omapi_host.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and remove OMAPI hosts into compatible DHCPd servers.\n class Omapi_host < Base\n # @return [:present, :absent] Create or remove OMAPI host.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String, nil] Sets the host lease hostname (mandatory if state=present).\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] Sets OMAPI server host to interact with.\n attribute :host\n validates :host, type: String\n\n # @return [Integer, nil] Sets the OMAPI server port to interact with.\n attribute :port\n validates :port, type: Integer\n\n # @return [String] Sets the TSIG key name for authenticating against OMAPI server.\n attribute :key_name\n validates :key_name, presence: true, type: String\n\n # @return [String] Sets the TSIG key content for authenticating against OMAPI server.\n attribute :key\n validates :key, presence: true, type: String\n\n # @return [String] Sets the lease host MAC address.\n attribute :macaddr\n validates :macaddr, presence: true, type: String\n\n # @return [String, nil] Sets the lease host IP address.\n attribute :ip\n validates :ip, type: String\n\n # @return [Object, nil] Attach a list of OMAPI DHCP statements with host lease (without ending semicolon).\n attribute :statements\n\n # @return [:yes, :no, nil] Enable dynamic DNS updates for this host.\n attribute :ddns\n validates :ddns, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6710411310195923, "alphanum_fraction": 0.674832284450531, "avg_line_length": 49.42647171020508, "blob_id": "cf896925af42ea021c25e8ec439d55be7b61d72e", "content_id": "b5685529fe8035444aa056ef283f9bfeff67998b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3429, "license_type": "permissive", "max_line_length": 216, "num_lines": 68, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_snapshot.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create snapshots of the running states of selected features, add new show commands for snapshot creation, delete and compare existing snapshots.\n class Nxos_snapshot < Base\n # @return [:add, :compare, :create, :delete, :delete_all] Define what snapshot action the module would perform.\n attribute :action\n validates :action, presence: true, expression_inclusion: {:in=>[:add, :compare, :create, :delete, :delete_all], :message=>\"%{value} needs to be :add, :compare, :create, :delete, :delete_all\"}\n\n # @return [String, nil] Snapshot name, to be used when C(action=create) or C(action=delete).\n attribute :snapshot_name\n validates :snapshot_name, type: String\n\n # @return [String, nil] Snapshot description to be used when C(action=create).\n attribute :description\n validates :description, type: String\n\n # @return [String, nil] First snapshot to be used when C(action=compare).\n attribute :snapshot1\n validates :snapshot1, type: String\n\n # @return [String, nil] Second snapshot to be used when C(action=compare).\n attribute :snapshot2\n validates :snapshot2, type: String\n\n # @return [String, nil] Name of the file where snapshots comparison will be stored when C(action=compare).\n attribute :comparison_results_file\n validates :comparison_results_file, type: String\n\n # @return [:summary, :ipv4routes, :ipv6routes, nil] Snapshot options to be used when C(action=compare).\n attribute :compare_option\n validates :compare_option, expression_inclusion: {:in=>[:summary, :ipv4routes, :ipv6routes], :message=>\"%{value} needs to be :summary, :ipv4routes, :ipv6routes\"}, allow_nil: true\n\n # @return [String, nil] Used to name the show command output, to be used when C(action=add).\n attribute :section\n validates :section, type: String\n\n # @return [String, nil] Specify a new show command, to be used when C(action=add).\n attribute :show_command\n validates :show_command, type: String\n\n # @return [String, nil] Specifies the tag of each row entry of the show command's XML output, to be used when C(action=add).\n attribute :row_id\n validates :row_id, type: String\n\n # @return [String, nil] Specify the tags used to distinguish among row entries, to be used when C(action=add).\n attribute :element_key1\n validates :element_key1, type: String\n\n # @return [Object, nil] Specify the tags used to distinguish among row entries, to be used when C(action=add).\n attribute :element_key2\n\n # @return [:yes, :no, nil] Specify to locally store a new created snapshot, to be used when C(action=create).\n attribute :save_snapshot_locally\n validates :save_snapshot_locally, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Specify the path of the file where new created snapshot or snapshots comparison will be stored, to be used when C(action=create) and C(save_snapshot_locally=true) or C(action=compare).\n attribute :path\n validates :path, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6669710874557495, "alphanum_fraction": 0.6669710874557495, "avg_line_length": 44, "blob_id": "11ca3bc624d6433cd79868a91460e14ed70bd61e", "content_id": "e4229217bd0b4f46af975987e6caa3337063205b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3285, "license_type": "permissive", "max_line_length": 191, "num_lines": 73, "path": "/lib/ansible/ruby/modules/generated/messaging/rabbitmq_queue.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module uses rabbitMQ Rest API to create/delete queues\n class Rabbitmq_queue < Base\n # @return [String] Name of the queue to create\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Whether the queue should be present or absent,Only present implemented atm\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] rabbitMQ user for connection\n attribute :login_user\n validates :login_user, type: String\n\n # @return [:yes, :no, nil] rabbitMQ password for connection\n attribute :login_password\n validates :login_password, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] rabbitMQ host for connection\n attribute :login_host\n validates :login_host, type: String\n\n # @return [Integer, nil] rabbitMQ management api port\n attribute :login_port\n validates :login_port, type: Integer\n\n # @return [String, nil] rabbitMQ virtual host\n attribute :vhost\n validates :vhost, type: String\n\n # @return [:yes, :no, nil] whether queue is durable or not\n attribute :durable\n validates :durable, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] if the queue should delete itself after all queues/queues unbound from it\n attribute :auto_delete\n validates :auto_delete, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] How long a message can live in queue before it is discarded (milliseconds)\n attribute :message_ttl\n validates :message_ttl, type: String\n\n # @return [String, nil] How long a queue can be unused before it is automatically deleted (milliseconds)\n attribute :auto_expires\n validates :auto_expires, type: String\n\n # @return [String, nil] How many messages can the queue contain before it starts rejecting\n attribute :max_length\n validates :max_length, type: String\n\n # @return [Object, nil] Optional name of an exchange to which messages will be republished if they,are rejected or expire\n attribute :dead_letter_exchange\n\n # @return [Object, nil] Optional replacement routing key to use when a message is dead-lettered.,Original routing key will be used if unset\n attribute :dead_letter_routing_key\n\n # @return [Object, nil] Maximum number of priority levels for the queue to support.,If not set, the queue will not support message priorities.,Larger numbers indicate higher priority.\n attribute :max_priority\n\n # @return [Object, nil] extra arguments for queue. If defined this argument is a key/value dictionary\n attribute :arguments\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6943454146385193, "alphanum_fraction": 0.6943454146385193, "avg_line_length": 43.6136360168457, "blob_id": "7199d320a1712db327d5a2679af275b75acf03e9", "content_id": "4854ffb7cf0ca4c0460ca432b5b76ad8e284c5bb", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1963, "license_type": "permissive", "max_line_length": 178, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_elementsw_cluster.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Initialize Element Software node ownership to form a cluster.\n class Na_elementsw_cluster < Base\n # @return [String] Floating (virtual) IP address for the cluster on the management network.\n attribute :management_virtual_ip\n validates :management_virtual_ip, presence: true, type: String\n\n # @return [String] Floating (virtual) IP address for the cluster on the storage (iSCSI) network.\n attribute :storage_virtual_ip\n validates :storage_virtual_ip, presence: true, type: String\n\n # @return [String, nil] Number of replicas of each piece of data to store in the cluster.\n attribute :replica_count\n validates :replica_count, type: String\n\n # @return [String, nil] Username for the cluster admin.,If not provided, default to login username.\n attribute :cluster_admin_username\n validates :cluster_admin_username, type: String\n\n # @return [String, nil] Initial password for the cluster admin account.,If not provided, default to login password.\n attribute :cluster_admin_password\n validates :cluster_admin_password, type: String\n\n # @return [Symbol, nil] Required to indicate your acceptance of the End User License Agreement when creating this cluster.,To accept the EULA, set this parameter to true.\n attribute :accept_eula\n validates :accept_eula, type: Symbol\n\n # @return [Array<String>, String, nil] Storage IP (SIP) addresses of the initial set of nodes making up the cluster.,nodes IP must be in the list.\n attribute :nodes\n validates :nodes, type: TypeGeneric.new(String)\n\n # @return [Object, nil] List of name-value pairs in JSON object format.\n attribute :attributes\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6997548937797546, "alphanum_fraction": 0.7028186321258545, "avg_line_length": 50, "blob_id": "6f40b8bdb4035e9d1126bebe79a9b648e4b2f778", "content_id": "33771fde25e6a231c6b36ce37146f3d2ed0b57fb", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1632, "license_type": "permissive", "max_line_length": 224, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_ssl_certificate.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module will import/delete SSL certificates on BIG-IP LTM. Certificates can be imported from certificate and key files on the local disk, in PEM format.\n class Bigip_ssl_certificate < Base\n # @return [String, nil] Sets the contents of a certificate directly to the specified value. This is used with lookup plugins or for anything with formatting or,C(content) must be provided when C(state) is C(present).\n attribute :content\n validates :content, type: String\n\n # @return [:present, :absent, nil] Certificate state. This determines if the provided certificate and key is to be made C(present) on the device or C(absent).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] SSL Certificate Name. This is the cert name used when importing a certificate into the F5. It also determines the filenames of the objects on the LTM.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Issuer certificate used for OCSP monitoring.,This parameter is only valid on versions of BIG-IP 13.0.0 or above.\n attribute :issuer_cert\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.681708812713623, "alphanum_fraction": 0.681708812713623, "avg_line_length": 43.91891860961914, "blob_id": "e5e812facc4c380a56ec8a1700fb21055ddae698", "content_id": "e5f989fcc7ba46e7cfcd317d84be8aaab2a2c623", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1662, "license_type": "permissive", "max_line_length": 185, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/packaging/os/pacman.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage packages with the I(pacman) package manager, which is used by Arch Linux and its variants.\n class Pacman < Base\n # @return [Array<String>, String, nil] Name or list of names of the packages to install, upgrade, or remove.\n attribute :name\n validates :name, type: TypeGeneric.new(String)\n\n # @return [:absent, :latest, :present, nil] Desired state of the package.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :latest, :present], :message=>\"%{value} needs to be :absent, :latest, :present\"}, allow_nil: true\n\n # @return [Symbol, nil] When removing a package, also remove its dependencies, provided that they are not required by other packages and were not explicitly installed by a user.\n attribute :recurse\n validates :recurse, type: Symbol\n\n # @return [Symbol, nil] When removing package - force remove package, without any checks. When update_cache - force redownload repo databases.\n attribute :force\n validates :force, type: Symbol\n\n # @return [Symbol, nil] Whether or not to refresh the master package lists. This can be run as part of a package installation or as a separate step.\n attribute :update_cache\n validates :update_cache, type: Symbol\n\n # @return [Symbol, nil] Whether or not to upgrade whole system.\n attribute :upgrade\n validates :upgrade, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6617449522018433, "alphanum_fraction": 0.6617449522018433, "avg_line_length": 45.5625, "blob_id": "303399fee0f90bb4f2bd8f6816e4a90910592c0b", "content_id": "0b34006532f67deecb29a45a544dedfd2ab633d3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1490, "license_type": "permissive", "max_line_length": 168, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/cloud/centurylink/clc_publicip.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # An Ansible module to add or delete public ip addresses on an existing server or servers in CenturyLink Cloud.\n class Clc_publicip < Base\n # @return [:TCP, :UDP, :ICMP, nil] The protocol that the public IP will listen for.\n attribute :protocol\n validates :protocol, expression_inclusion: {:in=>[:TCP, :UDP, :ICMP], :message=>\"%{value} needs to be :TCP, :UDP, :ICMP\"}, allow_nil: true\n\n # @return [Object, nil] A list of ports to expose. This is required when state is 'present'\n attribute :ports\n\n # @return [Object] A list of servers to create public ips on.\n attribute :server_ids\n validates :server_ids, presence: true\n\n # @return [:present, :absent, nil] Determine whether to create or delete public IPs. If present module will not create a second public ip if one already exists.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Whether to wait for the tasks to finish before returning.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6590313911437988, "alphanum_fraction": 0.6668848395347595, "avg_line_length": 43.94117736816406, "blob_id": "a3a445ea99eee165c8d1a8c896c6fd76ffb61f90", "content_id": "9611fca2cf3fec044490c43cb95d6f7e254641bd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3056, "license_type": "permissive", "max_line_length": 161, "num_lines": 68, "path": "/lib/ansible/ruby/modules/generated/cloud/oneandone/oneandone_private_network.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, remove, reconfigure, update a private network. This module has a dependency on 1and1 >= 1.0\n class Oneandone_private_network < Base\n # @return [:present, :absent, :update, nil] Define a network's state to create, remove, or update.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :update], :message=>\"%{value} needs to be :present, :absent, :update\"}, allow_nil: true\n\n # @return [String] Authenticating API token provided by 1&1.\n attribute :auth_token\n validates :auth_token, presence: true, type: String\n\n # @return [String] The identifier (id or name) of the network used with update state.\n attribute :private_network\n validates :private_network, presence: true, type: String\n\n # @return [Object, nil] Custom API URL. Overrides the ONEANDONE_API_URL environement variable.\n attribute :api_url\n\n # @return [String] Private network name used with present state. Used as identifier (id or name) when used with absent state.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Set a description for the network.\n attribute :description\n validates :description, type: String\n\n # @return [String, nil] The identifier of the datacenter where the private network will be created\n attribute :datacenter\n validates :datacenter, type: String\n\n # @return [String, nil] Set a private network space, i.e. 192.168.1.0\n attribute :network_address\n validates :network_address, type: String\n\n # @return [String, nil] Set the netmask for the private network, i.e. 255.255.255.0\n attribute :subnet_mask\n validates :subnet_mask, type: String\n\n # @return [Array<String>, String, nil] List of server identifiers (name or id) to be added to the private network.\n attribute :add_members\n validates :add_members, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] List of server identifiers (name or id) to be removed from the private network.\n attribute :remove_members\n validates :remove_members, type: TypeGeneric.new(String)\n\n # @return [:yes, :no, nil] wait for the instance to be in state 'running' before returning\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] how long before wait gives up, in seconds\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [Integer, nil] Defines the number of seconds to wait when using the _wait_for methods\n attribute :wait_interval\n validates :wait_interval, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6796141862869263, "alphanum_fraction": 0.6814389824867249, "avg_line_length": 61.88524627685547, "blob_id": "c811a2b7956a18ae8f320a0a83af60e44bc42587", "content_id": "098dba02d7ca7a0b5652f3292072c5794db0a38a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3836, "license_type": "permissive", "max_line_length": 324, "num_lines": 61, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/route53_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gets various details related to Route53 zone, record set or health check details\n class Route53_facts < Base\n # @return [:change, :checker_ip_range, :health_check, :hosted_zone, :record_sets, :reusable_delegation_set] specifies the query action to take\n attribute :query\n validates :query, presence: true, expression_inclusion: {:in=>[:change, :checker_ip_range, :health_check, :hosted_zone, :record_sets, :reusable_delegation_set], :message=>\"%{value} needs to be :change, :checker_ip_range, :health_check, :hosted_zone, :record_sets, :reusable_delegation_set\"}\n\n # @return [Object, nil] The ID of the change batch request. The value that you specify here is the value that ChangeResourceRecordSets returned in the Id element when you submitted the request.\n attribute :change_id\n\n # @return [String, nil] The Hosted Zone ID of the DNS zone\n attribute :hosted_zone_id\n validates :hosted_zone_id, type: String\n\n # @return [Integer, nil] Maximum number of items to return for various get/list requests\n attribute :max_items\n validates :max_items, type: Integer\n\n # @return [String, nil] Some requests such as list_command: hosted_zones will return a maximum number of entries - EG 100 or the number specified by max_items. If the number of entries exceeds this maximum another request can be sent using the NextMarker entry from the first response to get the next page of results\n attribute :next_marker\n validates :next_marker, type: String\n\n # @return [String, nil] The DNS Zone delegation set ID\n attribute :delegation_set_id\n validates :delegation_set_id, type: String\n\n # @return [Object, nil] The first name in the lexicographic ordering of domain names that you want the list_command: record_sets to start listing from\n attribute :start_record_name\n\n # @return [:A, :CNAME, :MX, :AAAA, :TXT, :PTR, :SRV, :SPF, :CAA, :NS, nil] The type of DNS record\n attribute :type\n validates :type, expression_inclusion: {:in=>[:A, :CNAME, :MX, :AAAA, :TXT, :PTR, :SRV, :SPF, :CAA, :NS], :message=>\"%{value} needs to be :A, :CNAME, :MX, :AAAA, :TXT, :PTR, :SRV, :SPF, :CAA, :NS\"}, allow_nil: true\n\n # @return [Object, nil] The first name in the lexicographic ordering of domain names that you want the list_command to start listing from\n attribute :dns_name\n\n # @return [Object, nil] The ID/s of the specified resource/s\n attribute :resource_id\n\n # @return [String, nil] The ID of the health check\n attribute :health_check_id\n validates :health_check_id, type: String\n\n # @return [:details, :list, :list_by_name, :count, :tags, nil] This is used in conjunction with query: hosted_zone. It allows for listing details, counts or tags of various hosted zone details.\n attribute :hosted_zone_method\n validates :hosted_zone_method, expression_inclusion: {:in=>[:details, :list, :list_by_name, :count, :tags], :message=>\"%{value} needs to be :details, :list, :list_by_name, :count, :tags\"}, allow_nil: true\n\n # @return [:list, :details, :status, :failure_reason, :count, :tags, nil] This is used in conjunction with query: health_check. It allows for listing details, counts or tags of various health check details.\n attribute :health_check_method\n validates :health_check_method, expression_inclusion: {:in=>[:list, :details, :status, :failure_reason, :count, :tags], :message=>\"%{value} needs to be :list, :details, :status, :failure_reason, :count, :tags\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6704270839691162, "alphanum_fraction": 0.6704270839691162, "avg_line_length": 43.32143020629883, "blob_id": "fda80b11fe73d2c1d266772ce07309a81376d9c2", "content_id": "1174de477e31373cc03eebf2b80b7b96f4ab4cbf", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1241, "license_type": "permissive", "max_line_length": 182, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/clustering/pacemaker_cluster.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can manage a pacemaker cluster and nodes from Ansible using the pacemaker cli.\n class Pacemaker_cluster < Base\n # @return [:cleanup, :offline, :online, :restart] Indicate desired state of the cluster\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:cleanup, :offline, :online, :restart], :message=>\"%{value} needs to be :cleanup, :offline, :online, :restart\"}\n\n # @return [Object, nil] Specify which node of the cluster you want to manage. None == the cluster status itself, 'all' == check the status of all nodes.\n attribute :node\n\n # @return [Integer, nil] Timeout when the module should considered that the action has failed\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [:yes, :no, nil] Force the change of the cluster state\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6422438621520996, "alphanum_fraction": 0.6445335149765015, "avg_line_length": 36.17021179199219, "blob_id": "ac7e585ceafd14d9cc14b9710554a983d3f325e6", "content_id": "ceb47efb3a0583e6f72af989ffd50cf2013b57a6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1747, "license_type": "permissive", "max_line_length": 143, "num_lines": 47, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_vpc_vgw.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates AWS VPN Virtual Gateways\n # Deletes AWS VPN Virtual Gateways\n # Attaches Virtual Gateways to VPCs\n # Detaches Virtual Gateways from VPCs\n class Ec2_vpc_vgw < Base\n # @return [:present, :absent, nil] present to ensure resource is created.,absent to remove resource\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] name of the vgw to be created or deleted\n attribute :name\n validates :name, type: String\n\n # @return [:\"ipsec.1\", nil] type of the virtual gateway to be created\n attribute :type\n validates :type, expression_inclusion: {:in=>[:\"ipsec.1\"], :message=>\"%{value} needs to be :\\\"ipsec.1\\\"\"}, allow_nil: true\n\n # @return [String, nil] vpn gateway id of an existing virtual gateway\n attribute :vpn_gateway_id\n validates :vpn_gateway_id, type: String\n\n # @return [String, nil] the vpc-id of a vpc to attach or detach\n attribute :vpc_id\n validates :vpc_id, type: String\n\n # @return [Object, nil] the BGP ASN of the amazon side\n attribute :asn\n\n # @return [Integer, nil] number of seconds to wait for status during vpc attach and detach\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [Hash, nil] dictionary of resource tags\n attribute :tags\n validates :tags, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6658805012702942, "alphanum_fraction": 0.6658805012702942, "avg_line_length": 42.86206817626953, "blob_id": "1256ee80e82d5b2f5f97b381756aeec83166488b", "content_id": "8a9cd04fb538f0f99aa582bc21cfa5df0e041a22", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1272, "license_type": "permissive", "max_line_length": 159, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_interface_policy_fc.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage ACI Fiber Channel interface policies on Cisco ACI fabrics.\n class Aci_interface_policy_fc < Base\n # @return [String] The name of the Fiber Channel interface policy.\n attribute :fc_policy\n validates :fc_policy, presence: true, type: String\n\n # @return [String, nil] The description of the Fiber Channel interface policy.\n attribute :description\n validates :description, type: String\n\n # @return [:f, :np, nil] The Port Mode to use.,The APIC defaults to C(f) when unset during creation.\n attribute :port_mode\n validates :port_mode, expression_inclusion: {:in=>[:f, :np], :message=>\"%{value} needs to be :f, :np\"}, allow_nil: true\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.702102780342102, "alphanum_fraction": 0.702102780342102, "avg_line_length": 37.90909194946289, "blob_id": "599bbb6e4d511e505f1ac67a66d671a01412b714", "content_id": "ade4ffcc555590aaa504c369917a0f666880c9d7", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 856, "license_type": "permissive", "max_line_length": 162, "num_lines": 22, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_cluster_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to gather facts about clusters in VMWare infrastructure.\n # All values and VMware object names are case sensitive.\n class Vmware_cluster_facts < Base\n # @return [String, nil] Datacenter to search for cluster/s.,This parameter is required, if C(cluster_name) is not supplied.\n attribute :datacenter\n validates :datacenter, type: String\n\n # @return [String, nil] Name of the cluster.,If set, facts of this cluster will be returned.,This parameter is required, if C(datacenter) is not supplied.\n attribute :cluster_name\n validates :cluster_name, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6965433955192566, "alphanum_fraction": 0.6973472833633423, "avg_line_length": 70.0857162475586, "blob_id": "2bd378e201eacede641b89aa838bd31ea80952cb", "content_id": "d9e3a3528c93a510b4c6a807e01abe4328e30db2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4976, "license_type": "permissive", "max_line_length": 623, "num_lines": 70, "path": "/lib/ansible/ruby/modules/generated/database/postgresql/postgresql_privs.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Grant or revoke privileges on PostgreSQL database objects.\n # This module is basically a wrapper around most of the functionality of PostgreSQL's GRANT and REVOKE statements with detection of changes (GRANT/REVOKE I(privs) ON I(type) I(objs) TO/FROM I(roles))\n class Postgresql_privs < Base\n # @return [String] Name of database to connect to.,Alias: I(db)\n attribute :database\n validates :database, presence: true, type: String\n\n # @return [:present, :absent, nil] If C(present), the specified privileges are granted, if C(absent) they are revoked.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] Comma separated list of privileges to grant/revoke.,Alias: I(priv)\n attribute :privs\n validates :privs, type: TypeGeneric.new(String)\n\n # @return [:table, :sequence, :function, :database, :schema, :language, :tablespace, :group, :default_privs, nil] Type of database object to set privileges on.,The `default_prives` choice is available starting at version 2.7.\n attribute :type\n validates :type, expression_inclusion: {:in=>[:table, :sequence, :function, :database, :schema, :language, :tablespace, :group, :default_privs], :message=>\"%{value} needs to be :table, :sequence, :function, :database, :schema, :language, :tablespace, :group, :default_privs\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] Comma separated list of database objects to set privileges on.,If I(type) is C(table) or C(sequence), the special value C(ALL_IN_SCHEMA) can be provided instead to specify all database objects of type I(type) in the schema specified via I(schema). (This also works with PostgreSQL < 9.0.),If I(type) is C(database), this parameter can be omitted, in which case privileges are set for the database specified via I(database).,If I(type) is I(function), colons (\":\") in object names will be replaced with commas (needed to specify function signatures, see examples),Alias: I(obj)\n attribute :objs\n validates :objs, type: TypeGeneric.new(String)\n\n # @return [String, nil] Schema that contains the database objects specified via I(objs).,May only be provided if I(type) is C(table), C(sequence) or C(function). Defaults to C(public) in these cases.\n attribute :schema\n validates :schema, type: String\n\n # @return [Array<String>, String] Comma separated list of role (user/group) names to set permissions for.,The special value C(PUBLIC) can be provided instead to set permissions for the implicitly defined PUBLIC group.,Alias: I(role)\n attribute :roles\n validates :roles, presence: true, type: TypeGeneric.new(String)\n\n # @return [Symbol, nil] Whether C(role) may grant/revoke the specified privileges/group memberships to others.,Set to C(no) to revoke GRANT OPTION, leave unspecified to make no changes.,I(grant_option) only has an effect if I(state) is C(present).,Alias: I(admin_option)\n attribute :grant_option\n validates :grant_option, type: Symbol\n\n # @return [Object, nil] Database host address. If unspecified, connect via Unix socket.,Alias: I(login_host)\n attribute :host\n\n # @return [Integer, nil] Database port to connect to.\n attribute :port\n validates :port, type: Integer\n\n # @return [Object, nil] Path to a Unix domain socket for local connections.,Alias: I(login_unix_socket)\n attribute :unix_socket\n\n # @return [String, nil] The username to authenticate with.,Alias: I(login_user)\n attribute :login\n validates :login, type: String\n\n # @return [Object, nil] The password to authenticate with.,Alias: I(login_password))\n attribute :password\n\n # @return [:disable, :allow, :prefer, :require, :\"verify-ca\", :\"verify-full\", nil] Determines whether or with what priority a secure SSL TCP/IP connection will be negotiated with the server.,See https://www.postgresql.org/docs/current/static/libpq-ssl.html for more information on the modes.,Default of C(prefer) matches libpq default.\n attribute :ssl_mode\n validates :ssl_mode, expression_inclusion: {:in=>[:disable, :allow, :prefer, :require, :\"verify-ca\", :\"verify-full\"], :message=>\"%{value} needs to be :disable, :allow, :prefer, :require, :\\\"verify-ca\\\", :\\\"verify-full\\\"\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the name of a file containing SSL certificate authority (CA) certificate(s). If the file exists, the server's certificate will be verified to be signed by one of these authorities.\n attribute :ssl_rootcert\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6612173914909363, "alphanum_fraction": 0.6653913259506226, "avg_line_length": 53.24528121948242, "blob_id": "8bdd4e7b518e04af462c1bba86a4709f94fad015", "content_id": "98301c75f3fe1d8458d40e7700db5b8c711695b8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2875, "license_type": "permissive", "max_line_length": 156, "num_lines": 53, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_vxlan_arp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages ARP attributes of VXLAN on HUAWEI CloudEngine devices.\n class Ce_vxlan_arp < Base\n # @return [:enable, :disable, nil] Enables EVN BGP.\n attribute :evn_bgp\n validates :evn_bgp, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the source address of an EVN BGP peer. The value is in dotted decimal notation.\n attribute :evn_source_ip\n\n # @return [Object, nil] Specifies the IP address of an EVN BGP peer. The value is in dotted decimal notation.\n attribute :evn_peer_ip\n\n # @return [:enable, :disable, nil] Configures the local device as the router reflector (RR) on the EVN network.\n attribute :evn_server\n validates :evn_server, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:enable, :disable, nil] Configures the local device as the route reflector (RR) and its peer as the client.\n attribute :evn_reflect_client\n validates :evn_reflect_client, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [Object, nil] Full name of VBDIF interface, i.e. Vbdif100.\n attribute :vbdif_name\n\n # @return [:enable, :disable, nil] Enables EVN BGP or BGP EVPN to collect host information.\n attribute :arp_collect_host\n validates :arp_collect_host, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:bgp, :none, nil] Enables EVN BGP or BGP EVPN to advertise host information.\n attribute :host_collect_protocol\n validates :host_collect_protocol, expression_inclusion: {:in=>[:bgp, :none], :message=>\"%{value} needs to be :bgp, :none\"}, allow_nil: true\n\n # @return [Object, nil] Specifies a BD(bridge domain) ID. The value is an integer ranging from 1 to 16777215.\n attribute :bridge_domain_id\n\n # @return [:enable, :disable, nil] Enables ARP broadcast suppression in a BD.\n attribute :arp_suppress\n validates :arp_suppress, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Determines whether the config should be present or not on the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6869806051254272, "alphanum_fraction": 0.6869806051254272, "avg_line_length": 42.31999969482422, "blob_id": "c26bc3c7a8728ad77de6dd1aa0789818ac4530e1", "content_id": "9b1e9a46caff0494e72b9bb4741a3b907df08b2a", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1083, "license_type": "permissive", "max_line_length": 325, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_software_install.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Install new images on a BIG-IP.\n class Bigip_software_install < Base\n # @return [String, nil] Image to install on the remote device.\n attribute :image\n validates :image, type: String\n\n # @return [String, nil] The volume to install the software image to.\n attribute :volume\n validates :volume, type: String\n\n # @return [:activated, :installed, nil] When C(installed), ensures that the software is installed on the volume and the volume is set to be booted from. The device is B(not) rebooted into the new software.,When C(activated), performs the same operation as C(installed), but the system is rebooted to the new software.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:activated, :installed], :message=>\"%{value} needs to be :activated, :installed\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5142857432365417, "alphanum_fraction": 0.5155279636383057, "avg_line_length": 21.36111068725586, "blob_id": "24b18c6cfb12d7a43282735db849f46199e1e488", "content_id": "558e470ea6338ea0f48cbdc2ec6d33a7759400aa", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 805, "license_type": "permissive", "max_line_length": 88, "num_lines": 36, "path": "/lib/ansible/ruby/serializer.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'yaml'\n\nmodule Ansible\n module Ruby\n module Serializer\n class << self\n def serialize(value)\n value = normalize_values value\n lines = value.to_yaml.split \"\\n\"\n lines.insert 1, '# This is a generated YAML file by ansible-ruby, DO NOT EDIT'\n lines.join \"\\n\"\n end\n\n private\n\n def normalize_values(value)\n # Don't want symbols in YAML\n case value\n when Hash\n Hash[value.map do |key, val|\n [key.to_s, normalize_values(val)]\n end]\n when Array\n value.map { |val| normalize_values(val) }\n when Symbol\n value.to_s\n else\n value\n end\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6497622728347778, "alphanum_fraction": 0.6497622728347778, "avg_line_length": 45.74074172973633, "blob_id": "b23a36e9ccfab3fd6b96d81b22f4295a624a0749", "content_id": "aba69a2014b97c0414c0240f0183b36b9d9f8901", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2524, "license_type": "permissive", "max_line_length": 266, "num_lines": 54, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_host.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and remove hosts.\n class Cs_host < Base\n # @return [String] Name of the host.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Url of the host used to create a host.,If not provided, C(http://) and param C(name) is used as url.,Only considered if C(state=present) and host does not yet exist.\n attribute :url\n\n # @return [Object, nil] Username for the host.,Required if C(state=present) and host does not yet exist.\n attribute :username\n\n # @return [Object, nil] Password for the host.,Required if C(state=present) and host does not yet exist.\n attribute :password\n\n # @return [String, nil] Name of the pod.,Required if C(state=present) and host does not yet exist.\n attribute :pod\n validates :pod, type: String\n\n # @return [String, nil] Name of the cluster.\n attribute :cluster\n validates :cluster, type: String\n\n # @return [:KVM, :VMware, :BareMetal, :XenServer, :LXC, :HyperV, :UCS, :OVM, :Simulator, nil] Name of the cluster.,Required if C(state=present) and host does not yet exist.\n attribute :hypervisor\n validates :hypervisor, expression_inclusion: {:in=>[:KVM, :VMware, :BareMetal, :XenServer, :LXC, :HyperV, :UCS, :OVM, :Simulator], :message=>\"%{value} needs to be :KVM, :VMware, :BareMetal, :XenServer, :LXC, :HyperV, :UCS, :OVM, :Simulator\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] Allocation state of the host.\n attribute :allocation_state\n validates :allocation_state, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] Tags of the host.\n attribute :host_tags\n validates :host_tags, type: TypeGeneric.new(String)\n\n # @return [:present, :absent, nil] State of the host.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Name of the zone in which the host should be deployed.,If not set, default zone is used.\n attribute :zone\n validates :zone, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6351351141929626, "alphanum_fraction": 0.6351351141929626, "avg_line_length": 36, "blob_id": "99d86e38ca870dabc251e32cecf9dce22778b5a8", "content_id": "31aab9e0f65546e43360f87354aacbbc7851eca1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2220, "license_type": "permissive", "max_line_length": 213, "num_lines": 60, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_nova_flavor.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove flavors from OpenStack.\n class Os_nova_flavor < Base\n # @return [:present, :absent, nil] Indicate desired state of the resource. When I(state) is 'present', then I(ram), I(vcpus), and I(disk) are all required. There are no default values for those parameters.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] Flavor name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Integer, nil] Amount of memory, in MB.\n attribute :ram\n validates :ram, type: Integer\n\n # @return [Integer, nil] Number of virtual CPUs.\n attribute :vcpus\n validates :vcpus, type: Integer\n\n # @return [Integer, nil] Size of local disk, in GB.\n attribute :disk\n validates :disk, type: Integer\n\n # @return [Integer, nil] Ephemeral space size, in GB.\n attribute :ephemeral\n validates :ephemeral, type: Integer\n\n # @return [Integer, nil] Swap space size, in MB.\n attribute :swap\n validates :swap, type: Integer\n\n # @return [Float, nil] RX/TX factor.\n attribute :rxtx_factor\n validates :rxtx_factor, type: Float\n\n # @return [:yes, :no, nil] Make flavor accessible to the public.\n attribute :is_public\n validates :is_public, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] ID for the flavor. This is optional as a unique UUID will be assigned if a value is not specified.\n attribute :flavorid\n validates :flavorid, type: String\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n\n # @return [Hash, nil] Metadata dictionary\n attribute :extra_specs\n validates :extra_specs, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5770006775856018, "alphanum_fraction": 0.5770006775856018, "avg_line_length": 28.739999771118164, "blob_id": "22652567f31dbe2a487123d0551c3341232a3e4a", "content_id": "2dc74a925a98d6b33f82aa9de3369e6c4bc26eb2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1487, "license_type": "permissive", "max_line_length": 86, "num_lines": 50, "path": "/lib/ansible/ruby/rake/compile.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# See LICENSE.txt in root of repository\nrequire 'rake/tasklib'\nrequire 'ansible-ruby'\nrequire 'ansible/ruby/rake/task_util'\n\nmodule Ansible\n module Ruby\n module Rake\n class Compile < ::Rake::TaskLib\n include TaskUtil\n\n # :reek:Attribute - Rake DSL gets ugly if we don't use a block\n attr_accessor :files\n\n def initialize(parameters = :default)\n self.class.load_rule\n name, deps = parse_params parameters\n yield self if block_given?\n raise 'You did not supply any files!' unless files && [*files].any?\n\n deps ||= []\n yml_filenames = yaml_filenames([*files])\n deps = [*deps] + yml_filenames\n task name => deps\n end\n\n class << self\n def load_rule\n return if @rule_done\n\n ::Rake.application.create_rule '.yml' => '.rb' do |filename|\n puts \"Updating Ansible file #{filename.name} from #{filename.source}...\"\n file_builder = Ansible::Ruby::DslBuilders::FileLevel.new\n exception = file_builder._handled_eval filename.source\n # Avoid lengthy stack trace\n raise exception if exception\n\n playbook = file_builder._result\n yml = Ansible::Ruby::Serializer.serialize playbook.to_h\n File.write filename.name, yml\n end\n @rule_done = true\n end\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6382046937942505, "alphanum_fraction": 0.6447728276252747, "avg_line_length": 43.56097412109375, "blob_id": "9fd03c305e34f998d3034a9c601a3e180025c0d3", "content_id": "d4ab8aba8bbb4044831288ee3777d689eaf1cd35", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1827, "license_type": "permissive", "max_line_length": 200, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/cloud/vultr/vultr_firewall_rule.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create and remove firewall rules.\n class Vultr_firewall_rule < Base\n # @return [String] Name of the firewall group.\n attribute :group\n validates :group, presence: true, type: String\n\n # @return [:v4, :v6, nil] IP address version\n attribute :ip_version\n validates :ip_version, expression_inclusion: {:in=>[:v4, :v6], :message=>\"%{value} needs to be :v4, :v6\"}, allow_nil: true\n\n # @return [:icmp, :tcp, :udp, :gre, nil] Protocol of the firewall rule.\n attribute :protocol\n validates :protocol, expression_inclusion: {:in=>[:icmp, :tcp, :udp, :gre], :message=>\"%{value} needs to be :icmp, :tcp, :udp, :gre\"}, allow_nil: true\n\n # @return [String, nil] Network in CIDR format,The CIDR format must match with the C(ip_version) value.,Required if C(state=present).,Defaulted to 0.0.0.0/0 or ::/0 depending on C(ip_version).\n attribute :cidr\n validates :cidr, type: String\n\n # @return [Integer, nil] Start port for the firewall rule.,Required if C(protocol) is tcp or udp and I(state=present).\n attribute :start_port\n validates :start_port, type: Integer\n\n # @return [Integer, nil] End port for the firewall rule.,Only considered if C(protocol) is tcp or udp and I(state=present).\n attribute :end_port\n validates :end_port, type: Integer\n\n # @return [:present, :absent, nil] State of the firewall rule.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6963993310928345, "alphanum_fraction": 0.6963993310928345, "avg_line_length": 41.13793182373047, "blob_id": "6a781d5dcba1e9752a101dbf062b586c1073cf17", "content_id": "16aa4d0e4590c0f308e223607c76fd84281657a3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1222, "license_type": "permissive", "max_line_length": 220, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_trafficmanagerendpoint_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Get facts for a specific Traffic Manager endpoints or all endpoints in a Traffic Manager profile\n class Azure_rm_trafficmanagerendpoint_facts < Base\n # @return [String, nil] Limit results to a specific Traffic Manager endpoint.\n attribute :name\n validates :name, type: String\n\n # @return [String] The resource group to search for the desired Traffic Manager profile\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] Name of Traffic Manager Profile\n attribute :profile_name\n validates :profile_name, presence: true, type: String\n\n # @return [:azure_endpoints, :external_endpoints, :nested_endpoints, nil] Type of endpoint.\n attribute :type\n validates :type, expression_inclusion: {:in=>[:azure_endpoints, :external_endpoints, :nested_endpoints], :message=>\"%{value} needs to be :azure_endpoints, :external_endpoints, :nested_endpoints\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6942856907844543, "alphanum_fraction": 0.6942856907844543, "avg_line_length": 65.21621704101562, "blob_id": "3a637dec5b595200c0a452fe780d4dc66a37902d", "content_id": "1f722d1bcf6345ba48cf39de923bc0ab12cfb5d5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2450, "license_type": "permissive", "max_line_length": 392, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/packaging/os/sorcery.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages \"spells\" on Source Mage GNU/Linux using I(sorcery) toolchain\n class Sorcery < Base\n # @return [String, nil] Name of the spell,multiple names can be given, separated by commas,special value '*' in conjunction with states C(latest) or C(rebuild) will update or rebuild the whole system respectively\n attribute :name\n validates :name, type: String\n\n # @return [:present, :latest, :absent, :cast, :dispelled, :rebuild, nil] Whether to cast, dispel or rebuild a package,state C(cast) is an equivalent of C(present), not C(latest),state C(latest) always triggers C(update_cache=yes),state C(rebuild) implies cast of all specified spells, not only those existed before\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :latest, :absent, :cast, :dispelled, :rebuild], :message=>\"%{value} needs to be :present, :latest, :absent, :cast, :dispelled, :rebuild\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] Comma-separated list of _optional_ dependencies to build a spell (or make sure it is built) with; use +/- in front of dependency to turn it on/off ('+' is optional though),this option is ignored if C(name) parameter is equal to '*' or contains more than one spell,providers must be supplied in the form recognized by Sorcery, e.g. 'openssl(SSL)'\n attribute :depends\n validates :depends, type: TypeGeneric.new(String)\n\n # @return [:yes, :no, nil] Whether or not to update sorcery scripts at the very first stage\n attribute :update\n validates :update, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Whether or not to update grimoire collection before casting spells\n attribute :update_cache\n validates :update_cache, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Time in seconds to invalidate grimoire collection on update,especially useful for SCM and rsync grimoires,makes sense only in pair with C(update_cache)\n attribute :cache_valid_time\n validates :cache_valid_time, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.661544919013977, "alphanum_fraction": 0.6689481735229492, "avg_line_length": 50.13571548461914, "blob_id": "ca36f37d7a835813a3e77e4a3daf4e9f8b981b70", "content_id": "15507c2f090339d76b0be685af30dc8b0b95c260", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 7159, "license_type": "permissive", "max_line_length": 265, "num_lines": 140, "path": "/lib/ansible/ruby/modules/generated/cloud/centurylink/clc_server.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # An Ansible module to Create, Delete, Start and Stop servers in CenturyLink Cloud.\n class Clc_server < Base\n # @return [Object, nil] The list of additional disks for the server\n attribute :additional_disks\n\n # @return [:yes, :no, nil] Whether to add a public ip to the server\n attribute :add_public_ip\n validates :add_public_ip, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] The account alias to provision the servers under.\n attribute :alias\n\n # @return [Object, nil] The anti-affinity policy to assign to the server. This is mutually exclusive with 'anti_affinity_policy_name'.\n attribute :anti_affinity_policy_id\n\n # @return [Object, nil] The anti-affinity policy to assign to the server. This is mutually exclusive with 'anti_affinity_policy_id'.\n attribute :anti_affinity_policy_name\n\n # @return [Object, nil] The alert policy to assign to the server. This is mutually exclusive with 'alert_policy_name'.\n attribute :alert_policy_id\n\n # @return [Object, nil] The alert policy to assign to the server. This is mutually exclusive with 'alert_policy_id'.\n attribute :alert_policy_name\n\n # @return [Integer, nil] The number of servers to build (mutually exclusive with exact_count)\n attribute :count\n validates :count, type: Integer\n\n # @return [String, nil] Required when exact_count is specified. The Server Group use to determine how many severs to deploy.\n attribute :count_group\n validates :count_group, type: String\n\n # @return [Integer, nil] How many CPUs to provision on the server\n attribute :cpu\n validates :cpu, type: Integer\n\n # @return [Object, nil] The autoscale policy to assign to the server.\n attribute :cpu_autoscale_policy_id\n\n # @return [Object, nil] The list of custom fields to set on the server.\n attribute :custom_fields\n\n # @return [Object, nil] The description to set for the server.\n attribute :description\n\n # @return [Integer, nil] Run in idempotent mode. Will insure that this exact number of servers are running in the provided group, creating and deleting them to reach that count. Requires count_group to be set.\n attribute :exact_count\n validates :exact_count, type: Integer\n\n # @return [String, nil] The Server Group to create servers under.\n attribute :group\n validates :group, type: String\n\n # @return [Object, nil] The IP Address for the server. One is assigned if not provided.\n attribute :ip_address\n\n # @return [Object, nil] The Datacenter to create servers in.\n attribute :location\n\n # @return [:yes, :no, nil] Whether to create the server as 'Managed' or not.\n attribute :managed_os\n validates :managed_os, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Memory in GB.\n attribute :memory\n validates :memory, type: Integer\n\n # @return [String, nil] A 1 to 6 character identifier to use for the server. This is required when state is 'present'\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] The network UUID on which to create servers.\n attribute :network_id\n\n # @return [Object, nil] The list of blue print packages to run on the server after its created.\n attribute :packages\n\n # @return [Object, nil] Password for the administrator / root user\n attribute :password\n\n # @return [Object, nil] Primary DNS used by the server.\n attribute :primary_dns\n\n # @return [:TCP, :UDP, :ICMP, nil] The protocol to use for the public ip if add_public_ip is set to True.\n attribute :public_ip_protocol\n validates :public_ip_protocol, expression_inclusion: {:in=>[:TCP, :UDP, :ICMP], :message=>\"%{value} needs to be :TCP, :UDP, :ICMP\"}, allow_nil: true\n\n # @return [Object, nil] A list of ports to allow on the firewall to the servers public ip, if add_public_ip is set to True.\n attribute :public_ip_ports\n\n # @return [Object, nil] Secondary DNS used by the server.\n attribute :secondary_dns\n\n # @return [Object, nil] Required for started, stopped, and absent states. A list of server Ids to insure are started, stopped, or absent.\n attribute :server_ids\n\n # @return [Object, nil] The password for the source server if a clone is specified.\n attribute :source_server_password\n\n # @return [:present, :absent, :started, :stopped, nil] The state to insure that the provided resources are in.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :started, :stopped], :message=>\"%{value} needs to be :present, :absent, :started, :stopped\"}, allow_nil: true\n\n # @return [:standard, :hyperscale, nil] The type of storage to attach to the server.\n attribute :storage_type\n validates :storage_type, expression_inclusion: {:in=>[:standard, :hyperscale], :message=>\"%{value} needs to be :standard, :hyperscale\"}, allow_nil: true\n\n # @return [String, nil] The template to use for server creation. Will search for a template if a partial string is provided. This is required when state is 'present'\n attribute :template\n validates :template, type: String\n\n # @return [Object, nil] The time to live for the server in seconds. The server will be deleted when this time expires.\n attribute :ttl\n\n # @return [:standard, :hyperscale, :bareMetal, nil] The type of server to create.\n attribute :type\n validates :type, expression_inclusion: {:in=>[:standard, :hyperscale, :bareMetal], :message=>\"%{value} needs to be :standard, :hyperscale, :bareMetal\"}, allow_nil: true\n\n # @return [Object, nil] Only required for bare metal servers. Specifies the identifier for the specific configuration type of bare metal server to deploy.\n attribute :configuration_id\n\n # @return [:redHat6_64Bit, :centOS6_64Bit, :windows2012R2Standard_64Bit, :ubuntu14_64Bit, nil] Only required for bare metal servers. Specifies the OS to provision with the bare metal server.\n attribute :os_type\n validates :os_type, expression_inclusion: {:in=>[:redHat6_64Bit, :centOS6_64Bit, :windows2012R2Standard_64Bit, :ubuntu14_64Bit], :message=>\"%{value} needs to be :redHat6_64Bit, :centOS6_64Bit, :windows2012R2Standard_64Bit, :ubuntu14_64Bit\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Whether to wait for the provisioning tasks to finish before returning.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5164257287979126, "alphanum_fraction": 0.5177398324012756, "avg_line_length": 19.026315689086914, "blob_id": "0320abd67c85e2fd18f784bf28a344461c343427", "content_id": "1e0ba1c06b154dc7731bfe5082b84342ccf7127f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 761, "license_type": "permissive", "max_line_length": 44, "num_lines": 38, "path": "/lib/ansible/ruby/dsl_builders/unit.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# see LICENSE.txt in project root\nmodule Ansible\n module Ruby\n module DslBuilders\n class Unit < Base\n def initialize\n super()\n @temp_counter = 0\n @task_args = {}\n end\n\n def become(*args)\n value = _implicit_bool args\n @task_args[:become] = value\n end\n\n def become_user(value)\n @task_args[:become_user] = value\n end\n\n def ansible_when(clause)\n @task_args[:when] = clause\n end\n\n def ignore_errors(*args)\n value = _implicit_bool args\n @task_args[:ignore_errors] = value\n end\n\n def vars(hash)\n @task_args[:vars] = hash\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6472166180610657, "alphanum_fraction": 0.6482226848602295, "avg_line_length": 51.31578826904297, "blob_id": "422a8a54b9df71ed04ae9794a6270869af9116a4", "content_id": "da93c95584c90150721df452167453f4bad9044d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2982, "license_type": "permissive", "max_line_length": 155, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/network/onyx/onyx_protocol.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides a mechanism for enabling and disabling protocols Mellanox on ONYX network devices.\n class Onyx_protocol < Base\n # @return [:enabled, :disabled, nil] MLAG protocol\n attribute :mlag\n validates :mlag, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] MAGP protocol\n attribute :magp\n validates :magp, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] Spanning Tree support\n attribute :spanning_tree\n validates :spanning_tree, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] DCB priority flow control\n attribute :dcb_pfc\n validates :dcb_pfc, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] IP IGMP snooping\n attribute :igmp_snooping\n validates :igmp_snooping, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] LACP protocol\n attribute :lacp\n validates :lacp, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] IP L3 support\n attribute :ip_l3\n validates :ip_l3, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] IP routing support\n attribute :ip_routing\n validates :ip_routing, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] LLDP protocol\n attribute :lldp\n validates :lldp, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] BGP protocol\n attribute :bgp\n validates :bgp, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] OSPF protocol\n attribute :ospf\n validates :ospf, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6493055820465088, "alphanum_fraction": 0.6493055820465088, "avg_line_length": 35, "blob_id": "e64141b96905fe7b8037b242d61af257e6e78116", "content_id": "b383d60575344a2b30127c570956e97d7171b40c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1152, "license_type": "permissive", "max_line_length": 143, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/network/onyx/onyx_vlan.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of VLANs on Mellanox ONYX network devices.\n class Onyx_vlan < Base\n # @return [String, nil] Name of the VLAN.\n attribute :name\n validates :name, type: String\n\n # @return [Integer, nil] ID of the VLAN.\n attribute :vlan_id\n validates :vlan_id, type: Integer\n\n # @return [Object, nil] List of VLANs definitions.\n attribute :aggregate\n\n # @return [Boolean, nil] Purge VLANs not defined in the I(aggregate) parameter.\n attribute :purge\n validates :purge, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:present, :absent, nil] State of the VLAN configuration.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6537971496582031, "alphanum_fraction": 0.6574394702911377, "avg_line_length": 52.3106803894043, "blob_id": "a104b3759e512b421d2ddecaafab4777a9be7aee", "content_id": "e34142d0a89bf664d7ad988f796fefcdba99d401", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5491, "license_type": "permissive", "max_line_length": 247, "num_lines": 103, "path": "/lib/ansible/ruby/modules/generated/cloud/oneandone/oneandone_server.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, destroy, update, start, stop, and reboot a 1&1 Host server. When the server is created it can optionally wait for it to be 'running' before returning.\n class Oneandone_server < Base\n # @return [:present, :absent, :running, :stopped, nil] Define a server's state to create, remove, start or stop it.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :running, :stopped], :message=>\"%{value} needs to be :present, :absent, :running, :stopped\"}, allow_nil: true\n\n # @return [String] Authenticating API token provided by 1&1. Overrides the ONEANDONE_AUTH_TOKEN environement variable.\n attribute :auth_token\n validates :auth_token, presence: true, type: String\n\n # @return [Object, nil] Custom API URL. Overrides the ONEANDONE_API_URL environement variable.\n attribute :api_url\n\n # @return [:US, :ES, :DE, :GB, nil] The datacenter location.\n attribute :datacenter\n validates :datacenter, expression_inclusion: {:in=>[:US, :ES, :DE, :GB], :message=>\"%{value} needs to be :US, :ES, :DE, :GB\"}, allow_nil: true\n\n # @return [String, nil] The hostname or ID of the server. Only used when state is 'present'.\n attribute :hostname\n validates :hostname, type: String\n\n # @return [Object, nil] The description of the server.\n attribute :description\n\n # @return [String, nil] The operating system name or ID for the server. It is required only for 'present' state.\n attribute :appliance\n validates :appliance, type: String\n\n # @return [:S, :M, :L, :XL, :XXL, :\"3XL\", :\"4XL\", :\"5XL\"] The instance size name or ID of the server. It is required only for 'present' state, and it is mutually exclusive with vcore, cores_per_processor, ram, and hdds parameters.\n attribute :fixed_instance_size\n validates :fixed_instance_size, presence: true, expression_inclusion: {:in=>[:S, :M, :L, :XL, :XXL, :\"3XL\", :\"4XL\", :\"5XL\"], :message=>\"%{value} needs to be :S, :M, :L, :XL, :XXL, :\\\"3XL\\\", :\\\"4XL\\\", :\\\"5XL\\\"\"}\n\n # @return [Integer, nil] The total number of processors. It must be provided with cores_per_processor, ram, and hdds parameters.\n attribute :vcore\n validates :vcore, type: Integer\n\n # @return [Integer, nil] The number of cores per processor. It must be provided with vcore, ram, and hdds parameters.\n attribute :cores_per_processor\n validates :cores_per_processor, type: Integer\n\n # @return [Float, nil] The amount of RAM memory. It must be provided with with vcore, cores_per_processor, and hdds parameters.\n attribute :ram\n validates :ram, type: Float\n\n # @return [Array<Hash>, Hash, nil] A list of hard disks with nested \"size\" and \"is_main\" properties. It must be provided with vcore, cores_per_processor, and ram parameters.\n attribute :hdds\n validates :hdds, type: TypeGeneric.new(Hash)\n\n # @return [Object, nil] The private network name or ID.\n attribute :private_network\n\n # @return [Object, nil] The firewall policy name or ID.\n attribute :firewall_policy\n\n # @return [Object, nil] The load balancer name or ID.\n attribute :load_balancer\n\n # @return [Object, nil] The monitoring policy name or ID.\n attribute :monitoring_policy\n\n # @return [String, nil] Server identifier (ID or hostname). It is required for all states except 'running' and 'present'.\n attribute :server\n validates :server, type: String\n\n # @return [Integer, nil] The number of servers to create.\n attribute :count\n validates :count, type: Integer\n\n # @return [String, nil] User's public SSH key (contents, not path).\n attribute :ssh_key\n validates :ssh_key, type: String\n\n # @return [:cloud, :baremetal, :k8s_node, nil] The type of server to be built.\n attribute :server_type\n validates :server_type, expression_inclusion: {:in=>[:cloud, :baremetal, :k8s_node], :message=>\"%{value} needs to be :cloud, :baremetal, :k8s_node\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Wait for the server to be in state 'running' before returning. Also used for delete operation (set to 'false' if you don't want to wait for each individual server to be deleted before moving on with other tasks.)\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] how long before wait gives up, in seconds\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [Integer, nil] Defines the number of seconds to wait when using the wait_for methods\n attribute :wait_interval\n validates :wait_interval, type: Integer\n\n # @return [:yes, :no, nil] When creating multiple servers at once, whether to differentiate hostnames by appending a count after them or substituting the count where there is a %02d or %03d in the hostname string.\n attribute :auto_increment\n validates :auto_increment, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6612136960029602, "alphanum_fraction": 0.6612136960029602, "avg_line_length": 42.068180084228516, "blob_id": "12952f414fa0cc199e7d11095fbde87082737bec", "content_id": "5df5e0ba4200d7c98e58e55a951fa9190ba2573c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1895, "license_type": "permissive", "max_line_length": 175, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/network/bigswitch/bcf_switch.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create and remove a Big Cloud Fabric switch.\n class Bcf_switch < Base\n # @return [String] The name of the switch.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:spine, :leaf] Fabric role of the switch.\n attribute :fabric_role\n validates :fabric_role, presence: true, expression_inclusion: {:in=>[:spine, :leaf], :message=>\"%{value} needs to be :spine, :leaf\"}\n\n # @return [String, nil] The leaf group of the switch if the switch is a leaf.\n attribute :leaf_group\n validates :leaf_group, type: String\n\n # @return [String] The MAC address of the switch.\n attribute :mac\n validates :mac, presence: true, type: String\n\n # @return [:present, :absent, nil] Whether the switch should be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The controller IP address.\n attribute :controller\n validates :controller, presence: true, type: String\n\n # @return [Boolean, nil] If C(false), SSL certificates will not be validated. This should only be used on personally controlled devices using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] Big Cloud Fabric access token. If this isn't set then the environment variable C(BIGSWITCH_ACCESS_TOKEN) is used.\n attribute :access_token\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6577423810958862, "alphanum_fraction": 0.6606367826461792, "avg_line_length": 38.485713958740234, "blob_id": "f84953364ce96cf19890f295f6231209744d9252", "content_id": "555453ebd59a45d18d06218c1c293563f2deab76", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1382, "license_type": "permissive", "max_line_length": 156, "num_lines": 35, "path": "/lib/ansible/ruby/modules/generated/network/onyx/onyx_l2_interface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of Layer-2 interface on Mellanox ONYX network devices.\n class Onyx_l2_interface < Base\n # @return [String, nil] Name of the interface.\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] List of Layer-2 interface definitions.\n attribute :aggregate\n\n # @return [:access, :trunk, :hybrid, nil] Mode in which interface needs to be configured.\n attribute :mode\n validates :mode, expression_inclusion: {:in=>[:access, :trunk, :hybrid], :message=>\"%{value} needs to be :access, :trunk, :hybrid\"}, allow_nil: true\n\n # @return [Integer, nil] Configure given VLAN in access port.\n attribute :access_vlan\n validates :access_vlan, type: Integer\n\n # @return [Object, nil] List of allowed VLANs in a given trunk port.\n attribute :trunk_allowed_vlans\n\n # @return [:present, :absent, nil] State of the Layer-2 Interface configuration.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6720665693283081, "alphanum_fraction": 0.6720665693283081, "avg_line_length": 54.70731735229492, "blob_id": "aa3a799dfba1f6e513e0b6e3b2f718b6d15ac52e", "content_id": "9931e1bae0acc34e735e861cc40a544358d3bd88", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2284, "license_type": "permissive", "max_line_length": 350, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/system/osx_defaults.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # osx_defaults allows users to read, write, and delete macOS user defaults from Ansible scripts. macOS applications and other programs use the defaults system to record user preferences and other information that must be maintained when the applications aren't running (such as default font for new documents, or the position of an Info panel).\n class Osx_defaults < Base\n # @return [String, nil] The domain is a domain name of the form com.companyname.appname.\n attribute :domain\n validates :domain, type: String\n\n # @return [String, nil] The host on which the preference should apply. The special value \"currentHost\" corresponds to the \"-currentHost\" switch of the defaults commandline tool.\n attribute :host\n validates :host, type: String\n\n # @return [String] The key of the user preference\n attribute :key\n validates :key, presence: true, type: String\n\n # @return [:array, :bool, :boolean, :date, :float, :int, :integer, :string, nil] The type of value to write.\n attribute :type\n validates :type, expression_inclusion: {:in=>[:array, :bool, :boolean, :date, :float, :int, :integer, :string], :message=>\"%{value} needs to be :array, :bool, :boolean, :date, :float, :int, :integer, :string\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Add new elements to the array for a key which has an array as its value.\n attribute :array_add\n validates :array_add, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Boolean, nil] The value to write. Only required when state = present.\n attribute :value\n validates :value, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:present, :absent, nil] The state of the user defaults\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6796116232872009, "alphanum_fraction": 0.6796116232872009, "avg_line_length": 33.33333206176758, "blob_id": "1b467a5c505d3a9f172122bfcfc630e5c142b972", "content_id": "499c938cad7f92d8bdac136a15cd66a247e3d71c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 824, "license_type": "permissive", "max_line_length": 162, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_postgresqlserver_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Get facts of PostgreSQL Server.\n class Azure_rm_postgresqlserver_facts < Base\n # @return [String] The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String, nil] The name of the server.\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] Limit results by providing a list of tags. Format tags as 'key' or 'key:value'.\n attribute :tags\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7043343782424927, "alphanum_fraction": 0.7043343782424927, "avg_line_length": 34.88888931274414, "blob_id": "690fc5b3b6bd286be62ddf49e239ce9b564b3f2a", "content_id": "810a74f427b32a74618f74511155d280ac007fa0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 646, "license_type": "permissive", "max_line_length": 144, "num_lines": 18, "path": "/lib/ansible/ruby/modules/generated/utilities/logic/fail.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module fails the progress with a custom message. It can be useful for bailing out when a certain condition is met using C(when).\n # This module is also supported for Windows targets.\n class Fail < Base\n # @return [String, nil] The customized message used for failing execution. If omitted, fail will simply bail out with a generic message.\n attribute :msg\n validates :msg, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.657471239566803, "alphanum_fraction": 0.657471239566803, "avg_line_length": 33.79999923706055, "blob_id": "156aa92b011a29977c472c787a46423abe4b4ff5", "content_id": "f2e36777c6ce65590577cc20db9f950c6d4f389c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 870, "license_type": "permissive", "max_line_length": 143, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/cloud/scaleway/scaleway_sshkey.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module manages SSH keys on Scaleway account U(https://developer.scaleway.com)\n class Scaleway_sshkey < Base\n # @return [:present, :absent, nil] Indicate desired state of the SSH key.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The public SSH key as a string to add.\n attribute :ssh_pub_key\n validates :ssh_pub_key, presence: true, type: String\n\n # @return [String, nil] Scaleway API URL\n attribute :api_url\n validates :api_url, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7014979720115662, "alphanum_fraction": 0.7014979720115662, "avg_line_length": 56.02083206176758, "blob_id": "29a846e25130a36b9b524a9658f143ca70c68e41", "content_id": "9e844c5d5b88d044a34bf4d62d7134212fb06825", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2737, "license_type": "permissive", "max_line_length": 588, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_router.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or Delete routers from OpenStack. Although Neutron allows routers to share the same name, this module enforces name uniqueness to be more user friendly.\n class Os_router < Base\n # @return [:present, :absent, nil] Indicate desired state of the resource\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] Name to be give to the router\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:yes, :no, nil] Desired admin state of the created or existing router.\n attribute :admin_state_up\n validates :admin_state_up, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Symbol, nil] Enable Source NAT (SNAT) attribute.\n attribute :enable_snat\n validates :enable_snat, type: Symbol\n\n # @return [String, nil] Unique name or ID of the external gateway network.,required I(interfaces) or I(enable_snat) are provided.\n attribute :network\n validates :network, type: String\n\n # @return [String, nil] Unique name or ID of the project.\n attribute :project\n validates :project, type: String\n\n # @return [Array<Hash>, Hash, nil] The IP address parameters for the external gateway network. Each is a dictionary with the subnet name or ID (subnet) and the IP address to assign on the subnet (ip). If no IP is specified, one is automatically assigned from that subnet.\n attribute :external_fixed_ips\n validates :external_fixed_ips, type: TypeGeneric.new(Hash)\n\n # @return [Array<String>, String, nil] List of subnets to attach to the router internal interface. Default gateway associated with the subnet will be automatically attached with the router's internal interface. In order to provide an ip address different from the default gateway,parameters are passed as dictionary with keys as network name or ID(net), subnet name or ID (subnet) and the IP of port (portip) from the network. User defined portip is often required when a multiple router need to be connected to a single subnet for which the default gateway has been already used.\n attribute :interfaces\n validates :interfaces, type: TypeGeneric.new(String, Hash)\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6807174682617188, "alphanum_fraction": 0.6807174682617188, "avg_line_length": 32.787879943847656, "blob_id": "b233b6d35c23d7f2ad3186f497e4cecb20978902", "content_id": "d02e4d146e23843ef0e8ba6b79845d8d1f7c6046", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1115, "license_type": "permissive", "max_line_length": 106, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/database/influxdb/influxdb_retention_policy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage InfluxDB retention policies\n class Influxdb_retention_policy < Base\n # @return [String] Name of the database.\n attribute :database_name\n validates :database_name, presence: true, type: String\n\n # @return [String] Name of the retention policy\n attribute :policy_name\n validates :policy_name, presence: true, type: String\n\n # @return [String] Determines how long InfluxDB should keep the data\n attribute :duration\n validates :duration, presence: true, type: String\n\n # @return [Integer] Determines how many independent copies of each point are stored in the cluster\n attribute :replication\n validates :replication, presence: true, type: Integer\n\n # @return [Object] Sets the retention policy as default retention policy\n attribute :default\n validates :default, presence: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6678009629249573, "alphanum_fraction": 0.6678009629249573, "avg_line_length": 45.09803771972656, "blob_id": "746f335c08a0e0256e20764c6be3fc5e6fe0e4e0", "content_id": "1de8feb46caf5f2e5692e8ef484da17460a82b37", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2351, "license_type": "permissive", "max_line_length": 223, "num_lines": 51, "path": "/lib/ansible/ruby/modules/generated/network/meraki/meraki_network.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows for creation, management, and visibility into networks within Meraki.\n class Meraki_network < Base\n # @return [String, nil] Authentication key provided by the dashboard. Required if environmental variable MERAKI_KEY is not set.\n attribute :auth_key\n validates :auth_key, type: String\n\n # @return [:absent, :present, :query, nil] Create or modify an organization.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n\n # @return [String, nil] Name of a network.\n attribute :net_name\n validates :net_name, type: String\n\n # @return [Object, nil] ID number of a network.\n attribute :net_id\n\n # @return [String, nil] Name of organization associated to a network.\n attribute :org_name\n validates :org_name, type: String\n\n # @return [Object, nil] ID of organization associated to a network.\n attribute :org_id\n\n # @return [:appliance, :combined, :switch, :wireless, nil] Type of network device network manages.,Required when creating a network.\n attribute :type\n validates :type, expression_inclusion: {:in=>[:appliance, :combined, :switch, :wireless], :message=>\"%{value} needs to be :appliance, :combined, :switch, :wireless\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] Comma delimited list of tags to assign to network.\n attribute :tags\n validates :tags, type: TypeGeneric.new(String)\n\n # @return [String, nil] Timezone associated to network.,See U(https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) for a list of valid timezones.\n attribute :timezone\n validates :timezone, type: String\n\n # @return [Symbol, nil] - Disables the local device status pages (U[my.meraki.com](my.meraki.com), U[ap.meraki.com](ap.meraki.com), U[switch.meraki.com](switch.meraki.com), U[wired.meraki.com](wired.meraki.com))\\r\\n\n attribute :disable_my_meraki\n validates :disable_my_meraki, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6898733973503113, "alphanum_fraction": 0.6913118362426758, "avg_line_length": 50.117645263671875, "blob_id": "4442b47470dc1297a586c9f692374b8b49276401", "content_id": "90404c23e0eb29d02e42a5988c1b38175b089d5a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3476, "license_type": "permissive", "max_line_length": 270, "num_lines": 68, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_applicationprofile.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure ApplicationProfile object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_applicationprofile < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Object, nil] User defined description for the object.\n attribute :description\n\n # @return [Object, nil] Specifies various dns service related controls for virtual service.\n attribute :dns_service_profile\n\n # @return [Object, nil] Specifies various security related controls for virtual service.\n attribute :dos_rl_profile\n\n # @return [Hash, nil] Specifies the http application proxy profile parameters.\n attribute :http_profile\n validates :http_profile, type: Hash\n\n # @return [String] The name of the application profile.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Symbol, nil] Specifies if client ip needs to be preserved for backend connection.,Not compatible with connection multiplexing.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :preserve_client_ip\n validates :preserve_client_ip, type: Symbol\n\n # @return [Symbol, nil] Specifies if we need to preserve client port while preseving client ip for backend connections.,Field introduced in 17.2.7.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :preserve_client_port\n validates :preserve_client_port, type: Symbol\n\n # @return [Object, nil] Specifies the tcp application proxy profile parameters.\n attribute :tcp_app_profile\n\n # @return [String, nil] It is a reference to an object of type tenant.\n attribute :tenant_ref\n validates :tenant_ref, type: String\n\n # @return [String] Specifies which application layer proxy is enabled for the virtual service.,Enum options - APPLICATION_PROFILE_TYPE_L4, APPLICATION_PROFILE_TYPE_HTTP, APPLICATION_PROFILE_TYPE_SYSLOG, APPLICATION_PROFILE_TYPE_DNS,,APPLICATION_PROFILE_TYPE_SSL.\n attribute :type\n validates :type, presence: true, type: String\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Uuid of the application profile.\n attribute :uuid\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6773675680160522, "alphanum_fraction": 0.6773675680160522, "avg_line_length": 28.66666603088379, "blob_id": "5e4f142bf432c0e4df7121963aff0f9a0a896025", "content_id": "d27c10093e9f951bf523ef3711486773567d0735", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 623, "license_type": "permissive", "max_line_length": 109, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/remote_management/oneview/oneview_datacenter_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Retrieve facts about the OneView Data Centers.\n class Oneview_datacenter_facts < Base\n # @return [String, nil] Data Center name.\n attribute :name\n validates :name, type: String\n\n # @return [Array<String>, String, nil] Retrieve additional facts. Options available: 'visualContent'.\n attribute :options\n validates :options, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.713491678237915, "alphanum_fraction": 0.713491678237915, "avg_line_length": 67.24137878417969, "blob_id": "f4fa2b3310da01cb734b5ad6e58b67d192a2315b", "content_id": "c6a3da74b09ecb9ee9029f1dbf001db4132d85a5", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1979, "license_type": "permissive", "max_line_length": 447, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_host_acceptance.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to manage acceptance level of an ESXi host.\n class Vmware_host_acceptance < Base\n # @return [String, nil] Name of the cluster.,Acceptance level of all ESXi host system in the given cluster will be managed.,If C(esxi_hostname) is not given, this parameter is required.\n attribute :cluster_name\n validates :cluster_name, type: String\n\n # @return [String, nil] ESXi hostname.,Acceptance level of this ESXi host system will be managed.,If C(cluster_name) is not given, this parameter is required.\n attribute :esxi_hostname\n validates :esxi_hostname, type: String\n\n # @return [:list, :present, nil] Set or list acceptance level of the given ESXi host.,If set to C(list), then will return current acceptance level of given host system/s.,If set to C(present), then will set given acceptance level.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:list, :present], :message=>\"%{value} needs to be :list, :present\"}, allow_nil: true\n\n # @return [:community, :partner, :vmware_accepted, :vmware_certified, nil] Name of acceptance level.,If set to C(partner), then accept only partner and VMware signed and certified VIBs.,If set to C(vmware_certified), then accept only VIBs that are signed and certified by VMware.,If set to C(vmware_accepted), then accept VIBs that have been accepted by VMware.,If set to C(community), then accept all VIBs, even those that are not signed.\n attribute :acceptance_level\n validates :acceptance_level, expression_inclusion: {:in=>[:community, :partner, :vmware_accepted, :vmware_certified], :message=>\"%{value} needs to be :community, :partner, :vmware_accepted, :vmware_certified\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6858710646629333, "alphanum_fraction": 0.6858710646629333, "avg_line_length": 30.69565200805664, "blob_id": "cfc42a49ab543965dbb1cf338353def67005d2ec", "content_id": "b0c9c793622230e726e5521db2a5910bcec41358", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 729, "license_type": "permissive", "max_line_length": 146, "num_lines": 23, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_subnets_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Retrieve facts about one or more subnets from OpenStack.\n class Os_subnets_facts < Base\n # @return [Object, nil] Name or ID of the subnet\n attribute :subnet\n\n # @return [Hash, nil] A dictionary of meta data to use for further filtering. Elements of this dictionary may be additional dictionaries.\n attribute :filters\n validates :filters, type: Hash\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6644859910011292, "alphanum_fraction": 0.6724299192428589, "avg_line_length": 46.55555725097656, "blob_id": "ee474671943b8472542239f75f654c30841d7f46", "content_id": "510e0338bf9b91bc124e1179a6201fedee667106", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2140, "license_type": "permissive", "max_line_length": 253, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_dvswitch.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or remove a distributed vSwitch\n class Vmware_dvswitch < Base\n # @return [String] The name of the datacenter that will contain the dvSwitch\n attribute :datacenter_name\n validates :datacenter_name, presence: true, type: String\n\n # @return [String] The name of the switch to create or remove\n attribute :switch_name\n validates :switch_name, presence: true, type: String\n\n # @return [String, nil] The version of the switch to create. Can be 6.5.0, 6.0.0, 5.5.0, 5.1.0, 5.0.0 with a vcenter running vSphere 6.5,Needed if you have a vcenter version > ESXi version to join DVS. If not specified version=version of vcenter\n attribute :switch_version\n validates :switch_version, type: String\n\n # @return [Integer] The switch maximum transmission unit\n attribute :mtu\n validates :mtu, presence: true, type: Integer\n\n # @return [Integer] Quantity of uplink per ESXi host added to the switch\n attribute :uplink_quantity\n validates :uplink_quantity, presence: true, type: Integer\n\n # @return [:cdp, :lldp] Link discovery protocol between Cisco and Link Layer discovery\n attribute :discovery_proto\n validates :discovery_proto, presence: true, expression_inclusion: {:in=>[:cdp, :lldp], :message=>\"%{value} needs to be :cdp, :lldp\"}\n\n # @return [:both, :none, :advertise, :listen, nil] Select the discovery operation\n attribute :discovery_operation\n validates :discovery_operation, expression_inclusion: {:in=>[:both, :none, :advertise, :listen], :message=>\"%{value} needs to be :both, :none, :advertise, :listen\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Create or remove dvSwitch\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6946075558662415, "alphanum_fraction": 0.6956753730773926, "avg_line_length": 47.02564239501953, "blob_id": "2a39dca186d2cc2e71c1ac772888a7454df00d76", "content_id": "7d426303f0f570bf7bbd17243dda3445845ea170", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1873, "license_type": "permissive", "max_line_length": 322, "num_lines": 39, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/sns_topic.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The C(sns_topic) module allows you to create, delete, and manage subscriptions for AWS SNS topics. As of 2.6, this module can be use to subscribe and unsubscribe to topics outside of your AWS account.\n class Sns_topic < Base\n # @return [String] The name or ARN of the SNS topic to manage\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, nil] Whether to create or destroy an SNS topic\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] Display name of the topic\n attribute :display_name\n validates :display_name, type: String\n\n # @return [Object, nil] Policy to apply to the SNS topic\n attribute :policy\n\n # @return [Hash, nil] Delivery policy to apply to the SNS topic\n attribute :delivery_policy\n validates :delivery_policy, type: Hash\n\n # @return [Object, nil] List of subscriptions to apply to the topic. Note that AWS requires subscriptions to be confirmed, so you will need to confirm any new subscriptions.\n attribute :subscriptions\n\n # @return [String, nil] Whether to purge any subscriptions not listed here. NOTE: AWS does not allow you to purge any PendingConfirmation subscriptions, so if any exist and would be purged, they are silently skipped. This means that somebody could come back later and confirm the subscription. Sorry. Blame Amazon.\n attribute :purge_subscriptions\n validates :purge_subscriptions, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6270053386688232, "alphanum_fraction": 0.6270053386688232, "avg_line_length": 24.79310417175293, "blob_id": "970fe684ff15928d338b08d381e303441cf46adb", "content_id": "11db77a74fca6ee5dbbe922f4f36d1febdde23b6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 748, "license_type": "permissive", "max_line_length": 54, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/notification/logentries_msg.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Send a message to logentries\n class Logentries_msg < Base\n # @return [String] Log token.\n attribute :token\n validates :token, presence: true, type: String\n\n # @return [String] The message body.\n attribute :msg\n validates :msg, presence: true, type: String\n\n # @return [String, nil] API endpoint\n attribute :api\n validates :api, type: String\n\n # @return [Integer, nil] API endpoint port\n attribute :port\n validates :port, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5613305568695068, "alphanum_fraction": 0.5620235800743103, "avg_line_length": 22.655736923217773, "blob_id": "6b28f35b7f4d167bbe49ee8f25ee13ad45fdad1c", "content_id": "921e1deaba8382f3e1b63ff773a9204730b3e11c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1443, "license_type": "permissive", "max_line_length": 109, "num_lines": 61, "path": "/lib/ansible/ruby/dsl_builders/base.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'ansible/ruby/models/jinja_expression'\n\nmodule Ansible\n module Ruby\n module DslBuilders\n class Base\n def initialize\n @result = nil\n end\n\n def _result\n @result\n end\n\n def respond_to_missing?(*)\n super\n end\n\n def jinja(text)\n Ansible::Ruby::Models::JinjaExpression.new(text)\n end\n\n # For the DSL, don't want to defer to regular method_missing\n def method_missing(id, *args, &block)\n result = _process_method id, *args, &block\n method_missing_return id, result, *args\n end\n\n private\n\n def _ansible_include(filename, &block)\n inclusion = Models::Inclusion.new(file: filename)\n if block\n args_builder = Args.new inclusion\n args_builder.instance_eval(&block)\n end\n inclusion\n end\n\n def _valid_attributes\n (self.class.instance_methods - Object.instance_methods - %i[_result method_missing validate?]).sort\n end\n\n def no_method_error(method, only_valid_clause)\n raise \"Invalid method/local variable `#{method}'. #{only_valid_clause}\"\n end\n\n def method_missing_return(*)\n # Don't leak return values\n nil\n end\n\n def _implicit_bool(args)\n args.empty? || args[0]\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7171401977539062, "alphanum_fraction": 0.7171401977539062, "avg_line_length": 63.060001373291016, "blob_id": "6323f4510c884ed8af2e8725a5f232e2f0c674c6", "content_id": "a02998c740f9e8bf3d1d26cfa360d963d3cb761d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3203, "license_type": "permissive", "max_line_length": 328, "num_lines": 50, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_auth.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module authenticates to oVirt/RHV engine and creates SSO token, which should be later used in all other oVirt/RHV modules, so all modules don't need to perform login and logout. This module returns an Ansible fact called I(ovirt_auth). Every module can use this fact as C(auth) parameter, to perform authentication.\n class Ovirt_auth < Base\n # @return [:present, :absent, nil] Specifies if a token should be created or revoked.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] The name of the user. For example: I(admin@internal) Default value is set by I(OVIRT_USERNAME) environment variable.\n attribute :username\n\n # @return [Object, nil] The password of the user. Default value is set by I(OVIRT_PASSWORD) environment variable.\n attribute :password\n\n # @return [Object, nil] SSO token to be used instead of login with username/password. Default value is set by I(OVIRT_TOKEN) environment variable.\n attribute :token\n\n # @return [Object, nil] A string containing the API URL of the server. For example: I(https://server.example.com/ovirt-engine/api). Default value is set by I(OVIRT_URL) environment variable.,Either C(url) or C(hostname) is required.\n attribute :url\n\n # @return [Object, nil] A string containing the hostname of the server. For example: I(server.example.com). Default value is set by I(OVIRT_HOSTNAME) environment variable.,Either C(url) or C(hostname) is required.\n attribute :hostname\n\n # @return [Object, nil] A boolean flag that indicates if the server TLS certificate and host name should be checked.\n attribute :insecure\n\n # @return [Object, nil] A PEM file containing the trusted CA certificates. The certificate presented by the server will be verified using these CA certificates. If C(ca_file) parameter is not set, system wide CA certificate store is used. Default value is set by I(OVIRT_CAFILE) environment variable.\n attribute :ca_file\n\n # @return [Object, nil] The maximum total time to wait for the response, in seconds. A value of zero (the default) means wait forever. If the timeout expires before the response is received an exception will be raised.\n attribute :timeout\n\n # @return [Object, nil] A boolean flag indicating if the SDK should ask the server to send compressed responses. The default is I(True). Note that this is a hint for the server, and that it may return uncompressed data even when this parameter is set to I(True).\n attribute :compress\n\n # @return [Object, nil] A boolean flag indicating if Kerberos authentication should be used instead of the default basic authentication.\n attribute :kerberos\n\n # @return [Object, nil] A dictionary of HTTP headers to be added to each API call.\n attribute :headers\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.69834965467453, "alphanum_fraction": 0.6989609003067017, "avg_line_length": 52.63934326171875, "blob_id": "480a4badc903492192a172977085bbc9771d7538", "content_id": "e75be399da8d3a1a2d70c5b13968de49f183c87b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3272, "license_type": "permissive", "max_line_length": 232, "num_lines": 61, "path": "/lib/ansible/ruby/modules/generated/cloud/misc/terraform.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Provides support for deploying resources with Terraform and pulling resource information back into Ansible.\n class Terraform < Base\n # @return [:planned, :present, :absent, nil] Goal state of given stage/project\n attribute :state\n validates :state, expression_inclusion: {:in=>[:planned, :present, :absent], :message=>\"%{value} needs to be :planned, :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] The path of a terraform binary to use, relative to the 'service_path' unless you supply an absolute path.\n attribute :binary_path\n\n # @return [String] The path to the root of the Terraform directory with the vars.tf/main.tf/etc to use.\n attribute :project_path\n validates :project_path, presence: true, type: String\n\n # @return [String, nil] The terraform workspace to work with.\n attribute :workspace\n validates :workspace, type: String\n\n # @return [Symbol, nil] Only works with state = absent,If true, the workspace will be deleted after the \"terraform destroy\" action.,The 'default' workspace will not be deleted.\n attribute :purge_workspace\n validates :purge_workspace, type: Symbol\n\n # @return [Object, nil] The path to an existing Terraform plan file to apply. If this is not specified, Ansible will build a new TF plan and execute it. Note that this option is required if 'state' has the 'planned' value.\n attribute :plan_file\n\n # @return [Object, nil] The path to an existing Terraform state file to use when building plan. If this is not specified, the default `terraform.tfstate` will be used.,This option is ignored when plan is specified.\n attribute :state_file\n\n # @return [Object, nil] The path to a variables file for Terraform to fill into the TF configurations.\n attribute :variables_file\n\n # @return [Object, nil] A group of key-values to override template variables or those in variables files.\n attribute :variables\n\n # @return [Object, nil] A list of specific resources to target in this plan/application. The resources selected here will also auto-include any dependencies.\n attribute :targets\n\n # @return [Object, nil] Enable statefile locking, if you use a service that accepts locks (such as S3+DynamoDB) to store your statefile.\n attribute :lock\n\n # @return [Object, nil] How long to maintain the lock on the statefile, if you use a service that accepts locks (such as S3+DynamoDB).\n attribute :lock_timeout\n\n # @return [Symbol, nil] To avoid duplicating infra, if a state file can't be found this will force a `terraform init`. Generally, this should be turned off unless you intend to provision an entirely new Terraform deployment.\n attribute :force_init\n validates :force_init, type: Symbol\n\n # @return [Hash, nil] A group of key-values to provide at init stage to the -backend-config parameter.\n attribute :backend_config\n validates :backend_config, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6837443709373474, "alphanum_fraction": 0.690170168876648, "avg_line_length": 56.58000183105469, "blob_id": "596ccf18a7a62f3b6fb2ef8ebf02f9517bde1f2a", "content_id": "b1212ec33daef3cf860f1ef772656cf04355fe7c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5758, "license_type": "permissive", "max_line_length": 306, "num_lines": 100, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_bgp_neighbor.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages BGP neighbors configurations on NX-OS switches.\n class Nxos_bgp_neighbor < Base\n # @return [Integer] BGP autonomous system number. Valid values are string, Integer in ASPLAIN or ASDOT notation.\n attribute :asn\n validates :asn, presence: true, type: Integer\n\n # @return [String, nil] Name of the VRF. The name 'default' is a valid VRF representing the global bgp.\n attribute :vrf\n validates :vrf, type: String\n\n # @return [String] Neighbor Identifier. Valid values are string. Neighbors may use IPv4 or IPv6 notation, with or without prefix length.\n attribute :neighbor\n validates :neighbor, presence: true, type: String\n\n # @return [String, nil] Description of the neighbor.\n attribute :description\n validates :description, type: String\n\n # @return [Symbol, nil] Configure whether or not to check for directly connected peer.\n attribute :connected_check\n validates :connected_check, type: Symbol\n\n # @return [Symbol, nil] Configure whether or not to negotiate capability with this neighbor.\n attribute :capability_negotiation\n validates :capability_negotiation, type: Symbol\n\n # @return [Symbol, nil] Configure whether or not to enable dynamic capability.\n attribute :dynamic_capability\n validates :dynamic_capability, type: Symbol\n\n # @return [Object, nil] Specify multihop TTL for a remote peer. Valid values are integers between 2 and 255, or keyword 'default' to disable this property.\n attribute :ebgp_multihop\n\n # @return [Integer, nil] Specify the local-as number for the eBGP neighbor. Valid values are String or Integer in ASPLAIN or ASDOT notation, or 'default', which means not to configure it.\n attribute :local_as\n validates :local_as, type: Integer\n\n # @return [:enable, :disable, :inherit, nil] Specify whether or not to enable log messages for neighbor up/down event.\n attribute :log_neighbor_changes\n validates :log_neighbor_changes, expression_inclusion: {:in=>[:enable, :disable, :inherit], :message=>\"%{value} needs to be :enable, :disable, :inherit\"}, allow_nil: true\n\n # @return [Symbol, nil] Specify whether or not to shut down this neighbor under memory pressure.\n attribute :low_memory_exempt\n validates :low_memory_exempt, type: Symbol\n\n # @return [Object, nil] Specify Maximum number of peers for this neighbor prefix Valid values are between 1 and 1000, or 'default', which does not impose the limit. Note that this parameter is accepted only on neighbors with address/prefix.\n attribute :maximum_peers\n\n # @return [Object, nil] Specify the password for neighbor. Valid value is string.\n attribute :pwd\n\n # @return [:\"3des\", :cisco_type_7, :default, nil] Specify the encryption type the password will use. Valid values are '3des' or 'cisco_type_7' encryption or keyword 'default'.\n attribute :pwd_type\n validates :pwd_type, expression_inclusion: {:in=>[:\"3des\", :cisco_type_7, :default], :message=>\"%{value} needs to be :\\\"3des\\\", :cisco_type_7, :default\"}, allow_nil: true\n\n # @return [Integer, nil] Specify Autonomous System Number of the neighbor. Valid values are String or Integer in ASPLAIN or ASDOT notation, or 'default', which means not to configure it.\n attribute :remote_as\n validates :remote_as, type: Integer\n\n # @return [:enable, :disable, :all, :\"replace-as\", nil] Specify the config to remove private AS number from outbound updates. Valid values are 'enable' to enable this config, 'disable' to disable this config, 'all' to remove all private AS number, or 'replace-as', to replace the private AS number.\n attribute :remove_private_as\n validates :remove_private_as, expression_inclusion: {:in=>[:enable, :disable, :all, :\"replace-as\"], :message=>\"%{value} needs to be :enable, :disable, :all, :\\\"replace-as\\\"\"}, allow_nil: true\n\n # @return [Symbol, nil] Configure to administratively shutdown this neighbor.\n attribute :shutdown\n validates :shutdown, type: Symbol\n\n # @return [Symbol, nil] Configure to suppress 4-byte AS Capability.\n attribute :suppress_4_byte_as\n validates :suppress_4_byte_as, type: Symbol\n\n # @return [Object, nil] Specify keepalive timer value. Valid values are integers between 0 and 3600 in terms of seconds, or 'default', which is 60.\n attribute :timers_keepalive\n\n # @return [Object, nil] Specify holdtime timer value. Valid values are integers between 0 and 3600 in terms of seconds, or 'default', which is 180.\n attribute :timers_holdtime\n\n # @return [Symbol, nil] Specify whether or not to only allow passive connection setup. Valid values are 'true', 'false', and 'default', which defaults to 'false'. This property can only be configured when the neighbor is in 'ip' address format without prefix length.\n attribute :transport_passive_only\n validates :transport_passive_only, type: Symbol\n\n # @return [String, nil] Specify source interface of BGP session and updates.\n attribute :update_source\n validates :update_source, type: String\n\n # @return [:present, :absent, nil] Determines whether the config should be present or not on the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6559727191925049, "alphanum_fraction": 0.6559727191925049, "avg_line_length": 38.5945930480957, "blob_id": "fc4885777b6f285d775c7994f9174b643dfa9a12", "content_id": "5f741c9eaac37b0bc35dc69eb7c2139e70746470", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1465, "license_type": "permissive", "max_line_length": 183, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_net_ifgrp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, modify, destroy the network interface group\n class Na_ontap_net_ifgrp < Base\n # @return [:present, :absent, nil] Whether the specified network interface group should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:mac, :ip, :sequential, :port, nil] Specifies the traffic distribution function for the ifgrp.\n attribute :distribution_function\n validates :distribution_function, expression_inclusion: {:in=>[:mac, :ip, :sequential, :port], :message=>\"%{value} needs to be :mac, :ip, :sequential, :port\"}, allow_nil: true\n\n # @return [String] Specifies the interface group name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Specifies the link policy for the ifgrp.\n attribute :mode\n validates :mode, type: String\n\n # @return [String] Specifies the name of node.\n attribute :node\n validates :node, presence: true, type: String\n\n # @return [String, nil] Adds the specified port.\n attribute :port\n validates :port, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6706444025039673, "alphanum_fraction": 0.6706444025039673, "avg_line_length": 23.647058486938477, "blob_id": "c49a959da9fd2f4fa55c567187cf2b51de92f16b", "content_id": "870e7d7a7b0711cccdec9df46ea8250e6fc3066d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 419, "license_type": "permissive", "max_line_length": 55, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_vtp_domain.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages VTP domain configuration.\n class Nxos_vtp_domain < Base\n # @return [String] VTP domain name.\n attribute :domain\n validates :domain, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.623481810092926, "alphanum_fraction": 0.637651801109314, "avg_line_length": 22.5238094329834, "blob_id": "1c2bf06649996d56cf1f499377144dac8b903f2c", "content_id": "2567f75c16874883f198a5f7d1922cacfb1bf1fd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 494, "license_type": "permissive", "max_line_length": 66, "num_lines": 21, "path": "/lib/ansible/ruby/modules/custom/packaging/language/pear.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# VALIDATED_CHECKSUM: aIM1dczpLFU2xMaIijCkTmi54/yEPZKaE3hO5Lja5bo=\n\nrequire 'ansible/ruby/modules/generated/packaging/language/pear'\n\nmodule Ansible\n module Ruby\n module Modules\n class Pear\n def to_h\n from_super = super\n pear_module = from_super[:pear]\n # Pear seems to insist on things being a CSV\n pear_module[:name] = pear_module[:name].join(',')\n from_super\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7154046893119812, "alphanum_fraction": 0.7519582509994507, "avg_line_length": 20.27777862548828, "blob_id": "2f9671ea7404a8e0798555f2f721a8fb4022ee63", "content_id": "6da568cac2c962970b83b6b2ecafc24943a316fe", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 383, "license_type": "permissive", "max_line_length": 66, "num_lines": 18, "path": "/lib/ansible/ruby/modules/custom/files/template.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# VALIDATED_CHECKSUM: Y5k5kRNhmLW2sw11h4w0+z33tsgENS/mFz4+H1I0N38=\n\n# see LICENSE.txt in project root\n\nrequire 'ansible/ruby/modules/generated/files/template'\nrequire 'ansible/ruby/modules/helpers/file_attributes'\n\nmodule Ansible\n module Ruby\n module Modules\n class Template\n include Helpers::FileAttributes\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7195308804512024, "alphanum_fraction": 0.7236104011535645, "avg_line_length": 64.36666870117188, "blob_id": "7be693de21cb127f5a47b2b6da15c11437bcf9ba", "content_id": "4a5612e99c4b30bbfb330901fe9f4b1400580392", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1961, "license_type": "permissive", "max_line_length": 458, "num_lines": 30, "path": "/lib/ansible/ruby/modules/generated/network/netconf/netconf_rpc.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # NETCONF is a network management protocol developed and standardized by the IETF. It is documented in RFC 6241.\n # This module allows the user to execute NETCONF RPC requests as defined by IETF RFC standards as well as proprietary requests.\n class Netconf_rpc < Base\n # @return [String, nil] This argument specifies the request (name of the operation) to be executed on the remote NETCONF enabled device.\n attribute :rpc\n validates :rpc, type: String\n\n # @return [String, nil] NETCONF operations not defined in rfc6241 typically require the appropriate XML namespace to be set. In the case the I(request) option is not already provided in XML format, the namespace can be defined by the I(xmlns) option.\n attribute :xmlns\n validates :xmlns, type: String\n\n # @return [Hash, String, nil] This argument specifies the optional request content (all RPC attributes). The I(content) value can either be provided as XML formatted string or as dictionary.\n attribute :content\n validates :content, type: MultipleTypes.new(Hash, String)\n\n # @return [:json, :pretty, :xml, nil] Encoding scheme to use when serializing output from the device. The option I(json) will serialize the output as JSON data. If the option value is I(json) it requires jxmlease to be installed on control node. The option I(pretty) is similar to received XML response but is using human readable format (spaces, new lines). The option value I(xml) is similar to received XML response but removes all XML namespaces.\n attribute :display\n validates :display, expression_inclusion: {:in=>[:json, :pretty, :xml], :message=>\"%{value} needs to be :json, :pretty, :xml\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6619468927383423, "alphanum_fraction": 0.6619468927383423, "avg_line_length": 25.904762268066406, "blob_id": "29f9aadbe500fb3ce722ec2d1bc795eab74982f9", "content_id": "1a75cefad5b8e7e17bc939a8076db41b6528866b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 565, "license_type": "permissive", "max_line_length": 73, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/database/mysql/mysql_variables.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Query / Set MySQL variables\n class Mysql_variables < Base\n # @return [String] Variable name to operate\n attribute :variable\n validates :variable, presence: true, type: String\n\n # @return [Integer, nil] If set, then sets variable value to this\n attribute :value\n validates :value, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6784325242042542, "alphanum_fraction": 0.6826204061508179, "avg_line_length": 57.64912414550781, "blob_id": "9b819fe8606192d54dff85732f5491285f64b0ed", "content_id": "208fdbda3bf081a9c79d3351de692185718a6272", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3343, "license_type": "permissive", "max_line_length": 281, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/net_tools/haproxy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Enable, disable, drain and set weights for HAProxy backend servers using socket commands.\n class Haproxy < Base\n # @return [String, nil] Name of the HAProxy backend pool.\n attribute :backend\n validates :backend, type: String\n\n # @return [Boolean, nil] Wait until the server has no active connections or until the timeout determined by wait_interval and wait_retries is reached. Continue only after the status changes to 'MAINT'. This overrides the shutdown_sessions option.\n attribute :drain\n validates :drain, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String] Name of the backend host to change.\n attribute :host\n validates :host, presence: true, type: String\n\n # @return [:yes, :no, nil] When disabling a server, immediately terminate all the sessions attached to the specified server. This can be used to terminate long-running sessions after a server is put into maintenance mode. Overridden by the drain option.\n attribute :shutdown_sessions\n validates :shutdown_sessions, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Path to the HAProxy socket file.\n attribute :socket\n validates :socket, type: String\n\n # @return [:enabled, :disabled, :drain] Desired state of the provided backend host.,Note that C(drain) state was added in version 2.4. It is supported only by HAProxy version 1.5 or later, if used on versions < 1.5, it will be ignored.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:enabled, :disabled, :drain], :message=>\"%{value} needs to be :enabled, :disabled, :drain\"}\n\n # @return [:yes, :no, nil] Fail whenever trying to enable/disable a backend host that does not exist\n attribute :fail_on_not_found\n validates :fail_on_not_found, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Wait until the server reports a status of 'UP' when `state=enabled`, status of 'MAINT' when `state=disabled` or status of 'DRAIN' when `state=drain`\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Number of seconds to wait between retries.\n attribute :wait_interval\n validates :wait_interval, type: Integer\n\n # @return [Integer, nil] Number of times to check for status after changing the state.\n attribute :wait_retries\n validates :wait_retries, type: Integer\n\n # @return [Integer, nil] The value passed in argument. If the value ends with the `%` sign, then the new weight will be relative to the initially configured weight. Relative weights are only permitted between 0 and 100% and absolute weights are permitted between 0 and 256.\n attribute :weight\n validates :weight, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6794871687889099, "alphanum_fraction": 0.6929824352264404, "avg_line_length": 51, "blob_id": "7471234334174deeced05b4a2486593b3d72a434", "content_id": "45c0e32198a69783ed4c02140a25774c447f91af", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2964, "license_type": "permissive", "max_line_length": 410, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_compute_vpn_tunnel.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # VPN tunnel resource.\n class Gcp_compute_vpn_tunnel < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] Name of the resource. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] An optional description of this resource.\n attribute :description\n\n # @return [String] URL of the Target VPN gateway with which this VPN tunnel is associated.\n attribute :target_vpn_gateway\n validates :target_vpn_gateway, presence: true, type: String\n\n # @return [String, nil] URL of router resource to be used for dynamic routing.\n attribute :router\n validates :router, type: String\n\n # @return [Object] IP address of the peer VPN gateway. Only IPv4 is supported.\n attribute :peer_ip\n validates :peer_ip, presence: true\n\n # @return [String] Shared secret used to set the secure session between the Cloud VPN gateway and the peer VPN gateway.\n attribute :shared_secret\n validates :shared_secret, presence: true, type: String\n\n # @return [Integer, nil] IKE protocol version to use when establishing the VPN tunnel with peer VPN gateway.,Acceptable IKE versions are 1 or 2. Default version is 2.\n attribute :ike_version\n validates :ike_version, type: Integer\n\n # @return [Object, nil] Local traffic selector to use when establishing the VPN tunnel with peer VPN gateway. The value should be a CIDR formatted string, for example `192.168.0.0/16`. The ranges should be disjoint.,Only IPv4 is supported.\n attribute :local_traffic_selector\n\n # @return [Object, nil] Remote traffic selector to use when establishing the VPN tunnel with peer VPN gateway. The value should be a CIDR formatted string, for example `192.168.0.0/16`. The ranges should be disjoint.,Only IPv4 is supported.\n attribute :remote_traffic_selector\n\n # @return [Object, nil] Labels to apply to this VpnTunnel.\n attribute :labels\n\n # @return [String] The region where the tunnel is located.\n attribute :region\n validates :region, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6039156913757324, "alphanum_fraction": 0.6054216623306274, "avg_line_length": 21.133333206176758, "blob_id": "a40dc05cc11c4c24d2d3f3976944624b033fadc9", "content_id": "0621a1176511a799853eee25906a6a43ba93a89f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 664, "license_type": "permissive", "max_line_length": 89, "num_lines": 30, "path": "/lib/ansible/ruby/models/block.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# see LICENSE.txt in project root\n\nrequire 'ansible/ruby/models/unit'\n\nmodule Ansible\n module Ruby\n module Models\n class Block < Unit\n attribute :tasks\n validates :tasks, type: TypeGeneric.new(Task)\n validate :enough_tasks\n\n def to_h\n # we put the list of tasks directly under the block in Ansible\n result = super\n tasks = result.delete :tasks\n { block: tasks }.merge result\n end\n\n private\n\n def enough_tasks\n errors.add :tasks, 'Must have at least 1 task in your block!' unless tasks.any?\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7122092843055725, "alphanum_fraction": 0.7325581312179565, "avg_line_length": 20.5, "blob_id": "ffa5560dac890d8abfbb6a13065255e78cd7baee", "content_id": "1e19569076467ae527a2e32bb922cadf51068b77", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 344, "license_type": "permissive", "max_line_length": 66, "num_lines": 16, "path": "/lib/ansible/ruby/modules/custom/utilities/logic/pause.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# VALIDATED_CHECKSUM: WaJ22CPnF/LKe3asnez70grWnKeUYzcT7cP2ZcgHswo=\n\nrequire 'ansible/ruby/modules/generated/utilities/logic/pause'\n\nmodule Ansible\n module Ruby\n module Modules\n class Pause\n remove_existing_validations :seconds\n validates :seconds, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6913161277770996, "alphanum_fraction": 0.6991859078407288, "avg_line_length": 58.918697357177734, "blob_id": "a6916068d33c0f5a78052b473e5f56f5c27fabd3", "content_id": "6f0a3bfa6461a7bb807ba2d3a4c7f0a687aa1ce1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 7370, "license_type": "permissive", "max_line_length": 462, "num_lines": 123, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_bgp_af.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages BGP Address-family configurations on NX-OS switches.\n class Nxos_bgp_af < Base\n # @return [Integer] BGP autonomous system number. Valid values are String, Integer in ASPLAIN or ASDOT notation.\n attribute :asn\n validates :asn, presence: true, type: Integer\n\n # @return [String] Name of the VRF. The name 'default' is a valid VRF representing the global bgp.\n attribute :vrf\n validates :vrf, presence: true, type: String\n\n # @return [:ipv4, :ipv6, :vpnv4, :vpnv6, :l2vpn] Address Family Identifier.\n attribute :afi\n validates :afi, presence: true, expression_inclusion: {:in=>[:ipv4, :ipv6, :vpnv4, :vpnv6, :l2vpn], :message=>\"%{value} needs to be :ipv4, :ipv6, :vpnv4, :vpnv6, :l2vpn\"}\n\n # @return [:unicast, :multicast, :evpn] Sub Address Family Identifier.\n attribute :safi\n validates :safi, presence: true, expression_inclusion: {:in=>[:unicast, :multicast, :evpn], :message=>\"%{value} needs to be :unicast, :multicast, :evpn\"}\n\n # @return [Symbol, nil] Install a backup path into the forwarding table and provide prefix independent convergence (PIC) in case of a PE-CE link failure.\n attribute :additional_paths_install\n validates :additional_paths_install, type: Symbol\n\n # @return [Symbol, nil] Enables the receive capability of additional paths for all of the neighbors under this address family for which the capability has not been disabled.\n attribute :additional_paths_receive\n validates :additional_paths_receive, type: Symbol\n\n # @return [Object, nil] Configures the capability of selecting additional paths for a prefix. Valid values are a string defining the name of the route-map.\n attribute :additional_paths_selection\n\n # @return [Symbol, nil] Enables the send capability of additional paths for all of the neighbors under this address family for which the capability has not been disabled.\n attribute :additional_paths_send\n validates :additional_paths_send, type: Symbol\n\n # @return [Symbol, nil] Advertise evpn routes.\n attribute :advertise_l2vpn_evpn\n validates :advertise_l2vpn_evpn, type: Symbol\n\n # @return [Symbol, nil] Configure client-to-client route reflection.\n attribute :client_to_client\n validates :client_to_client, type: Symbol\n\n # @return [Object, nil] Specify dampen value for IGP metric-related changes, in seconds. Valid values are integer and keyword 'default'.\n attribute :dampen_igp_metric\n\n # @return [Symbol, nil] Enable/disable route-flap dampening.\n attribute :dampening_state\n validates :dampening_state, type: Symbol\n\n # @return [Object, nil] Specify decay half-life in minutes for route-flap dampening. Valid values are integer and keyword 'default'.\n attribute :dampening_half_time\n\n # @return [Object, nil] Specify max suppress time for route-flap dampening stable route. Valid values are integer and keyword 'default'.\n attribute :dampening_max_suppress_time\n\n # @return [Object, nil] Specify route reuse time for route-flap dampening. Valid values are integer and keyword 'default'.\n attribute :dampening_reuse_time\n\n # @return [Object, nil] Specify route-map for route-flap dampening. Valid values are a string defining the name of the route-map.\n attribute :dampening_routemap\n\n # @return [Object, nil] Specify route suppress time for route-flap dampening. Valid values are integer and keyword 'default'.\n attribute :dampening_suppress_time\n\n # @return [Symbol, nil] Default information originate.\n attribute :default_information_originate\n validates :default_information_originate, type: Symbol\n\n # @return [Object, nil] Sets default metrics for routes redistributed into BGP. Valid values are Integer or keyword 'default'\n attribute :default_metric\n\n # @return [Object, nil] Sets the administrative distance for eBGP routes. Valid values are Integer or keyword 'default'.\n attribute :distance_ebgp\n\n # @return [Object, nil] Sets the administrative distance for iBGP routes. Valid values are Integer or keyword 'default'.\n attribute :distance_ibgp\n\n # @return [Object, nil] Sets the administrative distance for local BGP routes. Valid values are Integer or keyword 'default'.\n attribute :distance_local\n\n # @return [Object, nil] An array of route-map names which will specify prefixes to inject. Each array entry must first specify the inject-map name, secondly an exist-map name, and optionally the copy-attributes keyword which indicates that attributes should be copied from the aggregate. For example [['lax_inject_map', 'lax_exist_map'], ['nyc_inject_map', 'nyc_exist_map', 'copy-attributes'], ['fsd_inject_map', 'fsd_exist_map']].\n attribute :inject_map\n\n # @return [Object, nil] Configures the maximum number of equal-cost paths for load sharing. Valid value is an integer in the range 1-64.\n attribute :maximum_paths\n\n # @return [Object, nil] Configures the maximum number of ibgp equal-cost paths for load sharing. Valid value is an integer in the range 1-64.\n attribute :maximum_paths_ibgp\n\n # @return [Object, nil] Networks to configure. Valid value is a list of network prefixes to advertise. The list must be in the form of an array. Each entry in the array must include a prefix address and an optional route-map. For example [['10.0.0.0/16', 'routemap_LA'], ['192.168.1.1', 'Chicago'], ['192.168.2.0/24'], ['192.168.3.0/24', 'routemap_NYC']].\n attribute :networks\n\n # @return [Object, nil] Configure a route-map for valid nexthops. Valid values are a string defining the name of the route-map.\n attribute :next_hop_route_map\n\n # @return [Object, nil] A list of redistribute directives. Multiple redistribute entries are allowed. The list must be in the form of a nested array. the first entry of each array defines the source-protocol to redistribute from; the second entry defines a route-map name. A route-map is highly advised but may be optional on some platforms, in which case it may be omitted from the array list. For example [['direct', 'rm_direct'], ['lisp', 'rm_lisp']].\n attribute :redistribute\n\n # @return [Symbol, nil] Advertises only active routes to peers.\n attribute :suppress_inactive\n validates :suppress_inactive, type: Symbol\n\n # @return [Object, nil] Apply table-map to filter routes downloaded into URIB. Valid values are a string.\n attribute :table_map\n\n # @return [Symbol, nil] Filters routes rejected by the route-map and does not download them to the RIB.\n attribute :table_map_filter\n validates :table_map_filter, type: Symbol\n\n # @return [:present, :absent, nil] Determines whether the config should be present or not on the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6624714136123657, "alphanum_fraction": 0.6624714136123657, "avg_line_length": 33.959999084472656, "blob_id": "6f606618a6d4c4fb278222eb895ff648d2001c38", "content_id": "539cfeaac0a6b88ec04619882db5f013236c6889", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 874, "license_type": "permissive", "max_line_length": 185, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/identity/ipa/ipa_sudocmd.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add, modify or delete sudo command within FreeIPA server using FreeIPA API.\n class Ipa_sudocmd < Base\n # @return [Object] Sudo Command.\n attribute :sudocmd\n validates :sudocmd, presence: true\n\n # @return [String, nil] A description of this command.\n attribute :description\n validates :description, type: String\n\n # @return [:present, :absent, :enabled, :disabled, nil] State to ensure\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :enabled, :disabled], :message=>\"%{value} needs to be :present, :absent, :enabled, :disabled\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6915137767791748, "alphanum_fraction": 0.6915137767791748, "avg_line_length": 46.135135650634766, "blob_id": "41ad35f0023970b3ebdfa4450b16e65c5275aba8", "content_id": "036ecf7875daa2fb46db163e1d4123201bb6c4e0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1744, "license_type": "permissive", "max_line_length": 188, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/windows/win_domain_membership.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages domain membership or workgroup membership for a Windows host. Also supports hostname changes.\n # This module may require subsequent use of the M(win_reboot) action if changes are made.\n class Win_domain_membership < Base\n # @return [Object, nil] When C(state) is C(domain), the DNS name of the domain to which the targeted Windows host should be joined.\n attribute :dns_domain_name\n\n # @return [Object] Username of a domain admin for the target domain (required to join or leave the domain).\n attribute :domain_admin_user\n validates :domain_admin_user, presence: true\n\n # @return [Object, nil] Password for the specified C(domain_admin_user).\n attribute :domain_admin_password\n\n # @return [Object, nil] The desired hostname for the Windows host.\n attribute :hostname\n\n # @return [Object, nil] The desired OU path for adding the computer object.,This is only used when adding the target host to a domain, if it is already a member then it is ignored.\n attribute :domain_ou_path\n\n # @return [:domain, :workgroup, nil] Whether the target host should be a member of a domain or workgroup.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:domain, :workgroup], :message=>\"%{value} needs to be :domain, :workgroup\"}, allow_nil: true\n\n # @return [Object, nil] When C(state) is C(workgroup), the name of the workgroup that the Windows host should be in.\n attribute :workgroup_name\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7047551274299622, "alphanum_fraction": 0.7090134620666504, "avg_line_length": 77.27777862548828, "blob_id": "091207c7eec63e8b08fe1b5fe5cf794afc28e4b6", "content_id": "3a1374c33d57b5375b18b3d3a5999962159eb23d", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4227, "license_type": "permissive", "max_line_length": 575, "num_lines": 54, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_vlan.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage VLANs on a BIG-IP system\n class Bigip_vlan < Base\n # @return [Object, nil] The description to give to the VLAN.\n attribute :description\n\n # @return [Array<Float>, Float, nil] Specifies a list of tagged interfaces and trunks that you want to configure for the VLAN. Use tagged interfaces or trunks when you want to assign a single interface or trunk to multiple VLANs.\n attribute :tagged_interfaces\n validates :tagged_interfaces, type: TypeGeneric.new(Float)\n\n # @return [Object, nil] Specifies a list of untagged interfaces and trunks that you want to configure for the VLAN.\n attribute :untagged_interfaces\n\n # @return [String] The VLAN to manage. If the special VLAN C(ALL) is specified with the C(state) value of C(absent) then all VLANs will be removed.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, nil] The state of the VLAN on the system. When C(present), guarantees that the VLAN exists with the provided attributes. When C(absent), removes the VLAN from the system.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] Tag number for the VLAN. The tag number can be any integer between 1 and 4094. The system automatically assigns a tag number if you do not specify a value.\n attribute :tag\n validates :tag, type: String\n\n # @return [Object, nil] Specifies the maximum transmission unit (MTU) for traffic on this VLAN. When creating a new VLAN, if this parameter is not specified, the default value used will be C(1500).,This number must be between 576 to 9198.\n attribute :mtu\n\n # @return [:default, :\"destination-address\", :\"source-address\", :\"dst-ip\", :\"src-ip\", :dest, :destination, :source, :dst, :src, nil] Specifies how the traffic on the VLAN will be disaggregated. The value selected determines the traffic disaggregation method. You can choose to disaggregate traffic based on C(source-address) (the source IP address), C(destination-address) (destination IP address), or C(default), which specifies that the default CMP hash uses L4 ports.,When creating a new VLAN, if this parameter is not specified, the default of C(default) is used.\n attribute :cmp_hash\n validates :cmp_hash, expression_inclusion: {:in=>[:default, :\"destination-address\", :\"source-address\", :\"dst-ip\", :\"src-ip\", :dest, :destination, :source, :dst, :src], :message=>\"%{value} needs to be :default, :\\\"destination-address\\\", :\\\"source-address\\\", :\\\"dst-ip\\\", :\\\"src-ip\\\", :dest, :destination, :source, :dst, :src\"}, allow_nil: true\n\n # @return [:inner, :outer, nil] Specifies how the disaggregator (DAG) distributes received tunnel-encapsulated packets to TMM instances. Select C(inner) to distribute packets based on information in inner headers. Select C(outer) to distribute packets based on information in outer headers without inspecting inner headers.,When creating a new VLAN, if this parameter is not specified, the default of C(outer) is used.,This parameter is not supported on Virtual Editions of BIG-IP.\n attribute :dag_tunnel\n validates :dag_tunnel, expression_inclusion: {:in=>[:inner, :outer], :message=>\"%{value} needs to be :inner, :outer\"}, allow_nil: true\n\n # @return [Symbol, nil] Specifies whether some of the stateless traffic on the VLAN should be disaggregated in a round-robin order instead of using a static hash. The stateless traffic includes non-IP L2 traffic, ICMP, some UDP protocols, and so on.,When creating a new VLAN, if this parameter is not specified, the default of (no) is used.\n attribute :dag_round_robin\n validates :dag_round_robin, type: Symbol\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6873791813850403, "alphanum_fraction": 0.6942833662033081, "avg_line_length": 65.44036865234375, "blob_id": "ec3116a9f9bd5c6cc7036da99bad8a04a6405659", "content_id": "dc7771aaf5a9bcb5f199fc6147fdb12baa46c983", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 7242, "license_type": "permissive", "max_line_length": 555, "num_lines": 109, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_s3.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows the user to manage S3 buckets and the objects within them. Includes support for creating and deleting both objects and buckets, retrieving objects as files or strings and generating download links. This module has a dependency on boto3 and botocore.\n class Aws_s3 < Base\n # @return [Object, nil] AWS access key id. If not set then the value of the AWS_ACCESS_KEY environment variable is used.\n attribute :aws_access_key\n\n # @return [Object, nil] AWS secret key. If not set then the value of the AWS_SECRET_KEY environment variable is used.\n attribute :aws_secret_key\n\n # @return [String] Bucket name.\n attribute :bucket\n validates :bucket, presence: true, type: String\n\n # @return [String, nil] The destination file path when downloading an object/key with a GET operation.\n attribute :dest\n validates :dest, type: String\n\n # @return [Boolean, nil] When set for PUT mode, asks for server-side encryption.\n attribute :encrypt\n validates :encrypt, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:AES256, :\"aws:kms\", nil] What encryption mode to use if C(encrypt) is set\n attribute :encryption_mode\n validates :encryption_mode, expression_inclusion: {:in=>[:AES256, :\"aws:kms\"], :message=>\"%{value} needs to be :AES256, :\\\"aws:kms\\\"\"}, allow_nil: true\n\n # @return [Integer, nil] Time limit (in seconds) for the URL generated and returned by S3/Walrus when performing a mode=put or mode=geturl operation.\n attribute :expiration\n validates :expiration, type: Integer\n\n # @return [String, nil] Custom headers for PUT operation, as a dictionary of 'key=value' and 'key=value,key=value'.\n attribute :headers\n validates :headers, type: String\n\n # @return [String, nil] Specifies the key to start with when using list mode. Object keys are returned in alphabetical order, starting with key after the marker in order.\n attribute :marker\n validates :marker, type: String\n\n # @return [Integer, nil] Max number of results to return in list mode, set this if you want to retrieve fewer than the default 1000 keys.\n attribute :max_keys\n validates :max_keys, type: Integer\n\n # @return [Array<String>, String, nil] Metadata for PUT operation, as a dictionary of 'key=value' and 'key=value,key=value'.\n attribute :metadata\n validates :metadata, type: TypeGeneric.new(String)\n\n # @return [:get, :put, :delete, :create, :geturl, :getstr, :delobj, :list] Switches the module behaviour between put (upload), get (download), geturl (return download url, Ansible 1.3+), getstr (download object as string (1.3+)), list (list keys, Ansible 2.0+), create (bucket), delete (bucket), and delobj (delete object, Ansible 2.0+).\n attribute :mode\n validates :mode, presence: true, expression_inclusion: {:in=>[:get, :put, :delete, :create, :geturl, :getstr, :delobj, :list], :message=>\"%{value} needs to be :get, :put, :delete, :create, :geturl, :getstr, :delobj, :list\"}\n\n # @return [String, nil] Keyname of the object inside the bucket. Can be used to create \"virtual directories\", see examples.\n attribute :object\n validates :object, type: String\n\n # @return [String, nil] This option lets the user set the canned permissions on the object/bucket that are created. The permissions that can be set are 'private', 'public-read', 'public-read-write', 'authenticated-read' for a bucket or 'private', 'public-read', 'public-read-write', 'aws-exec-read', 'authenticated-read', 'bucket-owner-read', 'bucket-owner-full-control' for an object. Multiple permissions can be specified as a list.\n attribute :permission\n validates :permission, type: String\n\n # @return [String, nil] Limits the response to keys that begin with the specified prefix for list mode\n attribute :prefix\n validates :prefix, type: String\n\n # @return [String, nil] Version ID of the object inside the bucket. Can be used to get a specific version of a file if versioning is enabled in the target bucket.\n attribute :version\n validates :version, type: String\n\n # @return [String, nil] Force overwrite either locally on the filesystem or remotely with the object/key. Used with PUT and GET operations. Boolean or one of [always, never, different], true is equal to 'always' and false is equal to 'never', new in 2.0. When this is set to 'different', the md5 sum of the local file is compared with the 'ETag' of the object/key in S3. The ETag may or may not be an MD5 digest of the object data. See the ETag response header here U(https://docs.aws.amazon.com/AmazonS3/latest/API/RESTCommonResponseHeaders.html)\n attribute :overwrite\n validates :overwrite, type: String\n\n # @return [String, nil] AWS region to create the bucket in. If not set then the value of the AWS_REGION and EC2_REGION environment variables are checked, followed by the aws_region and ec2_region settings in the Boto config file. If none of those are set the region defaults to the S3 Location: US Standard. Prior to ansible 1.8 this parameter could be specified but had no effect.\n attribute :region\n validates :region, type: String\n\n # @return [Integer, nil] On recoverable failure, how many times to retry before actually failing.\n attribute :retries\n validates :retries, type: Integer\n\n # @return [String, nil] S3 URL endpoint for usage with Ceph, Eucalypus, fakes3, etc. Otherwise assumes AWS\n attribute :s3_url\n validates :s3_url, type: String\n\n # @return [:yes, :no, nil] Enables Amazon S3 Dual-Stack Endpoints, allowing S3 communications using both IPv4 and IPv6.,Requires at least botocore version 1.4.45.\n attribute :dualstack\n validates :dualstack, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Boolean, nil] Enable Ceph RGW S3 support. This option requires an explicit url via s3_url.\n attribute :rgw\n validates :rgw, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] The source file path when performing a PUT operation.\n attribute :src\n validates :src, type: String\n\n # @return [Object, nil] Overrides initial bucket lookups in case bucket or iam policies are restrictive. Example: a user may have the GetObject permission but no other permissions. In this case using the option mode: get will fail without specifying ignore_nonexistent_bucket: True.\n attribute :ignore_nonexistent_bucket\n\n # @return [Object, nil] KMS key id to use when encrypting objects using C(aws:kms) encryption. Ignored if encryption is not C(aws:kms)\n attribute :encryption_kms_key_id\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7008086442947388, "alphanum_fraction": 0.7015787363052368, "avg_line_length": 58.022727966308594, "blob_id": "6528d4bf0b11e4fac8e76d495ce25befc4e684f5", "content_id": "ec11b92d0ece866e293d6381d4b2dfe205cf6f3c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2597, "license_type": "permissive", "max_line_length": 357, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_virtualnetwork.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update or delete a virtual networks. Allows setting and updating the available IPv4 address ranges and setting custom DNS servers. Use the azure_rm_subnet module to associate subnets with a virtual network.\n class Azure_rm_virtualnetwork < Base\n # @return [String] name of resource group.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [Array<String>, String, nil] List of IPv4 address ranges where each is formatted using CIDR notation. Required when creating a new virtual network or using purge_address_prefixes.\n attribute :address_prefixes_cidr\n validates :address_prefixes_cidr, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] Custom list of DNS servers. Maximum length of two. The first server in the list will be treated as the Primary server. This is an explicit list. Existing DNS servers will be replaced with the specified list. Use the purge_dns_servers option to remove all custom DNS servers and revert to default Azure servers.\n attribute :dns_servers\n validates :dns_servers, type: TypeGeneric.new(String)\n\n # @return [Object, nil] Valid azure location. Defaults to location of the resource group.\n attribute :location\n\n # @return [String] name of the virtual network.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:yes, :no, nil] Use with state present to remove any existing address_prefixes.\n attribute :purge_address_prefixes\n validates :purge_address_prefixes, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Use with state present to remove existing DNS servers, reverting to default Azure servers. Mutually exclusive with dns_servers.\n attribute :purge_dns_servers\n validates :purge_dns_servers, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:absent, :present, nil] Assert the state of the virtual network. Use 'present' to create or update and 'absent' to delete.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6477197408676147, "alphanum_fraction": 0.6774619817733765, "avg_line_length": 54.01818084716797, "blob_id": "23e5cd78b150d5791a0acd233241ac7b4b401812", "content_id": "a954984065f7c4508c8db8e8f4a449af6b2cd916", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3026, "license_type": "permissive", "max_line_length": 229, "num_lines": 55, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_interface_ospf.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages configuration of an OSPF interface instanceon HUAWEI CloudEngine switches.\n class Ce_interface_ospf < Base\n # @return [Object] Full name of interface, i.e. 40GE1/0/10.\n attribute :interface\n validates :interface, presence: true\n\n # @return [Object] Specifies a process ID. The value is an integer ranging from 1 to 4294967295.\n attribute :process_id\n validates :process_id, presence: true\n\n # @return [Object] Ospf area associated with this ospf process. Valid values are a string, formatted as an IP address (i.e. \"0.0.0.0\") or as an integer between 1 and 4294967295.\n attribute :area\n validates :area, presence: true\n\n # @return [Object, nil] The cost associated with this interface. Valid values are an integer in the range from 1 to 65535.\n attribute :cost\n\n # @return [Object, nil] Time between sending successive hello packets. Valid values are an integer in the range from 1 to 65535.\n attribute :hello_interval\n\n # @return [Object, nil] Time interval an ospf neighbor waits for a hello packet before tearing down adjacencies. Valid values are an integer in the range from 1 to 235926000.\n attribute :dead_interval\n\n # @return [:yes, :no, nil] Setting to true will prevent this interface from receiving HELLO packets. Valid values are 'true' and 'false'.\n attribute :silent_interface\n validates :silent_interface, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:none, :null, :\"hmac-sha256\", :md5, :\"hmac-md5\", :simple, nil] Specifies the authentication type.\n attribute :auth_mode\n validates :auth_mode, expression_inclusion: {:in=>[:none, :null, :\"hmac-sha256\", :md5, :\"hmac-md5\", :simple], :message=>\"%{value} needs to be :none, :null, :\\\"hmac-sha256\\\", :md5, :\\\"hmac-md5\\\", :simple\"}, allow_nil: true\n\n # @return [Object, nil] Specifies a password for simple authentication. The value is a string of 1 to 8 characters.\n attribute :auth_text_simple\n\n # @return [Object, nil] Authentication key id when C(auth_mode) is 'hmac-sha256', 'md5' or 'hmac-md5. Valid value is an integer is in the range from 1 to 255.\n attribute :auth_key_id\n\n # @return [Object, nil] Specifies a password for MD5, HMAC-MD5, or HMAC-SHA256 authentication. The value is a string of 1 to 255 case-sensitive characters, spaces not supported.\n attribute :auth_text_md5\n\n # @return [:present, :absent, nil] Determines whether the config should be present or not on the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6775244474411011, "alphanum_fraction": 0.6786102056503296, "avg_line_length": 49.23636245727539, "blob_id": "3438ca7c4b5e686e9b3bd9d484807b8fe946f899", "content_id": "1731b87fb5d12bf79ef472bf07c30d86ef2c94dd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2763, "license_type": "permissive", "max_line_length": 301, "num_lines": 55, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_vrf.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of VRFs on CISCO NXOS network devices.\n class Nxos_vrf < Base\n # @return [String] Name of VRF to be managed.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:up, :down, nil] Administrative state of the VRF.\n attribute :admin_state\n validates :admin_state, expression_inclusion: {:in=>[:up, :down], :message=>\"%{value} needs to be :up, :down\"}, allow_nil: true\n\n # @return [Object, nil] Specify virtual network identifier. Valid values are Integer or keyword 'default'.\n attribute :vni\n\n # @return [Object, nil] VPN Route Distinguisher (RD). Valid values are a string in one of the route-distinguisher formats (ASN2:NN, ASN4:NN, or IPV4:NN); the keyword 'auto', or the keyword 'default'.\n attribute :rd\n\n # @return [Array<String>, String, nil] List of interfaces to check the VRF has been configured correctly or keyword 'default'.\n attribute :interfaces\n validates :interfaces, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] This is a intent option and checks the operational state of the for given vrf C(name) for associated interfaces. If the value in the C(associated_interfaces) does not match with the operational state of vrf interfaces on device it will result in failure.\n attribute :associated_interfaces\n validates :associated_interfaces, type: TypeGeneric.new(String)\n\n # @return [Array<Hash>, Hash, nil] List of VRFs definitions.\n attribute :aggregate\n validates :aggregate, type: TypeGeneric.new(Hash)\n\n # @return [:yes, :no, nil] Purge VRFs not defined in the I(aggregate) parameter.\n attribute :purge\n validates :purge, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Manages desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Description of the VRF or keyword 'default'.\n attribute :description\n validates :description, type: String\n\n # @return [Integer, nil] Time in seconds to wait before checking for the operational state on remote device. This wait is applicable for operational state arguments.\n attribute :delay\n validates :delay, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6868105530738831, "alphanum_fraction": 0.6872901916503906, "avg_line_length": 47.488372802734375, "blob_id": "9de8a6a4fe016dc6e0eaf85d85998253b1070fc3", "content_id": "084ddd11a6473379ff517178d321417e81821481", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2085, "license_type": "permissive", "max_line_length": 247, "num_lines": 43, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_vxlan_vtep_vni.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates a Virtual Network Identifier member (VNI) for an NVE overlay interface.\n class Nxos_vxlan_vtep_vni < Base\n # @return [String] Interface name for the VXLAN Network Virtualization Endpoint.\n attribute :interface\n validates :interface, presence: true, type: String\n\n # @return [Integer] ID of the Virtual Network Identifier.\n attribute :vni\n validates :vni, presence: true, type: Integer\n\n # @return [Symbol, nil] This attribute is used to identify and separate processing VNIs that are associated with a VRF and used for routing. The VRF and VNI specified with this command must match the configuration of the VNI under the VRF.\n attribute :assoc_vrf\n validates :assoc_vrf, type: Symbol\n\n # @return [:bgp, :static, :default, nil] Specifies mechanism for host reachability advertisement.\n attribute :ingress_replication\n validates :ingress_replication, expression_inclusion: {:in=>[:bgp, :static, :default], :message=>\"%{value} needs to be :bgp, :static, :default\"}, allow_nil: true\n\n # @return [Object, nil] The multicast group (range) of the VNI. Valid values are string and keyword 'default'.\n attribute :multicast_group\n\n # @return [Object, nil] Set the ingress-replication static peer list. Valid values are an array, a space-separated string of ip addresses, or the keyword 'default'.\n attribute :peer_list\n\n # @return [Symbol, nil] Suppress arp under layer 2 VNI.\n attribute :suppress_arp\n validates :suppress_arp, type: Symbol\n\n # @return [:present, :absent, nil] Determines whether the config should be present or not on the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5903716087341309, "alphanum_fraction": 0.6452702879905701, "avg_line_length": 48.33333206176758, "blob_id": "5615dca691d392b8a99bbd6286cd72264e7c9316", "content_id": "a34b4e789efdc150320b99586faa68ea5560b53c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2368, "license_type": "permissive", "max_line_length": 269, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/cloud/memset/memset_zone_record.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage DNS records in a Memset account.\n class Memset_zone_record < Base\n # @return [:absent, :present, nil] Indicates desired state of resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String] The API key obtained from the Memset control panel.\n attribute :api_key\n validates :api_key, presence: true, type: String\n\n # @return [String] The address for this record (can be IP or text string depending on record type).\n attribute :address\n validates :address, presence: true, type: String\n\n # @return [Object, nil] C(SRV) and C(TXT) record priority, in the range 0 > 999 (inclusive).\n attribute :priority\n\n # @return [String, nil] The subdomain to create.\n attribute :record\n validates :record, type: String\n\n # @return [:A, :AAAA, :CNAME, :MX, :NS, :SRV, :TXT] The type of DNS record to create.\n attribute :type\n validates :type, presence: true, expression_inclusion: {:in=>[:A, :AAAA, :CNAME, :MX, :NS, :SRV, :TXT], :message=>\"%{value} needs to be :A, :AAAA, :CNAME, :MX, :NS, :SRV, :TXT\"}\n\n # @return [Symbol, nil] If set then the current domain is added onto the address field for C(CNAME), C(MX), C(NS) and C(SRV)record types.\n attribute :relative\n validates :relative, type: Symbol\n\n # @return [0, 300, 600, 900, 1800, 3600, 7200, 10800, 21600, 43200, 86400, nil] The record's TTL in seconds (will inherit zone's TTL if not explicitly set). This must be a valid int from U(https://www.memset.com/apidocs/methods_dns.html#dns.zone_record_create).\n attribute :ttl\n validates :ttl, expression_inclusion: {:in=>[0, 300, 600, 900, 1800, 3600, 7200, 10800, 21600, 43200, 86400], :message=>\"%{value} needs to be 0, 300, 600, 900, 1800, 3600, 7200, 10800, 21600, 43200, 86400\"}, allow_nil: true\n\n # @return [String] The name of the zone to which to add the record to.\n attribute :zone\n validates :zone, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6782568097114563, "alphanum_fraction": 0.6782568097114563, "avg_line_length": 49.16279220581055, "blob_id": "50d92074450070d195c9ddfa7c0f13f8d7553413", "content_id": "c144b9f0583df984a975af1c6bb0b4b2cc2e6b9c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2157, "license_type": "permissive", "max_line_length": 229, "num_lines": 43, "path": "/lib/ansible/ruby/modules/generated/network/meraki/meraki_admin.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows for creation, management, and visibility into administrators within Meraki.\n class Meraki_admin < Base\n # @return [String, nil] Name of the dashboard administrator.,Required when creating a new administrator.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] Email address for the dashboard administrator.,Email cannot be updated.,Required when creating or editing an administrator.\n attribute :email\n validates :email, type: String\n\n # @return [:full, :none, :\"read-only\", nil] Privileges assigned to the administrator in the organization.\n attribute :orgAccess\n validates :orgAccess, expression_inclusion: {:in=>[:full, :none, :\"read-only\"], :message=>\"%{value} needs to be :full, :none, :\\\"read-only\\\"\"}, allow_nil: true\n\n # @return [Object, nil] Tags the administrator has privileges on.,When creating a new administrator, C(org_name), C(network), or C(tags) must be specified.,If C(none) is specified, C(network) or C(tags) must be specified.\n attribute :tags\n\n # @return [Object, nil] List of networks the administrator has privileges on.,When creating a new administrator, C(org_name), C(network), or C(tags) must be specified.\n attribute :networks\n\n # @return [:absent, :present, :query] Create or modify an organization\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}\n\n # @return [String, nil] Name of organization.,Used when C(name) should refer to another object.,When creating a new administrator, C(org_name), C(network), or C(tags) must be specified.\n attribute :org_name\n validates :org_name, type: String\n\n # @return [Integer, nil] ID of organization.\n attribute :org_id\n validates :org_id, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6762393116950989, "alphanum_fraction": 0.677264928817749, "avg_line_length": 58.693878173828125, "blob_id": "47ad8aed60510e17a63ec263fbb728ceb3429d9c", "content_id": "defcbc7c107da75ba0a4989c6607d67f09d90413", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2925, "license_type": "permissive", "max_line_length": 275, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/system/systemd.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Controls systemd services on remote hosts.\n class Systemd < Base\n # @return [String, nil] Name of the service. When using in a chroot environment you always need to specify the full name i.e. (crond.service).\n attribute :name\n validates :name, type: String\n\n # @return [:reloaded, :restarted, :started, :stopped, nil] C(started)/C(stopped) are idempotent actions that will not run commands unless necessary. C(restarted) will always bounce the service. C(reloaded) will always reload.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:reloaded, :restarted, :started, :stopped], :message=>\"%{value} needs to be :reloaded, :restarted, :started, :stopped\"}, allow_nil: true\n\n # @return [Symbol, nil] Whether the service should start on boot. B(At least one of state and enabled are required.)\n attribute :enabled\n validates :enabled, type: Symbol\n\n # @return [Symbol, nil] Whether to override existing symlinks.\n attribute :force\n validates :force, type: Symbol\n\n # @return [Symbol, nil] Whether the unit should be masked or not, a masked unit is impossible to start.\n attribute :masked\n validates :masked, type: Symbol\n\n # @return [:yes, :no, nil] run daemon-reload before doing any other operations, to make sure systemd has read any changes.\n attribute :daemon_reload\n validates :daemon_reload, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] (deprecated) run ``systemctl`` talking to the service manager of the calling user, rather than the service manager of the system.,This option is deprecated and will eventually be removed in 2.11. The ``scope`` option should be used instead.\n attribute :user\n validates :user, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:system, :user, :global, nil] run systemctl within a given service manager scope, either as the default system scope (system), the current user's scope (user), or the scope of all users (global).\n attribute :scope\n validates :scope, expression_inclusion: {:in=>[:system, :user, :global], :message=>\"%{value} needs to be :system, :user, :global\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Do not synchronously wait for the requested operation to finish. Enqueued job will continue without Ansible blocking on its completion.\n attribute :no_block\n validates :no_block, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6289970874786377, "alphanum_fraction": 0.6482558250427246, "avg_line_length": 46.44827651977539, "blob_id": "4a5361399623c3aafba00ac37c06e0e8139f516a", "content_id": "f8a3c20b84c7410e7c989f7b0e8e5feb44fe7b06", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2752, "license_type": "permissive", "max_line_length": 367, "num_lines": 58, "path": "/lib/ansible/ruby/modules/generated/net_tools/nsupdate.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and remove DNS records using DDNS updates\n # DDNS works well with both bind and Microsoft DNS (see https://technet.microsoft.com/en-us/library/cc961412.aspx)\n class Nsupdate < Base\n # @return [:present, :absent, nil] Manage DNS record.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] Apply DNS modification on this server.\n attribute :server\n validates :server, presence: true, type: String\n\n # @return [Integer, nil] Use this TCP port when connecting to C(server).\n attribute :port\n validates :port, type: Integer\n\n # @return [String, nil] Use TSIG key name to authenticate against DNS C(server)\n attribute :key_name\n validates :key_name, type: String\n\n # @return [String, nil] Use TSIG key secret, associated with C(key_name), to authenticate against C(server)\n attribute :key_secret\n validates :key_secret, type: String\n\n # @return [:\"HMAC-MD5.SIG-ALG.REG.INT\", :\"hmac-md5\", :\"hmac-sha1\", :\"hmac-sha224\", :\"hmac-sha256\", :\"hmac-sha384\", :\"hmac-sha512\", nil] Specify key algorithm used by C(key_secret).\n attribute :key_algorithm\n validates :key_algorithm, expression_inclusion: {:in=>[:\"HMAC-MD5.SIG-ALG.REG.INT\", :\"hmac-md5\", :\"hmac-sha1\", :\"hmac-sha224\", :\"hmac-sha256\", :\"hmac-sha384\", :\"hmac-sha512\"], :message=>\"%{value} needs to be :\\\"HMAC-MD5.SIG-ALG.REG.INT\\\", :\\\"hmac-md5\\\", :\\\"hmac-sha1\\\", :\\\"hmac-sha224\\\", :\\\"hmac-sha256\\\", :\\\"hmac-sha384\\\", :\\\"hmac-sha512\\\"\"}, allow_nil: true\n\n # @return [String, nil] DNS record will be modified on this C(zone).,When omitted DNS will be queried to attempt finding the correct zone.,Starting with Ansible 2.7 this parameter is optional.\n attribute :zone\n validates :zone, type: String\n\n # @return [String] Sets the DNS record to modify. When zone is omitted this has to be absolute (ending with a dot).\n attribute :record\n validates :record, presence: true, type: String\n\n # @return [String, nil] Sets the record type.\n attribute :type\n validates :type, type: String\n\n # @return [Integer, nil] Sets the record TTL.\n attribute :ttl\n validates :ttl, type: Integer\n\n # @return [Array<String>, String, nil] Sets the record value.\n attribute :value\n validates :value, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6701774001121521, "alphanum_fraction": 0.6718403697013855, "avg_line_length": 40.953487396240234, "blob_id": "3e2ed7ebd89dc287ebe27f98a84ed53164858c13", "content_id": "1081375278c6359f4b1acd267abf7a262ed5da4f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1804, "license_type": "permissive", "max_line_length": 143, "num_lines": 43, "path": "/lib/ansible/ruby/modules/generated/cloud/profitbricks/profitbricks_volume_attachments.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows you to attach or detach a volume from a ProfitBricks server. This module has a dependency on profitbricks >= 1.0.0\n class Profitbricks_volume_attachments < Base\n # @return [String] The datacenter in which to operate.\n attribute :datacenter\n validates :datacenter, presence: true, type: String\n\n # @return [String] The name of the server you wish to detach or attach the volume.\n attribute :server\n validates :server, presence: true, type: String\n\n # @return [String] The volume name or ID.\n attribute :volume\n validates :volume, presence: true, type: String\n\n # @return [Object, nil] The ProfitBricks username. Overrides the PB_SUBSCRIPTION_ID environment variable.\n attribute :subscription_user\n\n # @return [Object, nil] THe ProfitBricks password. Overrides the PB_PASSWORD environment variable.\n attribute :subscription_password\n\n # @return [:yes, :no, nil] wait for the operation to complete before returning\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] how long before wait gives up, in seconds\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [:present, :absent, nil] Indicate desired state of the resource\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6464890837669373, "alphanum_fraction": 0.6464890837669373, "avg_line_length": 37.41860580444336, "blob_id": "eea0c1fc53178910f9bda0907bd584c38d02dd3e", "content_id": "64621a51a5ae957383338b3636a87f9a86b46ea4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1652, "license_type": "permissive", "max_line_length": 161, "num_lines": 43, "path": "/lib/ansible/ruby/modules/generated/cloud/misc/helm.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Install, upgrade, delete and list packages with the Helm package manager.\n class Helm < Base\n # @return [String, nil] Tiller's server host.\n attribute :host\n validates :host, type: String\n\n # @return [Integer, nil] Tiller's server port.\n attribute :port\n validates :port, type: Integer\n\n # @return [String, nil] Kubernetes namespace where the chart should be installed.\n attribute :namespace\n validates :namespace, type: String\n\n # @return [String, nil] Release name to manage.\n attribute :name\n validates :name, type: String\n\n # @return [:absent, :purged, :present, nil] Whether to install C(present), remove C(absent), or purge C(purged) a package.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :purged, :present], :message=>\"%{value} needs to be :absent, :purged, :present\"}, allow_nil: true\n\n # @return [Object, nil] A map describing the chart to install. See examples for available options.\\r\\n\n attribute :chart\n\n # @return [Object, nil] A map of value options for the chart.\n attribute :values\n\n # @return [:yes, :no, nil] Whether to disable hooks during the uninstall process.\n attribute :disable_hooks\n validates :disable_hooks, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6603212356567383, "alphanum_fraction": 0.6603212356567383, "avg_line_length": 44.43243408203125, "blob_id": "5e63093eb8227e3b14ec16af27cf997f5891f289", "content_id": "bdde3813ac8c019f0300e7a24934f6ed87baa122", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1681, "license_type": "permissive", "max_line_length": 226, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_keystone_endpoint.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, or delete OpenStack Identity service endpoints. If a service with the same combination of I(service), I(interface) and I(region) exist, the I(url) and I(state) (C(present) or C(absent)) will be updated.\n class Os_keystone_endpoint < Base\n # @return [String] Name or id of the service.\n attribute :service\n validates :service, presence: true, type: String\n\n # @return [:admin, :public, :internal] Interface of the service.\n attribute :interface\n validates :interface, presence: true, expression_inclusion: {:in=>[:admin, :public, :internal], :message=>\"%{value} needs to be :admin, :public, :internal\"}\n\n # @return [String] URL of the service.\n attribute :url\n validates :url, presence: true, type: String\n\n # @return [String, nil] Region that the service belongs to. Note that I(region_name) is used for authentication.\n attribute :region\n validates :region, type: String\n\n # @return [Boolean, nil] Is the service enabled.\n attribute :enabled\n validates :enabled, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Should the resource be C(present) or C(absent).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6603034734725952, "alphanum_fraction": 0.6603034734725952, "avg_line_length": 39.86000061035156, "blob_id": "b14480bc77d85dfcbf94e840b504bbbc74985c6c", "content_id": "a571579b7eff585c06a12b1b7ef2516237582703", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2043, "license_type": "permissive", "max_line_length": 191, "num_lines": 50, "path": "/lib/ansible/ruby/modules/generated/monitoring/bigpanda.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Notify BigPanda when deployments start and end (successfully or not). Returns a deployment object containing all the parameters for future module calls.\n class Bigpanda < Base\n # @return [String] The name of the component being deployed. Ex: billing\n attribute :component\n validates :component, presence: true, type: String\n\n # @return [String] The deployment version.\n attribute :version\n validates :version, presence: true, type: String\n\n # @return [String] API token.\n attribute :token\n validates :token, presence: true, type: String\n\n # @return [:started, :finished, :failed] State of the deployment.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:started, :finished, :failed], :message=>\"%{value} needs to be :started, :finished, :failed\"}\n\n # @return [String, nil] Name of affected host name. Can be a list.\n attribute :hosts\n validates :hosts, type: String\n\n # @return [Object, nil] The environment name, typically 'production', 'staging', etc.\n attribute :env\n\n # @return [Object, nil] The person responsible for the deployment.\n attribute :owner\n\n # @return [Object, nil] Free text description of the deployment.\n attribute :description\n\n # @return [String, nil] Base URL of the API server.\n attribute :url\n validates :url, type: String\n\n # @return [:yes, :no, nil] If C(no), SSL certificates for the target url will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7175368070602417, "alphanum_fraction": 0.7175368070602417, "avg_line_length": 42.94117736816406, "blob_id": "11818953ef1a1ac15daec04d7b4e7e1bde6c4c43", "content_id": "fb321f19c79063f198aa22ec40af7350c8aaa6f4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 747, "license_type": "permissive", "max_line_length": 309, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/network/nso/nso_verify.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides support for verifying Cisco NSO configuration is in compliance with specified values.\n class Nso_verify < Base\n # @return [Hash] NSO data in format as C(| display json) converted to YAML. List entries can be annotated with a C(__state) entry. Set to in-sync/deep-in-sync for services to verify service is in sync with the network. Set to absent in list entries to ensure they are deleted if they exist in NSO.\\r\\n\n attribute :data\n validates :data, presence: true, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6801676154136658, "alphanum_fraction": 0.6801676154136658, "avg_line_length": 30.130434036254883, "blob_id": "1c9e79516a4d40448ba220fa439a19d789c63dbd", "content_id": "c32ba3448d04d50caf972757c6e529a64519f1ad", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 716, "license_type": "permissive", "max_line_length": 101, "num_lines": 23, "path": "/lib/ansible/ruby/modules/generated/network/panos/panos_lic.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Apply an authcode to a device.\n # The authcode should have been previously registered on the Palo Alto Networks support portal.\n # The device should have Internet access.\n class Panos_lic < Base\n # @return [Object] authcode to be applied\n attribute :auth_code\n validates :auth_code, presence: true\n\n # @return [String, nil] whether to apply authcode even if device is already licensed\n attribute :force\n validates :force, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6725791096687317, "alphanum_fraction": 0.6759347915649414, "avg_line_length": 59.463768005371094, "blob_id": "06c2052b4ee72265e879c49c114d3e5d1dace94e", "content_id": "3c96aa3ae08a391a06bd4e849a86e2c0f05ff723", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4172, "license_type": "permissive", "max_line_length": 275, "num_lines": 69, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_epg_to_domain.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Bind EPGs to Physical and Virtual Domains on Cisco ACI fabrics.\n class Aci_epg_to_domain < Base\n # @return [:encap, :useg, nil] Allows micro-segmentation.,The APIC defaults to C(encap) when unset during creation.\n attribute :allow_useg\n validates :allow_useg, expression_inclusion: {:in=>[:encap, :useg], :message=>\"%{value} needs to be :encap, :useg\"}, allow_nil: true\n\n # @return [String, nil] Name of an existing application network profile, that will contain the EPGs.\n attribute :ap\n validates :ap, type: String\n\n # @return [:immediate, :lazy, nil] Determines when the policy is pushed to hardware Policy CAM.,The APIC defaults to C(lazy) when unset during creation.\n attribute :deploy_immediacy\n validates :deploy_immediacy, expression_inclusion: {:in=>[:immediate, :lazy], :message=>\"%{value} needs to be :immediate, :lazy\"}, allow_nil: true\n\n # @return [String, nil] Name of the physical or virtual domain being associated with the EPG.\n attribute :domain\n validates :domain, type: String\n\n # @return [:phys, :vmm, nil] Determines if the Domain is physical (phys) or virtual (vmm).\n attribute :domain_type\n validates :domain_type, expression_inclusion: {:in=>[:phys, :vmm], :message=>\"%{value} needs to be :phys, :vmm\"}, allow_nil: true\n\n # @return [Integer, nil] The VLAN encapsulation for the EPG when binding a VMM Domain with static encap_mode.,This acts as the secondary encap when using useg.,Accepted values range between C(1) and C(4096).\n attribute :encap\n validates :encap, type: Integer\n\n # @return [:auto, :vlan, :vxlan, nil] The ecapsulataion method to be used.,The APIC defaults to C(auto) when unset during creation.\n attribute :encap_mode\n validates :encap_mode, expression_inclusion: {:in=>[:auto, :vlan, :vxlan], :message=>\"%{value} needs to be :auto, :vlan, :vxlan\"}, allow_nil: true\n\n # @return [String, nil] Name of the end point group.\n attribute :epg\n validates :epg, type: String\n\n # @return [Symbol, nil] Determines if netflow should be enabled.,The APIC defaults to C(no) when unset during creation.\n attribute :netflow\n validates :netflow, type: Symbol\n\n # @return [Integer, nil] Determines the primary VLAN ID when using useg.,Accepted values range between C(1) and C(4096).\n attribute :primary_encap\n validates :primary_encap, type: Integer\n\n # @return [:immediate, :lazy, :\"pre-provision\", nil] Determines when the policies should be resolved and available.,The APIC defaults to C(lazy) when unset during creation.\n attribute :resolution_immediacy\n validates :resolution_immediacy, expression_inclusion: {:in=>[:immediate, :lazy, :\"pre-provision\"], :message=>\"%{value} needs to be :immediate, :lazy, :\\\"pre-provision\\\"\"}, allow_nil: true\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n\n # @return [String, nil] Name of an existing tenant.\n attribute :tenant\n validates :tenant, type: String\n\n # @return [:cloudfoundry, :kubernetes, :microsoft, :openshift, :openstack, :redhat, :vmware, nil] The VM platform for VMM Domains.,Support for Kubernetes was added in ACI v3.0.,Support for CloudFoundry, OpenShift and Red Hat was added in ACI v3.1.\n attribute :vm_provider\n validates :vm_provider, expression_inclusion: {:in=>[:cloudfoundry, :kubernetes, :microsoft, :openshift, :openstack, :redhat, :vmware], :message=>\"%{value} needs to be :cloudfoundry, :kubernetes, :microsoft, :openshift, :openstack, :redhat, :vmware\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6503992676734924, "alphanum_fraction": 0.6503992676734924, "avg_line_length": 33.15151596069336, "blob_id": "b7607f820f3a422d3d287bb3c52934f7d1f850d5", "content_id": "06edad83f4c8c742c4a543689abc2cc1f03c2f1a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1127, "license_type": "permissive", "max_line_length": 143, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/cloud/digital_ocean/digital_ocean_sshkey.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create/delete DigitalOcean SSH keys.\n class Digital_ocean_sshkey < Base\n # @return [:present, :absent, nil] Indicate desired state of the target.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] This is a unique identifier for the SSH key used to delete a key\n attribute :fingerprint\n validates :fingerprint, type: String\n\n # @return [String, nil] The name for the SSH key\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] The Public SSH key to add.\n attribute :ssh_pub_key\n validates :ssh_pub_key, type: String\n\n # @return [String] DigitalOcean OAuth token.\n attribute :oauth_token\n validates :oauth_token, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7177655100822449, "alphanum_fraction": 0.72068852186203, "avg_line_length": 78.97402954101562, "blob_id": "c24e9a84484c0b6d21aae910983abbbc432673ec", "content_id": "04fb59f0978c2604c07010b892464fc37743f5f2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6158, "license_type": "permissive", "max_line_length": 557, "num_lines": 77, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/cloudformation.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Launches or updates an AWS CloudFormation stack and waits for it complete.\n class Cloudformation < Base\n # @return [String] name of the cloudformation stack\n attribute :stack_name\n validates :stack_name, presence: true, type: String\n\n # @return [:yes, :no, nil] If a stacks fails to form, rollback will remove the stack\n attribute :disable_rollback\n validates :disable_rollback, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] The amount of time (in minutes) that can pass before the stack status becomes CREATE_FAILED\n attribute :create_timeout\n validates :create_timeout, type: Integer\n\n # @return [Object, nil] A list of hashes of all the template variables for the stack. The value can be a string or a dict.,Dict can be used to set additional template parameter attributes like UsePreviousValue (see example).\n attribute :template_parameters\n\n # @return [:present, :absent, nil] If state is \"present\", stack will be created. If state is \"present\" and if stack exists and template has changed, it will be updated. If state is \"absent\", stack will be removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] The local path of the cloudformation template.,This must be the full path to the file, relative to the working directory. If using roles this may look like \"roles/cloudformation/files/cloudformation-example.json\".,If 'state' is 'present' and the stack does not exist yet, either 'template', 'template_body' or 'template_url' must be specified (but only one of them). If 'state' is 'present', the stack does exist, and neither 'template', 'template_body' nor 'template_url' are specified, the previous template will be reused.\n attribute :template\n validates :template, type: String\n\n # @return [Object, nil] The Simple Notification Service (SNS) topic ARNs to publish stack related events.\n attribute :notification_arns\n\n # @return [Object, nil] the path of the cloudformation stack policy. A policy cannot be removed once placed, but it can be modified. (for instance, [allow all updates](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/protect-stack-resources.html#d0e9051)\n attribute :stack_policy\n\n # @return [Hash, nil] Dictionary of tags to associate with stack and its resources during stack creation. Can be updated later, updating tags removes previous entries.\n attribute :tags\n validates :tags, type: Hash\n\n # @return [String, nil] Location of file containing the template body. The URL must point to a template (max size 307,200 bytes) located in an S3 bucket in the same region as the stack.,If 'state' is 'present' and the stack does not exist yet, either 'template', 'template_body' or 'template_url' must be specified (but only one of them). If 'state' ispresent, the stack does exist, and neither 'template', 'template_body' nor 'template_url' are specified, the previous template will be reused.\n attribute :template_url\n validates :template_url, type: String\n\n # @return [String, nil] If stack already exists create a changeset instead of directly applying changes. See the AWS Change Sets docs U(http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-changesets.html). WARNING: if the stack does not exist, it will be created without changeset. If the state is absent, the stack will be deleted immediately with no changeset.\n attribute :create_changeset\n validates :create_changeset, type: String\n\n # @return [Object, nil] Name given to the changeset when creating a changeset, only used when create_changeset is true. By default a name prefixed with Ansible-STACKNAME is generated based on input parameters. See the AWS Change Sets docs U(http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-changesets.html)\n attribute :changeset_name\n\n # @return [:json, :yaml, nil] (deprecated) For local templates, allows specification of json or yaml format. Templates are now passed raw to CloudFormation regardless of format. This parameter is ignored since Ansible 2.3.\n attribute :template_format\n validates :template_format, expression_inclusion: {:in=>[:json, :yaml], :message=>\"%{value} needs to be :json, :yaml\"}, allow_nil: true\n\n # @return [String, nil] The role that AWS CloudFormation assumes to create the stack. See the AWS CloudFormation Service Role docs U(http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-servicerole.html)\n attribute :role_arn\n validates :role_arn, type: String\n\n # @return [Boolean, nil] enable or disable termination protection on the stack. Only works with botocore >= 1.7.18.\n attribute :termination_protection\n validates :termination_protection, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] Template body. Use this to pass in the actual body of the Cloudformation template.,If 'state' is 'present' and the stack does not exist yet, either 'template', 'template_body' or 'template_url' must be specified (but only one of them). If 'state' ispresent, the stack does exist, and neither 'template', 'template_body' nor 'template_url' are specified, the previous template will be reused.\n attribute :template_body\n validates :template_body, type: String\n\n # @return [Integer, nil] Maximum number of CloudFormation events to fetch from a stack when creating or updating it.\n attribute :events_limit\n validates :events_limit, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6766541600227356, "alphanum_fraction": 0.6766541600227356, "avg_line_length": 32.375, "blob_id": "94fee0a22ed3953c55fc48ef312c05992022f722", "content_id": "cbbaaa9cbbcfb4d0f9c3654e2e3c7a79e11ee3f8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 801, "license_type": "permissive", "max_line_length": 111, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_securitygroup_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Get facts for a specific security group or all security groups within a resource group.\n class Azure_rm_securitygroup_facts < Base\n # @return [String, nil] Only show results for a specific security group.\n attribute :name\n validates :name, type: String\n\n # @return [String] Name of the resource group to use.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [Object, nil] Limit results by providing a list of tags. Format tags as 'key' or 'key:value'.\n attribute :tags\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6614146828651428, "alphanum_fraction": 0.6644317507743835, "avg_line_length": 52.26785659790039, "blob_id": "3cbd6d240abc05af14669735813c26c6b0dca299", "content_id": "4a7c727182a8f02734673f2328c262eebbe44fc4", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2983, "license_type": "permissive", "max_line_length": 485, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_elementsw_volume.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, destroy, or update volumes on ElementSW\n class Na_elementsw_volume < Base\n # @return [:present, :absent] Whether the specified volume should exist or not.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String] The name of the volume to manage.,It accepts volume_name or volume_id\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Integer] Account ID for the owner of this volume.,It accepts Account_id or Account_name\n attribute :account_id\n validates :account_id, presence: true, type: Integer\n\n # @return [Symbol, nil] Required when C(state=present),Should the volume provide 512-byte sector emulation?\n attribute :enable512e\n validates :enable512e, type: Symbol\n\n # @return [Hash, nil] Initial quality of service settings for this volume. Configure as dict in playbooks.\n attribute :qos\n validates :qos, type: Hash\n\n # @return [Object, nil] A YAML dictionary of attributes that you would like to apply on this volume.\n attribute :attributes\n\n # @return [Integer, nil] The size of the volume in (size_unit).,Required when C(state = present).\n attribute :size\n validates :size, type: Integer\n\n # @return [:bytes, :b, :kb, :mb, :gb, :tb, :pb, :eb, :zb, :yb, nil] The unit used to interpret the size parameter.\n attribute :size_unit\n validates :size_unit, expression_inclusion: {:in=>[:bytes, :b, :kb, :mb, :gb, :tb, :pb, :eb, :zb, :yb], :message=>\"%{value} needs to be :bytes, :b, :kb, :mb, :gb, :tb, :pb, :eb, :zb, :yb\"}, allow_nil: true\n\n # @return [:readOnly, :readWrite, :locked, :replicationTarget, nil] Access allowed for the volume.,readOnly Only read operations are allowed.,readWrite Reads and writes are allowed.,locked No reads or writes are allowed.,replicationTarget Identify a volume as the target volume for a paired set of volumes.,If the volume is not paired, the access status is locked.,If unspecified, the access settings of the clone will be the same as the source.\n attribute :access\n validates :access, expression_inclusion: {:in=>[:readOnly, :readWrite, :locked, :replicationTarget], :message=>\"%{value} needs to be :readOnly, :readWrite, :locked, :replicationTarget\"}, allow_nil: true\n\n # @return [String, nil] ElementSW access account password\n attribute :password\n validates :password, type: String\n\n # @return [String, nil] ElementSW access account user-name\n attribute :username\n validates :username, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6623376607894897, "alphanum_fraction": 0.6623376607894897, "avg_line_length": 38.43902587890625, "blob_id": "5a650fca1129fb4854ba4bbb1e2585803346ee2d", "content_id": "5e305956590fdfce2e8279f193659d85dfe946a3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1617, "license_type": "permissive", "max_line_length": 145, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/cloud/webfaction/webfaction_db.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove a database on a Webfaction host. Further documentation at https://github.com/quentinsf/ansible-webfaction.\n class Webfaction_db < Base\n # @return [String] The name of the database\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Whether the database should exist\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:mysql, :postgresql] The type of database to create.\n attribute :type\n validates :type, presence: true, expression_inclusion: {:in=>[:mysql, :postgresql], :message=>\"%{value} needs to be :mysql, :postgresql\"}\n\n # @return [String, nil] The password for the new database user.\n attribute :password\n validates :password, type: String\n\n # @return [String] The webfaction account to use\n attribute :login_name\n validates :login_name, presence: true, type: String\n\n # @return [String] The webfaction password to use\n attribute :login_password\n validates :login_password, presence: true, type: String\n\n # @return [String, nil] The machine name to use (optional for accounts with only one machine)\n attribute :machine\n validates :machine, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6417585611343384, "alphanum_fraction": 0.6559139490127563, "avg_line_length": 59.71900939941406, "blob_id": "dedf6fa4402fc3a0648eda88f75f0f79c98f8fd9", "content_id": "d99ccf430b46ce8773f7fb5feaa4fc227d990c82", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 7347, "license_type": "permissive", "max_line_length": 761, "num_lines": 121, "path": "/lib/ansible/ruby/modules/generated/network/meraki/meraki_ssid.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows for management of SSIDs in a Meraki wireless environment.\n class Meraki_ssid < Base\n # @return [:absent, :query, :present, nil] Specifies whether SNMP information should be queried or modified.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :query, :present], :message=>\"%{value} needs to be :absent, :query, :present\"}, allow_nil: true\n\n # @return [Object, nil] SSID number within network.\n attribute :number\n\n # @return [Object, nil] Name of SSID.\n attribute :name\n\n # @return [Object, nil] Name of organization.\n attribute :org_name\n\n # @return [Object, nil] ID of organization.\n attribute :org_id\n\n # @return [Object, nil] Name of network.\n attribute :net_name\n\n # @return [Object, nil] ID of network.\n attribute :net_id\n\n # @return [Symbol, nil] Enable or disable SSID network.\n attribute :enabled\n validates :enabled, type: Symbol\n\n # @return [:open, :psk, :\"open-with-radius\", :\"8021x-meraki\", :\"8021x-radius\", nil] Set authentication mode of network.\n attribute :auth_mode\n validates :auth_mode, expression_inclusion: {:in=>[:open, :psk, :\"open-with-radius\", :\"8021x-meraki\", :\"8021x-radius\"], :message=>\"%{value} needs to be :open, :psk, :\\\"open-with-radius\\\", :\\\"8021x-meraki\\\", :\\\"8021x-radius\\\"\"}, allow_nil: true\n\n # @return [:wpa, :eap, :\"wpa-eap\", nil] Set encryption mode of network.\n attribute :encryption_mode\n validates :encryption_mode, expression_inclusion: {:in=>[:wpa, :eap, :\"wpa-eap\"], :message=>\"%{value} needs to be :wpa, :eap, :\\\"wpa-eap\\\"\"}, allow_nil: true\n\n # @return [Object, nil] Password for wireless network.,Requires auth_mode to be set to psk.\n attribute :psk\n\n # @return [:\"WPA1 and WPA2\", :\"WPA2 only\", nil] Encryption mode within WPA2 specification.\n attribute :wpa_encryption_mode\n validates :wpa_encryption_mode, expression_inclusion: {:in=>[:\"WPA1 and WPA2\", :\"WPA2 only\"], :message=>\"%{value} needs to be :\\\"WPA1 and WPA2\\\", :\\\"WPA2 only\\\"\"}, allow_nil: true\n\n # @return [:None, :\"Click-through splash page\", :Billing, :\"Password-protected with Meraki RADIUS\", :\"Password-protected with custom RADIUS\", :\"Password-protected with Active Directory\", :\"Password-protected with LDAP\", :\"SMS authentication\", :\"Systems Manager Sentry\", :\"Facebook Wi-Fi\", :\"Google OAuth\", :\"Sponsored guest\", nil] Set to enable splash page and specify type of splash.\n attribute :splash_page\n validates :splash_page, expression_inclusion: {:in=>[:None, :\"Click-through splash page\", :Billing, :\"Password-protected with Meraki RADIUS\", :\"Password-protected with custom RADIUS\", :\"Password-protected with Active Directory\", :\"Password-protected with LDAP\", :\"SMS authentication\", :\"Systems Manager Sentry\", :\"Facebook Wi-Fi\", :\"Google OAuth\", :\"Sponsored guest\"], :message=>\"%{value} needs to be :None, :\\\"Click-through splash page\\\", :Billing, :\\\"Password-protected with Meraki RADIUS\\\", :\\\"Password-protected with custom RADIUS\\\", :\\\"Password-protected with Active Directory\\\", :\\\"Password-protected with LDAP\\\", :\\\"SMS authentication\\\", :\\\"Systems Manager Sentry\\\", :\\\"Facebook Wi-Fi\\\", :\\\"Google OAuth\\\", :\\\"Sponsored guest\\\"\"}, allow_nil: true\n\n # @return [Object, nil] List of RADIUS servers.\n attribute :radius_servers\n\n # @return [Symbol, nil] Enable or disable RADIUS CoA (Change of Authorization) on SSID.\n attribute :radius_coa_enabled\n validates :radius_coa_enabled, type: Symbol\n\n # @return [:\"Deny access\", :\"Allow access\", nil] Set client access policy in case RADIUS servers aren't available.\n attribute :radius_failover_policy\n validates :radius_failover_policy, expression_inclusion: {:in=>[:\"Deny access\", :\"Allow access\"], :message=>\"%{value} needs to be :\\\"Deny access\\\", :\\\"Allow access\\\"\"}, allow_nil: true\n\n # @return [:\"Strict priority order\", :\"Round robin\", nil] Set load balancing policy when multiple RADIUS servers are specified.\n attribute :radius_load_balancing_policy\n validates :radius_load_balancing_policy, expression_inclusion: {:in=>[:\"Strict priority order\", :\"Round robin\"], :message=>\"%{value} needs to be :\\\"Strict priority order\\\", :\\\"Round robin\\\"\"}, allow_nil: true\n\n # @return [Symbol, nil] Enable or disable RADIUS accounting.\n attribute :radius_accounting_enabled\n validates :radius_accounting_enabled, type: Symbol\n\n # @return [Object, nil] List of RADIUS servers for RADIUS accounting.\n attribute :radius_accounting_servers\n\n # @return [:\"NAT mode\", :\"Bridge mode\", :\"Layer 3 roaming\", :\"Layer 3 roaming with a concentrator\", :VPN, nil] Method of which SSID uses to assign IP addresses.\n attribute :ip_assignment_mode\n validates :ip_assignment_mode, expression_inclusion: {:in=>[:\"NAT mode\", :\"Bridge mode\", :\"Layer 3 roaming\", :\"Layer 3 roaming with a concentrator\", :VPN], :message=>\"%{value} needs to be :\\\"NAT mode\\\", :\\\"Bridge mode\\\", :\\\"Layer 3 roaming\\\", :\\\"Layer 3 roaming with a concentrator\\\", :VPN\"}, allow_nil: true\n\n # @return [Symbol, nil] Set whether to use VLAN tagging.\n attribute :use_vlan_tagging\n validates :use_vlan_tagging, type: Symbol\n\n # @return [Object, nil] Default VLAN ID.\n attribute :default_vlan_id\n\n # @return [Object, nil] ID number of VLAN on SSID.\n attribute :vlan_id\n\n # @return [Object, nil] List of VLAN tags.\n attribute :ap_tags_vlan_ids\n\n # @return [Symbol, nil] Enable or disable walled garden functionality.\n attribute :walled_garden_enabled\n validates :walled_garden_enabled, type: Symbol\n\n # @return [Object, nil] List of walled garden ranges.\n attribute :walled_garden_ranges\n\n # @return [1, 2, 5.5, 6, 9, 11, 12, 18, 24, 36, 48, 54, nil] Minimum bitrate (Mbps) allowed on SSID.\n attribute :min_bitrate\n validates :min_bitrate, expression_inclusion: {:in=>[1, 2, 5.5, 6, 9, 11, 12, 18, 24, 36, 48, 54], :message=>\"%{value} needs to be 1, 2, 5.5, 6, 9, 11, 12, 18, 24, 36, 48, 54\"}, allow_nil: true\n\n # @return [:\"Dual band operation\", :\"5 GHz band only\", :\"Dual band operation with Band Steering\", nil] Set band selection mode.\n attribute :band_selection\n validates :band_selection, expression_inclusion: {:in=>[:\"Dual band operation\", :\"5 GHz band only\", :\"Dual band operation with Band Steering\"], :message=>\"%{value} needs to be :\\\"Dual band operation\\\", :\\\"5 GHz band only\\\", :\\\"Dual band operation with Band Steering\\\"\"}, allow_nil: true\n\n # @return [Object, nil] Maximum bandwidth in Mbps devices on SSID can upload.\n attribute :per_client_bandwidth_limit_up\n\n # @return [Object, nil] Maximum bandwidth in Mbps devices on SSID can download.\n attribute :per_client_bandwidth_limit_down\n\n # @return [Object, nil] The concentrator to use for 'Layer 3 roaming with a concentrator' or 'VPN'.\n attribute :concentrator_network_id\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6708507537841797, "alphanum_fraction": 0.6708507537841797, "avg_line_length": 46.79999923706055, "blob_id": "9642675d905a24a46d917a7405ff259c6e28c727", "content_id": "a9f9b69ae6d0eb953df16ef1b6db0337b474bcfa", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1434, "license_type": "permissive", "max_line_length": 213, "num_lines": 30, "path": "/lib/ansible/ruby/modules/generated/cloud/atomic/atomic_image.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage the container images on the atomic host platform.\n # Allows to execute the commands specified by the RUN label in the container image when present.\n class Atomic_image < Base\n # @return [:docker, :ostree, nil] Define the backend where the image is pulled.\n attribute :backend\n validates :backend, expression_inclusion: {:in=>[:docker, :ostree], :message=>\"%{value} needs to be :docker, :ostree\"}, allow_nil: true\n\n # @return [String] Name of the container image.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :latest, :present, nil] The state of the container image.,The state C(latest) will ensure container image is upgraded to the latest version and forcefully restart container, if running.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :latest, :present], :message=>\"%{value} needs to be :absent, :latest, :present\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Start or Stop the container.\n attribute :started\n validates :started, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6556570529937744, "alphanum_fraction": 0.6816584467887878, "avg_line_length": 53.730770111083984, "blob_id": "2beb50c92bf79852bf8f2c7854cc7054646d5a53", "content_id": "1011525434d9b5e3339951222f080739fb415708", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2846, "license_type": "permissive", "max_line_length": 222, "num_lines": 52, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_ospf.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages configuration of an OSPF instance on HUAWEI CloudEngine switches.\n class Ce_ospf < Base\n # @return [Object] Specifies a process ID. The value is an integer ranging from 1 to 4294967295.\n attribute :process_id\n validates :process_id, presence: true\n\n # @return [Object, nil] Specifies the area ID. The area with the area-id being 0 is a backbone area. Valid values are a string, formatted as an IP address (i.e. \"0.0.0.0\") or as an integer between 1 and 4294967295.\n attribute :area\n\n # @return [Object, nil] Specifies the address of the network segment where the interface resides. The value is in dotted decimal notation.\n attribute :addr\n\n # @return [Object, nil] IP network wildcard bits in decimal format between 0 and 32.\n attribute :mask\n\n # @return [:none, :\"hmac-sha256\", :md5, :\"hmac-md5\", :simple, nil] Specifies the authentication type.\n attribute :auth_mode\n validates :auth_mode, expression_inclusion: {:in=>[:none, :\"hmac-sha256\", :md5, :\"hmac-md5\", :simple], :message=>\"%{value} needs to be :none, :\\\"hmac-sha256\\\", :md5, :\\\"hmac-md5\\\", :simple\"}, allow_nil: true\n\n # @return [Object, nil] Specifies a password for simple authentication. The value is a string of 1 to 8 characters.\n attribute :auth_text_simple\n\n # @return [Object, nil] Authentication key id when C(auth_mode) is 'hmac-sha256', 'md5' or 'hmac-md5. Valid value is an integer is in the range from 1 to 255.\n attribute :auth_key_id\n\n # @return [Object, nil] Specifies a password for MD5, HMAC-MD5, or HMAC-SHA256 authentication. The value is a string of 1 to 255 case-sensitive characters, spaces not supported.\n attribute :auth_text_md5\n\n # @return [Object, nil] IPv4 address for configure next-hop address's weight. Valid values are a string, formatted as an IP address.\n attribute :nexthop_addr\n\n # @return [Object, nil] Indicates the weight of the next hop. The smaller the value is, the higher the preference of the route is. It is an integer that ranges from 1 to 254.\n attribute :nexthop_weight\n\n # @return [Object, nil] The maximum number of paths for forward packets over multiple paths. Valid value is an integer in the range from 1 to 64.\n attribute :max_load_balance\n\n # @return [:present, :absent, nil] Determines whether the config should be present or not on the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6782480478286743, "alphanum_fraction": 0.6799325942993164, "avg_line_length": 56.21686935424805, "blob_id": "18e35abc8b155dfa2d27439dc507764993e1800b", "content_id": "d491c70e371228c9875c1c7b1781c0940204386c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4749, "license_type": "permissive", "max_line_length": 576, "num_lines": 83, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_ami_find.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Returns list of matching AMIs with AMI ID, along with other useful information\n # Can search AMIs with different owners\n # Can search by matching tag(s), by AMI name and/or other criteria\n # Results can be sorted and sliced\n class Ec2_ami_find < Base\n # @return [Object] The AWS region to use.\n attribute :region\n validates :region, presence: true\n\n # @return [String, nil] Search AMIs owned by the specified owner,Can specify an AWS account ID, or one of the special IDs 'self', 'amazon' or 'aws-marketplace',If not specified, all EC2 AMIs in the specified region will be searched.,You can include wildcards in many of the search options. An asterisk (*) matches zero or more characters, and a question mark (?) matches exactly one character. You can escape special characters using a backslash (\\) before the character. For example, a value of \\*amazon\\?\\\\ searches for the literal string *amazon?\\.\n attribute :owner\n validates :owner, type: String\n\n # @return [Object, nil] An AMI ID to match.\n attribute :ami_id\n\n # @return [Hash, nil] A hash/dictionary of tags to match for the AMI.\n attribute :ami_tags\n validates :ami_tags, type: Hash\n\n # @return [Object, nil] An architecture type to match (e.g. x86_64).\n attribute :architecture\n\n # @return [Object, nil] A hypervisor type type to match (e.g. xen).\n attribute :hypervisor\n\n # @return [Symbol, nil] Whether or not the image(s) are public.\n attribute :is_public\n validates :is_public, type: Symbol\n\n # @return [String, nil] An AMI name to match.\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] Platform type to match.\n attribute :platform\n\n # @return [Object, nil] Marketplace product code to match.\n attribute :product_code\n\n # @return [:name, :description, :tag, :architecture, :block_device_mapping, :creationDate, :hypervisor, :is_public, :location, :owner_id, :platform, :root_device_name, :root_device_type, :state, :virtualization_type, nil] Optional attribute which with to sort the results.,If specifying 'tag', the 'tag_name' parameter is required.,Starting at version 2.1, additional sort choices of architecture, block_device_mapping, creationDate, hypervisor, is_public, location, owner_id, platform, root_device_name, root_device_type, state, and virtualization_type are supported.\n attribute :sort\n validates :sort, expression_inclusion: {:in=>[:name, :description, :tag, :architecture, :block_device_mapping, :creationDate, :hypervisor, :is_public, :location, :owner_id, :platform, :root_device_name, :root_device_type, :state, :virtualization_type], :message=>\"%{value} needs to be :name, :description, :tag, :architecture, :block_device_mapping, :creationDate, :hypervisor, :is_public, :location, :owner_id, :platform, :root_device_name, :root_device_type, :state, :virtualization_type\"}, allow_nil: true\n\n # @return [Object, nil] Tag name with which to sort results.,Required when specifying 'sort=tag'.\n attribute :sort_tag\n\n # @return [:ascending, :descending, nil] Order in which to sort results.,Only used when the 'sort' parameter is specified.\n attribute :sort_order\n validates :sort_order, expression_inclusion: {:in=>[:ascending, :descending], :message=>\"%{value} needs to be :ascending, :descending\"}, allow_nil: true\n\n # @return [Object, nil] Which result to start with (when sorting).,Corresponds to Python slice notation.\n attribute :sort_start\n\n # @return [Integer, nil] Which result to end with (when sorting).,Corresponds to Python slice notation.\n attribute :sort_end\n validates :sort_end, type: Integer\n\n # @return [String, nil] AMI state to match.\n attribute :state\n validates :state, type: String\n\n # @return [Object, nil] Virtualization type to match (e.g. hvm).\n attribute :virtualization_type\n\n # @return [Object, nil] Root device type to match (e.g. ebs, instance-store).\n attribute :root_device_type\n\n # @return [:success, :fail, nil] What to do when no results are found.,'success' reports success and returns an empty array,'fail' causes the module to report failure\n attribute :no_result_action\n validates :no_result_action, expression_inclusion: {:in=>[:success, :fail], :message=>\"%{value} needs to be :success, :fail\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7080459594726562, "alphanum_fraction": 0.7080459594726562, "avg_line_length": 26.1875, "blob_id": "8c9cf0f0e80898eecd6c9ca841812c53f9e50d7f", "content_id": "8081a59e6777b6ca5ccef415a15e4ce2814d46bf", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 435, "license_type": "permissive", "max_line_length": 108, "num_lines": 16, "path": "/lib/ansible/ruby/modules/generated/windows/win_whoami.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Designed to return the same information as the C(whoami /all) command.\n # Also includes information missing from C(whoami) such as logon metadata like logon rights, id, type.\n class Win_whoami < Base\n\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6735751032829285, "alphanum_fraction": 0.6735751032829285, "avg_line_length": 37.599998474121094, "blob_id": "2e3d40ad1af25535aa7ab7bb51bf1b107000fe70", "content_id": "5c37ebf4cd9b46aa4c68bf3706e957acfd94d604", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1158, "license_type": "permissive", "max_line_length": 176, "num_lines": 30, "path": "/lib/ansible/ruby/modules/generated/windows/win_tempfile.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates temporary files and directories.\n # For non-Windows targets, please use the M(tempfile) module instead.\n class Win_tempfile < Base\n # @return [:directory, :file, nil] Whether to create file or directory.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:directory, :file], :message=>\"%{value} needs to be :directory, :file\"}, allow_nil: true\n\n # @return [String, nil] Location where temporary file or directory should be created.,If path is not specified default system temporary directory (%TEMP%) will be used.\n attribute :path\n validates :path, type: String\n\n # @return [String, nil] Prefix of file/directory name created by module.\n attribute :prefix\n validates :prefix, type: String\n\n # @return [String, nil] Suffix of file/directory name created by module.\n attribute :suffix\n validates :suffix, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6637653112411499, "alphanum_fraction": 0.6663442850112915, "avg_line_length": 55.400001525878906, "blob_id": "c0aa005f81f98e410ba2e2ca9824ddf8aa56dd4d", "content_id": "4ff9c470bd1c72e41368d177f5a5f02717b33663", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3102, "license_type": "permissive", "max_line_length": 319, "num_lines": 55, "path": "/lib/ansible/ruby/modules/generated/packaging/os/zypper_repository.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove Zypper repositories on SUSE and openSUSE\n class Zypper_repository < Base\n # @return [String, nil] A name for the repository. Not required when adding repofiles.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] URI of the repository or .repo file. Required when state=present.\n attribute :repo\n validates :repo, type: String\n\n # @return [:absent, :present, nil] A source string state.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [Object, nil] A description of the repository\n attribute :description\n\n # @return [:yes, :no, nil] Whether to disable GPG signature checking of all packages. Has an effect only if state is I(present).,Needs zypper version >= 1.6.2.\n attribute :disable_gpg_check\n validates :disable_gpg_check, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Enable autorefresh of the repository.\n attribute :autorefresh\n validates :autorefresh, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Set priority of repository. Packages will always be installed from the repository with the smallest priority number.,Needs zypper version >= 1.12.25.\n attribute :priority\n\n # @return [:yes, :no, nil] Overwrite multiple repository entries, if repositories with both name and URL already exist.\n attribute :overwrite_multiple\n validates :overwrite_multiple, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Automatically import the gpg signing key of the new or changed repository.,Has an effect only if state is I(present). Has no effect on existing (unchanged) repositories or in combination with I(absent).,Implies runrefresh.,Only works with C(.repo) files if `name` is given explicitly.\n attribute :auto_import_keys\n validates :auto_import_keys, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Refresh the package list of the given repository.,Can be used with repo=* to refresh all repositories.\n attribute :runrefresh\n validates :runrefresh, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Set repository to enabled (or disabled).\n attribute :enabled\n validates :enabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6862271428108215, "alphanum_fraction": 0.6886433959007263, "avg_line_length": 65.59770202636719, "blob_id": "7a6891a13d360d9b52d281caf7d4159b54a131bb", "content_id": "63b9a363874dd9354ab7b76e9e8949deea1d6ccf", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5794, "license_type": "permissive", "max_line_length": 451, "num_lines": 87, "path": "/lib/ansible/ruby/modules/generated/windows/win_uri.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Interacts with FTP, HTTP and HTTPS web services.\n # Supports Digest, Basic and WSSE HTTP authentication mechanisms.\n # For non-Windows targets, use the M(uri) module instead.\n class Win_uri < Base\n # @return [String] Supports FTP, HTTP or HTTPS URLs in the form of (ftp|http|https)://host.domain:port/path.\n attribute :url\n validates :url, presence: true, type: String\n\n # @return [:CONNECT, :DELETE, :GET, :HEAD, :MERGE, :OPTIONS, :PATCH, :POST, :PUT, :REFRESH, :TRACE, nil] The HTTP Method of the request or response.\n attribute :method\n validates :method, expression_inclusion: {:in=>[:CONNECT, :DELETE, :GET, :HEAD, :MERGE, :OPTIONS, :PATCH, :POST, :PUT, :REFRESH, :TRACE], :message=>\"%{value} needs to be :CONNECT, :DELETE, :GET, :HEAD, :MERGE, :OPTIONS, :PATCH, :POST, :PUT, :REFRESH, :TRACE\"}, allow_nil: true\n\n # @return [Object, nil] Sets the \"Content-Type\" header.\n attribute :content_type\n\n # @return [String, nil] The body of the HTTP request/response to the web service.\n attribute :body\n validates :body, type: String\n\n # @return [Object, nil] Username to use for authentication.\n attribute :user\n\n # @return [Object, nil] Password to use for authentication.\n attribute :password\n\n # @return [:yes, :no, nil] By default the authentication information is only sent when a webservice responds to an initial request with a 401 status. Since some basic auth services do not properly send a 401, logins will fail.,This option forces the sending of the Basic authentication header upon the initial request.\n attribute :force_basic_auth\n validates :force_basic_auth, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Output the response body to a file.\n attribute :dest\n validates :dest, type: String\n\n # @return [Hash, nil] Extra headers to set on the request, see the examples for more details on how to set this.\n attribute :headers\n validates :headers, type: Hash\n\n # @return [String, nil] A filename, when it already exists, this step will be skipped.\n attribute :creates\n validates :creates, type: String\n\n # @return [String, nil] A filename, when it does not exist, this step will be skipped.\n attribute :removes\n validates :removes, type: String\n\n # @return [:yes, :no, nil] Whether or not to return the body of the response as a \"content\" key in the dictionary result. If the reported Content-type is \"application/json\", then the JSON is additionally loaded into a key called C(json) in the dictionary results.\n attribute :return_content\n validates :return_content, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] A valid, numeric, HTTP status code that signifies success of the request.,Can also be comma separated list of status codes.\n attribute :status_code\n validates :status_code, type: TypeGeneric.new(String)\n\n # @return [Integer, nil] Specifies how long the request can be pending before it times out (in seconds).,The value 0 (zero) specifies an indefinite time-out.,A Domain Name System (DNS) query can take up to 15 seconds to return or time out. If your request contains a host name that requires resolution, and you set C(timeout) to a value greater than zero, but less than 15 seconds, it can take 15 seconds or more before your request times out.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [:all, :none, :safe, nil] Whether or not the C(win_uri) module should follow redirects.,C(all) will follow all redirects.,C(none) will not follow any redirects.,C(safe) will follow only \"safe\" redirects, where \"safe\" means that the client is only doing a C(GET) or C(HEAD) on the URI to which it is being redirected.\n attribute :follow_redirects\n validates :follow_redirects, expression_inclusion: {:in=>[:all, :none, :safe], :message=>\"%{value} needs to be :all, :none, :safe\"}, allow_nil: true\n\n # @return [Integer, nil] Specifies how many times C(win_uri) redirects a connection to an alternate Uniform Resource Identifier (URI) before the connection fails.,If C(maximum_redirection) is set to 0 (zero) or C(follow_redirects) is set to C(none), or set to C(safe) when not doing C(GET) or C(HEAD) it prevents all redirection.\n attribute :maximum_redirection\n validates :maximum_redirection, type: Integer\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated. This should only set to C(no) used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Specifies the client certificate (.pfx) that is used for a secure web request.,The WinRM connection must be authenticated with C(CredSSP) if the certificate file is not password protected.,Other authentication types can set I(client_cert_password) when the cert is password protected.\n attribute :client_cert\n validates :client_cert, type: String\n\n # @return [Object, nil] The password for the client certificate (.pfx) file that is used for a secure web request.\n attribute :client_cert_password\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5725646018981934, "alphanum_fraction": 0.5725646018981934, "avg_line_length": 19.95833396911621, "blob_id": "f8497fe7ca91a07b879d23752b6a8e073e3b7936", "content_id": "2323f666ba531250c939963a7b076d59537ee075", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 503, "license_type": "permissive", "max_line_length": 72, "num_lines": 24, "path": "/util/parser/option_data.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# See LICENSE.txt for license\nmodule Ansible\n module Ruby\n module Parser\n class OptionData\n attr_reader :types, :name, :description, :choices\n\n def initialize(name:, description:, required:, types:, choices:)\n @types = types\n @description = description\n @name = name\n @required = required\n @choices = choices\n end\n\n def required?\n @required\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6730058193206787, "alphanum_fraction": 0.6761753559112549, "avg_line_length": 50.16216278076172, "blob_id": "d8a28545f15d880cbb139e7981fcf0cb9f19d5a9", "content_id": "01e00e7a78af69c75be66d95e8d7414dfc224f96", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1893, "license_type": "permissive", "max_line_length": 197, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_interface_policy_l2.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage Layer 2 interface policies on Cisco ACI fabrics.\n class Aci_interface_policy_l2 < Base\n # @return [String] The name of the Layer 2 interface policy.\n attribute :l2_policy\n validates :l2_policy, presence: true, type: String\n\n # @return [String, nil] The description of the Layer 2 interface policy.\n attribute :description\n validates :description, type: String\n\n # @return [:core, :disabled, :edge, nil] Determines if QinQ is disabled or if the port should be considered a core or edge port.,The APIC defaults to C(disabled) when unset during creation.\n attribute :qinq\n validates :qinq, expression_inclusion: {:in=>[:core, :disabled, :edge], :message=>\"%{value} needs to be :core, :disabled, :edge\"}, allow_nil: true\n\n # @return [Symbol, nil] Determines if Virtual Ethernet Port Aggregator is disabled or enabled.,The APIC defaults to C(no) when unset during creation.\n attribute :vepa\n validates :vepa, type: Symbol\n\n # @return [:global, :portlocal, nil] The scope of the VLAN.,The APIC defaults to C(global) when unset during creation.\n attribute :vlan_scope\n validates :vlan_scope, expression_inclusion: {:in=>[:global, :portlocal], :message=>\"%{value} needs to be :global, :portlocal\"}, allow_nil: true\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7139211893081665, "alphanum_fraction": 0.7198752760887146, "avg_line_length": 61.98214340209961, "blob_id": "d2e27dd582a003161b15e7d7312594a392ae1506", "content_id": "f5980543f19744820a38c40aa30b6ef327a356c2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3527, "license_type": "permissive", "max_line_length": 299, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/net_tools/nios/nios_naptr_record.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Adds and/or removes instances of NAPTR record objects from Infoblox NIOS servers. This module manages NIOS C(record:naptr) objects using the Infoblox WAPI interface over REST.\n class Nios_naptr_record < Base\n # @return [String] Specifies the fully qualified hostname to add or remove from the system\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] Sets the DNS view to associate this a record with. The DNS view must already be configured on the system\n attribute :view\n validates :view, presence: true, type: String\n\n # @return [Integer] Configures the order (0-65535) for this NAPTR record. This parameter specifies the order in which the NAPTR rules are applied when multiple rules are present.\n attribute :order\n validates :order, presence: true, type: Integer\n\n # @return [Integer] Configures the preference (0-65535) for this NAPTR record. The preference field determines the order NAPTR records are processed when multiple records with the same order parameter are present.\n attribute :preference\n validates :preference, presence: true, type: Integer\n\n # @return [String] Configures the replacement field for this NAPTR record. For nonterminal NAPTR records, this field specifies the next domain name to look up.\n attribute :replacement\n validates :replacement, presence: true, type: String\n\n # @return [Object, nil] Configures the services field (128 characters maximum) for this NAPTR record. The services field contains protocol and service identifiers, such as \"http+E2U\" or \"SIPS+D2T\".\n attribute :services\n\n # @return [Object, nil] Configures the flags field for this NAPTR record. These control the interpretation of the fields for an NAPTR record object. Supported values for the flags field are \"U\", \"S\", \"P\" and \"A\".\n attribute :flags\n\n # @return [Object, nil] Configures the regexp field for this NAPTR record. This is the regular expression-based rewriting rule of the NAPTR record. This should be a POSIX compliant regular expression, including the substitution rule and flags. Refer to RFC 2915 for the field syntax details.\n attribute :regexp\n\n # @return [Object, nil] Configures the TTL to be associated with this NAPTR record\n attribute :ttl\n\n # @return [Object, nil] Allows for the configuration of Extensible Attributes on the instance of the object. This argument accepts a set of key / value pairs for configuration.\n attribute :extattrs\n\n # @return [String, nil] Configures a text string comment to be associated with the instance of this object. The provided text string will be configured on the object instance.\n attribute :comment\n validates :comment, type: String\n\n # @return [:present, :absent, nil] Configures the intended state of the instance of the object on the NIOS server. When this value is set to C(present), the object is configured on the device and when this value is set to C(absent) the value is removed (if necessary) from the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7153356075286865, "alphanum_fraction": 0.716315507888794, "avg_line_length": 48.780487060546875, "blob_id": "f793fe8d1babc59abcad5769ed3f20b94ac7dceb", "content_id": "dd496e388e69acb8e45dea8b20df40e90789a58a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2041, "license_type": "permissive", "max_line_length": 269, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/windows/win_reboot.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Reboot a Windows machine, wait for it to go down, come back up, and respond to commands.\n class Win_reboot < Base\n # @return [Integer, nil] Seconds for shutdown to wait before requesting reboot\n attribute :pre_reboot_delay\n validates :pre_reboot_delay, type: Integer\n\n # @return [Integer, nil] Seconds to wait after the reboot was successful and the connection was re-established,This is useful if you want wait for something to settle despite your connection already working\n attribute :post_reboot_delay\n validates :post_reboot_delay, type: Integer\n\n # @return [Integer, nil] Maximum seconds to wait for shutdown to occur,Increase this timeout for very slow hardware, large update applications, etc,This option has been removed since Ansible 2.5 as the win_reboot behavior has changed\n attribute :shutdown_timeout\n validates :shutdown_timeout, type: Integer\n\n # @return [Integer, nil] Maximum seconds to wait for machine to re-appear on the network and respond to a test command,This timeout is evaluated separately for both network appearance and test command success (so maximum clock time is actually twice this value)\n attribute :reboot_timeout\n validates :reboot_timeout, type: Integer\n\n # @return [Integer, nil] Maximum seconds to wait for a single successful TCP connection to the WinRM endpoint before trying again\n attribute :connect_timeout\n validates :connect_timeout, type: Integer\n\n # @return [String, nil] Command to expect success for to determine the machine is ready for management\n attribute :test_command\n validates :test_command, type: String\n\n # @return [String, nil] Message to display to users\n attribute :msg\n validates :msg, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.676576554775238, "alphanum_fraction": 0.676576554775238, "avg_line_length": 37.27586364746094, "blob_id": "80ab18df267c49de236b6bad4d4680d71e0ba1b2", "content_id": "1a5294e8a215e186b50d5e0f32f19a66e8e48927", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1110, "license_type": "permissive", "max_line_length": 177, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/monitoring/sensu_subscription.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage which I(sensu channels) a machine should subscribe to\n class Sensu_subscription < Base\n # @return [String] The name of the channel\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Whether the machine should subscribe or unsubscribe from the channel\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Path to the subscriptions json file\n attribute :path\n validates :path, type: String\n\n # @return [Symbol, nil] Create a backup file (if yes), including the timestamp information so you,can get the original file back if you somehow clobbered it incorrectly.\n attribute :backup\n validates :backup, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7273135781288147, "alphanum_fraction": 0.7283617854118347, "avg_line_length": 88.04000091552734, "blob_id": "f061e062ecf51e85e91167d751d7e707ade071ac", "content_id": "80bcec90270ce0c9e879942a660693ad115266f9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6678, "license_type": "permissive", "max_line_length": 555, "num_lines": 75, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/cloudformation_stack_set.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Launches/updates/deletes AWS CloudFormation Stack Sets\n class Cloudformation_stack_set < Base\n # @return [String] name of the cloudformation stack set\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] A description of what this stack set creates\n attribute :description\n validates :description, type: String\n\n # @return [Object, nil] A list of hashes of all the template variables for the stack. The value can be a string or a dict.,Dict can be used to set additional template parameter attributes like UsePreviousValue (see example).\n attribute :parameters\n\n # @return [:present, :absent, nil] If state is \"present\", stack will be created. If state is \"present\" and if stack exists and template has changed, it will be updated. If state is \"absent\", stack will be removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] The local path of the cloudformation template.,This must be the full path to the file, relative to the working directory. If using roles this may look like \"roles/cloudformation/files/cloudformation-example.json\".,If 'state' is 'present' and the stack does not exist yet, either 'template', 'template_body' or 'template_url' must be specified (but only one of them). If 'state' is present, the stack does exist, and neither 'template', 'template_body' nor 'template_url' are specified, the previous template will be reused.\n attribute :template\n\n # @return [Object, nil] Template body. Use this to pass in the actual body of the Cloudformation template.,If 'state' is 'present' and the stack does not exist yet, either 'template', 'template_body' or 'template_url' must be specified (but only one of them). If 'state' is present, the stack does exist, and neither 'template', 'template_body' nor 'template_url' are specified, the previous template will be reused.\n attribute :template_body\n\n # @return [String, nil] Location of file containing the template body. The URL must point to a template (max size 307,200 bytes) located in an S3 bucket in the same region as the stack.,If 'state' is 'present' and the stack does not exist yet, either 'template', 'template_body' or 'template_url' must be specified (but only one of them). If 'state' is present, the stack does exist, and neither 'template', 'template_body' nor 'template_url' are specified, the previous template will be reused.\n attribute :template_url\n validates :template_url, type: String\n\n # @return [Boolean, nil] Only applicable when I(state=absent). Sets whether, when deleting a stack set, the stack instances should also be deleted.,By default, instances will be deleted. Set to 'no' or 'false' to keep stacks when stack set is deleted.\n attribute :purge_stacks\n validates :purge_stacks, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Symbol, nil] Whether or not to wait for stack operation to complete. This includes waiting for stack instances to reach UPDATE_COMPLETE status.,If you choose not to wait, this module will not notify when stack operations fail because it will not wait for them to finish.\n attribute :wait\n validates :wait, type: Symbol\n\n # @return [Integer, nil] How long to wait (in seconds) for stacks to complete create/update/delete operations.\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [:CAPABILITY_IAM, :CAPABILITY_NAMED_IAM, nil] Capabilities allow stacks to create and modify IAM resources, which may include adding users or roles.,Currently the only available values are 'CAPABILITY_IAM' and 'CAPABILITY_NAMED_IAM'. Either or both may be provided.,The following resources require that one or both of these parameters is specified: AWS::IAM::AccessKey, AWS::IAM::Group, AWS::IAM::InstanceProfile, AWS::IAM::Policy, AWS::IAM::Role, AWS::IAM::User, AWS::IAM::UserToGroupAddition\\r\\n\n attribute :capabilities\n validates :capabilities, expression_inclusion: {:in=>[:CAPABILITY_IAM, :CAPABILITY_NAMED_IAM], :message=>\"%{value} needs to be :CAPABILITY_IAM, :CAPABILITY_NAMED_IAM\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] A list of AWS regions to create instances of a stack in. The I(region) parameter chooses where the Stack Set is created, and I(regions) specifies the region for stack instances.,At least one region must be specified to create a stack set. On updates, if fewer regions are specified only the specified regions will have their stack instances updated.\n attribute :regions\n validates :regions, type: TypeGeneric.new(String)\n\n # @return [Array<Integer>, Integer, nil] A list of AWS accounts in which to create instance of CloudFormation stacks.,At least one region must be specified to create a stack set. On updates, if fewer regions are specified only the specified regions will have their stack instances updated.\n attribute :accounts\n validates :accounts, type: TypeGeneric.new(Integer)\n\n # @return [Object, nil] ARN of the administration role, meaning the role that CloudFormation Stack Sets use to assume the roles in your child accounts.,This defaults to I(arn:aws:iam::{{ account ID }}:role/AWSCloudFormationStackSetAdministrationRole) where I({{ account ID }}) is replaced with the account number of the current IAM role/user/STS credentials.\n attribute :administration_role_arn\n\n # @return [Object, nil] ARN of the execution role, meaning the role that CloudFormation Stack Sets assumes in your child accounts.,This MUST NOT be an ARN, and the roles must exist in each child account specified.,The default name for the execution role is I(AWSCloudFormationStackSetExecutionRole)\n attribute :execution_role_name\n\n # @return [Hash, nil] Dictionary of tags to associate with stack and its resources during stack creation. Can be updated later, updating tags removes previous entries.\n attribute :tags\n validates :tags, type: Hash\n\n # @return [Object, nil] Settings to change what is considered \"failed\" when running stack instance updates, and how many to do at a time.\n attribute :failure_tolerance\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7073276042938232, "alphanum_fraction": 0.7073276042938232, "avg_line_length": 57, "blob_id": "56392fbcaa9cb8581fa30f7e81c17d0191fe7209", "content_id": "1f6944b79f0a9f57a4fa17819460f34e12044f05", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2320, "license_type": "permissive", "max_line_length": 520, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_policy_rule.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module will manage LTM policy rules on a BIG-IP.\n class Bigip_policy_rule < Base\n # @return [Object, nil] Description of the policy rule.\n attribute :description\n\n # @return [String, Array<Hash>, Hash, nil] The actions that you want the policy rule to perform.,The available attributes vary by the action, however, each action requires that a C(type) be specified.,These conditions can be specified in any order. Despite them being a list, the BIG-IP does not treat their order as anything special.\n attribute :actions\n validates :actions, type: TypeGeneric.new(Hash)\n\n # @return [String] The name of the policy that you want to associate this rule with.\n attribute :policy\n validates :policy, presence: true, type: String\n\n # @return [String] The name of the rule.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, Array<Hash>, Hash, nil] A list of attributes that describe the condition.,See suboptions for details on how to construct each list entry.,The ordering of this list is important, the module will ensure the order is kept when modifying the task.,The suboption options listed below are not required for all condition types, read the description for more details.,These conditions can be specified in any order. Despite them being a list, the BIG-IP does not treat their order as anything special.\n attribute :conditions\n validates :conditions, type: TypeGeneric.new(Hash)\n\n # @return [:present, :absent, nil] When C(present), ensures that the key is uploaded to the device. When C(absent), ensures that the key is removed from the device. If the key is currently in use, the module will not be able to remove the key.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6776859760284424, "alphanum_fraction": 0.6776859760284424, "avg_line_length": 43.448978424072266, "blob_id": "308a8bad5b8d042c6e8f6747709a2efcf8163875", "content_id": "77536b672ed4f08590a397291fa5c08198d9ece3", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2178, "license_type": "permissive", "max_line_length": 166, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_elementsw_volume_pair.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, delete volume pair\n class Na_elementsw_volume_pair < Base\n # @return [:present, :absent, nil] Whether the specified volume pair should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, Integer] Source volume name or volume ID\n attribute :src_volume\n validates :src_volume, presence: true, type: MultipleTypes.new(String, Integer)\n\n # @return [String, Integer] Source account name or ID\n attribute :src_account\n validates :src_account, presence: true, type: MultipleTypes.new(String, Integer)\n\n # @return [String, Integer] Destination volume name or volume ID\n attribute :dest_volume\n validates :dest_volume, presence: true, type: MultipleTypes.new(String, Integer)\n\n # @return [String, Integer] Destination account name or ID\n attribute :dest_account\n validates :dest_account, presence: true, type: MultipleTypes.new(String, Integer)\n\n # @return [:async, :sync, :snapshotsonly, nil] Mode to start the volume pairing\n attribute :mode\n validates :mode, expression_inclusion: {:in=>[:async, :sync, :snapshotsonly], :message=>\"%{value} needs to be :async, :sync, :snapshotsonly\"}, allow_nil: true\n\n # @return [String] Destination IP address of the paired cluster.\n attribute :dest_mvip\n validates :dest_mvip, presence: true, type: String\n\n # @return [String, nil] Destination username for the paired cluster,Optional if this is same as source cluster username.\n attribute :dest_username\n validates :dest_username, type: String\n\n # @return [String, nil] Destination password for the paired cluster,Optional if this is same as source cluster password.\n attribute :dest_password\n validates :dest_password, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7483989000320435, "alphanum_fraction": 0.7488563656806946, "avg_line_length": 74.37931060791016, "blob_id": "6ab53605c4a2e8fe98b8d84282bffb502fd04910", "content_id": "1dd9f89c22d02b12dc87467acd54997c4a0b3f93", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2186, "license_type": "permissive", "max_line_length": 414, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_config.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages a BIG-IP configuration by allowing TMSH commands that modify running configuration, or merge SCF formatted files into the running configuration. Additionally, this module is of significant importance because it allows you to save your running configuration to disk. Since the F5 module only manipulate running configuration, it is important that you utilize this module to save that running config.\n class Bigip_config < Base\n # @return [Boolean, nil] The C(save) argument instructs the module to save the running-config to startup-config.,This operation is performed after any changes are made to the current running config. If no changes are made, the configuration is still saved to the startup config.,This option will always cause the module to return changed.\n attribute :save\n validates :save, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Symbol, nil] Loads the default configuration on the device.,If this option is specified, the default configuration will be loaded before any commands or other provided configuration is run.\n attribute :reset\n validates :reset, type: Symbol\n\n # @return [String, nil] Loads the specified configuration that you want to merge into the running configuration. This is equivalent to using the C(tmsh) command C(load sys config from-terminal merge).,If you need to read configuration from a file or template, use Ansible's C(file) or C(template) lookup plugins respectively.\n attribute :merge_content\n validates :merge_content, type: String\n\n # @return [Symbol, nil] Validates the specified configuration to see whether they are valid to replace the running configuration.,The running configuration will not be changed.,When this parameter is set to C(yes), no change will be reported by the module.\n attribute :verify\n validates :verify, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6148524284362793, "alphanum_fraction": 0.629445493221283, "avg_line_length": 43.26315689086914, "blob_id": "5b0ef87c6e81ef0f3da85e99e3cc36f6410f01ab", "content_id": "0ad138f66261235a26007429a905d8f3f23d3dfb", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 9251, "license_type": "permissive", "max_line_length": 158, "num_lines": 209, "path": "/lib/ansible/ruby/modules/generated/cloud/univention/udm_share.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows to manage samba shares on a univention corporate server (UCS). It uses the python API of the UCS to create a new object or edit it.\n class Udm_share < Base\n # @return [:present, :absent, nil] Whether the share is present or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] Name\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Host FQDN (server which provides the share), e.g. C({{ ansible_fqdn }}). Required if C(state=present).\n attribute :host\n validates :host, type: String\n\n # @return [String, nil] Directory on the providing server, e.g. C(/home). Required if C(state=present).\n attribute :path\n validates :path, type: String\n\n # @return [Object, nil] Windows name. Required if C(state=present).\n attribute :samba_name\n\n # @return [Object] Organisational unit, inside the LDAP Base DN.\n attribute :ou\n validates :ou, presence: true\n\n # @return [Integer, nil] Directory owner of the share's root directory.\n attribute :owner\n validates :owner, type: Integer\n\n # @return [String, nil] Directory owner group of the share's root directory.\n attribute :group\n validates :group, type: String\n\n # @return [String, nil] Permissions for the share's root directory.\n attribute :directorymode\n validates :directorymode, type: String\n\n # @return [0, 1, nil] Modify user ID for root user (root squashing).\n attribute :root_squash\n validates :root_squash, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [0, 1, nil] Subtree checking.\n attribute :subtree_checking\n validates :subtree_checking, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [String, nil] NFS synchronisation.\n attribute :sync\n validates :sync, type: String\n\n # @return [0, 1, nil] NFS write access.\n attribute :writeable\n validates :writeable, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [Object, nil] Blocking size.\n attribute :samba_block_size\n\n # @return [0, 1, nil] Blocking locks.\n attribute :samba_blocking_locks\n validates :samba_blocking_locks, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [0, 1, nil] Show in Windows network environment.\n attribute :samba_browseable\n validates :samba_browseable, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [String, nil] File mode.\n attribute :samba_create_mode\n validates :samba_create_mode, type: String\n\n # @return [String, nil] Client-side caching policy.\n attribute :samba_csc_policy\n validates :samba_csc_policy, type: String\n\n # @return [Object, nil] Option name in smb.conf and its value.\n attribute :samba_custom_settings\n\n # @return [String, nil] Directory mode.\n attribute :samba_directory_mode\n validates :samba_directory_mode, type: String\n\n # @return [String, nil] Directory security mode.\n attribute :samba_directory_security_mode\n validates :samba_directory_security_mode, type: String\n\n # @return [0, 1, nil] Users with write access may modify permissions.\n attribute :samba_dos_filemode\n validates :samba_dos_filemode, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [0, 1, nil] Fake oplocks.\n attribute :samba_fake_oplocks\n validates :samba_fake_oplocks, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [0, 1, nil] Force file mode.\n attribute :samba_force_create_mode\n validates :samba_force_create_mode, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [0, 1, nil] Force directory mode.\n attribute :samba_force_directory_mode\n validates :samba_force_directory_mode, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [0, 1, nil] Force directory security mode.\n attribute :samba_force_directory_security_mode\n validates :samba_force_directory_security_mode, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [Object, nil] Force group.\n attribute :samba_force_group\n\n # @return [0, 1, nil] Force security mode.\n attribute :samba_force_security_mode\n validates :samba_force_security_mode, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [Object, nil] Force user.\n attribute :samba_force_user\n\n # @return [Object, nil] Hide files.\n attribute :samba_hide_files\n\n # @return [0, 1, nil] Hide unreadable files/directories.\n attribute :samba_hide_unreadable\n validates :samba_hide_unreadable, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [Object, nil] Allowed host/network.\n attribute :samba_hosts_allow\n\n # @return [Object, nil] Denied host/network.\n attribute :samba_hosts_deny\n\n # @return [0, 1, nil] Inherit ACLs.\n attribute :samba_inherit_acls\n validates :samba_inherit_acls, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [0, 1, nil] Create files/directories with the owner of the parent directory.\n attribute :samba_inherit_owner\n validates :samba_inherit_owner, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [0, 1, nil] Create files/directories with permissions of the parent directory.\n attribute :samba_inherit_permissions\n validates :samba_inherit_permissions, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [Object, nil] Invalid users or groups.\n attribute :samba_invalid_users\n\n # @return [0, 1, nil] Level 2 oplocks.\n attribute :samba_level_2_oplocks\n validates :samba_level_2_oplocks, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [0, 1, nil] Locking.\n attribute :samba_locking\n validates :samba_locking, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [0, 1, nil] MSDFS root.\n attribute :samba_msdfs_root\n validates :samba_msdfs_root, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [0, 1, nil] NT ACL support.\n attribute :samba_nt_acl_support\n validates :samba_nt_acl_support, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [0, 1, nil] Oplocks.\n attribute :samba_oplocks\n validates :samba_oplocks, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [Object, nil] Postexec script.\n attribute :samba_postexec\n\n # @return [Object, nil] Preexec script.\n attribute :samba_preexec\n\n # @return [0, 1, nil] Allow anonymous read-only access with a guest user.\n attribute :samba_public\n validates :samba_public, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [String, nil] Security mode.\n attribute :samba_security_mode\n validates :samba_security_mode, type: String\n\n # @return [String, nil] Strict locking.\n attribute :samba_strict_locking\n validates :samba_strict_locking, type: String\n\n # @return [Object, nil] VFS objects.\n attribute :samba_vfs_objects\n\n # @return [Object, nil] Valid users or groups.\n attribute :samba_valid_users\n\n # @return [Object, nil] Restrict write access to these users/groups.\n attribute :samba_write_list\n\n # @return [0, 1, nil] Samba write access.\n attribute :samba_writeable\n validates :samba_writeable, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [Object, nil] Only allow access for this host, IP address or network.\n attribute :nfs_hosts\n\n # @return [Object, nil] Option name in exports file.\n attribute :nfs_custom_settings\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.673202633857727, "alphanum_fraction": 0.673202633857727, "avg_line_length": 29.600000381469727, "blob_id": "0d792f3ec4553fa6c761e054b14752e25d36e073", "content_id": "59de74d48dd8e57d5b48f54783afa98e7277994f", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 765, "license_type": "permissive", "max_line_length": 70, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_vmkernel_ip_config.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configure the VMkernel IP Address\n class Vmware_vmkernel_ip_config < Base\n # @return [String] VMkernel interface name\n attribute :vmk_name\n validates :vmk_name, presence: true, type: String\n\n # @return [String] IP address to assign to VMkernel interface\n attribute :ip_address\n validates :ip_address, presence: true, type: String\n\n # @return [String] Subnet Mask to assign to VMkernel interface\n attribute :subnet_mask\n validates :subnet_mask, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6187499761581421, "alphanum_fraction": 0.625, "avg_line_length": 17.461538314819336, "blob_id": "9df3fa1fa2976a9c0f42c07bc6815ee5d7ad3f4e", "content_id": "c08b13f228060db18b112c283eef29987e7ba294", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 480, "license_type": "permissive", "max_line_length": 52, "num_lines": 26, "path": "/examples/block.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nplay 'block fun' do\n local_host\n\n # Compiles to an ansible 'include'\n ansible_include 'inclusion.yml' do\n variables howdy: 123\n end\n\n block do\n task 'say hello' do\n result = command 'uname'\n\n failed_when \"'Linux' not in #{result.stdout}\"\n end\n\n task 'and goodbye' do\n result = command 'uname -a ' + jinja('foo')\n\n failed_when \"'Darwin' not in #{result.stdout}\"\n end\n\n ansible_when jinja('stuff')\n end\nend\n" }, { "alpha_fraction": 0.69972825050354, "alphanum_fraction": 0.706793487071991, "avg_line_length": 50.83098602294922, "blob_id": "25840cd1a702b1b6a9965e9185a1aea0b13d8dae", "content_id": "eea75e6d99d78ace4fa6b909635b547973878416", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3680, "license_type": "permissive", "max_line_length": 360, "num_lines": 71, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_gslbhealthmonitor.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure GslbHealthMonitor object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_gslbhealthmonitor < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [Object, nil] User defined description for the object.\n attribute :description\n\n # @return [Object, nil] Healthmonitordns settings for gslbhealthmonitor.\n attribute :dns_monitor\n\n # @return [Object, nil] Healthmonitorexternal settings for gslbhealthmonitor.\n attribute :external_monitor\n\n # @return [Object, nil] Number of continuous failed health checks before the server is marked down.,Allowed values are 1-50.,Default value when not specified in API or module is interpreted by Avi Controller as 2.\n attribute :failed_checks\n\n # @return [Object, nil] Healthmonitorhttp settings for gslbhealthmonitor.\n attribute :http_monitor\n\n # @return [Object, nil] Healthmonitorhttp settings for gslbhealthmonitor.\n attribute :https_monitor\n\n # @return [Object, nil] Use this port instead of the port defined for the server in the pool.,If the monitor succeeds to this port, the load balanced traffic will still be sent to the port of the server defined within the pool.,Allowed values are 1-65535.,Special values are 0 - 'use server port'.\n attribute :monitor_port\n\n # @return [String] A user friendly name for this health monitor.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] A valid response from the server is expected within the receive timeout window.,This timeout must be less than the send interval.,If server status is regularly flapping up and down, consider increasing this value.,Allowed values are 1-300.,Default value when not specified in API or module is interpreted by Avi Controller as 4.\n attribute :receive_timeout\n\n # @return [Object, nil] Frequency, in seconds, that monitors are sent to a server.,Allowed values are 1-3600.,Default value when not specified in API or module is interpreted by Avi Controller as 5.\n attribute :send_interval\n\n # @return [Object, nil] Number of continuous successful health checks before server is marked up.,Allowed values are 1-50.,Default value when not specified in API or module is interpreted by Avi Controller as 2.\n attribute :successful_checks\n\n # @return [Object, nil] Healthmonitortcp settings for gslbhealthmonitor.\n attribute :tcp_monitor\n\n # @return [Object, nil] It is a reference to an object of type tenant.\n attribute :tenant_ref\n\n # @return [Object] Type of the health monitor.,Enum options - HEALTH_MONITOR_PING, HEALTH_MONITOR_TCP, HEALTH_MONITOR_HTTP, HEALTH_MONITOR_HTTPS, HEALTH_MONITOR_EXTERNAL, HEALTH_MONITOR_UDP,,HEALTH_MONITOR_DNS, HEALTH_MONITOR_GSLB.\n attribute :type\n validates :type, presence: true\n\n # @return [Object, nil] Healthmonitorudp settings for gslbhealthmonitor.\n attribute :udp_monitor\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Uuid of the health monitor.\n attribute :uuid\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7227723002433777, "alphanum_fraction": 0.7227723002433777, "avg_line_length": 58.96875, "blob_id": "8fb064ed3398667b05bb79ac0def077430f9c6c6", "content_id": "4ee0c54fdbe3eefb54fdfb08e9e915f2cefa81a9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1919, "license_type": "permissive", "max_line_length": 191, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/rds_snapshot_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # obtain facts about one or more RDS snapshots. These can be for unclustered snapshots or snapshots of clustered DBs (Aurora)\n # Aurora snapshot facts may be obtained if no identifier parameters are passed or if one of the cluster parameters are passed.\n class Rds_snapshot_facts < Base\n # @return [String, nil] Name of an RDS (unclustered) snapshot. Mutually exclusive with I(db_instance_identifier), I(db_cluster_identifier), I(db_cluster_snapshot_identifier)\n attribute :db_snapshot_identifier\n validates :db_snapshot_identifier, type: String\n\n # @return [String, nil] RDS instance name for which to find snapshots. Mutually exclusive with I(db_snapshot_identifier), I(db_cluster_identifier), I(db_cluster_snapshot_identifier)\n attribute :db_instance_identifier\n validates :db_instance_identifier, type: String\n\n # @return [Object, nil] RDS cluster name for which to find snapshots. Mutually exclusive with I(db_snapshot_identifier), I(db_instance_identifier), I(db_cluster_snapshot_identifier)\n attribute :db_cluster_identifier\n\n # @return [Object, nil] Name of an RDS cluster snapshot. Mutually exclusive with I(db_instance_identifier), I(db_snapshot_identifier), I(db_cluster_identifier)\n attribute :db_cluster_snapshot_identifier\n\n # @return [:automated, :manual, :shared, :public, nil] Type of snapshot to find. By default both automated and manual snapshots will be returned.\n attribute :snapshot_type\n validates :snapshot_type, expression_inclusion: {:in=>[:automated, :manual, :shared, :public], :message=>\"%{value} needs to be :automated, :manual, :shared, :public\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6695794463157654, "alphanum_fraction": 0.6695794463157654, "avg_line_length": 34.90196228027344, "blob_id": "27fc560a10e136c85d9ee5d589f4175b23bfeaf8", "content_id": "bcef9d2244df3f14c8ab9e76a40f1fbd3b50ab03", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1831, "license_type": "permissive", "max_line_length": 120, "num_lines": 51, "path": "/lib/ansible/ruby/modules/generated/remote_management/redfish/redfish_config.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Builds Redfish URIs locally and sends them to remote OOB controllers to set or update a configuration attribute.\n # Manages BIOS configuration settings.\n # Manages OOB controller configuration settings.\n class Redfish_config < Base\n # @return [String] Category to execute on OOB controller\n attribute :category\n validates :category, presence: true, type: String\n\n # @return [String] List of commands to execute on OOB controller\n attribute :command\n validates :command, presence: true, type: String\n\n # @return [String] Base URI of OOB controller\n attribute :baseuri\n validates :baseuri, presence: true, type: String\n\n # @return [String] User for authentication with OOB controller\n attribute :user\n validates :user, presence: true, type: String\n\n # @return [String] Password for authentication with OOB controller\n attribute :password\n validates :password, presence: true, type: String\n\n # @return [String, nil] name of BIOS attribute to update\n attribute :bios_attr_name\n validates :bios_attr_name, type: String\n\n # @return [String, nil] value of BIOS attribute to update\n attribute :bios_attr_value\n validates :bios_attr_value, type: String\n\n # @return [String, nil] name of Manager attribute to update\n attribute :mgr_attr_name\n validates :mgr_attr_name, type: String\n\n # @return [String, nil] value of Manager attribute to update\n attribute :mgr_attr_value\n validates :mgr_attr_value, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7004910111427307, "alphanum_fraction": 0.7004910111427307, "avg_line_length": 41.13793182373047, "blob_id": "1b8661a9a75bf50f682f21d1ba05934c4ac39c03", "content_id": "51943e13596f242cc8d46842a5fcd6ae0fd1c6ec", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1222, "license_type": "permissive", "max_line_length": 165, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/cloudfront_invalidation.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows for invalidation of a batch of paths for a CloudFront distribution.\n class Cloudfront_invalidation < Base\n # @return [String, nil] The id of the cloudfront distribution to invalidate paths for. Can be specified insted of the alias.\n attribute :distribution_id\n validates :distribution_id, type: String\n\n # @return [String, nil] The alias of the cloudfront distribution to invalidate paths for. Can be specified instead of distribution_id.\n attribute :alias\n validates :alias, type: String\n\n # @return [String, nil] A unique reference identifier for the invalidation paths.\n attribute :caller_reference\n validates :caller_reference, type: String\n\n # @return [Array<String>, String] A list of paths on the distribution to invalidate. Each path should begin with '/'. Wildcards are allowed. eg. '/foo/bar/*'\n attribute :target_paths\n validates :target_paths, presence: true, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6520833373069763, "alphanum_fraction": 0.6520833373069763, "avg_line_length": 36.5, "blob_id": "6de9ea51b927d8aa1d29994728c2b5c1ef57d08b", "content_id": "cc8eeedbcd9536ab2e4cd71c8625accf1a820db0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2400, "license_type": "permissive", "max_line_length": 166, "num_lines": 64, "path": "/lib/ansible/ruby/modules/generated/system/puppet.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Runs I(puppet) agent or apply in a reliable manner.\n class Puppet < Base\n # @return [String, nil] How long to wait for I(puppet) to finish.\n attribute :timeout\n validates :timeout, type: String\n\n # @return [Object, nil] The hostname of the puppetmaster to contact.\n attribute :puppetmaster\n\n # @return [String, nil] Path to an alternate location for puppet modules.\n attribute :modulepath\n validates :modulepath, type: String\n\n # @return [String, nil] Path to the manifest file to run puppet apply on.\n attribute :manifest\n validates :manifest, type: String\n\n # @return [Object, nil] A dict of values to pass in as persistent external facter facts.\n attribute :facts\n\n # @return [String, nil] Basename of the facter output file.\n attribute :facter_basename\n validates :facter_basename, type: String\n\n # @return [String, nil] Puppet environment to be used.\n attribute :environment\n validates :environment, type: String\n\n # @return [:stdout, :syslog, :all, nil] Where the puppet logs should go, if puppet apply is being used. C(all)\\r\\nwill go to both C(stdout) and C(syslog).\\r\\n\n attribute :logdest\n validates :logdest, expression_inclusion: {:in=>[:stdout, :syslog, :all], :message=>\"%{value} needs to be :stdout, :syslog, :all\"}, allow_nil: true\n\n # @return [String, nil] The name to use when handling certificates.\n attribute :certname\n validates :certname, type: String\n\n # @return [Array<String>, String, nil] A comma-separated list of puppet tags to be used.\n attribute :tags\n validates :tags, type: TypeGeneric.new(String)\n\n # @return [String, nil] Execute a specific piece of Puppet code.,It has no effect with a puppetmaster.\n attribute :execute\n validates :execute, type: String\n\n # @return [Object, nil] Whether to print a transaction summary\n attribute :summarize\n\n # @return [Object, nil] Print extra information\n attribute :verbose\n\n # @return [Object, nil] Enable full debugging\n attribute :debug\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6802054047584534, "alphanum_fraction": 0.6846405267715454, "avg_line_length": 55.3684196472168, "blob_id": "ac18b0645a075abce461b2b0e58246ddad61b836", "content_id": "e80b1f42c553da05e67be24f44aaa66a49d3e920", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4284, "license_type": "permissive", "max_line_length": 235, "num_lines": 76, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_interface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages physical attributes of interfaces of NX-OS switches.\n class Nxos_interface < Base\n # @return [String] Full name of interface, i.e. Ethernet1/1, port-channel10.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:loopback, :portchannel, :svi, :nve, nil] Interface type to be unconfigured from the device.\n attribute :interface_type\n validates :interface_type, expression_inclusion: {:in=>[:loopback, :portchannel, :svi, :nve], :message=>\"%{value} needs to be :loopback, :portchannel, :svi, :nve\"}, allow_nil: true\n\n # @return [Integer, nil] Interface link speed. Applicable for ethernet interface only.\n attribute :speed\n validates :speed, type: Integer\n\n # @return [:up, :down, nil] Administrative state of the interface.\n attribute :admin_state\n validates :admin_state, expression_inclusion: {:in=>[:up, :down], :message=>\"%{value} needs to be :up, :down\"}, allow_nil: true\n\n # @return [String, nil] Interface description.\n attribute :description\n validates :description, type: String\n\n # @return [:layer2, :layer3, nil] Manage Layer 2 or Layer 3 state of the interface. This option is supported for ethernet and portchannel interface. Applicable for ethernet and portchannel interface only.\n attribute :mode\n validates :mode, expression_inclusion: {:in=>[:layer2, :layer3], :message=>\"%{value} needs to be :layer2, :layer3\"}, allow_nil: true\n\n # @return [Object, nil] MTU for a specific interface. Must be an even number between 576 and 9216. Applicable for ethernet interface only.\n attribute :mtu\n\n # @return [:enable, :disable, nil] Enable/Disable ip forward feature on SVIs.\n attribute :ip_forward\n validates :ip_forward, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [Symbol, nil] Associate SVI with anycast gateway under VLAN configuration mode. Applicable for SVI interface only.\n attribute :fabric_forwarding_anycast_gateway\n validates :fabric_forwarding_anycast_gateway, type: Symbol\n\n # @return [:full, :half, :auto, nil] Interface link status. Applicable for ethernet interface only.\n attribute :duplex\n validates :duplex, expression_inclusion: {:in=>[:full, :half, :auto], :message=>\"%{value} needs to be :full, :half, :auto\"}, allow_nil: true\n\n # @return [String, nil] Transmit rate in bits per second (bps).,This is state check parameter only.,Supports conditionals, see L(Conditionals in Networking Modules,../network/user_guide/network_working_with_command_output.html)\n attribute :tx_rate\n validates :tx_rate, type: String\n\n # @return [String, nil] Receiver rate in bits per second (bps).,This is state check parameter only.,Supports conditionals, see L(Conditionals in Networking Modules,../network/user_guide/network_working_with_command_output.html)\n attribute :rx_rate\n validates :rx_rate, type: String\n\n # @return [Array<Hash>, Hash, nil] Check the operational state of given interface C(name) for LLDP neighbor.,The following suboptions are available. This is state check parameter only.\n attribute :neighbors\n validates :neighbors, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash, nil] List of Interfaces definitions.\n attribute :aggregate\n validates :aggregate, type: TypeGeneric.new(Hash)\n\n # @return [:present, :absent, :default, nil] Specify desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :default], :message=>\"%{value} needs to be :present, :absent, :default\"}, allow_nil: true\n\n # @return [Integer, nil] Time in seconds to wait before checking for the operational state on remote device. This wait is applicable for operational state arguments.\n attribute :delay\n validates :delay, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6511155962944031, "alphanum_fraction": 0.6511155962944031, "avg_line_length": 24.947368621826172, "blob_id": "3dab88f4443ee39eb3b3e8c467226899225913b8", "content_id": "0d6bff8927c4959527e8ccbf9b68cce9bea593d3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 493, "license_type": "permissive", "max_line_length": 89, "num_lines": 19, "path": "/spec/support/matchers/have_type_generic.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nRSpec::Matchers.define :have_type_generic do |*expected|\n match do |actual|\n @types = actual.types\n generic = @types.find { |t| t.is_a? TypeGeneric }\n @matcher = be_nil\n if @matcher.matches?(generic)\n @no_generics = true\n next false\n end\n @matcher = eq(expected)\n @matcher.matches? generic.klasses\n end\n\n failure_message do |_|\n @no_generics ? \"Could not find generic in types #{@types}\" : @matcher.failure_message\n end\nend\n" }, { "alpha_fraction": 0.6843835711479187, "alphanum_fraction": 0.68876713514328, "avg_line_length": 54.30303192138672, "blob_id": "89cabc06f8c2c69da684face2f7cef7842bbaf63", "content_id": "72bebb8e122fd19171b38e5ea881d7a3b34eb5f2", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1825, "license_type": "permissive", "max_line_length": 297, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_device_dns.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage BIG-IP device DNS settings.\n class Bigip_device_dns < Base\n # @return [:enabled, :disabled, :enable, :disable, nil] Specifies whether the system caches DNS lookups or performs the operation each time a lookup is needed. Please note that this applies only to Access Policy Manager features, such as ACLs, web application rewrites, and authentication.\n attribute :cache\n validates :cache, expression_inclusion: {:in=>[:enabled, :disabled, :enable, :disable], :message=>\"%{value} needs to be :enabled, :disabled, :enable, :disable\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] A list of name servers that the system uses to validate DNS lookups\n attribute :name_servers\n validates :name_servers, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] A list of domains that the system searches for local domain lookups, to resolve local host names.\n attribute :search\n validates :search, type: TypeGeneric.new(String)\n\n # @return [4, 6, nil] Specifies whether the DNS specifies IP addresses using IPv4 or IPv6.\n attribute :ip_version\n validates :ip_version, expression_inclusion: {:in=>[4, 6], :message=>\"%{value} needs to be 4, 6\"}, allow_nil: true\n\n # @return [:absent, :present, nil] The state of the variable on the system. When C(present), guarantees that an existing variable is set to C(value).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6590909361839294, "alphanum_fraction": 0.6590909361839294, "avg_line_length": 37.5, "blob_id": "aad39e830690859e35e89079c92406728e1489e9", "content_id": "dacb4db9b2e1c5275212584bfa3ad9df50182755", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1540, "license_type": "permissive", "max_line_length": 163, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_loadbalancer_rule_member.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add and remove load balancer rule members.\n class Cs_loadbalancer_rule_member < Base\n # @return [String] The name of the load balancer rule.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Public IP address from where the network traffic will be load balanced from.,Only needed to find the rule if C(name) is not unique.\n attribute :ip_address\n\n # @return [Array<String>, String] List of VMs to assign to or remove from the rule.\n attribute :vms\n validates :vms, presence: true, type: TypeGeneric.new(String)\n\n # @return [:present, :absent, nil] Should the VMs be present or absent from the rule.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Name of the project the firewall rule is related to.\n attribute :project\n\n # @return [Object, nil] Domain the rule is related to.\n attribute :domain\n\n # @return [Object, nil] Account the rule is related to.\n attribute :account\n\n # @return [Object, nil] Name of the zone in which the rule should be located.,If not set, default zone is used.\n attribute :zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7332421541213989, "alphanum_fraction": 0.7346101403236389, "avg_line_length": 44.6875, "blob_id": "d4a8aba10d2871a4da58c1d419adc88a4d5084a5", "content_id": "716c12a9173f395889322f664933c367ae5e9969", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 731, "license_type": "permissive", "max_line_length": 401, "num_lines": 16, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_az_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gather facts about availability zones in AWS.\n class Aws_az_facts < Base\n # @return [Object, nil] A dict of filters to apply. Each dict item consists of a filter key and a filter value. See U(https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeAvailabilityZones.html) for possible filters. Filter names and values are case sensitive. You can also use underscores instead of dashes (-) in the filter keys, which will take precedence in case of conflict.\n attribute :filters\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7067300081253052, "alphanum_fraction": 0.7093060612678528, "avg_line_length": 79.66233825683594, "blob_id": "db806e20b9c2f5d95d0cd95c3edf90011bf19a02", "content_id": "4fe609e889e9391ae206f0471ff9f602aa861a05", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 12422, "license_type": "permissive", "max_line_length": 643, "num_lines": 154, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_clusters.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Module to manage clusters in oVirt/RHV\n class Ovirt_cluster < Base\n # @return [String] Name of the cluster to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Should the cluster be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Datacenter name where cluster reside.\n attribute :data_center\n validates :data_center, type: String\n\n # @return [String, nil] Description of the cluster.\n attribute :description\n validates :description, type: String\n\n # @return [Object, nil] Comment of the cluster.\n attribute :comment\n\n # @return [Object, nil] Management network of cluster to access cluster hosts.\n attribute :network\n\n # @return [Boolean, nil] If I(True) enable memory balloon optimization. Memory balloon is used to re-distribute / reclaim the host memory based on VM needs in a dynamic way.\n attribute :ballooning\n validates :ballooning, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] If I(True), hosts in this cluster will be used to run virtual machines.\n attribute :virt\n\n # @return [Boolean, nil] If I(True), hosts in this cluster will be used as Gluster Storage server nodes, and not for running virtual machines.,By default the cluster is created for virtual machine hosts.\n attribute :gluster\n validates :gluster, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] If I(True) the exposed host threads would be treated as cores which can be utilized by virtual machines.\n attribute :threads_as_cores\n validates :threads_as_cores, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] I I(True) MoM enables to run Kernel Same-page Merging I(KSM) when necessary and when it can yield a memory saving benefit that outweighs its CPU cost.\n attribute :ksm\n\n # @return [Boolean, nil] If I(True) enables KSM C(ksm) for best performance inside NUMA nodes.\n attribute :ksm_numa\n validates :ksm_numa, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] If I(True) enables the oVirt/RHV to monitor cluster capacity for highly available virtual machines.\n attribute :ha_reservation\n validates :ha_reservation, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] If I(True) enables integration with an OpenAttestation server.\n attribute :trusted_service\n validates :trusted_service, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] If I(True) enables an optional reason field when a virtual machine is shut down from the Manager, allowing the administrator to provide an explanation for the maintenance.\n attribute :vm_reason\n validates :vm_reason, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] If I(True) enables an optional reason field when a host is placed into maintenance mode from the Manager, allowing the administrator to provide an explanation for the maintenance.\n attribute :host_reason\n validates :host_reason, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:disabled, :server, :desktop, nil] I(disabled) - Disables memory page sharing.,I(server) - Sets the memory page sharing threshold to 150% of the system memory on each host.,I(desktop) - Sets the memory page sharing threshold to 200% of the system memory on each host.\n attribute :memory_policy\n validates :memory_policy, expression_inclusion: {:in=>[:disabled, :server, :desktop], :message=>\"%{value} needs to be :disabled, :server, :desktop\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] List that specify the random number generator devices that all hosts in the cluster will use.,Supported generators are: I(hwrng) and I(random).\n attribute :rng_sources\n validates :rng_sources, type: TypeGeneric.new(String)\n\n # @return [Object, nil] The proxy by which the SPICE client will connect to virtual machines.,The address must be in the following format: I(protocol://[host]:[port])\n attribute :spice_proxy\n\n # @return [Object, nil] If I(True) enables fencing on the cluster.,Fencing is enabled by default.\n attribute :fence_enabled\n\n # @return [Object, nil] If I(True) any hosts in the cluster that are Non Responsive and still connected to storage will not be fenced.\n attribute :fence_skip_if_sd_active\n\n # @return [Object, nil] If I(True) fencing will be temporarily disabled if the percentage of hosts in the cluster that are experiencing connectivity issues is greater than or equal to the defined threshold.,The threshold can be specified by C(fence_connectivity_threshold).\n attribute :fence_skip_if_connectivity_broken\n\n # @return [Object, nil] The threshold used by C(fence_skip_if_connectivity_broken).\n attribute :fence_connectivity_threshold\n\n # @return [:do_not_migrate, :migrate, :migrate_highly_available, nil] The resilience policy defines how the virtual machines are prioritized in the migration.,Following values are supported:,C(do_not_migrate) - Prevents virtual machines from being migrated. ,C(migrate) - Migrates all virtual machines in order of their defined priority.,C(migrate_highly_available) - Migrates only highly available virtual machines to prevent overloading other hosts.\n attribute :resilience_policy\n validates :resilience_policy, expression_inclusion: {:in=>[:do_not_migrate, :migrate, :migrate_highly_available], :message=>\"%{value} needs to be :do_not_migrate, :migrate, :migrate_highly_available\"}, allow_nil: true\n\n # @return [:auto, :hypervisor_default, :custom, nil] The bandwidth settings define the maximum bandwidth of both outgoing and incoming migrations per host.,Following bandwidth options are supported:,C(auto) - Bandwidth is copied from the I(rate limit) [Mbps] setting in the data center host network QoS.,C(hypervisor_default) - Bandwidth is controlled by local VDSM setting on sending host.,C(custom) - Defined by user (in Mbps).\n attribute :migration_bandwidth\n validates :migration_bandwidth, expression_inclusion: {:in=>[:auto, :hypervisor_default, :custom], :message=>\"%{value} needs to be :auto, :hypervisor_default, :custom\"}, allow_nil: true\n\n # @return [Object, nil] Set the I(custom) migration bandwidth limit.,This parameter is used only when C(migration_bandwidth) is I(custom).\n attribute :migration_bandwidth_limit\n\n # @return [:true, :false, :inherit, nil] If I(True) auto-convergence is used during live migration of virtual machines.,Used only when C(migration_policy) is set to I(legacy).,Following options are supported:,C(true) - Override the global setting to I(true).,C(false) - Override the global setting to I(false).,C(inherit) - Use value which is set globally.\n attribute :migration_auto_converge\n validates :migration_auto_converge, expression_inclusion: {:in=>[:true, :false, :inherit], :message=>\"%{value} needs to be :true, :false, :inherit\"}, allow_nil: true\n\n # @return [:true, :false, :inherit, nil] If I(True) compression is used during live migration of the virtual machine.,Used only when C(migration_policy) is set to I(legacy).,Following options are supported:,C(true) - Override the global setting to I(true).,C(false) - Override the global setting to I(false).,C(inherit) - Use value which is set globally.\n attribute :migration_compressed\n validates :migration_compressed, expression_inclusion: {:in=>[:true, :false, :inherit], :message=>\"%{value} needs to be :true, :false, :inherit\"}, allow_nil: true\n\n # @return [:legacy, :minimal_downtime, :suspend_workload, :post_copy, nil] A migration policy defines the conditions for live migrating virtual machines in the event of host failure.,Following policies are supported:,C(legacy) - Legacy behavior of 3.6 version.,C(minimal_downtime) - Virtual machines should not experience any significant downtime.,C(suspend_workload) - Virtual machines may experience a more significant downtime.,C(post_copy) - Virtual machines should not experience any significant downtime. If the VM migration is not converging for a long time, the migration will be switched to post-copy. Added in version I(2.4).\n attribute :migration_policy\n validates :migration_policy, expression_inclusion: {:in=>[:legacy, :minimal_downtime, :suspend_workload, :post_copy], :message=>\"%{value} needs to be :legacy, :minimal_downtime, :suspend_workload, :post_copy\"}, allow_nil: true\n\n # @return [Object, nil] Specify a serial number policy for the virtual machines in the cluster.,Following options are supported:,C(vm) - Sets the virtual machine's UUID as its serial number.,C(host) - Sets the host's UUID as the virtual machine's serial number.,C(custom) - Allows you to specify a custom serial number in C(serial_policy_value).\n attribute :serial_policy\n\n # @return [Object, nil] Allows you to specify a custom serial number.,This parameter is used only when C(serial_policy) is I(custom).\n attribute :serial_policy_value\n\n # @return [Object, nil] Name of the scheduling policy to be used for cluster.\n attribute :scheduling_policy\n\n # @return [Object, nil] Custom scheduling policy properties of the cluster.,These optional properties override the properties of the scheduling policy specified by the C(scheduling_policy) parameter.\n attribute :scheduling_policy_properties\n\n # @return [:x86_64, :ppc64, :undefined, nil] CPU architecture of cluster.\n attribute :cpu_arch\n validates :cpu_arch, expression_inclusion: {:in=>[:x86_64, :ppc64, :undefined], :message=>\"%{value} needs to be :x86_64, :ppc64, :undefined\"}, allow_nil: true\n\n # @return [String, nil] CPU codename. For example I(Intel SandyBridge Family).\n attribute :cpu_type\n validates :cpu_type, type: String\n\n # @return [:legacy, :ovs, nil] Type of switch to be used by all networks in given cluster. Either I(legacy) which is using linux bridge or I(ovs) using Open vSwitch.\n attribute :switch_type\n validates :switch_type, expression_inclusion: {:in=>[:legacy, :ovs], :message=>\"%{value} needs to be :legacy, :ovs\"}, allow_nil: true\n\n # @return [Float, nil] The compatibility version of the cluster. All hosts in this cluster must support at least this compatibility version.\n attribute :compatibility_version\n validates :compatibility_version, type: Float\n\n # @return [Object, nil] MAC pool to be used by this cluster.,C(Note:),This is supported since oVirt version 4.1.\n attribute :mac_pool\n\n # @return [Array<Hash>, Hash, nil] List of references to the external network providers available in the cluster. If the automatic deployment of the external network provider is supported, the networks of the referenced network provider are available on every host in the cluster.,External network provider is described by following dictionary:,C(name) - Name of the external network provider. Either C(name) or C(id) is required.,C(id) - ID of the external network provider. Either C(name) or C(id) is required.,This is supported since oVirt version 4.2.\n attribute :external_network_providers\n validates :external_network_providers, type: TypeGeneric.new(Hash)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6429651975631714, "alphanum_fraction": 0.6429651975631714, "avg_line_length": 43.06666564941406, "blob_id": "b2b7b7b70325dfe037fa58b285e8b915fc1bd2dc", "content_id": "0254b92f57a52cfb1bb4dce0c83932febf366a91", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1983, "license_type": "permissive", "max_line_length": 204, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_firewall_policy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage a firewall policy for an Ontap Cluster\n class Na_ontap_firewall_policy < Base\n # @return [:present, :absent, nil] Whether to set up a fire policy or not\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] A list of IPs and masks to use\n attribute :allow_list\n validates :allow_list, type: TypeGeneric.new(String)\n\n # @return [String] A policy name for the firewall policy\n attribute :policy\n validates :policy, presence: true, type: String\n\n # @return [:http, :https, :ntp, :rsh, :snmp, :ssh, :telnet] The service to apply the policy to\n attribute :service\n validates :service, presence: true, expression_inclusion: {:in=>[:http, :https, :ntp, :rsh, :snmp, :ssh, :telnet], :message=>\"%{value} needs to be :http, :https, :ntp, :rsh, :snmp, :ssh, :telnet\"}\n\n # @return [String] The Vserver to apply the policy to.\n attribute :vserver\n validates :vserver, presence: true, type: String\n\n # @return [:enable, :disable, nil] enabled firewall\n attribute :enable\n validates :enable, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:enable, :disable, nil] enable logging\n attribute :logging\n validates :logging, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [String] The node to run the firewall configuration on\n attribute :node\n validates :node, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6783447861671448, "alphanum_fraction": 0.6783447861671448, "avg_line_length": 46.45783233642578, "blob_id": "da553ed221d213a076674c886b18f92a58f5efaf", "content_id": "63f8c2e506ec57dc74e882c5d16407d4e6858e20", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3939, "license_type": "permissive", "max_line_length": 297, "num_lines": 83, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_serviceengine.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure ServiceEngine object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_serviceengine < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Object, nil] Availability_zone of serviceengine.\n attribute :availability_zone\n\n # @return [Object, nil] It is a reference to an object of type cloud.\n attribute :cloud_ref\n\n # @return [Symbol, nil] Boolean flag to set container_mode.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :container_mode\n validates :container_mode, type: Symbol\n\n # @return [Object, nil] Enum options - container_type_bridge, container_type_host, container_type_host_dpdk.,Default value when not specified in API or module is interpreted by Avi Controller as CONTAINER_TYPE_HOST.\n attribute :container_type\n\n # @return [Symbol, nil] Boolean flag to set controller_created.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :controller_created\n validates :controller_created, type: Symbol\n\n # @return [Object, nil] Controller_ip of serviceengine.\n attribute :controller_ip\n\n # @return [Object, nil] List of vnic.\n attribute :data_vnics\n\n # @return [Object, nil] Inorder to disable se set this field appropriately.,Enum options - SE_STATE_ENABLED, SE_STATE_DISABLED_FOR_PLACEMENT, SE_STATE_DISABLED, SE_STATE_DISABLED_FORCE.,Default value when not specified in API or module is interpreted by Avi Controller as SE_STATE_ENABLED.\n attribute :enable_state\n\n # @return [Object, nil] Flavor of serviceengine.\n attribute :flavor\n\n # @return [Object, nil] It is a reference to an object of type vimgrhostruntime.\n attribute :host_ref\n\n # @return [Object, nil] Enum options - default, vmware_esx, kvm, vmware_vsan, xen.\n attribute :hypervisor\n\n # @return [Object, nil] Vnic settings for serviceengine.\n attribute :mgmt_vnic\n\n # @return [String, nil] Name of the object.,Default value when not specified in API or module is interpreted by Avi Controller as VM name unknown.\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] Seresources settings for serviceengine.\n attribute :resources\n\n # @return [Object, nil] It is a reference to an object of type serviceenginegroup.\n attribute :se_group_ref\n\n # @return [Object, nil] It is a reference to an object of type tenant.\n attribute :tenant_ref\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Unique object identifier of the object.\n attribute :uuid\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7296798229217529, "alphanum_fraction": 0.7296798229217529, "avg_line_length": 55, "blob_id": "6eece7daa7901c4485c558cb36f3665ffd4a210d", "content_id": "04e09194241b1c1d709e2e37c7df634c2c8669d9", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1624, "license_type": "permissive", "max_line_length": 300, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_configsync_action.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows one to run different config-sync actions. These actions allow you to manually sync your configuration across multiple BIG-IPs when those devices are in an HA pair.\n class Bigip_configsync_action < Base\n # @return [String] The device group that you want to perform config-sync actions on.\n attribute :device_group\n validates :device_group, presence: true, type: String\n\n # @return [Symbol, nil] Specifies that the system synchronizes configuration data from this device to other members of the device group. In this case, the device will do a \"push\" to all the other devices in the group. This option is mutually exclusive with the C(sync_group_to_device) option.\n attribute :sync_device_to_group\n validates :sync_device_to_group, type: Symbol\n\n # @return [Symbol, nil] Specifies that the system synchronizes configuration data from the device with the most recent configuration. In this case, the device will do a \"pull\" from the most recently updated device. This option is mutually exclusive with the C(sync_device_to_group) options.\n attribute :sync_most_recent_to_device\n validates :sync_most_recent_to_device, type: Symbol\n\n # @return [Symbol, nil] Indicates that the sync operation overwrites the configuration on the target.\n attribute :overwrite_config\n validates :overwrite_config, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6555642485618591, "alphanum_fraction": 0.6649686694145203, "avg_line_length": 64.43589782714844, "blob_id": "128cbaa0f08ae4755b68c8d1f103d8ebf223ea41", "content_id": "12f51123341606feab9fb2f4ffd8fb7ca0d0951a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2552, "license_type": "permissive", "max_line_length": 316, "num_lines": 39, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_eth_trunk.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages Eth-Trunk specific configuration parameters on HUAWEI CloudEngine switches.\n class Ce_eth_trunk < Base\n # @return [Object] Eth-Trunk interface number. The value is an integer. The value range depends on the assign forward eth-trunk mode command. When 256 is specified, the value ranges from 0 to 255. When 512 is specified, the value ranges from 0 to 511. When 1024 is specified, the value ranges from 0 to 1023.\n attribute :trunk_id\n validates :trunk_id, presence: true\n\n # @return [:manual, :\"lacp-dynamic\", :\"lacp-static\", nil] Specifies the working mode of an Eth-Trunk interface.\n attribute :mode\n validates :mode, expression_inclusion: {:in=>[:manual, :\"lacp-dynamic\", :\"lacp-static\"], :message=>\"%{value} needs to be :manual, :\\\"lacp-dynamic\\\", :\\\"lacp-static\\\"\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the minimum number of Eth-Trunk member links in the Up state. The value is an integer ranging from 1 to the maximum number of interfaces that can be added to a Eth-Trunk interface.\n attribute :min_links\n\n # @return [:\"src-dst-ip\", :\"src-dst-mac\", :enhanced, :\"dst-ip\", :\"dst-mac\", :\"src-ip\", :\"src-mac\", nil] Hash algorithm used for load balancing among Eth-Trunk member interfaces.\n attribute :hash_type\n validates :hash_type, expression_inclusion: {:in=>[:\"src-dst-ip\", :\"src-dst-mac\", :enhanced, :\"dst-ip\", :\"dst-mac\", :\"src-ip\", :\"src-mac\"], :message=>\"%{value} needs to be :\\\"src-dst-ip\\\", :\\\"src-dst-mac\\\", :enhanced, :\\\"dst-ip\\\", :\\\"dst-mac\\\", :\\\"src-ip\\\", :\\\"src-mac\\\"\"}, allow_nil: true\n\n # @return [Object, nil] List of interfaces that will be managed in a given Eth-Trunk. The interface name must be full name.\n attribute :members\n\n # @return [:yes, :no, nil] When true it forces Eth-Trunk members to match what is declared in the members param. This can be used to remove members.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Manage the state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6544217467308044, "alphanum_fraction": 0.6544217467308044, "avg_line_length": 27.269229888916016, "blob_id": "1dbb7f766d3620ec59758cfa0b91740b294982c6", "content_id": "7ea54ccc88526153df5c8dd8df81ee52116d1e92", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 735, "license_type": "permissive", "max_line_length": 67, "num_lines": 26, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_instance_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gathering facts from the API of an instance.\n class Cs_instance_facts < Base\n # @return [String] Name or display name of the instance.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Domain the instance is related to.\n attribute :domain\n\n # @return [Object, nil] Account the instance is related to.\n attribute :account\n\n # @return [Object, nil] Project the instance is related to.\n attribute :project\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.665381669998169, "alphanum_fraction": 0.6669236421585083, "avg_line_length": 37.14706039428711, "blob_id": "5cd42124aba75bde7db708a46c930823321497f6", "content_id": "55d363e6f83fb45ccddae9c5508c345496dfb08d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1297, "license_type": "permissive", "max_line_length": 143, "num_lines": 34, "path": "/lib/ansible/ruby/modules/generated/monitoring/grafana_plugin.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Install and remove Grafana plugins.\n class Grafana_plugin < Base\n # @return [String] Name of the plugin.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Version of the plugin to install.,Default to latest.\n attribute :version\n validates :version, type: String\n\n # @return [Object, nil] Directory where Grafana plugin will be installed.\n attribute :grafana_plugins_dir\n\n # @return [Object, nil] Grafana repository. If not set, gafana-cli will use the default value C(https://grafana.net/api/plugins).\n attribute :grafana_repo\n\n # @return [Object, nil] Custom Grafana plugin URL.,Requires grafana 4.6.x or later.\n attribute :grafana_plugin_url\n\n # @return [:absent, :present, nil] Status of the Grafana plugin.,If latest is set, the version parameter will be ignored.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6922680139541626, "alphanum_fraction": 0.6994845271110535, "avg_line_length": 51.43243408203125, "blob_id": "88a8593c6e06d80dc12a6eef93d79d1f263bd3ec", "content_id": "90195cad2e8dfcd0db53b52d7086ede560215ca5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1940, "license_type": "permissive", "max_line_length": 468, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_compute_url_map.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # UrlMaps are used to route requests to a backend service based on rules that you define for the host and path of an incoming URL.\n class Gcp_compute_url_map < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] A reference to BackendService resource if none of the hostRules match.\n attribute :default_service\n validates :default_service, presence: true, type: String\n\n # @return [Object, nil] An optional description of this resource. Provide this property when you create the resource.\n attribute :description\n\n # @return [Object, nil] The list of HostRules to use against the URL.\n attribute :host_rules\n\n # @return [String, nil] Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash.\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] The list of named PathMatchers to use against the URL.\n attribute :path_matchers\n\n # @return [Object, nil] The list of expected URL mappings. Request to update this UrlMap will succeed only if all of the test cases pass.\n attribute :tests\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6607431173324585, "alphanum_fraction": 0.6639741659164429, "avg_line_length": 43.21428680419922, "blob_id": "b0c948c6b0dd1fefc9d52d3c03ab00a678e98009", "content_id": "635587d5e8b4b29a3c9bcd3b8c1cc4019017fb1d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2476, "license_type": "permissive", "max_line_length": 171, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/kinesis_stream.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or Delete a Kinesis Stream.\n # Update the retention period of a Kinesis Stream.\n # Update Tags on a Kinesis Stream.\n # Enable/disable server side encryption on a Kinesis Stream.\n class Kinesis_stream < Base\n # @return [String] The name of the Kinesis Stream you are managing.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Integer, nil] The number of shards you want to have with this stream.,This is required when state == present\n attribute :shards\n validates :shards, type: Integer\n\n # @return [Integer, nil] The default retention period is 24 hours and can not be less than 24 hours.,The retention period can be modified during any point in time.\n attribute :retention_period\n validates :retention_period, type: Integer\n\n # @return [:present, :absent, nil] Create or Delete the Kinesis Stream.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Boolean, nil] Wait for operation to complete before returning.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Integer, nil] How many seconds to wait for an operation to complete before timing out.\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [Hash, nil] A dictionary of resource tags of the form: { tag1: value1, tag2: value2 }.\n attribute :tags\n validates :tags, type: Hash\n\n # @return [:enabled, :disabled, nil] Enable or Disable encryption on the Kinesis Stream.\n attribute :encryption_state\n validates :encryption_state, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [String, nil] The type of encryption.\n attribute :encryption_type\n validates :encryption_type, type: String\n\n # @return [String, nil] The GUID or alias for the KMS key.\n attribute :key_id\n validates :key_id, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7008119821548462, "alphanum_fraction": 0.7008119821548462, "avg_line_length": 52.36666488647461, "blob_id": "569eaf1872545b045ad88d62473ba786e75a15ca", "content_id": "9ea6b23241cc8a0980893f6c1dcb1fcf3c1813f1", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1601, "license_type": "permissive", "max_line_length": 202, "num_lines": 30, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_host_ntp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to manage NTP configuration information about an ESXi host.\n # User can specify an ESXi hostname or Cluster name. In case of cluster name, all ESXi hosts are updated.\n class Vmware_host_ntp < Base\n # @return [String, nil] Name of the cluster.,NTP settings are applied to every ESXi host system in the given cluster.,If C(esxi_hostname) is not given, this parameter is required.\n attribute :cluster_name\n validates :cluster_name, type: String\n\n # @return [String, nil] ESXi hostname.,NTP settings are applied to this ESXi host system.,If C(cluster_name) is not given, this parameter is required.\n attribute :esxi_hostname\n validates :esxi_hostname, type: String\n\n # @return [Array<String>, String] IP or FQDN of NTP server/s.,This accepts a list of NTP servers. For multiple servers, please look at the examples.\n attribute :ntp_servers\n validates :ntp_servers, presence: true, type: TypeGeneric.new(String)\n\n # @return [:present, :absent, nil] present: Add NTP server/s, if it specified server/s are absent else do nothing.,absent: Remove NTP server/s, if specified server/s are present else do nothing.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6714527010917664, "alphanum_fraction": 0.6714527010917664, "avg_line_length": 39.82758712768555, "blob_id": "92af5c69b2f5e081c4196838a6dce246205542f7", "content_id": "4d4be8d18dbdffbaa3121106269b17277c8c5430", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1184, "license_type": "permissive", "max_line_length": 248, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/notification/telegram.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Send notifications via telegram bot, to a verified group or user\n class Telegram < Base\n # @return [String] What message you wish to send.\n attribute :msg\n validates :msg, presence: true, type: String\n\n # @return [:plain, :markdown, :html, nil] Message format. Formatting options `markdown` and `html` described in Telegram API docs (https://core.telegram.org/bots/api#formatting-options). If option `plain` set, message will not be formatted.\n attribute :msg_format\n validates :msg_format, expression_inclusion: {:in=>[:plain, :markdown, :html], :message=>\"%{value} needs to be :plain, :markdown, :html\"}, allow_nil: true\n\n # @return [String] Token identifying your telegram bot.\n attribute :token\n validates :token, presence: true, type: String\n\n # @return [Integer] Telegram group or user chat_id\n attribute :chat_id\n validates :chat_id, presence: true, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.69826340675354, "alphanum_fraction": 0.6989869475364685, "avg_line_length": 52.153846740722656, "blob_id": "a59f35d0254acc39e1004136e4b1947bb278127c", "content_id": "10994a61be2d96fb261dc3e481a3218323769713", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1382, "license_type": "permissive", "max_line_length": 267, "num_lines": 26, "path": "/lib/ansible/ruby/modules/generated/system/dconf.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows modifications and reading of dconf database. The module is implemented as a wrapper around dconf tool. Please see the dconf(1) man page for more details.\n # Since C(dconf) requires a running D-Bus session to change values, the module will try to detect an existing session and reuse it, or run the tool via C(dbus-run-session).\n class Dconf < Base\n # @return [String] A dconf key to modify or read from the dconf database.\n attribute :key\n validates :key, presence: true, type: String\n\n # @return [Array<String>, String, nil] Value to set for the specified dconf key. Value should be specified in GVariant format. Due to complexity of this format, it is best to have a look at existing values in the dconf database. Required for C(state=present).\n attribute :value\n validates :value, type: TypeGeneric.new(String)\n\n # @return [:read, :present, :absent, nil] The action to take upon the key/value.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:read, :present, :absent], :message=>\"%{value} needs to be :read, :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.658088207244873, "alphanum_fraction": 0.6596638560295105, "avg_line_length": 44.33333206176758, "blob_id": "99989cd45db566fa64e33dee26791255af5f5e75", "content_id": "e67e89a071282eedee85f4026d8aa26df29a157c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1904, "license_type": "permissive", "max_line_length": 180, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/cloud/profitbricks/profitbricks_datacenter.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This is a simple module that supports creating or removing vDCs. A vDC is required before you can create servers. This module has a dependency on profitbricks >= 1.0.0\n class Profitbricks_datacenter < Base\n # @return [Object] The name of the virtual datacenter.\n attribute :name\n validates :name, presence: true\n\n # @return [Object, nil] The description of the virtual datacenter.\n attribute :description\n\n # @return [:\"us/las\", :\"de/fra\", :\"de/fkb\", nil] The datacenter location.\n attribute :location\n validates :location, expression_inclusion: {:in=>[:\"us/las\", :\"de/fra\", :\"de/fkb\"], :message=>\"%{value} needs to be :\\\"us/las\\\", :\\\"de/fra\\\", :\\\"de/fkb\\\"\"}, allow_nil: true\n\n # @return [Object, nil] The ProfitBricks username. Overrides the PB_SUBSCRIPTION_ID environment variable.\n attribute :subscription_user\n\n # @return [Object, nil] THe ProfitBricks password. Overrides the PB_PASSWORD environment variable.\n attribute :subscription_password\n\n # @return [:yes, :no, nil] wait for the datacenter to be created before returning\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] how long before wait gives up, in seconds\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [:present, :absent, nil] create or terminate datacenters\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6744982600212097, "alphanum_fraction": 0.6744982600212097, "avg_line_length": 46.511627197265625, "blob_id": "c1eb0ecf7d1830a09d7769b099d08dab1ef29a0c", "content_id": "cd70db6061fe53945e38dd1cc8b059a329664dc2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2043, "license_type": "permissive", "max_line_length": 206, "num_lines": 43, "path": "/lib/ansible/ruby/modules/generated/system/cronvar.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Use this module to manage crontab variables. This module allows you to create, update, or delete cron variable definitions.\n class Cronvar < Base\n # @return [String] Name of the crontab variable.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The value to set this variable to.,Required if C(state=present).\n attribute :value\n validates :value, type: String\n\n # @return [Object, nil] If specified, the variable will be inserted after the variable specified.,Used with C(state=present).\n attribute :insertafter\n\n # @return [Object, nil] Used with C(state=present). If specified, the variable will be inserted just before the variable specified.\n attribute :insertbefore\n\n # @return [:absent, :present, nil] Whether to ensure that the variable is present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] The specific user whose crontab should be modified.\n attribute :user\n validates :user, type: String\n\n # @return [String, nil] If specified, uses this file instead of an individual user's crontab. Without a leading /, this is assumed to be in /etc/cron.d. With a leading /, this is taken as absolute.\n attribute :cron_file\n validates :cron_file, type: String\n\n # @return [:yes, :no, nil] If set, create a backup of the crontab before it is modified. The location of the backup is returned in the C(backup) variable by this module.\n attribute :backup\n validates :backup, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6757709383964539, "alphanum_fraction": 0.6757709383964539, "avg_line_length": 34.46875, "blob_id": "78f1fee42b4d40c0e0b5df57f2d0a15467429c3e", "content_id": "fcfab8a80f975bead033e1fba68c22e675aaa786", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1135, "license_type": "permissive", "max_line_length": 117, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/network/panos/panos_op.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module will allow user to pass and execute any supported OP command on the PANW device.\n class Panos_op < Base\n # @return [String] IP address (or hostname) of PAN-OS device or Panorama management console being configured.\n attribute :ip_address\n validates :ip_address, presence: true, type: String\n\n # @return [String, nil] Username credentials to use for authentication.\n attribute :username\n validates :username, type: String\n\n # @return [String] Password credentials to use for authentication.\n attribute :password\n validates :password, presence: true, type: String\n\n # @return [Object, nil] API key that can be used instead of I(username)/I(password) credentials.\n attribute :api_key\n\n # @return [String] The OP command to be performed.\n attribute :cmd\n validates :cmd, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7199059128761292, "alphanum_fraction": 0.7211887836456299, "avg_line_length": 73.23809814453125, "blob_id": "8113e3de2ecefacb5ef75e9418673abb32dafab2", "content_id": "4b399d78c642819db12803e8837531a9aa912153", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4677, "license_type": "permissive", "max_line_length": 435, "num_lines": 63, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/cloudtrail.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates, deletes, or updates CloudTrail configuration. Ensures logging is also enabled.\n class Cloudtrail < Base\n # @return [:present, :absent, :enabled, :disabled] Add or remove CloudTrail configuration.,The following states have been preserved for backwards compatibility. C(state=enabled) and C(state=disabled).,enabled=present and disabled=absent.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent, :enabled, :disabled], :message=>\"%{value} needs to be :present, :absent, :enabled, :disabled\"}\n\n # @return [String] Name for the CloudTrail.,Names are unique per-region unless the CloudTrail is a multi-region trail, in which case it is unique per-account.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Boolean, nil] Start or stop the CloudTrail logging. If stopped the trail will be paused and will not record events or deliver log files.\n attribute :enable_logging\n validates :enable_logging, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] An existing S3 bucket where CloudTrail will deliver log files.,This bucket should exist and have the proper policy.,See U(http://docs.aws.amazon.com/awscloudtrail/latest/userguide/aggregating_logs_regions_bucket_policy.html),Required when C(state=present)\n attribute :s3_bucket_name\n validates :s3_bucket_name, type: String\n\n # @return [String, nil] S3 Key prefix for delivered log files. A trailing slash is not necessary and will be removed.\n attribute :s3_key_prefix\n validates :s3_key_prefix, type: String\n\n # @return [Boolean, nil] Specify whether the trail belongs only to one region or exists in all regions.\n attribute :is_multi_region_trail\n validates :is_multi_region_trail, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Specifies whether log file integrity validation is enabled.,CloudTrail will create a hash for every log file delivered and produce a signed digest file that can be used to ensure log files have not been tampered.\n attribute :enable_log_file_validation\n validates :enable_log_file_validation, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Record API calls from global services such as IAM and STS.\n attribute :include_global_events\n validates :include_global_events, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] SNS Topic name to send notifications to when a log file is delivered\n attribute :sns_topic_name\n\n # @return [String, nil] Specifies a full ARN for an IAM role that assigns the proper permissions for CloudTrail to create and write to the log group.,See U(https://docs.aws.amazon.com/awscloudtrail/latest/userguide/send-cloudtrail-events-to-cloudwatch-logs.html),Required when C(cloudwatch_logs_log_group_arn)\n attribute :cloudwatch_logs_role_arn\n validates :cloudwatch_logs_role_arn, type: String\n\n # @return [String, nil] A full ARN specifying a valid CloudWatch log group to which CloudTrail logs will be delivered. The log group should already exist.,See U(https://docs.aws.amazon.com/awscloudtrail/latest/userguide/send-cloudtrail-events-to-cloudwatch-logs.html),Required when C(cloudwatch_logs_role_arn)\n attribute :cloudwatch_logs_log_group_arn\n validates :cloudwatch_logs_log_group_arn, type: String\n\n # @return [String, nil] Specifies the KMS key ID to use to encrypt the logs delivered by CloudTrail. This also has the effect of enabling log file encryption.,The value can be an alias name prefixed by \"alias/\", a fully specified ARN to an alias, a fully specified ARN to a key, or a globally unique identifier.,See U(https://docs.aws.amazon.com/awscloudtrail/latest/userguide/encrypting-cloudtrail-log-files-with-aws-kms.html)\n attribute :kms_key_id\n validates :kms_key_id, type: String\n\n # @return [Object, nil] A hash/dictionary of tags to be applied to the CloudTrail resource.,Remove completely or specify an empty dictionary to remove all tags.\n attribute :tags\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6523157358169556, "alphanum_fraction": 0.6562296152114868, "avg_line_length": 40.43243408203125, "blob_id": "bbebb7f661d52824917436e0f03cc4cb72632ce2", "content_id": "cfef6d588420b461c1e9aa07b922f68e8b07ac57", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1533, "license_type": "permissive", "max_line_length": 143, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_key.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # create or delete an ec2 key pair.\n class Ec2_key < Base\n # @return [String] Name of the key pair.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Public key material.\n attribute :key_material\n validates :key_material, type: String\n\n # @return [Boolean, nil] Force overwrite of already existing key pair if key has changed.\n attribute :force\n validates :force, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:present, :absent, nil] create or delete keypair\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Boolean, nil] Wait for the specified action to complete before returning. This option has no effect since version 2.5.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Integer, nil] How long before wait gives up, in seconds. This option has no effect since version 2.5.\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6617100238800049, "alphanum_fraction": 0.6658405661582947, "avg_line_length": 58.04878234863281, "blob_id": "f4f3a3941fde39ec4d6ad7faf88bf3136d2d4a33", "content_id": "b3c48facedab3b181657f50e9e83fbc315f682f9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2421, "license_type": "permissive", "max_line_length": 275, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_domain_to_encap_pool.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Bind Domain to Encap Pools on Cisco ACI fabrics.\n class Aci_domain_to_encap_pool < Base\n # @return [String, nil] Name of the domain being associated with the Encap Pool.\n attribute :domain\n validates :domain, type: String\n\n # @return [:fc, :l2dom, :l3dom, :phys, :vmm, nil] Determines if the Domain is physical (phys) or virtual (vmm).\n attribute :domain_type\n validates :domain_type, expression_inclusion: {:in=>[:fc, :l2dom, :l3dom, :phys, :vmm], :message=>\"%{value} needs to be :fc, :l2dom, :l3dom, :phys, :vmm\"}, allow_nil: true\n\n # @return [String, nil] The name of the pool.\n attribute :pool\n validates :pool, type: String\n\n # @return [:dynamic, :static, nil] The method used for allocating encaps to resources.,Only vlan and vsan support allocation modes.\n attribute :pool_allocation_mode\n validates :pool_allocation_mode, expression_inclusion: {:in=>[:dynamic, :static], :message=>\"%{value} needs to be :dynamic, :static\"}, allow_nil: true\n\n # @return [:vlan, :vsan, :vxlan] The encap type of C(pool).\n attribute :pool_type\n validates :pool_type, presence: true, expression_inclusion: {:in=>[:vlan, :vsan, :vxlan], :message=>\"%{value} needs to be :vlan, :vsan, :vxlan\"}\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n\n # @return [:cloudfoundry, :kubernetes, :microsoft, :openshift, :openstack, :redhat, :vmware, nil] The VM platform for VMM Domains.,Support for Kubernetes was added in ACI v3.0.,Support for CloudFoundry, OpenShift and Red Hat was added in ACI v3.1.\n attribute :vm_provider\n validates :vm_provider, expression_inclusion: {:in=>[:cloudfoundry, :kubernetes, :microsoft, :openshift, :openstack, :redhat, :vmware], :message=>\"%{value} needs to be :cloudfoundry, :kubernetes, :microsoft, :openshift, :openstack, :redhat, :vmware\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7028663754463196, "alphanum_fraction": 0.7081146836280823, "avg_line_length": 55.29545593261719, "blob_id": "995d289139011114b3f808744c4785eebf855ad4", "content_id": "7eeafa34f4d9303301e9a6106459329050bff1bc", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2477, "license_type": "permissive", "max_line_length": 293, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/net_tools/nios/nios_ptr_record.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Adds and/or removes instances of PTR record objects from Infoblox NIOS servers. This module manages NIOS C(record:ptr) objects using the Infoblox WAPI interface over REST.\n class Nios_ptr_record < Base\n # @return [Object, nil] The name of the DNS PTR record in FQDN format to add or remove from the system. The field is required only for an PTR object in Forward Mapping Zone.\n attribute :name\n\n # @return [Object, nil] Sets the DNS view to associate this a record with. The DNS view must already be configured on the system\n attribute :view\n\n # @return [Object] The IPv4 Address of the record. Mutually exclusive with the ipv6addr.\n attribute :ipv4addr\n validates :ipv4addr, presence: true\n\n # @return [Object] The IPv6 Address of the record. Mutually exclusive with the ipv4addr.\n attribute :ipv6addr\n validates :ipv6addr, presence: true\n\n # @return [String] The domain name of the DNS PTR record in FQDN format.\n attribute :ptrdname\n validates :ptrdname, presence: true, type: String\n\n # @return [Object, nil] Time To Live (TTL) value for the record. A 32-bit unsigned integer that represents the duration, in seconds, that the record is valid (cached). Zero indicates that the record should not be cached.\n attribute :ttl\n\n # @return [Object, nil] Allows for the configuration of Extensible Attributes on the instance of the object. This argument accepts a set of key / value pairs for configuration.\n attribute :extattrs\n\n # @return [Object, nil] Configures a text string comment to be associated with the instance of this object. The provided text string will be configured on the object instance. Maximum 256 characters.\n attribute :comment\n\n # @return [:present, :absent, nil] Configures the intended state of the instance of the object on the NIOS server. When this value is set to C(present), the object is configured on the device and when this value is set to C(absent) the value is removed (if necessary) from the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.698637068271637, "alphanum_fraction": 0.7004038095474243, "avg_line_length": 59.030303955078125, "blob_id": "8a356f68d4c09c0d6f95d14f9497955d8dde9b25", "content_id": "52056122f88c221bd996cef96bebdbedae1c176f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3962, "license_type": "permissive", "max_line_length": 481, "num_lines": 66, "path": "/lib/ansible/ruby/modules/generated/utilities/logic/wait_for.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # You can wait for a set amount of time C(timeout), this is the default if nothing is specified or just C(timeout) is specified. This does not produce an error.\n # Waiting for a port to become available is useful for when services are not immediately available after their init scripts return which is true of certain Java application servers. It is also useful when starting guests with the M(virt) module and needing to pause until they are ready.\n # This module can also be used to wait for a regex match a string to be present in a file.\n # In 1.6 and later, this module can also be used to wait for a file to be available or absent on the filesystem.\n # In 1.8 and later, this module can also be used to wait for active connections to be closed before continuing, useful if a node is being rotated out of a load balancer pool.\n # For Windows targets, use the M(win_wait_for) module instead.\n class Wait_for < Base\n # @return [String, nil] A resolvable hostname or IP address to wait for.\n attribute :host\n validates :host, type: String\n\n # @return [Integer, nil] Maximum number of seconds to wait for, when used with another condition it will force an error.,When used without other conditions it is equivalent of just sleeping.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [Integer, nil] Maximum number of seconds to wait for a connection to happen before closing and retrying.\n attribute :connect_timeout\n validates :connect_timeout, type: Integer\n\n # @return [Integer, nil] Number of seconds to wait before starting to poll.\n attribute :delay\n validates :delay, type: Integer\n\n # @return [Integer, nil] Port number to poll.\n attribute :port\n validates :port, type: Integer\n\n # @return [String, nil] The list of TCP connection states which are counted as active connections.\n attribute :active_connection_states\n validates :active_connection_states, type: String\n\n # @return [:absent, :drained, :present, :started, :stopped, nil] Either C(present), C(started), or C(stopped), C(absent), or C(drained).,When checking a port C(started) will ensure the port is open, C(stopped) will check that it is closed, C(drained) will check for active connections.,When checking for a file or a search string C(present) or C(started) will ensure that the file or string is present before continuing, C(absent) will check that file is absent or removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :drained, :present, :started, :stopped], :message=>\"%{value} needs to be :absent, :drained, :present, :started, :stopped\"}, allow_nil: true\n\n # @return [String, nil] Path to a file on the filesystem that must exist before continuing.\n attribute :path\n validates :path, type: String\n\n # @return [String, nil] Can be used to match a string in either a file or a socket connection.,Defaults to a multiline regex.\n attribute :search_regex\n validates :search_regex, type: String\n\n # @return [Array<String>, String, nil] List of hosts or IPs to ignore when looking for active TCP connections for C(drained) state.\n attribute :exclude_hosts\n validates :exclude_hosts, type: TypeGeneric.new(String)\n\n # @return [Integer, nil] Number of seconds to sleep between checks, before 2.3 this was hardcoded to 1 second.\n attribute :sleep\n validates :sleep, type: Integer\n\n # @return [String, nil] This overrides the normal error message from a failure to meet the required conditions.\n attribute :msg\n validates :msg, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6610814929008484, "alphanum_fraction": 0.6618431210517883, "avg_line_length": 38.787879943847656, "blob_id": "d5b694e53586be75b5e663dc447dbed038714f8f", "content_id": "14a3b4552b38e07785f4c5b007866e36ffaa4fba", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1313, "license_type": "permissive", "max_line_length": 145, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_customer_gateway.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage an AWS customer gateway\n class Ec2_customer_gateway < Base\n # @return [Integer, nil] Border Gateway Protocol (BGP) Autonomous System Number (ASN), required when state=present.\n attribute :bgp_asn\n validates :bgp_asn, type: Integer\n\n # @return [String] Internet-routable IP address for customers gateway, must be a static address.\n attribute :ip_address\n validates :ip_address, presence: true, type: String\n\n # @return [String] Name of the customer gateway.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:static, :dynamic, nil] The type of routing.\n attribute :routing\n validates :routing, expression_inclusion: {:in=>[:static, :dynamic], :message=>\"%{value} needs to be :static, :dynamic\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Create or terminate the Customer Gateway.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6874381899833679, "alphanum_fraction": 0.6874381899833679, "avg_line_length": 41.125, "blob_id": "0e6411c26055662ed4bfd19515c9a2fb6ea5df09", "content_id": "bdccd3dcd80cbb1469cd1e6423995cf2574bf534", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1011, "license_type": "permissive", "max_line_length": 152, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/sf_check_connections.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Used to test the management connection to the cluster.\n # The test pings the MVIP and SVIP, and executes a simple API method to verify connectivity.\n class Sf_check_connections < Base\n # @return [:svip, :mvip, nil] Skip checking connection to SVIP or MVIP.\n attribute :skip\n validates :skip, expression_inclusion: {:in=>[:svip, :mvip], :message=>\"%{value} needs to be :svip, :mvip\"}, allow_nil: true\n\n # @return [Object, nil] Optionally, use to test connection of a different MVIP.,This is not needed to test the connection to the target cluster.\n attribute :mvip\n\n # @return [Object, nil] Optionally, use to test connection of a different SVIP.,This is not needed to test the connection to the target cluster.\n attribute :svip\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7132353186607361, "alphanum_fraction": 0.7132353186607361, "avg_line_length": 31, "blob_id": "d5a2aee91f139070b3085eb58b5c20522c6526b6", "content_id": "92f030fd5d1c89cbae634eab65b755b5f76bde1f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 544, "license_type": "permissive", "max_line_length": 104, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/cloud/digital_ocean/digital_ocean_certificate_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to gather facts about DigitalOcean provided certificates.\n class Digital_ocean_certificate_facts < Base\n # @return [String, nil] Certificate ID that can be used to identify and reference a certificate.\n attribute :certificate_id\n validates :certificate_id, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7297297120094299, "alphanum_fraction": 0.7297297120094299, "avg_line_length": 26.133333206176758, "blob_id": "5116fe5dc9d2962968705d8da05445b8777b1e37", "content_id": "8167f6f64143108e96fb26c44ea235b81d67707f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 407, "license_type": "permissive", "max_line_length": 155, "num_lines": 15, "path": "/lib/ansible/ruby/modules/generated/windows/win_disk_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # With the module you can retrieve and output detailed information about the attached disks of the target and its volumes and partitions if existent.\n class Win_disk_facts < Base\n\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6753312945365906, "alphanum_fraction": 0.6753312945365906, "avg_line_length": 46.85365676879883, "blob_id": "f5df01a3a9230a1292af60acaec6470c31153735", "content_id": "a6b9718589128dea5a9de90e86a81da78029dc0b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1962, "license_type": "permissive", "max_line_length": 224, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/ansible_tower/tower_credential_type.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, or destroy Ansible Tower credential type. See U(https://www.ansible.com/tower) for an overview.\n class Tower_credential_type < Base\n # @return [String] The name of the credential type.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The description of the credential type to give more detail about it.\n attribute :description\n validates :description, type: String\n\n # @return [:ssh, :vault, :net, :scm, :cloud, :insights, nil] The type of credential type being added. Note that only cloud and net can be used for creating credential types. Refer to the Ansible for more information.\n attribute :kind\n validates :kind, expression_inclusion: {:in=>[:ssh, :vault, :net, :scm, :cloud, :insights], :message=>\"%{value} needs to be :ssh, :vault, :net, :scm, :cloud, :insights\"}, allow_nil: true\n\n # @return [String, nil] Enter inputs using either JSON or YAML syntax. Refer to the Ansible Tower documentation for example syntax.\n attribute :inputs\n validates :inputs, type: String\n\n # @return [Hash, nil] Enter injectors using either JSON or YAML syntax. Refer to the Ansible Tower documentation for example syntax.\n attribute :injectors\n validates :injectors, type: Hash\n\n # @return [:present, :absent, nil] Desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Symbol, nil] Tower option to avoid certificates check.\n attribute :tower_verify_ssl\n validates :tower_verify_ssl, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6479331254959106, "alphanum_fraction": 0.6486298441886902, "avg_line_length": 50.261905670166016, "blob_id": "8f9e9aea48872132e08d26818974893fd4c894e8", "content_id": "9453194392dcac0d1f73911b24502f0932f121a1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4306, "license_type": "permissive", "max_line_length": 213, "num_lines": 84, "path": "/lib/ansible/ruby/modules/generated/cloud/digital_ocean/digital_ocean.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create/delete a droplet in DigitalOcean and optionally wait for it to be 'running', or deploy an SSH key.\n class Digital_ocean < Base\n # @return [:droplet, :ssh, nil] Which target you want to operate on.\n attribute :command\n validates :command, expression_inclusion: {:in=>[:droplet, :ssh], :message=>\"%{value} needs to be :droplet, :ssh\"}, allow_nil: true\n\n # @return [:present, :active, :absent, :deleted, nil] Indicate desired state of the target.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :active, :absent, :deleted], :message=>\"%{value} needs to be :present, :active, :absent, :deleted\"}, allow_nil: true\n\n # @return [String, nil] DigitalOcean api token.\n attribute :api_token\n validates :api_token, type: String\n\n # @return [Integer, nil] Numeric, the droplet id you want to operate on.\n attribute :id\n validates :id, type: Integer\n\n # @return [String, nil] String, this is the name of the droplet - must be formatted by hostname rules, or the name of a SSH key.\n attribute :name\n validates :name, type: String\n\n # @return [:yes, :no, nil] Bool, require unique hostnames. By default, DigitalOcean allows multiple hosts with the same name. Setting this to \"yes\" allows only one host per name. Useful for idempotence.\n attribute :unique_name\n validates :unique_name, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] This is the slug of the size you would like the droplet created with.\n attribute :size_id\n validates :size_id, type: String\n\n # @return [String, nil] This is the slug of the image you would like the droplet created with.\n attribute :image_id\n validates :image_id, type: String\n\n # @return [String, nil] This is the slug of the region you would like your server to be created in.\n attribute :region_id\n validates :region_id, type: String\n\n # @return [Integer, nil] Optional, array of SSH key (numeric) ID that you would like to be added to the server.\n attribute :ssh_key_ids\n validates :ssh_key_ids, type: Integer\n\n # @return [:yes, :no, nil] Bool, turn on virtio driver in droplet for improved network and storage I/O.\n attribute :virtio\n validates :virtio, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Bool, add an additional, private network interface to droplet for inter-droplet communication.\n attribute :private_networking\n validates :private_networking, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Optional, Boolean, enables backups for your droplet.\n attribute :backups_enabled\n validates :backups_enabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] opaque blob of data which is made available to the droplet\n attribute :user_data\n\n # @return [:yes, :no, nil] Optional, Boolean, enable IPv6 for your droplet.\n attribute :ipv6\n validates :ipv6, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Wait for the droplet to be in state 'running' before returning. If wait is \"no\" an ip_address may not be returned.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] How long before wait gives up, in seconds.\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [String, nil] The public SSH key you want to add to your account.\n attribute :ssh_pub_key\n validates :ssh_pub_key, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6576286554336548, "alphanum_fraction": 0.6576286554336548, "avg_line_length": 42.52000045776367, "blob_id": "3cb02043ef396386a02c61dbc52dfab5730c9150", "content_id": "1d3d7906f544a0c2a0c148c887637e6de1ca27d5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2176, "license_type": "permissive", "max_line_length": 258, "num_lines": 50, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_ip_address.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Acquires and associates a public IP to an account or project.\n # Due to API limitations this is not an idempotent call, so be sure to only conditionally call this when C(state=present).\n # Tagging the IP address can also make the call idempotent.\n class Cs_ip_address < Base\n # @return [String, nil] Public IP address.,Required if C(state=absent) and C(tags) is not set\n attribute :ip_address\n validates :ip_address, type: String\n\n # @return [Object, nil] Domain the IP address is related to.\n attribute :domain\n\n # @return [String, nil] Network the IP address is related to.\n attribute :network\n validates :network, type: String\n\n # @return [Object, nil] VPC the IP address is related to.\n attribute :vpc\n\n # @return [Object, nil] Account the IP address is related to.\n attribute :account\n\n # @return [Object, nil] Name of the project the IP address is related to.\n attribute :project\n\n # @return [Object, nil] Name of the zone in which the IP address is in.,If not set, default zone is used.\n attribute :zone\n\n # @return [:present, :absent, nil] State of the IP address.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash, nil] List of tags. Tags are a list of dictionaries having keys C(key) and C(value).,Tags can be used as an unique identifier for the IP Addresses.,In this case, at least one of them must be unique to ensure idempontency.\n attribute :tags\n validates :tags, type: TypeGeneric.new(Hash)\n\n # @return [:yes, :no, nil] Poll async jobs until job has finished.\n attribute :poll_async\n validates :poll_async, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6686298251152039, "alphanum_fraction": 0.6705529093742371, "avg_line_length": 60.17647171020508, "blob_id": "4a152a9f0d538f1585c569a56392ebb3bb839979", "content_id": "2d9d018975d54e13507f8eca87907cfd6b9688b6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 8320, "license_type": "permissive", "max_line_length": 422, "num_lines": 136, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_instance.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Deploy, start, update, scale, restart, restore, stop and destroy instances.\n class Cs_instance < Base\n # @return [String, nil] Host name of the instance. C(name) can only contain ASCII letters.,Name will be generated (UUID) by CloudStack if not specified and can not be changed afterwards.,Either C(name) or C(display_name) is required.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] Custom display name of the instances.,Display name will be set to C(name) if not specified.,Either C(name) or C(display_name) is required.\n attribute :display_name\n validates :display_name, type: String\n\n # @return [Object, nil] Group in where the new instance should be in.\n attribute :group\n\n # @return [:deployed, :started, :stopped, :restarted, :restored, :destroyed, :expunged, :present, :absent, nil] State of the instance.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:deployed, :started, :stopped, :restarted, :restored, :destroyed, :expunged, :present, :absent], :message=>\"%{value} needs to be :deployed, :started, :stopped, :restarted, :restored, :destroyed, :expunged, :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Name or id of the service offering of the new instance.,If not set, first found service offering is used.\n attribute :service_offering\n validates :service_offering, type: String\n\n # @return [Object, nil] The number of CPUs to allocate to the instance, used with custom service offerings\n attribute :cpu\n\n # @return [Object, nil] The clock speed/shares allocated to the instance, used with custom service offerings\n attribute :cpu_speed\n\n # @return [Object, nil] The memory allocated to the instance, used with custom service offerings\n attribute :memory\n\n # @return [String, nil] Name, display text or id of the template to be used for creating the new instance.,Required when using I(state=present).,Mutually exclusive with C(ISO) option.\n attribute :template\n validates :template, type: String\n\n # @return [String, nil] Name or id of the ISO to be used for creating the new instance.,Required when using I(state=present).,Mutually exclusive with C(template) option.\n attribute :iso\n validates :iso, type: String\n\n # @return [:all, :featured, :self, :selfexecutable, :sharedexecutable, :executable, :community, nil] Name of the filter used to search for the template or iso.,Used for params C(iso) or C(template) on I(state=present).,The filter C(all) was added in 2.6.\n attribute :template_filter\n validates :template_filter, expression_inclusion: {:in=>[:all, :featured, :self, :selfexecutable, :sharedexecutable, :executable, :community], :message=>\"%{value} needs to be :all, :featured, :self, :selfexecutable, :sharedexecutable, :executable, :community\"}, allow_nil: true\n\n # @return [:KVM, :kvm, :VMware, :vmware, :BareMetal, :baremetal, :XenServer, :xenserver, :LXC, :lxc, :HyperV, :hyperv, :UCS, :ucs, :OVM, :ovm, :Simulator, :simulator, nil] Name the hypervisor to be used for creating the new instance.,Relevant when using I(state=present), but only considered if not set on ISO/template.,If not set or found on ISO/template, first found hypervisor will be used.\n attribute :hypervisor\n validates :hypervisor, expression_inclusion: {:in=>[:KVM, :kvm, :VMware, :vmware, :BareMetal, :baremetal, :XenServer, :xenserver, :LXC, :lxc, :HyperV, :hyperv, :UCS, :ucs, :OVM, :ovm, :Simulator, :simulator], :message=>\"%{value} needs to be :KVM, :kvm, :VMware, :vmware, :BareMetal, :baremetal, :XenServer, :xenserver, :LXC, :lxc, :HyperV, :hyperv, :UCS, :ucs, :OVM, :ovm, :Simulator, :simulator\"}, allow_nil: true\n\n # @return [:de, :\"de-ch\", :es, :fi, :fr, :\"fr-be\", :\"fr-ch\", :is, :it, :jp, :\"nl-be\", :no, :pt, :uk, :us, nil] Keyboard device type for the instance.\n attribute :keyboard\n validates :keyboard, expression_inclusion: {:in=>[:de, :\"de-ch\", :es, :fi, :fr, :\"fr-be\", :\"fr-ch\", :is, :it, :jp, :\"nl-be\", :no, :pt, :uk, :us], :message=>\"%{value} needs to be :de, :\\\"de-ch\\\", :es, :fi, :fr, :\\\"fr-be\\\", :\\\"fr-ch\\\", :is, :it, :jp, :\\\"nl-be\\\", :no, :pt, :uk, :us\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] List of networks to use for the new instance.\n attribute :networks\n validates :networks, type: TypeGeneric.new(String)\n\n # @return [Object, nil] IPv4 address for default instance's network during creation.\n attribute :ip_address\n\n # @return [Object, nil] IPv6 address for default instance's network.\n attribute :ip6_address\n\n # @return [Array<Hash>, Hash, nil] List of mappings in the form I({'network': NetworkName, 'ip': 1.2.3.4}),Mutually exclusive with C(networks) option.\n attribute :ip_to_networks\n validates :ip_to_networks, type: TypeGeneric.new(Hash)\n\n # @return [String, nil] Name of the disk offering to be used.\n attribute :disk_offering\n validates :disk_offering, type: String\n\n # @return [Integer, nil] Disk size in GByte required if deploying instance from ISO.\n attribute :disk_size\n validates :disk_size, type: Integer\n\n # @return [Object, nil] Root disk size in GByte required if deploying instance with KVM hypervisor and want resize the root disk size at startup (need CloudStack >= 4.4, cloud-initramfs-growroot installed and enabled in the template)\n attribute :root_disk_size\n\n # @return [Object, nil] List of security groups the instance to be applied to.\n attribute :security_groups\n\n # @return [Object, nil] Host on which an instance should be deployed or started on.,Only considered when I(state=started) or instance is running.,Requires root admin privileges.\n attribute :host\n\n # @return [Object, nil] Domain the instance is related to.\n attribute :domain\n\n # @return [Object, nil] Account the instance is related to.\n attribute :account\n\n # @return [String, nil] Name of the project the instance to be deployed in.\n attribute :project\n validates :project, type: String\n\n # @return [String, nil] Name of the zone in which the instance should be deployed.,If not set, default zone is used.\n attribute :zone\n validates :zone, type: String\n\n # @return [String, nil] Name of the SSH key to be deployed on the new instance.\n attribute :ssh_key\n validates :ssh_key, type: String\n\n # @return [Object, nil] Affinity groups names to be applied to the new instance.\n attribute :affinity_groups\n\n # @return [String, nil] Optional data (ASCII) that can be sent to the instance upon a successful deployment.,The data will be automatically base64 encoded.,Consider switching to HTTP_POST by using I(CLOUDSTACK_METHOD=post) to increase the HTTP_GET size limit of 2KB to 32 KB.\n attribute :user_data\n validates :user_data, type: String\n\n # @return [Symbol, nil] Force stop/start the instance if required to apply changes, otherwise a running instance will not be changed.\n attribute :force\n validates :force, type: Symbol\n\n # @return [Symbol, nil] Enables a volume shrinkage when the new size is smaller than the old one.\n attribute :allow_root_disk_shrink\n validates :allow_root_disk_shrink, type: Symbol\n\n # @return [Array<Hash>, Hash, nil] List of tags. Tags are a list of dictionaries having keys C(key) and C(value).,If you want to delete all tags, set a empty list e.g. I(tags: []).\n attribute :tags\n validates :tags, type: TypeGeneric.new(Hash)\n\n # @return [Boolean, nil] Poll async jobs until job has finished.\n attribute :poll_async\n validates :poll_async, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] Map to specify custom parameters.\n attribute :details\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6915509104728699, "alphanum_fraction": 0.6915509104728699, "avg_line_length": 45.702701568603516, "blob_id": "30f7f92267ef1d566a28d95a9fd6049c0b0e1699", "content_id": "55a7f6b5433d061324a4b7bc3da09f18acf8deac", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1728, "license_type": "permissive", "max_line_length": 356, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_management_route.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configures route settings for the management interface of a BIG-IP.\n class Bigip_management_route < Base\n # @return [String] Specifies the name of the management route.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Description of the management route.\n attribute :description\n validates :description, type: String\n\n # @return [String, nil] Specifies that the system forwards packets to the destination through the gateway with the specified IP address.\n attribute :gateway\n validates :gateway, type: String\n\n # @return [String, nil] The subnet and netmask to be used for the route.,To specify that the route is the default route for the system, provide the value C(default).,Only one C(default) entry is allowed.,This parameter cannot be changed after it is set. Therefore, if you do need to change it, it is required that you delete and create a new route.\n attribute :network\n validates :network, type: String\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [:present, :absent, nil] When C(present), ensures that the resource exists.,When C(absent), ensures the resource is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6709911823272705, "alphanum_fraction": 0.6709911823272705, "avg_line_length": 36.05769348144531, "blob_id": "43d49e2430b8a6f47218f40a7254474304db3ed9", "content_id": "b7edc7fa69266e0efbd92254a5a6c1328e5e6ffa", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1927, "license_type": "permissive", "max_line_length": 154, "num_lines": 52, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_elementsw_backup.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create backup\n class Na_elementsw_backup < Base\n # @return [Object] hostname for the backup source cluster\n attribute :src_hostname\n validates :src_hostname, presence: true\n\n # @return [Object] username for the backup source cluster\n attribute :src_username\n validates :src_username, presence: true\n\n # @return [Object] password for the backup source cluster\n attribute :src_password\n validates :src_password, presence: true\n\n # @return [Object] ID of the backup source volume.\n attribute :src_volume_id\n validates :src_volume_id, presence: true\n\n # @return [Object, nil] hostname for the backup source cluster,will be set equal to src_hostname if not specified\n attribute :dest_hostname\n\n # @return [Object, nil] username for the backup destination cluster,will be set equal to src_username if not specified\n attribute :dest_username\n\n # @return [Object, nil] password for the backup destination cluster,will be set equal to src_password if not specified\n attribute :dest_password\n\n # @return [Object] ID of the backup destination volume\n attribute :dest_volume_id\n validates :dest_volume_id, presence: true\n\n # @return [:native, :uncompressed, nil] Backup format to use\n attribute :format\n validates :format, expression_inclusion: {:in=>[:native, :uncompressed], :message=>\"%{value} needs to be :native, :uncompressed\"}, allow_nil: true\n\n # @return [Object, nil] the backup script to be executed\n attribute :script\n\n # @return [Object, nil] the backup script parameters\n attribute :script_parameters\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.692307710647583, "alphanum_fraction": 0.6962524652481079, "avg_line_length": 30.6875, "blob_id": "9bc15cf7dd802912b18b2a49f2662003d1a74f98", "content_id": "b267a0d9f214e5e5f86eb25b95aea437222a3b2e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 507, "license_type": "permissive", "max_line_length": 172, "num_lines": 16, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_placement_group_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # List details of EC2 Placement Group(s).\n class Ec2_placement_group_facts < Base\n # @return [Object, nil] A list of names to filter on. If a listed group does not exist, there will be no corresponding entry in the result; no error will be raised.\n attribute :names\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6852367520332336, "alphanum_fraction": 0.6876243352890015, "avg_line_length": 60.29268264770508, "blob_id": "aa12f35b65e0bb93d485d539055e1029abc4016d", "content_id": "93c98594a47e2b6d31358f2f6c3e530ad5bae1ed", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2513, "license_type": "permissive", "max_line_length": 286, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/remote_management/ucs/ucs_mac_pool.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configures MAC address pools and MAC address blocks on Cisco UCS Manager.\n # Examples can be used with the UCS Platform Emulator U(https://communities.cisco.com/ucspe).\n class Ucs_mac_pool < Base\n # @return [:present, :absent, nil] If C(present), will verify MAC pool is present and will create if needed.,If C(absent), will verify MAC pool is absent and will delete if needed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The name of the MAC pool.,This name can be between 1 and 32 alphanumeric characters.,You cannot use spaces or any special characters other than - (hyphen), \"_\" (underscore), : (colon), and . (period).,You cannot change this name after the MAC pool is created.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] A description of the MAC pool.,Enter up to 256 characters.,You can use any characters or spaces except the following:,` (accent mark), (backslash), ^ (carat), \" (double quote), = (equal sign), > (greater than), < (less than), or ' (single quote).\n attribute :descrption\n\n # @return [:default, :sequential, nil] The Assignment Order field.,This can be one of the following:,default - Cisco UCS Manager selects a random identity from the pool.,sequential - Cisco UCS Manager selects the lowest available identity from the pool.\n attribute :order\n validates :order, expression_inclusion: {:in=>[:default, :sequential], :message=>\"%{value} needs to be :default, :sequential\"}, allow_nil: true\n\n # @return [String, nil] The first MAC address in the block of addresses.,This is the From field in the UCS Manager MAC Blocks menu.\n attribute :first_addr\n validates :first_addr, type: String\n\n # @return [String, nil] The last MAC address in the block of addresses.,This is the To field in the UCS Manager Add MAC Blocks menu.\n attribute :last_addr\n validates :last_addr, type: String\n\n # @return [String, nil] The distinguished name (dn) of the organization where the resource is assigned.\n attribute :org_dn\n validates :org_dn, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6729362607002258, "alphanum_fraction": 0.6729362607002258, "avg_line_length": 34.44444274902344, "blob_id": "d090d7c5a74ca803b496f9e819d92cff8726c96e", "content_id": "d624bac44abdc3a31eed5910b8efbaa1a4ec90ed", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 957, "license_type": "permissive", "max_line_length": 143, "num_lines": 27, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/redshift_subnet_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, modifies, and deletes Redshift cluster subnet groups.\n class Redshift_subnet_group < Base\n # @return [:present, :absent, nil] Specifies whether the subnet should be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object] Cluster subnet group name.\n attribute :group_name\n validates :group_name, presence: true\n\n # @return [Object, nil] Database subnet group description.\n attribute :group_description\n\n # @return [Object, nil] List of subnet IDs that make up the cluster subnet group.\n attribute :group_subnets\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7147650718688965, "alphanum_fraction": 0.7147650718688965, "avg_line_length": 34.05882263183594, "blob_id": "24298b62f9c95194ea9bc7895704725d476bf255", "content_id": "5828553bdbff5c00ada5dcc7a8fe9158a32522f5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 596, "license_type": "permissive", "max_line_length": 155, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/monitoring/zabbix/zabbix_group_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows you to search for Zabbix hostgroup entries.\n class Zabbix_group_facts < Base\n # @return [Array<String>, String] Name of the hostgroup in Zabbix.,hostgroup is the unique identifier used and cannot be updated using this module.\n attribute :hostgroup_name\n validates :hostgroup_name, presence: true, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6674090623855591, "alphanum_fraction": 0.6674090623855591, "avg_line_length": 36.41666793823242, "blob_id": "60526475b2d351f0b0503f0359cb8243e4d8edcb", "content_id": "5abd486ae1fcb29bf76a9ec1283f9c70570aaf96", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1347, "license_type": "permissive", "max_line_length": 153, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_functionapp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update or delete an Azure Function App\n class Azure_rm_functionapp < Base\n # @return [String] Name of resource group\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] Name of the Azure Function App\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Valid Azure location. Defaults to location of the resource group.\n attribute :location\n\n # @return [Object] Name of the storage account to use.\n attribute :storage_account\n validates :storage_account, presence: true\n\n # @return [Hash, nil] Dictionary containing application settings\n attribute :app_settings\n validates :app_settings, type: Hash\n\n # @return [:absent, :present, nil] Assert the state of the Function App. Use 'present' to create or update a Function App and 'absent' to delete.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6646795868873596, "alphanum_fraction": 0.6741182208061218, "avg_line_length": 50.61538314819336, "blob_id": "67057b5e0c24b909c2dee17498f6e2a04733d321", "content_id": "18f45d2acc175432b451c8efc99f483934ecfc73", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2013, "license_type": "permissive", "max_line_length": 165, "num_lines": 39, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_evpn_bgp_rr.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configure an RR in BGP-EVPN address family view on HUAWEI CloudEngine switches.\n class Ce_evpn_bgp_rr < Base\n # @return [Object] Specifies the number of the AS, in integer format. The value is an integer that ranges from 1 to 4294967295.\n attribute :as_number\n validates :as_number, presence: true\n\n # @return [Object, nil] Specifies the name of a BGP instance. The value of instance-name can be an integer 1 or a string of 1 to 31.\n attribute :bgp_instance\n\n # @return [:enable, :disable, nil] Enable or disable the BGP-EVPN address family.\n attribute :bgp_evpn_enable\n validates :bgp_evpn_enable, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:group_name, :ipv4_address, nil] Specify the peer type.\n attribute :peer_type\n validates :peer_type, expression_inclusion: {:in=>[:group_name, :ipv4_address], :message=>\"%{value} needs to be :group_name, :ipv4_address\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the IPv4 address or the group name of a peer.\n attribute :peer\n\n # @return [:enable, :disable, nil] Configure the local device as the route reflector and the peer or peer group as the client of the route reflector.\n attribute :reflect_client\n validates :reflect_client, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:enable, :disable, nil] Enable or disable the VPN-Target filtering.\n attribute :policy_vpn_target\n validates :policy_vpn_target, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6962655782699585, "alphanum_fraction": 0.6962655782699585, "avg_line_length": 39.16666793823242, "blob_id": "205971bc43c0c1ee5f561c49adec37d4c2c28a10", "content_id": "aeae449a4640a1a86f25de2330ff592c4b94537f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1205, "license_type": "permissive", "max_line_length": 272, "num_lines": 30, "path": "/lib/ansible/ruby/modules/generated/system/alternatives.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages symbolic links using the 'update-alternatives' tool\n # Useful when multiple programs are installed but provide similar functionality (e.g. different editors).\n class Alternatives < Base\n # @return [String] The generic name of the link.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] The path to the real executable that the link should point to.\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [String, nil] The path to the symbolic link that should point to the real executable.,This option is always required on RHEL-based distributions. On Debian-based distributions this option is required when the alternative I(name) is unknown to the system.\n attribute :link\n validates :link, type: String\n\n # @return [Integer, nil] The priority of the alternative\n attribute :priority\n validates :priority, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6681360006332397, "alphanum_fraction": 0.6681360006332397, "avg_line_length": 45.70588302612305, "blob_id": "090f116931abb9dc1cc5ae625e60930cd89ebe02", "content_id": "4358cb85321a3cf4f8a8f90dddad7848908e5cb3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1588, "license_type": "permissive", "max_line_length": 204, "num_lines": 34, "path": "/lib/ansible/ruby/modules/generated/windows/win_robocopy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Synchronizes the contents of two directories on the remote machine.\n # Under the hood this just calls out to RoboCopy, since that should be available on most modern Windows Systems.\n class Win_robocopy < Base\n # @return [String] Source file/directory to sync.\n attribute :src\n validates :src, presence: true, type: String\n\n # @return [String] Destination file/directory to sync (Will receive contents of src).\n attribute :dest\n validates :dest, presence: true, type: String\n\n # @return [:yes, :no, nil] Includes all subdirectories (Toggles the C(/e) flag to RoboCopy).,If C(flags) is set, this will be ignored.\n attribute :recurse\n validates :recurse, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Deletes any files/directories found in the destination that do not exist in the source.,Toggles the C(/purge) flag to RoboCopy. If C(flags) is set, this will be ignored.\n attribute :purge\n validates :purge, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Directly supply Robocopy flags. If set, C(purge) and C(recurse) will be ignored.\n attribute :flags\n validates :flags, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6655148863792419, "alphanum_fraction": 0.6655148863792419, "avg_line_length": 42.84848403930664, "blob_id": "88396b1ea8c2f67aa8e55a33efcf312e4b63286d", "content_id": "0d1d46d6f927efdfe9ab7c94ee1ac5375ce4dd5e", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1447, "license_type": "permissive", "max_line_length": 196, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_cifs_acl.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or destroy or modify cifs-share-access-controls on ONTAP\n class Na_ontap_cifs_acl < Base\n # @return [:no_access, :read, :change, :full_control, nil] -\"The access rights that the user or group has on the defined CIFS share.\"\n attribute :permission\n validates :permission, expression_inclusion: {:in=>[:no_access, :read, :change, :full_control], :message=>\"%{value} needs to be :no_access, :read, :change, :full_control\"}, allow_nil: true\n\n # @return [String] The name of the cifs-share-access-control to manage.\n attribute :share_name\n validates :share_name, presence: true, type: String\n\n # @return [:present, :absent, nil] Whether the specified CIFS share acl should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object] Name of the vserver to use.\n attribute :vserver\n validates :vserver, presence: true\n\n # @return [String] The user or group name for which the permissions are listed.\n attribute :user_or_group\n validates :user_or_group, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6818479895591736, "alphanum_fraction": 0.6861074566841125, "avg_line_length": 66.82221984863281, "blob_id": "e4a4c5f0f64cf5665eea5aaf6c54a6d01d7c36e0", "content_id": "8ce8fcd691856a69bd52143125dc02a20e9d56e5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3052, "license_type": "permissive", "max_line_length": 375, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/remote_management/ucs/ucs_wwn_pool.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configures WWNNs or WWPN pools on Cisco UCS Manager.\n # Examples can be used with the UCS Platform Emulator U(https://communities.cisco.com/ucspe).\n class Ucs_wwn_pool < Base\n # @return [:present, :absent, nil] If C(present), will verify WWNNs/WWPNs are present and will create if needed.,If C(absent), will verify WWNNs/WWPNs are absent and will delete if needed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The name of the World Wide Node Name (WWNN) or World Wide Port Name (WWPN) pool.,This name can be between 1 and 32 alphanumeric characters.,You cannot use spaces or any special characters other than - (hyphen), \"_\" (underscore), : (colon), and . (period).,You cannot change this name after the WWNN or WWPN pool is created.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:node, :port] Specify whether this is a node (WWNN) or port (WWPN) pool.,Optional if state is absent.\n attribute :purpose\n validates :purpose, presence: true, expression_inclusion: {:in=>[:node, :port], :message=>\"%{value} needs to be :node, :port\"}\n\n # @return [Object, nil] A description of the WWNN or WWPN pool.,Enter up to 256 characters.,You can use any characters or spaces except the following:,` (accent mark), (backslash), ^ (carat), \" (double quote), = (equal sign), > (greater than), < (less than), or ' (single quote).\n attribute :description\n\n # @return [:default, :sequential, nil] The Assignment Order field.,This can be one of the following:,default - Cisco UCS Manager selects a random identity from the pool.,sequential - Cisco UCS Manager selects the lowest available identity from the pool.\n attribute :order\n validates :order, expression_inclusion: {:in=>[:default, :sequential], :message=>\"%{value} needs to be :default, :sequential\"}, allow_nil: true\n\n # @return [String, nil] The first initiator in the World Wide Name (WWN) block.,This is the From field in the UCS Manager Add WWN Blocks menu.\n attribute :first_addr\n validates :first_addr, type: String\n\n # @return [String, nil] The last initiator in the Worlde Wide Name (WWN) block.,This is the To field in the UCS Manager Add WWN Blocks menu.,For WWxN pools, the pool size must be a multiple of ports-per-node + 1.,For example, if there are 7 ports per node, the pool size must be a multiple of 8.,If there are 63 ports per node, the pool size must be a multiple of 64.\n attribute :last_addr\n validates :last_addr, type: String\n\n # @return [String, nil] Org dn (distinguished name)\n attribute :org_dn\n validates :org_dn, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7703348994255066, "alphanum_fraction": 0.7727272510528564, "avg_line_length": 54.733333587646484, "blob_id": "d8dbe6f1c9420598e3f71f487b769bcfa4384c53", "content_id": "43e0dc2b53afe34590f14fb1d90117127701fb81", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 836, "license_type": "permissive", "max_line_length": 586, "num_lines": 15, "path": "/lib/ansible/ruby/modules/generated/network/cnos/cnos_factory.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows you to reset a switch's startup configuration. The method provides a way to reset the startup configuration to its factory settings. This is helpful when you want to move the switch to another topology as a new network device. This module uses SSH to manage network device configuration. The result of the operation can be viewed in results directory. For more information about this module and customizing it usage for your use cases, please visit U(http://systemx.lenovofiles.com/help/index.jsp?topic=%2Fcom.lenovo.switchmgt.ansible.doc%2Fcnos_factory.html)\n class Cnos_factory < Base\n\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.751937985420227, "alphanum_fraction": 0.751937985420227, "avg_line_length": 52.117645263671875, "blob_id": "d34950ee169bed1bc9b5b71a6707ab480ffa7a49", "content_id": "a281e72da9463fc82cfead01cd17f43df6cb32d0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 903, "license_type": "permissive", "max_line_length": 319, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/storage/purestorage/purefa_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Collect facts information from a Pure Storage Flasharray running the Purity//FA operating system. By default, the module will collect basic fact information including hosts, host groups, protection groups and volume counts. Additional fact information can be collected based on the configured set of arguements.\n class Purefa_facts < Base\n # @return [String, nil] When supplied, this argument will define the facts to be collected. Possible values for this include all, minimum, config, performance, capacity, network, subnet, interfaces, hgroups, pgroups, hosts, volumes and snapshots.\n attribute :gather_subset\n validates :gather_subset, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6869398355484009, "alphanum_fraction": 0.6927016377449036, "avg_line_length": 84.48258972167969, "blob_id": "e6a12c71d5f252e25a32146344f878ebcd9e36f6", "content_id": "68535be3a0b1e79f8601a9e8e63593eef8a9279b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 17182, "license_type": "permissive", "max_line_length": 638, "num_lines": 201, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_bgp_neighbor_af.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages BGP neighbor Address-family configurations on HUAWEI CloudEngine switches.\n class Ce_bgp_neighbor_af < Base\n # @return [Object] Name of a BGP instance. The name is a case-sensitive string of characters. The BGP instance can be used only after the corresponding VPN instance is created.\n attribute :vrf_name\n validates :vrf_name, presence: true\n\n # @return [:ipv4uni, :ipv4multi, :ipv4vpn, :ipv6uni, :ipv6vpn, :evpn] Address family type of a BGP instance.\n attribute :af_type\n validates :af_type, presence: true, expression_inclusion: {:in=>[:ipv4uni, :ipv4multi, :ipv4vpn, :ipv6uni, :ipv6vpn, :evpn], :message=>\"%{value} needs to be :ipv4uni, :ipv4multi, :ipv4vpn, :ipv6uni, :ipv6vpn, :evpn\"}\n\n # @return [Object] IPv4 or IPv6 peer connection address.\n attribute :remote_address\n validates :remote_address, presence: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, advertised IRB routes are distinguished. If the value is false, advertised IRB routes are not distinguished.\n attribute :advertise_irb\n validates :advertise_irb, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, advertised ARP routes are distinguished. If the value is false, advertised ARP routes are not distinguished.\n attribute :advertise_arp\n validates :advertise_arp, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, the remote next-hop attribute is advertised to peers. If the value is false, the remote next-hop attribute is not advertised to any peers.\n attribute :advertise_remote_nexthop\n validates :advertise_remote_nexthop, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, the community attribute is advertised to peers. If the value is false, the community attribute is not advertised to peers.\n attribute :advertise_community\n validates :advertise_community, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, the extended community attribute is advertised to peers. If the value is false, the extended community attribute is not advertised to peers.\n attribute :advertise_ext_community\n validates :advertise_ext_community, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, the extended community attribute in the peer route information is discarded. If the value is false, the extended community attribute in the peer route information is not discarded.\n attribute :discard_ext_community\n validates :discard_ext_community, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, repetitive local AS numbers are allowed. If the value is false, repetitive local AS numbers are not allowed.\n attribute :allow_as_loop_enable\n validates :allow_as_loop_enable, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [Object, nil] Set the maximum number of repetitive local AS number. The value is an integer ranging from 1 to 10.\n attribute :allow_as_loop_limit\n\n # @return [:no_use, :true, :false, nil] If the value is true, the system stores all route update messages received from all peers (groups) after BGP connection setup. If the value is false, the system stores only BGP update messages that are received from peers and pass the configured import policy.\n attribute :keep_all_routes\n validates :keep_all_routes, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:null, :local, :invariable, nil] null, The next hop is not changed. local, The next hop is changed to the local IP address. invariable, Prevent the device from changing the next hop of each imported IGP route when advertising it to its BGP peers.\n attribute :nexthop_configure\n validates :nexthop_configure, expression_inclusion: {:in=>[:null, :local, :invariable], :message=>\"%{value} needs to be :null, :local, :invariable\"}, allow_nil: true\n\n # @return [Object, nil] Assign a preferred value for the routes learned from a specified peer. The value is an integer ranging from 0 to 65535.\n attribute :preferred_value\n\n # @return [:no_use, :true, :false, nil] If the value is true, sent BGP update messages carry only the public AS number but do not carry private AS numbers. If the value is false, sent BGP update messages can carry private AS numbers.\n attribute :public_as_only\n validates :public_as_only, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, sent BGP update messages carry only the public AS number but do not carry private AS numbers. If the value is false, sent BGP update messages can carry private AS numbers.\n attribute :public_as_only_force\n validates :public_as_only_force, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] Limited use public as number.\n attribute :public_as_only_limited\n validates :public_as_only_limited, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] Private as replaced by public as number.\n attribute :public_as_only_replace\n validates :public_as_only_replace, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] Public as only skip peer as.\n attribute :public_as_only_skip_peer_as\n validates :public_as_only_skip_peer_as, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [Object, nil] Configure the maximum number of routes that can be accepted from a peer. The value is an integer ranging from 1 to 4294967295.\n attribute :route_limit\n\n # @return [Object, nil] Specify the percentage of routes when a router starts to generate an alarm. The value is an integer ranging from 1 to 100.\n attribute :route_limit_percent\n\n # @return [:noparameter, :alertOnly, :idleForever, :idleTimeout, nil] Noparameter, After the number of received routes exceeds the threshold and the timeout timer expires,no action. AlertOnly, An alarm is generated and no additional routes will be accepted if the maximum number of routes allowed have been received. IdleForever, The connection that is interrupted is not automatically re-established if the maximum number of routes allowed have been received. IdleTimeout, After the number of received routes exceeds the threshold and the timeout timer expires, the connection that is interrupted is automatically re-established.\n attribute :route_limit_type\n validates :route_limit_type, expression_inclusion: {:in=>[:noparameter, :alertOnly, :idleForever, :idleTimeout], :message=>\"%{value} needs to be :noparameter, :alertOnly, :idleForever, :idleTimeout\"}, allow_nil: true\n\n # @return [Object, nil] Specify the value of the idle-timeout timer to automatically reestablish the connections after they are cut off when the number of routes exceeds the set threshold. The value is an integer ranging from 1 to 1200.\n attribute :route_limit_idle_timeout\n\n # @return [Object, nil] Specify the minimum interval at which Update packets are sent. The value is an integer, in seconds. The value is an integer ranging from 0 to 600.\n attribute :rt_updt_interval\n\n # @return [:no_use, :true, :false, nil] Redirect ip.\n attribute :redirect_ip\n validates :redirect_ip, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] Redirect ip vaildation.\n attribute :redirect_ip_vaildation\n validates :redirect_ip_vaildation, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, the local device functions as the route reflector and a peer functions as a client of the route reflector. If the value is false, the route reflector and client functions are not configured.\n attribute :reflect_client\n validates :reflect_client, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, the function to replace a specified peer's AS number in the AS-Path attribute with the local AS number is enabled. If the value is false, the function to replace a specified peer's AS number in the AS-Path attribute with the local AS number is disabled.\n attribute :substitute_as_enable\n validates :substitute_as_enable, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [Object, nil] Specify the filtering policy applied to the routes learned from a peer. The value is a string of 1 to 40 characters.\n attribute :import_rt_policy_name\n\n # @return [Object, nil] Specify the filtering policy applied to the routes to be advertised to a peer. The value is a string of 1 to 40 characters.\n attribute :export_rt_policy_name\n\n # @return [Object, nil] Specify the IPv4 filtering policy applied to the routes received from a specified peer. The value is a string of 1 to 169 characters.\n attribute :import_pref_filt_name\n\n # @return [Object, nil] Specify the IPv4 filtering policy applied to the routes to be advertised to a specified peer. The value is a string of 1 to 169 characters.\n attribute :export_pref_filt_name\n\n # @return [Object, nil] Apply an AS_Path-based filtering policy to the routes received from a specified peer. The value is an integer ranging from 1 to 256.\n attribute :import_as_path_filter\n\n # @return [Object, nil] Apply an AS_Path-based filtering policy to the routes to be advertised to a specified peer. The value is an integer ranging from 1 to 256.\n attribute :export_as_path_filter\n\n # @return [Object, nil] A routing strategy based on the AS path list for routing received by a designated peer.\n attribute :import_as_path_name_or_num\n\n # @return [Object, nil] Application of a AS path list based filtering policy to the routing of a specified peer.\n attribute :export_as_path_name_or_num\n\n # @return [Object, nil] Apply an IPv4 ACL-based filtering policy to the routes received from a specified peer. The value is a string of 1 to 32 characters.\n attribute :import_acl_name_or_num\n\n # @return [Object, nil] Apply an IPv4 ACL-based filtering policy to the routes to be advertised to a specified peer. The value is a string of 1 to 32 characters.\n attribute :export_acl_name_or_num\n\n # @return [:no_use, :true, :false, nil] If the value is true, the address prefix-based Outbound Route Filter (ORF) capability is enabled for peers. If the value is false, the address prefix-based Outbound Route Filter (ORF) capability is disabled for peers.\n attribute :ipprefix_orf_enable\n validates :ipprefix_orf_enable, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, Non-standard capability codes are used during capability negotiation. If the value is false, RFC-defined standard ORF capability codes are used during capability negotiation.\n attribute :is_nonstd_ipprefix_mod\n validates :is_nonstd_ipprefix_mod, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [Object, nil] ORF Type. The value is an integer ranging from 0 to 65535.\n attribute :orftype\n\n # @return [:null, :receive, :send, :both, nil] ORF mode. null, Default value. receive, ORF for incoming packets. send, ORF for outgoing packets. both, ORF for incoming and outgoing packets.\n attribute :orf_mode\n validates :orf_mode, expression_inclusion: {:in=>[:null, :receive, :send, :both], :message=>\"%{value} needs to be :null, :receive, :send, :both\"}, allow_nil: true\n\n # @return [Object, nil] Configure the Site-of-Origin (SoO) extended community attribute. The value is a string of 3 to 21 characters.\n attribute :soostring\n\n # @return [:no_use, :true, :false, nil] If the value is true, the function to advertise default routes to peers is enabled. If the value is false, the function to advertise default routes to peers is disabled.\n attribute :default_rt_adv_enable\n validates :default_rt_adv_enable, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [Object, nil] Specify the name of a used policy. The value is a string. The value is a string of 1 to 40 characters.\n attribute :default_rt_adv_policy\n\n # @return [:null, :matchall, :matchany, nil] null, Null. matchall, Advertise the default route if all matching conditions are met. matchany, Advertise the default route if any matching condition is met.\n attribute :default_rt_match_mode\n validates :default_rt_match_mode, expression_inclusion: {:in=>[:null, :matchall, :matchany], :message=>\"%{value} needs to be :null, :matchall, :matchany\"}, allow_nil: true\n\n # @return [:null, :receive, :send, :both, nil] null, Null. receive, Support receiving Add-Path routes. send, Support sending Add-Path routes. both, Support receiving and sending Add-Path routes.\n attribute :add_path_mode\n validates :add_path_mode, expression_inclusion: {:in=>[:null, :receive, :send, :both], :message=>\"%{value} needs to be :null, :receive, :send, :both\"}, allow_nil: true\n\n # @return [Object, nil] The number of addPath advertise route. The value is an integer ranging from 2 to 64.\n attribute :adv_add_path_num\n\n # @return [:no_use, :true, :false, nil] If the value is true, Application results of route announcement. If the value is false, Routing application results are not notified.\n attribute :origin_as_valid\n validates :origin_as_valid, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, vpls enable. If the value is false, vpls disable.\n attribute :vpls_enable\n validates :vpls_enable, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, enable vpls-ad. If the value is false, disable vpls-ad.\n attribute :vpls_ad_disable\n validates :vpls_ad_disable, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] If the value is true, When the vpnv4 multicast neighbor receives and updates the message, the message has no label. If the value is false, When the vpnv4 multicast neighbor receives and updates the message, the message has label.\n attribute :update_pkt_standard_compatible\n validates :update_pkt_standard_compatible, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7119476199150085, "alphanum_fraction": 0.7176759243011475, "avg_line_length": 65.0540542602539, "blob_id": "76e741f9317937e53245b764c2b9b889700faa61", "content_id": "4a7d967d4b7ec82fb477736f67ba0aba9923f5df", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2444, "license_type": "permissive", "max_line_length": 463, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_compute_target_https_proxy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Represents a TargetHttpsProxy resource, which is used by one or more global forwarding rule to route incoming HTTPS requests to a URL map.\n class Gcp_compute_target_https_proxy < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] An optional description of this resource.\n attribute :description\n validates :description, type: String\n\n # @return [String] Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:NONE, :ENABLE, :DISABLE, nil] Specifies the QUIC override policy for this resource. This determines whether the load balancer will attempt to negotiate QUIC with clients or not. Can specify one of NONE, ENABLE, or DISABLE. If NONE is specified, uses the QUIC policy with no user overrides, which is equivalent to DISABLE. Not specifying this field is equivalent to specifying NONE.\n attribute :quic_override\n validates :quic_override, expression_inclusion: {:in=>[:NONE, :ENABLE, :DISABLE], :message=>\"%{value} needs to be :NONE, :ENABLE, :DISABLE\"}, allow_nil: true\n\n # @return [Object] A list of SslCertificate resources that are used to authenticate connections between users and the load balancer. Currently, exactly one SSL certificate must be specified.\n attribute :ssl_certificates\n validates :ssl_certificates, presence: true\n\n # @return [Object] A reference to the UrlMap resource that defines the mapping from URL to the BackendService.\n attribute :url_map\n validates :url_map, presence: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.693927526473999, "alphanum_fraction": 0.693927526473999, "avg_line_length": 46.488372802734375, "blob_id": "fc9ce8805c919dbd2c6dab063911fb648748a7bd", "content_id": "ec992b1059ddf787f5272fbbdfbfad777f4a6f98", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2042, "license_type": "permissive", "max_line_length": 321, "num_lines": 43, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_container_node_pool.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # NodePool contains the name and configuration for a cluster's node pool.\n # Node pools are a set of nodes (i.e. VM's), with a common configuration and specification, under the control of the cluster master. They may have a set of Kubernetes labels applied to them, which may be used to reference them during pod scheduling. They may also be resized up or down, to accommodate the workload.\n class Gcp_container_node_pool < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] The name of the node pool.\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] The node configuration of the pool.\n attribute :config\n\n # @return [Integer] The initial node count for the pool. You must ensure that your Compute Engine resource quota is sufficient for this number of instances. You must also have available firewall and routes quota.\n attribute :initial_node_count\n validates :initial_node_count, presence: true, type: Integer\n\n # @return [Object, nil] Autoscaler configuration for this NodePool. Autoscaler is enabled only if a valid configuration is present.\n attribute :autoscaling\n\n # @return [Object, nil] Management configuration for this NodePool.\n attribute :management\n\n # @return [String] The cluster this node pool belongs to.\n attribute :cluster\n validates :cluster, presence: true, type: String\n\n # @return [String] The zone where the node pool is deployed.\n attribute :zone\n validates :zone, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7244389057159424, "alphanum_fraction": 0.7244389057159424, "avg_line_length": 43.55555725097656, "blob_id": "78bcb005cec922fc229f3e09c204eea89a8c810b", "content_id": "1542a3e1f5f945f23c80f6e1537ac38c76e4a5cb", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 802, "license_type": "permissive", "max_line_length": 204, "num_lines": 18, "path": "/lib/ansible/ruby/modules/generated/windows/win_power_plan.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module will change the power plan of a Windows system to the defined string.\n # Windows defaults to C(balanced) which will cause CPU throttling. In some cases it can be preferable to change the mode to C(high performance) to increase CPU performance.\n class Win_power_plan < Base\n # @return [String] String value that indicates the desired power plan. The power plan must already be present on the system. Commonly there will be options for C(balanced) and C(high performance).\n attribute :name\n validates :name, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6530268788337708, "alphanum_fraction": 0.6552690863609314, "avg_line_length": 53.06060791015625, "blob_id": "350bf4ba08d31b4f0028c12a0031627cbef0709c", "content_id": "fb094af232376e0550b30135e93b9ea9ca4a4a58", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3568, "license_type": "permissive", "max_line_length": 411, "num_lines": 66, "path": "/lib/ansible/ruby/modules/generated/notification/irc.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Send a message to an IRC channel. This is a very simplistic implementation.\n class Irc < Base\n # @return [String, nil] IRC server name/address\n attribute :server\n validates :server, type: String\n\n # @return [Integer, nil] IRC server port number\n attribute :port\n validates :port, type: Integer\n\n # @return [String, nil] Nickname to send the message from. May be shortened, depending on server's NICKLEN setting.\n attribute :nick\n validates :nick, type: String\n\n # @return [String] The message body.\n attribute :msg\n validates :msg, presence: true, type: String\n\n # @return [Object, nil] Set the channel topic\n attribute :topic\n\n # @return [:none, :white, :black, :blue, :green, :red, :brown, :purple, :orange, :yellow, :light_green, :teal, :light_cyan, :light_blue, :pink, :gray, :light_gray, nil] Text color for the message. (\"none\" is a valid option in 1.6 or later, in 1.6 and prior, the default color is black, not \"none\"). Added 11 more colors in version 2.0.\n attribute :color\n validates :color, expression_inclusion: {:in=>[:none, :white, :black, :blue, :green, :red, :brown, :purple, :orange, :yellow, :light_green, :teal, :light_cyan, :light_blue, :pink, :gray, :light_gray], :message=>\"%{value} needs to be :none, :white, :black, :blue, :green, :red, :brown, :purple, :orange, :yellow, :light_green, :teal, :light_cyan, :light_blue, :pink, :gray, :light_gray\"}, allow_nil: true\n\n # @return [NilClass] Channel name. One of nick_to or channel needs to be set. When both are set, the message will be sent to both of them.\n attribute :channel\n validates :channel, presence: true, type: NilClass\n\n # @return [Array<String>, String, nil] A list of nicknames to send the message to. One of nick_to or channel needs to be set. When both are defined, the message will be sent to both of them.\n attribute :nick_to\n validates :nick_to, type: TypeGeneric.new(String)\n\n # @return [Object, nil] Channel key\n attribute :key\n\n # @return [Object, nil] Server password\n attribute :passwd\n\n # @return [Integer, nil] Timeout to use while waiting for successful registration and join messages, this is to prevent an endless loop\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [:yes, :no, nil] Designates whether TLS/SSL should be used when connecting to the IRC server\n attribute :use_ssl\n validates :use_ssl, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Designates whether user should part from channel after sending message or not. Useful for when using a faux bot and not wanting join/parts between messages.\n attribute :part\n validates :part, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:bold, :underline, :reverse, :italic, nil] Text style for the message. Note italic does not work on some clients\n attribute :style\n validates :style, expression_inclusion: {:in=>[:bold, :underline, :reverse, :italic], :message=>\"%{value} needs to be :bold, :underline, :reverse, :italic\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.67405766248703, "alphanum_fraction": 0.67405766248703, "avg_line_length": 25.52941131591797, "blob_id": "0c6de31c2093a2ef3111d467d1a3f235da03e69b", "content_id": "d18cf6c89c1ac9117c78db1ac3693a9d0872d476", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 451, "license_type": "permissive", "max_line_length": 77, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/windows/win_file_version.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Get DLL or EXE file build version.\n class Win_file_version < Base\n # @return [String] File to get version.,Always provide absolute path.\n attribute :path\n validates :path, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.654181182384491, "alphanum_fraction": 0.654181182384491, "avg_line_length": 33.787879943847656, "blob_id": "c61af5702f9ad9f8043b8d38de023c6e58f33707", "content_id": "2c8a9d4f8a13cea289691474100230551f9cc1e8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1148, "license_type": "permissive", "max_line_length": 143, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/cloud/digital_ocean/digital_ocean_floating_ip.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create/delete/assign a floating IP.\n class Digital_ocean_floating_ip < Base\n # @return [:present, :absent, nil] Indicate desired state of the target.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Public IP address of the Floating IP. Used to remove an IP\n attribute :ip\n validates :ip, type: String\n\n # @return [String, nil] The region that the Floating IP is reserved to.\n attribute :region\n validates :region, type: String\n\n # @return [Integer, nil] The Droplet that the Floating IP has been assigned to.\n attribute :droplet_id\n validates :droplet_id, type: Integer\n\n # @return [Object] DigitalOcean OAuth token.\n attribute :oauth_token\n validates :oauth_token, presence: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7058823704719543, "alphanum_fraction": 0.7074551582336426, "avg_line_length": 60.13461685180664, "blob_id": "8495347bbc21cd21d68abf05f8199a1a34d6f1da", "content_id": "8e3e641665933192e558c46466a24016cd90e150", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3179, "license_type": "permissive", "max_line_length": 621, "num_lines": 52, "path": "/lib/ansible/ruby/modules/generated/monitoring/pagerduty_alert.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module will let you trigger, acknowledge or resolve a PagerDuty incident by sending events\n class Pagerduty_alert < Base\n # @return [String, nil] PagerDuty unique subdomain. Obsolete. It is not used with PagerDuty REST v2 API.\n attribute :name\n validates :name, type: String\n\n # @return [String] ID of PagerDuty service when incidents will be triggered, acknowledged or resolved.\n attribute :service_id\n validates :service_id, presence: true, type: String\n\n # @return [Object, nil] The GUID of one of your \"Generic API\" services. Obsolete. Please use I(integration_key).\n attribute :service_key\n\n # @return [String] The GUID of one of your \"Generic API\" services.,This is the \"integration key\" listed on a \"Integrations\" tab of PagerDuty service.\n attribute :integration_key\n validates :integration_key, presence: true, type: String\n\n # @return [:triggered, :acknowledged, :resolved] Type of event to be sent.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:triggered, :acknowledged, :resolved], :message=>\"%{value} needs to be :triggered, :acknowledged, :resolved\"}\n\n # @return [String] The pagerduty API key (readonly access), generated on the pagerduty site.\n attribute :api_key\n validates :api_key, presence: true, type: String\n\n # @return [String, nil] For C(triggered) I(state) - Required. Short description of the problem that led to this trigger. This field (or a truncated version) will be used when generating phone calls, SMS messages and alert emails. It will also appear on the incidents tables in the PagerDuty UI. The maximum length is 1024 characters.,For C(acknowledged) or C(resolved) I(state) - Text that will appear in the incident's log associated with this event.\n attribute :desc\n validates :desc, type: String\n\n # @return [String, nil] Identifies the incident to which this I(state) should be applied.,For C(triggered) I(state) - If there's no open (i.e. unresolved) incident with this key, a new one will be created. If there's already an open incident with a matching key, this event will be appended to that incident's log. The event key provides an easy way to \"de-dup\" problem reports.,For C(acknowledged) or C(resolved) I(state) - This should be the incident_key you received back when the incident was first opened by a trigger event. Acknowledge events referencing resolved or nonexistent incidents will be discarded.\n attribute :incident_key\n validates :incident_key, type: String\n\n # @return [String, nil] The name of the monitoring client that is triggering this event.\n attribute :client\n validates :client, type: String\n\n # @return [String, nil] The URL of the monitoring client that is triggering this event.\n attribute :client_url\n validates :client_url, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.682102620601654, "alphanum_fraction": 0.682102620601654, "avg_line_length": 37.0476188659668, "blob_id": "30db116cf2552248c614b87f0aedc9726e3355d4", "content_id": "06909c3f11ad20bf8ec185e16208bef5aa95fba8", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 799, "license_type": "permissive", "max_line_length": 135, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vca_nat.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Adds or removes nat rules from a gateway in a vca environment\n class Vca_nat < Base\n # @return [Symbol, nil] If set to true, it will delete all rules in the gateway that are not given as parameter to this module.\n attribute :purge_rules\n validates :purge_rules, type: Symbol\n\n # @return [Boolean] A list of rules to be added to the gateway, Please see examples on valid entries\n attribute :nat_rules\n validates :nat_rules, presence: true, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6626367568969727, "alphanum_fraction": 0.6626367568969727, "avg_line_length": 37.599998474121094, "blob_id": "cd56c53cd55f84ca7a02c482a3dbf8071593f0b9", "content_id": "0c210bf5eab5af313e91fc28544bd9dd367a6f0a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1737, "license_type": "permissive", "max_line_length": 157, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/jenkins_job.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage Jenkins jobs by using Jenkins REST API.\n class Jenkins_job < Base\n # @return [String, nil] config in XML format.,Required if job does not yet exist.,Mutually exclusive with C(enabled).,Considered if C(state=present).\n attribute :config\n validates :config, type: String\n\n # @return [Symbol, nil] Whether the job should be enabled or disabled.,Mutually exclusive with C(config).,Considered if C(state=present).\n attribute :enabled\n validates :enabled, type: Symbol\n\n # @return [String] Name of the Jenkins job.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Password to authenticate with the Jenkins server.\n attribute :password\n validates :password, type: String\n\n # @return [:present, :absent, nil] Attribute that specifies if the job has to be created or deleted.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] API token used to authenticate alternatively to password.\n attribute :token\n validates :token, type: String\n\n # @return [String, nil] URL where the Jenkins server is accessible.\n attribute :url\n validates :url, type: String\n\n # @return [String, nil] User to authenticate with the Jenkins server.\n attribute :user\n validates :user, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5690754652023315, "alphanum_fraction": 0.5690754652023315, "avg_line_length": 28.40625, "blob_id": "f10496ecf9ba160047859916a92ebd557248ed10", "content_id": "d57c9d31d131ee79228df4b3531097e0fc7bffdd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1882, "license_type": "permissive", "max_line_length": 73, "num_lines": 64, "path": "/lib/ansible/ruby/rake/execute.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'rake/tasklib'\nrequire 'ansible-ruby'\nrequire 'ansible/ruby/rake/task_util'\nrequire 'ansible/ruby/rake/compile'\nrequire 'ansible/ruby/rake/clean'\n\nmodule Ansible\n module Ruby\n module Rake\n class Execute < ::Rake::TaskLib\n include TaskUtil\n\n # :reek:Attribute - Rake DSL gets ugly if we don't use a block\n attr_writer :playbooks\n # :reek:Attribute - Rake DSL gets ugly if we don't use a block\n attr_accessor :options\n\n def initialize(parameters = :default)\n name, deps = parse_params parameters\n yield self if block_given?\n raise 'You did not supply any playbooks!' unless playbooks.any?\n\n deps ||= []\n compile_task_name = \"#{name}_compile\".to_sym\n deps = [*deps] << compile_task_name\n playbook_yml_files = yaml_filenames playbooks\n task name => deps do\n flat = flat_options\n flat += ' ' unless flat.empty?\n sh \"ansible-playbook #{flat}#{playbook_yml_files.join ' '}\"\n end\n symbol = name.inspect.to_s\n desc \"Compiles YAML files for #{symbol} task\"\n compiled_files = playbooks + nested_files\n Compile.new compile_task_name do |compile_task|\n compile_task.files = compiled_files\n end\n desc \"Cleans YAML files for #{symbol} task\"\n Clean.new \"#{name}_clean\".to_sym do |clean_task|\n clean_task.files = compiled_files\n end\n end\n\n private\n\n def playbooks\n [*@playbooks]\n end\n\n def nested_files\n FileList['roles/*/tasks/**/*.rb',\n 'roles/*/handlers/**/*.rb']\n end\n\n def flat_options\n array = [*options] << ENV['ANSIBLE_OPTS']\n array.compact.join ' '\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7053045034408569, "alphanum_fraction": 0.7053045034408569, "avg_line_length": 39.720001220703125, "blob_id": "a1a282983d9ff1f39efa4902cc31390b1bfa323d", "content_id": "2a644d07a8d9d7c501663c79240a91836a7a12ee", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1018, "license_type": "permissive", "max_line_length": 197, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_datastore_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to gather facts about datastores in VMWare infrastructure.\n # All values and VMware object names are case sensitive.\n class Vmware_datastore_facts < Base\n # @return [String, nil] Name of the datastore to match.,If set, facts of specific datastores are returned.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] Datacenter to search for datastores.,This parameter is required, if C(cluster) is not supplied.\n attribute :datacenter\n validates :datacenter, type: String\n\n # @return [Object, nil] Cluster to search for datastores.,If set, facts of datastores belonging this clusters will be returned.,This parameter is required, if C(datacenter) is not supplied.\n attribute :cluster\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7290294170379639, "alphanum_fraction": 0.7290294170379639, "avg_line_length": 70.15625, "blob_id": "d8b7a787a0c97261eceb3e58ec5c92a10982fbcd", "content_id": "01722a43a6da13d06f457778cea8cfbcc3238ebd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2277, "license_type": "permissive", "max_line_length": 341, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/network/enos/enos_command.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Sends arbitrary commands to an ENOS node and returns the results read from the device. The C(enos_command) module includes an argument that will cause the module to wait for a specific condition before returning or timing out if the condition is not met.\n class Enos_command < Base\n # @return [Object] List of commands to send to the remote device over the configured provider. The resulting output from the command is returned. If the I(wait_for) argument is provided, the module is not returned until the condition is satisfied or the number of retires as expired.\n attribute :commands\n validates :commands, presence: true\n\n # @return [Object, nil] List of conditions to evaluate against the output of the command. The task will wait for each condition to be true before moving forward. If the conditional is not true within the configured number of retries, the task fails. See examples.\n attribute :wait_for\n\n # @return [:any, :all, nil] The I(match) argument is used in conjunction with the I(wait_for) argument to specify the match policy. Valid values are C(all) or C(any). If the value is set to C(all) then all conditionals in the wait_for must be satisfied. If the value is set to C(any) then only one of the values must be satisfied.\n attribute :match\n validates :match, expression_inclusion: {:in=>[:any, :all], :message=>\"%{value} needs to be :any, :all\"}, allow_nil: true\n\n # @return [Integer, nil] Specifies the number of retries a command should by tried before it is considered failed. The command is run on the target device every retry and evaluated against the I(wait_for) conditions.\n attribute :retries\n validates :retries, type: Integer\n\n # @return [Integer, nil] Configures the interval in seconds to wait between retries of the command. If the command does not pass the specified conditions, the interval indicates how long to wait before trying the command again.\n attribute :interval\n validates :interval, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6915462613105774, "alphanum_fraction": 0.6920813322067261, "avg_line_length": 62.35593032836914, "blob_id": "ac71d007d25edb6399afa3e03b35b2d5a83caac9", "content_id": "0cd611cdf3a29efd99eba764adec906ca1e8ca77", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 7476, "license_type": "permissive", "max_line_length": 424, "num_lines": 118, "path": "/lib/ansible/ruby/modules/generated/windows/win_domain_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages Windows Active Directory user accounts.\n class Win_domain_user < Base\n # @return [String] Name of the user to create, remove or modify.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, :query, nil] When C(present), creates or updates the user account. When C(absent), removes the user account if it exists. When C(query), retrieves the user account details without making any changes.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n\n # @return [:yes, :no, nil] C(yes) will enable the user account.,C(no) will disable the account.\n attribute :enabled\n validates :enabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:no, nil] C(no) will unlock the user account if locked. Note that there is not a way to lock an account as an administrator. Accounts are locked due to user actions; as an admin, you may only unlock a locked account. If you wish to administratively disable an account, set I(enabled) to C(no).\n attribute :account_locked\n validates :account_locked, expression_inclusion: {:in=>[:no], :message=>\"%{value} needs to be :no\"}, allow_nil: true\n\n # @return [Object, nil] Description of the user\n attribute :description\n\n # @return [Array<String>, String, nil] Adds or removes the user from this list of groups, depending on the value of I(groups_action). To remove all but the Principal Group, set C(groups=<principal group name>) and I(groups_action=replace). Note that users cannot be removed from their principal group (for example, \"Domain Users\").\n attribute :groups\n validates :groups, type: TypeGeneric.new(String)\n\n # @return [:add, :remove, :replace, nil] If C(add), the user is added to each group in I(groups) where not already a member.,If C(remove), the user is removed from each group in I(groups).,If C(replace), the user is added as a member of each group in I(groups) and removed from any other groups.\n attribute :groups_action\n validates :groups_action, expression_inclusion: {:in=>[:add, :remove, :replace], :message=>\"%{value} needs to be :add, :remove, :replace\"}, allow_nil: true\n\n # @return [String, nil] Optionally set the user's password to this (plain text) value. In order to enable an account - I(enabled) - a password must already be configured on the account, or you must provide a password here.\n attribute :password\n validates :password, type: String\n\n # @return [:always, :on_create, nil] C(always) will update passwords if they differ.,C(on_create) will only set the password for newly created users.,Note that C(always) will always report an Ansible status of 'changed' because we cannot determine whether the new password differs from the old password.\n attribute :update_password\n validates :update_password, expression_inclusion: {:in=>[:always, :on_create], :message=>\"%{value} needs to be :always, :on_create\"}, allow_nil: true\n\n # @return [Symbol, nil] C(yes) will require the user to change their password at next login.,C(no) will clear the expired password flag.,This is mutually exclusive with I(password_never_expires).\n attribute :password_expired\n validates :password_expired, type: Symbol\n\n # @return [Symbol, nil] C(yes) will set the password to never expire.,C(no) will allow the password to expire.,This is mutually exclusive with I(password_expired).\n attribute :password_never_expires\n validates :password_never_expires, type: Symbol\n\n # @return [Symbol, nil] C(yes) will prevent the user from changing their password.,C(no) will allow the user to change their password.\n attribute :user_cannot_change_password\n validates :user_cannot_change_password, type: Symbol\n\n # @return [String, nil] Configures the user's first name (given name).\n attribute :firstname\n validates :firstname, type: String\n\n # @return [String, nil] Configures the user's last name (surname).\n attribute :surname\n validates :surname, type: String\n\n # @return [String, nil] Configures the user's company name.\n attribute :company\n validates :company, type: String\n\n # @return [Object, nil] Configures the User Principal Name (UPN) for the account.,This is not required, but is best practice to configure for modern versions of Active Directory.,The format is C(<username>@<domain>).\n attribute :upn\n\n # @return [Object, nil] Configures the user's email address.,This is a record in AD and does not do anything to configure any email servers or systems.\n attribute :email\n\n # @return [String, nil] Configures the user's street address.\n attribute :street\n validates :street, type: String\n\n # @return [String, nil] Configures the user's city.\n attribute :city\n validates :city, type: String\n\n # @return [String, nil] Configures the user's state or province.\n attribute :state_province\n validates :state_province, type: String\n\n # @return [Integer, nil] Configures the user's postal code / zip code.\n attribute :postal_code\n validates :postal_code, type: Integer\n\n # @return [String, nil] Configures the user's country code.,Note that this is a two-character ISO 3166 code.\n attribute :country\n validates :country, type: String\n\n # @return [Array<String>, String, nil] Container or OU for the new user; if you do not specify this, the user will be placed in the default container for users in the domain.,Setting the path is only available when a new user is created; if you specify a path on an existing user, the user's path will not be updated - you must delete (e.g., state=absent) the user and then re-add the user with the appropriate path.\n attribute :path\n validates :path, type: TypeGeneric.new(String)\n\n # @return [Hash, nil] A dict of custom LDAP attributes to set on the user.,This can be used to set custom attributes that are not exposed as module parameters, e.g. C(telephoneNumber).,See the examples on how to format this parameter.\n attribute :attributes\n validates :attributes, type: Hash\n\n # @return [String, nil] The username to use when interacting with AD.,If this is not set then the user Ansible used to log in with will be used instead when using CredSSP or Kerberos with credential delegation.\n attribute :domain_username\n validates :domain_username, type: String\n\n # @return [String, nil] The password for I(username).\n attribute :domain_password\n validates :domain_password, type: String\n\n # @return [String, nil] Specifies the Active Directory Domain Services instance to connect to.,Can be in the form of an FQDN or NetBIOS name.,If not specified then the value is based on the domain of the computer running PowerShell.\n attribute :domain_server\n validates :domain_server, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7049278616905212, "alphanum_fraction": 0.7085336446762085, "avg_line_length": 56.379310607910156, "blob_id": "635124b0f2350c16303a16bdd6a625000002c814", "content_id": "36865cf4e7479bd315a80020f4afbacd336577f8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1664, "license_type": "permissive", "max_line_length": 309, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/rackspace/rax_mon_notification.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or delete a Rackspace Cloud Monitoring notification that specifies a channel that can be used to communicate alarms, such as email, webhooks, or PagerDuty. Rackspace monitoring module flow | rax_mon_entity -> rax_mon_check -> *rax_mon_notification* -> rax_mon_notification_plan -> rax_mon_alarm\n class Rax_mon_notification < Base\n # @return [:present, :absent, nil] Ensure that the notification with this C(label) exists or does not exist.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object] Defines a friendly name for this notification. String between 1 and 255 characters long.\n attribute :label\n validates :label, presence: true\n\n # @return [:webhook, :email, :pagerduty] A supported notification type.\n attribute :notification_type\n validates :notification_type, presence: true, expression_inclusion: {:in=>[:webhook, :email, :pagerduty], :message=>\"%{value} needs to be :webhook, :email, :pagerduty\"}\n\n # @return [Object] Dictionary of key-value pairs used to initialize the notification. Required keys and meanings vary with notification type. See http://docs.rackspace.com/cm/api/v1.0/cm-devguide/content/ service-notification-types-crud.html for details.\n attribute :details\n validates :details, presence: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6485195755958557, "alphanum_fraction": 0.6494746804237366, "avg_line_length": 46.59090805053711, "blob_id": "8dba94b6b1b4d5a71bb9c54a106644ec8a65ffac", "content_id": "bc1be3b89a5a1030161be65c0b5be2ce796da460", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2094, "license_type": "permissive", "max_line_length": 151, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/source_control/hg.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages Mercurial (hg) repositories. Supports SSH, HTTP/S and local address.\n class Hg < Base\n # @return [String] The repository address.\n attribute :repo\n validates :repo, presence: true, type: String\n\n # @return [String] Absolute path of where the repository should be cloned to. This parameter is required, unless clone and update are set to no\n attribute :dest\n validates :dest, presence: true, type: String\n\n # @return [String, nil] Equivalent C(-r) option in hg command which could be the changeset, revision number, branch name or even tag.\n attribute :revision\n validates :revision, type: String\n\n # @return [:yes, :no, nil] Discards uncommitted changes. Runs C(hg update -C). Prior to 1.9, the default was `yes`.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Deletes untracked files. Runs C(hg purge).\n attribute :purge\n validates :purge, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), do not retrieve new revisions from the origin repository\n attribute :update\n validates :update, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), do not clone the repository if it does not exist locally.\n attribute :clone\n validates :clone, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Path to hg executable to use. If not supplied, the normal mechanism for resolving binary paths will be used.\n attribute :executable\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6716259121894836, "alphanum_fraction": 0.6737513542175293, "avg_line_length": 44.90243911743164, "blob_id": "8e4bc3b324d563c2ea750c7a9122cce38f7e905a", "content_id": "45e745c526faf0705cb8aba77708f2d050097b1b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1882, "license_type": "permissive", "max_line_length": 214, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/crypto/openssl_privatekey.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows one to (re)generate OpenSSL private keys. It uses the pyOpenSSL python library to interact with openssl. One can generate either RSA or DSA private keys. Keys are generated in PEM format.\n class Openssl_privatekey < Base\n # @return [:present, :absent, nil] Whether the private key should exist or not, taking action if the state is different from what is stated.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Integer, nil] Size (in bits) of the TLS/SSL key to generate\n attribute :size\n validates :size, type: Integer\n\n # @return [:RSA, :DSA, nil] The algorithm used to generate the TLS/SSL private key\n attribute :type\n validates :type, expression_inclusion: {:in=>[:RSA, :DSA], :message=>\"%{value} needs to be :RSA, :DSA\"}, allow_nil: true\n\n # @return [Symbol, nil] Should the key be regenerated even if it already exists\n attribute :force\n validates :force, type: Symbol\n\n # @return [String] Name of the file in which the generated TLS/SSL private key will be written. It will have 0600 mode.\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [String, nil] The passphrase for the private key.\n attribute :passphrase\n validates :passphrase, type: String\n\n # @return [String, nil] The cipher to encrypt the private key. (cipher can be found by running `openssl list-cipher-algorithms`)\n attribute :cipher\n validates :cipher, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7069733142852783, "alphanum_fraction": 0.7069733142852783, "avg_line_length": 52.91999816894531, "blob_id": "6ffc84b5723d4db90436c4eef7481046df8eb4c3", "content_id": "f250bb960faddee2998a85ed3c94198f21faf0cc", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1348, "license_type": "permissive", "max_line_length": 242, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/storage/glusterfs/gluster_peer.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or diminish a GlusterFS trusted storage pool. A set of nodes can be added into an existing trusted storage pool or a new storage pool can be formed. Or, nodes can be removed from an existing trusted storage pool.\n class Gluster_peer < Base\n # @return [:present, :absent] Determines whether the nodes should be attached to the pool or removed from the pool. If the state is present, nodes will be attached to the pool. If state is absent, nodes will be detached from the pool.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [Array<String>, String] List of nodes that have to be probed into the pool.\n attribute :nodes\n validates :nodes, presence: true, type: TypeGeneric.new(String)\n\n # @return [Symbol, nil] Applicable only while removing the nodes from the pool. gluster will refuse to detach a node from the pool if any one of the node is down, in such cases force can be used.\n attribute :force\n validates :force, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6748188138008118, "alphanum_fraction": 0.6784420013427734, "avg_line_length": 38.42856979370117, "blob_id": "9f5f970e8b6c559a2003797eecf6cffd702872c7", "content_id": "a181153d225d6ba5a00174935ea9601ab3bccbd2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1104, "license_type": "permissive", "max_line_length": 193, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_server_metadata.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add, Update or Remove metadata in compute instances from OpenStack.\n class Os_server_metadata < Base\n # @return [Object] Name of the instance to update the metadata\n attribute :server\n validates :server, presence: true\n\n # @return [Object] A list of key value pairs that should be provided as a metadata to the instance or a string containing a list of key-value pairs. Eg: meta: \"key1=value1,key2=value2\"\n attribute :meta\n validates :meta, presence: true\n\n # @return [:present, :absent, nil] Should the resource be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Availability zone in which to create the snapshot.\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6860660314559937, "alphanum_fraction": 0.6894236207008362, "avg_line_length": 42.585365295410156, "blob_id": "112e7d380a84ddadf3ff8b70d79e98a866b2c09b", "content_id": "b8bcb956b1e0b742bbd58f4512616aa0fc2afc10", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1787, "license_type": "permissive", "max_line_length": 187, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/notification/office_365_connector_card.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates Connector Card messages through\n # Office 365 Connectors U(https://dev.outlook.com/Connectors)\n class Office_365_connector_card < Base\n # @return [String] The webhook URL is given to you when you create a new Connector.\n attribute :webhook\n validates :webhook, presence: true, type: String\n\n # @return [String, nil] A string used for summarizing card content.,This will be shown as the message subject.,This is required if the text parameter isn't populated.\n attribute :summary\n validates :summary, type: String\n\n # @return [String, nil] Accent color used for branding or indicating status in the card.\n attribute :color\n validates :color, type: String\n\n # @return [String, nil] A title for the Connector message. Shown at the top of the message.\n attribute :title\n validates :title, type: String\n\n # @return [Array<String>, String, nil] The main text of the card.,This will be rendered below the sender information and optional title,,and above any sections or actions present.\n attribute :text\n validates :text, type: TypeGeneric.new(String)\n\n # @return [Object, nil] This array of objects will power the action links,found at the bottom of the card.\n attribute :actions\n\n # @return [Array<Hash>, Hash, nil] Contains a list of sections to display in the card.,For more information see https://dev.outlook.com/Connectors/reference.\n attribute :sections\n validates :sections, type: TypeGeneric.new(Hash)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6619250774383545, "alphanum_fraction": 0.6718823909759521, "avg_line_length": 51.724998474121094, "blob_id": "b935612cfe045747a7d6c83d926e1258a93e842d", "content_id": "f9178d3ff43280378645112b76840135e53551e0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2109, "license_type": "permissive", "max_line_length": 169, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_ntp_auth.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages NTP authentication configuration on HUAWEI CloudEngine switches.\n class Ce_ntp_auth < Base\n # @return [Object] Authentication key identifier (numeric).\n attribute :key_id\n validates :key_id, presence: true\n\n # @return [Object, nil] Plain text with length of 1 to 255, encrypted text with length of 20 to 392.\n attribute :auth_pwd\n\n # @return [:\"hmac-sha256\", :md5, nil] Specify authentication algorithm.\n attribute :auth_mode\n validates :auth_mode, expression_inclusion: {:in=>[:\"hmac-sha256\", :md5], :message=>\"%{value} needs to be :\\\"hmac-sha256\\\", :md5\"}, allow_nil: true\n\n # @return [:text, :encrypt, nil] Whether the given password is in cleartext or has been encrypted. If in cleartext, the device will encrypt it before storing it.\n attribute :auth_type\n validates :auth_type, expression_inclusion: {:in=>[:text, :encrypt], :message=>\"%{value} needs to be :text, :encrypt\"}, allow_nil: true\n\n # @return [:enable, :disable, nil] Whether the given key is required to be supplied by a time source for the device to synchronize to the time source.\n attribute :trusted_key\n validates :trusted_key, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:enable, :disable, nil] Configure ntp authentication enable or unconfigure ntp authentication enable.\n attribute :authentication\n validates :authentication, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Manage the state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.685935378074646, "alphanum_fraction": 0.6877560019493103, "avg_line_length": 63.617645263671875, "blob_id": "474ecc1959a77cdb3b6c8e39e4c720dd6d99cd89", "content_id": "dc7be85fdfcb0eb05869f94a732e91eef3505c70", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2197, "license_type": "permissive", "max_line_length": 288, "num_lines": 34, "path": "/lib/ansible/ruby/modules/generated/files/fetch.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module works like M(copy), but in reverse. It is used for fetching files from remote machines and storing them locally in a file tree, organized by hostname.\n # This module is also supported for Windows targets.\n class Fetch < Base\n # @return [String] The file on the remote system to fetch. This I(must) be a file, not a directory. Recursive fetching may be supported in a later release.\n attribute :src\n validates :src, presence: true, type: String\n\n # @return [String] A directory to save the file into. For example, if the I(dest) directory is C(/backup) a I(src) file named C(/etc/profile) on host C(host.example.com), would be saved into C(/backup/host.example.com/etc/profile)\n attribute :dest\n validates :dest, presence: true, type: String\n\n # @return [:yes, :no, nil] When set to 'yes', the task will fail if the remote file cannot be read for any reason. Prior to Ansible-2.5, setting this would only fail if the source file was missing.,The default was changed to \"yes\" in Ansible-2.5.\n attribute :fail_on_missing\n validates :fail_on_missing, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Verify that the source and destination checksums match after the files are fetched.\n attribute :validate_checksum\n validates :validate_checksum, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Allows you to override the default behavior of appending hostname/path/to/file to the destination. If dest ends with '/', it will use the basename of the source file, similar to the copy module. Obviously this is only handy if the filenames are unique.\n attribute :flat\n validates :flat, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.674477219581604, "alphanum_fraction": 0.6777525544166565, "avg_line_length": 53.3698616027832, "blob_id": "ef04ff4f5ea736016b0883777bcca9548e8d6fd9", "content_id": "e7e6992faee13930b2ee3294f66d53d72e862fc4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3969, "license_type": "permissive", "max_line_length": 350, "num_lines": 73, "path": "/lib/ansible/ruby/modules/generated/monitoring/icinga2_host.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove a host to Icinga2 through the API.\n # See U(https://www.icinga.com/docs/icinga2/latest/doc/12-icinga2-api/)\n class Icinga2_host < Base\n # @return [String] HTTP, HTTPS, or FTP URL in the form (http|https|ftp)://[user[:pass]]@host.domain[:port]/path\n attribute :url\n validates :url, presence: true, type: String\n\n # @return [:yes, :no, nil] If C(no), it will not use a proxy, even if one is defined in an environment variable on the target hosts.\n attribute :use_proxy\n validates :use_proxy, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] The username for use in HTTP basic authentication.,This parameter can be used without C(url_password) for sites that allow empty passwords.\n attribute :url_username\n validates :url_username, type: String\n\n # @return [String, nil] The password for use in HTTP basic authentication.,If the C(url_username) parameter is not specified, the C(url_password) parameter will not be used.\n attribute :url_password\n validates :url_password, type: String\n\n # @return [:yes, :no, nil] httplib2, the library used by the uri module only sends authentication information when a webservice responds to an initial request with a 401 status. Since some basic auth services do not properly send a 401, logins will fail. This option forces the sending of the Basic authentication header upon initial request.\n attribute :force_basic_auth\n validates :force_basic_auth, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] PEM formatted certificate chain file to be used for SSL client authentication. This file can also include the key as well, and if the key is included, C(client_key) is not required.\n attribute :client_cert\n\n # @return [Object, nil] PEM formatted file that contains your private key to be used for SSL client authentication. If C(client_cert) contains both the certificate and key, this option is not required.\n attribute :client_key\n\n # @return [:present, :absent, nil] Apply feature state.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] Name used to create / delete the host. This does not need to be the FQDN, but does needs to be unique.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] The zone from where this host should be polled.\n attribute :zone\n\n # @return [Object, nil] The template used to define the host.,Template cannot be modified after object creation.\n attribute :template\n\n # @return [String, nil] The command used to check if the host is alive.\n attribute :check_command\n validates :check_command, type: String\n\n # @return [String, nil] The name used to display the host.\n attribute :display_name\n validates :display_name, type: String\n\n # @return [String] The IP address of the host.\n attribute :ip\n validates :ip, presence: true, type: String\n\n # @return [Object, nil] List of variables.\n attribute :variables\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7323324084281921, "alphanum_fraction": 0.7336267232894897, "avg_line_length": 84.84444427490234, "blob_id": "708a85b89dd65162c0673ff857c94f9c877ff7e5", "content_id": "ffbc2757cf6421088a74218e3dc858192ac1435a", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3863, "license_type": "permissive", "max_line_length": 736, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_remote_role.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages remote roles on a BIG-IP. Remote roles are used in situations where user authentication is handled off-box. Local access control to the BIG-IP is controlled by the defined remote role. Where-as authentication (and by extension, assignment to the role) is handled off-box.\n class Bigip_remote_role < Base\n # @return [String] Specifies the name of the remote role.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Integer, nil] Specifies the order of the line in the file C(/config/bigip/auth/remoterole).,The LDAP and Active Directory servers read this file line by line.,The order of the information is important; therefore, F5 recommends that you set the first line at 1000. This allows you, in the future, to insert lines before the first line.,When creating a new remote role, this parameter is required.\n attribute :line_order\n validates :line_order, type: Integer\n\n # @return [Array<String>, String, nil] Specifies the user account attributes saved in the group, in the format C(cn=, ou=, dc=).,When creating a new remote role, this parameter is required.\n attribute :attribute_string\n validates :attribute_string, type: TypeGeneric.new(String)\n\n # @return [Symbol, nil] Enables or disables remote access for the specified group of remotely authenticated users.,When creating a new remote role, if this parameter is not specified, the default is C(yes).\n attribute :remote_access\n validates :remote_access, type: Symbol\n\n # @return [String, nil] Specifies the authorization (level of access) for the account.,When creating a new remote role, if this parameter is not provided, the default is C(none).,The C(partition_access) parameter controls which partitions the account can access.,The chosen role may affect the partitions that one is allowed to specify. Specifically, roles such as C(administrator), C(auditor) and C(resource-administrator) required a C(partition_access) of C(all).,A set of pre-existing roles ship with the system. They are C(none), C(guest), C(operator), C(application-editor), C(manager), C(certificate-manager), C(irule-manager), C(user-manager), C(resource-administrator), C(auditor), C(administrator), C(firewall-manager).\n attribute :assigned_role\n validates :assigned_role, type: String\n\n # @return [String, nil] Specifies the accessible partitions for the account.,This parameter supports the reserved names C(all) and C(Common), as well as specific partitions a user may access.,Users who have access to a partition can operate on objects in that partition, as determined by the permissions conferred by the user's C(assigned_role).,When creating a new remote role, if this parameter is not specified, the default is C(all).\n attribute :partition_access\n validates :partition_access, type: String\n\n # @return [String, nil] Specifies terminal-based accessibility for remote accounts not already explicitly assigned a user role.,Common values for this include C(tmsh) and C(none), however custom values may also be specified.,When creating a new remote role, if this parameter is not specified, the default is C(none).\n attribute :terminal_access\n validates :terminal_access, type: String\n\n # @return [:absent, :present, nil] When C(present), guarantees that the remote role exists.,When C(absent), removes the remote role from the system.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6619981527328491, "alphanum_fraction": 0.6676003932952881, "avg_line_length": 35.931034088134766, "blob_id": "a51aa8a0472ce169810b03d5140cfd577b86cabb", "content_id": "808368f8346fe377bd5d0e8b20a48c62f5f72699", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1071, "license_type": "permissive", "max_line_length": 143, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/network/onyx/onyx_ospf.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management and configuration of OSPF protocol on Mellanox ONYX network devices.\n class Onyx_ospf < Base\n # @return [Integer] OSPF instance number 1-65535\n attribute :ospf\n validates :ospf, presence: true, type: Integer\n\n # @return [String, nil] OSPF router ID. Required if I(state=present).\n attribute :router_id\n validates :router_id, type: String\n\n # @return [Array<Hash>, Hash, nil] List of interfaces and areas. Required if I(state=present).\n attribute :interfaces\n validates :interfaces, type: TypeGeneric.new(Hash)\n\n # @return [:present, :absent, nil] OSPF state.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6436597108840942, "alphanum_fraction": 0.6436597108840942, "avg_line_length": 28.66666603088379, "blob_id": "bd77593732b36dff61850a3b438ad7cc3755b3f7", "content_id": "64cb4f91e7bcc6b3daf55928e61f69dbdacfeb9a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 623, "license_type": "permissive", "max_line_length": 128, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/network/panos/panos_loadcfg.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Load configuration on PAN-OS device\n class Panos_loadcfg < Base\n # @return [String, nil] configuration file to load\n attribute :file\n validates :file, type: String\n\n # @return [:yes, :no, nil] commit if changed\n attribute :commit\n validates :commit, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.49810367822647095, "alphanum_fraction": 0.5107458829879761, "avg_line_length": 20.97222137451172, "blob_id": "4781cba0f43241ef05a6570c840aadf098871e3d", "content_id": "a43e5776f6cca1ea96cca87fcb67fb7719448583", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1582, "license_type": "permissive", "max_line_length": 108, "num_lines": 72, "path": "/lib/ansible/ruby/serializer_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'spec_helper'\nrequire 'ansible-ruby'\n\ndescribe Ansible::Ruby::Serializer do\n describe '::serialize' do\n subject { Ansible::Ruby::Serializer.serialize hash }\n\n context 'standard' do\n let(:hash) do\n { ec2: { foo: 123 } }\n end\n\n it do\n text = <<~YAML\n ---\n # This is a generated YAML file by ansible-ruby, DO NOT EDIT\n ec2:\n foo: 123\n YAML\n # Don't expecte a trailing CR\n is_expected.to eq text.rstrip\n end\n end\n\n context 'array of plays' do\n let(:hash) do\n [{ ec2: { foo: 123 } }]\n end\n\n it do\n text = <<~YAML\n ---\n # This is a generated YAML file by ansible-ruby, DO NOT EDIT\n - ec2:\n foo: 123\n YAML\n # Don't expecte a trailing CR\n is_expected.to eq text.rstrip\n end\n end\n\n context 'null' do\n let(:hash) do\n { ec2: { foo: nil } }\n end\n\n it do\n # both null or empty as Ruby outputs this end up as None in Python\n is_expected.to eq \"---\\n# This is a generated YAML file by ansible-ruby, DO NOT EDIT\\nec2:\\n foo: \"\n end\n end\n\n context 'symbol' do\n let(:hash) do\n [{ ec2: { foo: :howdy } }]\n end\n\n it do\n text = <<~YAML\n ---\n # This is a generated YAML file by ansible-ruby, DO NOT EDIT\n - ec2:\n foo: howdy\n YAML\n # Don't expecte a trailing CR\n is_expected.to eq text.rstrip\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6489050984382629, "alphanum_fraction": 0.6489050984382629, "avg_line_length": 44.66666793823242, "blob_id": "9bc711f7912468f14904bc2439a254c7e4c05499", "content_id": "555c43477fc60c36b7efbc4d192fd17f178215e5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2740, "license_type": "permissive", "max_line_length": 180, "num_lines": 60, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_securitygroup_rule.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add and remove security group rules.\n class Cs_securitygroup_rule < Base\n # @return [String] Name of the security group the rule is related to. The security group must be existing.\n attribute :security_group\n validates :security_group, presence: true, type: String\n\n # @return [:present, :absent, nil] State of the security group rule.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:tcp, :udp, :icmp, :ah, :esp, :gre, nil] Protocol of the security group rule.\n attribute :protocol\n validates :protocol, expression_inclusion: {:in=>[:tcp, :udp, :icmp, :ah, :esp, :gre], :message=>\"%{value} needs to be :tcp, :udp, :icmp, :ah, :esp, :gre\"}, allow_nil: true\n\n # @return [:ingress, :egress, nil] Ingress or egress security group rule.\n attribute :type\n validates :type, expression_inclusion: {:in=>[:ingress, :egress], :message=>\"%{value} needs to be :ingress, :egress\"}, allow_nil: true\n\n # @return [String, nil] CIDR (full notation) to be used for security group rule.\n attribute :cidr\n validates :cidr, type: String\n\n # @return [String, nil] Security group this rule is based of.\n attribute :user_security_group\n validates :user_security_group, type: String\n\n # @return [Integer, nil] Start port for this rule. Required if C(protocol=tcp) or C(protocol=udp).\n attribute :start_port\n validates :start_port, type: Integer\n\n # @return [Integer, nil] End port for this rule. Required if C(protocol=tcp) or C(protocol=udp), but C(start_port) will be used if not set.\n attribute :end_port\n validates :end_port, type: Integer\n\n # @return [Integer, nil] Type of the icmp message being sent. Required if C(protocol=icmp).\n attribute :icmp_type\n validates :icmp_type, type: Integer\n\n # @return [Integer, nil] Error code for this icmp message. Required if C(protocol=icmp).\n attribute :icmp_code\n validates :icmp_code, type: Integer\n\n # @return [Object, nil] Name of the project the security group to be created in.\n attribute :project\n\n # @return [Boolean, nil] Poll async jobs until job has finished.\n attribute :poll_async\n validates :poll_async, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6912392973899841, "alphanum_fraction": 0.6915954351425171, "avg_line_length": 51.98113250732422, "blob_id": "9b6db10d564359a3a830eccb8107ad3ff94a8496", "content_id": "a9119fe075c4f13fd43495d84187a68e533837e8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2808, "license_type": "permissive", "max_line_length": 226, "num_lines": 53, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_vpc_nat_gateway.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Ensure the state of AWS VPC NAT Gateways based on their id, allocation and subnet ids.\n class Ec2_vpc_nat_gateway < Base\n # @return [:present, :absent, nil] Ensure NAT Gateway is present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] The id AWS dynamically allocates to the NAT Gateway on creation. This is required when the absent option is present.\n attribute :nat_gateway_id\n validates :nat_gateway_id, type: String\n\n # @return [String, nil] The id of the subnet to create the NAT Gateway in. This is required with the present option.\n attribute :subnet_id\n validates :subnet_id, type: String\n\n # @return [String, nil] The id of the elastic IP allocation. If this is not passed and the eip_address is not passed. An EIP is generated for this NAT Gateway.\n attribute :allocation_id\n validates :allocation_id, type: String\n\n # @return [String, nil] The elastic IP address of the EIP you want attached to this NAT Gateway. If this is not passed and the allocation_id is not passed, an EIP is generated for this NAT Gateway.\n attribute :eip_address\n validates :eip_address, type: String\n\n # @return [Boolean, nil] if a NAT Gateway exists already in the subnet_id, then do not create a new one.\n attribute :if_exist_do_not_create\n validates :if_exist_do_not_create, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] Deallocate the EIP from the VPC.,Option is only valid with the absent state.,You should use this with the wait option. Since you can not release an address while a delete operation is happening.\n attribute :release_eip\n validates :release_eip, type: String\n\n # @return [String, nil] Wait for operation to complete before returning.\n attribute :wait\n validates :wait, type: String\n\n # @return [Integer, nil] How many seconds to wait for an operation to complete before timing out.\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [String, nil] Optional unique token to be used during create to ensure idempotency. When specifying this option, ensure you specify the eip_address parameter as well otherwise any subsequent runs will fail.\n attribute :client_token\n validates :client_token, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7146801948547363, "alphanum_fraction": 0.7179015278816223, "avg_line_length": 85.91999816894531, "blob_id": "58f7c026c3206784da3b3c50bed476064885c029", "content_id": "5044041878c74c43014b45de1ea7c313e7bff9a0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4346, "license_type": "permissive", "max_line_length": 744, "num_lines": 50, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/deploy_helper.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The Deploy Helper manages some of the steps common in deploying software. It creates a folder structure, manages a symlink for the current release and cleans up old releases.\n # Running it with the C(state=query) or C(state=present) will return the C(deploy_helper) fact. C(project_path), whatever you set in the path parameter, C(current_path), the path to the symlink that points to the active release, C(releases_path), the path to the folder to keep releases in, C(shared_path), the path to the folder to keep shared resources in, C(unfinished_filename), the file to check for to recognize unfinished builds, C(previous_release), the release the 'current' symlink is pointing to, C(previous_release_path), the full path to the 'current' symlink target, C(new_release), either the 'release' parameter or a generated timestamp, C(new_release_path), the path to the new release folder (not created by the module).\n class Deploy_helper < Base\n # @return [String] the root path of the project. Alias I(dest). Returned in the C(deploy_helper.project_path) fact.\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [:present, :finalize, :absent, :clean, :query, nil] the state of the project. C(query) will only gather facts, C(present) will create the project I(root) folder, and in it the I(releases) and I(shared) folders, C(finalize) will remove the unfinished_filename file, create a symlink to the newly deployed release and optionally clean old releases, C(clean) will remove failed & old releases, C(absent) will remove the project folder (synonymous to the M(file) module with C(state=absent))\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :finalize, :absent, :clean, :query], :message=>\"%{value} needs to be :present, :finalize, :absent, :clean, :query\"}, allow_nil: true\n\n # @return [String, nil] the release version that is being deployed. Defaults to a timestamp format %Y%m%d%H%M%S (i.e. '20141119223359'). This parameter is optional during C(state=present), but needs to be set explicitly for C(state=finalize). You can use the generated fact C(release={{ deploy_helper.new_release }}).\n attribute :release\n validates :release, type: String\n\n # @return [String, nil] the name of the folder that will hold the releases. This can be relative to C(path) or absolute. Returned in the C(deploy_helper.releases_path) fact.\n attribute :releases_path\n validates :releases_path, type: String\n\n # @return [String, nil] the name of the folder that will hold the shared resources. This can be relative to C(path) or absolute. If this is set to an empty string, no shared folder will be created. Returned in the C(deploy_helper.shared_path) fact.\n attribute :shared_path\n validates :shared_path, type: String\n\n # @return [String, nil] the name of the symlink that is created when the deploy is finalized. Used in C(finalize) and C(clean). Returned in the C(deploy_helper.current_path) fact.\n attribute :current_path\n validates :current_path, type: String\n\n # @return [String, nil] the name of the file that indicates a deploy has not finished. All folders in the releases_path that contain this file will be deleted on C(state=finalize) with clean=True, or C(state=clean). This file is automatically deleted from the I(new_release_path) during C(state=finalize).\n attribute :unfinished_filename\n validates :unfinished_filename, type: String\n\n # @return [:yes, :no, nil] Whether to run the clean procedure in case of C(state=finalize).\n attribute :clean\n validates :clean, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] the number of old releases to keep when cleaning. Used in C(finalize) and C(clean). Any unfinished builds will be deleted first, so only correct releases will count. The current version will not count.\n attribute :keep_releases\n validates :keep_releases, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6753623485565186, "alphanum_fraction": 0.6766045689582825, "avg_line_length": 48.28571319580078, "blob_id": "2beec1578b77a55378de6cba9854e178834c5bda", "content_id": "a7c9cda8a86b65b5dcd7893a24638a0541900f23", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2415, "license_type": "permissive", "max_line_length": 209, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/windows/win_shortcut.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, manage and delete Windows shortcuts\n class Win_shortcut < Base\n # @return [String, nil] Executable or URL the shortcut points to.,The executable needs to be in your PATH, or has to be an absolute path to the executable.\n attribute :src\n validates :src, type: String\n\n # @return [String, nil] Description for the shortcut.,This is usually shown when hoovering the icon.\n attribute :description\n validates :description, type: String\n\n # @return [String] Destination file for the shortcuting file.,File name should have a C(.lnk) or C(.url) extension.\n attribute :dest\n validates :dest, presence: true, type: String\n\n # @return [String, nil] Additional arguments for the executable defined in C(src).\n attribute :args\n validates :args, type: String\n\n # @return [String, nil] Working directory for executable defined in C(src).\n attribute :directory\n validates :directory, type: String\n\n # @return [String, nil] Icon used for the shortcut.,File name should have a C(.ico) extension.,The file name is followed by a comma and the number in the library file (.dll) or use 0 for an image file.\n attribute :icon\n validates :icon, type: String\n\n # @return [String, nil] Key combination for the shortcut.,This is a combination of one or more modifiers and a key.,Possible modifiers are Alt, Ctrl, Shift, Ext.,Possible keys are [A-Z] and [0-9].\n attribute :hotkey\n validates :hotkey, type: String\n\n # @return [:maximized, :minimized, :normal, nil] Influences how the application is displayed when it is launched.\n attribute :windowstyle\n validates :windowstyle, expression_inclusion: {:in=>[:maximized, :minimized, :normal], :message=>\"%{value} needs to be :maximized, :minimized, :normal\"}, allow_nil: true\n\n # @return [:absent, :present, nil] When C(absent), removes the shortcut if it exists.,When C(present), creates or updates the shortcut.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6248552799224854, "alphanum_fraction": 0.6472404599189758, "avg_line_length": 65.43589782714844, "blob_id": "53211a4a46f369aa61ceb400d7a02a72c8dab0bc", "content_id": "e68dbce7b6d7a53eb18337bf94772e58918c6c80", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2591, "license_type": "permissive", "max_line_length": 476, "num_lines": 39, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_interface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages physical attributes of interfaces on HUAWEI CloudEngine switches.\n class Ce_interface < Base\n # @return [Object, nil] Full name of interface, i.e. 40GE1/0/10, Tunnel1.\n attribute :interface\n\n # @return [:ge, :\"10ge\", :\"25ge\", :\"4x10ge\", :\"40ge\", :\"100ge\", :vlanif, :loopback, :meth, :\"eth-trunk\", :nve, :tunnel, :ethernet, :\"fcoe-port\", :\"fabric-port\", :\"stack-port\", :null, nil] Interface type to be configured from the device.\n attribute :interface_type\n validates :interface_type, expression_inclusion: {:in=>[:ge, :\"10ge\", :\"25ge\", :\"4x10ge\", :\"40ge\", :\"100ge\", :vlanif, :loopback, :meth, :\"eth-trunk\", :nve, :tunnel, :ethernet, :\"fcoe-port\", :\"fabric-port\", :\"stack-port\", :null], :message=>\"%{value} needs to be :ge, :\\\"10ge\\\", :\\\"25ge\\\", :\\\"4x10ge\\\", :\\\"40ge\\\", :\\\"100ge\\\", :vlanif, :loopback, :meth, :\\\"eth-trunk\\\", :nve, :tunnel, :ethernet, :\\\"fcoe-port\\\", :\\\"fabric-port\\\", :\\\"stack-port\\\", :null\"}, allow_nil: true\n\n # @return [:up, :down, nil] Specifies the interface management status. The value is an enumerated type. up, An interface is in the administrative Up state. down, An interface is in the administrative Down state.\n attribute :admin_state\n validates :admin_state, expression_inclusion: {:in=>[:up, :down], :message=>\"%{value} needs to be :up, :down\"}, allow_nil: true\n\n # @return [Object, nil] Specifies an interface description. The value is a string of 1 to 242 case-sensitive characters, spaces supported but question marks (?) not supported.\n attribute :description\n\n # @return [:layer2, :layer3, nil] Manage Layer 2 or Layer 3 state of the interface.\n attribute :mode\n validates :mode, expression_inclusion: {:in=>[:layer2, :layer3], :message=>\"%{value} needs to be :layer2, :layer3\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Specifies whether the interface is a Layer 2 sub-interface.\n attribute :l2sub\n validates :l2sub, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, :default, nil] Specify desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :default], :message=>\"%{value} needs to be :present, :absent, :default\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6585606336593628, "alphanum_fraction": 0.6585606336593628, "avg_line_length": 45.81538391113281, "blob_id": "bb3e4d86bee6ea4ee2f9dce8a2a19b130e3ee903", "content_id": "0d41e56e8009b7c6bd74e62b065d6534fed71f92", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3043, "license_type": "permissive", "max_line_length": 266, "num_lines": 65, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_storage_pool.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, put into maintenance, disable, enable and remove storage pools.\n class Cs_storage_pool < Base\n # @return [String] Name of the storage pool.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Name of the zone in which the host should be deployed.,If not set, default zone is used.\n attribute :zone\n validates :zone, type: String\n\n # @return [String, nil] URL of the storage pool.,Required if C(state=present).\n attribute :storage_url\n validates :storage_url, type: String\n\n # @return [String, nil] Name of the pod.\n attribute :pod\n validates :pod, type: String\n\n # @return [String, nil] Name of the cluster.\n attribute :cluster\n validates :cluster, type: String\n\n # @return [:cluster, :zone, nil] The scope of the storage pool.,Defaults to cluster when C(cluster) is provided, otherwise zone.\n attribute :scope\n validates :scope, expression_inclusion: {:in=>[:cluster, :zone], :message=>\"%{value} needs to be :cluster, :zone\"}, allow_nil: true\n\n # @return [Object, nil] Whether the storage pool should be managed by CloudStack.,Only considere on creation.\n attribute :managed\n\n # @return [:KVM, :VMware, :BareMetal, :XenServer, :LXC, :HyperV, :UCS, :OVM, :Simulator, nil] Required when creating a zone scoped pool.\n attribute :hypervisor\n validates :hypervisor, expression_inclusion: {:in=>[:KVM, :VMware, :BareMetal, :XenServer, :LXC, :HyperV, :UCS, :OVM, :Simulator], :message=>\"%{value} needs to be :KVM, :VMware, :BareMetal, :XenServer, :LXC, :HyperV, :UCS, :OVM, :Simulator\"}, allow_nil: true\n\n # @return [Object, nil] Tags associated with this storage pool.\n attribute :storage_tags\n\n # @return [String, nil] Name of the storage provider e.g. SolidFire, SolidFireShared, DefaultPrimary, CloudByte.\n attribute :provider\n validates :provider, type: String\n\n # @return [Object, nil] Bytes CloudStack can provision from this storage pool.\n attribute :capacity_bytes\n\n # @return [Object, nil] Bytes CloudStack can provision from this storage pool.\n attribute :capacity_iops\n\n # @return [:enabled, :disabled, :maintenance, nil] Allocation state of the storage pool.\n attribute :allocation_state\n validates :allocation_state, expression_inclusion: {:in=>[:enabled, :disabled, :maintenance], :message=>\"%{value} needs to be :enabled, :disabled, :maintenance\"}, allow_nil: true\n\n # @return [:present, :absent, nil] State of the storage pool.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7132719159126282, "alphanum_fraction": 0.7165898680686951, "avg_line_length": 73.82758331298828, "blob_id": "61d10f746fcfa0339752e63cef4db486305d96d2", "content_id": "0f1dd7519ed9714d687bd8345e768d9d65638ab8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 10850, "license_type": "permissive", "max_line_length": 685, "num_lines": 145, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/rds_instance.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, modify, and delete RDS instances.\n class Rds_instance < Base\n # @return [:present, :absent, :terminated, :running, :started, :stopped, :rebooted, :restarted, nil] Whether the snapshot should exist or not. I(rebooted) is not idempotent and will leave the DB instance in a running state and start it prior to rebooting if it was stopped. I(present) will leave the DB instance in the current running/stopped state, (running if creating the DB instance).,I(state=running) and I(state=started) are synonyms, as are I(state=rebooted) and I(state=restarted). Note - rebooting the instance is not idempotent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :terminated, :running, :started, :stopped, :rebooted, :restarted], :message=>\"%{value} needs to be :present, :absent, :terminated, :running, :started, :stopped, :rebooted, :restarted\"}, allow_nil: true\n\n # @return [:snapshot, :s3, :instance, nil] Which source to use if restoring from a template (an existing instance, S3 bucket, or snapshot).\n attribute :creation_source\n validates :creation_source, expression_inclusion: {:in=>[:snapshot, :s3, :instance], :message=>\"%{value} needs to be :snapshot, :s3, :instance\"}, allow_nil: true\n\n # @return [Symbol, nil] Set to True to update your cluster password with I(master_user_password). Since comparing passwords to determine if it needs to be updated is not possible this is set to False by default to allow idempotence.\n attribute :force_update_password\n validates :force_update_password, type: Symbol\n\n # @return [Boolean, nil] Set to False to retain any enabled cloudwatch logs that aren't specified in the task and are associated with the instance.\n attribute :purge_cloudwatch_logs_exports\n validates :purge_cloudwatch_logs_exports, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Set to False to retain any tags that aren't specified in task and are associated with the instance.\n attribute :purge_tags\n validates :purge_tags, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Symbol, nil] Set to False to promote a read replica cluster or true to create one. When creating a read replica C(creation_source) should be set to 'instance' or not provided. C(source_db_instance_identifier) must be provided with this option.\n attribute :read_replica\n validates :read_replica, type: Symbol\n\n # @return [Boolean, nil] Whether to wait for the cluster to be available, stopped, or deleted. At a later time a wait_timeout option may be added. Following each API call to create/modify/delete the instance a waiter is used with a 60 second delay 30 times until the instance reaches the expected state (available/stopped/deleted). The total task time may also be influenced by AWSRetry which helps stabilize if the instance is in an invalid state to operate on to begin with (such as if you try to stop it when it is in the process of rebooting). If setting this to False task retries and delays may make your playbook execution better handle timeouts for major modifications.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] The amount of storage (in gibibytes) to allocate for the DB instance.\n attribute :allocated_storage\n validates :allocated_storage, type: String\n\n # @return [Symbol, nil] Whether to allow major version upgrades.\n attribute :allow_major_version_upgrade\n validates :allow_major_version_upgrade, type: Symbol\n\n # @return [Symbol, nil] A value that specifies whether modifying a cluster with I(new_db_instance_identifier) and I(master_user_password) should be applied as soon as possible, regardless of the I(preferred_maintenance_window) setting. If false, changes are applied during the next maintenance window.\n attribute :apply_immediately\n validates :apply_immediately, type: Symbol\n\n # @return [Symbol, nil] Whether minor version upgrades are applied automatically to the DB instance during the maintenance window.\n attribute :auto_minor_version_upgrade\n validates :auto_minor_version_upgrade, type: Symbol\n\n # @return [Object, nil] A list of EC2 Availability Zones that instances in the DB cluster can be created in. May be used when creating a cluster or when restoring from S3 or a snapshot. Mutually exclusive with I(multi_az).\n attribute :availability_zone\n\n # @return [Object, nil] The number of days for which automated backups are retained (must be greater or equal to 1). May be used when creating a new cluster, when restoring from S3, or when modifying a cluster.\n attribute :backup_retention_period\n\n # @return [Object, nil] The identifier of the CA certificate for the DB instance.\n attribute :ca_certificate_identifier\n\n # @return [Object, nil] The character set to associate with the DB cluster.\n attribute :character_set_name\n\n # @return [Symbol, nil] Whether or not to copy all tags from the DB instance to snapshots of the instance. When initially creating a DB instance the RDS API defaults this to false if unspecified.\n attribute :copy_tags_to_snapshot\n validates :copy_tags_to_snapshot, type: Symbol\n\n # @return [Object, nil] The DB cluster (lowercase) identifier to add the aurora DB instance to. The identifier must contain from 1 to 63 letters, numbers, or hyphens and the first character must be a letter and may not end in a hyphen or contain consecutive hyphens.\n attribute :db_cluster_identifier\n\n # @return [String, nil] The compute and memory capacity of the DB instance, for example db.t2.micro.\n attribute :db_instance_class\n validates :db_instance_class, type: String\n\n # @return [String] The DB instance (lowercase) identifier. The identifier must contain from 1 to 63 letters, numbers, or hyphens and the first character must be a letter and may not end in a hyphen or contain consecutive hyphens.\n attribute :db_instance_identifier\n validates :db_instance_identifier, presence: true, type: String\n\n # @return [Object, nil] The name for your database. If a name is not provided Amazon RDS will not create a database.\n attribute :db_name\n\n # @return [Object, nil] The name of the DB parameter group to associate with this DB instance. When creating the DB instance if this argument is omitted the default DBParameterGroup for the specified engine is used.\n attribute :db_parameter_group_name\n\n # @return [Array<String>, String, nil] (EC2-Classic platform) A list of DB security groups to associate with this DB instance.\n attribute :db_security_groups\n validates :db_security_groups, type: TypeGeneric.new(String)\n\n # @return [Object, nil] The identifier for the DB snapshot to restore from if using I(creation_source=snapshot).\n attribute :db_snapshot_identifier\n\n # @return [Object, nil] The DB subnet group name to use for the DB instance.\n attribute :db_subnet_group_name\n\n # @return [Object, nil] The Active Directory Domain to restore the instance in.\n attribute :domain\n\n # @return [Object, nil] The name of the IAM role to be used when making API calls to the Directory Service.\n attribute :domain_iam_role_name\n\n # @return [Array<String>, String, nil] A list of log types that need to be enabled for exporting to CloudWatch Logs.\n attribute :enable_cloudwatch_logs_exports\n validates :enable_cloudwatch_logs_exports, type: TypeGeneric.new(String)\n\n # @return [Symbol, nil] Enable mapping of AWS Identity and Access Management (IAM) accounts to database accounts. If this option is omitted when creating the cluster, Amazon RDS sets this to False.\n attribute :enable_iam_database_authentication\n validates :enable_iam_database_authentication, type: Symbol\n\n # @return [Symbol, nil] Whether to enable Performance Insights for the DB instance.\n attribute :enable_performance_insights\n validates :enable_performance_insights, type: Symbol\n\n # @return [String, nil] The name of the database engine to be used for this DB instance. This is required to create an instance. Valid choices are aurora | aurora-mysql | aurora-postgresql | mariadb | mysql | oracle-ee | oracle-se | oracle-se1 | oracle-se2 | postgres | sqlserver-ee | sqlserver-ex | sqlserver-se | sqlserver-web\n attribute :engine\n validates :engine, type: String\n\n # @return [Object, nil] The version number of the database engine to use. For Aurora MySQL that could be 5.6.10a , 5.7.12. Aurora PostgreSQL example, 9.6.3\n attribute :engine_version\n\n # @return [Object, nil] The DB instance snapshot identifier of the new DB instance snapshot created when I(skip_final_snapshot) is false.\n attribute :final_db_snapshot_identifier\n\n # @return [Symbol, nil] Set to true to conduct the reboot through a MultiAZ failover.\n attribute :force_failover\n validates :force_failover, type: Symbol\n\n # @return [Object, nil] The Provisioned IOPS (I/O operations per second) value.\n attribute :iops\n\n # @return [Object, nil] The ARN of the AWS KMS key identifier for an encrypted DB instance. If you are creating a DB instance with the same AWS account that owns the KMS encryption key used to encrypt the new DB instance, then you can use the KMS key alias instead of the ARN for the KM encryption key.,If I(storage_encrypted) is true and and this option is not provided, the default encryption key is used.\n attribute :kms_key_id\n\n # @return [:\"license-included\", :\"bring-your-own-license\", :\"general-public-license\", nil] The license model for the DB instance.\n attribute :license_model\n validates :license_model, expression_inclusion: {:in=>[:\"license-included\", :\"bring-your-own-license\", :\"general-public-license\"], :message=>\"%{value} needs to be :\\\"license-included\\\", :\\\"bring-your-own-license\\\", :\\\"general-public-license\\\"\"}, allow_nil: true\n\n # @return [Object, nil] An 8-41 character password for the master database user. The password can contain any printable ASCII character except \"/\",\n attribute :master_user_password\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6853552460670471, "alphanum_fraction": 0.6853552460670471, "avg_line_length": 50.724998474121094, "blob_id": "35904fa8cdae03e924f0739278ac31eb530165fe", "content_id": "bcc6405c69d5409aaeb07aad87a772c69a4f67d2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2069, "license_type": "permissive", "max_line_length": 304, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/network/interface/net_linkagg.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of link aggregation groups on network devices.\n class Net_linkagg < Base\n # @return [String] Name of the link aggregation group.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Boolean, nil] Mode of the link aggregation group. A value of C(on) will enable LACP. C(active) configures the link to actively information about the state of the link, or it can be configured in C(passive) mode ie. send link state information only when received them from another link.\n attribute :mode\n validates :mode, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Array<String>, String] List of members interfaces of the link aggregation group. The value can be single interface or list of interfaces.\n attribute :members\n validates :members, presence: true, type: TypeGeneric.new(String)\n\n # @return [Object, nil] Minimum members that should be up before bringing up the link aggregation group.\n attribute :min_links\n\n # @return [Array<Hash>, Hash, nil] List of link aggregation definitions.\n attribute :aggregate\n validates :aggregate, type: TypeGeneric.new(Hash)\n\n # @return [Boolean, nil] Purge link aggregation groups not defined in the I(aggregate) parameter.\n attribute :purge\n validates :purge, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:present, :absent, :up, :down, nil] State of the link aggregation group.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :up, :down], :message=>\"%{value} needs to be :present, :absent, :up, :down\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6827731132507324, "alphanum_fraction": 0.6827731132507324, "avg_line_length": 41.5, "blob_id": "4e42bd8ab7ecddeae48140c81b401fb4030a68f7", "content_id": "6b12c5f3f7a4e151aeb9e87b10bce45d2207ecc6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2380, "license_type": "permissive", "max_line_length": 168, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_virtualmachine_extension.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and delete Azure Virtual Machine Extension\n class Azure_rm_virtualmachine_extension < Base\n # @return [String] Name of a resource group where the vm extension exists or will be created.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] Name of the vm extension\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, nil] Assert the state of the vm extension. Use 'present' to create or update a vm extension and 'absent' to delete a vm extension.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] Valid azure location. Defaults to location of the resource group.\n attribute :location\n validates :location, type: String\n\n # @return [String, nil] The name of the virtual machine where the extension should be create or updated.\n attribute :virtual_machine_name\n validates :virtual_machine_name, type: String\n\n # @return [String, nil] The name of the extension handler publisher.\n attribute :publisher\n validates :publisher, type: String\n\n # @return [String, nil] The type of the extension handler.\n attribute :virtual_machine_extension_type\n validates :virtual_machine_extension_type, type: String\n\n # @return [Float, nil] The type version of the extension handler.\n attribute :type_handler_version\n validates :type_handler_version, type: Float\n\n # @return [Hash, nil] Json formatted public settings for the extension.\n attribute :settings\n validates :settings, type: Hash\n\n # @return [Object, nil] Json formatted protected settings for the extension.\n attribute :protected_settings\n\n # @return [Symbol, nil] Whether the extension handler should be automatically upgraded across minor versions.\n attribute :auto_upgrade_minor_version\n validates :auto_upgrade_minor_version, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7058449983596802, "alphanum_fraction": 0.7077509760856628, "avg_line_length": 61.1315803527832, "blob_id": "c5e7feaa29a08f04f33b49b5551f2fd373d8c4ba", "content_id": "984417ce1ad0091d427264bc6fe13cae7c1b5bc3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4722, "license_type": "permissive", "max_line_length": 260, "num_lines": 76, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_eni.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create and optionally attach an Elastic Network Interface (ENI) to an instance. If an ENI ID or private_ip is provided, the existing ENI (if any) will be modified. The 'attached' parameter controls the attachment status of the network interface.\n class Ec2_eni < Base\n # @return [String, nil] The ID of the ENI (to modify); if null and state is present, a new eni will be created.\n attribute :eni_id\n validates :eni_id, type: String\n\n # @return [String, nil] Instance ID that you wish to attach ENI to. Since version 2.2, use the 'attached' parameter to attach or detach an ENI. Prior to 2.2, to detach an ENI from an instance, use 'None'.\n attribute :instance_id\n validates :instance_id, type: String\n\n # @return [String, nil] Private IP address.\n attribute :private_ip_address\n validates :private_ip_address, type: String\n\n # @return [String, nil] ID of subnet in which to create the ENI.\n attribute :subnet_id\n validates :subnet_id, type: String\n\n # @return [String, nil] Optional description of the ENI.\n attribute :description\n validates :description, type: String\n\n # @return [Object, nil] List of security groups associated with the interface. Only used when state=present. Since version 2.2, you can specify security groups by ID or by name or a combination of both. Prior to 2.2, you can specify only by ID.\n attribute :security_groups\n\n # @return [:present, :absent, nil] Create or delete ENI\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Integer, nil] The index of the device for the network interface attachment on the instance.\n attribute :device_index\n validates :device_index, type: Integer\n\n # @return [Symbol, nil] Specifies if network interface should be attached or detached from instance. If omitted, attachment status won't change\n attribute :attached\n validates :attached, type: Symbol\n\n # @return [:yes, :no, nil] Force detachment of the interface. This applies either when explicitly detaching the interface by setting instance_id to None or when deleting an interface with state=absent.\n attribute :force_detach\n validates :force_detach, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Symbol, nil] Delete the interface when the instance it is attached to is terminated. You can only specify this flag when the interface is being modified, not on creation.\n attribute :delete_on_termination\n validates :delete_on_termination, type: Symbol\n\n # @return [Symbol, nil] By default, interfaces perform source/destination checks. NAT instances however need this check to be disabled. You can only specify this flag when the interface is being modified, not on creation.\n attribute :source_dest_check\n validates :source_dest_check, type: Symbol\n\n # @return [Array<String>, String, nil] A list of IP addresses to assign as secondary IP addresses to the network interface. This option is mutually exclusive of secondary_private_ip_address_count\n attribute :secondary_private_ip_addresses\n validates :secondary_private_ip_addresses, type: TypeGeneric.new(String)\n\n # @return [Symbol, nil] To be used with I(secondary_private_ip_addresses) to determine whether or not to remove any secondary IP addresses other than those specified. Set secondary_private_ip_addresses to an empty list to purge all secondary addresses.\n attribute :purge_secondary_private_ip_addresses\n validates :purge_secondary_private_ip_addresses, type: Symbol\n\n # @return [Integer, nil] The number of secondary IP addresses to assign to the network interface. This option is mutually exclusive of secondary_private_ip_addresses\n attribute :secondary_private_ip_address_count\n validates :secondary_private_ip_address_count, type: Integer\n\n # @return [:yes, :no, nil] Indicates whether to allow an IP address that is already assigned to another network interface or instance to be reassigned to the specified network interface.\n attribute :allow_reassignment\n validates :allow_reassignment, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6950732469558716, "alphanum_fraction": 0.6950732469558716, "avg_line_length": 34.761905670166016, "blob_id": "ae9e8a02262eacd7ec960de4d124d4b635bf1af1", "content_id": "fa57a8ae322ea6d81bdfae0963ea2719cf841baf", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 751, "license_type": "permissive", "max_line_length": 184, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_hosts_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Retrieve facts about one or more oVirt/RHV hosts.\n class Ovirt_host_facts < Base\n # @return [String, nil] Search term which is accepted by oVirt/RHV search backend.,For example to search host X from datacenter Y use following pattern: name=X and datacenter=Y\n attribute :pattern\n validates :pattern, type: String\n\n # @return [Symbol, nil] If I(true) all the attributes of the hosts should be included in the response.\n attribute :all_content\n validates :all_content, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6700565218925476, "alphanum_fraction": 0.6711864471435547, "avg_line_length": 35.875, "blob_id": "b46ccc691d5786d9d0df43b5b22fd660d346becb", "content_id": "ca400040e53e061e1baa99adc16825b772a15298", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 885, "license_type": "permissive", "max_line_length": 169, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_vpc_igw.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage an AWS VPC Internet gateway\n class Ec2_vpc_igw < Base\n # @return [Object] The VPC ID for the VPC in which to manage the Internet Gateway.\n attribute :vpc_id\n validates :vpc_id, presence: true\n\n # @return [Object, nil] A dict of tags to apply to the internet gateway. Any tags currently applied to the internet gateway and not present here will be removed.\n attribute :tags\n\n # @return [:present, :absent, nil] Create or terminate the IGW\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6452174186706543, "alphanum_fraction": 0.6568115949630737, "avg_line_length": 48.75961685180664, "blob_id": "b8f7cf0ce40dd33eb09569ee3a873b39e9d10ae0", "content_id": "4a15acd2c3031c1a63f9a8d1ed16fa6dcb893169", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5175, "license_type": "permissive", "max_line_length": 499, "num_lines": 104, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/redshift.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates, deletes, or modifies amazon Redshift cluster instances.\n class Redshift < Base\n # @return [:create, :facts, :delete, :modify] Specifies the action to take.\n attribute :command\n validates :command, presence: true, expression_inclusion: {:in=>[:create, :facts, :delete, :modify], :message=>\"%{value} needs to be :create, :facts, :delete, :modify\"}\n\n # @return [String] Redshift cluster identifier.\n attribute :identifier\n validates :identifier, presence: true, type: String\n\n # @return [:\"ds1.xlarge\", :\"ds1.8xlarge\", :\"ds2.xlarge\", :\"ds2.8xlarge\", :\"dc1.large\", :\"dc1.8xlarge\", :\"dc2.large\", :\"dc2.8xlarge\", :\"dw1.xlarge\", :\"dw1.8xlarge\", :\"dw2.large\", :\"dw2.8xlarge\", nil] The node type of the cluster. Must be specified when command=create.\n attribute :node_type\n validates :node_type, expression_inclusion: {:in=>[:\"ds1.xlarge\", :\"ds1.8xlarge\", :\"ds2.xlarge\", :\"ds2.8xlarge\", :\"dc1.large\", :\"dc1.8xlarge\", :\"dc2.large\", :\"dc2.8xlarge\", :\"dw1.xlarge\", :\"dw1.8xlarge\", :\"dw2.large\", :\"dw2.8xlarge\"], :message=>\"%{value} needs to be :\\\"ds1.xlarge\\\", :\\\"ds1.8xlarge\\\", :\\\"ds2.xlarge\\\", :\\\"ds2.8xlarge\\\", :\\\"dc1.large\\\", :\\\"dc1.8xlarge\\\", :\\\"dc2.large\\\", :\\\"dc2.8xlarge\\\", :\\\"dw1.xlarge\\\", :\\\"dw1.8xlarge\\\", :\\\"dw2.large\\\", :\\\"dw2.8xlarge\\\"\"}, allow_nil: true\n\n # @return [String, nil] Master database username. Used only when command=create.\n attribute :username\n validates :username, type: String\n\n # @return [String, nil] Master database password. Used only when command=create.\n attribute :password\n validates :password, type: String\n\n # @return [:\"multi-node\", :\"single-node\", nil] The type of cluster.\n attribute :cluster_type\n validates :cluster_type, expression_inclusion: {:in=>[:\"multi-node\", :\"single-node\"], :message=>\"%{value} needs to be :\\\"multi-node\\\", :\\\"single-node\\\"\"}, allow_nil: true\n\n # @return [Object, nil] Name of the database.\n attribute :db_name\n\n # @return [Object, nil] availability zone in which to launch cluster\n attribute :availability_zone\n\n # @return [Object, nil] Number of nodes. Only used when cluster_type=multi-node.\n attribute :number_of_nodes\n\n # @return [Object, nil] which subnet to place the cluster\n attribute :cluster_subnet_group_name\n\n # @return [Object, nil] in which security group the cluster belongs\n attribute :cluster_security_groups\n\n # @return [Object, nil] VPC security group\n attribute :vpc_security_group_ids\n\n # @return [String, nil] skip a final snapshot before deleting the cluster. Used only when command=delete.\n attribute :skip_final_cluster_snapshot\n validates :skip_final_cluster_snapshot, type: String\n\n # @return [Object, nil] identifier of the final snapshot to be created before deleting the cluster. If this parameter is provided, final_cluster_snapshot_identifier must be false. Used only when command=delete.\n attribute :final_cluster_snapshot_identifier\n\n # @return [Object, nil] maintenance window\n attribute :preferred_maintenance_window\n\n # @return [Object, nil] name of the cluster parameter group\n attribute :cluster_parameter_group_name\n\n # @return [Object, nil] period when the snapshot take place\n attribute :automated_snapshot_retention_period\n\n # @return [Object, nil] which port the cluster is listining\n attribute :port\n\n # @return [1.0, nil] which version the cluster should have\n attribute :cluster_version\n validates :cluster_version, expression_inclusion: {:in=>[1.0], :message=>\"%{value} needs to be 1.0\"}, allow_nil: true\n\n # @return [String, nil] flag to determinate if upgrade of version is possible\n attribute :allow_version_upgrade\n validates :allow_version_upgrade, type: String\n\n # @return [String, nil] if the cluster is accessible publicly or not\n attribute :publicly_accessible\n validates :publicly_accessible, type: String\n\n # @return [String, nil] if the cluster is encrypted or not\n attribute :encrypted\n validates :encrypted, type: String\n\n # @return [Object, nil] if the cluster has an elastic IP or not\n attribute :elastic_ip\n\n # @return [Object, nil] Only used when command=modify.\n attribute :new_cluster_identifier\n\n # @return [:yes, :no, nil] When command=create, modify or restore then wait for the database to enter the 'available' state. When command=delete wait for the database to be terminated.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] how long before wait gives up, in seconds\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5520459413528442, "alphanum_fraction": 0.5534816980361938, "avg_line_length": 26.3137264251709, "blob_id": "5e5e7dc784236d74e7ed86b146efe48a7801ceb0", "content_id": "9736c01d77aa62c18766b7381464324e9eae4ff8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1393, "license_type": "permissive", "max_line_length": 81, "num_lines": 51, "path": "/lib/ansible/ruby/dsl_builders/args.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'ansible/ruby/dsl_builders/base'\n\nmodule Ansible\n module Ruby\n module DslBuilders\n class Args < Base\n # Each of these are normally Ruby methods but we want to control them\n KERNEL_METHOD_OVERRIDES = %i[system test warn sleep method].freeze\n\n def initialize(recipient, &block)\n super()\n @error_handler = block\n @recipient = recipient\n end\n\n def _process_method(id, *args)\n setter = \"#{id}=\".to_sym\n @error_handler[id] if @error_handler && [email protected]_to?(setter)\n value = args.length == 1 ? args[0] : args\n value = _convert_ast_node value\n @recipient.send(setter, value)\n end\n\n KERNEL_METHOD_OVERRIDES.each do |method|\n define_method(method) do |*args|\n _process_method method, *args\n end\n end\n\n private\n\n def _convert_ast_node(value)\n case value\n when DslBuilders::JinjaItemNode\n Ansible::Ruby::Models::JinjaExpression.new(value.flat_context)\n when Hash\n Hash[\n value.map { |key, hash_val| [key, _convert_ast_node(hash_val)] }\n ]\n when Array\n value.map { |val| _convert_ast_node(val) }\n else\n value\n end\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6689655184745789, "alphanum_fraction": 0.6703448295593262, "avg_line_length": 42.93939208984375, "blob_id": "0f22852a0c94f54eb7f4531ad490bc4de21c6867", "content_id": "995f55f0eb6ebaed94b662cfaecfc5b80c57aadf", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1450, "license_type": "permissive", "max_line_length": 176, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/windows/win_psmodule.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module helps to install Powershell modules and register custom modules repository on Windows Server.\n class Win_psmodule < Base\n # @return [String] Name of the powershell module that has to be installed.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:yes, :no, nil] If C(yes) imports all commands, even if they have the same names as commands that already exists. Available only in Powershell 5.1 or higher.\n attribute :allow_clobber\n validates :allow_clobber, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Name of the custom repository to register or use.\n attribute :repository\n validates :repository, type: String\n\n # @return [String, nil] URL of the custom repository to register.\n attribute :url\n validates :url, type: String\n\n # @return [:absent, :present, nil] If C(present) a new module is installed.,If C(absent) a module is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6545275449752808, "alphanum_fraction": 0.6594488024711609, "avg_line_length": 34.034481048583984, "blob_id": "d6e99dd079c89d1c31e253963f2087b55b8b92a8", "content_id": "56ac7ca280f3c161892ee1929c4b73a1cbd0b4c1", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1016, "license_type": "permissive", "max_line_length": 143, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_net_vlan.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or Delete a network VLAN\n class Na_ontap_net_vlan < Base\n # @return [:present, :absent, nil] Whether the specified network VLAN should exist or not\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The interface that hosts the VLAN interface.\n attribute :parent_interface\n validates :parent_interface, presence: true, type: String\n\n # @return [String] The VLAN id. Ranges from 1 to 4094.\n attribute :vlanid\n validates :vlanid, presence: true, type: String\n\n # @return [String] Node name of VLAN interface.\n attribute :node\n validates :node, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6484535932540894, "alphanum_fraction": 0.6491408944129944, "avg_line_length": 49.17241287231445, "blob_id": "456515b2e75f34ddb6554171601658309d639184", "content_id": "56f14bd911ecd6ff543dc5638af3f2e4e521c5f9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2910, "license_type": "permissive", "max_line_length": 220, "num_lines": 58, "path": "/lib/ansible/ruby/modules/generated/source_control/subversion.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Deploy given repository URL / revision to dest. If dest exists, update to the specified revision, otherwise perform a checkout.\n class Subversion < Base\n # @return [String] The subversion URL to the repository.\n attribute :repo\n validates :repo, presence: true, type: String\n\n # @return [String] Absolute path where the repository should be deployed.\n attribute :dest\n validates :dest, presence: true, type: String\n\n # @return [String, nil] Specific revision to checkout.\n attribute :revision\n validates :revision, type: String\n\n # @return [:yes, :no, nil] If C(yes), modified files will be discarded. If C(no), module will fail if it encounters modified files. Prior to 1.9 the default was C(yes).\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If the directory exists, then the working copy will be checked-out over-the-top using svn checkout --force; if force is specified then existing files with different content are reverted\n attribute :in_place\n validates :in_place, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] C(--username) parameter passed to svn.\n attribute :username\n\n # @return [Object, nil] C(--password) parameter passed to svn.\n attribute :password\n\n # @return [Object, nil] Path to svn executable to use. If not supplied, the normal mechanism for resolving binary paths will be used.\n attribute :executable\n\n # @return [:yes, :no, nil] If C(no), do not check out the repository if it does not exist locally.\n attribute :checkout\n validates :checkout, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), do not retrieve new revisions from the origin repository.\n attribute :update\n validates :update, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(yes), do export instead of checkout/update.\n attribute :export\n validates :export, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), do not call svn switch before update.\n attribute :switch\n validates :switch, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6565205454826355, "alphanum_fraction": 0.6618263125419617, "avg_line_length": 44.3291130065918, "blob_id": "e4a03ee37378736509d2ca210b205301592edd56", "content_id": "99895ec5b5c05883f8c885ffd26c52e5ab398bae", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3581, "license_type": "permissive", "max_line_length": 186, "num_lines": 79, "path": "/lib/ansible/ruby/modules/generated/cloud/rackspace/rax_scaling_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manipulate Rackspace Cloud Autoscale Groups\n class Rax_scaling_group < Base\n # @return [:yes, :no, nil] Attach read-only configuration drive to server as label config-2\n attribute :config_drive\n validates :config_drive, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] The period of time, in seconds, that must pass before any scaling can occur after the previous scaling. Must be an integer between 0 and 86400 (24 hrs).\n attribute :cooldown\n\n # @return [:auto, :manual, nil] Disk partitioning strategy\n attribute :disk_config\n validates :disk_config, expression_inclusion: {:in=>[:auto, :manual], :message=>\"%{value} needs to be :auto, :manual\"}, allow_nil: true\n\n # @return [Object, nil] Files to insert into the instance. Hash of C(remotepath: localpath)\n attribute :files\n\n # @return [Object] flavor to use for the instance\n attribute :flavor\n validates :flavor, presence: true\n\n # @return [Object] image to use for the instance. Can be an C(id), C(human_id) or C(name)\n attribute :image\n validates :image, presence: true\n\n # @return [Object, nil] key pair to use on the instance\n attribute :key_name\n\n # @return [Object, nil] List of load balancer C(id) and C(port) hashes\n attribute :loadbalancers\n\n # @return [Object] The maximum number of entities that are allowed in the scaling group. Must be an integer between 0 and 1000.\n attribute :max_entities\n validates :max_entities, presence: true\n\n # @return [Object, nil] A hash of metadata to associate with the instance\n attribute :meta\n\n # @return [Object] The minimum number of entities that are allowed in the scaling group. Must be an integer between 0 and 1000.\n attribute :min_entities\n validates :min_entities, presence: true\n\n # @return [Object] Name to give the scaling group\n attribute :name\n validates :name, presence: true\n\n # @return [String, nil] The network to attach to the instances. If specified, you must include ALL networks including the public and private interfaces. Can be C(id) or C(label).\n attribute :networks\n validates :networks, type: String\n\n # @return [Object] The base name for servers created by Autoscale\n attribute :server_name\n validates :server_name, presence: true\n\n # @return [:present, :absent, nil] Indicate desired state of the resource\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Data to be uploaded to the servers config drive. This option implies I(config_drive). Can be a file path or a string\n attribute :user_data\n\n # @return [:yes, :no, nil] wait for the scaling group to finish provisioning the minimum amount of servers\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] how long before wait gives up, in seconds\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6780968904495239, "alphanum_fraction": 0.6806686520576477, "avg_line_length": 58.82051467895508, "blob_id": "74c4e8f61b94a0d9d6cb115fadd62927eecab18f", "content_id": "1da866497f8bfb6b3aac89bc6dd569153d2f165d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2333, "license_type": "permissive", "max_line_length": 307, "num_lines": 39, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_netstream_template.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages NetStream template configuration on HUAWEI CloudEngine switches.\n class Ce_netstream_template < Base\n # @return [:present, :absent, nil] Specify desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:ip, :vxlan] Configure the type of netstream record.\n attribute :type\n validates :type, presence: true, expression_inclusion: {:in=>[:ip, :vxlan], :message=>\"%{value} needs to be :ip, :vxlan\"}\n\n # @return [Object, nil] Configure the name of netstream record. The value is a string of 1 to 32 case-insensitive characters.\n attribute :record_name\n\n # @return [:\"destination-address\", :\"destination-port\", :tos, :protocol, :\"source-address\", :\"source-port\", nil] Configure flexible flow statistics template keywords.\n attribute :match\n validates :match, expression_inclusion: {:in=>[:\"destination-address\", :\"destination-port\", :tos, :protocol, :\"source-address\", :\"source-port\"], :message=>\"%{value} needs to be :\\\"destination-address\\\", :\\\"destination-port\\\", :tos, :protocol, :\\\"source-address\\\", :\\\"source-port\\\"\"}, allow_nil: true\n\n # @return [:bytes, :packets, nil] Configure the number of packets and bytes that are included in the flexible flow statistics sent to NSC.\n attribute :collect_counter\n validates :collect_counter, expression_inclusion: {:in=>[:bytes, :packets], :message=>\"%{value} needs to be :bytes, :packets\"}, allow_nil: true\n\n # @return [:input, :output, nil] Configure the input or output interface that are included in the flexible flow statistics sent to NSC.\n attribute :collect_interface\n validates :collect_interface, expression_inclusion: {:in=>[:input, :output], :message=>\"%{value} needs to be :input, :output\"}, allow_nil: true\n\n # @return [Object, nil] Configure the description of netstream record. The value is a string of 1 to 80 case-insensitive characters.\n attribute :description\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6329442262649536, "alphanum_fraction": 0.6543450355529785, "avg_line_length": 35.71428680419922, "blob_id": "7ef91869482ec0b7652305e9e7e20eeaa5a75ffc", "content_id": "dd336ede88283a0cbde3df8d281c7875c3bf9496", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1542, "license_type": "permissive", "max_line_length": 143, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_net_routes.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Modify ONTAP network routes.\n class Na_ontap_net_routes < Base\n # @return [:present, :absent, nil] Whether you want to create or delete a network route.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The name of the vserver.\n attribute :vserver\n validates :vserver, presence: true, type: String\n\n # @return [String] Specify the route destination.,Example 10.7.125.5/20, fd20:13::/64.\n attribute :destination\n validates :destination, presence: true, type: String\n\n # @return [String] Specify the route gateway.,Example 10.7.125.1, fd20:13::1.\n attribute :gateway\n validates :gateway, presence: true, type: String\n\n # @return [String, nil] Specify the route metric.,If this field is not provided the default will be set to 20.\n attribute :metric\n validates :metric, type: String\n\n # @return [Object, nil] Specify the new route destination.\n attribute :new_destination\n\n # @return [Object, nil] Specify the new route gateway.\n attribute :new_gateway\n\n # @return [Object, nil] Specify the new route metric.\n attribute :new_metric\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6616643667221069, "alphanum_fraction": 0.6630286574363708, "avg_line_length": 33.904762268066406, "blob_id": "e6d02f6c9162c782ba77533739e2a9baab7f6483", "content_id": "4d928d48163856e5c7e60a28fe346269b2901bf0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 733, "license_type": "permissive", "max_line_length": 143, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/system/locale_gen.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages locales by editing /etc/locale.gen and invoking locale-gen.\n class Locale_gen < Base\n # @return [String] Name and encoding of the locale, such as \"en_GB.UTF-8\".\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, nil] Whether the locale shall be present.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6800997257232666, "alphanum_fraction": 0.6855006217956543, "avg_line_length": 56.30952453613281, "blob_id": "f34fc012b609182c18c2a7dd1e300625434f95c4", "content_id": "31381bc076ccfea20027ddd205ab95647302ceb2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2407, "license_type": "permissive", "max_line_length": 380, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/packaging/os/svr4pkg.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages SVR4 packages on Solaris 10 and 11.\n # These were the native packages on Solaris <= 10 and are available as a legacy feature in Solaris 11.\n # Note that this is a very basic packaging system. It will not enforce dependencies on install or remove.\n class Svr4pkg < Base\n # @return [String] Package name, e.g. C(SUNWcsr)\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent] Whether to install (C(present)), or remove (C(absent)) a package.,If the package is to be installed, then I(src) is required.,The SVR4 package system doesn't provide an upgrade operation. You need to uninstall the old, then install the new package.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String, nil] Specifies the location to install the package from. Required when C(state=present).,Can be any path acceptable to the C(pkgadd) command's C(-d) option. e.g.: C(somefile.pkg), C(/dir/with/pkgs), C(http:/server/mypkgs.pkg).,If using a file or directory, they must already be accessible by the host. See the M(copy) module for a way to get them there.\n attribute :src\n validates :src, type: String\n\n # @return [Object, nil] HTTP[s] proxy to be used if C(src) is a URL.\n attribute :proxy\n\n # @return [String, nil] Specifies the location of a response file to be used if package expects input on install. (added in Ansible 1.4)\n attribute :response_file\n validates :response_file, type: String\n\n # @return [:current, :all, nil] Whether to install the package only in the current zone, or install it into all zones.,The installation into all zones works only if you are working with the global zone.\n attribute :zone\n validates :zone, expression_inclusion: {:in=>[:current, :all], :message=>\"%{value} needs to be :current, :all\"}, allow_nil: true\n\n # @return [Symbol, nil] Install/Remove category instead of a single package.\n attribute :category\n validates :category, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6546310782432556, "alphanum_fraction": 0.6546310782432556, "avg_line_length": 35.400001525878906, "blob_id": "fb8e2c44d21257b780cbfda2df46eba3187da863", "content_id": "d081deaaf0df07bba0ec9c58d1500b8a75998562", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1274, "license_type": "permissive", "max_line_length": 143, "num_lines": 35, "path": "/lib/ansible/ruby/modules/generated/network/system/net_ping.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Tests reachability using ping from network device to a remote destination.\n # For Windows targets, use the M(win_ping) module instead.\n # For targets running Python, use the M(ping) module instead.\n class Net_ping < Base\n # @return [Integer, nil] Number of packets to send.\n attribute :count\n validates :count, type: Integer\n\n # @return [String] The IP Address or hostname (resolvable by switch) of the remote node.\n attribute :dest\n validates :dest, presence: true, type: String\n\n # @return [String, nil] The source IP Address.\n attribute :source\n validates :source, type: String\n\n # @return [:absent, :present, nil] Determines if the expected result is success or fail.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] The VRF to use for forwarding.\n attribute :vrf\n validates :vrf, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6938998103141785, "alphanum_fraction": 0.6968046426773071, "avg_line_length": 49.07272720336914, "blob_id": "d14850e57a811e2f8b83f311b86514e230f93033", "content_id": "cf83e6e464734e4246c6718abef66cc7316d1fd2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2754, "license_type": "permissive", "max_line_length": 271, "num_lines": 55, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_backend_service.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or Destroy a Backend Service. See U(https://cloud.google.com/compute/docs/load-balancing/http/backend-service) for an overview. Full install/configuration instructions for the Google Cloud modules can be found in the comments of ansible/test/gce_tests.py.\n class Gcp_backend_service < Base\n # @return [String] Name of the Backend Service.\n attribute :backend_service_name\n validates :backend_service_name, presence: true, type: String\n\n # @return [Array<Hash>, Hash] List of backends that make up the backend service. A backend is made up of an instance group and optionally several other parameters. See U(https://cloud.google.com/compute/docs/reference/latest/backendServices) for details.\n attribute :backends\n validates :backends, presence: true, type: TypeGeneric.new(Hash)\n\n # @return [Array<String>, String] List of healthchecks. Only one healthcheck is supported.\n attribute :healthchecks\n validates :healthchecks, presence: true, type: TypeGeneric.new(String)\n\n # @return [Object, nil] If true, enable Cloud CDN for this Backend Service.\n attribute :enable_cdn\n\n # @return [String, nil] Name of the port on the managed instance group (MIG) that backend services can forward data to. Required for external load balancing.\n attribute :port_name\n validates :port_name, type: String\n\n # @return [Object, nil] The protocol this Backend Service uses to communicate with backends. Possible values are HTTP, HTTPS, TCP, and SSL. The default is HTTP.\n attribute :protocol\n\n # @return [Integer, nil] How many seconds to wait for the backend before considering it a failed request. Default is 30 seconds. Valid range is 1-86400.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [String, nil] Service account email\n attribute :service_account_email\n validates :service_account_email, type: String\n\n # @return [String, nil] Path to the JSON file associated with the service account email.\n attribute :credentials_file\n validates :credentials_file, type: String\n\n # @return [String, nil] GCE project ID.\n attribute :project_id\n validates :project_id, type: String\n\n # @return [:absent, :present, nil] Desired state of the resource\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6803149580955505, "alphanum_fraction": 0.6803149580955505, "avg_line_length": 43.30232620239258, "blob_id": "76cdc5fc00fd3024e43124aecea941225e25d0a2", "content_id": "368f2370906d482c4d69082ab39ab63b6667614d", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1905, "license_type": "permissive", "max_line_length": 184, "num_lines": 43, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_vserver_peer.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create/Delete vserver peer\n class Na_ontap_vserver_peer < Base\n # @return [:present, :absent, nil] Whether the specified vserver peer should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Specifies name of the source Vserver in the relationship.\n attribute :vserver\n validates :vserver, type: String\n\n # @return [:snapmirror, :file_copy, :lun_copy, nil] List of applications which can make use of the peering relationship.\n attribute :applications\n validates :applications, expression_inclusion: {:in=>[:snapmirror, :file_copy, :lun_copy], :message=>\"%{value} needs to be :snapmirror, :file_copy, :lun_copy\"}, allow_nil: true\n\n # @return [String, nil] Specifies name of the peer Vserver in the relationship.\n attribute :peer_vserver\n validates :peer_vserver, type: String\n\n # @return [String, nil] Specifies name of the peer Cluster.,If peer Cluster is not given, it considers local Cluster.\n attribute :peer_cluster\n validates :peer_cluster, type: String\n\n # @return [String, nil] Destination hostname or IP address.,Required for creating the vserver peer relationship\n attribute :dest_hostname\n validates :dest_hostname, type: String\n\n # @return [Object, nil] Destination username.,Optional if this is same as source username.\n attribute :dest_username\n\n # @return [Object, nil] Destination password.,Optional if this is same as source password.\n attribute :dest_password\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6345653533935547, "alphanum_fraction": 0.6527850031852722, "avg_line_length": 41.68888854980469, "blob_id": "c1c4dea884ddc48a0d618b45c12da0a67d1def95", "content_id": "ccf39a94357cf4e724940a01a3fa8bec4f565d66", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1921, "license_type": "permissive", "max_line_length": 152, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_ip_interface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages Layer 3 attributes for IPv4 and IPv6 interfaces.\n class Nxos_ip_interface < Base\n # @return [String] Full name of interface, i.e. Ethernet1/1, vlan10.\n attribute :interface\n validates :interface, presence: true, type: String\n\n # @return [String, nil] IPv4 or IPv6 Address.\n attribute :addr\n validates :addr, type: String\n\n # @return [:v4, :v6, nil] Version of IP address. If the IP address is IPV4 version should be v4. If the IP address is IPV6 version should be v6.\n attribute :version\n validates :version, expression_inclusion: {:in=>[:v4, :v6], :message=>\"%{value} needs to be :v4, :v6\"}, allow_nil: true\n\n # @return [Integer, nil] Subnet mask for IPv4 or IPv6 Address in decimal format.\n attribute :mask\n validates :mask, type: Integer\n\n # @return [Integer, nil] Configures IEEE 802.1Q VLAN encapsulation on the subinterface. The range is from 2 to 4093.\n attribute :dot1q\n validates :dot1q, type: Integer\n\n # @return [Integer, nil] Route tag for IPv4 or IPv6 Address in integer format.\n attribute :tag\n validates :tag, type: Integer\n\n # @return [:yes, :no, nil] Allow to configure IPv4 secondary addresses on interface.\n attribute :allow_secondary\n validates :allow_secondary, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Specify desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7236272096633911, "alphanum_fraction": 0.726561427116394, "avg_line_length": 83.19999694824219, "blob_id": "9a09d83841bcbc9cc473536dbf9429def84db249", "content_id": "f782703fe9084af7112e3de7bdd8637eb6eb82b9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 7157, "license_type": "permissive", "max_line_length": 440, "num_lines": 85, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_networkinterface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update or delete a network interface. When creating a network interface you must provide the name of an existing virtual network, the name of an existing subnet within the virtual network. A default security group and public IP address will be created automatically, or you can provide the name of an existing security group and public IP address. See the examples below for more details.\n class Azure_rm_networkinterface < Base\n # @return [String] Name of a resource group where the network interface exists or will be created.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] Name of the network interface.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, nil] Assert the state of the network interface. Use 'present' to create or update an interface and 'absent' to delete an interface.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [Object, nil] Valid azure location. Defaults to location of the resource group.\n attribute :location\n\n # @return [String] An existing virtual network with which the network interface will be associated. Required when creating a network interface.,It can be the virtual network's name.,Make sure your virtual network is in the same resource group as NIC when you give only the name.,It can be the virtual network's resource id.,It can be a dict which contains C(name) and C(resource_group) of the virtual network.\n attribute :virtual_network\n validates :virtual_network, presence: true, type: String\n\n # @return [String] Name of an existing subnet within the specified virtual network. Required when creating a network interface,Use the C(virtual_network)'s resource group.\n attribute :subnet_name\n validates :subnet_name, presence: true, type: String\n\n # @return [:Windows, :Linux, nil] Determines any rules to be added to a default security group. When creating a network interface, if no security group name is provided, a default security group will be created. If the os_type is 'Windows', a rule will be added allowing RDP access. If the os_type is 'Linux', a rule allowing SSH access will be added.\n attribute :os_type\n validates :os_type, expression_inclusion: {:in=>[:Windows, :Linux], :message=>\"%{value} needs to be :Windows, :Linux\"}, allow_nil: true\n\n # @return [Object, nil] (Deprecate) Valid IPv4 address that falls within the specified subnet.,This option will be deprecated in 2.9, use I(ip_configurations) instead.\n attribute :private_ip_address\n\n # @return [:Dynamic, :Static, nil] (Deprecate) Specify whether or not the assigned IP address is permanent. NOTE: when creating a network interface specifying a value of 'Static' requires that a private_ip_address value be provided. You can update the allocation method to 'Static' after a dynamic private ip address has been assigned.,This option will be deprecated in 2.9, use I(ip_configurations) instead.\n attribute :private_ip_allocation_method\n validates :private_ip_allocation_method, expression_inclusion: {:in=>[:Dynamic, :Static], :message=>\"%{value} needs to be :Dynamic, :Static\"}, allow_nil: true\n\n # @return [:yes, :no, nil] (Deprecate) When creating a network interface, if no public IP address name is provided a default public IP address will be created. Set to false, if you do not want a public IP address automatically created.,This option will be deprecated in 2.9, use I(ip_configurations) instead.\n attribute :public_ip\n validates :public_ip, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] (Deprecate) Name of an existing public IP address object to associate with the security group.,This option will be deprecated in 2.9, use I(ip_configurations) instead.\n attribute :public_ip_address_name\n\n # @return [:Dynamic, :Static, nil] (Deprecate) If a public_ip_address_name is not provided, a default public IP address will be created. The allocation method determines whether or not the public IP address assigned to the network interface is permanent.,This option will be deprecated in 2.9, use I(ip_configurations) instead.\n attribute :public_ip_allocation_method\n validates :public_ip_allocation_method, expression_inclusion: {:in=>[:Dynamic, :Static], :message=>\"%{value} needs to be :Dynamic, :Static\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash, nil] List of ip configuration if contains mutilple configuration, should contain configuration object include field private_ip_address, private_ip_allocation_method, public_ip_address_name, public_ip, public_ip_allocation_method, name\n attribute :ip_configurations\n validates :ip_configurations, type: TypeGeneric.new(Hash)\n\n # @return [Symbol, nil] Specifies whether the network interface should be created with the accelerated networking feature or not\n attribute :enable_accelerated_networking\n validates :enable_accelerated_networking, type: Symbol\n\n # @return [Boolean, nil] Specifies whether a default security group should be be created with the NIC. Only applies when creating a new NIC.\n attribute :create_with_security_group\n validates :create_with_security_group, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, Hash, nil] An existing security group with which to associate the network interface. If not provided, a default security group will be created when C(create_with_security_group) is true.,It can be the name of security group.,Make sure the security group is in the same resource group when you only give its name.,It can be the resource id.,It can be a dict contains security_group's C(name) and C(resource_group).\n attribute :security_group\n validates :security_group, type: MultipleTypes.new(String, Hash)\n\n # @return [Object, nil] When a default security group is created for a Linux host a rule will be added allowing inbound TCP connections to the default SSH port 22, and for a Windows host rules will be added allowing inbound access to RDP ports 3389 and 5986. Override the default ports by providing a list of open ports.\n attribute :open_ports\n\n # @return [Symbol, nil] Whether to enable IP forwarding\n attribute :enable_ip_forwarding\n validates :enable_ip_forwarding, type: Symbol\n\n # @return [Array<String>, String, nil] Which DNS servers should the NIC lookup,List of IP's\n attribute :dns_servers\n validates :dns_servers, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6711798906326294, "alphanum_fraction": 0.6914893388748169, "avg_line_length": 56.44444274902344, "blob_id": "955125a88de422238781c90154e40b3d1fcc2081", "content_id": "d003029e296f6b81b1449aa70d7bcdf17783477f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2068, "license_type": "permissive", "max_line_length": 285, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_vxlan_vap.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages VXLAN Virtual access point on HUAWEI CloudEngine Devices.\n class Ce_vxlan_vap < Base\n # @return [Object, nil] Specifies a bridge domain ID. The value is an integer ranging from 1 to 16777215.\n attribute :bridge_domain_id\n\n # @return [Object, nil] Specifies the VLAN binding to a BD(Bridge Domain). The value is an integer ranging ranging from 1 to 4094.\n attribute :bind_vlan_id\n\n # @return [Object, nil] Specifies an Sub-Interface full name, i.e. \"10GE1/0/41.1\". The value is a string of 1 to 63 case-insensitive characters, spaces supported.\n attribute :l2_sub_interface\n\n # @return [:dot1q, :default, :untag, :qinq, :none, nil] Specifies an encapsulation type of packets allowed to pass through a Layer 2 sub-interface.\n attribute :encapsulation\n validates :encapsulation, expression_inclusion: {:in=>[:dot1q, :default, :untag, :qinq, :none], :message=>\"%{value} needs to be :dot1q, :default, :untag, :qinq, :none\"}, allow_nil: true\n\n # @return [Object, nil] When I(encapsulation) is 'dot1q', specifies a VLAN ID in the outer VLAN tag. When I(encapsulation) is 'qinq', specifies an outer VLAN ID for double-tagged packets to be received by a Layer 2 sub-interface. The value is an integer ranging from 1 to 4094.\n attribute :ce_vid\n\n # @return [Object, nil] When I(encapsulation) is 'qinq', specifies an inner VLAN ID for double-tagged packets to be received by a Layer 2 sub-interface. The value is an integer ranging from 1 to 4094.\n attribute :pe_vid\n\n # @return [:present, :absent, nil] Determines whether the config should be present or not on the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.670811116695404, "alphanum_fraction": 0.670811116695404, "avg_line_length": 37.3863639831543, "blob_id": "cf4771f1d402165247ae5b19906b4e8bade506dd", "content_id": "30c75ac7e7594a9ee7c9708dabc399d914f057c8", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1689, "license_type": "permissive", "max_line_length": 130, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_net_port.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Modify a ONTAP network port.\n class Na_ontap_net_port < Base\n # @return [:present, nil] Whether the specified net port should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present], :message=>\"%{value} needs to be :present\"}, allow_nil: true\n\n # @return [String] Specifies the name of node.\n attribute :node\n validates :node, presence: true, type: String\n\n # @return [String] Specifies the name of port.\n attribute :port\n validates :port, presence: true, type: String\n\n # @return [Object, nil] Specifies the maximum transmission unit (MTU) reported by the port.\n attribute :mtu\n\n # @return [String, nil] Enables or disables Ethernet auto-negotiation of speed, duplex and flow control.\n attribute :autonegotiate_admin\n validates :autonegotiate_admin, type: String\n\n # @return [Object, nil] Specifies the user preferred duplex setting of the port.,Valid values auto, half, full\n attribute :duplex_admin\n\n # @return [Object, nil] Specifies the user preferred speed setting of the port.\n attribute :speed_admin\n\n # @return [Object, nil] Specifies the user preferred flow control setting of the port.\n attribute :flowcontrol_admin\n\n # @return [Object, nil] Specifies the port's associated IPspace name.,The 'Cluster' ipspace is reserved for cluster ports.\n attribute :ipspace\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7174665927886963, "alphanum_fraction": 0.7174665927886963, "avg_line_length": 60.24242401123047, "blob_id": "f09992d2edd09da4a0f15964313f02d8576af124", "content_id": "685a90c5f711a45afc4c383e3d710fe784dd16c6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2021, "license_type": "permissive", "max_line_length": 293, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/net_tools/nios/nios_dns_view.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Adds and/or removes instances of DNS view objects from Infoblox NIOS servers. This module manages NIOS C(view) objects using the Infoblox WAPI interface over REST.\n # Updates instances of DNS view object from Infoblox NIOS servers.\n class Nios_dns_view < Base\n # @return [String, Hash] Specifies the fully qualified hostname to add or remove from the system. User can also update the hostname as it is possible to pass a dict containing I(new_name), I(old_name). See examples.\n attribute :name\n validates :name, presence: true, type: MultipleTypes.new(String, Hash)\n\n # @return [String] Specifies the name of the network view to assign the configured DNS view to. The network view must already be configured on the target system.\n attribute :network_view\n validates :network_view, presence: true, type: String\n\n # @return [Object, nil] Allows for the configuration of Extensible Attributes on the instance of the object. This argument accepts a set of key / value pairs for configuration.\n attribute :extattrs\n\n # @return [String, nil] Configures a text string comment to be associated with the instance of this object. The provided text string will be configured on the object instance.\n attribute :comment\n validates :comment, type: String\n\n # @return [:present, :absent, nil] Configures the intended state of the instance of the object on the NIOS server. When this value is set to C(present), the object is configured on the device and when this value is set to C(absent) the value is removed (if necessary) from the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6945347785949707, "alphanum_fraction": 0.7062459588050842, "avg_line_length": 79.89473724365234, "blob_id": "e4738e2e9ea9312d65c7bb88783d583e2c4ac01b", "content_id": "b080cfbf33c993fa0d93fcbb0edbc14f79c26202", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3078, "license_type": "permissive", "max_line_length": 532, "num_lines": 38, "path": "/lib/ansible/ruby/modules/generated/remote_management/ucs/ucs_vsans.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configures VSANs on Cisco UCS Manager.\n # Examples can be used with the UCS Platform Emulator U(https://communities.cisco.com/ucspe).\n class Ucs_vsans < Base\n # @return [:present, :absent, nil] If C(present), will verify VSANs are present and will create if needed.,If C(absent), will verify VSANs are absent and will delete if needed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The name assigned to the VSAN.,This name can be between 1 and 32 alphanumeric characters.,You cannot use spaces or any special characters other than - (hyphen), \"_\" (underscore), : (colon), and . (period).,You cannot change this name after the VSAN is created.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] The unique identifier assigned to the VSAN.,The ID can be a string between '1' and '4078', or between '4080' and '4093'. '4079' is a reserved VSAN ID.,In addition, if you plan to use FC end-host mode, the range between '3840' to '4079' is also a reserved VSAN ID range.,Optional if state is absent.\n attribute :vsan_id\n validates :vsan_id, presence: true, type: String\n\n # @return [String] The unique string identifier assigned to the VLAN used for Fibre Channel connections.,Note that Cisco UCS Manager uses VLAN '4048'. See the UCS Manager configuration guide if you want to assign '4048' to a VLAN.,Optional if state is absent.\n attribute :vlan_id\n validates :vlan_id, presence: true, type: String\n\n # @return [:disabled, :enabled, nil] Fibre Channel zoning configuration for the Cisco UCS domain.,Fibre Channel zoning can be set to one of the following values:,disabled — The upstream switch handles Fibre Channel zoning, or Fibre Channel zoning is not implemented for the Cisco UCS domain.,enabled — Cisco UCS Manager configures and controls Fibre Channel zoning for the Cisco UCS domain.,If you enable Fibre Channel zoning, do not configure the upstream switch with any VSANs that are being used for Fibre Channel zoning.\n attribute :fc_zoning\n validates :fc_zoning, expression_inclusion: {:in=>[:disabled, :enabled], :message=>\"%{value} needs to be :disabled, :enabled\"}, allow_nil: true\n\n # @return [:common, :A, :B, nil] The fabric configuration of the VSAN. This can be one of the following:,common - The VSAN maps to the same VSAN ID in all available fabrics.,A - The VSAN maps to the a VSAN ID that exists only in fabric A.,B - The VSAN maps to the a VSAN ID that exists only in fabric B.\n attribute :fabric\n validates :fabric, expression_inclusion: {:in=>[:common, :A, :B], :message=>\"%{value} needs to be :common, :A, :B\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7747551798820496, "alphanum_fraction": 0.7769314646720886, "avg_line_length": 60.266666412353516, "blob_id": "becc4e5e30a3edb7909c78b6578ee8a01abba6c8", "content_id": "1de5243db2d5c8a3a014df1ed2449f0b98b45632", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 919, "license_type": "permissive", "max_line_length": 672, "num_lines": 15, "path": "/lib/ansible/ruby/modules/generated/network/cnos/cnos_save.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows you to copy the running configuration of a switch over its startup configuration. It is recommended to use this module shortly after any major configuration changes so they persist after a switch restart. This module uses SSH to manage network device configuration. The results of the operation will be placed in a directory named 'results' that must be created by the user in their local directory to where the playbook is run. For more information about this module from Lenovo and customizing it usage for your use cases, please visit U(http://systemx.lenovofiles.com/help/index.jsp?topic=%2Fcom.lenovo.switchmgt.ansible.doc%2Fcnos_save.html)\n class Cnos_save < Base\n\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6672297120094299, "alphanum_fraction": 0.6672297120094299, "avg_line_length": 34.878787994384766, "blob_id": "861e769b8920991bd09a59f4589ec4d60c8ac87a", "content_id": "241148769c597e34d55e47323f72f8b4c3832fd9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1184, "license_type": "permissive", "max_line_length": 143, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/ejabberd_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides user management for ejabberd servers\n class Ejabberd_user < Base\n # @return [String] the name of the user to manage\n attribute :username\n validates :username, presence: true, type: String\n\n # @return [String] the ejabberd host associated with this username\n attribute :host\n validates :host, presence: true, type: String\n\n # @return [String, nil] the password to assign to the username\n attribute :password\n validates :password, type: String\n\n # @return [Symbol, nil] enables or disables the local syslog facility for this module\n attribute :logging\n validates :logging, type: Symbol\n\n # @return [:present, :absent, nil] describe the desired state of the user to be managed\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6967105269432068, "alphanum_fraction": 0.7059210538864136, "avg_line_length": 53.28571319580078, "blob_id": "2da1c6e49f96df4455b1a85ce80a89df3f6723c6", "content_id": "c92a35871555e61374e75f838ff6dbe06063eec6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1520, "license_type": "permissive", "max_line_length": 463, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_compute_target_http_proxy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Represents a TargetHttpProxy resource, which is used by one or more global forwarding rule to route incoming HTTP requests to a URL map.\n class Gcp_compute_target_http_proxy < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] An optional description of this resource.\n attribute :description\n\n # @return [String] Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] A reference to the UrlMap resource that defines the mapping from URL to the BackendService.\n attribute :url_map\n validates :url_map, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6721405982971191, "alphanum_fraction": 0.6738691926002502, "avg_line_length": 50.04411697387695, "blob_id": "fa245ef887c696b6604c694f413c891e651e5f17", "content_id": "3ec129071dc4e327648ddb6706d1a6decbf8e33f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3471, "license_type": "permissive", "max_line_length": 477, "num_lines": 68, "path": "/lib/ansible/ruby/modules/generated/database/mongodb/mongodb_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Adds or removes a user from a MongoDB database.\n class Mongodb_user < Base\n # @return [String, nil] The username used to authenticate with\n attribute :login_user\n validates :login_user, type: String\n\n # @return [String, nil] The password used to authenticate with\n attribute :login_password\n validates :login_password, type: String\n\n # @return [String, nil] The host running the database\n attribute :login_host\n validates :login_host, type: String\n\n # @return [Integer, nil] The port to connect to\n attribute :login_port\n validates :login_port, type: Integer\n\n # @return [Object, nil] The database where login credentials are stored\n attribute :login_database\n\n # @return [String, nil] Replica set to connect to (automatically connects to primary for writes)\n attribute :replica_set\n validates :replica_set, type: String\n\n # @return [String] The name of the database to add/remove the user from\n attribute :database\n validates :database, presence: true, type: String\n\n # @return [String] The name of the user to add or remove\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Integer, String, nil] The password to use for the user\n attribute :password\n validates :password, type: MultipleTypes.new(Integer, String)\n\n # @return [Boolean, nil] Whether to use an SSL connection when connecting to the database\n attribute :ssl\n validates :ssl, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:CERT_REQUIRED, :CERT_OPTIONAL, :CERT_NONE, nil] Specifies whether a certificate is required from the other side of the connection, and whether it will be validated if provided.\n attribute :ssl_cert_reqs\n validates :ssl_cert_reqs, expression_inclusion: {:in=>[:CERT_REQUIRED, :CERT_OPTIONAL, :CERT_NONE], :message=>\"%{value} needs to be :CERT_REQUIRED, :CERT_OPTIONAL, :CERT_NONE\"}, allow_nil: true\n\n # @return [String, nil] The database user roles valid values could either be one or more of the following strings: 'read', 'readWrite', 'dbAdmin', 'userAdmin', 'clusterAdmin', 'readAnyDatabase', 'readWriteAnyDatabase', 'userAdminAnyDatabase', 'dbAdminAnyDatabase'\\r\\n,Or the following dictionary '{ db: DATABASE_NAME, role: ROLE_NAME }'.,This param requires pymongo 2.5+. If it is a string, mongodb 2.4+ is also required. If it is a dictionary, mongo 2.6+ is required.\n attribute :roles\n validates :roles, type: String\n\n # @return [:present, :absent, nil] The database user state\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:always, :on_create, nil] C(always) will update passwords if they differ. C(on_create) will only set the password for newly created users.\n attribute :update_password\n validates :update_password, expression_inclusion: {:in=>[:always, :on_create], :message=>\"%{value} needs to be :always, :on_create\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7073529362678528, "alphanum_fraction": 0.7102941274642944, "avg_line_length": 62.75, "blob_id": "18d6e51d206362baf22b2469adf29c090bc70d9d", "content_id": "fe5ef4b2713be2dd0b8238e69504b6d3a70bd163", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2040, "license_type": "permissive", "max_line_length": 333, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/windows/win_region.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Set the location settings of a Windows Server.\n # Set the format settings of a Windows Server.\n # Set the unicode language settings of a Windows Server.\n # Copy across these settings to the default profile.\n class Win_region < Base\n # @return [Integer, nil] The location to set for the current user, see U(https://msdn.microsoft.com/en-us/library/dd374073.aspx) for a list of GeoIDs you can use and what location it relates to. This needs to be set if C(format) or C(unicode_language) is not set.\n attribute :location\n validates :location, type: Integer\n\n # @return [String, nil] The language format to set for the current user, see U(https://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.aspx) for a list of culture names to use. This needs to be set if C(location) or C(unicode_language) is not set.\n attribute :format\n validates :format, type: String\n\n # @return [String, nil] The unicode language format to set for all users, see U(https://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.aspx) for a list of culture names to use. This needs to be set if C(location) or C(format) is not set. After setting this value a reboot is required for it to take effect.\n attribute :unicode_language\n validates :unicode_language, type: String\n\n # @return [:yes, :no, nil] This will copy the current format and location values to new user profiles and the welcome screen. This will only run if C(location), C(format) or C(unicode_language) has resulted in a change. If this process runs then it will always result in a change.\n attribute :copy_settings\n validates :copy_settings, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6482504606246948, "alphanum_fraction": 0.6482504606246948, "avg_line_length": 24.85714340209961, "blob_id": "2e03f5af2c2f43e3d7a74eef5f436c4c824dd551", "content_id": "45f7cafaaafd489208230c730f3ec5d26d628c0e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 543, "license_type": "permissive", "max_line_length": 73, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/notification/say.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # makes a computer speak! Amuse your friends, annoy your coworkers!\n class Say < Base\n # @return [String] What to say\n attribute :msg\n validates :msg, presence: true, type: String\n\n # @return [String, nil] What voice to use\n attribute :voice\n validates :voice, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.663922131061554, "alphanum_fraction": 0.663922131061554, "avg_line_length": 45.068965911865234, "blob_id": "0e449f6b78f312fff2a1d2156a4c5e01e4861833", "content_id": "e7345c0d1b854e861294e8140498b9693a18ef1f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1336, "license_type": "permissive", "max_line_length": 155, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_udld.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages UDLD global configuration params.\n class Nxos_udld < Base\n # @return [:enabled, :disabled, nil] Toggles aggressive mode.\n attribute :aggressive\n validates :aggressive, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [Integer, nil] Message time in seconds for UDLD packets or keyword 'default'.\n attribute :msg_time\n validates :msg_time, type: Integer\n\n # @return [:yes, :no, nil] Ability to reset all ports shut down by UDLD. 'state' parameter cannot be 'absent' when this is present.\n attribute :reset\n validates :reset, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Manage the state of the resource. When set to 'absent', aggressive and msg_time are set to their default values.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7078831791877747, "alphanum_fraction": 0.7086834907531738, "avg_line_length": 85.17241668701172, "blob_id": "f11b1f0bf895c72cf8a1573c50ba24909f6e9605", "content_id": "75bf690175cf90c86d67c64a4d2c9553a12063d9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2499, "license_type": "permissive", "max_line_length": 381, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/database/proxysql/proxysql_manage_config.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The M(proxysql_global_variables) module writes the proxysql configuration settings between layers. Currently this module will always report a changed state, so should typically be used with WHEN however this will change in a future version when the CHECKSUM table commands are available for all tables in proxysql.\n class Proxysql_manage_config < Base\n # @return [:LOAD, :SAVE] The supplied I(action) combines with the supplied I(direction) to provide the semantics of how we want to move the I(config_settings) between the I(config_layers).\n attribute :action\n validates :action, presence: true, expression_inclusion: {:in=>[:LOAD, :SAVE], :message=>\"%{value} needs to be :LOAD, :SAVE\"}\n\n # @return [:\"MYSQL USERS\", :\"MYSQL SERVERS\", :\"MYSQL QUERY RULES\", :\"MYSQL VARIABLES\", :\"ADMIN VARIABLES\", :SCHEDULER] The I(config_settings) specifies which configuration we're writing.\n attribute :config_settings\n validates :config_settings, presence: true, expression_inclusion: {:in=>[:\"MYSQL USERS\", :\"MYSQL SERVERS\", :\"MYSQL QUERY RULES\", :\"MYSQL VARIABLES\", :\"ADMIN VARIABLES\", :SCHEDULER], :message=>\"%{value} needs to be :\\\"MYSQL USERS\\\", :\\\"MYSQL SERVERS\\\", :\\\"MYSQL QUERY RULES\\\", :\\\"MYSQL VARIABLES\\\", :\\\"ADMIN VARIABLES\\\", :SCHEDULER\"}\n\n # @return [:FROM, :TO] FROM - denotes we're reading values FROM the supplied I(config_layer) and writing to the next layer. TO - denotes we're reading from the previous layer and writing TO the supplied I(config_layer).\"\n attribute :direction\n validates :direction, presence: true, expression_inclusion: {:in=>[:FROM, :TO], :message=>\"%{value} needs to be :FROM, :TO\"}\n\n # @return [:MEMORY, :DISK, :RUNTIME, :CONFIG] RUNTIME - represents the in-memory data structures of ProxySQL used by the threads that are handling the requests. MEMORY - (sometimes also referred as main) represents the in-memory SQLite3 database. DISK - represents the on-disk SQLite3 database. CONFIG - is the classical config file. You can only LOAD FROM the config file.\n attribute :config_layer\n validates :config_layer, presence: true, expression_inclusion: {:in=>[:MEMORY, :DISK, :RUNTIME, :CONFIG], :message=>\"%{value} needs to be :MEMORY, :DISK, :RUNTIME, :CONFIG\"}\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6428571343421936, "alphanum_fraction": 0.6428571343421936, "avg_line_length": 38.319149017333984, "blob_id": "f6bfc1c3bb552fe9f1f7a1b4fc27444f48214f48", "content_id": "ccb338225f88bb61f9f00ba387ca4f6beedd4c07", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1848, "license_type": "permissive", "max_line_length": 237, "num_lines": 47, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/ansible_tower/tower_role.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, or destroy Ansible Tower roles. See U(https://www.ansible.com/tower) for an overview.\n class Tower_role < Base\n # @return [String, nil] User that receives the permissions specified by the role.\n attribute :user\n validates :user, type: String\n\n # @return [Object, nil] Team that receives the permissions specified by the role.\n attribute :team\n\n # @return [:admin, :read, :member, :execute, :adhoc, :update, :use, :auditor] The role type to grant/revoke.\n attribute :role\n validates :role, presence: true, expression_inclusion: {:in=>[:admin, :read, :member, :execute, :adhoc, :update, :use, :auditor], :message=>\"%{value} needs to be :admin, :read, :member, :execute, :adhoc, :update, :use, :auditor\"}\n\n # @return [String, nil] Team that the role acts on.\n attribute :target_team\n validates :target_team, type: String\n\n # @return [Object, nil] Inventory the role acts on.\n attribute :inventory\n\n # @return [Object, nil] The job template the role acts on.\n attribute :job_template\n\n # @return [Object, nil] Credential the role acts on.\n attribute :credential\n\n # @return [Object, nil] Organization the role acts on.\n attribute :organization\n\n # @return [Object, nil] Project the role acts on.\n attribute :project\n\n # @return [:present, :absent, nil] Desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6593616008758545, "alphanum_fraction": 0.6593616008758545, "avg_line_length": 38.60377502441406, "blob_id": "9a1567efc5e61bf9fc5c8529b5a648aca3bf47f5", "content_id": "3cd202ee3583e1f82defc1b43bf2fe8e0e9943b7", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2099, "license_type": "permissive", "max_line_length": 143, "num_lines": 53, "path": "/lib/ansible/ruby/modules/generated/storage/purestorage/purefb_fs.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module manages filesystems on Pure Storage FlashBlade.\n class Purefb_fs < Base\n # @return [String] Filesystem Name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Create, delete or modifies a filesystem.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Symbol, nil] Define whether to eradicate the filesystem on delete or leave in trash.\n attribute :eradicate\n validates :eradicate, type: Symbol\n\n # @return [String, nil] Volume size in M, G, T or P units. See examples.\n attribute :size\n validates :size, type: String\n\n # @return [Boolean, nil] Define whether to NFS protocol is enabled for the filesystem.\n attribute :nfs\n validates :nfs, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] Define the NFS rules in operation.\n attribute :nfs_rules\n validates :nfs_rules, type: TypeGeneric.new(String)\n\n # @return [Symbol, nil] Define whether to SMB protocol is enabled for the filesystem.\n attribute :smb\n validates :smb, type: Symbol\n\n # @return [Symbol, nil] Define whether to HTTP/HTTPS protocol is enabled for the filesystem.\n attribute :http\n validates :http, type: Symbol\n\n # @return [Symbol, nil] Define whether a snapshot directory is enabled for the filesystem.\n attribute :snapshot\n validates :snapshot, type: Symbol\n\n # @return [Symbol, nil] Define whether the fast remove directory is enabled for the filesystem.\n attribute :fastremove\n validates :fastremove, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.699851393699646, "alphanum_fraction": 0.7017087936401367, "avg_line_length": 57.5217399597168, "blob_id": "5738f37dbebc8a187e8021aef3cb7db9edcf24b6", "content_id": "c2588a09ca25aedef90c3a9b543207005d1c01ca", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2692, "license_type": "permissive", "max_line_length": 422, "num_lines": 46, "path": "/lib/ansible/ruby/modules/generated/remote_management/imc/imc_rest.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Provides direct access to the Cisco IMC REST API.\n # Perform any configuration changes and actions that the Cisco IMC supports.\n # More information about the IMC REST API is available from U(http://www.cisco.com/c/en/us/td/docs/unified_computing/ucs/c/sw/api/3_0/b_Cisco_IMC_api_301.html)\n class Imc_rest < Base\n # @return [String] IP Address or hostname of Cisco IMC, resolvable by Ansible control host.\n attribute :hostname\n validates :hostname, presence: true, type: String\n\n # @return [String, nil] Username used to login to the switch.\n attribute :username\n validates :username, type: String\n\n # @return [String, nil] The password to use for authentication.\n attribute :password\n validates :password, type: String\n\n # @return [Object, nil] Name of the absolute path of the filename that includes the body of the http request being sent to the Cisco IMC REST API.,Parameter C(path) is mutual exclusive with parameter C(content).\n attribute :path\n\n # @return [String, nil] When used instead of C(path), sets the content of the API requests directly.,This may be convenient to template simple requests, for anything complex use the M(template) module.,You can collate multiple IMC XML fragments and they will be processed sequentially in a single stream, the Cisco IMC output is subsequently merged.,Parameter C(content) is mutual exclusive with parameter C(path).\n attribute :content\n validates :content, type: String\n\n # @return [:http, :https, nil] Connection protocol to use.\n attribute :protocol\n validates :protocol, expression_inclusion: {:in=>[:http, :https], :message=>\"%{value} needs to be :http, :https\"}, allow_nil: true\n\n # @return [Integer, nil] The socket level timeout in seconds.,This is the time that every single connection (every fragment) can spend. If this C(timeout) is reached, the module will fail with a C(Connection failure) indicating that C(The read operation timed out).\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated.,This should only set to C(no) used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6614222526550293, "alphanum_fraction": 0.6614222526550293, "avg_line_length": 38.724998474121094, "blob_id": "e548b20ba004cce9f3aadc091355d200ff24989b", "content_id": "d9ff8118f5405cedea712f692d18a7de159f9de0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1589, "license_type": "permissive", "max_line_length": 143, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/network/routing/net_static_route.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of static IP routes on network appliances (routers, switches et. al.).\n class Net_static_route < Base\n # @return [String] Network prefix of the static route.\n attribute :prefix\n validates :prefix, presence: true, type: String\n\n # @return [String] Network prefix mask of the static route.\n attribute :mask\n validates :mask, presence: true, type: String\n\n # @return [String] Next hop IP of the static route.\n attribute :next_hop\n validates :next_hop, presence: true, type: String\n\n # @return [Object, nil] Admin distance of the static route.\n attribute :admin_distance\n\n # @return [Array<Hash>, Hash, nil] List of static route definitions\n attribute :aggregate\n validates :aggregate, type: TypeGeneric.new(Hash)\n\n # @return [Boolean, nil] Purge static routes not defined in the I(aggregate) parameter.\n attribute :purge\n validates :purge, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:present, :absent, nil] State of the static route configuration.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6764013171195984, "alphanum_fraction": 0.6844088435173035, "avg_line_length": 50.780487060546875, "blob_id": "d25c362e871a956b51fc39ac7c1c5da39f4afcbd", "content_id": "ca61887e9560e7e331bce91cef75b4d1ce322f7c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2123, "license_type": "permissive", "max_line_length": 333, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/cloud/dimensiondata/dimensiondata_vlan.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage VLANs in Cloud Control network domains.\n class Dimensiondata_vlan < Base\n # @return [String, nil] The name of the target VLAN.,Required if C(state) is C(present).\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] A description of the VLAN.\n attribute :description\n validates :description, type: String\n\n # @return [String] The Id or name of the target network domain.\n attribute :network_domain\n validates :network_domain, presence: true, type: String\n\n # @return [String, nil] The base address for the VLAN's IPv4 network (e.g. 192.168.1.0).\n attribute :private_ipv4_base_address\n validates :private_ipv4_base_address, type: String\n\n # @return [Integer, nil] The size of the IPv4 address space, e.g 24.,Required, if C(private_ipv4_base_address) is specified.\n attribute :private_ipv4_prefix_size\n validates :private_ipv4_prefix_size, type: Integer\n\n # @return [:present, :absent, :readonly, nil] The desired state for the target VLAN.,C(readonly) ensures that the state is only ever read, not modified (the module will fail if the resource does not exist).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :readonly], :message=>\"%{value} needs to be :present, :absent, :readonly\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Permit expansion of the target VLAN's network if the module parameters specify a larger network than the VLAN currently posesses?,If C(False), the module will fail under these conditions.,This is intended to prevent accidental expansion of a VLAN's network (since this operation is not reversible).\n attribute :allow_expand\n validates :allow_expand, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6688555479049683, "alphanum_fraction": 0.6688555479049683, "avg_line_length": 35.75862121582031, "blob_id": "9d2f192738b9b8a5d3fff26a297b92f2cea54c9e", "content_id": "9179b1d9b59ddbaf3f5858439a37fb5178799028", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1066, "license_type": "permissive", "max_line_length": 143, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_groups.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Module to manage groups in oVirt/RHV\n class Ovirt_group < Base\n # @return [String] Name of the group to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Should the group be present/absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object] Authorization provider of the group. In previous versions of oVirt/RHV known as domain.\n attribute :authz_name\n validates :authz_name, presence: true\n\n # @return [Array<String>, String, nil] Namespace of the authorization provider, where group resides.\n attribute :namespace\n validates :namespace, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6621900796890259, "alphanum_fraction": 0.6621900796890259, "avg_line_length": 44.02325439453125, "blob_id": "4aa7fd1a299e4278a09a7c9b8b0cc6e524931c30", "content_id": "69928e9af347ed2e99bf0159499afe01b031c944", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1936, "license_type": "permissive", "max_line_length": 173, "num_lines": 43, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_vlan_pool_encap_block.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage VLAN encap blocks that are assigned to VLAN pools on Cisco ACI fabrics.\n class Aci_vlan_pool_encap_block < Base\n # @return [:dynamic, :inherit, :static, nil] The method used for allocating encaps to resources.\n attribute :allocation_mode\n validates :allocation_mode, expression_inclusion: {:in=>[:dynamic, :inherit, :static], :message=>\"%{value} needs to be :dynamic, :inherit, :static\"}, allow_nil: true\n\n # @return [Object, nil] Description for the pool encap block.\n attribute :description\n\n # @return [String, nil] The name of the pool that the encap block should be assigned to.\n attribute :pool\n validates :pool, type: String\n\n # @return [:dynamic, :static, nil] The method used for allocating encaps to resources.\n attribute :pool_allocation_mode\n validates :pool_allocation_mode, expression_inclusion: {:in=>[:dynamic, :static], :message=>\"%{value} needs to be :dynamic, :static\"}, allow_nil: true\n\n # @return [Integer, nil] The end of encap block.\n attribute :block_end\n validates :block_end, type: Integer\n\n # @return [Object, nil] The name to give to the encap block.\n attribute :block_name\n\n # @return [Integer, nil] The start of the encap block.\n attribute :block_start\n validates :block_start, type: Integer\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6892388463020325, "alphanum_fraction": 0.6950131058692932, "avg_line_length": 47.846153259277344, "blob_id": "f8adb2bda0540a530af28566db2a3cafd2f8f337", "content_id": "87a772e05b2ed9d0705f6271bd0eca1b4d580a9d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1905, "license_type": "permissive", "max_line_length": 179, "num_lines": 39, "path": "/lib/ansible/ruby/modules/generated/network/netscaler/netscaler_save_config.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module uncoditionally saves the configuration on the target netscaler node.\n # This module does not support check mode.\n # This module is intended to run either on the ansible control node or a bastion (jumpserver) with access to the actual netscaler instance.\n class Netscaler_save_config < Base\n # @return [String] The ip address of the netscaler appliance where the nitro API calls will be made.,The port can be specified with the colon (:). E.g. C(192.168.1.1:555).\n attribute :nsip\n validates :nsip, presence: true, type: String\n\n # @return [String] The username with which to authenticate to the netscaler node.\n attribute :nitro_user\n validates :nitro_user, presence: true, type: String\n\n # @return [String] The password with which to authenticate to the netscaler node.\n attribute :nitro_pass\n validates :nitro_pass, presence: true, type: String\n\n # @return [:http, :https, nil] Which protocol to use when accessing the nitro API objects.\n attribute :nitro_protocol\n validates :nitro_protocol, expression_inclusion: {:in=>[:http, :https], :message=>\"%{value} needs to be :http, :https\"}, allow_nil: true\n\n # @return [String, nil] If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, type: String\n\n # @return [Integer, nil] Time in seconds until a timeout error is thrown when establishing a new session with Netscaler.\n attribute :nitro_timeout\n validates :nitro_timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6776669025421143, "alphanum_fraction": 0.6776669025421143, "avg_line_length": 34.216217041015625, "blob_id": "437a86329fdaa835fe7f706973d54cf2576c7e70", "content_id": "f0578c5579f3db651fca70d0695aec3fd57d4e54", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1303, "license_type": "permissive", "max_line_length": 71, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_migrate_vmk.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Migrate a VMK interface from VSS to VDS\n class Vmware_migrate_vmk < Base\n # @return [String] ESXi hostname to be managed\n attribute :esxi_hostname\n validates :esxi_hostname, presence: true, type: String\n\n # @return [String] VMK interface name\n attribute :device\n validates :device, presence: true, type: String\n\n # @return [String] Switch VMK interface is currently on\n attribute :current_switch_name\n validates :current_switch_name, presence: true, type: String\n\n # @return [String] Portgroup name VMK interface is currently on\n attribute :current_portgroup_name\n validates :current_portgroup_name, presence: true, type: String\n\n # @return [String] Switch name to migrate VMK interface to\n attribute :migrate_switch_name\n validates :migrate_switch_name, presence: true, type: String\n\n # @return [String] Portgroup name to migrate VMK interface to\n attribute :migrate_portgroup_name\n validates :migrate_portgroup_name, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6285508871078491, "alphanum_fraction": 0.6285508871078491, "avg_line_length": 47.78947448730469, "blob_id": "8ecea15feaf366270e242bed5fec554f8dd0814e", "content_id": "9afeb8973d6e789be6e324f12043fcca2e654315", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2781, "license_type": "permissive", "max_line_length": 140, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/system/mksysb.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module manages a basic AIX mksysb (image) of rootvg.\n class Mksysb < Base\n # @return [:yes, :no, nil] Backup encrypted files.\n attribute :backup_crypt_files\n validates :backup_crypt_files, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Back up DMAPI filesystem files.\n attribute :backup_dmapi_fs\n validates :backup_dmapi_fs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Creates a new MAP files.\n attribute :create_map_files\n validates :create_map_files, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Excludes files using C(/etc/rootvg.exclude).\n attribute :exclude_files\n validates :exclude_files, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Excludes WPAR files.\n attribute :exclude_wpar_files\n validates :exclude_wpar_files, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Backup extended attributes.\n attribute :extended_attrs\n validates :extended_attrs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String] Backup name\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:yes, :no, nil] Creates a new file data.\n attribute :new_image_data\n validates :new_image_data, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Exclude files from packing option listed in C(/etc/exclude_packing.rootvg).\n attribute :software_packing\n validates :software_packing, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String] Storage path where the mksysb will stored.\n attribute :storage_path\n validates :storage_path, presence: true, type: String\n\n # @return [:yes, :no, nil] Creates backup using snapshots.\n attribute :use_snapshot\n validates :use_snapshot, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6918604373931885, "alphanum_fraction": 0.6918604373931885, "avg_line_length": 31.761905670166016, "blob_id": "e290865bb4f43d2d2249fcb3cd62866c092d010f", "content_id": "4db66582c93ebad419571bd79c374de8db8da179", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 688, "license_type": "permissive", "max_line_length": 85, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_vm_vss_dvs_migrate.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Migrates a virtual machine from a standard vswitch to distributed\n class Vmware_vm_vss_dvs_migrate < Base\n # @return [String] Name of the virtual machine to migrate to a dvSwitch\n attribute :vm_name\n validates :vm_name, presence: true, type: String\n\n # @return [String] Name of the portgroup to migrate to the virtual machine to\n attribute :dvportgroup_name\n validates :dvportgroup_name, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6886110901832581, "alphanum_fraction": 0.6886110901832581, "avg_line_length": 60.01694869995117, "blob_id": "5dc5d9aff56f27c1c6da4cc46be790895d008f58", "content_id": "b4e5649a84790dde06fbc81b8bf24cbb3e0a6cf9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3600, "license_type": "permissive", "max_line_length": 316, "num_lines": 59, "path": "/lib/ansible/ruby/modules/generated/packaging/language/bundler.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage installation and Gem version dependencies for Ruby using the Bundler gem\n class Bundler < Base\n # @return [String, nil] The path to the bundler executable\n attribute :executable\n validates :executable, type: String\n\n # @return [:present, :latest, nil] The desired state of the Gem bundle. C(latest) updates gems to the most recent, acceptable version\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :latest], :message=>\"%{value} needs to be :present, :latest\"}, allow_nil: true\n\n # @return [String, nil] The directory to execute the bundler commands from. This directoy needs to contain a valid Gemfile or .bundle/ directory\n attribute :chdir\n validates :chdir, type: String\n\n # @return [String, nil] A list of Gemfile groups to exclude during operations. This only applies when state is C(present). Bundler considers this a 'remembered' property for the Gemfile and will automatically exclude groups in future operations even if C(exclude_groups) is not set\n attribute :exclude_groups\n validates :exclude_groups, type: String\n\n # @return [:yes, :no, nil] Only applies if state is C(present). If set removes any gems on the target host that are not in the gemfile\n attribute :clean\n validates :clean, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Only applies if state is C(present). The path to the gemfile to use to install gems.\n attribute :gemfile\n validates :gemfile, type: String\n\n # @return [:yes, :no, nil] If set only installs gems from the cache on the target host\n attribute :local\n validates :local, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Only applies if state is C(present). If set it will install gems in ./vendor/bundle instead of the default location. Requires a Gemfile.lock file to have been created prior\n attribute :deployment_mode\n validates :deployment_mode, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Only applies if state is C(present). Installs gems in the local user's cache or for all users\n attribute :user_install\n validates :user_install, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Only applies if state is C(present). Specifies the directory to install the gems into. If C(chdir) is set then this path is relative to C(chdir)\n attribute :gem_path\n validates :gem_path, type: String\n\n # @return [Object, nil] Only applies if state is C(present). Specifies the directory to install any gem bins files to. When executed the bin files will run within the context of the Gemfile and fail if any required gem dependencies are not installed. If C(chdir) is set then this path is relative to C(chdir)\n attribute :binstub_directory\n\n # @return [Object, nil] A space separated string of additional commands that can be applied to the Bundler command. Refer to the Bundler documentation for more information\n attribute :extra_args\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6910229921340942, "alphanum_fraction": 0.6910229921340942, "avg_line_length": 27.176469802856445, "blob_id": "fe7fe05cce7dc973458b815cfb0de4dd81826d66", "content_id": "f010b711ed9ff300ab900ee0e61c125e8957330a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 479, "license_type": "permissive", "max_line_length": 68, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_overlay_global.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configures anycast gateway MAC of the switch.\n class Nxos_overlay_global < Base\n # @return [String] Anycast gateway mac of the switch.\n attribute :anycast_gateway_mac\n validates :anycast_gateway_mac, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7197696566581726, "alphanum_fraction": 0.7216890454292297, "avg_line_length": 29.647058486938477, "blob_id": "405b5fffa91d4e27666ac97c9e966f5c471fe650", "content_id": "1ace18c04c1e718fabdc5a6ea1b903c3cab1ed1b", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 521, "license_type": "permissive", "max_line_length": 119, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_category_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to gather facts about VMware tag categories.\n # Tag feature is introduced in vSphere 6 version, so this module is not supported in earlier versions of vSphere.\n # All variables and VMware object names are case sensitive.\n class Vmware_category_facts < Base\n\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7134367823600769, "alphanum_fraction": 0.7137669324874878, "avg_line_length": 66.31111145019531, "blob_id": "2ebc87d02b2b44f978d02a471b415ae134a66de4", "content_id": "91f062a08bb711ba2a15c9e9abc41fc3c3d7f407", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3029, "license_type": "permissive", "max_line_length": 683, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_portgroup.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create a VMware portgroup on given host/s or hosts of given cluster\n class Vmware_portgroup < Base\n # @return [String] vSwitch to modify.\n attribute :switch_name\n validates :switch_name, presence: true, type: String\n\n # @return [String] Portgroup name to add.\n attribute :portgroup_name\n validates :portgroup_name, presence: true, type: String\n\n # @return [String] VLAN ID to assign to portgroup.\n attribute :vlan_id\n validates :vlan_id, presence: true, type: String\n\n # @return [Array<String>, String, nil] Network policy specifies layer 2 security settings for a portgroup such as promiscuous mode, where guest adapter listens to all the packets, MAC address changes and forged transmits.,Dict which configures the different security values for portgroup.,Valid attributes are:,- C(promiscuous_mode) (bool): indicates whether promiscuous mode is allowed. (default: false),- C(forged_transmits) (bool): indicates whether forged transmits are allowed. (default: false),- C(mac_changes) (bool): indicates whether mac changes are allowed. (default: false)\n attribute :network_policy\n validates :network_policy, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] Dictionary which configures the different teaming values for portgroup.,Valid attributes are:,- C(load_balance_policy) (string): Network adapter teaming policy. (default: loadbalance_srcid), - choices: [ loadbalance_ip, loadbalance_srcmac, loadbalance_srcid, failover_explicit ],- C(inbound_policy) (bool): Indicate whether or not the teaming policy is applied to inbound frames as well. (default: False),- C(notify_switches) (bool): Indicate whether or not to notify the physical switch if a link fails. (default: True),- C(rolling_order) (bool): Indicate whether or not to use a rolling policy when restoring links. (default: False)\n attribute :teaming_policy\n validates :teaming_policy, type: TypeGeneric.new(String)\n\n # @return [String, nil] Name of cluster name for host membership.,Portgroup will be created on all hosts of the given cluster.,This option is required if C(hosts) is not specified.\n attribute :cluster_name\n validates :cluster_name, type: String\n\n # @return [Array<String>, String, nil] List of name of host or hosts on which portgroup needs to be added.,This option is required if C(cluster_name) is not specified.\n attribute :hosts\n validates :hosts, type: TypeGeneric.new(String)\n\n # @return [:present, :absent, nil] Determines if the portgroup should be present or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6613047122955322, "alphanum_fraction": 0.6613047122955322, "avg_line_length": 42.882354736328125, "blob_id": "72ccf78440df6ddc1b6d46cbb86658712d131ff6", "content_id": "de67a2707ca7de7caa838adb9031dfd7547b63d2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2238, "license_type": "permissive", "max_line_length": 166, "num_lines": 51, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_tenant.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure Tenant object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_tenant < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Hash, nil] Tenantconfiguration settings for tenant.\n attribute :config_settings\n validates :config_settings, type: Hash\n\n # @return [Object, nil] Creator of this tenant.\n attribute :created_by\n\n # @return [Array<String>, String, nil] User defined description for the object.\n attribute :description\n validates :description, type: TypeGeneric.new(String)\n\n # @return [Symbol, nil] Boolean flag to set local.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :local\n validates :local, type: Symbol\n\n # @return [String] Name of the object.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Unique object identifier of the object.\n attribute :uuid\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6722221970558167, "alphanum_fraction": 0.6722221970558167, "avg_line_length": 30.764705657958984, "blob_id": "c7933c5399ab6a8e7714167dfb7fcbf20320e773", "content_id": "112e70e3211411a17fcd31ddfabd727e302e11e0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 540, "license_type": "permissive", "max_line_length": 133, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_reboot.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Reboot a network device.\n class Nxos_reboot < Base\n # @return [Boolean, nil] Safeguard boolean. Set to true if you're sure you want to reboot.\n attribute :confirm\n validates :confirm, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7477751970291138, "alphanum_fraction": 0.7515222430229187, "avg_line_length": 96.04545593261719, "blob_id": "9b875d9576004ddf00047b737193e6e2360f6f4e", "content_id": "19b9ae21da03923edda775a8aa6a00571e92edaa", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4270, "license_type": "permissive", "max_line_length": 645, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_compute_firewall.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Each network has its own firewall controlling access to and from the instances.\n # All traffic to instances, even from other instances, is blocked by the firewall unless firewall rules are created to allow it.\n # The default network has automatically created firewall rules that are shown in default firewall rules. No manually created network has automatically created firewall rules except for a default \"allow\" rule for outgoing traffic and a default \"deny\" for incoming traffic. For all networks except the default network, you must create any firewall rules you need.\n class Gcp_compute_firewall < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash, nil] The list of ALLOW rules specified by this firewall. Each rule specifies a protocol and port-range tuple that describes a permitted connection.\n attribute :allowed\n validates :allowed, type: TypeGeneric.new(Hash)\n\n # @return [Object, nil] An optional description of this resource. Provide this property when you create the resource.\n attribute :description\n\n # @return [String, nil] Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash.\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] URL of the network resource for this firewall rule. If not specified when creating a firewall rule, the default network is used: global/networks/default If you choose to specify this property, you can specify the network as a full or partial URL. For example, the following are all valid URLs: U(https://www.googleapis.com/compute/v1/projects/myproject/global/) networks/my-network projects/myproject/global/networks/my-network global/networks/default .\n attribute :network\n\n # @return [Object, nil] If source ranges are specified, the firewall will apply only to traffic that has source IP address in these ranges. These ranges must be expressed in CIDR format. One or both of sourceRanges and sourceTags may be set. If both properties are set, the firewall will apply to traffic that has source IP address within sourceRanges OR the source IP that belongs to a tag listed in the sourceTags property. The connection does not need to match both properties for the firewall to apply. Only IPv4 is supported.\n attribute :source_ranges\n\n # @return [Array<String>, String, nil] If source tags are specified, the firewall will apply only to traffic with source IP that belongs to a tag listed in source tags. Source tags cannot be used to control traffic to an instance's external IP address. Because tags are associated with an instance, not an IP address. One or both of sourceRanges and sourceTags may be set. If both properties are set, the firewall will apply to traffic that has source IP address within sourceRanges OR the source IP that belongs to a tag listed in the sourceTags property. The connection does not need to match both properties for the firewall to apply.\n attribute :source_tags\n validates :source_tags, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] A list of instance tags indicating sets of instances located in the network that may make network connections as specified in allowed[].,If no targetTags are specified, the firewall rule applies to all instances on the specified network.\n attribute :target_tags\n validates :target_tags, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5601317882537842, "alphanum_fraction": 0.5700165033340454, "avg_line_length": 17.96875, "blob_id": "2cd080d51e74425c3fac21ec5d877848ff85ee14", "content_id": "d138969122e9101d08524edf7046aca8136d5bc4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 607, "license_type": "permissive", "max_line_length": 51, "num_lines": 32, "path": "/lib/ansible/ruby/modules/custom/packaging/language/pear_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# see LICENSE.txt in project root\nrequire 'spec_helper'\n\ndescribe Ansible::Ruby::Modules::Pear do\n subject(:mod) do\n Ansible::Ruby::Modules::Pear.new name: packages\n end\n\n describe '#to_h' do\n subject { mod.to_h }\n\n context 'array' do\n let(:packages) { %w[package1 package2] }\n it do\n is_expected.to eq pear: {\n name: 'package1,package2'\n }\n end\n end\n\n context 'single' do\n let(:packages) { 'package1' }\n it do\n is_expected.to eq pear: {\n name: 'package1'\n }\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6502923965454102, "alphanum_fraction": 0.6502923965454102, "avg_line_length": 31.884614944458008, "blob_id": "72b2bfce0551f0ba99eb7623da7be9df024ab725", "content_id": "807eaf20567b9a1db3623e7d4eaf33feab7f8fd8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 855, "license_type": "permissive", "max_line_length": 143, "num_lines": 26, "path": "/lib/ansible/ruby/modules/generated/windows/win_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add and remove local groups.\n # For non-Windows targets, please use the M(group) module instead.\n class Win_group < Base\n # @return [String] Name of the group.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Description of the group.\n attribute :description\n validates :description, type: String\n\n # @return [:absent, :present, nil] Create or remove the group.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6905630826950073, "alphanum_fraction": 0.6908237934112549, "avg_line_length": 68.74545288085938, "blob_id": "65f1181a4058a352d141090e2776e0eb14fedcf4", "content_id": "d38c78814422bbb282bfaa258bd549ad18f77481", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3836, "license_type": "permissive", "max_line_length": 555, "num_lines": 55, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/efs.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Module allows create, search and destroy Amazon EFS file systems\n class Efs < Base\n # @return [:yes, :no, nil] A boolean value that, if true, creates an encrypted file system. This can not be modfied after the file system is created.\n attribute :encrypt\n validates :encrypt, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] The id of the AWS KMS CMK that will be used to protect the encrypted file system. This parameter is only required if you want to use a non-default CMK. If this parameter is not specified, the default CMK for Amazon EFS is used. The key id can be Key ID, Key ID ARN, Key Alias or Key Alias ARN.\n attribute :kms_key_id\n\n # @return [:yes, :no, nil] If yes, existing tags will be purged from the resource to match exactly what is defined by I(tags) parameter. If the I(tags) parameter is not set then tags will not be modified.\n attribute :purge_tags\n validates :purge_tags, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Allows to create, search and destroy Amazon EFS file system\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Creation Token of Amazon EFS file system. Required for create and update. Either name or ID required for delete.\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] ID of Amazon EFS. Either name or ID required for delete.\n attribute :id\n\n # @return [:general_purpose, :max_io, nil] File system's performance mode to use. Only takes effect during creation.\n attribute :performance_mode\n validates :performance_mode, expression_inclusion: {:in=>[:general_purpose, :max_io], :message=>\"%{value} needs to be :general_purpose, :max_io\"}, allow_nil: true\n\n # @return [Hash, nil] List of tags of Amazon EFS. Should be defined as dictionary In case of 'present' state with list of tags and existing EFS (matched by 'name'), tags of EFS will be replaced with provided data.\n attribute :tags\n validates :tags, type: Hash\n\n # @return [Array<Hash>, Hash, nil] List of mounted targets. It should be a list of dictionaries, every dictionary should include next attributes: - subnet_id - Mandatory. The ID of the subnet to add the mount target in. - ip_address - Optional. A valid IPv4 address within the address range of the specified subnet. - security_groups - Optional. List of security group IDs, of the form 'sg-xxxxxxxx'. These must be for the same VPC as subnet specified This data may be modified for existing EFS using state 'present' and new list of mount targets.\n attribute :targets\n validates :targets, type: TypeGeneric.new(Hash)\n\n # @return [:yes, :no, nil] In case of 'present' state should wait for EFS 'available' life cycle state (of course, if current state not 'deleting' or 'deleted') In case of 'absent' state should wait for EFS 'deleted' life cycle state\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] How long the module should wait (in seconds) for desired state before returning. Zero means wait as long as necessary.\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6652014851570129, "alphanum_fraction": 0.6652014851570129, "avg_line_length": 33.125, "blob_id": "db5e19fd087ff788d8101f42b5ed2521f73ffd20", "content_id": "a5fac9ef3adaaec2c3f92de1335fa4a28176575f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1365, "license_type": "permissive", "max_line_length": 104, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_configuration.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages global, zone, account, storage and cluster configurations.\n class Cs_configuration < Base\n # @return [String] Name of the configuration.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [FalseClass, TrueClass, Float] Value of the configuration.\n attribute :value\n validates :value, presence: true, type: MultipleTypes.new(FalseClass, TrueClass, Float)\n\n # @return [String, nil] Ensure the value for corresponding account.\n attribute :account\n validates :account, type: String\n\n # @return [String, nil] Domain the account is related to.,Only considered if C(account) is used.\n attribute :domain\n validates :domain, type: String\n\n # @return [String, nil] Ensure the value for corresponding zone.\n attribute :zone\n validates :zone, type: String\n\n # @return [String, nil] Ensure the value for corresponding storage pool.\n attribute :storage\n validates :storage, type: String\n\n # @return [Object, nil] Ensure the value for corresponding cluster.\n attribute :cluster\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6659844517707825, "alphanum_fraction": 0.6676217913627625, "avg_line_length": 42.625, "blob_id": "96e9043acefc89da0e54d83e66327ff3bc84985e", "content_id": "64434229ac5b6429cc5f37ee407a99159f822391", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2446, "license_type": "permissive", "max_line_length": 149, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/monitoring/stackdriver.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Send code deploy and annotation events to Stackdriver\n class Stackdriver < Base\n # @return [String] API key.\n attribute :key\n validates :key, presence: true, type: String\n\n # @return [:annotation, :deploy, nil] The type of event to send, either annotation or deploy\n attribute :event\n validates :event, expression_inclusion: {:in=>[:annotation, :deploy], :message=>\"%{value} needs to be :annotation, :deploy\"}, allow_nil: true\n\n # @return [String, nil] The revision of the code that was deployed. Required for deploy events\n attribute :revision_id\n validates :revision_id, type: String\n\n # @return [String, nil] The person or robot responsible for deploying the code\n attribute :deployed_by\n validates :deployed_by, type: String\n\n # @return [String, nil] The environment code was deployed to. (ie: development, staging, production)\n attribute :deployed_to\n validates :deployed_to, type: String\n\n # @return [String, nil] The repository (or project) deployed\n attribute :repository\n validates :repository, type: String\n\n # @return [String, nil] The contents of the annotation message, in plain text.  Limited to 256 characters. Required for annotation.\n attribute :msg\n validates :msg, type: String\n\n # @return [String, nil] The person or robot who the annotation should be attributed to.\n attribute :annotated_by\n validates :annotated_by, type: String\n\n # @return [:INFO, :WARN, :ERROR, nil] one of INFO/WARN/ERROR, defaults to INFO if not supplied.  May affect display.\n attribute :level\n validates :level, expression_inclusion: {:in=>[:INFO, :WARN, :ERROR], :message=>\"%{value} needs to be :INFO, :WARN, :ERROR\"}, allow_nil: true\n\n # @return [String, nil] id of an EC2 instance that this event should be attached to, which will limit the contexts where this event is shown\n attribute :instance_id\n validates :instance_id, type: String\n\n # @return [Object, nil] Unix timestamp of where the event should appear in the timeline, defaults to now. Be careful with this.\n attribute :event_epoch\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6605719923973083, "alphanum_fraction": 0.6619784235954285, "avg_line_length": 39.24528121948242, "blob_id": "449b3adf2ab5d893cd36504629cb56a02e5a5f60", "content_id": "1b9f272a608b5a5ce8487b2337e06608103fa3ac", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2133, "license_type": "permissive", "max_line_length": 164, "num_lines": 53, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_snapshot.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # creates an EC2 snapshot from an existing EBS volume\n class Ec2_snapshot < Base\n # @return [String, nil] volume from which to take the snapshot\n attribute :volume_id\n validates :volume_id, type: String\n\n # @return [String, nil] description to be applied to the snapshot\n attribute :description\n validates :description, type: String\n\n # @return [String, nil] instance that has the required volume to snapshot mounted\n attribute :instance_id\n validates :instance_id, type: String\n\n # @return [String, nil] device name of a mounted volume to be snapshotted\n attribute :device_name\n validates :device_name, type: String\n\n # @return [Hash, nil] a hash/dictionary of tags to add to the snapshot\n attribute :snapshot_tags\n validates :snapshot_tags, type: Hash\n\n # @return [Boolean, nil] wait for the snapshot to be ready\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Integer, nil] how long before wait gives up, in seconds,specify 0 to wait forever\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [:absent, :present, nil] whether to add or create a snapshot\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] snapshot id to remove\n attribute :snapshot_id\n validates :snapshot_id, type: String\n\n # @return [Integer, nil] If the volume's most recent snapshot has started less than `last_snapshot_min_age' minutes ago, a new snapshot will not be created.\n attribute :last_snapshot_min_age\n validates :last_snapshot_min_age, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6559031009674072, "alphanum_fraction": 0.6559031009674072, "avg_line_length": 33.17241287231445, "blob_id": "b0847f47815782c4281a41cd6c922b7edfeccbee", "content_id": "e8683711ae6fe9225cb085da294bcd1b8a0094d2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 991, "license_type": "permissive", "max_line_length": 174, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ecs_cluster.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates or terminates ecs clusters.\n class Ecs_cluster < Base\n # @return [:present, :absent, :has_instances] The desired state of the cluster\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent, :has_instances], :message=>\"%{value} needs to be :present, :absent, :has_instances\"}\n\n # @return [String] The cluster name\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Integer, nil] Number of seconds to wait\n attribute :delay\n validates :delay, type: Integer\n\n # @return [Integer, nil] The number of times to wait for the cluster to have an instance\n attribute :repeat\n validates :repeat, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6707875728607178, "alphanum_fraction": 0.6749083995819092, "avg_line_length": 52.26829147338867, "blob_id": "ec9a9b610e0743ad1292e282ff18b956d74e2b21", "content_id": "efb3849dc3bea945650501e1b4d4c4d3b9a674d6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2184, "license_type": "permissive", "max_line_length": 219, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/source_control/github_hooks.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Adds service hooks and removes service hooks that have an error status.\n class Github_hooks < Base\n # @return [String] Github username.\n attribute :user\n validates :user, presence: true, type: String\n\n # @return [String] The oauth key provided by GitHub. It can be found/generated on GitHub under \"Edit Your Profile\" >> \"Developer settings\" >> \"Personal Access Tokens\"\n attribute :oauthkey\n validates :oauthkey, presence: true, type: String\n\n # @return [String] This is the API url for the repository you want to manage hooks for. It should be in the form of: https://api.github.com/repos/user:/repo:. Note this is different than the normal repo url.\\r\\n\n attribute :repo\n validates :repo, presence: true, type: String\n\n # @return [String, nil] When creating a new hook, this is the url that you want GitHub to post to. It is only required when creating a new hook.\n attribute :hookurl\n validates :hookurl, type: String\n\n # @return [:create, :cleanall, :list, :clean504] This tells the githooks module what you want it to do.\n attribute :action\n validates :action, presence: true, expression_inclusion: {:in=>[:create, :cleanall, :list, :clean504], :message=>\"%{value} needs to be :create, :cleanall, :list, :clean504\"}\n\n # @return [:yes, :no, nil] If C(no), SSL certificates for the target repo will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:json, :form, nil] Content type to use for requests made to the webhook\n attribute :content_type\n validates :content_type, expression_inclusion: {:in=>[:json, :form], :message=>\"%{value} needs to be :json, :form\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6547064185142517, "alphanum_fraction": 0.6547064185142517, "avg_line_length": 46.68888854980469, "blob_id": "58159caf928b96bc96e9cbbe3dfa79179402a72f", "content_id": "6a96e33025780d8f8fa8bf331dc1783ee690616f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2146, "license_type": "permissive", "max_line_length": 204, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_dnsrecordset.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates, deletes, and updates DNS records sets and records within an existing Azure DNS Zone.\n class Azure_rm_dnsrecordset < Base\n # @return [String] name of resource group\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] name of the existing DNS zone in which to manage the record set\n attribute :zone_name\n validates :zone_name, presence: true, type: String\n\n # @return [String] relative name of the record set\n attribute :relative_name\n validates :relative_name, presence: true, type: String\n\n # @return [:A, :AAAA, :CNAME, :MX, :NS, :SRV, :TXT, :PTR] the type of record set to create or delete\n attribute :record_type\n validates :record_type, presence: true, expression_inclusion: {:in=>[:A, :AAAA, :CNAME, :MX, :NS, :SRV, :TXT, :PTR], :message=>\"%{value} needs to be :A, :AAAA, :CNAME, :MX, :NS, :SRV, :TXT, :PTR\"}\n\n # @return [:append, :purge, nil] whether existing record values not sent to the module should be purged\n attribute :record_mode\n validates :record_mode, expression_inclusion: {:in=>[:append, :purge], :message=>\"%{value} needs to be :append, :purge\"}, allow_nil: true\n\n # @return [:absent, :present, nil] Assert the state of the record set. Use C(present) to create or update and C(absent) to delete.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [Integer, nil] time to live of the record set in seconds\n attribute :time_to_live\n validates :time_to_live, type: Integer\n\n # @return [String, Array<Hash>, Hash, nil] list of records to be created depending on the type of record (set)\n attribute :records\n validates :records, type: TypeGeneric.new(Hash)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6542624235153198, "alphanum_fraction": 0.6572275757789612, "avg_line_length": 54.28688430786133, "blob_id": "b0c6236f4938c9e0014533e41f7b91a5bbcbc559", "content_id": "2e8451813108e23c72f1ad681afdffb25b177990", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6745, "license_type": "permissive", "max_line_length": 406, "num_lines": 122, "path": "/lib/ansible/ruby/modules/generated/net_tools/dnsmadeeasy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages DNS records via the v2 REST API of the DNS Made Easy service. It handles records only; there is no manipulation of domains or monitor/account support yet. See: U(https://www.dnsmadeeasy.com/integration/restapi/)\n\n class Dnsmadeeasy < Base\n # @return [String] Account API Key.\n attribute :account_key\n validates :account_key, presence: true, type: String\n\n # @return [String] Account Secret Key.\n attribute :account_secret\n validates :account_secret, presence: true, type: String\n\n # @return [String] Domain to work with. Can be the domain name (e.g. \"mydomain.com\") or the numeric ID of the domain in DNS Made Easy (e.g. \"839989\") for faster resolution\n attribute :domain\n validates :domain, presence: true, type: String\n\n # @return [:yes, :no, nil] Decides if the sandbox API should be used. Otherwise (default) the production API of DNS Made Easy is used.\n attribute :sandbox\n validates :sandbox, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Record name to get/create/delete/update. If record_name is not specified; all records for the domain will be returned in \"result\" regardless of the state argument.\n attribute :record_name\n validates :record_name, type: String\n\n # @return [:A, :AAAA, :CNAME, :ANAME, :HTTPRED, :MX, :NS, :PTR, :SRV, :TXT, nil] Record type.\n attribute :record_type\n validates :record_type, expression_inclusion: {:in=>[:A, :AAAA, :CNAME, :ANAME, :HTTPRED, :MX, :NS, :PTR, :SRV, :TXT], :message=>\"%{value} needs to be :A, :AAAA, :CNAME, :ANAME, :HTTPRED, :MX, :NS, :PTR, :SRV, :TXT\"}, allow_nil: true\n\n # @return [String, nil] Record value. HTTPRED: <redirection URL>, MX: <priority> <target name>, NS: <name server>, PTR: <target name>, SRV: <priority> <weight> <port> <target name>, TXT: <text value>\"\\r\\n,If record_value is not specified; no changes will be made and the record will be returned in 'result' (in other words, this module can be used to fetch a record's current id, type, and ttl)\\r\\n\n attribute :record_value\n validates :record_value, type: String\n\n # @return [Integer, nil] record's \"Time to live\". Number of seconds the record remains cached in DNS servers.\n attribute :record_ttl\n validates :record_ttl, type: Integer\n\n # @return [:present, :absent] whether the record should exist or not\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(yes), add or change the monitor. This is applicable only for A records.\n attribute :monitor\n validates :monitor, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String] Description used by the monitor.\n attribute :systemDescription\n validates :systemDescription, presence: true, type: String\n\n # @return [Integer] Number of emails sent to the contact list by the monitor.\n attribute :maxEmails\n validates :maxEmails, presence: true, type: Integer\n\n # @return [:TCP, :UDP, :HTTP, :DNS, :SMTP, :HTTPS] Protocol used by the monitor.\n attribute :protocol\n validates :protocol, presence: true, expression_inclusion: {:in=>[:TCP, :UDP, :HTTP, :DNS, :SMTP, :HTTPS], :message=>\"%{value} needs to be :TCP, :UDP, :HTTP, :DNS, :SMTP, :HTTPS\"}\n\n # @return [Integer] Port used by the monitor.\n attribute :port\n validates :port, presence: true, type: Integer\n\n # @return [:Low, :Medium, :High] Number of checks the monitor performs before a failover occurs where Low = 8, Medium = 5,and High = 3.\n attribute :sensitivity\n validates :sensitivity, presence: true, expression_inclusion: {:in=>[:Low, :Medium, :High], :message=>\"%{value} needs to be :Low, :Medium, :High\"}\n\n # @return [String] Name or id of the contact list that the monitor will notify.,The default C('') means the Account Owner.\n attribute :contactList\n validates :contactList, presence: true, type: String\n\n # @return [String, nil] The fully qualified domain name used by the monitor.\n attribute :httpFqdn\n validates :httpFqdn, type: String\n\n # @return [String, nil] The file at the Fqdn that the monitor queries for HTTP or HTTPS.\n attribute :httpFile\n validates :httpFile, type: String\n\n # @return [String, nil] The string in the httpFile that the monitor queries for HTTP or HTTPS.\n attribute :httpQueryString\n validates :httpQueryString, type: String\n\n # @return [:yes, :no, nil] If C(yes), add or change the failover. This is applicable only for A records.\n attribute :failover\n validates :failover, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If true, fallback to the primary IP address is manual after a failover.,If false, fallback to the primary IP address is automatic after a failover.\n attribute :autoFailover\n validates :autoFailover, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Primary IP address for the failover.,Required if adding or changing the monitor or failover.\n attribute :ip1\n validates :ip1, type: String\n\n # @return [String, nil] Secondary IP address for the failover.,Required if adding or changing the failover.\n attribute :ip2\n validates :ip2, type: String\n\n # @return [String, nil] Tertiary IP address for the failover.\n attribute :ip3\n validates :ip3, type: String\n\n # @return [String, nil] Quaternary IP address for the failover.\n attribute :ip4\n validates :ip4, type: String\n\n # @return [String, nil] Quinary IP address for the failover.\n attribute :ip5\n validates :ip5, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5304911136627197, "alphanum_fraction": 0.536787211894989, "avg_line_length": 24.73611068725586, "blob_id": "264b897f2809ea37d3bc4061887e7255f42ee263", "content_id": "0d5d5dfb9a30411487ce30c7540dfeed2c8925ef", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5559, "license_type": "permissive", "max_line_length": 180, "num_lines": 216, "path": "/lib/ansible/ruby/dsl_builders/block_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# see LICENSE.txt in project root\nrequire 'spec_helper'\n\ndescribe Ansible::Ruby::DslBuilders::Block do\n let(:context) { Ansible::Ruby::Models::Task }\n let(:builder) { Ansible::Ruby::DslBuilders::Block.new }\n\n def evaluate\n builder.instance_eval ruby\n builder._result\n end\n\n subject(:block) { evaluate }\n\n before do\n Ansible::Ruby::DslBuilders::Task.counter_variable = 0\n klass = Class.new(Ansible::Ruby::Modules::Base) do\n attribute :src\n validates :src, presence: true\n end\n stub_const 'Ansible::Ruby::Modules::Copy', klass\n end\n\n context 'single task' do\n let(:ruby) do\n <<-RUBY\n task 'Copy something' do\n copy do\n src '/file1.conf'\n end\n end\n\n ansible_when \"ansible_distribution == 'CentOS'\"\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Block }\n it { is_expected.to have_attributes when: \"ansible_distribution == 'CentOS'\" }\n\n describe 'tasks' do\n subject(:tasks) { block.tasks }\n\n it { is_expected.to have_attributes length: 1 }\n\n describe 'task' do\n subject { tasks[0] }\n\n it { is_expected.to have_attributes name: 'Copy something', module: be_a(Ansible::Ruby::Modules::Copy) }\n end\n end\n\n describe 'hash keys' do\n subject { block.to_h.stringify_keys.keys }\n\n it { is_expected.to eq %w[block when] }\n end\n end\n\n context 'vars' do\n let(:ruby) do\n <<-RUBY\n task 'Copy something' do\n copy do\n src '/file1.conf'\n end\n end\n vars foo: 123\n ansible_when \"ansible_distribution == 'CentOS'\"\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Block }\n it do\n is_expected.to have_attributes when: \"ansible_distribution == 'CentOS'\",\n vars: { foo: 123 }\n end\n end\n\n context 'other attributes' do\n let(:ruby) do\n <<-RUBY\n task 'Copy something' do\n copy do\n src '/file1.conf'\n end\n end\n\n become true\n become_user 'root'\n ignore_errors true\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Block }\n it do\n # This not an actual problem. it's an rspec assertion\n # rubocop:disable Style/MixinUsage\n is_expected.to have_attributes tasks: include(Ansible::Ruby::Models::Task),\n become: true,\n become_user: 'root',\n ignore_errors: true\n # rubocop:enable Style/MixinUsage\n end\n end\n\n context 'unknown keyword' do\n let(:ruby) { 'foobar()' }\n\n\n it 'should raise an error' do\n expect {evaluate}.to raise_error \"Invalid method/local variable `foobar'. Only valid options are [:ansible_when, :become, :become_user, :ignore_errors, :jinja, :task, :vars]\"\n end\n end\n\n context 'register' do\n context 'no usage outside of task' do\n let(:ruby) do\n <<-RUBY\n task 'Copy something' do\n result = copy do\n src '/file1.conf'\n end\n\n changed_when \"'No upgrade available' not in \\#{result.stdout}\"\n end\n task 'Copy something else' do\n result = copy do\n src '/file1.conf'\n end\n\n changed_when \"'yes' not in \\#{result.stdout}\"\n end\n RUBY\n end\n\n describe 'task 1' do\n subject { block.tasks[0] }\n\n it do\n is_expected.to have_attributes register: 'result_1',\n changed_when: \"'No upgrade available' not in result_1.stdout\"\n end\n end\n\n describe 'task 2' do\n subject { block.tasks[1] }\n\n it do\n is_expected.to have_attributes register: 'result_2',\n changed_when: \"'yes' not in result_2.stdout\"\n end\n end\n end\n\n context 'usage between tasks' do\n let(:ruby) do\n <<-RUBY\n stuff = task 'Copy something' do\n result = copy do\n src '/file1.conf'\n end\n\n changed_when \"'No upgrade available' not in \\#{result.stdout}\"\n end\n\n task 'Copy something else' do\n copy do\n src '/file1.conf'\n end\n\n ansible_when \"'yes' not in \\#{stuff.stdout}\"\n end\n RUBY\n end\n\n it 'uses result from first task' do\n items = block.tasks\n expect(items[0]).to have_attributes register: 'result_1',\n changed_when: \"'No upgrade available' not in result_1.stdout\"\n second = items[1]\n expect(second).to have_attributes when: \"'yes' not in result_1.stdout\",\n register: nil\n end\n end\n\n context 'usage between task without use in first task' do\n let(:ruby) do\n <<-RUBY\n stuff = task 'Copy something' do\n copy do\n src '/file1.conf'\n end\n end\n\n task 'Copy something else' do\n copy do\n src '/file1.conf'\n end\n\n ansible_when \"'yes' not in \\#{stuff.stdout}\"\n end\n RUBY\n end\n\n it 'uses result from first task' do\n items = block.tasks\n expect(items[0]).to have_attributes register: 'result_1'\n second = items[1]\n expect(second).to have_attributes when: \"'yes' not in result_1.stdout\",\n register: nil\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7104300260543823, "alphanum_fraction": 0.7106587290763855, "avg_line_length": 74.37931060791016, "blob_id": "42c32e2d72b6fdc69e23921ce6cfb6c7174e417d", "content_id": "2ba79b2af6873d7eb47949b32767c181ff1d538e", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4372, "license_type": "permissive", "max_line_length": 676, "num_lines": 58, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_profile_http.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage HTTP profiles on a BIG-IP.\n class Bigip_profile_http < Base\n # @return [String] Specifies the name of the profile.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Specifies the profile from which this profile inherits settings.,When creating a new profile, if this parameter is not specified, the default is the system-supplied C(http) profile.\n attribute :parent\n validates :parent, type: String\n\n # @return [Object, nil] Description of the profile.\n attribute :description\n\n # @return [:reverse, :transparent, :explicit, nil] Specifies the proxy mode for the profile.,When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.\n attribute :proxy_type\n validates :proxy_type, expression_inclusion: {:in=>[:reverse, :transparent, :explicit], :message=>\"%{value} needs to be :reverse, :transparent, :explicit\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the name of a configured DNS resolver, this option is mandatory when C(proxy_type) is set to C(explicit).,Format of the name can be either be prepended by partition (C(/Common/foo)), or specified just as an object name (C(foo)).,To remove the entry a value of C(none) or C('') can be set, however the profile C(proxy_type) must not be set as C(explicit).\n attribute :dns_resolver\n\n # @return [Symbol, nil] When specified system inserts an X-Forwarded-For header in an HTTP request with the client IP address, to use with connection pooling.,When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.\n attribute :insert_xforwarded_for\n validates :insert_xforwarded_for, type: Symbol\n\n # @return [:none, :all, :matching, :nodes, nil] Specifies whether the system rewrites the URIs that are part of HTTP redirect (3XX) responses.,When set to C(none) the system will not rewrite the URI in any HTTP redirect responses.,When set to C(all) the system rewrites the URI in all HTTP redirect responses.,When set to C(matching) the system rewrites the URI in any HTTP redirect responses that match the request URI.,When set to C(nodes) if the URI contains a node IP address instead of a host name, the system changes it to the virtual server address.,When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.\n attribute :redirect_rewrite\n validates :redirect_rewrite, expression_inclusion: {:in=>[:none, :all, :matching, :nodes], :message=>\"%{value} needs to be :none, :all, :matching, :nodes\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] Cookie names for the system to encrypt.,To remove the entry completely a value of C(none) or C('') should be set.,When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.\n attribute :encrypt_cookies\n validates :encrypt_cookies, type: TypeGeneric.new(String)\n\n # @return [Object, nil] Passphrase for cookie encryption.,When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.\n attribute :encrypt_cookie_secret\n\n # @return [:always, :on_create, nil] C(always) will update passwords if the C(encrypt_cookie_secret) is specified.,C(on_create) will only set the password for newly created profiles.\n attribute :update_password\n validates :update_password, expression_inclusion: {:in=>[:always, :on_create], :message=>\"%{value} needs to be :always, :on_create\"}, allow_nil: true\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [:present, :absent, nil] When C(present), ensures that the profile exists.,When C(absent), ensures the profile is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.662665069103241, "alphanum_fraction": 0.662665069103241, "avg_line_length": 32.31999969482422, "blob_id": "72c08616a27e8ed8fd39ca89286b131d0ceccebb", "content_id": "b7ee73e6947104f39f863a552a0fe5b86af4c908", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 833, "license_type": "permissive", "max_line_length": 126, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/network/panos/panos_commit.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # PanOS module that will commit firewall's candidate configuration on\n # the device. The new configuration will become active immediately.\n class Panos_commit < Base\n # @return [Float, nil] interval for checking commit job\n attribute :interval\n validates :interval, type: Float\n\n # @return [Object, nil] timeout for commit job\n attribute :timeout\n\n # @return [:yes, :no, nil] if commit should be synchronous\n attribute :sync\n validates :sync, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.712437093257904, "alphanum_fraction": 0.712437093257904, "avg_line_length": 54.63999938964844, "blob_id": "25154f004ac97d8b1497c80c5222040294f9da48", "content_id": "bdcc21d9af7b1f177c7dbb63c8b143efd7a7f20f", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1391, "license_type": "permissive", "max_line_length": 306, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_device_group_member.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages members in a device group. Members in a device group can only be added or removed, never updated. This is because the members are identified by unique name values and changing that name would invalidate the uniqueness.\n class Bigip_device_group_member < Base\n # @return [String] Specifies the name of the device that you want to add to the device group. Often this will be the hostname of the device. This member must be trusted by the device already. Trusting can be done with the C(bigip_device_trust) module and the C(peer_hostname) option to that module.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] The device group that you want to add the member to.\n attribute :device_group\n validates :device_group, presence: true, type: String\n\n # @return [:present, :absent, nil] When C(present), ensures that the device group member exists.,When C(absent), ensures the device group member is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5900740623474121, "alphanum_fraction": 0.6081711053848267, "avg_line_length": 25.049999237060547, "blob_id": "de43b9629e0b64550395f5a3a8076f7dd8cc87d5", "content_id": "7318a77278744f166bdb02acb1aa16010b7e26f8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3647, "license_type": "permissive", "max_line_length": 124, "num_lines": 140, "path": "/lib/ansible/ruby/models/base_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'spec_helper'\nrequire 'ansible-ruby'\n\ndescribe Ansible::Ruby::Models::Base do\n before { stub_const 'Ansible::Ruby::TestModel', klass }\n\n subject { instance }\n\n let(:klass) do\n Class.new(Ansible::Ruby::Models::Base) do\n attribute :foo\n validates :foo, presence: true\n attribute :bar\n end\n end\n\n context 'valid' do\n let(:instance) { klass.new foo: 123 }\n\n it { is_expected.to be_valid }\n it { is_expected.to have_hash foo: 123 }\n it { is_expected.to have_attributes foo: 123 }\n end\n\n context 'via setter' do\n let(:instance) { klass.new }\n\n before { instance.foo = 123 }\n\n it { is_expected.to be_valid }\n it { is_expected.to have_hash foo: 123 }\n it { is_expected.to have_attributes foo: 123 }\n end\n\n context 'inheritance' do\n let(:klass) do\n superklass = super()\n stub_const 'Ansible::Ruby::TestModelBase', superklass\n puts \"super is #{superklass.attr_options} #{superklass}\"\n Class.new(superklass)\n end\n\n let(:instance) { klass.new foo: 123 }\n\n it { is_expected.to be_valid }\n it { is_expected.to have_hash foo: 123 }\n it { is_expected.to have_attributes foo: 123 }\n end\n\n context 'jinja expression with valid values' do\n let(:klass) do\n Class.new(Ansible::Ruby::Models::Base) do\n attribute :foo\n validates :foo, expression_inclusion: { in: %i[yes no], message: '%{value} needs to be :yes, :no' }, allow_nil: true\n end\n end\n\n let(:instance) { klass.new foo: Ansible::Ruby::Models::JinjaExpression.new('howdy') }\n\n it { is_expected.to be_valid }\n it { is_expected.to have_hash foo: '{{ howdy }}' }\n end\n\n context 'generic' do\n let(:klass) do\n Class.new(Ansible::Ruby::Models::Base) do\n attribute :foo\n validates :foo, type: TypeGeneric.new(Integer)\n end\n end\n\n context 'Jinja expression' do\n let(:instance) { klass.new foo: Ansible::Ruby::Models::JinjaExpression.new('howdy') }\n\n it { is_expected.to be_valid }\n it { is_expected.to have_hash foo: '{{ howdy }}' }\n end\n\n context 'single value' do\n context 'on its own' do\n let(:instance) { klass.new foo: 123 }\n\n it { is_expected.to be_valid }\n it { is_expected.to have_hash foo: [123] }\n it { is_expected.to have_attributes foo: 123 }\n end\n\n context 'in array' do\n let(:instance) { klass.new foo: [123] }\n\n it { is_expected.to be_valid }\n it { is_expected.to have_hash foo: [123] }\n it { is_expected.to have_attributes foo: [123] }\n end\n end\n\n context 'multiple values' do\n let(:instance) { klass.new foo: [123, 456] }\n\n it { is_expected.to be_valid }\n it { is_expected.to have_hash foo: [123, 456] }\n it { is_expected.to have_attributes foo: [123, 456] }\n end\n end\n\n context 'explicit nil' do\n let(:klass) do\n Class.new(Ansible::Ruby::Models::Base) do\n attribute :foo\n validates :foo, presence: true, allow_nil: true\n end\n end\n\n let(:instance) { klass.new foo: nil }\n\n it { is_expected.to be_valid }\n it { is_expected.to have_hash foo: nil }\n end\n\n context 'nested unit' do\n let(:nested_klass) do\n Class.new(Ansible::Ruby::Models::Base) do\n attribute :image\n end\n end\n\n let(:instance) { klass.new foo: nested_klass.new(image: 'centos') }\n\n it { is_expected.to have_hash(foo: { image: 'centos' }) }\n end\n\n context 'missing attribute' do\n let(:instance) { klass.new bar: 123 }\n\n it { is_expected.to_not be_valid }\n it { is_expected.to have_errors foo: \"can't be blank\" }\n end\nend\n" }, { "alpha_fraction": 0.6966824531555176, "alphanum_fraction": 0.6976303458213806, "avg_line_length": 39.57692337036133, "blob_id": "9e9c0f501c1cbfc16e8e2d00f6cc24ebc5ff5ed3", "content_id": "3f1c24609b03b19522201b861e1c8ffce64190b8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1055, "license_type": "permissive", "max_line_length": 211, "num_lines": 26, "path": "/lib/ansible/ruby/modules/generated/utilities/logic/debug.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module prints statements during execution and can be useful for debugging variables or expressions without necessarily halting the playbook. Useful for debugging together with the 'when:' directive.\n # This module is also supported for Windows targets.\n class Debug < Base\n # @return [String, nil] The customized message that is printed. If omitted, prints a generic message.\n attribute :msg\n validates :msg, type: String\n\n # @return [String, nil] A variable name to debug. Mutually exclusive with the 'msg' option.\n attribute :var\n validates :var, type: String\n\n # @return [Integer, nil] A number that controls when the debug is run, if you set to 3 it will only run debug when -vvv or above\n attribute :verbosity\n validates :verbosity, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5577464699745178, "alphanum_fraction": 0.5577464699745178, "avg_line_length": 15.904762268066406, "blob_id": "04c984223127f299fc18501a5d4b02ac222cc468", "content_id": "bf0efa6c1d8eb662f1307f6fd45c5c4609d1b168", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 355, "license_type": "permissive", "max_line_length": 47, "num_lines": 21, "path": "/lib/ansible/ruby/modules/base.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'ansible/ruby/models/base'\n\nmodule Ansible\n module Ruby\n module Modules\n class Base < Models::Base\n def to_h\n {\n ansible_name.to_sym => super\n }\n end\n\n def ansible_name\n self.class.name.demodulize.underscore\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7266300320625305, "alphanum_fraction": 0.7282010912895203, "avg_line_length": 71.05660247802734, "blob_id": "8c26f75e5e2118fe908316b4c56e3c976ac1ca5d", "content_id": "175d914c83849d2dbf9db6713e37e504912ccd5e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3819, "license_type": "permissive", "max_line_length": 745, "num_lines": 53, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_application_scaling_policy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates, updates or removes a Scaling Policy\n class Aws_application_scaling_policy < Base\n # @return [String] The name of the scaling policy.\n attribute :policy_name\n validates :policy_name, presence: true, type: String\n\n # @return [:ecs, :elasticmapreduce, :ec2, :appstream, :dynamodb] The namespace of the AWS service.\n attribute :service_namespace\n validates :service_namespace, presence: true, expression_inclusion: {:in=>[:ecs, :elasticmapreduce, :ec2, :appstream, :dynamodb], :message=>\"%{value} needs to be :ecs, :elasticmapreduce, :ec2, :appstream, :dynamodb\"}\n\n # @return [String] The identifier of the resource associated with the scalable target.\n attribute :resource_id\n validates :resource_id, presence: true, type: String\n\n # @return [:\"ecs:service:DesiredCount\", :\"ec2:spot-fleet-request:TargetCapacity\", :\"elasticmapreduce:instancegroup:InstanceCount\", :\"appstream:fleet:DesiredCapacity\", :\"dynamodb:table:ReadCapacityUnits\", :\"dynamodb:table:WriteCapacityUnits\", :\"dynamodb:index:ReadCapacityUnits\", :\"dynamodb:index:WriteCapacityUnits\"] The scalable dimension associated with the scalable target.\n attribute :scalable_dimension\n validates :scalable_dimension, presence: true, expression_inclusion: {:in=>[:\"ecs:service:DesiredCount\", :\"ec2:spot-fleet-request:TargetCapacity\", :\"elasticmapreduce:instancegroup:InstanceCount\", :\"appstream:fleet:DesiredCapacity\", :\"dynamodb:table:ReadCapacityUnits\", :\"dynamodb:table:WriteCapacityUnits\", :\"dynamodb:index:ReadCapacityUnits\", :\"dynamodb:index:WriteCapacityUnits\"], :message=>\"%{value} needs to be :\\\"ecs:service:DesiredCount\\\", :\\\"ec2:spot-fleet-request:TargetCapacity\\\", :\\\"elasticmapreduce:instancegroup:InstanceCount\\\", :\\\"appstream:fleet:DesiredCapacity\\\", :\\\"dynamodb:table:ReadCapacityUnits\\\", :\\\"dynamodb:table:WriteCapacityUnits\\\", :\\\"dynamodb:index:ReadCapacityUnits\\\", :\\\"dynamodb:index:WriteCapacityUnits\\\"\"}\n\n # @return [:StepScaling, :TargetTrackingScaling] The policy type.\n attribute :policy_type\n validates :policy_type, presence: true, expression_inclusion: {:in=>[:StepScaling, :TargetTrackingScaling], :message=>\"%{value} needs to be :StepScaling, :TargetTrackingScaling\"}\n\n # @return [Hash, nil] A step scaling policy. This parameter is required if you are creating a policy and the policy type is StepScaling.\n attribute :step_scaling_policy_configuration\n validates :step_scaling_policy_configuration, type: Hash\n\n # @return [Hash, nil] A target tracking policy. This parameter is required if you are creating a new policy and the policy type is TargetTrackingScaling.\n attribute :target_tracking_scaling_policy_configuration\n validates :target_tracking_scaling_policy_configuration, type: Hash\n\n # @return [Integer, nil] The minimum value to scale to in response to a scale in event. This parameter is required if you are creating a first new policy for the specified service.\n attribute :minimum_tasks\n validates :minimum_tasks, type: Integer\n\n # @return [Integer, nil] The maximum value to scale to in response to a scale out event. This parameter is required if you are creating a first new policy for the specified service.\n attribute :maximum_tasks\n validates :maximum_tasks, type: Integer\n\n # @return [Symbol, nil] Whether or not to override values of minimum and/or maximum tasks if it's already set.\n attribute :override_task_capacity\n validates :override_task_capacity, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6690802574157715, "alphanum_fraction": 0.6690802574157715, "avg_line_length": 49.594058990478516, "blob_id": "1d1ada534f7855c87d1562d01de48fae00caa7e5", "content_id": "3f8578fa3631d7765d9edc6d3d044996813cb319", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5110, "license_type": "permissive", "max_line_length": 240, "num_lines": 101, "path": "/lib/ansible/ruby/modules/generated/monitoring/sensu_check.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage the checks that should be run on a machine by I(Sensu).\n # Most options do not have a default and will not be added to the check definition unless specified.\n # All defaults except I(path), I(state), I(backup) and I(metric) are not managed by this module,\n # they are simply specified for your convenience.\n class Sensu_check < Base\n # @return [String] The name of the check,This is the key that is used to determine whether a check exists\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Whether the check should be present or not\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Path to the json file of the check to be added/removed.,Will be created if it does not exist (unless I(state=absent)).,The parent folders need to exist when I(state=present), otherwise an error will be thrown\n attribute :path\n validates :path, type: String\n\n # @return [:yes, :no, nil] Create a backup file (if yes), including the timestamp information so,you can get the original file back if you somehow clobbered it incorrectly.\n attribute :backup\n validates :backup, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String] Path to the sensu check to run (not required when I(state=absent))\n attribute :command\n validates :command, presence: true, type: String\n\n # @return [Object, nil] List of handlers to notify when the check fails\n attribute :handlers\n\n # @return [Object, nil] List of subscribers/channels this check should run for,See sensu_subscribers to subscribe a machine to a channel\n attribute :subscribers\n\n # @return [Integer, nil] Check interval in seconds\n attribute :interval\n validates :interval, type: Integer\n\n # @return [Integer, nil] Timeout for the check\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [Object, nil] Time to live in seconds until the check is considered stale\n attribute :ttl\n\n # @return [:yes, :no, nil] Whether the check should be handled or not\n attribute :handle\n validates :handle, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] When to disable handling of check failures\n attribute :subdue_begin\n\n # @return [Object, nil] When to enable handling of check failures\n attribute :subdue_end\n\n # @return [Object, nil] Other checks this check depends on, if dependencies fail,,handling of this check will be disabled\n attribute :dependencies\n\n # @return [:yes, :no, nil] Whether the check is a metric\n attribute :metric\n validates :metric, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Whether the check should be scheduled by the sensu client or server,This option obviates the need for specifying the I(subscribers) option\n attribute :standalone\n validates :standalone, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Whether the check should be scheduled at all.,You can still issue it via the sensu api\n attribute :publish\n validates :publish, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Number of event occurrences before the handler should take action\n attribute :occurrences\n validates :occurrences, type: Integer\n\n # @return [Object, nil] Number of seconds handlers should wait before taking second action\n attribute :refresh\n\n # @return [:yes, :no, nil] Classifies the check as an aggregate check,,making it available via the aggregate API\n attribute :aggregate\n validates :aggregate, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] The low threshold for flap detection\n attribute :low_flap_threshold\n\n # @return [Object, nil] The high threshold for flap detection\n attribute :high_flap_threshold\n\n # @return [Object, nil] A hash/dictionary of custom parameters for mixing to the configuration.,You can't rewrite others module parameters using this\n attribute :custom\n\n # @return [Object, nil] The check source, used to create a JIT Sensu client for an external resource (e.g. a network switch).\n attribute :source\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6883116960525513, "alphanum_fraction": 0.6911976933479309, "avg_line_length": 33.650001525878906, "blob_id": "2a9d1653259a2abc9ec9280b3a29d75d1fa9f4bd", "content_id": "95a402f0a67b80654129f631c51a72df27fabd7b", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 693, "license_type": "permissive", "max_line_length": 156, "num_lines": 20, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/netapp_e_global.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allow the user to configure several of the global settings associated with an E-Series storage-system\n class Netapp_e_global < Base\n # @return [String, nil] Set the name of the E-Series storage-system,This label/name doesn't have to be unique.,May be up to 30 characters in length.\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] A local path to a file to be used for debug logging\n attribute :log_path\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6703436374664307, "alphanum_fraction": 0.6720407009124756, "avg_line_length": 50.239131927490234, "blob_id": "d6f0b1d3740f8f0c3be0c76d056a4a0e104b9be5", "content_id": "90db1c1efc54d5aead1f1f498982da890c4a997e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2357, "license_type": "permissive", "max_line_length": 264, "num_lines": 46, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_datacenter.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Module to manage data centers in oVirt/RHV\n class Ovirt_datacenter < Base\n # @return [String] Name of the data center to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Should the data center be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Description of the data center.\n attribute :description\n\n # @return [Object, nil] Comment of the data center.\n attribute :comment\n\n # @return [Boolean, nil] I(True) if the data center should be local, I(False) if should be shared.,Default value is set by engine.\n attribute :local\n validates :local, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Float, nil] Compatibility version of the data center.\n attribute :compatibility_version\n validates :compatibility_version, type: Float\n\n # @return [:disabled, :audit, :enabled, nil] Quota mode of the data center. One of I(disabled), I(audit) or I(enabled)\n attribute :quota_mode\n validates :quota_mode, expression_inclusion: {:in=>[:disabled, :audit, :enabled], :message=>\"%{value} needs to be :disabled, :audit, :enabled\"}, allow_nil: true\n\n # @return [Object, nil] MAC pool to be used by this datacenter.,IMPORTANT: This option is deprecated in oVirt/RHV 4.1. You should use C(mac_pool) in C(ovirt_clusters) module, as MAC pools are set per cluster since 4.1.\n attribute :mac_pool\n\n # @return [Boolean, nil] This parameter can be used only when removing a data center. If I(True) data center will be forcibly removed, even though it contains some clusters. Default value is I(False), which means that only empty data center can be removed.\n attribute :force\n validates :force, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7031195163726807, "alphanum_fraction": 0.7083771228790283, "avg_line_length": 63.84090805053711, "blob_id": "d0e829b989894de617e342706437f4cb1d17ee7d", "content_id": "b6c43ee08cf2547257d922d1c32bc1e21ac547ce", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2853, "license_type": "permissive", "max_line_length": 512, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_security_address_list.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages the AFM address lists on a BIG-IP. This module can be used to add and remove address list entries.\n class Bigip_firewall_address_list < Base\n # @return [String] Specifies the name of the address list.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [Object, nil] Description of the address list\n attribute :description\n\n # @return [Object, nil] List of geolocations specified by their C(country) and C(region).\n attribute :geo_locations\n\n # @return [Array<String>, String, nil] Individual addresses that you want to add to the list. These addresses differ from ranges, and lists of lists such as what can be used in C(address_ranges) and C(address_lists) respectively.,This list can also include networks that have CIDR notation.\n attribute :addresses\n validates :addresses, type: TypeGeneric.new(String)\n\n # @return [Object, nil] A list of address ranges where the range starts with a port number, is followed by a dash (-) and then a second number.,If the first address is greater than the second number, the numbers will be reversed so-as to be properly formatted. ie, C(2.2.2.2-1.1.1). would become C(1.1.1.1-2.2.2.2).\n attribute :address_ranges\n\n # @return [Object, nil] Simple list of existing address lists to add to this list. Address lists can be specified in either their fully qualified name (/Common/foo) or their short name (foo). If a short name is used, the C(partition) argument will automatically be prepended to the short name.\n attribute :address_lists\n\n # @return [Object, nil] A list of fully qualified domain names (FQDNs).,An FQDN has at least one decimal point in it, separating the host from the domain.,To add FQDNs to a list requires that a global FQDN resolver be configured. At the moment, this must either be done via C(bigip_command), or, in the GUI of BIG-IP. If using C(bigip_command), this can be done with C(tmsh modify security firewall global-fqdn-policy FOO) where C(FOO) is a DNS resolver configured at C(tmsh create net dns-resolver FOO).\n attribute :fqdns\n\n # @return [:present, :absent, nil] When C(present), ensures that the address list and entries exists.,When C(absent), ensures the address list is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5848696827888489, "alphanum_fraction": 0.6668785810470581, "avg_line_length": 46.66666793823242, "blob_id": "efb9840b74273cc4dfb9e107e89d5978adf0692b", "content_id": "47a81c6585721259431265ba79d6bf0c7e1fb2e8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1573, "license_type": "permissive", "max_line_length": 238, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/cloud/memset/memset_zone.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage DNS zones in a Memset account.\n class Memset_zone < Base\n # @return [:absent, :present] Indicates desired state of resource.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}\n\n # @return [String] The API key obtained from the Memset control panel.\n attribute :api_key\n validates :api_key, presence: true, type: String\n\n # @return [String] The zone nickname; usually the same as the main domain. Ensure this value has at most 250 characters.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [0, 300, 600, 900, 1800, 3600, 7200, 10800, 21600, 43200, 86400, nil] The default TTL for all records created in the zone. This must be a valid int from U(https://www.memset.com/apidocs/methods_dns.html#dns.zone_create).\n attribute :ttl\n validates :ttl, expression_inclusion: {:in=>[0, 300, 600, 900, 1800, 3600, 7200, 10800, 21600, 43200, 86400], :message=>\"%{value} needs to be 0, 300, 600, 900, 1800, 3600, 7200, 10800, 21600, 43200, 86400\"}, allow_nil: true\n\n # @return [Symbol, nil] Forces deletion of a zone and all zone domains/zone records it contains.\n attribute :force\n validates :force, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6619718074798584, "alphanum_fraction": 0.6619718074798584, "avg_line_length": 40.41666793823242, "blob_id": "397ad5d39360b1943d9e01a50665a8fa0ecc67d8", "content_id": "7782d76ab006339a4aede74f1b1402ffd86e9934", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1491, "license_type": "permissive", "max_line_length": 143, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/cloud/heroku/heroku_collaborator.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages collaborators for Heroku apps.\n # If set to C(present) and heroku user is already collaborator, then do nothing.\n # If set to C(present) and heroku user is not collaborator, then add user to app.\n # If set to C(absent) and heroku user is collaborator, then delete user from app.\n class Heroku_collaborator < Base\n # @return [String, nil] Heroku API key\n attribute :api_key\n validates :api_key, type: String\n\n # @return [Array<String>, String] List of Heroku App names\n attribute :apps\n validates :apps, presence: true, type: TypeGeneric.new(String)\n\n # @return [:yes, :no, nil] Suppress email invitation when creating collaborator\n attribute :suppress_invitation\n validates :suppress_invitation, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String] User ID or e-mail\n attribute :user\n validates :user, presence: true, type: String\n\n # @return [:present, :absent, nil] Create or remove the heroku collaborator\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6659693121910095, "alphanum_fraction": 0.6659693121910095, "avg_line_length": 37.75675582885742, "blob_id": "4e5830b5b9061ec897a61ed2bccc5e7e64dc8422", "content_id": "025723dd0cd5b50c5a371cb14a1e681ca929c19a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1434, "license_type": "permissive", "max_line_length": 166, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/windows/win_toast.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Sends alerts which appear in the Action Center area of the windows desktop.\n class Win_toast < Base\n # @return [Integer, nil] How long in seconds before the notification expires.\n attribute :expire\n validates :expire, type: Integer\n\n # @return [String, nil] Which notification group to add the notification to.\n attribute :group\n validates :group, type: String\n\n # @return [Array<String>, String, nil] The message to appear inside the notification.,May include \\n to format the message to appear within the Action Center.\n attribute :msg\n validates :msg, type: TypeGeneric.new(String)\n\n # @return [Boolean, nil] If C(no), the notification will not pop up and will only appear in the Action Center.\n attribute :popup\n validates :popup, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] The tag to add to the notification.\n attribute :tag\n validates :tag, type: String\n\n # @return [String, nil] The notification title, which appears in the pop up..\n attribute :title\n validates :title, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6911686658859253, "alphanum_fraction": 0.6911686658859253, "avg_line_length": 56.30303192138672, "blob_id": "e75e1c4301ee6ed360ff44209210c8aac413baa1", "content_id": "ff18cf110fab9b238775e3af2060234b0ad47354", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1891, "license_type": "permissive", "max_line_length": 588, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_cdot_svm.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or destroy svm on NetApp cDOT\n class Na_cdot_svm < Base\n # @return [:present, :absent] Whether the specified SVM should exist or not.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String] The name of the SVM to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Root volume of the SVM. Required when C(state=present).\n attribute :root_volume\n validates :root_volume, type: String\n\n # @return [String, nil] The aggregate on which the root volume will be created.,Required when C(state=present).\n attribute :root_volume_aggregate\n validates :root_volume_aggregate, type: String\n\n # @return [:unix, :ntfs, :mixed, :unified, nil] Security Style of the root volume.,When specified as part of the vserver-create, this field represents the security style for the Vserver root volume.,When specified as part of vserver-get-iter call, this will return the list of matching Vservers.,Possible values are 'unix', 'ntfs', 'mixed'.,The 'unified' security style, which applies only to Infinite Volumes, cannot be applied to a Vserver's root volume.,Valid options are \"unix\" for NFS, \"ntfs\" for CIFS, \"mixed\" for Mixed, \"unified\" for Unified.,Required when C(state=present)\n attribute :root_volume_security_style\n validates :root_volume_security_style, expression_inclusion: {:in=>[:unix, :ntfs, :mixed, :unified], :message=>\"%{value} needs to be :unix, :ntfs, :mixed, :unified\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6791828870773315, "alphanum_fraction": 0.6839060187339783, "avg_line_length": 53.28845977783203, "blob_id": "e1d564f8038fdb152f67fc3c72a00aa4a6f1446f", "content_id": "105cb14ff1c6b7d78340026ae15405d51c8db189", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 8469, "license_type": "permissive", "max_line_length": 310, "num_lines": 156, "path": "/lib/ansible/ruby/modules/generated/cloud/docker/docker_swarm_service.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage docker services. Allows live altering of already defined services\n\n class Docker_swarm_service < Base\n # @return [String] Service name\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] Service image path and tag. Maps docker service IMAGE parameter.\n attribute :image\n validates :image, presence: true, type: String\n\n # @return [:present, :absent] Service state.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [Object, nil] List comprised of the command and the arguments to be run inside,the container\n attribute :args\n\n # @return [Object, nil] List of the service constraints.,Maps docker service --constraint option.\n attribute :constraints\n\n # @return [String, nil] Container hostname,Maps docker service --hostname option.,Requires api_version >= 1.25\n attribute :hostname\n validates :hostname, type: String\n\n # @return [Symbol, nil] Allocate a pseudo-TTY,Maps docker service --tty option.,Requires api_version >= 1.25\n attribute :tty\n validates :tty, type: Symbol\n\n # @return [Object, nil] List of custom DNS servers.,Maps docker service --dns option.,Requires api_version >= 1.25\n attribute :dns\n\n # @return [Object, nil] List of custom DNS search domains.,Maps docker service --dns-search option.,Requires api_version >= 1.25\n attribute :dns_search\n\n # @return [Object, nil] List of custom DNS options.,Maps docker service --dns-option option.,Requires api_version >= 1.25\n attribute :dns_options\n\n # @return [Symbol, nil] Force update even if no changes require it.,Maps to docker service update --force option.,Requires api_version >= 1.25\n attribute :force_update\n validates :force_update, type: Symbol\n\n # @return [Object, nil] List of the service labels.,Maps docker service --label option.\n attribute :labels\n\n # @return [Object, nil] List of the service containers labels.,Maps docker service --container-label option.\n attribute :container_labels\n\n # @return [:vip, :dnsrr, nil] Service endpoint mode.,Maps docker service --endpoint-mode option.\n attribute :endpoint_mode\n validates :endpoint_mode, expression_inclusion: {:in=>[:vip, :dnsrr], :message=>\"%{value} needs to be :vip, :dnsrr\"}, allow_nil: true\n\n # @return [Object, nil] List of the service environment variables.,Maps docker service --env option.\n attribute :env\n\n # @return [String, nil] Configure the logging driver for a service\n attribute :log_driver\n validates :log_driver, type: String\n\n # @return [Object, nil] Options for service logging driver\n attribute :log_driver_options\n\n # @return [Float, nil] Service CPU limit. 0 equals no limit.,Maps docker service --limit-cpu option.\n attribute :limit_cpu\n validates :limit_cpu, type: Float\n\n # @return [Float, nil] Service CPU reservation. 0 equals no reservation.,Maps docker service --reserve-cpu option.\n attribute :reserve_cpu\n validates :reserve_cpu, type: Float\n\n # @return [Integer, nil] Service memory limit in MB. 0 equals no limit.,Maps docker service --limit-memory option.\n attribute :limit_memory\n validates :limit_memory, type: Integer\n\n # @return [Integer, nil] Service memory reservation in MB. 0 equals no reservation.,Maps docker service --reserve-memory option.\n attribute :reserve_memory\n validates :reserve_memory, type: Integer\n\n # @return [String, nil] Service replication mode.,Maps docker service --mode option.\n attribute :mode\n validates :mode, type: String\n\n # @return [Object, nil] List of dictionaries describing the service mounts.,Every item must be a dictionary exposing the keys source, target, type (defaults to 'bind'), readonly (defaults to false),Maps docker service --mount option.\n attribute :mounts\n\n # @return [Object, nil] List of dictionaries describing the service secrets.,Every item must be a dictionary exposing the keys secret_id, secret_name, filename, uid (defaults to 0), gid (defaults to 0), mode (defaults to 0o444),Maps docker service --secret option.\n attribute :secrets\n\n # @return [Object, nil] List of dictionaries describing the service configs.,Every item must be a dictionary exposing the keys config_id, config_name, filename, uid (defaults to 0), gid (defaults to 0), mode (defaults to 0o444),Maps docker service --config option.\n attribute :configs\n\n # @return [Object, nil] List of the service networks names.,Maps docker service --network option.\n attribute :networks\n\n # @return [Object, nil] List of dictionaries describing the service published ports.,Every item must be a dictionary exposing the keys published_port, target_port, protocol (defaults to 'tcp'), mode <ingress|host>, default to ingress.,Only used with api_version >= 1.25\n attribute :publish\n\n # @return [Integer, nil] Number of containers instantiated in the service. Valid only if ``mode=='replicated'``.,If set to -1, and service is not present, service replicas will be set to 1.,If set to -1, and service is present, service replicas will be unchanged.,Maps docker service --replicas option.\n attribute :replicas\n validates :replicas, type: Integer\n\n # @return [:none, :\"on-failure\", :any, nil] Restart condition of the service.,Maps docker service --restart-condition option.\n attribute :restart_policy\n validates :restart_policy, expression_inclusion: {:in=>[:none, :\"on-failure\", :any], :message=>\"%{value} needs to be :none, :\\\"on-failure\\\", :any\"}, allow_nil: true\n\n # @return [Integer, nil] Maximum number of service restarts.,Maps docker service --restart-max-attempts option.\n attribute :restart_policy_attempts\n validates :restart_policy_attempts, type: Integer\n\n # @return [Integer, nil] Delay between restarts.,Maps docker service --restart-delay option.\n attribute :restart_policy_delay\n validates :restart_policy_delay, type: Integer\n\n # @return [Integer, nil] Restart policy evaluation window.,Maps docker service --restart-window option.\n attribute :restart_policy_window\n validates :restart_policy_window, type: Integer\n\n # @return [Integer, nil] Rolling update delay,Maps docker service --update-delay option\n attribute :update_delay\n validates :update_delay, type: Integer\n\n # @return [Integer, nil] Rolling update parallelism,Maps docker service --update-parallelism option\n attribute :update_parallelism\n validates :update_parallelism, type: Integer\n\n # @return [:continue, :pause, nil] Action to take in case of container failure,Maps to docker service --update-failure-action option\n attribute :update_failure_action\n validates :update_failure_action, expression_inclusion: {:in=>[:continue, :pause], :message=>\"%{value} needs to be :continue, :pause\"}, allow_nil: true\n\n # @return [Integer, nil] Time to monitor updated tasks for failures, in nanoseconds.,Maps to docker service --update-monitor option\n attribute :update_monitor\n validates :update_monitor, type: Integer\n\n # @return [Float, nil] Fraction of tasks that may fail during an update before the failure action is invoked,Maps to docker service --update-max-failure-ratio\n attribute :update_max_failure_ratio\n validates :update_max_failure_ratio, type: Float\n\n # @return [:\"stop-first\", :\"start-first\", nil] Specifies the order of operations when rolling out an updated task.,Maps to docker service --update-order\n attribute :update_order\n validates :update_order, expression_inclusion: {:in=>[:\"stop-first\", :\"start-first\"], :message=>\"%{value} needs to be :\\\"stop-first\\\", :\\\"start-first\\\"\"}, allow_nil: true\n\n # @return [String, nil] username or UID\n attribute :user\n validates :user, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6776228547096252, "alphanum_fraction": 0.6806108951568604, "avg_line_length": 56.92307662963867, "blob_id": "e8f4155c841d69302cb8416faea452a24ac84c83", "content_id": "495241d8bd671d7e27633233e716d56bbef5b3a6", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3012, "license_type": "permissive", "max_line_length": 380, "num_lines": 52, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_aggregate.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, delete, or manage aggregates on ONTAP.\n class Na_ontap_aggregate < Base\n # @return [:present, :absent, nil] Whether the specified aggregate should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:online, :offline, nil] Whether the specified aggregate should be enabled or disabled. Creates aggregate if doesnt exist.\n attribute :service_state\n validates :service_state, expression_inclusion: {:in=>[:online, :offline], :message=>\"%{value} needs to be :online, :offline\"}, allow_nil: true\n\n # @return [String] The name of the aggregate to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Name of the aggregate to be renamed.\n attribute :from_name\n\n # @return [Object, nil] Node(s) for the aggregate to be created on. If no node specified, mgmt lif home will be used.,If multiple nodes specified an aggr stripe will be made.\n attribute :nodes\n\n # @return [:ATA, :BSAS, :FCAL, :FSAS, :LUN, :MSATA, :SAS, :SSD, :VMDISK, nil] Type of disk to use to build aggregate\n attribute :disk_type\n validates :disk_type, expression_inclusion: {:in=>[:ATA, :BSAS, :FCAL, :FSAS, :LUN, :MSATA, :SAS, :SSD, :VMDISK], :message=>\"%{value} needs to be :ATA, :BSAS, :FCAL, :FSAS, :LUN, :MSATA, :SAS, :SSD, :VMDISK\"}, allow_nil: true\n\n # @return [Integer, nil] Number of disks to place into the aggregate, including parity disks.,The disks in this newly-created aggregate come from the spare disk pool.,The smallest disks in this pool join the aggregate first, unless the C(disk-size) argument is provided.,Either C(disk-count) or C(disks) must be supplied. Range [0..2^31-1].,Required when C(state=present).\n attribute :disk_count\n validates :disk_count, type: Integer\n\n # @return [Object, nil] Disk size to use in 4K block size. Disks within 10% of specified size will be used.\n attribute :disk_size\n\n # @return [Object, nil] Sets the maximum number of drives per raid group.\n attribute :raid_size\n\n # @return [Object, nil] Specifies the type of RAID groups to use in the new aggregate.,The default value is raid4 on most platforms.\n attribute :raid_type\n\n # @return [Symbol, nil] If set to \"TRUE\", this option specifies that all of the volumes hosted by the given aggregate are to be unmounted,before the offline operation is executed.,By default, the system will reject any attempt to offline an aggregate that hosts one or more online volumes.\n attribute :unmount_volumes\n validates :unmount_volumes, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7144185900688171, "alphanum_fraction": 0.7144185900688171, "avg_line_length": 50.19047546386719, "blob_id": "b587eeb467e4125603bdde47849d6b5919c3b689", "content_id": "2b203e81bb2e1bbdcbe6666e6b3d4dd92abaf9e3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1075, "license_type": "permissive", "max_line_length": 353, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/remote_management/oneview/oneview_ethernet_network.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Provides an interface to manage Ethernet Network resources. Can create, update, or delete.\n class Oneview_ethernet_network < Base\n # @return [:present, :absent, :default_bandwidth_reset, nil] Indicates the desired state for the Ethernet Network resource. - C(present) will ensure data properties are compliant with OneView. - C(absent) will remove the resource from OneView, if it exists. - C(default_bandwidth_reset) will reset the network connection template to the default.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :default_bandwidth_reset], :message=>\"%{value} needs to be :present, :absent, :default_bandwidth_reset\"}, allow_nil: true\n\n # @return [Hash] List with Ethernet Network properties.\n attribute :data\n validates :data, presence: true, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.661051869392395, "alphanum_fraction": 0.661051869392395, "avg_line_length": 49.40565872192383, "blob_id": "9138a923134e551da1879a06afdb28c991e0b7fa", "content_id": "ca738d582e56ee31407ce8a0ea78e92b02082c87", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5343, "license_type": "permissive", "max_line_length": 171, "num_lines": 106, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_coe_cluster_template.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or Remove COE cluster template from the OpenStack Container Infra service.\n class Os_coe_cluster_template < Base\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n\n # @return [:kubernetes, :swarm, :mesos, nil] The Container Orchestration Engine for this clustertemplate\n attribute :coe\n validates :coe, expression_inclusion: {:in=>[:kubernetes, :swarm, :mesos], :message=>\"%{value} needs to be :kubernetes, :swarm, :mesos\"}, allow_nil: true\n\n # @return [String, nil] The DNS nameserver address\n attribute :dns_nameserver\n validates :dns_nameserver, type: String\n\n # @return [:devicemapper, :overlay, nil] Docker storage driver\n attribute :docker_storage_driver\n validates :docker_storage_driver, expression_inclusion: {:in=>[:devicemapper, :overlay], :message=>\"%{value} needs to be :devicemapper, :overlay\"}, allow_nil: true\n\n # @return [Object, nil] The size in GB of the docker volume\n attribute :docker_volume_size\n\n # @return [Object, nil] The external network to attach to the Cluster\n attribute :external_network_id\n\n # @return [Object, nil] The fixed network name to attach to the Cluster\n attribute :fixed_network\n\n # @return [Object, nil] The fixed subnet name to attach to the Cluster\n attribute :fixed_subnet\n\n # @return [Object, nil] The flavor of the minion node for this ClusterTemplate\n attribute :flavor_id\n\n # @return [:yes, :no, nil] Indicates whether created clusters should have a floating ip or not\n attribute :floating_ip_enabled\n validates :floating_ip_enabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Name or ID of the keypair to use.\n attribute :keypair_id\n validates :keypair_id, type: String\n\n # @return [String, nil] Image id the cluster will be based on\n attribute :image_id\n validates :image_id, type: String\n\n # @return [Object, nil] One or more key/value pairs\n attribute :labels\n\n # @return [Object, nil] Address of a proxy that will receive all HTTP requests and relay them The format is a URL including a port number\n attribute :http_proxy\n\n # @return [Object, nil] Address of a proxy that will receive all HTTPS requests and relay them. The format is a URL including a port number\n attribute :https_proxy\n\n # @return [Object, nil] The flavor of the master node for this ClusterTemplate\n attribute :master_flavor_id\n\n # @return [:yes, :no, nil] Indicates whether created clusters should have a load balancer for master nodes or not\n attribute :master_lb_enabled\n validates :master_lb_enabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String] Name that has to be given to the cluster template\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:flannel, :calico, :docker, nil] The name of the driver used for instantiating container networks\n attribute :network_driver\n validates :network_driver, expression_inclusion: {:in=>[:flannel, :calico, :docker], :message=>\"%{value} needs to be :flannel, :calico, :docker\"}, allow_nil: true\n\n # @return [Object, nil] A comma separated list of IPs for which proxies should not be used in the cluster\n attribute :no_proxy\n\n # @return [:yes, :no, nil] Indicates whether the ClusterTemplate is public or not\n attribute :public\n validates :public, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Indicates whether the docker registry is enabled\n attribute :registry_enabled\n validates :registry_enabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:vm, :bm, nil] Server type for this ClusterTemplate\n attribute :server_type\n validates :server_type, expression_inclusion: {:in=>[:vm, :bm], :message=>\"%{value} needs to be :vm, :bm\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Indicate desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Indicates whether the TLS should be disabled\n attribute :tls_disabled\n validates :tls_disabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:cinder, :rexray, nil] The name of the driver used for instantiating container volumes\n attribute :volume_driver\n validates :volume_driver, expression_inclusion: {:in=>[:cinder, :rexray], :message=>\"%{value} needs to be :cinder, :rexray\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6961501836776733, "alphanum_fraction": 0.7009226679801941, "avg_line_length": 70.43181610107422, "blob_id": "3a409dfee2ce2bf9d0a1b9dbf9602dc238a8aa64", "content_id": "cbe923c02b5d7f0124aa4c4a90d5beee52a01b9a", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3143, "license_type": "permissive", "max_line_length": 546, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_guest_powerstate.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Power on / Power off / Restart a virtual machine.\n class Vmware_guest_powerstate < Base\n # @return [:\"powered-off\", :\"powered-on\", :\"reboot-guest\", :restarted, :\"shutdown-guest\", :suspended, :present, nil] Set the state of the virtual machine.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:\"powered-off\", :\"powered-on\", :\"reboot-guest\", :restarted, :\"shutdown-guest\", :suspended, :present], :message=>\"%{value} needs to be :\\\"powered-off\\\", :\\\"powered-on\\\", :\\\"reboot-guest\\\", :restarted, :\\\"shutdown-guest\\\", :suspended, :present\"}, allow_nil: true\n\n # @return [String, nil] Name of the virtual machine to work with.,Virtual machine names in vCenter are not necessarily unique, which may be problematic, see C(name_match).\n attribute :name\n validates :name, type: String\n\n # @return [:first, :last, nil] If multiple virtual machines matching the name, use the first or last found.\n attribute :name_match\n validates :name_match, expression_inclusion: {:in=>[:first, :last], :message=>\"%{value} needs to be :first, :last\"}, allow_nil: true\n\n # @return [Object, nil] UUID of the instance to manage if known, this is VMware's unique identifier.,This is required if name is not supplied.\n attribute :uuid\n\n # @return [String, nil] Destination folder, absolute or relative path to find an existing guest or create the new guest.,The folder should include the datacenter. ESX's datacenter is ha-datacenter,Examples:, folder: /ha-datacenter/vm, folder: ha-datacenter/vm, folder: /datacenter1/vm, folder: datacenter1/vm, folder: /datacenter1/vm/folder1, folder: datacenter1/vm/folder1, folder: /folder1/datacenter1/vm, folder: folder1/datacenter1/vm, folder: /folder1/datacenter1/vm/folder2, folder: vm/folder2, folder: folder2\n attribute :folder\n validates :folder, type: String\n\n # @return [String, nil] Date and time in string format at which specificed task needs to be performed.,The required format for date and time - 'dd/mm/yyyy hh:mm'.,Scheduling task requires vCenter server. A standalone ESXi server does not support this option.\n attribute :scheduled_at\n validates :scheduled_at, type: String\n\n # @return [Symbol, nil] Ignore warnings and complete the actions.,This parameter is useful while forcing virtual machine state.\n attribute :force\n validates :force, type: Symbol\n\n # @return [Integer, nil] If the C(state) is set to C(shutdown-guest), by default the module will return immediately after sending the shutdown signal.,If this argument is set to a positive integer, the module will instead wait for the VM to reach the poweredoff state.,The value sets a timeout in seconds for the module to wait for the state change.\n attribute :state_change_timeout\n validates :state_change_timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6634615659713745, "alphanum_fraction": 0.6634615659713745, "avg_line_length": 31.275861740112305, "blob_id": "402b0da9791b3fbc38a031e120f540d43ee19378", "content_id": "c244fd1a9bde1941ea458945f9cd32dda428f940", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 936, "license_type": "permissive", "max_line_length": 111, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ecs_service_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Lists or describes services in ecs.\n class Ecs_service_facts < Base\n # @return [Symbol, nil] Set this to true if you want detailed information about the services.\n attribute :details\n validates :details, type: Symbol\n\n # @return [Symbol, nil] Whether to return ECS service events. Only has an effect if C(details) is true.\n attribute :events\n validates :events, type: Symbol\n\n # @return [String, nil] The cluster ARNS in which to list the services.\n attribute :cluster\n validates :cluster, type: String\n\n # @return [String, nil] One or more services to get details for\n attribute :service\n validates :service, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.67988520860672, "alphanum_fraction": 0.67988520860672, "avg_line_length": 57.96923065185547, "blob_id": "29976efe97c24cd83f96ceb303bde6da0c61b6af", "content_id": "b040aa220a7d2021c1e05f515cfa0f6e995dbf0c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3833, "license_type": "permissive", "max_line_length": 257, "num_lines": 65, "path": "/lib/ansible/ruby/modules/generated/monitoring/sensu_handler.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages Sensu handler configuration\n # For more information, refer to the Sensu documentation: U(https://sensuapp.org/docs/latest/reference/handlers.html)\n class Sensu_handler < Base\n # @return [:present, :absent, nil] Whether the handler should be present or not\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] A unique name for the handler. The name cannot contain special characters or spaces.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:pipe, :tcp, :udp, :transport, :set] The handler type\n attribute :type\n validates :type, presence: true, expression_inclusion: {:in=>[:pipe, :tcp, :udp, :transport, :set], :message=>\"%{value} needs to be :pipe, :tcp, :udp, :transport, :set\"}\n\n # @return [Object, nil] The Sensu event filter (name) to use when filtering events for the handler.\n attribute :filter\n\n # @return [Object, nil] An array of Sensu event filters (names) to use when filtering events for the handler.,Each array item must be a string.\n attribute :filters\n\n # @return [:warning, :critical, :unknown, nil] An array of check result severities the handler will handle.,NOTE: event resolution bypasses this filtering.\n attribute :severities\n validates :severities, expression_inclusion: {:in=>[:warning, :critical, :unknown], :message=>\"%{value} needs to be :warning, :critical, :unknown\"}, allow_nil: true\n\n # @return [Object, nil] The Sensu event mutator (name) to use to mutate event data for the handler.\n attribute :mutator\n\n # @return [Integer, nil] The handler execution duration timeout in seconds (hard stop).,Only used by pipe and tcp handler types.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [:yes, :no, nil] If events matching one or more silence entries should be handled.\n attribute :handle_silenced\n validates :handle_silenced, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If events in the flapping state should be handled.\n attribute :handle_flapping\n validates :handle_flapping, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] The handler command to be executed.,The event data is passed to the process via STDIN.,NOTE: the command attribute is only required for Pipe handlers (i.e. handlers configured with \"type\": \"pipe\").\n attribute :command\n validates :command, type: String\n\n # @return [Hash, nil] The socket definition scope, used to configure the TCP/UDP handler socket.,NOTE: the socket attribute is only required for TCP/UDP handlers (i.e. handlers configured with \"type\": \"tcp\" or \"type\": \"udp\").\n attribute :socket\n validates :socket, type: Hash\n\n # @return [Object, nil] The pipe definition scope, used to configure the Sensu transport pipe.,NOTE: the pipe attribute is only required for Transport handlers (i.e. handlers configured with \"type\": \"transport\").\n attribute :pipe\n\n # @return [Object, nil] An array of Sensu event handlers (names) to use for events using the handler set.,Each array item must be a string.,NOTE: the handlers attribute is only required for handler sets (i.e. handlers configured with \"type\": \"set\").\n attribute :handlers\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6911602020263672, "alphanum_fraction": 0.6983425617218018, "avg_line_length": 53.84848403930664, "blob_id": "f42987c4633756378b38aaa8b767066d2268178e", "content_id": "1bc1150f836f2b765b0fa8cafd0b52ed50a719e8", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1810, "license_type": "permissive", "max_line_length": 528, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_guest_move.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to move virtual machines between folders.\n class Vmware_guest_move < Base\n # @return [String, nil] Name of the existing virtual machine to move.,This is required if C(UUID) is not supplied.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] UUID of the virtual machine to manage if known, this is VMware's unique identifier.,This is required if C(name) is not supplied.\n attribute :uuid\n validates :uuid, type: String\n\n # @return [:first, :last, nil] If multiple virtual machines matching the name, use the first or last found.\n attribute :name_match\n validates :name_match, expression_inclusion: {:in=>[:first, :last], :message=>\"%{value} needs to be :first, :last\"}, allow_nil: true\n\n # @return [String] Absolute path to move an existing guest,The dest_folder should include the datacenter. ESX's datacenter is ha-datacenter.,This parameter is case sensitive.,Examples:, dest_folder: /ha-datacenter/vm, dest_folder: ha-datacenter/vm, dest_folder: /datacenter1/vm, dest_folder: datacenter1/vm, dest_folder: /datacenter1/vm/folder1, dest_folder: datacenter1/vm/folder1, dest_folder: /folder1/datacenter1/vm, dest_folder: folder1/datacenter1/vm, dest_folder: /folder1/datacenter1/vm/folder2\n attribute :dest_folder\n validates :dest_folder, presence: true, type: String\n\n # @return [String] Destination datacenter for the move operation\n attribute :datacenter\n validates :datacenter, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6502485275268555, "alphanum_fraction": 0.6556710600852966, "avg_line_length": 44.163265228271484, "blob_id": "e5590eb41b82c02c4edae7ee82a3d8a4d761a88a", "content_id": "5a2ff0f99c3cf68daa2dd1cbbf01704167d44397", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2213, "license_type": "permissive", "max_line_length": 343, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_hsrp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages HSRP configuration on NX-OS switches.\n class Nxos_hsrp < Base\n # @return [Integer] HSRP group number.\n attribute :group\n validates :group, presence: true, type: Integer\n\n # @return [String] Full name of interface that is being managed for HSRP.\n attribute :interface\n validates :interface, presence: true, type: String\n\n # @return [1, 2, nil] HSRP version.\n attribute :version\n validates :version, expression_inclusion: {:in=>[1, 2], :message=>\"%{value} needs to be 1, 2\"}, allow_nil: true\n\n # @return [Integer, nil] HSRP priority or keyword 'default'.\n attribute :priority\n validates :priority, type: Integer\n\n # @return [:enabled, :disabled, nil] Enable/Disable preempt.\n attribute :preempt\n validates :preempt, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [String, nil] HSRP virtual IP address or keyword 'default'\n attribute :vip\n validates :vip, type: String\n\n # @return [String, nil] Authentication string. If this needs to be hidden(for md5 type), the string should be 7 followed by the key string. Otherwise, it can be 0 followed by key string or just key string (for backward compatibility). For text type, this should be just be a key string. if this is 'default', authentication is removed.\n attribute :auth_string\n validates :auth_string, type: String\n\n # @return [:text, :md5, nil] Authentication type.\n attribute :auth_type\n validates :auth_type, expression_inclusion: {:in=>[:text, :md5], :message=>\"%{value} needs to be :text, :md5\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Specify desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6900063753128052, "alphanum_fraction": 0.6900063753128052, "avg_line_length": 46.60606002807617, "blob_id": "5c5f89b5895b981d75562434066515e9ad7cae2c", "content_id": "871ee5a8450094b17cea022f5d6aa645179862e2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1571, "license_type": "permissive", "max_line_length": 278, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/network/aos/aos_blueprint_virtnet.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Apstra AOS Blueprint Virtual Network module let you manage your Virtual Network easily. You can create access, define and delete Virtual Network by name or by using a JSON / Yaml file. This module is idempotent and support the I(check) mode. It's using the AOS REST API.\n class Aos_blueprint_virtnet < Base\n # @return [String] An existing AOS session as obtained by M(aos_login) module.\n attribute :session\n validates :session, presence: true, type: String\n\n # @return [String] Blueprint Name or Id as defined in AOS.\n attribute :blueprint\n validates :blueprint, presence: true, type: String\n\n # @return [String, nil] Name of Virtual Network as part of the Blueprint.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] Datastructure of the Virtual Network to manage. The data can be in YAML / JSON or directly a variable. It's the same datastructure that is returned on success in I(value).\n attribute :content\n validates :content, type: String\n\n # @return [:present, :absent, nil] Indicate what is the expected state of the Virtual Network (present or not).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6546280980110168, "alphanum_fraction": 0.6548672318458557, "avg_line_length": 54.01315689086914, "blob_id": "4abda0e3d595e04fbebc881e7b8840d68e36b486", "content_id": "aa92321fff91fb4228172a391e3f1eca2eae24ae", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4181, "license_type": "permissive", "max_line_length": 234, "num_lines": 76, "path": "/lib/ansible/ruby/modules/generated/source_control/gitlab_hooks.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Adds, updates and removes project hooks\n class Gitlab_hooks < Base\n # @return [String] GitLab API url, e.g. https://gitlab.example.com/api\n attribute :api_url\n validates :api_url, presence: true, type: String\n\n # @return [String, nil] The oauth key provided by GitLab. One of access_token or private_token is required. See https://docs.gitlab.com/ee/api/oauth2.html\n attribute :access_token\n validates :access_token, type: String\n\n # @return [Object, nil] Personal access token to use. One of private_token or access_token is required. See https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html\n attribute :private_token\n\n # @return [String, Integer] Numeric project id or name of project in the form of group/name\n attribute :project\n validates :project, presence: true, type: MultipleTypes.new(String, Integer)\n\n # @return [String] The url that you want GitLab to post to, this is used as the primary key for updates and deletion.\n attribute :hook_url\n validates :hook_url, presence: true, type: String\n\n # @return [:present, :absent] When C(present) the hook will be updated to match the input or created if it doesn't exist. When C(absent) it will be deleted if it exists.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [:yes, :no, nil] Trigger hook on push events\n attribute :push_events\n validates :push_events, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Trigger hook on issues events\n attribute :issues_events\n validates :issues_events, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Trigger hook on merge requests events\n attribute :merge_requests_events\n validates :merge_requests_events, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Trigger hook on tag push events\n attribute :tag_push_events\n validates :tag_push_events, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Trigger hook on note events\n attribute :note_events\n validates :note_events, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Trigger hook on job events\n attribute :job_events\n validates :job_events, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Trigger hook on pipeline events\n attribute :pipeline_events\n validates :pipeline_events, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Trigger hook on wiki events\n attribute :wiki_page_events\n validates :wiki_page_events, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Whether GitLab will do SSL verification when triggering the hook\n attribute :enable_ssl_verification\n validates :enable_ssl_verification, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Secret token to validate hook messages at the receiver.,If this is present it will always result in a change as it cannot be retrieved from GitLab.,Will show up in the X-Gitlab-Token HTTP request header\n attribute :token\n validates :token, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6724137663841248, "alphanum_fraction": 0.6736453175544739, "avg_line_length": 37.66666793823242, "blob_id": "0806f68dfb9bef832aecd18a1dd43e66b5584012", "content_id": "318325235424f854eb132b3bd18e8d0a43413674", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 812, "license_type": "permissive", "max_line_length": 186, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_gtm_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Collect facts from F5 BIG-IP GTM devices.\n class Bigip_gtm_facts < Base\n # @return [:pool, :wide_ip, :server] Fact category to collect.\n attribute :include\n validates :include, presence: true, expression_inclusion: {:in=>[:pool, :wide_ip, :server], :message=>\"%{value} needs to be :pool, :wide_ip, :server\"}\n\n # @return [String, nil] Perform regex filter of response. Filtering is done on the name of the resource. Valid filters are anything that can be provided to Python's C(re) module.\n attribute :filter\n validates :filter, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6886075735092163, "alphanum_fraction": 0.6891139149665833, "avg_line_length": 43.8863639831543, "blob_id": "7c84fe557306caeded02f3584231da8ed82ed133", "content_id": "71449abd75d640c51dbe3b6120ec6f5b661cada0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1975, "license_type": "permissive", "max_line_length": 203, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/monitoring/sensu_silence.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create and clear (delete) a silence entries via the Sensu API for subscriptions and checks.\n class Sensu_silence < Base\n # @return [String, nil] Specifies the check which the silence entry applies to.\n attribute :check\n validates :check, type: String\n\n # @return [String, nil] Specifies the entity responsible for this entry.\n attribute :creator\n validates :creator, type: String\n\n # @return [Object, nil] If specified, the silence entry will be automatically cleared after this number of seconds.\n attribute :expire\n\n # @return [Symbol, nil] If specified as true, the silence entry will be automatically cleared once the condition it is silencing is resolved.\n attribute :expire_on_resolve\n validates :expire_on_resolve, type: Symbol\n\n # @return [String, nil] If specified, this free-form string is used to provide context or rationale for the reason this silence entry was created.\n attribute :reason\n validates :reason, type: String\n\n # @return [:present, :absent] Specifies to create or clear (delete) a silence entry via the Sensu API\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [Object] Specifies the subscription which the silence entry applies to.,To create a silence entry for a client prepend C(client:) to client name. Example - C(client:server1.example.dev)\n attribute :subscription\n validates :subscription, presence: true\n\n # @return [String, nil] Specifies the URL of the Sensu monitoring host server.\n attribute :url\n validates :url, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6846098303794861, "alphanum_fraction": 0.6846098303794861, "avg_line_length": 50.25925827026367, "blob_id": "afc6a8fe2300ecd649ea814e6558ca8809e9f83c", "content_id": "5db14ebc2f8ad0cac9dc4f882c43884127ab0eed", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2768, "license_type": "permissive", "max_line_length": 322, "num_lines": 54, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_ironic.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or Remove Ironic nodes from OpenStack.\n class Os_ironic < Base\n # @return [:present, :absent, nil] Indicates desired state of the resource\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] globally unique identifier (UUID) to be given to the resource. Will be auto-generated if not specified, and name is specified.,Definition of a UUID will always take precedence to a name value.\n attribute :uuid\n validates :uuid, type: String\n\n # @return [Object, nil] unique name identifier to be given to the resource.\n attribute :name\n\n # @return [String] The name of the Ironic Driver to use with this node.\n attribute :driver\n validates :driver, presence: true, type: String\n\n # @return [String, nil] Associate the node with a pre-defined chassis.\n attribute :chassis_uuid\n validates :chassis_uuid, type: String\n\n # @return [Object, nil] If noauth mode is utilized, this is required to be set to the endpoint URL for the Ironic API. Use with \"auth\" and \"auth_type\" settings set to None.\n attribute :ironic_url\n\n # @return [Hash, nil] Information for this server's driver. Will vary based on which driver is in use. Any sub-field which is populated will be validated during creation.\n attribute :driver_info\n validates :driver_info, type: Hash\n\n # @return [Array<Hash>, Hash] A list of network interface cards, eg, \" - mac: aa:bb:cc:aa:bb:cc\"\n attribute :nics\n validates :nics, presence: true, type: TypeGeneric.new(Hash)\n\n # @return [Hash, nil] Definition of the physical characteristics of this server, used for scheduling purposes\n attribute :properties\n validates :properties, type: Hash\n\n # @return [:yes, :no, nil] Allows the code that would assert changes to nodes to skip the update if the change is a single line consisting of the password field. As of Kilo, by default, passwords are always masked to API requests, which means the logic as a result always attempts to re-assert the password field.\n attribute :skip_update_of_driver_password\n validates :skip_update_of_driver_password, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.651177704334259, "alphanum_fraction": 0.6638650894165039, "avg_line_length": 66.68115997314453, "blob_id": "f9bc0f6346e87ada42160016336bd97cbca10877", "content_id": "3e3913a841570c0225d01809ecd54b2edf7e5fb7", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 18716, "license_type": "permissive", "max_line_length": 939, "num_lines": 276, "path": "/lib/ansible/ruby/modules/generated/cloud/misc/proxmox_kvm.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows you to create/delete/stop Qemu(KVM) Virtual Machines in Proxmox VE cluster.\n class Proxmox_kvm < Base\n # @return [:yes, :no, nil] Specify if ACPI should be enabled/disabled.\n attribute :acpi\n validates :acpi, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Symbol, nil] Specify if the QEMU Guest Agent should be enabled/disabled.\n attribute :agent\n validates :agent, type: Symbol\n\n # @return [Array<String>, String, nil] Pass arbitrary arguments to kvm.,This option is for experts only!\n attribute :args\n validates :args, type: TypeGeneric.new(String)\n\n # @return [String] Specify the target host of the Proxmox VE cluster.\n attribute :api_host\n validates :api_host, presence: true, type: String\n\n # @return [String] Specify the user to authenticate with.\n attribute :api_user\n validates :api_user, presence: true, type: String\n\n # @return [String, nil] Specify the password to authenticate with.,You can use C(PROXMOX_PASSWORD) environment variable.\n attribute :api_password\n validates :api_password, type: String\n\n # @return [:yes, :no, nil] Specify if the VM should be automatically restarted after crash (currently ignored in PVE API).\n attribute :autostart\n validates :autostart, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Specify the amount of RAM for the VM in MB.,Using zero disables the balloon driver.\n attribute :balloon\n validates :balloon, type: Integer\n\n # @return [:seabios, :ovmf, nil] Specify the BIOS implementation.\n attribute :bios\n validates :bios, expression_inclusion: {:in=>[:seabios, :ovmf], :message=>\"%{value} needs to be :seabios, :ovmf\"}, allow_nil: true\n\n # @return [String, nil] Specify the boot order -> boot on floppy C(a), hard disk C(c), CD-ROM C(d), or network C(n).,You can combine to set order.\n attribute :boot\n validates :boot, type: String\n\n # @return [Object, nil] Enable booting from specified disk. C((ide|sata|scsi|virtio)\\d+)\n attribute :bootdisk\n\n # @return [String, nil] Name of VM to be cloned. If C(vmid) is setted, C(clone) can take arbitrary value but required for intiating the clone.\n attribute :clone\n validates :clone, type: String\n\n # @return [Integer, nil] Specify number of cores per socket.\n attribute :cores\n validates :cores, type: Integer\n\n # @return [String, nil] Specify emulated CPU type.\n attribute :cpu\n validates :cpu, type: String\n\n # @return [Object, nil] Specify if CPU usage will be limited. Value 0 indicates no CPU limit.,If the computer has 2 CPUs, it has total of '2' CPU time\n attribute :cpulimit\n\n # @return [Integer, nil] Specify CPU weight for a VM.,You can disable fair-scheduler configuration by setting this to 0\n attribute :cpuunits\n validates :cpuunits, type: Integer\n\n # @return [Array<String>, String, nil] Specify a list of settings you want to delete.\n attribute :delete\n validates :delete, type: TypeGeneric.new(String)\n\n # @return [Object, nil] Specify the description for the VM. Only used on the configuration web interface.,This is saved as comment inside the configuration file.\n attribute :description\n\n # @return [Object, nil] Specify if to prevent changes if current configuration file has different SHA1 digest.,This can be used to prevent concurrent modifications.\n attribute :digest\n\n # @return [Symbol, nil] Allow to force stop VM.,Can be used only with states C(stopped), C(restarted).\n attribute :force\n validates :force, type: Symbol\n\n # @return [:cloop, :cow, :qcow, :qcow2, :qed, :raw, :vmdk, nil] Target drive's backing file's data format.,Used only with clone\n attribute :format\n validates :format, expression_inclusion: {:in=>[:cloop, :cow, :qcow, :qcow2, :qed, :raw, :vmdk], :message=>\"%{value} needs to be :cloop, :cow, :qcow, :qcow2, :qed, :raw, :vmdk\"}, allow_nil: true\n\n # @return [Symbol, nil] Specify if PVE should freeze CPU at startup (use 'c' monitor command to start execution).\n attribute :freeze\n validates :freeze, type: Symbol\n\n # @return [:yes, :no, nil] Create a full copy of all disk. This is always done when you clone a normal VM.,For VM templates, we try to create a linked clone by default.,Used only with clone\n attribute :full\n validates :full, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Specify a hash/dictionary of map host pci devices into guest. C(hostpci='{\"key\":\"value\", \"key\":\"value\"}').,Keys allowed are - C(hostpci[n]) where 0 ≤ n ≤ N.,Values allowed are - C(\"host=\"HOSTPCIID[;HOSTPCIID2...]\",pcie=\"1|0\",rombar=\"1|0\",x-vga=\"1|0\"\").,The C(host) parameter is Host PCI device pass through. HOSTPCIID syntax is C(bus:dev.func) (hexadecimal numbers).,C(pcie=boolean) I(default=0) Choose the PCI-express bus (needs the q35 machine model).,C(rombar=boolean) I(default=1) Specify whether or not the device's ROM will be visible in the guest's memory map.,C(x-vga=boolean) I(default=0) Enable vfio-vga device support.,/!\\ This option allows direct access to host hardware. So it is no longer possible to migrate such machines - use with special care.\n attribute :hostpci\n\n # @return [Object, nil] Selectively enable hotplug features.,This is a comma separated list of hotplug features C('network', 'disk', 'cpu', 'memory' and 'usb').,Value 0 disables hotplug completely and value 1 is an alias for the default C('network,disk,usb').\n attribute :hotplug\n\n # @return [:any, 2, 1024, nil] Enable/disable hugepages memory.\n attribute :hugepages\n validates :hugepages, expression_inclusion: {:in=>[:any, 2, 1024], :message=>\"%{value} needs to be :any, 2, 1024\"}, allow_nil: true\n\n # @return [Object, nil] A hash/dictionary of volume used as IDE hard disk or CD-ROM. C(ide='{\"key\":\"value\", \"key\":\"value\"}').,Keys allowed are - C(ide[n]) where 0 ≤ n ≤ 3.,Values allowed are - C(\"storage:size,format=value\").,C(storage) is the storage identifier where to create the disk.,C(size) is the size of the disk in GB.,C(format) is the drive's backing file's data format. C(qcow2|raw|subvol).\n attribute :ide\n\n # @return [Object, nil] Sets the keyboard layout for VNC server.\n attribute :keyboard\n\n # @return [:yes, :no, nil] Enable/disable KVM hardware virtualization.\n attribute :kvm\n validates :kvm, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Symbol, nil] Sets the real time clock to local time.,This is enabled by default if ostype indicates a Microsoft OS.\n attribute :localtime\n validates :localtime, type: Symbol\n\n # @return [:migrate, :backup, :snapshot, :rollback, nil] Lock/unlock the VM.\n attribute :lock\n validates :lock, expression_inclusion: {:in=>[:migrate, :backup, :snapshot, :rollback], :message=>\"%{value} needs to be :migrate, :backup, :snapshot, :rollback\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the Qemu machine type.,type => C((pc|pc(-i440fx)?-\\d+\\.\\d+(\\.pxe)?|q35|pc-q35-\\d+\\.\\d+(\\.pxe)?))\n attribute :machine\n\n # @return [Integer, nil] Memory size in MB for instance.\n attribute :memory\n validates :memory, type: Integer\n\n # @return [Object, nil] Sets maximum tolerated downtime (in seconds) for migrations.\n attribute :migrate_downtime\n\n # @return [Object, nil] Sets maximum speed (in MB/s) for migrations.,A value of 0 is no limit.\n attribute :migrate_speed\n\n # @return [String, nil] Specifies the VM name. Only used on the configuration web interface.,Required only for C(state=present).\n attribute :name\n validates :name, type: String\n\n # @return [Hash, nil] A hash/dictionary of network interfaces for the VM. C(net='{\"key\":\"value\", \"key\":\"value\"}').,Keys allowed are - C(net[n]) where 0 ≤ n ≤ N.,Values allowed are - C(\"model=\"XX:XX:XX:XX:XX:XX\",brigde=\"value\",rate=\"value\",tag=\"value\",firewall=\"1|0\",trunks=\"vlanid\"\").,Model is one of C(e1000 e1000-82540em e1000-82544gc e1000-82545em i82551 i82557b i82559er ne2k_isa ne2k_pci pcnet rtl8139 virtio vmxnet3).,C(XX:XX:XX:XX:XX:XX) should be an unique MAC address. This is automatically generated if not specified.,The C(bridge) parameter can be used to automatically add the interface to a bridge device. The Proxmox VE standard bridge is called 'vmbr0'.,Option C(rate) is used to limit traffic bandwidth from and to this interface. It is specified as floating point number, unit is 'Megabytes per second'.,If you specify no bridge, we create a kvm 'user' (NATed) network device, which provides DHCP and DNS services.\n attribute :net\n validates :net, type: Hash\n\n # @return [Integer, nil] VMID for the clone. Used only with clone.,If newid is not set, the next available VM ID will be fetched from ProxmoxAPI.\n attribute :newid\n validates :newid, type: Integer\n\n # @return [String, nil] Proxmox VE node, where the new VM will be created.,Only required for C(state=present).,For other states, it will be autodiscovered.\n attribute :node\n validates :node, type: String\n\n # @return [Object, nil] A hash/dictionaries of NUMA topology. C(numa='{\"key\":\"value\", \"key\":\"value\"}').,Keys allowed are - C(numa[n]) where 0 ≤ n ≤ N.,Values allowed are - C(\"cpu=\"<id[-id];...>\",hostnodes=\"<id[-id];...>\",memory=\"number\",policy=\"(bind|interleave|preferred)\"\").,C(cpus) CPUs accessing this NUMA node.,C(hostnodes) Host NUMA nodes to use.,C(memory) Amount of memory this NUMA node provides.,C(policy) NUMA allocation policy.\n attribute :numa\n\n # @return [:yes, :no, nil] Specifies whether a VM will be started during system bootup.\n attribute :onboot\n validates :onboot, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:other, :wxp, :w2k, :w2k3, :w2k8, :wvista, :win7, :win8, :l24, :l26, :solaris, nil] Specifies guest operating system. This is used to enable special optimization/features for specific operating systems.,The l26 is Linux 2.6/3.X Kernel.\n attribute :ostype\n validates :ostype, expression_inclusion: {:in=>[:other, :wxp, :w2k, :w2k3, :w2k8, :wvista, :win7, :win8, :l24, :l26, :solaris], :message=>\"%{value} needs to be :other, :wxp, :w2k, :w2k3, :w2k8, :wvista, :win7, :win8, :l24, :l26, :solaris\"}, allow_nil: true\n\n # @return [Object, nil] A hash/dictionary of map host parallel devices. C(parallel='{\"key\":\"value\", \"key\":\"value\"}').,Keys allowed are - (parallel[n]) where 0 ≤ n ≤ 2.,Values allowed are - C(\"/dev/parport\\d+|/dev/usb/lp\\d+\").\n attribute :parallel\n\n # @return [Object, nil] Add the new VM to the specified pool.\n attribute :pool\n\n # @return [Symbol, nil] Enable/disable the protection flag of the VM. This will enable/disable the remove VM and remove disk operations.\n attribute :protection\n validates :protection, type: Symbol\n\n # @return [Symbol, nil] Allow reboot. If set to C(yes), the VM exit on reboot.\n attribute :reboot\n validates :reboot, type: Symbol\n\n # @return [Array<String>, String, nil] Revert a pending change.\n attribute :revert\n validates :revert, type: TypeGeneric.new(String)\n\n # @return [Object, nil] A hash/dictionary of volume used as sata hard disk or CD-ROM. C(sata='{\"key\":\"value\", \"key\":\"value\"}').,Keys allowed are - C(sata[n]) where 0 ≤ n ≤ 5.,Values allowed are - C(\"storage:size,format=value\").,C(storage) is the storage identifier where to create the disk.,C(size) is the size of the disk in GB.,C(format) is the drive's backing file's data format. C(qcow2|raw|subvol).\n attribute :sata\n\n # @return [Object, nil] A hash/dictionary of volume used as SCSI hard disk or CD-ROM. C(scsi='{\"key\":\"value\", \"key\":\"value\"}').,Keys allowed are - C(sata[n]) where 0 ≤ n ≤ 13.,Values allowed are - C(\"storage:size,format=value\").,C(storage) is the storage identifier where to create the disk.,C(size) is the size of the disk in GB.,C(format) is the drive's backing file's data format. C(qcow2|raw|subvol).\n attribute :scsi\n\n # @return [:lsi, :lsi53c810, :\"virtio-scsi-pci\", :\"virtio-scsi-single\", :megasas, :pvscsi, nil] Specifies the SCSI controller model.\n attribute :scsihw\n validates :scsihw, expression_inclusion: {:in=>[:lsi, :lsi53c810, :\"virtio-scsi-pci\", :\"virtio-scsi-single\", :megasas, :pvscsi], :message=>\"%{value} needs to be :lsi, :lsi53c810, :\\\"virtio-scsi-pci\\\", :\\\"virtio-scsi-single\\\", :megasas, :pvscsi\"}, allow_nil: true\n\n # @return [Object, nil] A hash/dictionary of serial device to create inside the VM. C('{\"key\":\"value\", \"key\":\"value\"}').,Keys allowed are - serial[n](str; required) where 0 ≤ n ≤ 3.,Values allowed are - C((/dev/.+|socket)).,/!\\ If you pass through a host serial device, it is no longer possible to migrate such machines - use with special care.\n attribute :serial\n\n # @return [Object, nil] Rets amount of memory shares for auto-ballooning. (0 - 50000).,The larger the number is, the more memory this VM gets.,The number is relative to weights of all other running VMs.,Using 0 disables auto-ballooning, this means no limit.\n attribute :shares\n\n # @return [Object, nil] Ignore locks,Only root is allowed to use this option.\n attribute :skiplock\n\n # @return [Object, nil] Specifies SMBIOS type 1 fields.\n attribute :smbios\n\n # @return [Object, nil] The name of the snapshot. Used only with clone.\n attribute :snapname\n\n # @return [Integer, nil] Sets the number of CPU sockets. (1 - N).\n attribute :sockets\n validates :sockets, type: Integer\n\n # @return [Object, nil] Sets the initial date of the real time clock.,Valid format for date are C('now') or C('2016-09-25T16:01:21') or C('2016-09-25').\n attribute :startdate\n\n # @return [Object, nil] Startup and shutdown behavior. C([[order=]\\d+] [,up=\\d+] [,down=\\d+]).,Order is a non-negative number defining the general startup order.,Shutdown in done with reverse ordering.\n attribute :startup\n\n # @return [:present, :started, :absent, :stopped, :restarted, :current, nil] Indicates desired state of the instance.,If C(current), the current state of the VM will be fecthed. You can access it with C(results.status)\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :started, :absent, :stopped, :restarted, :current], :message=>\"%{value} needs to be :present, :started, :absent, :stopped, :restarted, :current\"}, allow_nil: true\n\n # @return [String, nil] Target storage for full clone.\n attribute :storage\n validates :storage, type: String\n\n # @return [:yes, :no, nil] Enables/disables the USB tablet device.\n attribute :tablet\n validates :tablet, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Target node. Only allowed if the original VM is on shared storage.,Used only with clone\n attribute :target\n\n # @return [Symbol, nil] Enables/disables time drift fix.\n attribute :tdf\n validates :tdf, type: Symbol\n\n # @return [:yes, :no, nil] Enables/disables the template.\n attribute :template\n validates :template, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Timeout for operations.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [:yes, :no, nil] If C(yes), the VM will be update with new value.,Cause of the operations of the API and security reasons, I have disabled the update of the following parameters,C(net, virtio, ide, sata, scsi). Per example updating C(net) update the MAC address and C(virtio) create always new disk...\n attribute :update\n validates :update, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Sets number of hotplugged vcpus.\n attribute :vcpus\n validates :vcpus, type: Integer\n\n # @return [:std, :cirrus, :vmware, :qxl, :serial0, :serial1, :serial2, :serial3, :qxl2, :qxl3, :qxl4, nil] Select VGA type. If you want to use high resolution modes (>= 1280x1024x16) then you should use option 'std' or 'vmware'.\n attribute :vga\n validates :vga, expression_inclusion: {:in=>[:std, :cirrus, :vmware, :qxl, :serial0, :serial1, :serial2, :serial3, :qxl2, :qxl3, :qxl4], :message=>\"%{value} needs to be :std, :cirrus, :vmware, :qxl, :serial0, :serial1, :serial2, :serial3, :qxl2, :qxl3, :qxl4\"}, allow_nil: true\n\n # @return [Hash, nil] A hash/dictionary of volume used as VIRTIO hard disk. C(virtio='{\"key\":\"value\", \"key\":\"value\"}').,Keys allowed are - C(virto[n]) where 0 ≤ n ≤ 15.,Values allowed are - C(\"storage:size,format=value\").,C(storage) is the storage identifier where to create the disk.,C(size) is the size of the disk in GB.,C(format) is the drive's backing file's data format. C(qcow2|raw|subvol).\n attribute :virtio\n validates :virtio, type: Hash\n\n # @return [Integer, nil] Specifies the VM ID. Instead use I(name) parameter.,If vmid is not set, the next available VM ID will be fetched from ProxmoxAPI.\n attribute :vmid\n validates :vmid, type: Integer\n\n # @return [Object, nil] Creates a virtual hardware watchdog device.\n attribute :watchdog\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7077910900115967, "alphanum_fraction": 0.7116782069206238, "avg_line_length": 96, "blob_id": "3a6d5536e563ff63a59d9f5a060059668414c714", "content_id": "3cc1f1e2b2a7c22e64223f237bb720549c7b08d2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5917, "license_type": "permissive", "max_line_length": 740, "num_lines": 61, "path": "/lib/ansible/ruby/modules/generated/windows/win_lineinfile.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module will search a file for a line, and ensure that it is present or absent.\n # This is primarily useful when you want to change a single line in a file only.\n class Win_lineinfile < Base\n # @return [String] The path of the file to modify.,Note that the Windows path delimiter C(\\) must be escaped as C(\\\\) when the line is double quoted.,Before 2.3 this option was only usable as I(dest), I(destfile) and I(name).\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [String, nil] The regular expression to look for in every line of the file. For C(state=present), the pattern to replace if found; only the last line found will be replaced. For C(state=absent), the pattern of the line to remove. Uses .NET compatible regular expressions; see U(https://msdn.microsoft.com/en-us/library/hs600312%28v=vs.110%29.aspx).\n attribute :regexp\n validates :regexp, type: String\n\n # @return [:absent, :present, nil] Whether the line should be there or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] Required for C(state=present). The line to insert/replace into the file. If C(backrefs) is set, may contain backreferences that will get expanded with the C(regexp) capture groups if the regexp matches.,Be aware that the line is processed first on the controller and thus is dependent on yaml quoting rules. Any double quoted line will have control characters, such as '\\r\\n', expanded. To print such characters literally, use single or no quotes.\n attribute :line\n validates :line, type: String\n\n # @return [:yes, :no, nil] Used with C(state=present). If set, line can contain backreferences (both positional and named) that will get populated if the C(regexp) matches. This flag changes the operation of the module slightly; C(insertbefore) and C(insertafter) will be ignored, and if the C(regexp) doesn't match anywhere in the file, the file will be left unchanged.,If the C(regexp) does match, the last matching line will be replaced by the expanded line parameter.\n attribute :backrefs\n validates :backrefs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:EOF, :\"*regex*\", nil] Used with C(state=present). If specified, the line will be inserted after the last match of specified regular expression. A special value is available; C(EOF) for inserting the line at the end of the file.,If specified regular expression has no matches, EOF will be used instead. May not be used with C(backrefs).\n attribute :insertafter\n validates :insertafter, expression_inclusion: {:in=>[:EOF, :\"*regex*\"], :message=>\"%{value} needs to be :EOF, :\\\"*regex*\\\"\"}, allow_nil: true\n\n # @return [:BOF, :\"*regex*\", nil] Used with C(state=present). If specified, the line will be inserted before the last match of specified regular expression. A value is available; C(BOF) for inserting the line at the beginning of the file.,If specified regular expression has no matches, the line will be inserted at the end of the file. May not be used with C(backrefs).\n attribute :insertbefore\n validates :insertbefore, expression_inclusion: {:in=>[:BOF, :\"*regex*\"], :message=>\"%{value} needs to be :BOF, :\\\"*regex*\\\"\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Used with C(state=present). If specified, the file will be created if it does not already exist. By default it will fail if the file is missing.\n attribute :create\n validates :create, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.\n attribute :backup\n validates :backup, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Validation to run before copying into place. Use %s in the command to indicate the current file to validate.,The command is passed securely so shell features like expansion and pipes won't work.\n attribute :validate\n\n # @return [String, nil] Specifies the encoding of the source text file to operate on (and thus what the output encoding will be). The default of C(auto) will cause the module to auto-detect the encoding of the source file and ensure that the modified file is written with the same encoding.,An explicit encoding can be passed as a string that is a valid value to pass to the .NET framework System.Text.Encoding.GetEncoding() method - see U(https://msdn.microsoft.com/en-us/library/system.text.encoding%28v=vs.110%29.aspx).,This is mostly useful with C(create=yes) if you want to create a new file with a specific encoding. If C(create=yes) is specified without a specific encoding, the default encoding (UTF-8, no BOM) will be used.\n attribute :encoding\n validates :encoding, type: String\n\n # @return [:unix, :windows, nil] Specifies the line separator style to use for the modified file. This defaults to the windows line separator (C(\\r\\n)). Note that the indicated line separator will be used for file output regardless of the original line separator that appears in the input file.\n attribute :newline\n validates :newline, expression_inclusion: {:in=>[:unix, :windows], :message=>\"%{value} needs to be :unix, :windows\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6675928235054016, "alphanum_fraction": 0.6769385933876038, "avg_line_length": 48.48749923706055, "blob_id": "29e85ee59ca3f26b58c6b5cb5e5fbc9aa63a4cbc", "content_id": "715061215d8e345a9a507061e6281c0a96b06920", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3959, "license_type": "permissive", "max_line_length": 285, "num_lines": 80, "path": "/lib/ansible/ruby/modules/generated/network/netvisor/pn_vrouterif.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Execute vrouter-interface-add, vrouter-interface-remove, vrouter-interface-modify command.\n # You configure interfaces to vRouter services on a fabric, cluster, standalone switch or virtual network(VNET).\n class Pn_vrouterif < Base\n # @return [String, nil] Provide login username if user is not root.\n attribute :pn_cliusername\n validates :pn_cliusername, type: String\n\n # @return [String, nil] Provide login password if user is not root.\n attribute :pn_clipassword\n validates :pn_clipassword, type: String\n\n # @return [Object, nil] Target switch to run the cli on.\n attribute :pn_cliswitch\n\n # @return [:present, :absent, :update] State the action to perform. Use 'present' to add vrouter interface, 'absent' to remove vrouter interface and 'update' to modify vrouter interface.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent, :update], :message=>\"%{value} needs to be :present, :absent, :update\"}\n\n # @return [String] Specify the name of the vRouter interface.\n attribute :pn_vrouter_name\n validates :pn_vrouter_name, presence: true, type: String\n\n # @return [Integer, nil] Specify the VLAN identifier. This is a value between 1 and 4092.\n attribute :pn_vlan\n validates :pn_vlan, type: Integer\n\n # @return [String, nil] Specify the IP address of the interface in x.x.x.x/n format.\n attribute :pn_interface_ip\n validates :pn_interface_ip, type: String\n\n # @return [:none, :dhcp, :dhcpv6, :autov6, nil] Specify the DHCP method for IP address assignment.\n attribute :pn_assignment\n validates :pn_assignment, expression_inclusion: {:in=>[:none, :dhcp, :dhcpv6, :autov6], :message=>\"%{value} needs to be :none, :dhcp, :dhcpv6, :autov6\"}, allow_nil: true\n\n # @return [Object, nil] Specify the VXLAN identifier. This is a value between 1 and 16777215.\n attribute :pn_vxlan\n\n # @return [:mgmt, :data, :span, nil] Specify if the interface is management, data or span interface.\n attribute :pn_interface\n validates :pn_interface, expression_inclusion: {:in=>[:mgmt, :data, :span], :message=>\"%{value} needs to be :mgmt, :data, :span\"}, allow_nil: true\n\n # @return [Object, nil] Specify an alias for the interface.\n attribute :pn_alias\n\n # @return [Object, nil] Specify if the interface is exclusive to the configuration. Exclusive means that other configurations cannot use the interface. Exclusive is specified when you configure the interface as span interface and allows higher throughput through the interface.\n attribute :pn_exclusive\n\n # @return [Object, nil] Specify if the NIC is enabled or not\n attribute :pn_nic_enable\n\n # @return [Object, nil] Specify the ID for the VRRP interface. The IDs on both vRouters must be the same IS number.\n attribute :pn_vrrp_id\n\n # @return [Integer, nil] Specify the priority for the VRRP interface. This is a value between 1 (lowest) and 255 (highest).\n attribute :pn_vrrp_priority\n validates :pn_vrrp_priority, type: Integer\n\n # @return [Object, nil] Specify a VRRP advertisement interval in milliseconds. The range is from 30 to 40950 with a default value of 1000.\n attribute :pn_vrrp_adv_int\n\n # @return [Object, nil] Specify a Layer 3 port for the interface.\n attribute :pn_l3port\n\n # @return [Object, nil] Specify a secondary MAC address for the interface.\n attribute :pn_secondary_macs\n\n # @return [Object, nil] Specify the type of NIC. Used for vrouter-interface remove/modify.\n attribute :pn_nic_str\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6886898279190063, "alphanum_fraction": 0.6898096203804016, "avg_line_length": 61.887325286865234, "blob_id": "3937d3c1248279daa3c1d890968e17432e9f0f72", "content_id": "0efed0d9f83838ff0bb0037ac871a06091e0e78b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4465, "license_type": "permissive", "max_line_length": 619, "num_lines": 71, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_healthcheck.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, Update or Destroy a Healthcheck. Currently only HTTP and HTTPS Healthchecks are supported. Healthchecks are used to monitor individual instances, managed instance groups and/or backend services. Healtchecks are reusable.\n # Visit U(https://cloud.google.com/compute/docs/load-balancing/health-checks) for an overview of Healthchecks on GCP.\n # See U(https://cloud.google.com/compute/docs/reference/latest/httpHealthChecks) for API details on HTTP Healthchecks.\n # See U(https://cloud.google.com/compute/docs/reference/latest/httpsHealthChecks) for more details on the HTTPS Healtcheck API.\n class Gcp_healthcheck < Base\n # @return [Integer, nil] How often (in seconds) to send a health check.\n attribute :check_interval\n validates :check_interval, type: Integer\n\n # @return [String] Name of the Healthcheck.\n attribute :healthcheck_name\n validates :healthcheck_name, presence: true, type: String\n\n # @return [:HTTP, :HTTPS] Type of Healthcheck.\n attribute :healthcheck_type\n validates :healthcheck_type, presence: true, expression_inclusion: {:in=>[:HTTP, :HTTPS], :message=>\"%{value} needs to be :HTTP, :HTTPS\"}\n\n # @return [String] The value of the host header in the health check request. If left empty, the public IP on behalf of which this health check is performed will be used.\n attribute :host_header\n validates :host_header, presence: true, type: String\n\n # @return [Object, nil] The TCP port number for the health check request. The default value is 443 for HTTPS and 80 for HTTP.\n attribute :port\n\n # @return [String, nil] The request path of the HTTPS health check request.\n attribute :request_path\n validates :request_path, type: String\n\n # @return [:present, :absent] State of the Healthcheck.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [Integer, nil] How long (in seconds) to wait for a response before claiming failure. It is invalid for timeout to have a greater value than check_interval.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [Integer, nil] A so-far healthy instance will be marked unhealthy after this many consecutive failures.\n attribute :unhealthy_threshold\n validates :unhealthy_threshold, type: Integer\n\n # @return [Integer, nil] A so-far unhealthy instance will be marked healthy after this many consecutive successes.\n attribute :healthy_threshold\n validates :healthy_threshold, type: Integer\n\n # @return [String, nil] service account email\n attribute :service_account_email\n validates :service_account_email, type: String\n\n # @return [:bigquery, :\"cloud-platform\", :\"compute-ro\", :\"compute-rw\", :\"useraccounts-ro\", :\"useraccounts-rw\", :datastore, :\"logging-write\", :monitoring, :\"sql-admin\", :\"storage-full\", :\"storage-ro\", :\"storage-rw\", :taskqueue, :\"userinfo-email\", nil] service account permissions (see U(https://cloud.google.com/sdk/gcloud/reference/compute/instances/create), --scopes section for detailed information)\n attribute :service_account_permissions\n validates :service_account_permissions, expression_inclusion: {:in=>[:bigquery, :\"cloud-platform\", :\"compute-ro\", :\"compute-rw\", :\"useraccounts-ro\", :\"useraccounts-rw\", :datastore, :\"logging-write\", :monitoring, :\"sql-admin\", :\"storage-full\", :\"storage-ro\", :\"storage-rw\", :taskqueue, :\"userinfo-email\"], :message=>\"%{value} needs to be :bigquery, :\\\"cloud-platform\\\", :\\\"compute-ro\\\", :\\\"compute-rw\\\", :\\\"useraccounts-ro\\\", :\\\"useraccounts-rw\\\", :datastore, :\\\"logging-write\\\", :monitoring, :\\\"sql-admin\\\", :\\\"storage-full\\\", :\\\"storage-ro\\\", :\\\"storage-rw\\\", :taskqueue, :\\\"userinfo-email\\\"\"}, allow_nil: true\n\n # @return [String, nil] Path to the JSON file associated with the service account email\n attribute :credentials_file\n validates :credentials_file, type: String\n\n # @return [String, nil] Your GCP project ID\n attribute :project_id\n validates :project_id, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6878654956817627, "alphanum_fraction": 0.6951754093170166, "avg_line_length": 46.17241287231445, "blob_id": "0491cbeb590f36dd3379c0aa9948ec9c6f09ec31", "content_id": "55f259e7bca3c381f50814f4d70425e4ed133399", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1368, "license_type": "permissive", "max_line_length": 276, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_cifs.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or destroy or modify(path) cifs-share on ONTAP\n class Na_ontap_cifs < Base\n # @return [String, nil] The file system path that is shared through this CIFS share. The path is the full, user visible path relative to the vserver root, and it might be crossing junction mount points. The path is in UTF8 and uses forward slash as directory separator\n attribute :path\n validates :path, type: String\n\n # @return [String] Vserver containing the CIFS share.\n attribute :vserver\n validates :vserver, presence: true, type: String\n\n # @return [String] The name of the CIFS share. The CIFS share name is a UTF-8 string with the following characters being illegal; control characters from 0x00 to 0x1F, both inclusive, 0x22 (double quotes)\n attribute :share_name\n validates :share_name, presence: true, type: String\n\n # @return [:present, :absent, nil] Whether the specified CIFS share should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6931408047676086, "alphanum_fraction": 0.6931408047676086, "avg_line_length": 56.02941131591797, "blob_id": "17b6421fee61c3959e92c1c67e784751fc7368a0", "content_id": "14b6a5f62725bc10926e88faa4a93af1b6654e05", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1939, "license_type": "permissive", "max_line_length": 345, "num_lines": 34, "path": "/lib/ansible/ruby/modules/generated/system/nosh.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Control running and enabled state for system-wide or user services.\n # BSD and Linux systems are supported.\n class Nosh < Base\n # @return [String] Name of the service to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:started, :stopped, :reset, :restarted, :reloaded, nil] C(started)/C(stopped) are idempotent actions that will not run commands unless necessary. C(restarted) will always bounce the service. C(reloaded) will send a SIGHUP or start the service. C(reset) will start or stop the service according to whether it is enabled or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:started, :stopped, :reset, :restarted, :reloaded], :message=>\"%{value} needs to be :started, :stopped, :reset, :restarted, :reloaded\"}, allow_nil: true\n\n # @return [Symbol, nil] Enable or disable the service, independently of C(*.preset) file preference or running state. Mutually exclusive with I(preset). Will take effect prior to I(state=reset).\n attribute :enabled\n validates :enabled, type: Symbol\n\n # @return [Symbol, nil] Enable or disable the service according to local preferences in *.preset files. Mutually exclusive with I(enabled). Only has an effect if set to true. Will take effect prior to I(state=reset).\n attribute :preset\n validates :preset, type: Symbol\n\n # @return [:yes, :no, nil] Run system-control talking to the calling user's service manager, rather than the system-wide service manager.\n attribute :user\n validates :user, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7274606823921204, "alphanum_fraction": 0.7274606823921204, "avg_line_length": 73.4000015258789, "blob_id": "560f81003ce9742211335fed5403b0e803914c0d", "content_id": "93fbf68d96eee87f285a028abca757a9c014f58e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4836, "license_type": "permissive", "max_line_length": 781, "num_lines": 65, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_storage_bucket.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The Buckets resource represents a bucket in Google Cloud Storage. There is a single global namespace shared by all buckets. For more information, see Bucket Name Requirements.\n # Buckets contain objects which can be accessed by their own methods. In addition to the acl property, buckets contain bucketAccessControls, for use in fine-grained manipulation of an existing bucket's access controls.\n # A bucket is always owned by the project team owners group.\n class Gcp_storage_bucket < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Access controls on the bucket.\n attribute :acl\n\n # @return [Object, nil] The bucket's Cross-Origin Resource Sharing (CORS) configuration.\n attribute :cors\n\n # @return [Object, nil] Default access controls to apply to new objects when no ACL is provided.\n attribute :default_object_acl\n\n # @return [Object, nil] The bucket's lifecycle configuration.,See U(https://developers.google.com/storage/docs/lifecycle) for more information.\n attribute :lifecycle\n\n # @return [Object, nil] The location of the bucket. Object data for objects in the bucket resides in physical storage within this region. Defaults to US. See the developer's guide for the authoritative list.\n attribute :location\n\n # @return [Object, nil] The bucket's logging configuration, which defines the destination bucket and optional name prefix for the current bucket's logs.\n attribute :logging\n\n # @return [Object, nil] The metadata generation of this bucket.\n attribute :metageneration\n\n # @return [String, nil] The name of the bucket.\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] The owner of the bucket. This is always the project team's owner group.\n attribute :owner\n\n # @return [:MULTI_REGIONAL, :REGIONAL, :STANDARD, :NEARLINE, :COLDLINE, :DURABLE_REDUCED_AVAILABILITY, nil] The bucket's default storage class, used whenever no storageClass is specified for a newly-created object. This defines how objects in the bucket are stored and determines the SLA and the cost of storage.,Values include MULTI_REGIONAL, REGIONAL, STANDARD, NEARLINE, COLDLINE, and DURABLE_REDUCED_AVAILABILITY. If this value is not specified when the bucket is created, it will default to STANDARD. For more information, see storage classes.\n attribute :storage_class\n validates :storage_class, expression_inclusion: {:in=>[:MULTI_REGIONAL, :REGIONAL, :STANDARD, :NEARLINE, :COLDLINE, :DURABLE_REDUCED_AVAILABILITY], :message=>\"%{value} needs to be :MULTI_REGIONAL, :REGIONAL, :STANDARD, :NEARLINE, :COLDLINE, :DURABLE_REDUCED_AVAILABILITY\"}, allow_nil: true\n\n # @return [Object, nil] The bucket's versioning configuration.\n attribute :versioning\n\n # @return [Object, nil] The bucket's website configuration, controlling how the service behaves when accessing bucket contents as a web site. See the Static Website Examples for more information.\n attribute :website\n\n # @return [String, nil] A valid API project identifier.\n attribute :project\n validates :project, type: String\n\n # @return [:authenticatedRead, :bucketOwnerFullControl, :bucketOwnerRead, :private, :projectPrivate, :publicRead, nil] Apply a predefined set of default object access controls to this bucket.,Acceptable values are: - \"authenticatedRead\": Object owner gets OWNER access, and allAuthenticatedUsers get READER access.,- \"bucketOwnerFullControl\": Object owner gets OWNER access, and project team owners get OWNER access.,- \"bucketOwnerRead\": Object owner gets OWNER access, and project team owners get READER access.,- \"private\": Object owner gets OWNER access.,- \"projectPrivate\": Object owner gets OWNER access, and project team members get access according to their roles.,- \"publicRead\": Object owner gets OWNER access, and allUsers get READER access.\n attribute :predefined_default_object_acl\n validates :predefined_default_object_acl, expression_inclusion: {:in=>[:authenticatedRead, :bucketOwnerFullControl, :bucketOwnerRead, :private, :projectPrivate, :publicRead], :message=>\"%{value} needs to be :authenticatedRead, :bucketOwnerFullControl, :bucketOwnerRead, :private, :projectPrivate, :publicRead\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6487748026847839, "alphanum_fraction": 0.6557759642601013, "avg_line_length": 50.93939208984375, "blob_id": "af5a81a12c2e3f3b41e6697c911b462a5fd5a333", "content_id": "373cb8895ac19f15e54e950abba794c90194e786", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1714, "license_type": "permissive", "max_line_length": 372, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/network/vyos/vyos_linkagg.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of link aggregation groups on VyOS network devices.\n class Vyos_linkagg < Base\n # @return [String] Name of the link aggregation group.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:\"802.3ad\", :\"active-backup\", :broadcast, :\"round-robin\", :\"transmit-load-balance\", :\"adaptive-load-balance\", :\"xor-hash\", :on, nil] Mode of the link aggregation group.\n attribute :mode\n validates :mode, expression_inclusion: {:in=>[:\"802.3ad\", :\"active-backup\", :broadcast, :\"round-robin\", :\"transmit-load-balance\", :\"adaptive-load-balance\", :\"xor-hash\", :on], :message=>\"%{value} needs to be :\\\"802.3ad\\\", :\\\"active-backup\\\", :broadcast, :\\\"round-robin\\\", :\\\"transmit-load-balance\\\", :\\\"adaptive-load-balance\\\", :\\\"xor-hash\\\", :on\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] List of members of the link aggregation group.\n attribute :members\n validates :members, type: TypeGeneric.new(String)\n\n # @return [Array<Hash>, Hash, nil] List of link aggregation definitions.\n attribute :aggregate\n validates :aggregate, type: TypeGeneric.new(Hash)\n\n # @return [:present, :absent, :up, :down, nil] State of the link aggregation group.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :up, :down], :message=>\"%{value} needs to be :present, :absent, :up, :down\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6897391080856323, "alphanum_fraction": 0.6897391080856323, "avg_line_length": 52.24074172973633, "blob_id": "f1f4926f95fff9d8df1910de8358a6d1da64700a", "content_id": "c6765f7d6d558caba03fb90432b475495557ddc2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2875, "license_type": "permissive", "max_line_length": 192, "num_lines": 54, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_config_rollback.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Provides rollback and rollback preview functionality for Cisco ACI fabrics.\n # Config Rollbacks are done using snapshots C(aci_snapshot) with the configImportP class.\n class Aci_config_rollback < Base\n # @return [String, nil] The export policy that the C(compare_snapshot) is associated to.\n attribute :compare_export_policy\n validates :compare_export_policy, type: String\n\n # @return [String, nil] The name of the snapshot to compare with C(snapshot).\n attribute :compare_snapshot\n validates :compare_snapshot, type: String\n\n # @return [String, nil] The description for the Import Policy.\n attribute :description\n validates :description, type: String\n\n # @return [String] The export policy that the C(snapshot) is associated to.\n attribute :export_policy\n validates :export_policy, presence: true, type: String\n\n # @return [Symbol, nil] Determines if the APIC should fail the rollback if unable to decrypt secured data.,The APIC defaults to C(yes) when unset.\n attribute :fail_on_decrypt\n validates :fail_on_decrypt, type: Symbol\n\n # @return [:atomic, :\"best-effort\", nil] Determines how the import should be handled by the APIC.,The APIC defaults to C(atomic) when unset.\n attribute :import_mode\n validates :import_mode, expression_inclusion: {:in=>[:atomic, :\"best-effort\"], :message=>\"%{value} needs to be :atomic, :\\\"best-effort\\\"\"}, allow_nil: true\n\n # @return [String, nil] The name of the Import Policy to use for config rollback.\n attribute :import_policy\n validates :import_policy, type: String\n\n # @return [:merge, :replace, nil] Determines how the current and snapshot configuration should be compared for replacement.,The APIC defaults to C(replace) when unset.\n attribute :import_type\n validates :import_type, expression_inclusion: {:in=>[:merge, :replace], :message=>\"%{value} needs to be :merge, :replace\"}, allow_nil: true\n\n # @return [String] The name of the snapshot to rollback to, or the base snapshot to use for comparison.,The C(aci_snapshot) module can be used to query the list of available snapshots.\n attribute :snapshot\n validates :snapshot, presence: true, type: String\n\n # @return [:preview, :rollback, nil] Use C(preview) for previewing the diff between two snapshots.,Use C(rollback) for reverting the configuration to a previous snapshot.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:preview, :rollback], :message=>\"%{value} needs to be :preview, :rollback\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7153317928314209, "alphanum_fraction": 0.7172539830207825, "avg_line_length": 79.33087921142578, "blob_id": "74697773ceeb6ce42866f93ee5e2b9a8671b0c58", "content_id": "7e956194f1b262223baf6c590340da1f00612868", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 10925, "license_type": "permissive", "max_line_length": 666, "num_lines": 136, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_virtualmachine.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, stop and start a virtual machine. Provide an existing storage account and network interface or allow the module to create these for you. If you choose not to provide a network interface, the resource group must contain a virtual network with at least one subnet.\n # Before Ansible 2.5, this required an image found in the Azure Marketplace which can be discovered with M(azure_rm_virtualmachineimage_facts). In Ansible 2.5 and newer, custom images can be used as well, see the examples for more details.\n class Azure_rm_virtualmachine < Base\n # @return [String, NilClass] Name of the resource group containing the virtual machine.\n attribute :resource_group\n validates :resource_group, presence: true, type: MultipleTypes.new(String, NilClass)\n\n # @return [String] Name of the virtual machine.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Data which is made available to the virtual machine and used by e.g., cloud-init.\n attribute :custom_data\n\n # @return [:absent, :present, nil] Assert the state of the virtual machine.,State 'present' will check that the machine exists with the requested configuration. If the configuration of the existing machine does not match, the machine will be updated. Use options started, allocated and restarted to change the machine's power state.,State 'absent' will remove the virtual machine.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [Boolean, nil] Use with state 'present' to start the machine. Set to false to have the machine be 'stopped'.\n attribute :started\n validates :started, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Toggle that controls if the machine is allocated/deallocated, only useful with state='present'.\n attribute :allocated\n validates :allocated, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Symbol, nil] Use with state 'present' to restart a running VM.\n attribute :restarted\n validates :restarted, type: Symbol\n\n # @return [Object, nil] Valid Azure location. Defaults to location of the resource group.\n attribute :location\n\n # @return [Object, nil] Name assigned internally to the host. On a linux VM this is the name returned by the `hostname` command. When creating a virtual machine, short_hostname defaults to name.\n attribute :short_hostname\n\n # @return [String, nil] A valid Azure VM size value. For example, 'Standard_D4'. The list of choices varies depending on the subscription and location. Check your subscription for available choices. Required when creating a VM.\n attribute :vm_size\n validates :vm_size, type: String\n\n # @return [String, nil] Admin username used to access the host after it is created. Required when creating a VM.\n attribute :admin_username\n validates :admin_username, type: String\n\n # @return [String, nil] Password for the admin username. Not required if the os_type is Linux and SSH password authentication is disabled by setting ssh_password_enabled to false.\n attribute :admin_password\n validates :admin_password, type: String\n\n # @return [Boolean, nil] When the os_type is Linux, setting ssh_password_enabled to false will disable SSH password authentication and require use of SSH keys.\n attribute :ssh_password_enabled\n validates :ssh_password_enabled, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash, nil] For os_type Linux provide a list of SSH keys. Each item in the list should be a dictionary where the dictionary contains two keys: path and key_data. Set the path to the default location of the authorized_keys files. On an Enterprise Linux host, for example, the path will be /home/<admin username>/.ssh/authorized_keys. Set key_data to the actual value of the public key.\n attribute :ssh_public_keys\n validates :ssh_public_keys, type: TypeGeneric.new(Hash)\n\n # @return [Hash, String] Specifies the image used to build the VM.,If a string, the image is sourced from a custom image based on the name.,If a dict with the keys C(publisher), C(offer), C(sku), and C(version), the image is sourced from a Marketplace image. NOTE: set image.version to C(latest) to get the most recent version of a given image.,If a dict with the keys C(name) and C(resource_group), the image is sourced from a custom image based on the C(name) and C(resource_group) set. NOTE: the key C(resource_group) is optional and if omitted, all images in the subscription will be searched for by C(name).,Custom image support was added in Ansible 2.5\n attribute :image\n validates :image, presence: true, type: MultipleTypes.new(Hash, String)\n\n # @return [String, nil] Name or ID of an existing availability set to add the VM to. The availability_set should be in the same resource group as VM.\n attribute :availability_set\n validates :availability_set, type: String\n\n # @return [Object, nil] Name of an existing storage account that supports creation of VHD blobs. If not specified for a new VM, a new storage account named <vm name>01 will be created using storage type 'Standard_LRS'.\n attribute :storage_account_name\n\n # @return [String, nil] Name of the container to use within the storage account to store VHD blobs. If no name is specified a default container will created.\n attribute :storage_container_name\n validates :storage_container_name, type: String\n\n # @return [Object, nil] Name fo the storage blob used to hold the VM's OS disk image. If no name is provided, defaults to the VM name + '.vhd'. If you provide a name, it must end with '.vhd'\n attribute :storage_blob_name\n\n # @return [:Standard_LRS, :Premium_LRS, nil] Managed OS disk type\n attribute :managed_disk_type\n validates :managed_disk_type, expression_inclusion: {:in=>[:Standard_LRS, :Premium_LRS], :message=>\"%{value} needs to be :Standard_LRS, :Premium_LRS\"}, allow_nil: true\n\n # @return [:ReadOnly, :ReadWrite, nil] Type of OS disk caching.\n attribute :os_disk_caching\n validates :os_disk_caching, expression_inclusion: {:in=>[:ReadOnly, :ReadWrite], :message=>\"%{value} needs to be :ReadOnly, :ReadWrite\"}, allow_nil: true\n\n # @return [Integer, nil] Type of OS disk size in GB.\n attribute :os_disk_size_gb\n validates :os_disk_size_gb, type: Integer\n\n # @return [:Windows, :Linux, nil] Base type of operating system.\n attribute :os_type\n validates :os_type, expression_inclusion: {:in=>[:Windows, :Linux], :message=>\"%{value} needs to be :Windows, :Linux\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash, nil] Describes list of data disks.\n attribute :data_disks\n validates :data_disks, type: TypeGeneric.new(Hash)\n\n # @return [:Dynamic, :Static, :Disabled, nil] If a public IP address is created when creating the VM (because a Network Interface was not provided), determines if the public IP address remains permanently associated with the Network Interface. If set to 'Dynamic' the public IP address may change any time the VM is rebooted or power cycled.,The C(Disabled) choice was added in Ansible 2.6.\n attribute :public_ip_allocation_method\n validates :public_ip_allocation_method, expression_inclusion: {:in=>[:Dynamic, :Static, :Disabled], :message=>\"%{value} needs to be :Dynamic, :Static, :Disabled\"}, allow_nil: true\n\n # @return [Object, nil] If a network interface is created when creating the VM, a security group will be created as well. For Linux hosts a rule will be added to the security group allowing inbound TCP connections to the default SSH port 22, and for Windows hosts ports 3389 and 5986 will be opened. Override the default open ports by providing a list of ports.\n attribute :open_ports\n\n # @return [Object, nil] List of existing network interface names to add to the VM.,Item can be a str of name or resource id of the network interface.,Item can also be a dict contains C(resource_group) and C(name) of the network interface.,If a network interface name is not provided when the VM is created, a default network interface will be created.,In order for the module to create a new network interface, at least one Virtual Network with one Subnet must exist.\n attribute :network_interface_names\n\n # @return [Object, nil] When creating a virtual machine, if a specific virtual network from another resource group should be used, use this parameter to specify the resource group to use.\n attribute :virtual_network_resource_group\n\n # @return [Object, nil] When creating a virtual machine, if a network interface name is not provided, one will be created.,The network interface will be assigned to the first virtual network found in the resource group.,Use this parameter to provide a specific virtual network instead.,If the virtual network in in another resource group, specific resource group by C(virtual_network_resource_group).\n attribute :virtual_network_name\n\n # @return [Object, nil] When creating a virtual machine, if a network interface name is not provided, one will be created.,The new network interface will be assigned to the first subnet found in the virtual network.,Use this parameter to provide a specific subnet instead.,If the subnet is in another resource group, specific resource group by C(virtual_network_resource_group).\n attribute :subnet_name\n\n # @return [String, nil] When removing a VM using state 'absent', also remove associated resources,It can be 'all' or a list with any of the following: ['network_interfaces', 'virtual_storage', 'public_ips'],Any other input will be ignored\n attribute :remove_on_absent\n validates :remove_on_absent, type: String\n\n # @return [Hash, nil] A dictionary describing a third-party billing plan for an instance\n attribute :plan\n validates :plan, type: Hash\n\n # @return [Symbol, nil] Accept terms for marketplace images that require it,Only Azure service admin/account admin users can purchase images from the marketplace\n attribute :accept_terms\n validates :accept_terms, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6585695147514343, "alphanum_fraction": 0.6612685322761536, "avg_line_length": 40.16666793823242, "blob_id": "f8d00190e684eb21fe516c1123f090803ba5a41a", "content_id": "ba922e1ff49e2a08397b6b5fc546ce26cc6007cc", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1482, "license_type": "permissive", "max_line_length": 173, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/cloud/univention/udm_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows to manage user groups on a univention corporate server (UCS). It uses the python API of the UCS to create a new object or edit it.\n class Udm_group < Base\n # @return [:present, :absent, nil] Whether the group is present or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] Name of the posix group.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Group description.\n attribute :description\n\n # @return [Array<String>, String, nil] define the whole ldap position of the group, e.g. C(cn=g123m-1A,cn=classes,cn=schueler,cn=groups,ou=schule,dc=example,dc=com).\n attribute :position\n validates :position, type: TypeGeneric.new(String)\n\n # @return [String, nil] LDAP OU, e.g. school for LDAP OU C(ou=school,dc=example,dc=com).\n attribute :ou\n validates :ou, type: String\n\n # @return [Array<String>, String, nil] Subpath inside the OU, e.g. C(cn=classes,cn=students,cn=groups).\n attribute :subpath\n validates :subpath, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7265486717224121, "alphanum_fraction": 0.7265486717224121, "avg_line_length": 85.92308044433594, "blob_id": "0f45dc4d0e84cb4f02807c5c51964c09f1cc54d7", "content_id": "1832426042dd2a81d6817fad32c0fe2ecebb2c6f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3390, "license_type": "permissive", "max_line_length": 431, "num_lines": 39, "path": "/lib/ansible/ruby/modules/generated/network/asa/asa_acl.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows you to work with access-lists on a Cisco ASA device.\n class Asa_acl < Base\n # @return [Array<String>, String] The ordered set of commands that should be configured in the section. The commands must be the exact same commands as found in the device running-config. Be sure to note the configuration command syntax as some commands are automatically modified by the device config parser.\n attribute :lines\n validates :lines, presence: true, type: TypeGeneric.new(String)\n\n # @return [String, nil] The ordered set of commands to push on to the command stack if a change needs to be made. This allows the playbook designer the opportunity to perform configuration commands prior to pushing any changes without affecting how the set of commands are matched against the system.\n attribute :before\n validates :before, type: String\n\n # @return [Object, nil] The ordered set of commands to append to the end of the command stack if a changed needs to be made. Just like with I(before) this allows the playbook designer to append a set of commands to be executed after the command set.\n attribute :after\n\n # @return [:line, :strict, :exact, nil] Instructs the module on the way to perform the matching of the set of commands against the current device config. If match is set to I(line), commands are matched line by line. If match is set to I(strict), command lines are matched with respect to position. Finally if match is set to I(exact), command lines must be an equal match.\n attribute :match\n validates :match, expression_inclusion: {:in=>[:line, :strict, :exact], :message=>\"%{value} needs to be :line, :strict, :exact\"}, allow_nil: true\n\n # @return [:line, :block, nil] Instructs the module on the way to perform the configuration on the device. If the replace argument is set to I(line) then the modified lines are pushed to the device in configuration mode. If the replace argument is set to I(block) then the entire command block is pushed to the device in configuration mode if any line is not correct.\n attribute :replace\n validates :replace, expression_inclusion: {:in=>[:line, :block], :message=>\"%{value} needs to be :line, :block\"}, allow_nil: true\n\n # @return [:yes, :no, nil] The force argument instructs the module to not consider the current devices running-config. When set to true, this will cause the module to push the contents of I(src) into the device without first checking if already configured.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] The module, by default, will connect to the remote device and retrieve the current running-config to use as a base for comparing against the contents of source. There are times when it is not desirable to have the task get the current running-config for every task in a playbook. The I(config) argument allows the implementer to pass in the configuruation to use as the base config for comparison.\n attribute :config\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.704059362411499, "alphanum_fraction": 0.7044958472251892, "avg_line_length": 54.878047943115234, "blob_id": "9467c1e885e255d67dcfd4f93850ae0080a54075", "content_id": "a0a0faa81454fd9e47c6fb381c36433c41af376e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2291, "license_type": "permissive", "max_line_length": 304, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_subnet.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update or delete a subnet within a given virtual network. Allows setting and updating the address prefix CIDR, which must be valid within the context of the virtual network. Use the azure_rm_networkinterface module to associate interfaces with the subnet and assign specific IP addresses.\n class Azure_rm_subnet < Base\n # @return [String] Name of resource group.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] Name of the subnet.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] CIDR defining the IPv4 address space of the subnet. Must be valid within the context of the virtual network.\n attribute :address_prefix_cidr\n validates :address_prefix_cidr, presence: true, type: String\n\n # @return [Hash, nil] Existing security group with which to associate the subnet.,It can be the security group name which is in the same resource group.,It can be the resource Id.,It can be a dict which contains C(name) and C(resource_group) of the security group.\n attribute :security_group\n validates :security_group, type: Hash\n\n # @return [:absent, :present, nil] Assert the state of the subnet. Use 'present' to create or update a subnet and 'absent' to delete a subnet.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String] Name of an existing virtual network with which the subnet is or will be associated.\n attribute :virtual_network_name\n validates :virtual_network_name, presence: true, type: String\n\n # @return [String, nil] The reference of the RouteTable resource.,It can accept both a str or a dict.,The str can be the name or resource id of the route table.,The dict can contains C(name) and C(resource_group) of the route_table.\n attribute :route_table\n validates :route_table, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6770601272583008, "alphanum_fraction": 0.6770601272583008, "avg_line_length": 25.41176414489746, "blob_id": "3e5e3e7e3f251741ed76854e7dbc165bccb03a18", "content_id": "d755a0b309a283f5cf8d0e4a8a453fc7717be22e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 449, "license_type": "permissive", "max_line_length": 64, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_evpn_global.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Handles the EVPN control plane for VXLAN.\n class Nxos_evpn_global < Base\n # @return [Symbol] EVPN control plane.\n attribute :nv_overlay_evpn\n validates :nv_overlay_evpn, presence: true, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6977346539497375, "alphanum_fraction": 0.7003236413002014, "avg_line_length": 47.28125, "blob_id": "0a221888dd03ff9e43af41ec1033d769656b8bdf", "content_id": "83392e6828c39f76be2690805ead3aa529097ce1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1545, "license_type": "permissive", "max_line_length": 214, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_dns_managed_zone.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # A zone is a subtree of the DNS namespace under one administrative responsibility. A ManagedZone is a resource that represents a DNS zone hosted by the Cloud DNS service.\n class Gcp_dns_managed_zone < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] A mutable string of at most 1024 characters associated with this resource for the user's convenience. Has no effect on the managed zone's function.\n attribute :description\n validates :description, type: String\n\n # @return [String, nil] The DNS name of this managed zone, for instance \"example.com.\".\n attribute :dns_name\n validates :dns_name, type: String\n\n # @return [String] User assigned name for this resource.,Must be unique within the project.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Optionally specifies the NameServerSet for this ManagedZone. A NameServerSet is a set of DNS name servers that all host the same ManagedZones. Most users will leave this field unset.\n attribute :name_server_set\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6849817037582397, "alphanum_fraction": 0.6990231871604919, "avg_line_length": 57.5, "blob_id": "fc4f4bb2b33b86b8faee165194227356d409eb32", "content_id": "45ee0f57c044fd5271427f66a976c38889cc8e0f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1638, "license_type": "permissive", "max_line_length": 464, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_compute_global_address.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Represents a Global Address resource. Global addresses are used for HTTP(S) load balancing.\n class Gcp_compute_global_address < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] An optional description of this resource.,Provide this property when you create the resource.\n attribute :description\n\n # @return [String] Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:IPV4, :IPV6, nil] The IP Version that will be used by this address. Valid options are IPV4 or IPV6. The default value is IPV4.\n attribute :ip_version\n validates :ip_version, expression_inclusion: {:in=>[:IPV4, :IPV6], :message=>\"%{value} needs to be :IPV4, :IPV6\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6740932464599609, "alphanum_fraction": 0.6777201890945435, "avg_line_length": 46.07316970825195, "blob_id": "a88098962e8792b3f61ca8d86db90f11617ba18b", "content_id": "cd04ca69f5f97e4968393449b897eceffdc52e6a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1930, "license_type": "permissive", "max_line_length": 249, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/cloud/centurylink/clc_alert_policy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # An Ansible module to Create or Delete Alert Policies at CenturyLink Cloud.\n class Clc_alert_policy < Base\n # @return [Object] The alias of your CLC Account\n attribute :alias\n validates :alias, presence: true\n\n # @return [String, nil] The name of the alert policy. This is mutually exclusive with id\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] The alert policy id. This is mutually exclusive with name\n attribute :id\n\n # @return [Object, nil] A list of recipient email ids to notify the alert. This is required for state 'present'\n attribute :alert_recipients\n\n # @return [:cpu, :memory, :disk, nil] The metric on which to measure the condition that will trigger the alert. This is required for state 'present'\n attribute :metric\n validates :metric, expression_inclusion: {:in=>[:cpu, :memory, :disk], :message=>\"%{value} needs to be :cpu, :memory, :disk\"}, allow_nil: true\n\n # @return [Object, nil] The length of time in minutes that the condition must exceed the threshold. This is required for state 'present'\n attribute :duration\n\n # @return [Object, nil] The threshold that will trigger the alert when the metric equals or exceeds it. This is required for state 'present' This number represents a percentage and must be a value between 5.0 - 95.0 that is a multiple of 5.0\n attribute :threshold\n\n # @return [:present, :absent, nil] Whether to create or delete the policy.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6718186736106873, "alphanum_fraction": 0.672333836555481, "avg_line_length": 43.1136360168457, "blob_id": "ceba138b8afece555c8683fde2d1525f9823a063", "content_id": "c5beb5f5a0e97ad460205ec8f1c09fd507371265", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1941, "license_type": "permissive", "max_line_length": 153, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_glue_connection.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage an AWS Glue connection. See U(https://aws.amazon.com/glue/) for details.\n class Aws_glue_connection < Base\n # @return [Object, nil] The ID of the Data Catalog in which to create the connection. If none is supplied, the AWS account ID is used by default.\n attribute :catalog_id\n\n # @return [Hash] A dict of key-value pairs used as parameters for this connection.\n attribute :connection_properties\n validates :connection_properties, presence: true, type: Hash\n\n # @return [:JDBC, :SFTP, nil] The type of the connection. Currently, only JDBC is supported; SFTP is not supported.\n attribute :connection_type\n validates :connection_type, expression_inclusion: {:in=>[:JDBC, :SFTP], :message=>\"%{value} needs to be :JDBC, :SFTP\"}, allow_nil: true\n\n # @return [Object, nil] The description of the connection.\n attribute :description\n\n # @return [Object, nil] A list of UTF-8 strings that specify the criteria that you can use in selecting this connection.\n attribute :match_criteria\n\n # @return [String] The name of the connection.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] A list of security groups to be used by the connection. Use either security group name or ID.\n attribute :security_groups\n\n # @return [:present, :absent] Create or delete the AWS Glue connection.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [Object, nil] The subnet ID used by the connection.\n attribute :subnet_id\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6651583909988403, "alphanum_fraction": 0.6651583909988403, "avg_line_length": 36.61701965332031, "blob_id": "ea4ebb2ee969b89e9d1077e19d7623dbacd75854", "content_id": "960083a5ad2ac6230a549f22341311a3a6cfa5d8", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1768, "license_type": "permissive", "max_line_length": 173, "num_lines": 47, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_elementsw_vlan.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, delete, modify VLAN\n class Na_elementsw_vlan < Base\n # @return [:present, :absent, nil] Whether the specified vlan should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Integer] Virtual Network Tag\n attribute :vlan_tag\n validates :vlan_tag, presence: true, type: Integer\n\n # @return [String, nil] User defined name for the new VLAN,Name of the vlan is unique,Required for create\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] Storage virtual IP which is unique,Required for create\n attribute :svip\n validates :svip, type: String\n\n # @return [Array<Hash>, Hash, nil] List of address blocks for the VLAN,Each address block contains the starting IP address and size for the block,Required for create\n attribute :address_blocks\n validates :address_blocks, type: TypeGeneric.new(Hash)\n\n # @return [String, nil] Netmask for the VLAN,Required for create\n attribute :netmask\n validates :netmask, type: String\n\n # @return [Object, nil] Gateway for the VLAN\n attribute :gateway\n\n # @return [Symbol, nil] Enable or disable namespaces\n attribute :namespace\n validates :namespace, type: Symbol\n\n # @return [Object, nil] Dictionary of attributes with name and value for each attribute\n attribute :attributes\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6991434693336487, "alphanum_fraction": 0.6991434693336487, "avg_line_length": 39.60869598388672, "blob_id": "b182b6ac0ba6c7c5f372af9ba89b8a51f6d1a56d", "content_id": "f1cbcb2d080e1c7e1231a5d84a5e8cc4b8c37a05", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 934, "license_type": "permissive", "max_line_length": 177, "num_lines": 23, "path": "/lib/ansible/ruby/modules/generated/windows/win_reg_stat.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Like M(win_file), M(win_reg_stat) will return whether the key/property exists.\n # It also returns the sub keys and properties of the key specified.\n # If specifying a property name through I(property), it will return the information specific for that property.\n class Win_reg_stat < Base\n # @return [String] The full registry key path including the hive to search for.\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [String, nil] The registry property name to get information for, the return json will not include the sub_keys and properties entries for the I(key) specified.\n attribute :name\n validates :name, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6933101415634155, "alphanum_fraction": 0.6933101415634155, "avg_line_length": 47.978721618652344, "blob_id": "029b91ee37154dc84ab47d24e14ce22e8a9dfa23", "content_id": "a3f0603ece547e520c372f2121d1312d3c857f2b", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2302, "license_type": "permissive", "max_line_length": 251, "num_lines": 47, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_sys_global.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage BIG-IP global settings.\n class Bigip_sys_global < Base\n # @return [Object, nil] Specifies the text to present in the advisory banner.\n attribute :banner_text\n\n # @return [Object, nil] Specifies the number of seconds of inactivity before the system logs off a user that is logged on.\n attribute :console_timeout\n\n # @return [Symbol, nil] C(enable) or C(disabled) the Setup utility in the browser-based Configuration utility.\n attribute :gui_setup\n validates :gui_setup, type: Symbol\n\n # @return [Symbol, nil] Specifies, when C(enabled), that the system menu displays on the LCD screen on the front of the unit. This setting has no effect when used on the VE platform.\n attribute :lcd_display\n validates :lcd_display, type: Symbol\n\n # @return [Symbol, nil] Specifies whether or not to enable DHCP client on the management interface\n attribute :mgmt_dhcp\n validates :mgmt_dhcp, type: Symbol\n\n # @return [Symbol, nil] Specifies, when C(enabled), that the next time you reboot the system, the system boots to an ISO image on the network, rather than an internal media drive.\n attribute :net_reboot\n validates :net_reboot, type: Symbol\n\n # @return [Symbol, nil] Specifies, when C(enabled), that the system suppresses informational text on the console during the boot cycle. When C(disabled), the system presents messages and informational text on the console during the boot cycle.\n attribute :quiet_boot\n validates :quiet_boot, type: Symbol\n\n # @return [Symbol, nil] Specifies whether the system displays an advisory message on the login screen.\n attribute :security_banner\n validates :security_banner, type: Symbol\n\n # @return [:present, nil] The state of the variable on the system. When C(present), guarantees that an existing variable is set to C(value).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present], :message=>\"%{value} needs to be :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7228816747665405, "alphanum_fraction": 0.7232910394668579, "avg_line_length": 65.02702331542969, "blob_id": "e38cfdeca786d06be3be5c4a6118ca08bb6ba14c", "content_id": "392b0e3700f5ea1917a23e52c6631e4e86106f2b", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2443, "license_type": "permissive", "max_line_length": 689, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_profile_udp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage UDP profiles on a BIG-IP. Many of UDP profiles exist; each with their own adjustments to the standard C(udp) profile. Users of this module should be aware that many of the adjustable knobs have no module default. Instead, the default is assigned by the BIG-IP system itself which, in most cases, is acceptable.\n class Bigip_profile_udp < Base\n # @return [String] Specifies the name of the profile.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Specifies the profile from which this profile inherits settings.,When creating a new profile, if this parameter is not specified, the default is the system-supplied C(udp) profile.\n attribute :parent\n validates :parent, type: String\n\n # @return [Integer, nil] Specifies the length of time that a connection is idle (has no traffic) before the connection is eligible for deletion.,When creating a new profile, if this parameter is not specified, the remote device will choose a default value appropriate for the profile, based on its C(parent) profile.,When a number is specified, indicates the number of seconds that the UDP connection can remain idle before the system deletes it.,When C(0), or C(indefinite), specifies that UDP connections can remain idle indefinitely.,When C(immediate), specifies that you do not want the UDP connection to remain idle, and that it is therefore immediately eligible for deletion.\n attribute :idle_timeout\n validates :idle_timeout, type: Integer\n\n # @return [Symbol, nil] Specifies, when C(yes), that the system load balances UDP traffic packet-by-packet.\n attribute :datagram_load_balancing\n validates :datagram_load_balancing, type: Symbol\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [:present, :absent, nil] When C(present), ensures that the profile exists.,When C(absent), ensures the profile is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7374328970909119, "alphanum_fraction": 0.7403611540794373, "avg_line_length": 67.30000305175781, "blob_id": "cfacd611a814dafc76d89e989254796894e18de5", "content_id": "fb4258a5fa73a601c6107eea412238c0e9adbcca", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2049, "license_type": "permissive", "max_line_length": 373, "num_lines": 30, "path": "/lib/ansible/ruby/modules/generated/network/sros/sros_rollback.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configure the rollback feature on remote Nokia devices running the SR OS operating system. this module provides a stateful implementation for managing the configuration of the rollback feature\n class Sros_rollback < Base\n # @return [String, nil] The I(rollback_location) specifies the location and filename of the rollback checkpoint files. This argument supports any valid local or remote URL as specified in SR OS\n attribute :rollback_location\n validates :rollback_location, type: String\n\n # @return [Object, nil] The I(remote_max_checkpoints) argument configures the maximum number of rollback files that can be transferred and saved to a remote location. Valid values for this argument are in the range of 1 to 50\n attribute :remote_max_checkpoints\n\n # @return [Object, nil] The I(local_max_checkpoints) argument configures the maximum number of rollback files that can be saved on the devices local compact flash. Valid values for this argument are in the range of 1 to 50\n attribute :local_max_checkpoints\n\n # @return [Object, nil] The I(rescue_location) specifies the location of the rescue file. This argument supports any valid local or remote URL as specified in SR OS\n attribute :rescue_location\n\n # @return [:present, :absent, nil] The I(state) argument specifies the state of the configuration entries in the devices active configuration. When the state value is set to C(true) the configuration is present in the devices active configuration. When the state value is set to C(false) the configuration values are removed from the devices active configuration.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6758034229278564, "alphanum_fraction": 0.6758034229278564, "avg_line_length": 34.266666412353516, "blob_id": "39084d1294514de75fe7779a6076633fe8fd9f4c", "content_id": "0c55c0752a507f16b8b309957d41f42f2756f029", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1058, "license_type": "permissive", "max_line_length": 144, "num_lines": 30, "path": "/lib/ansible/ruby/modules/generated/network/nso/nso_action.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provices support for executing Cisco NSO actions and then verifying that the output is as expected.\n class Nso_action < Base\n # @return [String] Path to NSO action.\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [Object, nil] NSO action parameters.\\r\\n\n attribute :input\n\n # @return [Hash, nil] Required output parameters.\\r\\n\n attribute :output_required\n validates :output_required, type: Hash\n\n # @return [Object, nil] List of result parameter names that will cause the task to fail if they are present.\\r\\n\n attribute :output_invalid\n\n # @return [Object, nil] If set to true, the task will fail if any output parameters not in output_required is present in the output.\\r\\n\n attribute :validate_strict\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6926626563072205, "alphanum_fraction": 0.6965851187705994, "avg_line_length": 61.81159591674805, "blob_id": "140c3372747af3bf5480d7f359afed3fd2e8d489", "content_id": "ad6556811f530396f43fc17bdb70acd3e7156414", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4334, "license_type": "permissive", "max_line_length": 832, "num_lines": 69, "path": "/lib/ansible/ruby/modules/generated/packaging/language/maven_artifact.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Downloads an artifact from a maven repository given the maven coordinates provided to the module.\n # Can retrieve snapshots or release versions of the artifact and will resolve the latest available version if one is not available.\n class Maven_artifact < Base\n # @return [String] The Maven groupId coordinate\n attribute :group_id\n validates :group_id, presence: true, type: String\n\n # @return [String] The maven artifactId coordinate\n attribute :artifact_id\n validates :artifact_id, presence: true, type: String\n\n # @return [String, nil] The maven version coordinate\n attribute :version\n validates :version, type: String\n\n # @return [Object, nil] The maven classifier coordinate\n attribute :classifier\n\n # @return [String, nil] The maven type/extension coordinate\n attribute :extension\n validates :extension, type: String\n\n # @return [String, nil] The URL of the Maven Repository to download from.,Use s3://... if the repository is hosted on Amazon S3, added in version 2.2.,Use file://... if the repository is local, added in version 2.6\n attribute :repository_url\n validates :repository_url, type: String\n\n # @return [String, nil] The username to authenticate as to the Maven Repository. Use AWS secret key of the repository is hosted on S3\n attribute :username\n validates :username, type: String\n\n # @return [String, nil] The password to authenticate with to the Maven Repository. Use AWS secret access key of the repository is hosted on S3\n attribute :password\n validates :password, type: String\n\n # @return [String] The path where the artifact should be written to,If file mode or ownerships are specified and destination path already exists, they affect the downloaded file\n attribute :dest\n validates :dest, presence: true, type: String\n\n # @return [:present, :absent, nil] The desired state of the artifact\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Integer, nil] Specifies a timeout in seconds for the connection attempt\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated. This should only be set to C(no) when no other option exists.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(yes), the downloaded artifact's name is preserved, i.e the version number remains part of it.,This option only has effect when C(dest) is a directory and C(version) is set to C(latest).\n attribute :keep_name\n validates :keep_name, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:never, :download, :change, :always, nil] If C(never), the md5 checksum will never be downloaded and verified.,If C(download), the md5 checksum will be downloaded and verified only after artifact download. This is the default.,If C(change), the md5 checksum will be downloaded and verified if the destination already exist, to verify if they are identical. This was the behaviour before 2.6. Since it downloads the md5 before (maybe) downloading the artifact, and since some repository software, when acting as a proxy/cache, return a 404 error if the artifact has not been cached yet, it may fail unexpectedly. If you still need it, you should consider using C(always) instead - if you deal with a checksum, it is better to use it to verify integrity after download.,C(always) combines C(download) and C(change).\n attribute :verify_checksum\n validates :verify_checksum, expression_inclusion: {:in=>[:never, :download, :change, :always], :message=>\"%{value} needs to be :never, :download, :change, :always\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6737967729568481, "alphanum_fraction": 0.6737967729568481, "avg_line_length": 32, "blob_id": "ecc98150ed9b341d8f5e5a378675ea8a096658e8", "content_id": "e344b6e8986444daa50c1f1f34876a44eec8c4af", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 561, "license_type": "permissive", "max_line_length": 142, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/cloud/misc/cloud_init_data_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gathers facts by reading the status.json and result.json of cloud-init.\n class Cloud_init_data_facts < Base\n # @return [:status, :result, nil] Filter facts\n attribute :filter\n validates :filter, expression_inclusion: {:in=>[:status, :result], :message=>\"%{value} needs to be :status, :result\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6863764524459839, "alphanum_fraction": 0.688758909702301, "avg_line_length": 51.46590805053711, "blob_id": "e3187af231f8895251d2e3a672fcd253b5075d31", "content_id": "6ad635f93d273eb04914062d9aa1ece86c5af587", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4617, "license_type": "permissive", "max_line_length": 387, "num_lines": 88, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_lc.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Can create or delete AWS Autoscaling Configurations\n # Works with the ec2_asg module to manage Autoscaling Groups\n class Ec2_lc < Base\n # @return [:present, :absent, nil] Register or deregister the instance\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] Unique name for configuration\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] Instance type to use for the instance\n attribute :instance_type\n validates :instance_type, presence: true, type: String\n\n # @return [String, nil] The AMI unique identifier to be used for the group\n attribute :image_id\n validates :image_id, type: String\n\n # @return [String, nil] The SSH key name to be used for access to managed instances\n attribute :key_name\n validates :key_name, type: String\n\n # @return [Array<String>, String, nil] A list of security groups to apply to the instances. Since version 2.4 you can specify either security group names or IDs or a mix. Previous to 2.4, for VPC instances, specify security group IDs and for EC2-Classic, specify either security group names or IDs.\n attribute :security_groups\n validates :security_groups, type: TypeGeneric.new(String)\n\n # @return [Array<Hash>, Hash, nil] A list of volume dicts, each containing device name and optionally ephemeral id or snapshot id. Size and type (and number of iops for io device type) must be specified for a new volume or a root volume, and may be passed for a snapshot volume. For any volume, a volume size less than 1 will be interpreted as a request not to create the volume.\n attribute :volumes\n validates :volumes, type: TypeGeneric.new(Hash)\n\n # @return [Object, nil] Opaque blob of data which is made available to the ec2 instance. Mutually exclusive with I(user_data_path).\n attribute :user_data\n\n # @return [Object, nil] Path to the file that contains userdata for the ec2 instances. Mutually exclusive with I(user_data).\n attribute :user_data_path\n\n # @return [Object, nil] Kernel id for the EC2 instance\n attribute :kernel_id\n\n # @return [Object, nil] The spot price you are bidding. Only applies for an autoscaling group with spot instances.\n attribute :spot_price\n\n # @return [:yes, :no, nil] Specifies whether instances are launched with detailed monitoring.\n attribute :instance_monitoring\n validates :instance_monitoring, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Used for Auto Scaling groups that launch instances into an Amazon Virtual Private Cloud. Specifies whether to assign a public IP address to each instance launched in a Amazon VPC.\n attribute :assign_public_ip\n\n # @return [Object, nil] A RAM disk id for the instances.\n attribute :ramdisk_id\n\n # @return [Object, nil] The name or the Amazon Resource Name (ARN) of the instance profile associated with the IAM role for the instances.\n attribute :instance_profile_name\n\n # @return [Boolean, nil] Specifies whether the instance is optimized for EBS I/O (true) or not (false).\n attribute :ebs_optimized\n validates :ebs_optimized, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] Id of ClassicLink enabled VPC\n attribute :classic_link_vpc_id\n\n # @return [Object, nil] A list of security group IDs with which to associate the ClassicLink VPC instances.\n attribute :classic_link_vpc_security_groups\n\n # @return [Object, nil] VPC ID, used when resolving security group names to IDs.\n attribute :vpc_id\n\n # @return [String, nil] The Id of a running instance to use as a basis for a launch configuration. Can be used in place of image_id and instance_type.\n attribute :instance_id\n validates :instance_id, type: String\n\n # @return [String, nil] Determines whether the instance runs on single-tenant harware or not.\n attribute :placement_tenancy\n validates :placement_tenancy, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6728748679161072, "alphanum_fraction": 0.6752626299858093, "avg_line_length": 42.625, "blob_id": "243631e91acff298b467a033dc5c38f0848432c6", "content_id": "510873e91f40355b70f906fcb217f117b0527b26", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2094, "license_type": "permissive", "max_line_length": 292, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/network/vyos/vyos_vlan.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of VLANs on VyOS network devices.\n class Vyos_vlan < Base\n # @return [String, nil] Name of the VLAN.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] Configure Virtual interface address.\n attribute :address\n validates :address, type: String\n\n # @return [Integer] ID of the VLAN. Range 0-4094.\n attribute :vlan_id\n validates :vlan_id, presence: true, type: Integer\n\n # @return [Array<String>, String] List of interfaces that should be associated to the VLAN.\n attribute :interfaces\n validates :interfaces, presence: true, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] This is a intent option and checks the operational state of the for given vlan C(name) for associated interfaces. If the value in the C(associated_interfaces) does not match with the operational state of vlan on device it will result in failure.\n attribute :associated_interfaces\n validates :associated_interfaces, type: TypeGeneric.new(String)\n\n # @return [Integer, nil] Delay the play should wait to check for declarative intent params values.\n attribute :delay\n validates :delay, type: Integer\n\n # @return [Object, nil] List of VLANs definitions.\n attribute :aggregate\n\n # @return [Boolean, nil] Purge VLANs not defined in the I(aggregate) parameter.\n attribute :purge\n validates :purge, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:present, :absent, nil] State of the VLAN configuration.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.788395881652832, "alphanum_fraction": 0.788395881652832, "avg_line_length": 31.55555534362793, "blob_id": "737c4bd27a6bf542a5f5c9e08f2644d659f58d14", "content_id": "c59ee2770901739cd70c12f036a4026b4ff60b2a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 293, "license_type": "permissive", "max_line_length": 47, "num_lines": 9, "path": "/lib/ansible-ruby.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# rubocop:disable Naming/FileName\n# frozen_string_literal: true\n\n# This is the name of the GEM, need it this way\nrequire 'ansible/ruby/version'\nrequire 'ansible/ruby/serializer'\nrequire 'ansible/ruby/dsl_builders/file_level'\nrequire 'ansible/ruby/modules/all'\n# rubocop:enable Naming/FileName\n" }, { "alpha_fraction": 0.7130225300788879, "alphanum_fraction": 0.7130225300788879, "avg_line_length": 58.238094329833984, "blob_id": "9b473597db51c9010428ed8ed34d20e61067e096", "content_id": "82f6cc54a9ddb1e684018998256da1d56e6fca7a", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1244, "license_type": "permissive", "max_line_length": 509, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_iapplx_package.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages Javascript iApp packages on a BIG-IP. This module will allow you to deploy iAppLX packages to the BIG-IP and manage their lifecycle.\n class Bigip_iapplx_package < Base\n # @return [String, nil] The iAppLX package that you want to upload or remove. When C(state) is C(present), and you intend to use this module in a C(role), it is recommended that you use the C({{ role_path }}) variable. An example is provided in the C(EXAMPLES) section.,When C(state) is C(absent), it is not necessary for the package to exist on the Ansible controller. If the full path to the package is provided, the fileame will specifically be cherry picked from it to properly remove the package.\n attribute :package\n validates :package, type: String\n\n # @return [:present, :absent, nil] Whether the iAppLX package should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7078135013580322, "alphanum_fraction": 0.7091267108917236, "avg_line_length": 59.91999816894531, "blob_id": "9fc828a5607445b154d0a67199f32e0c04763be4", "content_id": "4758a19e597db5db373ecb621325888174cf42f4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3046, "license_type": "permissive", "max_line_length": 293, "num_lines": 50, "path": "/lib/ansible/ruby/modules/generated/net_tools/nios/nios_host_record.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Adds and/or removes instances of host record objects from Infoblox NIOS servers. This module manages NIOS C(record:host) objects using the Infoblox WAPI interface over REST.\n # Updates instances of host record object from Infoblox NIOS servers.\n class Nios_host_record < Base\n # @return [String, Hash] Specifies the fully qualified hostname to add or remove from the system. User can also update the hostname as it is possible to pass a dict containing I(new_name), I(old_name). See examples.\n attribute :name\n validates :name, presence: true, type: MultipleTypes.new(String, Hash)\n\n # @return [String] Sets the DNS view to associate this host record with. The DNS view must already be configured on the system\n attribute :view\n validates :view, presence: true, type: String\n\n # @return [Boolean, nil] Sets the DNS to particular parent. If user needs to bypass DNS user can make the value to false.\n attribute :configure_for_dns\n validates :configure_for_dns, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] Configures the IPv4 addresses for this host record. This argument accepts a list of values (see suboptions)\n attribute :ipv4addrs\n\n # @return [Object, nil] Configures the IPv6 addresses for the host record. This argument accepts a list of values (see options)\n attribute :ipv6addrs\n\n # @return [Array<String>, String, nil] Configures an optional list of additional aliases to add to the host record. These are equivalent to CNAMEs but held within a host record. Must be in list format.\n attribute :aliases\n validates :aliases, type: TypeGeneric.new(String)\n\n # @return [Object, nil] Configures the TTL to be associated with this host record\n attribute :ttl\n\n # @return [Object, nil] Allows for the configuration of Extensible Attributes on the instance of the object. This argument accepts a set of key / value pairs for configuration.\n attribute :extattrs\n\n # @return [String, nil] Configures a text string comment to be associated with the instance of this object. The provided text string will be configured on the object instance.\n attribute :comment\n validates :comment, type: String\n\n # @return [:present, :absent, nil] Configures the intended state of the instance of the object on the NIOS server. When this value is set to C(present), the object is configured on the device and when this value is set to C(absent) the value is removed (if necessary) from the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7304270267486572, "alphanum_fraction": 0.7330960631370544, "avg_line_length": 52.52381134033203, "blob_id": "15c577cb6f4f3af7069f98cdb9420217450ec76b", "content_id": "ea3ae8cca05a5e9fbfa0ab415d67a7d4c99fd348", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1124, "license_type": "permissive", "max_line_length": 289, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/windows/win_dns_client.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The C(win_dns_client) module configures the DNS client on Windows network adapters.\n class Win_dns_client < Base\n # @return [String] Adapter name or list of adapter names for which to manage DNS settings ('*' is supported as a wildcard value). The adapter name used is the connection caption in the Network Control Panel or via C(Get-NetAdapter), eg C(Local Area Connection).\n attribute :adapter_names\n validates :adapter_names, presence: true, type: String\n\n # @return [Array<String>, String] Single or ordered list of DNS server IPv4 addresses to configure for lookup. An empty list will configure the adapter to use the DHCP-assigned values on connections where DHCP is enabled, or disable DNS lookup on statically-configured connections.\n attribute :ipv4_addresses\n validates :ipv4_addresses, presence: true, type: TypeGeneric.new(String, NilClass)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7482339143753052, "alphanum_fraction": 0.7488226294517517, "avg_line_length": 93.37036895751953, "blob_id": "f62e53839b155cb4be5b0628a8a86f04659d193d", "content_id": "272101cbaa0a13dd3ca2c4a950d8d9220a5aeb9f", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5096, "license_type": "permissive", "max_line_length": 886, "num_lines": 54, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_profile_oneconnect.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage OneConnect profiles on a BIG-IP.\n class Bigip_profile_oneconnect < Base\n # @return [String] Specifies the name of the OneConnect profile.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Specifies the profile from which this profile inherits settings.,When creating a new profile, if this parameter is not specified, the default is the system-supplied C(oneconnect) profile.\n attribute :parent\n\n # @return [Object, nil] Specifies a value that the system applies to the source address to determine its eligibility for reuse.,When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.,The system applies the value of this setting to the server-side source address to determine its eligibility for reuse.,A mask of C(0) causes the system to share reused connections across all source addresses. A host mask of C(32) causes the system to share only those reused connections originating from the same source address.,When you are using a SNAT or SNAT pool, the server-side source address is translated first and then the OneConnect mask is applied to the translated address.\n attribute :source_mask\n\n # @return [Object, nil] Description of the profile.\n attribute :description\n\n # @return [Object, nil] Specifies the maximum number of connections that the system holds in the connection reuse pool.,If the pool is already full, then a server-side connection closes after the response is completed.,When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.\n attribute :maximum_size\n\n # @return [Object, nil] Specifies the maximum number of seconds allowed for a connection in the connection reuse pool.,For any connection with an age higher than this value, the system removes that connection from the re-use pool.,When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.\n attribute :maximum_age\n\n # @return [Object, nil] Specifies the maximum number of times that a server-side connection can be reused.,When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.\n attribute :maximum_reuse\n\n # @return [Object, nil] Specifies the number of seconds that a connection is idle before the connection flow is eligible for deletion.,When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.,You may specify a number of seconds for the timeout override.,When C(disabled), specifies that there is no timeout override for the connection.,When C(indefinite), Specifies that a connection may be idle with no timeout override.\n attribute :idle_timeout_override\n\n # @return [:none, :idle, :strict, nil] When C(none), simultaneous in-flight requests and responses over TCP connections to a pool member are counted toward the limit. This is the historical behavior.,When C(idle), idle connections will be dropped as the TCP connection limit is reached. For short intervals, during the overlap of the idle connection being dropped and the new connection being established, the TCP connection limit may be exceeded.,When C(strict), the TCP connection limit is honored with no exceptions. This means that idle connections will prevent new TCP connections from being made until they expire, even if they could otherwise be reused.,C(strict) is not a recommended configuration except in very special cases with short expiration timeouts.,When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.\n attribute :limit_type\n validates :limit_type, expression_inclusion: {:in=>[:none, :idle, :strict], :message=>\"%{value} needs to be :none, :idle, :strict\"}, allow_nil: true\n\n # @return [Symbol, nil] Indicates that connections may be shared not only within a virtual server, but also among similar virtual servers,When C(yes), all virtual servers that use the same OneConnect and other internal network profiles can share connections.,When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.\n attribute :share_pools\n validates :share_pools, type: Symbol\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [:present, :absent, nil] When C(present), ensures that the profile exists.,When C(absent), ensures the profile is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6662320494651794, "alphanum_fraction": 0.6662320494651794, "avg_line_length": 28.5, "blob_id": "d61241af4daa14d92208527b61b17b34c3def2bc", "content_id": "040aa22a7677f9bb8f9074db83231d8450bf78df", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 767, "license_type": "permissive", "max_line_length": 114, "num_lines": 26, "path": "/lib/ansible/ruby/modules/generated/cloud/rackspace/rax_meta.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manipulate metadata for Rackspace Cloud Servers\n class Rax_meta < Base\n # @return [Object, nil] Server IP address to modify metadata for, will match any IP assigned to the server\n attribute :address\n\n # @return [Object, nil] Server ID to modify metadata for\n attribute :id\n\n # @return [String, nil] Server name to modify metadata for\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] A hash of metadata to associate with the instance\n attribute :meta\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6433484554290771, "alphanum_fraction": 0.6448582410812378, "avg_line_length": 61.74736785888672, "blob_id": "61b1c1848343cd7ade51cc5ac78c9994f8a73c25", "content_id": "9cd3726733b3618db8e55204c49c7608d108027d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5961, "license_type": "permissive", "max_line_length": 247, "num_lines": 95, "path": "/lib/ansible/ruby/modules/generated/packaging/os/portage.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages Gentoo packages\n class Portage < Base\n # @return [String, nil] Package atom or set, e.g. C(sys-apps/foo) or C(>foo-2.13) or C(@world)\n attribute :package\n validates :package, type: String\n\n # @return [:present, :installed, :emerged, :absent, :removed, :unmerged, :latest, nil] State of the package atom\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :installed, :emerged, :absent, :removed, :unmerged, :latest], :message=>\"%{value} needs to be :present, :installed, :emerged, :absent, :removed, :unmerged, :latest\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Update packages to the best version available (--update)\n attribute :update\n validates :update, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Consider the entire dependency tree of packages (--deep)\n attribute :deep\n validates :deep, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Include installed packages where USE flags have changed (--newuse)\n attribute :newuse\n validates :newuse, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Include installed packages where USE flags have changed, except when,flags that the user has not enabled are added or removed,(--changed-use)\n attribute :changed_use\n validates :changed_use, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Do not add the packages to the world file (--oneshot)\n attribute :oneshot\n validates :oneshot, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Do not re-emerge installed packages (--noreplace)\n attribute :noreplace\n validates :noreplace, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Only merge packages but not their dependencies (--nodeps)\n attribute :nodeps\n validates :nodeps, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Only merge packages' dependencies but not the packages (--onlydeps)\n attribute :onlydeps\n validates :onlydeps, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Remove packages not needed by explicitly merged packages (--depclean),If no package is specified, clean up the world's dependencies,Otherwise, --depclean serves as a dependency aware version of --unmerge\n attribute :depclean\n validates :depclean, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Run emerge in quiet mode (--quiet)\n attribute :quiet\n validates :quiet, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Run emerge in verbose mode (--verbose)\n attribute :verbose\n validates :verbose, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:web, :yes, :no, nil] Sync package repositories first,If yes, perform \"emerge --sync\",If web, perform \"emerge-webrsync\"\n attribute :sync\n validates :sync, expression_inclusion: {:in=>[:web, :yes, :no], :message=>\"%{value} needs to be :web, :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Prefer packages specified at PORTAGE_BINHOST in make.conf\n attribute :getbinpkg\n validates :getbinpkg, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Merge only binaries (no compiling). This sets getbinpkg=yes.\n attribute :usepkgonly\n validates :usepkgonly, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Continue as much as possible after an error.\n attribute :keepgoing\n validates :keepgoing, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the number of packages to build simultaneously.,Since version 2.6: Value of 0 or False resets any previously added,--jobs setting values\n attribute :jobs\n\n # @return [Object, nil] Specifies that no new builds should be started if there are,other builds running and the load average is at least LOAD,Since version 2.6: Value of 0 or False resets any previously added,--load-average setting values\n attribute :loadavg\n\n # @return [:yes, :no, nil] Redirect all build output to logs alone, and do not display it,on stdout (--quiet-build)\n attribute :quietbuild\n validates :quietbuild, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Suppresses display of the build log on stdout (--quiet-fail),Only the die message and the path of the build log will be,displayed on stdout.\n attribute :quietfail\n validates :quietfail, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6500229239463806, "alphanum_fraction": 0.6500229239463806, "avg_line_length": 40.980770111083984, "blob_id": "584e3091b0676b92760bb122149e50a2c7561ea2", "content_id": "3eb81067644508df195306178baa614f00b237da", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2183, "license_type": "permissive", "max_line_length": 173, "num_lines": 52, "path": "/lib/ansible/ruby/modules/generated/cloud/rackspace/rax_clb_nodes.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Adds, modifies and removes nodes from a Rackspace Cloud Load Balancer\n class Rax_clb_nodes < Base\n # @return [String, nil] IP address or domain name of the node\n attribute :address\n validates :address, type: String\n\n # @return [:enabled, :disabled, :draining, nil] Condition for the node, which determines its role within the load balancer\n attribute :condition\n validates :condition, expression_inclusion: {:in=>[:enabled, :disabled, :draining], :message=>\"%{value} needs to be :enabled, :disabled, :draining\"}, allow_nil: true\n\n # @return [Integer] Load balancer id\n attribute :load_balancer_id\n validates :load_balancer_id, presence: true, type: Integer\n\n # @return [Integer, nil] Node id\n attribute :node_id\n validates :node_id, type: Integer\n\n # @return [Integer, nil] Port number of the load balanced service on the node\n attribute :port\n validates :port, type: Integer\n\n # @return [:present, :absent, nil] Indicate desired state of the node\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:primary, :secondary, nil] Type of node\n attribute :type\n validates :type, expression_inclusion: {:in=>[:primary, :secondary], :message=>\"%{value} needs to be :primary, :secondary\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Wait for the load balancer to become active before returning\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] How long to wait before giving up and returning an error\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [Object, nil] Weight of node\n attribute :weight\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6551241874694824, "alphanum_fraction": 0.6568730473518372, "avg_line_length": 45.86885070800781, "blob_id": "b5dc3550c3d62096852013bba7e4dddc72ca9646", "content_id": "c6e74ccc739e4a300be6a44b1a2226a9dbb96f49", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2859, "license_type": "permissive", "max_line_length": 289, "num_lines": 61, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_snapshot_policy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and delete volume snapshot policies.\n class Cs_snapshot_policy < Base\n # @return [String, nil] Name of the volume.,Either C(volume) or C(vm) is required.\n attribute :volume\n validates :volume, type: String\n\n # @return [:DATADISK, :ROOT, nil] Type of the volume.\n attribute :volume_type\n validates :volume_type, expression_inclusion: {:in=>[:DATADISK, :ROOT], :message=>\"%{value} needs to be :DATADISK, :ROOT\"}, allow_nil: true\n\n # @return [String, nil] Name of the instance to select the volume from.,Use C(volume_type) if VM has a DATADISK and ROOT volume.,In case of C(volume_type=DATADISK), additionally use C(device_id) if VM has more than one DATADISK volume.,Either C(volume) or C(vm) is required.\n attribute :vm\n validates :vm, type: String\n\n # @return [Integer, nil] ID of the device on a VM the volume is attached to.,This will only be considered if VM has multiple DATADISK volumes.\n attribute :device_id\n validates :device_id, type: Integer\n\n # @return [Object, nil] Name of the vpc the instance is deployed in.\n attribute :vpc\n\n # @return [:hourly, :daily, :weekly, :monthly, nil] Interval of the snapshot.\n attribute :interval_type\n validates :interval_type, expression_inclusion: {:in=>[:hourly, :daily, :weekly, :monthly], :message=>\"%{value} needs to be :hourly, :daily, :weekly, :monthly\"}, allow_nil: true\n\n # @return [Integer, nil] Max number of snapshots.\n attribute :max_snaps\n validates :max_snaps, type: Integer\n\n # @return [String, nil] Time the snapshot is scheduled. Required if C(state=present).,Format for C(interval_type=HOURLY): C(MM),Format for C(interval_type=DAILY): C(MM:HH),Format for C(interval_type=WEEKLY): C(MM:HH:DD (1-7)),Format for C(interval_type=MONTHLY): C(MM:HH:DD (1-28))\n attribute :schedule\n validates :schedule, type: String\n\n # @return [String, nil] Specifies a timezone for this command.\n attribute :time_zone\n validates :time_zone, type: String\n\n # @return [:present, :absent, nil] State of the snapshot policy.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Domain the volume is related to.\n attribute :domain\n\n # @return [Object, nil] Account the volume is related to.\n attribute :account\n\n # @return [Object, nil] Name of the project the volume is related to.\n attribute :project\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6509636044502258, "alphanum_fraction": 0.6509636044502258, "avg_line_length": 18.45833396911621, "blob_id": "e58a48591dcb3823c9bac05e82859fba2007e6ba", "content_id": "3970eb16bac96dfad08cf86e71246575ff2fc4f4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 467, "license_type": "permissive", "max_line_length": 74, "num_lines": 24, "path": "/lib/ansible/ruby/dsl_builders/result_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# see LICENSE.txt in project root\nrequire 'spec_helper'\n\ndescribe Ansible::Ruby::DslBuilders::Result do\n let(:name_fetcher) do\n -> { 'the_var' }\n end\n\n subject(:result) { Ansible::Ruby::DslBuilders::Result.new name_fetcher }\n\n describe '#to_s' do\n subject { result.to_s }\n\n it { is_expected.to eq 'the_var' }\n end\n\n describe 'chain' do\n subject { result.stuff }\n\n it { is_expected.to eq 'the_var.stuff' }\n end\nend\n" }, { "alpha_fraction": 0.6464995741844177, "alphanum_fraction": 0.6464995741844177, "avg_line_length": 35.15625, "blob_id": "4913968884bee7c091363992efb6260d68cf32dd", "content_id": "e0a32d6a5eda6d4cb658df7ae8d7805fd95a3849", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1157, "license_type": "permissive", "max_line_length": 143, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_snmp_community.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages SNMP community configuration.\n class Nxos_snmp_community < Base\n # @return [String] Case-sensitive community string.\n attribute :community\n validates :community, presence: true, type: String\n\n # @return [:ro, :rw, nil] Access type for community.\n attribute :access\n validates :access, expression_inclusion: {:in=>[:ro, :rw], :message=>\"%{value} needs to be :ro, :rw\"}, allow_nil: true\n\n # @return [String, nil] Group to which the community belongs.\n attribute :group\n validates :group, type: String\n\n # @return [Object, nil] ACL name to filter snmp requests or keyword 'default'.\n attribute :acl\n\n # @return [:present, :absent, nil] Manage the state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6608695387840271, "alphanum_fraction": 0.6608695387840271, "avg_line_length": 35.79999923706055, "blob_id": "3d4513a8147f0b6055b7c61ff2dd6c7486738529", "content_id": "8f3649e46bb1daf0a1169f94f3fc721689c828a8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 920, "license_type": "permissive", "max_line_length": 160, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/packaging/os/swdepot.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Will install, upgrade and remove packages with swdepot package manager (HP-UX)\n class Swdepot < Base\n # @return [String] package name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :latest, :absent] whether to install (C(present), C(latest)), or remove (C(absent)) a package.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :latest, :absent], :message=>\"%{value} needs to be :present, :latest, :absent\"}\n\n # @return [String, nil] The source repository from which install or upgrade a package.\n attribute :depot\n validates :depot, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6931144595146179, "alphanum_fraction": 0.6931144595146179, "avg_line_length": 53.82500076293945, "blob_id": "f732b6a7bc90dd30ad89dbb8bc706a375c8e4f7a", "content_id": "f5ce415be9a5e3b9603ebfafbd2f7ede0b001a7f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2193, "license_type": "permissive", "max_line_length": 230, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_publicipaddress.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and delete a Public IP address. Allows setting and updating the address allocation method and domain name label. Use the azure_rm_networkinterface module to associate a Public IP with a network interface.\n class Azure_rm_publicipaddress < Base\n # @return [String] Name of resource group with which the Public IP is associated.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [:Dynamic, :Static, nil] Control whether the assigned Public IP remains permanently assigned to the object. If not set to 'Static', the IP address my changed anytime an associated virtual machine is power cycled.\n attribute :allocation_method\n validates :allocation_method, expression_inclusion: {:in=>[:Dynamic, :Static], :message=>\"%{value} needs to be :Dynamic, :Static\"}, allow_nil: true\n\n # @return [String, nil] The customizable portion of the FQDN assigned to public IP address. This is an explicit setting. If no value is provided, any existing value will be removed on an existing public IP.\n attribute :domain_name\n validates :domain_name, type: String\n\n # @return [String] Name of the Public IP.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, nil] Assert the state of the Public IP. Use 'present' to create or update a and 'absent' to delete.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [Object, nil] Valid azure location. Defaults to location of the resource group.\n attribute :location\n\n # @return [:Basic, :Standard, nil] The public IP address SKU.\n attribute :sku\n validates :sku, expression_inclusion: {:in=>[:Basic, :Standard], :message=>\"%{value} needs to be :Basic, :Standard\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6442516446113586, "alphanum_fraction": 0.6442516446113586, "avg_line_length": 35.880001068115234, "blob_id": "edb9069af2d033f70bebc2463c24528e478a6eda", "content_id": "25ed36091a8fe47ef1e91990ce6235b5b0be3b40", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 922, "license_type": "permissive", "max_line_length": 143, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_fcp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Start, Stop and Enable FCP services.\n class Na_ontap_fcp < Base\n # @return [:present, :absent, nil] Whether the FCP should be enabled or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:up, :down, nil] Whether the FCP should be up or down\n attribute :status\n validates :status, expression_inclusion: {:in=>[:up, :down], :message=>\"%{value} needs to be :up, :down\"}, allow_nil: true\n\n # @return [String] The name of the vserver to use.\n attribute :vserver\n validates :vserver, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6969964504241943, "alphanum_fraction": 0.6969964504241943, "avg_line_length": 44.279998779296875, "blob_id": "1b15446207718d0376721a9a1ea4d05f35257ec3", "content_id": "b682df807444a2fef65ad27f0aa022ee75ec7436", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1132, "license_type": "permissive", "max_line_length": 213, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/network/files/net_get.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides functionality to copy file from network device to ansible controller.\n class Net_get < Base\n # @return [String] Specifies the source file. The path to the source file can either be the full path on the network device or a relative path as per path supported by destination network device.\n attribute :src\n validates :src, presence: true, type: String\n\n # @return [:scp, :sftp, nil] Protocol used to transfer file.\n attribute :protocol\n validates :protocol, expression_inclusion: {:in=>[:scp, :sftp], :message=>\"%{value} needs to be :scp, :sftp\"}, allow_nil: true\n\n # @return [String, nil] Specifies the destination file. The path to the destination file can either be the full path on the Ansible control host or a relative path from the playbook or role root directory.\n attribute :dest\n validates :dest, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6649819612503052, "alphanum_fraction": 0.6664260029792786, "avg_line_length": 39.735294342041016, "blob_id": "9792e24230bba1704708fe086b82991a4a2590af", "content_id": "99c330d53da93b6f937c33f8577c968f315afd5e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1385, "license_type": "permissive", "max_line_length": 193, "num_lines": 34, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_tags.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module manage tags in oVirt/RHV. It can also manage assignments of those tags to entities.\n class Ovirt_tag < Base\n # @return [String] Name of the tag to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, :attached, :detached, nil] Should the tag be present/absent/attached/detached.,C(Note): I(attached) and I(detached) states are supported since version 2.4.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :attached, :detached], :message=>\"%{value} needs to be :present, :absent, :attached, :detached\"}, allow_nil: true\n\n # @return [Object, nil] Description of the tag to manage.\n attribute :description\n\n # @return [Object, nil] Name of the parent tag.\n attribute :parent\n\n # @return [Array<String>, String, nil] List of the VMs names, which should have assigned this tag.\n attribute :vms\n validates :vms, type: TypeGeneric.new(String, NilClass)\n\n # @return [Object, nil] List of the hosts names, which should have assigned this tag.\n attribute :hosts\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.655781090259552, "alphanum_fraction": 0.656663715839386, "avg_line_length": 33.33333206176758, "blob_id": "e50d5594d5e7da3092b7862d0991760d327b9810", "content_id": "926daabab2074055981d8c9adb779aa5e22ea87a", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1133, "license_type": "permissive", "max_line_length": 125, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_ucadapter.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # modify the UC adapter mode and type taking pending type and mode into account.\n class Na_ontap_ucadapter < Base\n # @return [:present, nil] Whether the specified adapter should exist.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present], :message=>\"%{value} needs to be :present\"}, allow_nil: true\n\n # @return [String] Specifies the adapter name.\n attribute :adapter_name\n validates :adapter_name, presence: true, type: String\n\n # @return [String] Specifies the adapter home node.\n attribute :node_name\n validates :node_name, presence: true, type: String\n\n # @return [String, nil] Specifies the mode of the adapter.\n attribute :mode\n validates :mode, type: String\n\n # @return [String, nil] Specifies the fc4 type of the adapter.\n attribute :type\n validates :type, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7086330652236938, "alphanum_fraction": 0.7086330652236938, "avg_line_length": 31.705883026123047, "blob_id": "3c8f90f83181905c2f8e4766997b2cf5d1a93f69", "content_id": "7acbd74ee2da580bd6fb3f9db8ab11205baa6052", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 556, "license_type": "permissive", "max_line_length": 108, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/cloud/digital_ocean/digital_ocean_load_balancer_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to gather facts about DigitalOcean provided load balancers.\n class Digital_ocean_load_balancer_facts < Base\n # @return [String, nil] Load balancer ID that can be used to identify and reference a load_balancer.\n attribute :load_balancer_id\n validates :load_balancer_id, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6574664115905762, "alphanum_fraction": 0.6574664115905762, "avg_line_length": 37.18918991088867, "blob_id": "900c2119e1c21fbc519c9a3b8f6bc15c07e3da57", "content_id": "589401af02948fd4f6a9ffc742e0df0c558c5879", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1413, "license_type": "permissive", "max_line_length": 161, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/notification/pushbullet.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module sends push notifications via Pushbullet to channels or devices.\n class Pushbullet < Base\n # @return [String] Push bullet API token\n attribute :api_key\n validates :api_key, presence: true, type: String\n\n # @return [String, nil] The channel TAG you wish to broadcast a push notification, as seen on the \"My Channels\" > \"Edit your channel\" at Pushbullet page.\n attribute :channel\n validates :channel, type: String\n\n # @return [String, nil] The device NAME you wish to send a push notification, as seen on the Pushbullet main page.\n attribute :device\n validates :device, type: String\n\n # @return [:note, :link, nil] Thing you wish to push.\n attribute :push_type\n validates :push_type, expression_inclusion: {:in=>[:note, :link], :message=>\"%{value} needs to be :note, :link\"}, allow_nil: true\n\n # @return [String] Title of the notification.\n attribute :title\n validates :title, presence: true, type: String\n\n # @return [String, nil] Body of the notification, e.g. Details of the fault you're alerting.\n attribute :body\n validates :body, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7166386842727661, "alphanum_fraction": 0.7193277478218079, "avg_line_length": 81.63888549804688, "blob_id": "4dfe5e59398a8d9d3cc810b3d60807d592d4faae", "content_id": "93f1ffda13f1adde7a5c012c49c5ed89e5ff8ca4", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2975, "license_type": "permissive", "max_line_length": 513, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_policy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages general policy configuration on a BIG-IP. This module is best used in conjunction with the C(bigip_policy_rule) module. This module can handle general configuration like setting the draft state of the policy, the description, and things unrelated to the policy rules themselves. It is also the first module that should be used when creating rules as the C(bigip_policy_rule) module requires a policy parameter.\n class Bigip_policy < Base\n # @return [Object, nil] The description to attach to the policy.,This parameter is only supported on versions of BIG-IP >= 12.1.0. On earlier versions it will simply be ignored.\n attribute :description\n\n # @return [String] The name of the policy to create.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, :draft, nil] When C(state) is C(present), ensures that the policy exists and is published. When C(state) is C(absent), ensures that the policy is removed, even if it is currently drafted.,When C(state) is C(draft), ensures that the policy exists and is drafted. When modifying rules, it is required that policies first be in a draft.,Drafting is only supported on versions of BIG-IP >= 12.1.0. On versions prior to that, specifying a C(state) of C(draft) will raise an error.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :draft], :message=>\"%{value} needs to be :present, :absent, :draft\"}, allow_nil: true\n\n # @return [:first, :all, :best, nil] Specifies the method to determine which actions get executed in the case where there are multiple rules that match. When creating new policies, the default is C(first).,This module does not allow you to specify the C(best) strategy to use. It will choose the system default (C(/Common/best-match)) for you instead.\n attribute :strategy\n validates :strategy, expression_inclusion: {:in=>[:first, :all, :best], :message=>\"%{value} needs to be :first, :all, :best\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] Specifies a list of rules that you want associated with this policy. The order of this list is the order they will be evaluated by BIG-IP. If the specified rules do not exist (for example when creating a new policy) then they will be created.,The C(conditions) for a default rule are C(all).,The C(actions) for a default rule are C(ignore).,The C(bigip_policy_rule) module can be used to create and edit existing and new rules.\n attribute :rules\n validates :rules, type: TypeGeneric.new(String)\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6722016930580139, "alphanum_fraction": 0.6722016930580139, "avg_line_length": 40.69230651855469, "blob_id": "1f0bbb53226ff14e8743f1b7b1f859a334cd3048", "content_id": "7d3c4e16f958884b8d76efd06927940cfca98a10", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1626, "license_type": "permissive", "max_line_length": 215, "num_lines": 39, "path": "/lib/ansible/ruby/modules/generated/network/panos/panos_dag_tags.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create the ip address to tag associations. Tags will in turn be used to create DAG's\n class Panos_dag_tags < Base\n # @return [Object, nil] API key that can be used instead of I(username)/I(password) credentials.\n attribute :api_key\n\n # @return [String, nil] The purpose / objective of the static Address Group\n attribute :description\n validates :description, type: String\n\n # @return [Boolean, nil] commit if changed\n attribute :commit\n validates :commit, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] - Device groups are used for the Panorama interaction with Firewall(s). The group must exists on Panorama. If device group is not define we assume that we are contacting Firewall.\\r\\n\n attribute :devicegroup\n\n # @return [String, nil] The action to be taken. Supported values are I(add)/I(update)/I(find)/I(delete).\n attribute :operation\n validates :operation, type: String\n\n # @return [String, nil] The list of the tags that will be added or removed from the IP address.\n attribute :tag_names\n validates :tag_names, type: String\n\n # @return [String, nil] IP that will be registered with the given tag names.\n attribute :ip_to_register\n validates :ip_to_register, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6698873043060303, "alphanum_fraction": 0.6698873043060303, "avg_line_length": 28.571428298950195, "blob_id": "4f09432b972953d76f1a08ebd7d068278aef97bc", "content_id": "c5c126ab6913fd19ec5aa0ebce28f32d5da1d168", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 621, "license_type": "permissive", "max_line_length": 82, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_quotas_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Retrieve facts about one or more oVirt/RHV quotas.\n class Ovirt_quota_facts < Base\n # @return [String] Name of the datacenter where quota resides.\n attribute :data_center\n validates :data_center, presence: true, type: String\n\n # @return [String, nil] Name of the quota, can be used as glob expression.\n attribute :name\n validates :name, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7051792740821838, "alphanum_fraction": 0.7051792740821838, "avg_line_length": 49.20000076293945, "blob_id": "9dddaf45694d03dcf5f4eadf44278e429a146a27", "content_id": "f3a54ec1b75c424fad4b795adcace76121824c0e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1506, "license_type": "permissive", "max_line_length": 188, "num_lines": 30, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_ses_identity_policy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows the user to manage sending authorization policies associated with an SES identity (email or domain).\n # SES authorization sending policies can be used to control what actors are able to send email on behalf of the validated identity and what conditions must be met by the sent emails.\n class Aws_ses_identity_policy < Base\n # @return [String] The SES identity to attach or remove a policy from. This can be either the full ARN or just\\r\\nthe verified email or domain.\\r\\n\n attribute :identity\n validates :identity, presence: true, type: String\n\n # @return [String] The name used to identify the policy within the scope of the identity it's attached to.\n attribute :policy_name\n validates :policy_name, presence: true, type: String\n\n # @return [String, nil] A properly formated JSON sending authorization policy. Required when I(state=present).\n attribute :policy\n validates :policy, type: String\n\n # @return [:present, :absent, nil] Whether to create(or update) or delete the authorization policy on the identity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6387362480163574, "alphanum_fraction": 0.656593382358551, "avg_line_length": 41.82352828979492, "blob_id": "46887848641ad4c9017e55453d8f65a8883d3d8f", "content_id": "fbb53deecffe960c5202c0fc88a0bc15cb9243dd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1456, "license_type": "permissive", "max_line_length": 173, "num_lines": 34, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_switchport.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages Layer 2 switchport interfaces on HUAWEI CloudEngine switches.\n class Ce_switchport < Base\n # @return [Object] Full name of the interface, i.e. 40GE1/0/22.\n attribute :interface\n validates :interface, presence: true\n\n # @return [:access, :trunk, nil] The link type of an interface.\n attribute :mode\n validates :mode, expression_inclusion: {:in=>[:access, :trunk], :message=>\"%{value} needs to be :access, :trunk\"}, allow_nil: true\n\n # @return [Object, nil] If C(mode=access), used as the access VLAN ID, in the range from 1 to 4094.\n attribute :access_vlan\n\n # @return [Object, nil] If C(mode=trunk), used as the trunk native VLAN ID, in the range from 1 to 4094.\n attribute :native_vlan\n\n # @return [Object, nil] If C(mode=trunk), used as the VLAN range to ADD or REMOVE from the trunk, such as 2-10 or 2,5,10-15, etc.\n attribute :trunk_vlans\n\n # @return [:present, :absent, :unconfigured, nil] Manage the state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :unconfigured], :message=>\"%{value} needs to be :present, :absent, :unconfigured\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6518340110778809, "alphanum_fraction": 0.6530366539955139, "avg_line_length": 43.945945739746094, "blob_id": "1596b99ea003ad0e04ebcb053e13da92c68dd8fc", "content_id": "dac52468d2489c95612978bf03604ebb22212470", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1663, "license_type": "permissive", "max_line_length": 274, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/cloud/smartos/imgadm.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage SmartOS virtual machine images through imgadm(1M)\n class Imgadm < Base\n # @return [Symbol, nil] Force a given operation (where supported by imgadm(1M)).\n attribute :force\n validates :force, type: Symbol\n\n # @return [String, nil] zpool to import to or delete images from.\n attribute :pool\n validates :pool, type: String\n\n # @return [String, nil] URI for the image source.\n attribute :source\n validates :source, type: String\n\n # @return [:present, :absent, :deleted, :imported, :updated, :vacuumed] State the object operated on should be in. C(imported) is an alias for for C(present) and C(deleted) for C(absent). When set to C(vacuumed) and C(uuid) to C(*), it will remove all unused images.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent, :deleted, :imported, :updated, :vacuumed], :message=>\"%{value} needs to be :present, :absent, :deleted, :imported, :updated, :vacuumed\"}\n\n # @return [:imgapi, :docker, :dsapi, nil] Type for image sources.\n attribute :type\n validates :type, expression_inclusion: {:in=>[:imgapi, :docker, :dsapi], :message=>\"%{value} needs to be :imgapi, :docker, :dsapi\"}, allow_nil: true\n\n # @return [String, nil] Image UUID. Can either be a full UUID or C(*) for all images.\n attribute :uuid\n validates :uuid, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6812681555747986, "alphanum_fraction": 0.688770592212677, "avg_line_length": 64.5873031616211, "blob_id": "935740107ae84a6eac14966000e82dcdfc2b2dda", "content_id": "0ed935416c553d2c6d49a7f9411bf42977069091", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4132, "license_type": "permissive", "max_line_length": 592, "num_lines": 63, "path": "/lib/ansible/ruby/modules/generated/cloud/lxd/lxd_container.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Management of LXD containers\n class Lxd_container < Base\n # @return [String] Name of a container.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] The architecture for the container (e.g. \"x86_64\" or \"i686\"). See U(https://github.com/lxc/lxd/blob/master/doc/rest-api.md#post-1)\n attribute :architecture\n\n # @return [Object, nil] The config for the container (e.g. {\"limits.cpu\": \"2\"}). See U(https://github.com/lxc/lxd/blob/master/doc/rest-api.md#post-1),If the container already exists and its \"config\" value in metadata obtained from GET /1.0/containers/<name> U(https://github.com/lxc/lxd/blob/master/doc/rest-api.md#10containersname) are different, they this module tries to apply the configurations.,The key starts with 'volatile.' are ignored for this comparison.,Not all config values are supported to apply the existing container. Maybe you need to delete and recreate a container.\n attribute :config\n\n # @return [Object, nil] The devices for the container (e.g. { \"rootfs\": { \"path\": \"/dev/kvm\", \"type\": \"unix-char\" }). See U(https://github.com/lxc/lxd/blob/master/doc/rest-api.md#post-1)\n attribute :devices\n\n # @return [Object, nil] Whether or not the container is ephemeral (e.g. true or false). See U(https://github.com/lxc/lxd/blob/master/doc/rest-api.md#post-1)\n attribute :ephemeral\n\n # @return [Object, nil] The source for the container (e.g. { \"type\": \"image\", \"mode\": \"pull\", \"server\": \"https://images.linuxcontainers.org\", \"protocol\": \"lxd\", \"alias\": \"ubuntu/xenial/amd64\" }). See U(https://github.com/lxc/lxd/blob/master/doc/rest-api.md#post-1)\n attribute :source\n\n # @return [:started, :stopped, :restarted, :absent, :frozen, nil] Define the state of a container.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:started, :stopped, :restarted, :absent, :frozen], :message=>\"%{value} needs to be :started, :stopped, :restarted, :absent, :frozen\"}, allow_nil: true\n\n # @return [Integer, nil] A timeout for changing the state of the container.,This is also used as a timeout for waiting until IPv4 addresses are set to the all network interfaces in the container after starting or restarting.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [Boolean, nil] If this is true, the C(lxd_container) waits until IPv4 addresses are set to the all network interfaces in the container after starting or restarting.\n attribute :wait_for_ipv4_addresses\n validates :wait_for_ipv4_addresses, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] If this is true, the C(lxd_container) forces to stop the container when it stops or restarts the container.\n attribute :force_stop\n validates :force_stop, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] The unix domain socket path or the https URL for the LXD server.\n attribute :url\n validates :url, type: String\n\n # @return [String, nil] The client certificate key file path.\n attribute :key_file\n validates :key_file, type: String\n\n # @return [String, nil] The client certificate file path.\n attribute :cert_file\n validates :cert_file, type: String\n\n # @return [Object, nil] The client trusted password.,You need to set this password on the LXD server before running this module using the following command. lxc config set core.trust_password <some random password> See U(https://www.stgraber.org/2016/04/18/lxd-api-direct-interaction/),If trust_password is set, this module send a request for authentication before sending any requests.\n attribute :trust_password\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.680786669254303, "alphanum_fraction": 0.6822995543479919, "avg_line_length": 44.58620834350586, "blob_id": "1e237359f6e0d516e6e0125390965d3ae05dc0f2", "content_id": "4bb757e0436dd39bdb056b9eda5ac6c882304ea8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1322, "license_type": "permissive", "max_line_length": 151, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/digital_ocean/digital_ocean_tag.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create and remove tag(s) to DigitalOcean resource.\n class Digital_ocean_tag < Base\n # @return [String] The name of the tag. The supported characters for names include alphanumeric characters, dashes, and underscores.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The ID of the resource to operate on.,The data type of resource_id is changed from integer to string, from version 2.5.\n attribute :resource_id\n validates :resource_id, type: String\n\n # @return [:droplet, nil] The type of resource to operate on. Currently, only tagging of droplets is supported.\n attribute :resource_type\n validates :resource_type, expression_inclusion: {:in=>[:droplet], :message=>\"%{value} needs to be :droplet\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Whether the tag should be present or absent on the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6673743724822998, "alphanum_fraction": 0.6680821180343628, "avg_line_length": 41.818180084228516, "blob_id": "0b5d636d4dab84bf877b54623bc616374c8ea429", "content_id": "8f8e573c1f8f4a52875fc8e7b9affc4f28dc6daf", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1413, "license_type": "permissive", "max_line_length": 186, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/storage/infinidat/infini_pool.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module to creates, deletes or modifies pools on Infinibox.\n class Infini_pool < Base\n # @return [String] Pool Name\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Creates/Modifies Pool when present or removes when absent\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Pool Physical Capacity in MB, GB or TB units. If pool size is not set on pool creation, size will be equal to 1TB. See examples.\n attribute :size\n validates :size, type: String\n\n # @return [String, nil] Pool Virtual Capacity in MB, GB or TB units. If pool vsize is not set on pool creation, Virtual Capacity will be equal to Physical Capacity. See examples.\n attribute :vsize\n validates :vsize, type: String\n\n # @return [Boolean, nil] Enable/Disable SSD Cache on Pool\n attribute :ssd_cache\n validates :ssd_cache, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6945520639419556, "alphanum_fraction": 0.698883056640625, "avg_line_length": 54.531646728515625, "blob_id": "68af7e9c3b2740bbe82bb8e844ef08a8fcab39b0", "content_id": "d8182fe7d47bc28be8c235fac40bdcefa1e9988b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4387, "license_type": "permissive", "max_line_length": 318, "num_lines": 79, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_batch_compute_environment.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows the management of AWS Batch Compute Environments. It is idempotent and supports \"Check\" mode. Use module M(aws_batch_compute_environment) to manage the compute environment, M(aws_batch_job_queue) to manage job queues, M(aws_batch_job_definition) to manage job definitions.\n class Aws_batch_compute_environment < Base\n # @return [Object] The name for your compute environment. Up to 128 letters (uppercase and lowercase), numbers, and underscores are allowed.\n attribute :compute_environment_name\n validates :compute_environment_name, presence: true\n\n # @return [:MANAGED, :UNMANAGED] The type of the compute environment.\n attribute :type\n validates :type, presence: true, expression_inclusion: {:in=>[:MANAGED, :UNMANAGED], :message=>\"%{value} needs to be :MANAGED, :UNMANAGED\"}\n\n # @return [:present, :absent] Describes the desired state.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [:ENABLED, :DISABLED, nil] The state of the compute environment. If the state is ENABLED, then the compute environment accepts jobs from a queue and can scale out automatically based on queues.\n attribute :compute_environment_state\n validates :compute_environment_state, expression_inclusion: {:in=>[:ENABLED, :DISABLED], :message=>\"%{value} needs to be :ENABLED, :DISABLED\"}, allow_nil: true\n\n # @return [Object] The full Amazon Resource Name (ARN) of the IAM role that allows AWS Batch to make calls to other AWS services on your behalf.\n attribute :service_role\n validates :service_role, presence: true\n\n # @return [:EC2, :SPOT] The type of compute resource.\n attribute :compute_resource_type\n validates :compute_resource_type, presence: true, expression_inclusion: {:in=>[:EC2, :SPOT], :message=>\"%{value} needs to be :EC2, :SPOT\"}\n\n # @return [Object] The minimum number of EC2 vCPUs that an environment should maintain.\n attribute :minv_cpus\n validates :minv_cpus, presence: true\n\n # @return [Object] The maximum number of EC2 vCPUs that an environment can reach.\n attribute :maxv_cpus\n validates :maxv_cpus, presence: true\n\n # @return [Object, nil] The desired number of EC2 vCPUS in the compute environment.\n attribute :desiredv_cpus\n\n # @return [Object] The instance types that may be launched.\n attribute :instance_types\n validates :instance_types, presence: true\n\n # @return [Object, nil] The Amazon Machine Image (AMI) ID used for instances launched in the compute environment.\n attribute :image_id\n\n # @return [Object] The VPC subnets into which the compute resources are launched.\n attribute :subnets\n validates :subnets, presence: true\n\n # @return [Object] The EC2 security groups that are associated with instances launched in the compute environment.\n attribute :security_group_ids\n validates :security_group_ids, presence: true\n\n # @return [Object, nil] The EC2 key pair that is used for instances launched in the compute environment.\n attribute :ec2_key_pair\n\n # @return [Object] The Amazon ECS instance role applied to Amazon EC2 instances in a compute environment.\n attribute :instance_role\n validates :instance_role, presence: true\n\n # @return [Object, nil] Key-value pair tags to be applied to resources that are launched in the compute environment.\n attribute :tags\n\n # @return [Object, nil] The minimum percentage that a Spot Instance price must be when compared with the On-Demand price for that instance type before instances are launched. For example, if your bid percentage is 20%, then the Spot price must be below 20% of the current On-Demand price for that EC2 instance.\n attribute :bid_percentage\n\n # @return [Object, nil] The Amazon Resource Name (ARN) of the Amazon EC2 Spot Fleet IAM role applied to a SPOT compute environment.\n attribute :spot_iam_fleet_role\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6652286648750305, "alphanum_fraction": 0.6652286648750305, "avg_line_length": 37.63333511352539, "blob_id": "4cfa3894bc2f6cb84f3d5e32ce8c8048fb86e22c", "content_id": "7f5780124daa4eead4fa0d3e6a83e15bed437d68", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1159, "license_type": "permissive", "max_line_length": 159, "num_lines": 30, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_filter.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages top level filter objects on Cisco ACI fabrics.\n # This modules does not manage filter entries, see M(aci_filter_entry) for this functionality.\n class Aci_filter < Base\n # @return [String] The name of the filter.\n attribute :filter\n validates :filter, presence: true, type: String\n\n # @return [String, nil] Description for the filter.\n attribute :description\n validates :description, type: String\n\n # @return [String] The name of the tenant.\n attribute :tenant\n validates :tenant, presence: true, type: String\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6393775343894958, "alphanum_fraction": 0.6786197423934937, "avg_line_length": 60.58333206176758, "blob_id": "ba269de2ea9b8b41b4c000e35fde139f0ad24861", "content_id": "846c44ec203c6b5b183afe472029ca74b1c4d03c", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2956, "license_type": "permissive", "max_line_length": 301, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_profile_http_compression.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage HTTP compression profiles on a BIG-IP.\n class Bigip_profile_http_compression < Base\n # @return [String] Specifies the name of the compression profile.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Specifies the profile from which this profile inherits settings.,When creating a new profile, if this parameter is not specified, the default is the system-supplied C(httpcompression) profile.\n attribute :parent\n\n # @return [String, nil] Description of the HTTP compression profile.\n attribute :description\n validates :description, type: String\n\n # @return [Integer, nil] Maximum number of compressed bytes that the system buffers before inserting a Content-Length header (which specifies the compressed size) into the response.,When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.\n attribute :buffer_size\n validates :buffer_size, type: Integer\n\n # @return [1, 2, 3, 4, 5, 6, 7, 8, 9, nil] Specifies the degree to which the system compresses the content.,Higher compression levels cause the compression process to be slower.,Valid values are between 1 (least compression and fastest) to 9 (most compression and slowest).\n attribute :gzip_level\n validates :gzip_level, expression_inclusion: {:in=>[1, 2, 3, 4, 5, 6, 7, 8, 9], :message=>\"%{value} needs to be 1, 2, 3, 4, 5, 6, 7, 8, 9\"}, allow_nil: true\n\n # @return [1, 2, 4, 8, 16, 32, 64, 128, 256, nil] Number of kilobytes of memory that the system uses for internal compression buffers when compressing a server response.\n attribute :gzip_memory_level\n validates :gzip_memory_level, expression_inclusion: {:in=>[1, 2, 4, 8, 16, 32, 64, 128, 256], :message=>\"%{value} needs to be 1, 2, 4, 8, 16, 32, 64, 128, 256\"}, allow_nil: true\n\n # @return [1, 2, 4, 8, 16, 32, 64, 128, nil] Number of kilobytes in the window size that the system uses when compressing a server response.\n attribute :gzip_window_size\n validates :gzip_window_size, expression_inclusion: {:in=>[1, 2, 4, 8, 16, 32, 64, 128], :message=>\"%{value} needs to be 1, 2, 4, 8, 16, 32, 64, 128\"}, allow_nil: true\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [:present, :absent, nil] When C(present), ensures that the profile exists.,When C(absent), ensures the profile is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6806978583335876, "alphanum_fraction": 0.6818056106567383, "avg_line_length": 64.65454864501953, "blob_id": "03262fec9d5bf83cd0ef0d89aa66107a69250544", "content_id": "a1fc3b68d31821e625901c54f19d6f6ff23c0932", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3611, "license_type": "permissive", "max_line_length": 443, "num_lines": 55, "path": "/lib/ansible/ruby/modules/generated/files/unarchive.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The C(unarchive) module unpacks an archive.\n # By default, it will copy the source file from the local system to the target before unpacking.\n # Set C(remote_src=yes) to unpack an archive which already exists on the target.\n # For Windows targets, use the M(win_unzip) module instead.\n # If checksum validation is desired, use M(get_url) or M(uri) instead to fetch the file and set C(remote_src=yes).\n class Unarchive < Base\n # @return [String] If C(remote_src=no) (default), local path to archive file to copy to the target server; can be absolute or relative. If C(remote_src=yes), path on the target server to existing archive file to unpack.,If C(remote_src=yes) and C(src) contains C(://), the remote machine will download the file from the URL first. (version_added 2.0). This is only for simple cases, for full download support use the M(get_url) module.\n attribute :src\n validates :src, presence: true, type: String\n\n # @return [String] Remote absolute path where the archive should be unpacked.\n attribute :dest\n validates :dest, presence: true, type: String\n\n # @return [:yes, :no, nil] If true, the file is copied from local 'master' to the target machine, otherwise, the plugin will look for src archive at the target machine.,This option has been deprecated in favor of C(remote_src).,This option is mutually exclusive with C(remote_src).\n attribute :copy\n validates :copy, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] If the specified absolute path (file or directory) already exists, this step will B(not) be run.\n attribute :creates\n\n # @return [:yes, :no, nil] If set to True, return the list of files that are contained in the tarball.\n attribute :list_files\n validates :list_files, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] List the directory and file entries that you would like to exclude from the unarchive action.\n attribute :exclude\n\n # @return [:yes, :no, nil] Do not replace existing files that are newer than files from the archive.\n attribute :keep_newer\n validates :keep_newer, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Specify additional options by passing in an array.\n attribute :extra_opts\n validates :extra_opts, type: String\n\n # @return [:yes, :no, nil] Set to C(yes) to indicate the archived file is already on the remote system and not local to the Ansible controller.,This option is mutually exclusive with C(copy).\n attribute :remote_src\n validates :remote_src, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] This only applies if using a https URL as the source of the file.,This should only set to C(no) used on personally controlled sites using self-signed certificate.,Prior to 2.2 the code worked as if this was set to C(yes).\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6711656451225281, "alphanum_fraction": 0.6711656451225281, "avg_line_length": 31.600000381469727, "blob_id": "1b629945a8b3f4b3ae0462e6bd9563825c7e2b83", "content_id": "1cefabb49d1f0c517b713e38c9ea4feb0fb4df6e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 815, "license_type": "permissive", "max_line_length": 107, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/windows/win_wakeonlan.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The C(win_wakeonlan) module sends magic Wake-on-LAN (WoL) broadcast packets.\n class Win_wakeonlan < Base\n # @return [String] MAC address to send Wake-on-LAN broadcast packet for.\n attribute :mac\n validates :mac, presence: true, type: String\n\n # @return [String, nil] Network broadcast address to use for broadcasting magic Wake-on-LAN packet.\n attribute :broadcast\n validates :broadcast, type: String\n\n # @return [Integer, nil] UDP port to use for magic Wake-on-LAN packet.\n attribute :port\n validates :port, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7109800577163696, "alphanum_fraction": 0.7214155793190002, "avg_line_length": 70.09677124023438, "blob_id": "a21bf4c5177f0c3b861f22a69ad322c316c5f912", "content_id": "f40e84f88b7c36e70dc4a379e5d2ef88cd033b77", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2204, "license_type": "permissive", "max_line_length": 557, "num_lines": 31, "path": "/lib/ansible/ruby/modules/generated/network/netscaler/netscaler_cs_policy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage content switching policy.\n # This module is intended to run either on the ansible control node or a bastion (jumpserver) with access to the actual netscaler instance.\n class Netscaler_cs_policy < Base\n # @return [String, nil] Name for the content switching policy. Must begin with an ASCII alphanumeric or underscore C(_) character, and must contain only ASCII alphanumeric, underscore, hash C(#), period C(.), space C( ), colon C(:), at sign C(@), equal sign C(=), and hyphen C(-) characters. Cannot be changed after a policy is created.,The following requirement applies only to the NetScaler CLI:,If the name includes one or more spaces, enclose the name in double or single quotation marks (for example, my policy or my policy).,Minimum length = 1\n attribute :policyname\n validates :policyname, type: String\n\n # @return [String, nil] URL string that is matched with the URL of a request. Can contain a wildcard character. Specify the string value in the following format: C([[prefix] [*]] [.suffix]).,Minimum length = 1,Maximum length = 208\n attribute :url\n validates :url, type: String\n\n # @return [Object, nil] Expression, or name of a named expression, against which traffic is evaluated. Written in the classic or default syntax.,Note:,Maximum length of a string literal in the expression is 255 characters. A longer string can be split into smaller strings of up to 255 characters each, and the smaller strings concatenated with the + operator. For example, you can create a 500-character string as follows: '\"<string of 255 characters>\" + \"<string of 245 characters>\"'\n attribute :rule\n\n # @return [Object, nil] The domain name. The string value can range to 63 characters.,Minimum length = 1\n attribute :domain\n\n # @return [Object, nil] Content switching action that names the target load balancing virtual server to which the traffic is switched.\n attribute :action\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6676017045974731, "alphanum_fraction": 0.6676017045974731, "avg_line_length": 32.9523811340332, "blob_id": "0a72df24ba82fb7f667097d09519052be1ec865a", "content_id": "aa5ffe106787b99de7ecbb6e88306b2bf65fe6bc", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 713, "license_type": "permissive", "max_line_length": 143, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_ospf.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages configuration of an ospf instance.\n class Nxos_ospf < Base\n # @return [Integer] Name of the ospf instance.\n attribute :ospf\n validates :ospf, presence: true, type: Integer\n\n # @return [:present, :absent, nil] Determines whether the config should be present or not on the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7100173234939575, "alphanum_fraction": 0.7170900702476501, "avg_line_length": 86.69620513916016, "blob_id": "4d64f4827afdd0bb24d644e52bdd0d23407ba8fc", "content_id": "6f955c7cde86230bdaeacf627474f74fad3d7108", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6928, "license_type": "permissive", "max_line_length": 822, "num_lines": 79, "path": "/lib/ansible/ruby/modules/generated/net_tools/basics/get_url.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Downloads files from HTTP, HTTPS, or FTP to the remote server. The remote server I(must) have direct access to the remote resource.\n # By default, if an environment variable C(<protocol>_proxy) is set on the target host, requests will be sent through that proxy. This behaviour can be overridden by setting a variable for this task (see `setting the environment <https://docs.ansible.com/playbooks_environment.html>`_), or by using the use_proxy option.\n # HTTP redirects can redirect from HTTP to HTTPS so you should be sure that your proxy environment for both protocols is correct.\n # From Ansible 2.4 when run with C(--check), it will do a HEAD request to validate the URL but will not download the entire file or verify it against hashes.\n # For Windows targets, use the M(win_get_url) module instead.\n class Get_url < Base\n # @return [String] HTTP, HTTPS, or FTP URL in the form (http|https|ftp)://[user[:pass]]@host.domain[:port]/path\n attribute :url\n validates :url, presence: true, type: String\n\n # @return [String] Absolute path of where to download the file to.,If C(dest) is a directory, either the server provided filename or, if none provided, the base name of the URL on the remote server will be used. If a directory, C(force) has no effect.,If C(dest) is a directory, the file will always be downloaded (regardless of the C(force) option), but replaced only if the contents changed..\n attribute :dest\n validates :dest, presence: true, type: String\n\n # @return [Object, nil] Absolute path of where temporary file is downloaded to.,When run on Ansible 2.5 or greater, path defaults to ansible's remote_tmp setting,When run on Ansible prior to 2.5, it defaults to C(TMPDIR), C(TEMP) or C(TMP) env variables or a platform specific value.,U(https://docs.python.org/2/library/tempfile.html#tempfile.tempdir)\n attribute :tmp_dest\n\n # @return [:yes, :no, nil] If C(yes) and C(dest) is not a directory, will download the file every time and replace the file if the contents change. If C(no), the file will only be downloaded if the destination does not exist. Generally should be C(yes) only for small local files.,Prior to 0.6, this module behaved as if C(yes) was the default.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.\n attribute :backup\n validates :backup, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] If a SHA-256 checksum is passed to this parameter, the digest of the destination file will be calculated after it is downloaded to ensure its integrity and verify that the transfer completed successfully. This option is deprecated. Use C(checksum) instead.\n attribute :sha256sum\n validates :sha256sum, type: String\n\n # @return [String, nil] If a checksum is passed to this parameter, the digest of the destination file will be calculated after it is downloaded to ensure its integrity and verify that the transfer completed successfully. Format: <algorithm>:<checksum|url>, e.g. checksum=\"sha256:D98291AC[...]B6DC7B97\", checksum=\"sha256:http://example.com/path/sha256sum.txt\",If you worry about portability, only the sha1 algorithm is available on all platforms and python versions.,The third party hashlib library can be installed for access to additional algorithms.,Additionally, if a checksum is passed to this parameter, and the file exist under the C(dest) location, the I(destination_checksum) would be calculated, and if checksum equals I(destination_checksum), the file download would be skipped (unless C(force) is true).\n attribute :checksum\n validates :checksum, type: String\n\n # @return [:yes, :no, nil] if C(no), it will not use a proxy, even if one is defined in an environment variable on the target hosts.\n attribute :use_proxy\n validates :use_proxy, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Timeout in seconds for URL request.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [Hash, nil] Add custom HTTP headers to a request in hash/dict format. The hash/dict format was added in 2.6. Previous versions used a C(\"key:value,key:value\") string format. The C(\"key:value,key:value\") string format is deprecated and will be removed in version 2.10.\n attribute :headers\n validates :headers, type: Hash\n\n # @return [Object, nil] The username for use in HTTP basic authentication.,This parameter can be used without C(url_password) for sites that allow empty passwords.\n attribute :url_username\n\n # @return [Object, nil] The password for use in HTTP basic authentication.,If the C(url_username) parameter is not specified, the C(url_password) parameter will not be used.\n attribute :url_password\n\n # @return [:yes, :no, nil] httplib2, the library used by the uri module only sends authentication information when a webservice responds to an initial request with a 401 status. Since some basic auth services do not properly send a 401, logins will fail. This option forces the sending of the Basic authentication header upon initial request.\n attribute :force_basic_auth\n validates :force_basic_auth, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] PEM formatted certificate chain file to be used for SSL client authentication. This file can also include the key as well, and if the key is included, C(client_key) is not required.\n attribute :client_cert\n\n # @return [Object, nil] PEM formatted file that contains your private key to be used for SSL client authentication. If C(client_cert) contains both the certificate and key, this option is not required.\n attribute :client_key\n\n # @return [Object, nil] all arguments accepted by the M(file) module also work here\n attribute :others\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7153351902961731, "alphanum_fraction": 0.7153351902961731, "avg_line_length": 50.85714340209961, "blob_id": "ac3adec4950817290ad7ae681d9fcf76a2ec9fb7", "content_id": "ea7614f39355167414f67fbafd659e839bc32fed", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1089, "license_type": "permissive", "max_line_length": 376, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/remote_management/oneview/oneview_san_manager.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Provides an interface to manage SAN Manager resources. Can create, update, or delete.\n class Oneview_san_manager < Base\n # @return [:present, :absent, :connection_information_set, nil] Indicates the desired state for the Uplink Set resource. - C(present) ensures data properties are compliant with OneView. - C(absent) removes the resource from OneView, if it exists. - C(connection_information_set) updates the connection information for the SAN Manager. This operation is non-idempotent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :connection_information_set], :message=>\"%{value} needs to be :present, :absent, :connection_information_set\"}, allow_nil: true\n\n # @return [Hash] List with SAN Manager properties.\n attribute :data\n validates :data, presence: true, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6644660234451294, "alphanum_fraction": 0.6675727963447571, "avg_line_length": 37.43283462524414, "blob_id": "d193b775c95204e49d3c95a9d51abcea7339d64e", "content_id": "d2e502185642d7a6811be78dbdef0b481ddacdb7", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2575, "license_type": "permissive", "max_line_length": 195, "num_lines": 67, "path": "/lib/ansible/ruby/modules/generated/network/fortimanager/fmgr_provisioning.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add model devices on the FortiManager using jsonrpc API and have them pre-configured, so when central management is configured, the configuration is pushed down to the registering devices\n class Fmgr_provisioning < Base\n # @return [Object] The administrative domain (admon) the configuration belongs to\n attribute :adom\n validates :adom, presence: true\n\n # @return [Object, nil] The virtual domain (vdom) the configuration belongs to\n attribute :vdom\n\n # @return [Object] The FortiManager's Address.\n attribute :host\n validates :host, presence: true\n\n # @return [Object] The username to log into the FortiManager\n attribute :username\n validates :username, presence: true\n\n # @return [Object, nil] The password associated with the username account.\n attribute :password\n\n # @return [Object] The name of the policy package to be assigned to the device.\n attribute :policy_package\n validates :policy_package, presence: true\n\n # @return [String] The name of the device to be provisioned.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] The name of the device group the provisioned device can belong to.\n attribute :group\n\n # @return [Object] The serial number of the device that will be provisioned.\n attribute :serial\n validates :serial, presence: true\n\n # @return [Object] The platform of the device, such as model number or VM.\n attribute :platform\n validates :platform, presence: true\n\n # @return [Object, nil] Description of the device to be provisioned.\n attribute :description\n\n # @return [Object] The Fortinet OS version to be used for the device, such as 5.0 or 6.0.\n attribute :os_version\n validates :os_version, presence: true\n\n # @return [Object, nil] The minor release number such as 6.X.1, as X being the minor release.\n attribute :minor_release\n\n # @return [Object, nil] The patch release number such as 6.0.X, as X being the patch release.\n attribute :patch_release\n\n # @return [Object] The Fortinet OS type to be pushed to the device, such as 'FOS' for FortiOS.\n attribute :os_type\n validates :os_type, presence: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6519337296485901, "alphanum_fraction": 0.6519337296485901, "avg_line_length": 47.56097412109375, "blob_id": "acf4b5255a11c4eb2a7cfa4404b14aa77c998a49", "content_id": "fd4bb76a99b7c95b07ace10ab8c9d79ea2275eb2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1991, "license_type": "permissive", "max_line_length": 184, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/system/sysctl.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module manipulates sysctl entries and optionally performs a C(/sbin/sysctl -p) after changing them.\n class Sysctl < Base\n # @return [String] The dot-separated path (aka I(key)) specifying the sysctl variable.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Integer, nil] Desired value of the sysctl key.\n attribute :value\n validates :value, type: Integer\n\n # @return [:present, :absent, nil] Whether the entry should be present or absent in the sysctl file.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Use this option to ignore errors about unknown keys.\n attribute :ignoreerrors\n validates :ignoreerrors, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(yes), performs a I(/sbin/sysctl -p) if the C(sysctl_file) is updated. If C(no), does not reload I(sysctl) even if the C(sysctl_file) is updated.\n attribute :reload\n validates :reload, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Specifies the absolute path to C(sysctl.conf), if not C(/etc/sysctl.conf).\n attribute :sysctl_file\n validates :sysctl_file, type: String\n\n # @return [:yes, :no, nil] Verify token value with the sysctl command and set with -w if necessary\n attribute :sysctl_set\n validates :sysctl_set, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6305460929870605, "alphanum_fraction": 0.63225257396698, "avg_line_length": 23.41666603088379, "blob_id": "861edd5b56687e73ad125571a9fd7c8b572ad604", "content_id": "296d8db0150d631e0d0fb76c300bbcc99b403eee", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1172, "license_type": "permissive", "max_line_length": 86, "num_lines": 48, "path": "/spec/support/matchers/have_yaml.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nRSpec::Matchers.define :have_yaml do |*expected|\n match do |_|\n filename = expected[0]\n options = expected[1]\n unless filename\n @our_messages = \"'Expected' should be 'something.yml'\"\n next false\n end\n\n unless !options || (options.is_a?(Hash) && options.keys == [:that])\n @our_messages = \"'Expected' should be 'something.yml, that: eq('foobar')'\"\n next false\n end\n\n unless File.exist?(filename)\n @our_messages = \"File #{filename} does not exist!\"\n next false\n end\n\n next true unless options\n\n file_contents = File.read filename\n @matcher = options[:that]\n @matcher.matches? file_contents\n end\n\n match_when_negated do |_|\n actual = Dir.glob('**/*.yml')\n if expected.any?\n @matcher = include(*expected)\n @negate_message = true\n @matcher.does_not_match? actual\n else\n @matcher = be_empty\n @matcher.matches? actual\n end\n end\n\n failure_message do |_|\n @our_messages || @matcher.failure_message\n end\n\n failure_message_when_negated do |_|\n @negate_message ? @matcher.failure_message_when_negated : @matcher.failure_message\n end\nend\n" }, { "alpha_fraction": 0.6682903170585632, "alphanum_fraction": 0.6736482977867126, "avg_line_length": 46.74418640136719, "blob_id": "b1e1748533e65a724f8f13e668ba931fa3c2d664", "content_id": "cc55c865b01f3f23bdda88af5ddb7d35ceccb174", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2053, "license_type": "permissive", "max_line_length": 173, "num_lines": 43, "path": "/lib/ansible/ruby/modules/generated/network/slxos/slxos_l2_interface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of Layer-2 interface on Extreme slxos devices.\n class Slxos_l2_interface < Base\n # @return [String] Full name of the interface excluding any logical unit number, i.e. Ethernet 0/1.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:access, :trunk, nil] Mode in which interface needs to be configured.\n attribute :mode\n validates :mode, expression_inclusion: {:in=>[:access, :trunk], :message=>\"%{value} needs to be :access, :trunk\"}, allow_nil: true\n\n # @return [Integer, nil] Configure given VLAN in access port. If C(mode=access), used as the access VLAN ID.\n attribute :access_vlan\n validates :access_vlan, type: Integer\n\n # @return [String, nil] List of VLANs to be configured in trunk port. If C(mode=trunk), used as the VLAN range to ADD or REMOVE from the trunk.\n attribute :trunk_vlans\n validates :trunk_vlans, type: String\n\n # @return [Integer, nil] Native VLAN to be configured in trunk port. If C(mode=trunk), used as the trunk native VLAN ID.\n attribute :native_vlan\n validates :native_vlan, type: Integer\n\n # @return [Object, nil] List of allowed VLANs in a given trunk port. If C(mode=trunk), these are the only VLANs that will be configured on the trunk, i.e. \"2-10,15\".\n attribute :trunk_allowed_vlans\n\n # @return [Object, nil] List of Layer-2 interface definitions.\n attribute :aggregate\n\n # @return [:present, :absent, :unconfigured, nil] Manage the state of the Layer-2 Interface configuration.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :unconfigured], :message=>\"%{value} needs to be :present, :absent, :unconfigured\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7292666435241699, "alphanum_fraction": 0.7354352474212646, "avg_line_length": 78.58181762695312, "blob_id": "12db00b218defb6a8c3fb2035c79d1b4ba9eeda4", "content_id": "8503498b188a0b6b5e46af2bd099e32959d1d9ab", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4377, "license_type": "permissive", "max_line_length": 623, "num_lines": 55, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_compute_route.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Represents a Route resource.\n # A route is a rule that specifies how certain packets should be handled by the virtual network. Routes are associated with virtual machines by tag, and the set of routes for a particular virtual machine is called its routing table. For each packet leaving a virtual machine, the system searches that virtual machine's routing table for a single best matching route.\n # Routes match packets by destination IP address, preferring smaller or more specific ranges over larger ones. If there is a tie, the system selects the route with the smallest priority value. If there is still a tie, it uses the layer three and four packet headers to select just one of the remaining matching routes. The packet is then forwarded as specified by the next_hop field of the winning route -- either to another virtual machine destination, a virtual machine gateway or a Compute Engine-operated gateway. Packets that do not match any route in the sending virtual machine's routing table will be dropped.\n # A Route resource must have exactly one specification of either nextHopGateway, nextHopInstance, nextHopIp, or nextHopVpnTunnel.\n class Gcp_compute_route < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The destination range of outgoing packets that this route applies to.,Only IPv4 is supported.\n attribute :dest_range\n validates :dest_range, presence: true, type: String\n\n # @return [Object, nil] An optional description of this resource. Provide this property when you create the resource.\n attribute :description\n\n # @return [String] Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] The network that this route applies to.\n attribute :network\n validates :network, presence: true, type: String\n\n # @return [Object, nil] The priority of this route. Priority is used to break ties in cases where there is more than one matching route of equal prefix length.,In the case of two routes with equal prefix length, the one with the lowest-numbered priority value wins.,Default value is 1000. Valid range is 0 through 65535.\n attribute :priority\n\n # @return [Array<String>, String, nil] A list of instance tags to which this route applies.\n attribute :tags\n validates :tags, type: TypeGeneric.new(String)\n\n # @return [String, nil] URL to a gateway that should handle matching packets.,Currently, you can only specify the internet gateway, using a full or partial valid URL: * U(https://www.googleapis.com/compute/v1/projects/project/global/gateways/default-internet-gateway) * projects/project/global/gateways/default-internet-gateway * global/gateways/default-internet-gateway .\n attribute :next_hop_gateway\n validates :next_hop_gateway, type: String\n\n # @return [Object, nil] URL to an instance that should handle matching packets.,You can specify this as a full or partial URL. For example: * U(https://www.googleapis.com/compute/v1/projects/project/zones/zone/) instances/instance * projects/project/zones/zone/instances/instance * zones/zone/instances/instance .\n attribute :next_hop_instance\n\n # @return [Object, nil] Network IP address of an instance that should handle matching packets.\n attribute :next_hop_ip\n\n # @return [Object, nil] URL to a VpnTunnel that should handle matching packets.\n attribute :next_hop_vpn_tunnel\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6740041971206665, "alphanum_fraction": 0.6740041971206665, "avg_line_length": 33.07143020629883, "blob_id": "f4c1bd8b746f8796fa61b8c718431189acf247b1", "content_id": "18f75a6805ade3517576bb19de5127978c17163a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 954, "license_type": "permissive", "max_line_length": 126, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/notification/pushover.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Send notifications via pushover, to subscriber list of devices, and email addresses. Requires pushover app on devices.\n class Pushover < Base\n # @return [String] What message you wish to send.\n attribute :msg\n validates :msg, presence: true, type: String\n\n # @return [String] Pushover issued token identifying your pushover app.\n attribute :app_token\n validates :app_token, presence: true, type: String\n\n # @return [String] Pushover issued authentication key for your user.\n attribute :user_key\n validates :user_key, presence: true, type: String\n\n # @return [Object, nil] Message priority (see U(https://pushover.net) for details.)\n attribute :pri\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6313427686691284, "alphanum_fraction": 0.6427338719367981, "avg_line_length": 54.71154022216797, "blob_id": "df686fd675e2cf707583b6493abd5e4a3a3f87fb", "content_id": "bb8b6a215b790475beec9a5e192156da2b264738", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2897, "license_type": "permissive", "max_line_length": 233, "num_lines": 52, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_export_policy_rule.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or delete or modify export rules in ONTAP\n class Na_ontap_export_policy_rule < Base\n # @return [:present, :absent, nil] Whether the specified export policy rule should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The name of the export rule to manage.\n attribute :policy_name\n validates :policy_name, presence: true, type: String\n\n # @return [String, nil] List of Client Match Hostnames, IP Addresses, Netgroups, or Domains\n attribute :client_match\n validates :client_match, type: String\n\n # @return [:any, :none, :never, :krb5, :krb5i, :krb5p, :ntlm, :sys, nil] Read only access specifications for the rule\n attribute :ro_rule\n validates :ro_rule, expression_inclusion: {:in=>[:any, :none, :never, :krb5, :krb5i, :krb5p, :ntlm, :sys], :message=>\"%{value} needs to be :any, :none, :never, :krb5, :krb5i, :krb5p, :ntlm, :sys\"}, allow_nil: true\n\n # @return [:any, :none, :never, :krb5, :krb5i, :krb5p, :ntlm, :sys, nil] Read Write access specifications for the rule\n attribute :rw_rule\n validates :rw_rule, expression_inclusion: {:in=>[:any, :none, :never, :krb5, :krb5i, :krb5p, :ntlm, :sys], :message=>\"%{value} needs to be :any, :none, :never, :krb5, :krb5i, :krb5p, :ntlm, :sys\"}, allow_nil: true\n\n # @return [:any, :none, :never, :krb5, :krb5i, :krb5p, :ntlm, :sys, nil] Read Write access specifications for the rule\n attribute :super_user_security\n validates :super_user_security, expression_inclusion: {:in=>[:any, :none, :never, :krb5, :krb5i, :krb5p, :ntlm, :sys], :message=>\"%{value} needs to be :any, :none, :never, :krb5, :krb5i, :krb5p, :ntlm, :sys\"}, allow_nil: true\n\n # @return [Symbol, nil] If 'true', NFS server will honor SetUID bits in SETATTR operation. Default value on creation is 'true'\n attribute :allow_suid\n validates :allow_suid, type: Symbol\n\n # @return [:any, :nfs, :nfs3, :nfs4, :cifs, :flexcache, nil] Client access protocol. Default value is 'any'\n attribute :protocol\n validates :protocol, expression_inclusion: {:in=>[:any, :nfs, :nfs3, :nfs4, :cifs, :flexcache], :message=>\"%{value} needs to be :any, :nfs, :nfs3, :nfs4, :cifs, :flexcache\"}, allow_nil: true\n\n # @return [Object, nil] rule index of the export policy for delete and modify\n attribute :rule_index\n\n # @return [String] Name of the vserver to use.\n attribute :vserver\n validates :vserver, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6653524041175842, "alphanum_fraction": 0.6653524041175842, "avg_line_length": 35.23214340209961, "blob_id": "454ecadea8e1d812be4470325c5b1705cf4ce3d1", "content_id": "219a3e7ee4805783ae53460e074bb3b889da1b5a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2029, "license_type": "permissive", "max_line_length": 98, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/remote_management/redfish/redfish_command.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Builds Redfish URIs locally and sends them to remote OOB controllers to perform an action.\n # Manages OOB controller ex. reboot, log management.\n # Manages OOB controller users ex. add, remove, update.\n # Manages system power ex. on, off, graceful and forced reboot.\n class Redfish_command < Base\n # @return [String] Category to execute on OOB controller\n attribute :category\n validates :category, presence: true, type: String\n\n # @return [Array<String>, String] List of commands to execute on OOB controller\n attribute :command\n validates :command, presence: true, type: TypeGeneric.new(String)\n\n # @return [String] Base URI of OOB controller\n attribute :baseuri\n validates :baseuri, presence: true, type: String\n\n # @return [String] User for authentication with OOB controller\n attribute :user\n validates :user, presence: true, type: String\n\n # @return [String] Password for authentication with OOB controller\n attribute :password\n validates :password, presence: true, type: String\n\n # @return [String, nil] ID of user to add/delete/modify\n attribute :userid\n validates :userid, type: String\n\n # @return [String, nil] name of user to add/delete/modify\n attribute :username\n validates :username, type: String\n\n # @return [String, nil] password of user to add/delete/modify\n attribute :userpswd\n validates :userpswd, type: String\n\n # @return [String, nil] role of user to add/delete/modify\n attribute :userrole\n validates :userrole, type: String\n\n # @return [String, nil] bootdevice when setting boot configuration\n attribute :bootdevice\n validates :bootdevice, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5466893315315247, "alphanum_fraction": 0.5504244565963745, "avg_line_length": 22.098039627075195, "blob_id": "f7e9c76a738e86beeeb86b6a8f076395832010fe", "content_id": "d9f63cdfff52a816d7b11c5a6fea64c818964d11", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5890, "license_type": "permissive", "max_line_length": 107, "num_lines": 255, "path": "/lib/ansible/ruby/dsl_builders/module_call_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'spec_helper'\nrequire 'ansible-ruby'\n\ndescribe Ansible::Ruby::DslBuilders::ModuleCall do\n let(:builder) { Ansible::Ruby::DslBuilders::ModuleCall.new }\n\n let(:evaluated_builder) do\n evaluate\n builder\n end\n\n def evaluate\n builder.instance_eval ruby\n builder._result\n end\n\n subject { evaluate }\n\n before do\n klass = Class.new(Ansible::Ruby::Modules::Base) do\n attribute :src\n validates :src, presence: true\n attribute :dest\n validates :dest, presence: true\n end\n stub_const 'Ansible::Ruby::Modules::Copy', klass\n klass = Class.new(Ansible::Ruby::Modules::Base) do\n attribute :src\n validates :src, presence: true\n end\n stub_const 'Ansible::Ruby::Modules::Gem', klass\n end\n\n context 'gem keyword' do\n let(:ruby) do\n <<-RUBY\n gem do\n src '/file1.conf'\n end\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Modules::Gem }\n it { is_expected.to have_attributes src: '/file1.conf' }\n end\n\n context 'fail module' do\n let(:ruby) do\n <<-RUBY\n ansible_fail do\n msg 'This is why we failed'\n end\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Modules::Fail }\n it { is_expected.to have_attributes msg: 'This is why we failed' }\n end\n\n context 'non free-form module' do\n let(:ruby) do\n <<-RUBY\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Modules::Copy }\n it { is_expected.to have_attributes src: '/file1.conf', dest: '/file2.conf' }\n end\n\n context 'jinja' do\n let(:ruby) do\n <<-RUBY\n copy do\n src jinja('a_file')\n dest '/file2.conf'\n end\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Modules::Copy }\n it do\n is_expected.to have_attributes src: Ansible::Ruby::Models::JinjaExpression.new('a_file'),\n dest: '/file2.conf'\n end\n end\n\n context 'free form' do\n context 'using free form name on non free-form module' do\n let(:ruby) do\n <<-RUBY\n copy 'howdy' do\n src '/file1.conf'\n dest '/file2.conf'\n end\n RUBY\n end\n\n it 'should raise an error' do\n expect {evaluate}.to raise_error \"Can't use arguments [\\\"howdy\\\"] on this type of module\"\n end\n end\n\n context 'no block' do\n let(:ruby) do\n <<-RUBY\n copy()\n RUBY\n end\n\n it 'should raise an error' do\n expect {evaluate}.to raise_error 'You must supply a block when using this type of module'\n end\n end\n\n context 'valid module' do\n before do\n klass_free_form = Class.new(Ansible::Ruby::Models::Base) do\n attribute :free_form\n validates :free_form, presence: true\n\n attribute :foo\n end\n stub_const 'Ansible::Ruby::Modules::Command', klass_free_form\n # simulate monkey patching existing\n klass_free_form.class_eval do\n include Ansible::Ruby::Modules::FreeForm\n end\n end\n\n context 'block, no jinja' do\n let(:ruby) do\n <<-RUBY\n command 'ls /stuff' do\n foo '/file1.conf'\n end\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Modules::Command }\n it { is_expected.to have_attributes free_form: 'ls /stuff', foo: '/file1.conf' }\n end\n\n context 'jinja item in name' do\n let(:ruby) do\n <<-RUBY\n item = Ansible::Ruby::DslBuilders::JinjaItemNode.new\n\n command item\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Modules::Command }\n it { is_expected.to have_attributes free_form: Ansible::Ruby::Models::JinjaExpression.new('item') }\n end\n\n context 'no block' do\n let(:ruby) do\n <<-RUBY\n command 'ls /stuff'\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Modules::Command }\n it { is_expected.to have_attributes free_form: 'ls /stuff' }\n end\n\n context 'too many args' do\n let(:ruby) do\n <<-RUBY\n command 'ls /stuff', 'more' do\n foo '/file1.conf'\n end\n RUBY\n end\n\n it 'should raise an error' do\n expect {evaluate}.to raise_error 'Expected only 1 argument for this type of module'\n end\n end\n\n context 'free form not supplied' do\n let(:ruby) do\n <<-RUBY\n command do\n foo '/file1.conf'\n end\n RUBY\n end\n\n it 'should raise an error' do\n expect {evaluate}.to raise_error 'Expected 1 argument for this type of module'\n end\n end\n\n context 'argument not found' do\n let(:ruby) do\n <<-RUBY\n command 'ls /stuff' do\n bar '/file1.conf'\n end\n RUBY\n end\n\n it 'should raise an error' do\n expect {evaluate}.to raise_error <<~ERROR\n Unknown attribute 'bar' for Ansible::Ruby::Modules::Command.\n\n Valid attributes are: [:foo]\n ERROR\n end\n end\n end\n end\n\n context 'attribute missing' do\n let(:ruby) do\n <<-RUBY\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n\n copy do\n src '/file1.conf'\n end\n RUBY\n end\n\n it 'should raise an error' do\n expect {evaluate}.to raise_error \"Validation failed: Dest can't be blank\"\n end\n end\n\n context 'not found' do\n let(:ruby) do\n <<-RUBY\n # comments\n foo_copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n RUBY\n end\n\n it 'should raise an error' do\n expect {evaluate}.to raise_error 'Unknown module foo_copy'\n end\n end\nend\n" }, { "alpha_fraction": 0.6989051103591919, "alphanum_fraction": 0.7003649473190308, "avg_line_length": 69.25640869140625, "blob_id": "34c114082b56e8c26fbc6232069c587613a5d5c9", "content_id": "02885e4bd27b9f73650f6502448df9500efb1c20", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5480, "license_type": "permissive", "max_line_length": 860, "num_lines": 78, "path": "/lib/ansible/ruby/modules/generated/cloud/docker/docker_image.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Build, load or pull an image, making the image available for creating containers. Also supports tagging an image into a repository and archiving an image to a .tar file.\n class Docker_image < Base\n # @return [String, nil] Use with state C(present) to archive an image to a .tar file.\n attribute :archive_path\n validates :archive_path, type: String\n\n # @return [String, nil] Use with state C(present) to load an image from a .tar file.\n attribute :load_path\n validates :load_path, type: String\n\n # @return [Object, nil] Use with state C(present) to provide an alternate name for the Dockerfile to use when building an image.\n attribute :dockerfile\n\n # @return [Symbol, nil] Use with state I(absent) to un-tag and remove all images matching the specified name. Use with state C(present) to build, load or pull an image when the image already exists.\n attribute :force\n validates :force, type: Symbol\n\n # @return [Object, nil] Timeout for HTTP requests during the image build operation. Provide a positive integer value for the number of seconds.\n attribute :http_timeout\n\n # @return [String] Image name. Name format will be one of: name, repository/name, registry_server:port/name. When pushing or pulling an image the name can optionally include the tag by appending ':tag_name'.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Use with state 'present' to build an image. Will be the path to a directory containing the context and Dockerfile for building an image.\n attribute :path\n validates :path, type: String\n\n # @return [Boolean, nil] When building an image downloads any updates to the FROM image in Dockerfile.\n attribute :pull\n validates :pull, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Symbol, nil] Push the image to the registry. Specify the registry as part of the I(name) or I(repository) parameter.\n attribute :push\n validates :push, type: Symbol\n\n # @return [Boolean, nil] Remove intermediate containers after build.\n attribute :rm\n validates :rm, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Symbol, nil] Do not use cache when building an image.\n attribute :nocache\n validates :nocache, type: Symbol\n\n # @return [String, nil] Full path to a repository. Use with state C(present) to tag the image into the repository. Expects format I(repository:tag). If no tag is provided, will use the value of the C(tag) parameter or I(latest).\n attribute :repository\n validates :repository, type: String\n\n # @return [:absent, :present, :build, nil] Make assertions about the state of an image.,When C(absent) an image will be removed. Use the force option to un-tag and remove all images matching the provided name.,When C(present) check if an image exists using the provided name and tag. If the image is not found or the force option is used, the image will either be pulled, built or loaded. By default the image will be pulled from Docker Hub. To build the image, provide a path value set to a directory containing a context and Dockerfile. To load an image, specify load_path to provide a path to an archive file. To tag an image to a repository, provide a repository path. If the name contains a repository path, it will be pushed.,NOTE: C(build) is DEPRECATED and will be removed in release 2.3. Specifying C(build) will behave the same as C(present).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :build], :message=>\"%{value} needs to be :absent, :present, :build\"}, allow_nil: true\n\n # @return [String, nil] Used to select an image when pulling. Will be added to the image when pushing, tagging or building. Defaults to I(latest).,If C(name) parameter format is I(name:tag), then tag value from C(name) will take precedence.\n attribute :tag\n validates :tag, type: String\n\n # @return [Hash, nil] Provide a dictionary of C(key:value) build arguments that map to Dockerfile ARG directive.,Docker expects the value to be a string. For convenience any non-string values will be converted to strings.,Requires Docker API >= 1.21 and docker-py >= 1.7.0.\n attribute :buildargs\n validates :buildargs, type: Hash\n\n # @return [Object, nil] A dictionary of limits applied to each container created by the build process.\n attribute :container_limits\n\n # @return [:no, :encrypt, :verify, nil] DEPRECATED. Whether to use tls to connect to the docker server. Set to C(no) when TLS will not be used. Set to C(encrypt) to use TLS. And set to C(verify) to use TLS and verify that the server's certificate is valid for the server. NOTE: If you specify this option, it will set the value of the tls or tls_verify parameters.\n attribute :use_tls\n validates :use_tls, expression_inclusion: {:in=>[:no, :encrypt, :verify], :message=>\"%{value} needs to be :no, :encrypt, :verify\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6754468679428101, "alphanum_fraction": 0.6754468679428101, "avg_line_length": 36.96428680419922, "blob_id": "33d1c040ed81da972368f8b7c20436dfc0236e0e", "content_id": "056d03a5d7fc1641abb8af9f9f8ecc41f729b6df", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1063, "license_type": "permissive", "max_line_length": 151, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/network/panos/panos_import.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Import file on PAN-OS device\n class Panos_import < Base\n # @return [String, nil] Category of file uploaded. The default is software.,See API > Import section of the API reference for category options.\n attribute :category\n validates :category, type: String\n\n # @return [String, nil] Location of the file to import into device.\n attribute :file\n validates :file, type: String\n\n # @return [Object, nil] URL of the file that will be imported to device.\n attribute :url\n\n # @return [Boolean, nil] If C(no), SSL certificates will not be validated. Disabling certificate validation is not recommended.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6783625483512878, "alphanum_fraction": 0.6783625483512878, "avg_line_length": 19.117647171020508, "blob_id": "1f72fecc4f2746d2e0fca3bb9de7cf5435f820f6", "content_id": "802c5ffc3ac9a3ee3dde64a8e9ceca66e05708c0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 342, "license_type": "permissive", "max_line_length": 87, "num_lines": 17, "path": "/lib/ansible/ruby/models/multiple_types.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# See LICENSE.txt for license\n\nclass MultipleTypes\n def initialize(*klasses)\n @klasses = klasses\n end\n\n def valid?(value)\n @klasses.any? { |klass| value.is_a? klass }\n end\n\n def error(attribute, value)\n \"Attribute #{attribute} expected to be one of #{@klasses} but was a #{value.class}\"\n end\nend\n" }, { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.6776922941207886, "avg_line_length": 49, "blob_id": "e60a5d3d30cf6cf41e1cfd09bc821e7a6008536a", "content_id": "79b78907f8d5b38777f5b9fb4a1da1a870e2491c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1300, "license_type": "permissive", "max_line_length": 294, "num_lines": 26, "path": "/lib/ansible/ruby/modules/generated/remote_management/ucs/ucs_ntp_server.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configures NTP server on Cisco UCS Manager.\n # Examples can be used with the L(UCS Platform Emulator,https://communities.cisco.com/ucspe).\n class Ucs_ntp_server < Base\n # @return [:absent, :present, nil] If C(absent), will remove an NTP server.,If C(present), will add or update an NTP server.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] NTP server IP address or hostname.,Enter up to 63 characters that form a valid hostname.,Enter a valid IPV4 Address.\n attribute :ntp_server\n validates :ntp_server, type: String\n\n # @return [String, nil] A user-defined description of the NTP server.,Enter up to 256 characters.,You can use any characters or spaces except the following:,` (accent mark), (backslash), ^ (carat), \" (double quote), = (equal sign), > (greater than), < (less than), or ' (single quote).\n attribute :description\n validates :description, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6606060862541199, "alphanum_fraction": 0.6606060862541199, "avg_line_length": 35.09375, "blob_id": "51c18aee80d82efc2fa26c658d3878db21942cde", "content_id": "bcd918b43a442195840c187caf735eb73e13d633", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1155, "license_type": "permissive", "max_line_length": 143, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_project_access.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove flavor, volume_type or other resources access from OpenStack.\n class Os_project_access < Base\n # @return [:present, :absent, nil] Indicate desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] Project id.\n attribute :target_project_id\n validates :target_project_id, presence: true, type: String\n\n # @return [String, nil] The resource type (eg. nova_flavor, cinder_volume_type).\n attribute :resource_type\n validates :resource_type, type: String\n\n # @return [String, nil] The resource name (eg. tiny).\n attribute :resource_name\n validates :resource_name, type: String\n\n # @return [Object, nil] The availability zone of the resource.\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6467847228050232, "alphanum_fraction": 0.6505125761032104, "avg_line_length": 30.558822631835938, "blob_id": "9bdd56bd8db6e0531d662daac88ae0ea9f76c6b4", "content_id": "6025cf1d0fc5c9e6b3f59f716d6e699646a152d8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1073, "license_type": "permissive", "max_line_length": 87, "num_lines": 34, "path": "/lib/ansible/ruby/modules/generated/clustering/etcd3.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Sets or deletes values in etcd3 cluster using its v3 api.\n # Needs python etcd3 lib to work\n class Etcd3 < Base\n # @return [String] the key where the information is stored in the cluster\n attribute :key\n validates :key, presence: true, type: String\n\n # @return [String] the information stored\n attribute :value\n validates :value, presence: true, type: String\n\n # @return [String, nil] the IP address of the cluster\n attribute :host\n validates :host, type: String\n\n # @return [Integer, nil] the port number used to connect to the cluster\n attribute :port\n validates :port, type: Integer\n\n # @return [String] the state of the value for the key.,can be present or absent\n attribute :state\n validates :state, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6474820375442505, "alphanum_fraction": 0.6604316830635071, "avg_line_length": 41.121212005615234, "blob_id": "bda52751a2b4ee544708a302385a288a4feead6d", "content_id": "b2079ac7ce575eaf95aa1b732b90cce3233739e9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1390, "license_type": "permissive", "max_line_length": 143, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/storage/infinidat/infini_export_client.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module creates, deletes or modifys NFS client(s) for existing exports on Infinibox.\n class Infini_export_client < Base\n # @return [String] Client IP or Range. Ranges can be defined as follows 192.168.0.1-192.168.0.254.\n attribute :client\n validates :client, presence: true, type: String\n\n # @return [:present, :absent, nil] Creates/Modifies client when present and removes when absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:RW, :RO, nil] Read Write or Read Only Access.\n attribute :access_mode\n validates :access_mode, expression_inclusion: {:in=>[:RW, :RO], :message=>\"%{value} needs to be :RW, :RO\"}, allow_nil: true\n\n # @return [Symbol, nil] Don't squash root user to anonymous. Will be set to \"no\" on creation if not specified explicitly.\n attribute :no_root_squash\n validates :no_root_squash, type: Symbol\n\n # @return [String] Name of the export.\n attribute :export\n validates :export, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7166776061058044, "alphanum_fraction": 0.7166776061058044, "avg_line_length": 66.68888854980469, "blob_id": "020dfc9cde23c53868e3ea442114c589d2860f61", "content_id": "9504713248781dd4b5886a9783e2973c8ed62f98", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3046, "license_type": "permissive", "max_line_length": 399, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_ucs.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage upload, installation and removal of UCS files.\n class Bigip_ucs < Base\n # @return [Symbol, nil] During restore of the UCS file, include chassis level configuration that is shared among boot volume sets. For example, cluster default configuration.\n attribute :include_chassis_level_config\n validates :include_chassis_level_config, type: Symbol\n\n # @return [String, nil] The path to the UCS file to install. The parameter must be provided if the C(state) is either C(installed) or C(activated). When C(state) is C(absent), the full path for this parameter will be ignored and only the filename will be used to select a UCS for removal. Therefore you could specify C(/mickey/mouse/test.ucs) and this module would only look for C(test.ucs).\n attribute :ucs\n validates :ucs, type: String\n\n # @return [Symbol, nil] If C(yes) will upload the file every time and replace the file on the device. If C(no), the file will only be uploaded if it does not already exist. Generally should be C(yes) only in cases where you have reason to believe that the image was corrupted during upload.\n attribute :force\n validates :force, type: Symbol\n\n # @return [Symbol, nil] Performs a full restore of the UCS file and all the files it contains, with the exception of the license file. The option must be used to restore a UCS on RMA devices (Returned Materials Authorization).\n attribute :no_license\n validates :no_license, type: Symbol\n\n # @return [Symbol, nil] Bypasses the platform check and allows a UCS that was created using a different platform to be installed. By default (without this option), a UCS created from a different platform is not allowed to be installed.\n attribute :no_platform_check\n validates :no_platform_check, type: Symbol\n\n # @return [Symbol, nil] Specifies the passphrase that is necessary to load the specified UCS file.\n attribute :passphrase\n validates :passphrase, type: Symbol\n\n # @return [Symbol, nil] When specified, the device and trust domain certs and keys are not loaded from the UCS. Instead, a new set is regenerated.\n attribute :reset_trust\n validates :reset_trust, type: Symbol\n\n # @return [:absent, :installed, :present, nil] When C(installed), ensures that the UCS is uploaded and installed, on the system. When C(present), ensures that the UCS is uploaded. When C(absent), the UCS will be removed from the system. When C(installed), the uploading of the UCS is idempotent, however the installation of that configuration is not idempotent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :installed, :present], :message=>\"%{value} needs to be :absent, :installed, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6327450275421143, "alphanum_fraction": 0.6470146179199219, "avg_line_length": 45.71929931640625, "blob_id": "e48a5a2b1742d7400c7766e935096aa2c040f022", "content_id": "7bb8036b9cdad83843b87e82645e7cce36e42426", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2663, "license_type": "permissive", "max_line_length": 211, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_snmp_target_host.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages SNMP target host configurations on HUAWEI CloudEngine switches.\n class Ce_snmp_target_host < Base\n # @return [:none, :v1, :v2c, :v3, :v1v2c, :v1v3, :v2cv3, :all, nil] Version(s) Supported by SNMP Engine.\n attribute :version\n validates :version, expression_inclusion: {:in=>[:none, :v1, :v2c, :v3, :v1v2c, :v1v3, :v2cv3, :all], :message=>\"%{value} needs to be :none, :v1, :v2c, :v3, :v1v2c, :v1v3, :v2cv3, :all\"}, allow_nil: true\n\n # @return [Object, nil] Udp port used by SNMP agent to connect the Network management.\n attribute :connect_port\n\n # @return [Object, nil] Unique name to identify target host entry.\n attribute :host_name\n\n # @return [Object, nil] Network Address.\n attribute :address\n\n # @return [:trap, :inform, nil] To configure notify type as trap or inform.\n attribute :notify_type\n validates :notify_type, expression_inclusion: {:in=>[:trap, :inform], :message=>\"%{value} needs to be :trap, :inform\"}, allow_nil: true\n\n # @return [Object, nil] VPN instance Name.\n attribute :vpn_name\n\n # @return [Object, nil] UDP Port number used by network management to receive alarm messages.\n attribute :recv_port\n\n # @return [:v1, :v2c, :v3, nil] Security Model.\n attribute :security_model\n validates :security_model, expression_inclusion: {:in=>[:v1, :v2c, :v3], :message=>\"%{value} needs to be :v1, :v2c, :v3\"}, allow_nil: true\n\n # @return [Object, nil] Security Name.\n attribute :security_name\n\n # @return [Object, nil] Security Name V3.\n attribute :security_name_v3\n\n # @return [:noAuthNoPriv, :authentication, :privacy, nil] Security level indicating whether to use authentication and encryption.\n attribute :security_level\n validates :security_level, expression_inclusion: {:in=>[:noAuthNoPriv, :authentication, :privacy], :message=>\"%{value} needs to be :noAuthNoPriv, :authentication, :privacy\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] To enable or disable Public Net-manager for target Host.\n attribute :is_public_net\n validates :is_public_net, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [Object, nil] Name of the interface to send the trap message.\n attribute :interface_name\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.682170569896698, "alphanum_fraction": 0.6862505078315735, "avg_line_length": 57.35714340209961, "blob_id": "270545427c5eacaa319cd2e6d0054bf14d972ec6", "content_id": "572bcdc346203f039ff86ab812ac797890c03575", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2451, "license_type": "permissive", "max_line_length": 264, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_elb.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module de-registers or registers an AWS EC2 instance from the ELBs that it belongs to.\n # Returns fact \"ec2_elbs\" which is a list of elbs attached to the instance if state=absent is passed as an argument.\n # Will be marked changed when called only if there are ELBs found to operate on.\n class Ec2_elb < Base\n # @return [:present, :absent] register or deregister the instance\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [Object] EC2 Instance ID\n attribute :instance_id\n validates :instance_id, presence: true\n\n # @return [Object, nil] List of ELB names, required for registration. The ec2_elbs fact should be used if there was a previous de-register.\n attribute :ec2_elbs\n\n # @return [:yes, :no, nil] Whether to enable the availability zone of the instance on the target ELB if the availability zone has not already been enabled. If set to no, the task will fail if the availability zone is not enabled on the ELB.\n attribute :enable_availability_zone\n validates :enable_availability_zone, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Wait for instance registration or deregistration to complete successfully before returning.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] When set to \"no\", SSL certificates will not be validated for boto versions >= 2.6.0.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Number of seconds to wait for an instance to change state. If 0 then this module may return an error if a transient error occurs. If non-zero then any transient errors are ignored until the timeout is reached. Ignored when wait=no.\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6991766691207886, "alphanum_fraction": 0.6998100280761719, "avg_line_length": 64.79166412353516, "blob_id": "5bad271fb7dff162fa672cab76354320fae43f22", "content_id": "de1d1fa332a806d3227c36973f722ff0ac012281", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1579, "license_type": "permissive", "max_line_length": 560, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Collect facts from F5 BIG-IP devices via iControl SOAP API\n class Bigip_facts < Base\n # @return [Symbol, nil] BIG-IP session support; may be useful to avoid concurrency issues in certain circumstances.\n attribute :session\n validates :session, type: Symbol\n\n # @return [:address_class, :certificate, :client_ssl_profile, :device, :device_group, :interface, :key, :node, :pool, :provision, :rule, :self_ip, :software, :system_info, :traffic_group, :trunk, :virtual_address, :virtual_server, :vlan] Fact category or list of categories to collect\n attribute :include\n validates :include, presence: true, expression_inclusion: {:in=>[:address_class, :certificate, :client_ssl_profile, :device, :device_group, :interface, :key, :node, :pool, :provision, :rule, :self_ip, :software, :system_info, :traffic_group, :trunk, :virtual_address, :virtual_server, :vlan], :message=>\"%{value} needs to be :address_class, :certificate, :client_ssl_profile, :device, :device_group, :interface, :key, :node, :pool, :provision, :rule, :self_ip, :software, :system_info, :traffic_group, :trunk, :virtual_address, :virtual_server, :vlan\"}\n\n # @return [Object, nil] Shell-style glob matching string used to filter fact keys. Not applicable for software, provision, and system_info fact categories.\n attribute :filter\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7185401916503906, "alphanum_fraction": 0.7223274111747742, "avg_line_length": 92.69355010986328, "blob_id": "40f899d664849b33642768a6d638e7e3e71a5082", "content_id": "ab22af7d8436571dc3d9f68c5b8157ac63992bf8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 11618, "license_type": "permissive", "max_line_length": 763, "num_lines": 124, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/cloudfront_distribution.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows for easy creation, updating and deletion of CloudFront distributions.\n class Cloudfront_distribution < Base\n # @return [:present, :absent, nil] The desired state of the distribution present - creates a new distribution or updates an existing distribution. absent - deletes an existing distribution.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] The id of the cloudfront distribution. This parameter can be exchanged with I(alias) or I(caller_reference) and is used in conjunction with I(e_tag).\n attribute :distribution_id\n validates :distribution_id, type: String\n\n # @return [Object, nil] A unique identifier of a modified or existing distribution. Used in conjunction with I(distribution_id). Is determined automatically if not specified.\n attribute :e_tag\n\n # @return [String, nil] A unique identifier for creating and updating cloudfront distributions. Each caller reference must be unique across all distributions. e.g. a caller reference used in a web distribution cannot be reused in a streaming distribution. This parameter can be used instead of I(distribution_id) to reference an existing distribution. If not specified, this defaults to a datetime stamp of the format 'YYYY-MM-DDTHH:MM:SS.ffffff'.\n attribute :caller_reference\n validates :caller_reference, type: String\n\n # @return [Hash, nil] Should be input as a dict() of key-value pairs. Note that numeric keys or values must be wrapped in quotes. e.g. \"Priority:\" '1'\n attribute :tags\n validates :tags, type: Hash\n\n # @return [:yes, :no, nil] Specifies whether existing tags will be removed before adding new tags. When I(purge_tags=yes), existing tags are removed and I(tags) are added, if specified. If no tags are specified, it removes all existing tags for the distribution. When I(purge_tags=no), existing tags are kept and I(tags) are added, if specified.\n attribute :purge_tags\n validates :purge_tags, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] The name of an alias (CNAME) that is used in a distribution. This is used to effectively reference a distribution by its alias as an alias can only be used by one distribution per AWS account. This variable avoids having to provide the I(distribution_id) as well as the I(e_tag), or I(caller_reference) of an existing distribution.\n attribute :alias\n\n # @return [Array<String>, String, nil] A I(list[]) of domain name aliases (CNAMEs) as strings to be used for the distribution. Each alias must be unique across all distribution for the AWS account.\n attribute :aliases\n validates :aliases, type: TypeGeneric.new(String)\n\n # @return [:yes, :no, nil] Specifies whether existing aliases will be removed before adding new aliases. When I(purge_aliases=yes), existing aliases are removed and I(aliases) are added.\n attribute :purge_aliases\n validates :purge_aliases, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] A config element that specifies the path to request when the user requests the origin. e.g. if specified as 'index.html', this maps to www.example.com/index.html when www.example.com is called by the user. This prevents the entire distribution origin from being exposed at the root.\n attribute :default_root_object\n\n # @return [String, nil] The domain name to use for an origin if no I(origins) have been specified. Should only be used on a first run of generating a distribution and not on subsequent runs. Should not be used in conjunction with I(distribution_id), I(caller_reference) or I(alias).\n attribute :default_origin_domain_name\n validates :default_origin_domain_name, type: String\n\n # @return [Object, nil] The default origin path to specify for an origin if no I(origins) have been specified. Defaults to empty if not specified.\n attribute :default_origin_path\n\n # @return [Array<Hash>, Hash, nil] A config element that is a I(list[]) of complex origin objects to be specified for the distribution. Used for creating and updating distributions. Each origin item comprises the attributes I(id) I(domain_name) (defaults to default_origin_domain_name if not specified) I(origin_path) (defaults to default_origin_path if not specified) I(custom_headers[]) I(header_name) I(header_value) I(s3_origin_access_identity_enabled) I(custom_origin_config) I(http_port) I(https_port) I(origin_protocol_policy) I(origin_ssl_protocols[]) I(origin_read_timeout) I(origin_keepalive_timeout)\n attribute :origins\n validates :origins, type: TypeGeneric.new(Hash)\n\n # @return [Boolean, nil] Whether to remove any origins that aren't listed in I(origins)\n attribute :purge_origins\n validates :purge_origins, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Hash, nil] A config element that is a complex object specifying the default cache behavior of the distribution. If not specified, the I(target_origin_id) is defined as the I(target_origin_id) of the first valid I(cache_behavior) in I(cache_behaviors) with defaults. The default cache behavior comprises the attributes I(target_origin_id) I(forwarded_values) I(query_string) I(cookies) I(forward) I(whitelisted_names) I(headers[]) I(query_string_cache_keys[]) I(trusted_signers) I(enabled) I(items[]) I(viewer_protocol_policy) I(min_ttl) I(allowed_methods) I(items[]) I(cached_methods[]) I(smooth_streaming) I(default_ttl) I(max_ttl) I(compress) I(lambda_function_associations[]) I(lambda_function_arn) I(event_type) I(field_level_encryption_id)\n attribute :default_cache_behavior\n validates :default_cache_behavior, type: Hash\n\n # @return [Object, nil] A config element that is a I(list[]) of complex cache behavior objects to be specified for the distribution. The order of the list is preserved across runs unless C(purge_cache_behavior) is enabled. Each cache behavior comprises the attributes I(path_pattern) I(target_origin_id) I(forwarded_values) I(query_string) I(cookies) I(forward) I(whitelisted_names) I(headers[]) I(query_string_cache_keys[]) I(trusted_signers) I(enabled) I(items[]) I(viewer_protocol_policy) I(min_ttl) I(allowed_methods) I(items[]) I(cached_methods[]) I(smooth_streaming) I(default_ttl) I(max_ttl) I(compress) I(lambda_function_associations[]) I(field_level_encryption_id)\n attribute :cache_behaviors\n\n # @return [Boolean, nil] Whether to remove any cache behaviors that aren't listed in I(cache_behaviors). This switch also allows the reordering of cache_behaviors.\n attribute :purge_cache_behaviors\n validates :purge_cache_behaviors, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] A config element that is a I(list[]) of complex custom error responses to be specified for the distribution. This attribute configures custom http error messages returned to the user. Each custom error response object comprises the attributes I(error_code) I(reponse_page_path) I(response_code) I(error_caching_min_ttl)\n attribute :custom_error_responses\n\n # @return [Boolean, nil] Whether to remove any custom error responses that aren't listed in I(custom_error_responses)\n attribute :purge_custom_error_responses\n validates :purge_custom_error_responses, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] A comment that describes the cloudfront distribution. If not specified, it defaults to a generic message that it has been created with Ansible, and a datetime stamp.\n attribute :comment\n validates :comment, type: String\n\n # @return [Hash, nil] A config element that is a complex object that defines logging for the distribution. The logging object comprises the attributes I(enabled) I(include_cookies) I(bucket) I(prefix)\n attribute :logging\n validates :logging, type: Hash\n\n # @return [:PriceClass_100, :PriceClass_200, :PriceClass_All, nil] A string that specifies the pricing class of the distribution. As per U(https://aws.amazon.com/cloudfront/pricing/) I(price_class=PriceClass_100) consists of the areas United States Canada Europe I(price_class=PriceClass_200) consists of the areas United States Canada Europe Hong Kong, Philippines, S. Korea, Singapore & Taiwan Japan India I(price_class=PriceClass_All) consists of the areas United States Canada Europe Hong Kong, Philippines, S. Korea, Singapore & Taiwan Japan India South America Australia\n attribute :price_class\n validates :price_class, expression_inclusion: {:in=>[:PriceClass_100, :PriceClass_200, :PriceClass_All], :message=>\"%{value} needs to be :PriceClass_100, :PriceClass_200, :PriceClass_All\"}, allow_nil: true\n\n # @return [:yes, :no, nil] A boolean value that specifies whether the distribution is enabled or disabled.\n attribute :enabled\n validates :enabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] A config element that is a complex object that specifies the encryption details of the distribution. Comprises the following attributes I(cloudfront_default_certificate) I(iam_certificate_id) I(acm_certificate_arn) I(ssl_support_method) I(minimum_protocol_version) I(certificate) I(certificate_source)\n attribute :viewer_certificate\n\n # @return [Object, nil] A config element that is a complex object that describes how a distribution should restrict it's content. The restriction object comprises the following attributes I(geo_restriction) I(restriction_type) I(items[])\n attribute :restrictions\n\n # @return [Object, nil] The id of a Web Application Firewall (WAF) Access Control List (ACL).\n attribute :web_acl_id\n\n # @return [:\"http1.1\", :http2, nil] The version of the http protocol to use for the distribution.\n attribute :http_version\n validates :http_version, expression_inclusion: {:in=>[:\"http1.1\", :http2], :message=>\"%{value} needs to be :\\\"http1.1\\\", :http2\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Determines whether IPv6 support is enabled or not.\n attribute :ipv6_enabled\n validates :ipv6_enabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Specifies whether the module waits until the distribution has completed processing the creation or update.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Specifies the duration in seconds to wait for a timeout of a cloudfront create or update. Defaults to 1800 seconds (30 minutes).\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7069091200828552, "alphanum_fraction": 0.7069091200828552, "avg_line_length": 54, "blob_id": "7fef6d121677772d2c16d7064f1cd3d5cdd960da", "content_id": "b4a8dddc605f262a5f24e3a0e2bc5b6023d4b5e0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1375, "license_type": "permissive", "max_line_length": 380, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/network/junos/junos_lldp_interface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of LLDP interfaces configuration on Juniper JUNOS network devices.\n class Junos_lldp_interface < Base\n # @return [String, nil] Name of the interface LLDP should be configured on.\n attribute :name\n validates :name, type: String\n\n # @return [:present, :absent, :enabled, :disabled, nil] Value of C(present) ensures given LLDP configured on given I(interfaces) and is enabled, for value of C(absent) LLDP configuration on given I(interfaces) deleted. Value C(enabled) ensures LLDP protocol is enabled on given I(interfaces) and for value of C(disabled) it ensures LLDP is disabled on given I(interfaces).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :enabled, :disabled], :message=>\"%{value} needs to be :present, :absent, :enabled, :disabled\"}, allow_nil: true\n\n # @return [Boolean, nil] Specifies whether or not the configuration is active or deactivated\n attribute :active\n validates :active, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7274168133735657, "alphanum_fraction": 0.7321711778640747, "avg_line_length": 59.095237731933594, "blob_id": "708e753c4e1b2905660b36d318f021b082e27221", "content_id": "2d80e9f24af8b33fb2956c173ed6331579f05afd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1262, "license_type": "permissive", "max_line_length": 291, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/utilities/logic/include.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Includes a file with a list of plays or tasks to be executed in the current playbook.\n # Files with a list of plays can only be included at the top level. Lists of tasks can only be included where tasks normally run (in play).\n # Before Ansible version 2.0, all includes were 'static' and were executed when the play was compiled.\n # Static includes are not subject to most directives. For example, loops or conditionals are applied instead to each inherited task.\n # Since Ansible 2.0, task includes are dynamic and behave more like real tasks. This means they can be looped, skipped and use variables from any source. Ansible tries to auto detect this, but you can use the `static` directive (which was added in Ansible 2.1) to bypass autodetection.\n # This module is also supported for Windows targets.\n class Include < Base\n # @return [Object, nil] This module allows you to specify the name of the file directly without any other options.\n attribute :free_form, original_name: 'free-form'\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.694432258605957, "alphanum_fraction": 0.694432258605957, "avg_line_length": 48.58695602416992, "blob_id": "ac469d191d5a71302937cf3596f1e8d2c5133ac3", "content_id": "0c2956276fd7c057cb1826b6a573000e2f75636a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2281, "license_type": "permissive", "max_line_length": 296, "num_lines": 46, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gce_mig.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, Update or Destroy a Managed Instance Group (MIG). See U(https://cloud.google.com/compute/docs/instance-groups) for an overview. Full install/configuration instructions for the gce* modules can be found in the comments of ansible/test/gce_tests.py.\n class Gce_mig < Base\n # @return [String] Name of the Managed Instance Group.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Instance Template to be used in creating the VMs. See U(https://cloud.google.com/compute/docs/instance-templates) to learn more about Instance Templates. Required for creating MIGs.\n attribute :template\n\n # @return [Object, nil] Size of Managed Instance Group. If MIG already exists, it will be resized to the number provided here. Required for creating MIGs.\n attribute :size\n\n # @return [Object, nil] service account email\n attribute :service_account_email\n\n # @return [Object, nil] Path to the JSON file associated with the service account email\n attribute :credentials_file\n\n # @return [Object, nil] GCE project ID\n attribute :project_id\n\n # @return [:absent, :present, nil] desired state of the resource\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [Object] The GCE zone to use for this Managed Instance Group.\n attribute :zone\n validates :zone, presence: true\n\n # @return [Object, nil] A dictionary of configuration for the autoscaler. 'enabled (bool)', 'name (str)' and policy.max_instances (int) are required fields if autoscaling is used. See U(https://cloud.google.com/compute/docs/reference/beta/autoscalers) for more information on Autoscaling.\n attribute :autoscaling\n\n # @return [Object, nil] Define named ports that backend services can forward data to. Format is a a list of name:port dictionaries.\n attribute :named_ports\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6771611571311951, "alphanum_fraction": 0.6776947975158691, "avg_line_length": 43.619049072265625, "blob_id": "4d4f753a0d754b9afb56376d6a3a54b3853d28f8", "content_id": "df4e2ccda9802cf301bb4057d0581ac6060ad401", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1874, "license_type": "permissive", "max_line_length": 257, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gce_tag.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can add or remove tags U(https://cloud.google.com/compute/docs/label-or-tag-resources#tags) to/from GCE instances. Use 'instance_pattern' to update multiple instances in a specify zone.\n class Gce_tag < Base\n # @return [String, nil] The name of the GCE instance to add/remove tags.,Required if C(instance_pattern) is not specified.\n attribute :instance_name\n validates :instance_name, type: String\n\n # @return [String, nil] The pattern of GCE instance names to match for adding/removing tags. Full-Python regex is supported. See U(https://docs.python.org/2/library/re.html) for details.,If C(instance_name) is not specified, this field is required.\n attribute :instance_pattern\n validates :instance_pattern, type: String\n\n # @return [Array<String>, String] Comma-separated list of tags to add or remove.\n attribute :tags\n validates :tags, presence: true, type: TypeGeneric.new(String)\n\n # @return [:absent, :present, nil] Desired state of the tags.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] The zone of the disk specified by source.\n attribute :zone\n validates :zone, type: String\n\n # @return [Object, nil] Service account email.\n attribute :service_account_email\n\n # @return [Object, nil] Path to the PEM file associated with the service account email.\n attribute :pem_file\n\n # @return [Object, nil] Your GCE project ID.\n attribute :project_id\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6557830572128296, "alphanum_fraction": 0.6557830572128296, "avg_line_length": 35.8775520324707, "blob_id": "86a07b159d24ec36324b57395b9afd5dc3871a91", "content_id": "044a397274944ad94d61f32e8ce02756b23db72a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1807, "license_type": "permissive", "max_line_length": 161, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/packaging/language/npm.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage node.js packages with Node Package Manager (npm)\n class Npm < Base\n # @return [String, nil] The name of a node.js library to install\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] The base path where to install the node.js libraries\n attribute :path\n validates :path, type: String\n\n # @return [String, nil] The version to be installed\n attribute :version\n validates :version, type: String\n\n # @return [Symbol, nil] Install the node.js library globally\n attribute :global\n validates :global, type: Symbol\n\n # @return [String, nil] The executable location for npm.,This is useful if you are using a version manager, such as nvm\n attribute :executable\n validates :executable, type: String\n\n # @return [Symbol, nil] Use the C(--ignore-scripts) flag when installing.\n attribute :ignore_scripts\n validates :ignore_scripts, type: Symbol\n\n # @return [Symbol, nil] Install dependencies in production mode, excluding devDependencies\n attribute :production\n validates :production, type: Symbol\n\n # @return [String, nil] The registry to install modules from.\n attribute :registry\n validates :registry, type: String\n\n # @return [:present, :absent, :latest, nil] The state of the node.js library\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :latest], :message=>\"%{value} needs to be :present, :absent, :latest\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6508991122245789, "alphanum_fraction": 0.6508991122245789, "avg_line_length": 40.934425354003906, "blob_id": "9e4ba89fb76afca793b78b1090d6b85bb12fd8da", "content_id": "ad61ed04603dd44182c4eea2c838188e4eba7134", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2558, "license_type": "permissive", "max_line_length": 143, "num_lines": 61, "path": "/lib/ansible/ruby/modules/generated/cloud/misc/proxmox_template.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # allows you to upload/delete templates in Proxmox VE cluster\n class Proxmox_template < Base\n # @return [String] the host of the Proxmox VE cluster\n attribute :api_host\n validates :api_host, presence: true, type: String\n\n # @return [String] the user to authenticate with\n attribute :api_user\n validates :api_user, presence: true, type: String\n\n # @return [String, nil] the password to authenticate with,you can use PROXMOX_PASSWORD environment variable\n attribute :api_password\n validates :api_password, type: String\n\n # @return [:yes, :no, nil] enable / disable https certificate verification\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String] Proxmox VE node, when you will operate with template\n attribute :node\n validates :node, presence: true, type: String\n\n # @return [String, nil] path to uploaded file,required only for C(state=present)\n attribute :src\n validates :src, type: String\n\n # @return [String, nil] the template name,required only for states C(absent), C(info)\n attribute :template\n validates :template, type: String\n\n # @return [:vztmpl, :iso, nil] content type,required only for C(state=present)\n attribute :content_type\n validates :content_type, expression_inclusion: {:in=>[:vztmpl, :iso], :message=>\"%{value} needs to be :vztmpl, :iso\"}, allow_nil: true\n\n # @return [String, nil] target storage\n attribute :storage\n validates :storage, type: String\n\n # @return [Integer, nil] timeout for operations\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [:yes, :no, nil] can be used only with C(state=present), exists template will be overwritten\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Indicate desired state of the template\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6606354713439941, "alphanum_fraction": 0.6606354713439941, "avg_line_length": 47.212764739990234, "blob_id": "6757402fe5718b075011c0bbfbdde52d25dba0ec", "content_id": "36aecc956e7b37437d4c1069065c5aabfffe81d3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2266, "license_type": "permissive", "max_line_length": 173, "num_lines": 47, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_encap_pool_range.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage vlan, vxlan, and vsan ranges that are assigned to pools on Cisco ACI fabrics.\n class Aci_encap_pool_range < Base\n # @return [:dynamic, :inherit, :static, nil] The method used for allocating encaps to resources.,Only vlan and vsan support allocation modes.\n attribute :allocation_mode\n validates :allocation_mode, expression_inclusion: {:in=>[:dynamic, :inherit, :static], :message=>\"%{value} needs to be :dynamic, :inherit, :static\"}, allow_nil: true\n\n # @return [Object, nil] Description for the pool range.\n attribute :description\n\n # @return [String, nil] The name of the pool that the range should be assigned to.\n attribute :pool\n validates :pool, type: String\n\n # @return [:dynamic, :static, nil] The method used for allocating encaps to resources.,Only vlan and vsan support allocation modes.\n attribute :pool_allocation_mode\n validates :pool_allocation_mode, expression_inclusion: {:in=>[:dynamic, :static], :message=>\"%{value} needs to be :dynamic, :static\"}, allow_nil: true\n\n # @return [:vlan, :vxlan, :vsan] The encap type of C(pool).\n attribute :pool_type\n validates :pool_type, presence: true, expression_inclusion: {:in=>[:vlan, :vxlan, :vsan], :message=>\"%{value} needs to be :vlan, :vxlan, :vsan\"}\n\n # @return [Integer, nil] The end of encap range.\n attribute :range_end\n validates :range_end, type: Integer\n\n # @return [Object, nil] The name to give to the encap range.\n attribute :range_name\n\n # @return [Integer, nil] The start of the encap range.\n attribute :range_start\n validates :range_start, type: Integer\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6616862416267395, "alphanum_fraction": 0.6645321846008301, "avg_line_length": 42.921875, "blob_id": "37ea5e99c61844016875babbd1b541a869c7cce0", "content_id": "b185388c6c07c8d501a62d599fda9d4d58e4f256", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2811, "license_type": "permissive", "max_line_length": 166, "num_lines": 64, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_vrfcontext.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure VrfContext object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_vrfcontext < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Object, nil] Bgp local and peer info.\n attribute :bgp_profile\n\n # @return [Object, nil] It is a reference to an object of type cloud.\n attribute :cloud_ref\n\n # @return [Object, nil] Configure debug flags for vrf.,Field introduced in 17.1.1.\n attribute :debugvrfcontext\n\n # @return [Object, nil] User defined description for the object.\n attribute :description\n\n # @return [Object, nil] Configure ping based heartbeat check for gateway in service engines of vrf.\n attribute :gateway_mon\n\n # @return [Object, nil] Configure ping based heartbeat check for all default gateways in service engines of vrf.,Field introduced in 17.1.1.\n attribute :internal_gateway_monitor\n\n # @return [String] Name of the object.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] List of staticroute.\n attribute :static_routes\n\n # @return [Symbol, nil] Boolean flag to set system_default.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :system_default\n validates :system_default, type: Symbol\n\n # @return [Object, nil] It is a reference to an object of type tenant.\n attribute :tenant_ref\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Unique object identifier of the object.\n attribute :uuid\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7359516620635986, "alphanum_fraction": 0.7363544702529907, "avg_line_length": 96.35294342041016, "blob_id": "8176f77a9f1564dec432d06ba61efc8e06fdaf3f", "content_id": "11d05da6d0e74499744e4fda6b431ade4818ab43", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4965, "license_type": "permissive", "max_line_length": 647, "num_lines": 51, "path": "/lib/ansible/ruby/modules/generated/network/cli/cli_config.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides platform agnostic way of pushing text based configuration to network devices over network_cli connection plugin.\n class Cli_config < Base\n # @return [String, nil] The config to be pushed to the network device. This argument is mutually exclusive with C(rollback) and either one of the option should be given as input. The config should have indentation that the device uses.\n attribute :config\n validates :config, type: String\n\n # @return [Symbol, nil] The C(commit) argument instructs the module to push the configuration to the device. This is mapped to module check mode.\n attribute :commit\n validates :commit, type: Symbol\n\n # @return [String, nil] If the C(replace) argument is set to C(yes), it will replace the entire running-config of the device with the C(config) argument value. For NXOS devices, C(replace) argument takes path to the file on the device that will be used for replacing the entire running-config. Nexus 9K devices only support replace. Use I(net_put) or I(nxos_file_copy) module to copy the flat file to remote device and then use set the fullpath to this argument.\n attribute :replace\n validates :replace, type: String\n\n # @return [Object, nil] The C(rollback) argument instructs the module to rollback the current configuration to the identifier specified in the argument. If the specified rollback identifier does not exist on the remote device, the module will fail. To rollback to the most recent commit, set the C(rollback) argument to 0. This option is mutually exclusive with C(config).\n attribute :rollback\n\n # @return [String, nil] The C(commit_comment) argument specifies a text string to be used when committing the configuration. If the C(commit) argument is set to False, this argument is silently ignored. This argument is only valid for the platforms that support commit operation with comment.\n attribute :commit_comment\n validates :commit_comment, type: String\n\n # @return [:yes, :no, nil] The I(defaults) argument will influence how the running-config is collected from the device. When the value is set to true, the command used to collect the running-config is append with the all keyword. When the value is set to false, the command is issued without the all keyword.\n attribute :defaults\n validates :defaults, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] This argument is used when pushing a multiline configuration element to the device. It specifies the character to use as the delimiting character. This only applies to the configuration action.\n attribute :multiline_delimiter\n validates :multiline_delimiter, type: String\n\n # @return [:line, :block, :config, nil] Instructs the module on the way to perform the configuration on the device. If the C(diff_replace) argument is set to I(line) then the modified lines are pushed to the device in configuration mode. If the argument is set to I(block) then the entire command block is pushed to the device in configuration mode if any line is not correct. Note that this parameter will be ignored if the platform has onbox diff support.\n attribute :diff_replace\n validates :diff_replace, expression_inclusion: {:in=>[:line, :block, :config], :message=>\"%{value} needs to be :line, :block, :config\"}, allow_nil: true\n\n # @return [:line, :strict, :exact, :none, nil] Instructs the module on the way to perform the matching of the set of commands against the current device config. If C(diff_match) is set to I(line), commands are matched line by line. If C(diff_match) is set to I(strict), command lines are matched with respect to position. If C(diff_match) is set to I(exact), command lines must be an equal match. Finally, if C(diff_match) is set to I(none), the module will not attempt to compare the source configuration with the running configuration on the remote device. Note that this parameter will be ignored if the platform has onbox diff support.\n attribute :diff_match\n validates :diff_match, expression_inclusion: {:in=>[:line, :strict, :exact, :none], :message=>\"%{value} needs to be :line, :strict, :exact, :none\"}, allow_nil: true\n\n # @return [Object, nil] Use this argument to specify one or more lines that should be ignored during the diff. This is used for lines in the configuration that are automatically updated by the system. This argument takes a list of regular expressions or exact line matches. Note that this parameter will be ignored if the platform has onbox diff support.\n attribute :diff_ignore_lines\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.70100337266922, "alphanum_fraction": 0.7096989750862122, "avg_line_length": 54.37036895751953, "blob_id": "1b49dbc40d401571cacda9e6c68003e23629e056", "content_id": "1bc2820677a0cc925dbe840a37f1350a576671f6", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1495, "license_type": "permissive", "max_line_length": 576, "num_lines": 27, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_guest_snapshot_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to gather facts about virtual machine's snapshots.\n class Vmware_guest_snapshot_facts < Base\n # @return [String, nil] Name of the VM to work with.,This is required if C(uuid) is not supplied.\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] UUID of the instance to manage if known, this value is VMware's unique identifier.,This is required if C(name) is not supplied.,The C(folder) is ignored, if C(uuid) is provided.\n attribute :uuid\n\n # @return [Object, nil] Destination folder, absolute or relative path to find an existing guest.,This is required only, if multiple virtual machines with same name are found on given vCenter.,The folder should include the datacenter. ESX's datacenter is ha-datacenter,Examples:, folder: /ha-datacenter/vm, folder: ha-datacenter/vm, folder: /datacenter1/vm, folder: datacenter1/vm, folder: /datacenter1/vm/folder1, folder: datacenter1/vm/folder1, folder: /folder1/datacenter1/vm, folder: folder1/datacenter1/vm, folder: /folder1/datacenter1/vm/folder2\n attribute :folder\n\n # @return [String] Name of the datacenter.\n attribute :datacenter\n validates :datacenter, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6999749541282654, "alphanum_fraction": 0.7017917633056641, "avg_line_length": 73.93896484375, "blob_id": "1e01f423d72964a627707b5d3ca7cef0d2564ec1", "content_id": "a17c2f184f4c0354b608028d56564ac3579f078a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 15962, "license_type": "permissive", "max_line_length": 716, "num_lines": 213, "path": "/lib/ansible/ruby/modules/generated/cloud/spotinst/spotinst_aws_elastigroup.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Can create, update, or delete Spotinst AWS Elastigroups Launch configuration is part of the elastigroup configuration, so no additional modules are necessary for handling the launch configuration. You will have to have a credentials file in this location - <home>/.spotinst/credentials The credentials file must contain a row that looks like this token = <YOUR TOKEN> Full documentation available at https://help.spotinst.com/hc/en-us/articles/115003530285-Ansible-\n class Spotinst_aws_elastigroup < Base\n # @return [Object, nil] (String) Optional parameter that allows to set a non-default credentials path. Default is ~/.spotinst/credentials\n attribute :credentials_path\n\n # @return [Object, nil] (String) Optional parameter that allows to set an account-id inside the module configuration By default this is retrieved from the credentials path\n attribute :account_id\n\n # @return [:availabilityOriented, :costOriented, :balanced] (String) The strategy orientation.\n attribute :availability_vs_cost\n validates :availability_vs_cost, presence: true, expression_inclusion: {:in=>[:availabilityOriented, :costOriented, :balanced], :message=>\"%{value} needs to be :availabilityOriented, :costOriented, :balanced\"}\n\n # @return [Object] (List of Objects) a list of hash/dictionaries of Availability Zones that are configured in the elastigroup; '[{\"key\":\"value\", \"key\":\"value\"}]'; keys allowed are name (String), subnet_id (String), placement_group_name (String),\n attribute :availability_zones\n validates :availability_zones, presence: true\n\n # @return [Object, nil] (List of Objects) a list of hash/dictionaries of Block Device Mappings for elastigroup instances; You can specify virtual devices and EBS volumes.; '[{\"key\":\"value\", \"key\":\"value\"}]'; keys allowed are device_name (List of Strings), virtual_name (String), no_device (String), ebs (Object, expects the following keys- delete_on_termination(Boolean), encrypted(Boolean), iops (Integer), snapshot_id(Integer), volume_type(String), volume_size(Integer))\n attribute :block_device_mappings\n\n # @return [Object, nil] (Object) The Chef integration configuration.; Expects the following keys - chef_server (String), organization (String), user (String), pem_key (String), chef_version (String)\n attribute :chef\n\n # @return [Object, nil] (Integer) Time for instance to be drained from incoming requests and deregistered from ELB before termination.\n attribute :draining_timeout\n\n # @return [Object, nil] (Boolean) Enable EBS optimization for supported instances which are not enabled by default.; Note - additional charges will be applied.\n attribute :ebs_optimized\n\n # @return [Object, nil] (List of Objects) a list of hash/dictionaries of EBS devices to reattach to the elastigroup when available; '[{\"key\":\"value\", \"key\":\"value\"}]'; keys allowed are - volume_ids (List of Strings), device_name (String)\n attribute :ebs_volume_pool\n\n # @return [Object, nil] (Object) The ECS integration configuration.; Expects the following key - cluster_name (String)\n attribute :ecs\n\n # @return [Object, nil] (List of Strings) List of ElasticIps Allocation Ids (Example C(eipalloc-9d4e16f8)) to associate to the group instances\n attribute :elastic_ips\n\n # @return [Object, nil] (Boolean) In case of no spots available, Elastigroup will launch an On-demand instance instead\n attribute :fallback_to_od\n\n # @return [Integer, nil] (Integer) The amount of time, in seconds, after the instance has launched to start and check its health.\n attribute :health_check_grace_period\n validates :health_check_grace_period, type: Integer\n\n # @return [Object, nil] (Integer) Minimal mount of time instance should be unhealthy for us to consider it unhealthy.\n attribute :health_check_unhealthy_duration_before_replacement\n\n # @return [:ELB, :HCS, :TARGET_GROUP, :MLB, :EC2, nil] (String) The service to use for the health check.\n attribute :health_check_type\n validates :health_check_type, expression_inclusion: {:in=>[:ELB, :HCS, :TARGET_GROUP, :MLB, :EC2], :message=>\"%{value} needs to be :ELB, :HCS, :TARGET_GROUP, :MLB, :EC2\"}, allow_nil: true\n\n # @return [Object, nil] (String) The instance profile iamRole name,Only use iam_role_arn, or iam_role_name\n attribute :iam_role_name\n\n # @return [Object, nil] (String) The instance profile iamRole arn,Only use iam_role_arn, or iam_role_name\n attribute :iam_role_arn\n\n # @return [Object, nil] (String) The group id if it already exists and you want to update, or delete it. This will not work unless the uniqueness_by field is set to id. When this is set, and the uniqueness_by field is set, the group will either be updated or deleted, but not created.\n attribute :id\n\n # @return [:image_id, :target, nil] (List of Strings) list of fields on which changes should be ignored when updating\n attribute :ignore_changes\n validates :ignore_changes, expression_inclusion: {:in=>[:image_id, :target], :message=>\"%{value} needs to be :image_id, :target\"}, allow_nil: true\n\n # @return [Object] (String) The image Id used to launch the instance.; In case of conflict between Instance type and image type, an error will be returned\n attribute :image_id\n validates :image_id, presence: true\n\n # @return [Object] (String) Specify a Key Pair to attach to the instances\n attribute :key_pair\n validates :key_pair, presence: true\n\n # @return [Object, nil] (Object) The Kubernetes integration configuration. Expects the following keys - api_server (String), token (String)\n attribute :kubernetes\n\n # @return [Object, nil] (String) lifetime period\n attribute :lifetime_period\n\n # @return [Object, nil] (List of Strings) List of classic ELB names\n attribute :load_balancers\n\n # @return [Object] (Integer) The upper limit number of instances that you can scale up to\n attribute :max_size\n validates :max_size, presence: true\n\n # @return [Object, nil] (Object) The Mesosphere integration configuration. Expects the following key - api_server (String)\n attribute :mesosphere\n\n # @return [Object] (Integer) The lower limit number of instances that you can scale down to\n attribute :min_size\n validates :min_size, presence: true\n\n # @return [Object] (Boolean) Describes whether instance Enhanced Monitoring is enabled\n attribute :monitoring\n validates :monitoring, presence: true\n\n # @return [String] (String) Unique name for elastigroup to be created, updated or deleted\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] (List of Objects) a list of hash/dictionaries of network interfaces to add to the elastigroup; '[{\"key\":\"value\", \"key\":\"value\"}]'; keys allowed are - description (String), device_index (Integer), secondary_private_ip_address_count (Integer), associate_public_ip_address (Boolean), delete_on_termination (Boolean), groups (List of Strings), network_interface_id (String), private_ip_address (String), subnet_id (String), associate_ipv6_address (Boolean), private_ip_addresses (List of Objects, Keys are privateIpAddress (String, required) and primary (Boolean))\n attribute :network_interfaces\n\n # @return [Object, nil] (Integer) Required if risk is not set,Number of on demand instances to launch. All other instances will be spot instances.; Either set this parameter or the risk parameter\n attribute :on_demand_count\n\n # @return [Object] (String) On-demand instance type that will be provisioned\n attribute :on_demand_instance_type\n validates :on_demand_instance_type, presence: true\n\n # @return [Object, nil] (Object) The elastigroup OpsWorks integration configration.; Expects the following key - layer_id (String)\n attribute :opsworks\n\n # @return [Object, nil] (Object) The Stateful elastigroup configration.; Accepts the following keys - should_persist_root_device (Boolean), should_persist_block_devices (Boolean), should_persist_private_ip (Boolean)\n attribute :persistence\n\n # @return [:\"Linux/UNIX\", :\"SUSE Linux\", :Windows, :\"Linux/UNIX (Amazon VPC)\", :\"SUSE Linux (Amazon VPC)\", :Windows] (String) Operation system type._\n attribute :product\n validates :product, presence: true, expression_inclusion: {:in=>[:\"Linux/UNIX\", :\"SUSE Linux\", :Windows, :\"Linux/UNIX (Amazon VPC)\", :\"SUSE Linux (Amazon VPC)\", :Windows], :message=>\"%{value} needs to be :\\\"Linux/UNIX\\\", :\\\"SUSE Linux\\\", :Windows, :\\\"Linux/UNIX (Amazon VPC)\\\", :\\\"SUSE Linux (Amazon VPC)\\\", :Windows\"}\n\n # @return [Object, nil] (Object) The Rancher integration configuration.; Expects the following keys - access_key (String), secret_key (String), master_host (String)\n attribute :rancher\n\n # @return [Object, nil] (Object) The Rightscale integration configuration.; Expects the following keys - account_id (String), refresh_token (String)\n attribute :right_scale\n\n # @return [Object, nil] (Integer) required if on demand is not set. The percentage of Spot instances to launch (0 - 100).\n attribute :risk\n\n # @return [Object, nil] (Object) Roll configuration.; If you would like the group to roll after updating, please use this feature. Accepts the following keys - batch_size_percentage(Integer, Required), grace_period - (Integer, Required), health_check_type(String, Optional)\n attribute :roll_config\n\n # @return [Object, nil] (List of Objects) a list of hash/dictionaries of scheduled tasks to configure in the elastigroup; '[{\"key\":\"value\", \"key\":\"value\"}]'; keys allowed are - adjustment (Integer), scale_target_capacity (Integer), scale_min_capacity (Integer), scale_max_capacity (Integer), adjustment_percentage (Integer), batch_size_percentage (Integer), cron_expression (String), frequency (String), grace_period (Integer), task_type (String, required), is_enabled (Boolean)\n attribute :scheduled_tasks\n\n # @return [Object] (List of Strings) One or more security group IDs. ; In case of update it will override the existing Security Group with the new given array\n attribute :security_group_ids\n validates :security_group_ids, presence: true\n\n # @return [Object, nil] (String) The Base64-encoded shutdown script that executes prior to instance termination. Encode before setting.\n attribute :shutdown_script\n\n # @return [Object, nil] (List of Objects) a list of hash/dictionaries of signals to configure in the elastigroup; keys allowed are - name (String, required), timeout (Integer)\n attribute :signals\n\n # @return [Object, nil] (Integer) spin up time, in seconds, for the instance\n attribute :spin_up_time\n\n # @return [Object] (List of Strings) Spot instance type that will be provisioned.\n attribute :spot_instance_types\n validates :spot_instance_types, presence: true\n\n # @return [:present, :absent, nil] (String) create or delete the elastigroup\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] (List of tagKey:tagValue paris) a list of tags to configure in the elastigroup. Please specify list of keys and values (key colon value);\n attribute :tags\n\n # @return [Object] (Integer) The number of instances to launch\n attribute :target\n validates :target, presence: true\n\n # @return [Object, nil] (List of Strings) List of target group arns instances should be registered to\n attribute :target_group_arns\n\n # @return [:default, :dedicated, nil] (String) dedicated vs shared tenancy\n attribute :tenancy\n validates :tenancy, expression_inclusion: {:in=>[:default, :dedicated], :message=>\"%{value} needs to be :default, :dedicated\"}, allow_nil: true\n\n # @return [Object, nil] (Boolean) terminate at the end of billing hour\n attribute :terminate_at_end_of_billing_hour\n\n # @return [:instance, :weight] (String) The capacity unit to launch instances by.\n attribute :unit\n validates :unit, presence: true, expression_inclusion: {:in=>[:instance, :weight], :message=>\"%{value} needs to be :instance, :weight\"}\n\n # @return [Object, nil] (List of Objects) a list of hash/dictionaries of scaling policies to configure in the elastigroup; '[{\"key\":\"value\", \"key\":\"value\"}]'; keys allowed are - policy_name (String, required), namespace (String, required), metric_name (String, required), dimensions (List of Objects, Keys allowed are name (String, required) and value (String)), statistic (String, required) evaluation_periods (String, required), period (String, required), threshold (String, required), cooldown (String, required), unit (String, required), operator (String, required), action_type (String, required), adjustment (String), min_target_capacity (String), target (String), maximum (String), minimum (String)\n attribute :up_scaling_policies\n\n # @return [Object, nil] (List of Objects) a list of hash/dictionaries of scaling policies to configure in the elastigroup; '[{\"key\":\"value\", \"key\":\"value\"}]'; keys allowed are - policy_name (String, required), namespace (String, required), metric_name (String, required), dimensions ((List of Objects), Keys allowed are name (String, required) and value (String)), statistic (String, required), evaluation_periods (String, required), period (String, required), threshold (String, required), cooldown (String, required), unit (String, required), operator (String, required), action_type (String, required), adjustment (String), max_target_capacity (String), target (String), maximum (String), minimum (String)\n attribute :down_scaling_policies\n\n # @return [Object, nil] (List of Objects) a list of hash/dictionaries of target tracking policies to configure in the elastigroup; '[{\"key\":\"value\", \"key\":\"value\"}]'; keys allowed are - policy_name (String, required), namespace (String, required), source (String, required), metric_name (String, required), statistic (String, required), unit (String, required), cooldown (String, required), target (String, required)\n attribute :target_tracking_policies\n\n # @return [:id, :name, nil] (String) If your group names are not unique, you may use this feature to update or delete a specific group. Whenever this property is set, you must set a group_id in order to update or delete a group, otherwise a group will be created.\n attribute :uniqueness_by\n validates :uniqueness_by, expression_inclusion: {:in=>[:id, :name], :message=>\"%{value} needs to be :id, :name\"}, allow_nil: true\n\n # @return [Object, nil] (String) Base64-encoded MIME user data. Encode before setting the value.\n attribute :user_data\n\n # @return [Object, nil] (Boolean) In case of any available Reserved Instances, Elastigroup will utilize your reservations before purchasing Spot instances.\n attribute :utilize_reserved_instances\n\n # @return [Object, nil] (Boolean) Whether or not the elastigroup creation / update actions should wait for the instances to spin\n attribute :wait_for_instances\n\n # @return [Object, nil] (Integer) How long the module should wait for instances before failing the action.; Only works if wait_for_instances is True.\n attribute :wait_timeout\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6843838095664978, "alphanum_fraction": 0.6900282502174377, "avg_line_length": 50.85365676879883, "blob_id": "0e055776b259e88536014df338e00a61a37a4ee6", "content_id": "b9651a70e0488afdc99c47856c3ae4b08bdde6c2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2126, "license_type": "permissive", "max_line_length": 311, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/iam_policy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows uploading or removing IAM policies for IAM users, groups or roles.\n class Iam_policy < Base\n # @return [:user, :group, :role] Type of IAM resource\n attribute :iam_type\n validates :iam_type, presence: true, expression_inclusion: {:in=>[:user, :group, :role], :message=>\"%{value} needs to be :user, :group, :role\"}\n\n # @return [String] Name of IAM resource you wish to target for policy actions. In other words, the user name, group name or role name.\n attribute :iam_name\n validates :iam_name, presence: true, type: String\n\n # @return [String] The name label for the policy to create or remove.\n attribute :policy_name\n validates :policy_name, presence: true, type: String\n\n # @return [String, nil] The path to the properly json formatted policy file (mutually exclusive with C(policy_json))\n attribute :policy_document\n validates :policy_document, type: String\n\n # @return [String, nil] A properly json formatted policy as string (mutually exclusive with C(policy_document), see https://github.com/ansible/ansible/issues/7005#issuecomment-42894813 on how to use it properly)\n attribute :policy_json\n validates :policy_json, type: String\n\n # @return [:present, :absent] Whether to create or delete the IAM policy.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String, nil] By default the module looks for any policies that match the document you pass in, if there is a match it will not make a new policy object with the same rules. You can override this by specifying false which would allow for two policy objects with different names but same rules.\n attribute :skip_duplicates\n validates :skip_duplicates, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6853932738304138, "alphanum_fraction": 0.6853932738304138, "avg_line_length": 25.176469802856445, "blob_id": "53429271621a817e1f3cc57785c93e1b55ffd53a", "content_id": "dbdf054944300dcf85ec1e616b7abcb1147a5c27", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 445, "license_type": "permissive", "max_line_length": 64, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/cloud/scaleway/scaleway_organization_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gather facts about the Scaleway organizations available.\n class Scaleway_organization_facts < Base\n # @return [String, nil] Scaleway API URL\n attribute :api_url\n validates :api_url, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7324113249778748, "alphanum_fraction": 0.7324113249778748, "avg_line_length": 74.59091186523438, "blob_id": "92dc3db3a7214785dda9f7749eba41dc1c5b62b4", "content_id": "0bc86229132b217e3bae09341d15803c10d479d3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3326, "license_type": "permissive", "max_line_length": 337, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/network/vyos/vyos_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of the local usernames configured on network devices. It allows playbooks to manage either individual usernames or the collection of usernames in the current running config. It also supports purging usernames from the configuration that are not explicitly defined.\n class Vyos_user < Base\n # @return [Array<Hash>, Hash, nil] The set of username objects to be configured on the remote VyOS device. The list entries can either be the username or a hash of username and properties. This argument is mutually exclusive with the C(name) argument.\n attribute :aggregate\n validates :aggregate, type: TypeGeneric.new(Hash)\n\n # @return [String, nil] The username to be configured on the VyOS device. This argument accepts a string value and is mutually exclusive with the C(aggregate) argument. Please note that this option is not same as C(provider username).\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] The C(full_name) argument provides the full name of the user account to be created on the remote device. This argument accepts any text string value.\n attribute :full_name\n\n # @return [String, nil] The password to be configured on the VyOS device. The password needs to be provided in clear and it will be encrypted on the device. Please note that this option is not same as C(provider password).\n attribute :configured_password\n validates :configured_password, type: String\n\n # @return [:on_create, :always, nil] Since passwords are encrypted in the device running config, this argument will instruct the module when to change the password. When set to C(always), the password will always be updated in the device and when set to C(on_create) the password will be updated only if the username is created.\n attribute :update_password\n validates :update_password, expression_inclusion: {:in=>[:on_create, :always], :message=>\"%{value} needs to be :on_create, :always\"}, allow_nil: true\n\n # @return [String, nil] The C(level) argument configures the level of the user when logged into the system. This argument accepts string values admin or operator.\n attribute :level\n validates :level, type: String\n\n # @return [Symbol, nil] Instructs the module to consider the resource definition absolute. It will remove any previously configured usernames on the device with the exception of the `admin` user (the current defined set of users).\n attribute :purge\n validates :purge, type: Symbol\n\n # @return [:present, :absent, nil] Configures the state of the username definition as it relates to the device operational configuration. When set to I(present), the username(s) should be configured in the device active configuration and when set to I(absent) the username(s) should not be in the device active configuration\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7057960629463196, "alphanum_fraction": 0.7057960629463196, "avg_line_length": 57, "blob_id": "b62d553a09cb323dbdaa9100256e86403c065510", "content_id": "64eccbcea06cfa1e0662fa3569c7810acca2887e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2726, "license_type": "permissive", "max_line_length": 322, "num_lines": 47, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/elb_target.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Used to register or deregister a target in a target group\n class Elb_target < Base\n # @return [Symbol, nil] The default behaviour for targets that are unused is to leave them registered. If instead you would like to remove them set I(deregister_unused) to yes.\n attribute :deregister_unused\n validates :deregister_unused, type: Symbol\n\n # @return [Object, nil] An Availability Zone or all. This determines whether the target receives traffic from the load balancer nodes in the specified Availability Zone or from all enabled Availability Zones for the load balancer. This parameter is not supported if the target type of the target group is instance.\n attribute :target_az\n\n # @return [Object, nil] The Amazon Resource Name (ARN) of the target group. Mutually exclusive of I(target_group_name).\n attribute :target_group_arn\n\n # @return [String, nil] The name of the target group. Mutually exclusive of I(target_group_arn).\n attribute :target_group_name\n validates :target_group_name, type: String\n\n # @return [String] The ID of the target.\n attribute :target_id\n validates :target_id, presence: true, type: String\n\n # @return [String, nil] The port on which the target is listening. You can specify a port override. If a target is already registered, you can register it again using a different port.\n attribute :target_port\n validates :target_port, type: String\n\n # @return [:initial, :healthy, :unhealthy, :unused, :draining, :unavailable, nil] Blocks and waits for the target status to equal given value. For more detail on target status see U(http://docs.aws.amazon.com/elasticloadbalancing/latest/application/target-group-health-checks.html#target-health-states)\n attribute :target_status\n validates :target_status, expression_inclusion: {:in=>[:initial, :healthy, :unhealthy, :unused, :draining, :unavailable], :message=>\"%{value} needs to be :initial, :healthy, :unhealthy, :unused, :draining, :unavailable\"}, allow_nil: true\n\n # @return [Integer, nil] Maximum time in seconds to wait for target_status change\n attribute :target_status_timeout\n validates :target_status_timeout, type: Integer\n\n # @return [:present, :absent] Register or deregister the target.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6581284403800964, "alphanum_fraction": 0.6581284403800964, "avg_line_length": 50.3684196472168, "blob_id": "138f3787151670a159880b5e59aad23dce86d204", "content_id": "25c754c8a83d412c94b68c29fcd78d37bb304a0a", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2928, "license_type": "permissive", "max_line_length": 213, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/netapp_e_volume.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or remove volumes (standard and thin) for NetApp E/EF-series storage arrays.\n class Netapp_e_volume < Base\n # @return [:present, :absent] Whether the specified volume should exist or not.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String] The name of the volume to manage\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object] Required only when requested state is 'present'. The name of the storage pool the volume should exist on.\n attribute :storage_pool_name\n validates :storage_pool_name, presence: true\n\n # @return [:bytes, :b, :kb, :mb, :gb, :tb, :pb, :eb, :zb, :yb, nil] The unit used to interpret the size parameter\n attribute :size_unit\n validates :size_unit, expression_inclusion: {:in=>[:bytes, :b, :kb, :mb, :gb, :tb, :pb, :eb, :zb, :yb], :message=>\"%{value} needs to be :bytes, :b, :kb, :mb, :gb, :tb, :pb, :eb, :zb, :yb\"}, allow_nil: true\n\n # @return [Object] Required only when state = 'present'. The size of the volume in (size_unit).\n attribute :size\n validates :size, presence: true\n\n # @return [Integer, nil] The segment size of the new volume\n attribute :segment_size_kb\n validates :segment_size_kb, type: Integer\n\n # @return [:yes, :no, nil] Whether the volume should be thin provisioned. Thin volumes can only be created on disk pools (raidDiskPool).\n attribute :thin_provision\n validates :thin_provision, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object] Initial size of the thin volume repository volume (in size_unit)\n attribute :thin_volume_repo_size\n validates :thin_volume_repo_size, presence: true\n\n # @return [String, nil] Maximum size that the thin volume repository volume will automatically expand to\n attribute :thin_volume_max_repo_size\n validates :thin_volume_max_repo_size, type: String\n\n # @return [Symbol, nil] Whether an existing SSD cache should be enabled on the volume (fails if no SSD cache defined),The default value is to ignore existing SSD cache setting.\n attribute :ssd_cache_enabled\n validates :ssd_cache_enabled, type: Symbol\n\n # @return [:yes, :no, nil] If data assurance should be enabled for the volume\n attribute :data_assurance_enabled\n validates :data_assurance_enabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6929292678833008, "alphanum_fraction": 0.6929292678833008, "avg_line_length": 28.117647171020508, "blob_id": "de6fe20f49273b2e6794bf664088021a03c44cce", "content_id": "486bac9395a77b937b364d211b8b83809a0ac6e8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 495, "license_type": "permissive", "max_line_length": 84, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/cloud/digital_ocean/digital_ocean_domain_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to gather facts about DigitalOcean provided Domains.\n class Digital_ocean_domain_facts < Base\n # @return [String, nil] Name of the domain to gather facts for.\n attribute :domain_name\n validates :domain_name, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6593939661979675, "alphanum_fraction": 0.6593939661979675, "avg_line_length": 49, "blob_id": "919d562a78adfaedf9744d721409b28b0974bff3", "content_id": "d4e6bf49d42ba6cc7f5b7a0f772daffd9d44b585", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1650, "license_type": "permissive", "max_line_length": 188, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/packaging/os/xbps.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage packages with the XBPS package manager.\n class Xbps < Base\n # @return [Array<String>, String, nil] Name of the package to install, upgrade, or remove.\n attribute :name\n validates :name, type: TypeGeneric.new(String)\n\n # @return [:present, :absent, :latest, nil] Desired state of the package.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :latest], :message=>\"%{value} needs to be :present, :absent, :latest\"}, allow_nil: true\n\n # @return [:yes, :no, nil] When removing a package, also remove its dependencies, provided that they are not required by other packages and were not explicitly installed by a user.\n attribute :recurse\n validates :recurse, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Whether or not to refresh the master package lists. This can be run as part of a package installation or as a separate step.\n attribute :update_cache\n validates :update_cache, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Whether or not to upgrade whole system\n attribute :upgrade\n validates :upgrade, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6896725296974182, "alphanum_fraction": 0.691183865070343, "avg_line_length": 68.64912414550781, "blob_id": "bec9bfa9e5cabcdb0080a5dae854d9801053c465", "content_id": "6f52145f7f38f11cfab56eee1883426f65149e99", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3970, "license_type": "permissive", "max_line_length": 418, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/s3_sync.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The S3 module is great, but it is very slow for a large volume of files- even a dozen will be noticeable. In addition to speed, it handles globbing, inclusions/exclusions, mime types, expiration mapping, recursion, cache control and smart directory mapping.\n class S3_sync < Base\n # @return [:push] sync direction.\n attribute :mode\n validates :mode, presence: true, expression_inclusion: {:in=>[:push], :message=>\"%{value} needs to be :push\"}\n\n # @return [:force, :checksum, :date_size, nil] Difference determination method to allow changes-only syncing. Unlike rsync, files are not patched- they are fully skipped or fully uploaded.,date_size will upload if file sizes don't match or if local file modified date is newer than s3's version,checksum will compare etag values based on s3's implementation of chunked md5s.,force will always upload all files.\n attribute :file_change_strategy\n validates :file_change_strategy, expression_inclusion: {:in=>[:force, :checksum, :date_size], :message=>\"%{value} needs to be :force, :checksum, :date_size\"}, allow_nil: true\n\n # @return [String] Bucket name.\n attribute :bucket\n validates :bucket, presence: true, type: String\n\n # @return [String, nil] In addition to file path, prepend s3 path with this prefix. Module will add slash at end of prefix if necessary.\n attribute :key_prefix\n validates :key_prefix, type: String\n\n # @return [String] File/directory path for synchronization. This is a local path.,This root path is scrubbed from the key name, so subdirectories will remain as keys.\n attribute :file_root\n validates :file_root, presence: true, type: String\n\n # @return [:\"\", :private, :\"public-read\", :\"public-read-write\", :\"authenticated-read\", :\"aws-exec-read\", :\"bucket-owner-read\", :\"bucket-owner-full-control\", nil] Canned ACL to apply to synced files.,Changing this ACL only changes newly synced files, it does not trigger a full reupload.\n attribute :permission\n validates :permission, expression_inclusion: {:in=>[:\"\", :private, :\"public-read\", :\"public-read-write\", :\"authenticated-read\", :\"aws-exec-read\", :\"bucket-owner-read\", :\"bucket-owner-full-control\"], :message=>\"%{value} needs to be :\\\"\\\", :private, :\\\"public-read\\\", :\\\"public-read-write\\\", :\\\"authenticated-read\\\", :\\\"aws-exec-read\\\", :\\\"bucket-owner-read\\\", :\\\"bucket-owner-full-control\\\"\"}, allow_nil: true\n\n # @return [Hash, nil] Dict entry from extension to MIME type. This will override any default/sniffed MIME type. For example C({\".txt\": \"application/text\", \".yml\": \"application/text\"})\\r\\n\n attribute :mime_map\n validates :mime_map, type: Hash\n\n # @return [String, nil] Shell pattern-style file matching.,Used before exclude to determine eligible files (for instance, only \"*.gif\"),For multiple patterns, comma-separate them.\n attribute :include\n validates :include, type: String\n\n # @return [String, nil] Shell pattern-style file matching.,Used after include to remove files (for instance, skip \"*.txt\"),For multiple patterns, comma-separate them.\n attribute :exclude\n validates :exclude, type: String\n\n # @return [Array<String>, String, nil] This is a string.,Cache-Control header set on uploaded objects.,Directives are separated by commmas.\n attribute :cache_control\n validates :cache_control, type: TypeGeneric.new(String)\n\n # @return [Boolean, nil] Remove remote files that exist in bucket but are not present in the file root.\n attribute :delete\n validates :delete, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7009345889091492, "alphanum_fraction": 0.7009345889091492, "avg_line_length": 34.66666793823242, "blob_id": "0fea7d178407f4af4bb1f7e591cab7d26c999b57", "content_id": "363ce7a0f761d03c939f31f8d9471cbcf6e9e67f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 749, "license_type": "permissive", "max_line_length": 229, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/remote_management/oneview/oneview_network_set_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Retrieve facts about the Network Sets from OneView.\n class Oneview_network_set_facts < Base\n # @return [String, nil] Network Set name.\n attribute :name\n validates :name, type: String\n\n # @return [Array<String>, String, nil] List with options to gather facts about Network Set. Option allowed: C(withoutEthernet). The option C(withoutEthernet) retrieves the list of network_sets excluding Ethernet networks.\n attribute :options\n validates :options, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6859813332557678, "alphanum_fraction": 0.7001869082450867, "avg_line_length": 73.30555725097656, "blob_id": "e82a89f1a51250b678fd783240f9d7b1c44af205", "content_id": "3ebf2c047cfc0bf81612220c99b7e2ea0ddbd826", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2675, "license_type": "permissive", "max_line_length": 463, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_compute_ssl_policy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Represents a SSL policy. SSL policies give you the ability to control the features of SSL that your SSL proxy or HTTPS load balancer negotiates.\n class Gcp_compute_ssl_policy < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] An optional description of this resource.\n attribute :description\n\n # @return [String] Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:COMPATIBLE, :MODERN, :RESTRICTED, :CUSTOM, nil] Profile specifies the set of SSL features that can be used by the load balancer when negotiating SSL with clients. This can be one of `COMPATIBLE`, `MODERN`, `RESTRICTED`, or `CUSTOM`. If using `CUSTOM`, the set of SSL features to enable must be specified in the `customFeatures` field.\n attribute :profile\n validates :profile, expression_inclusion: {:in=>[:COMPATIBLE, :MODERN, :RESTRICTED, :CUSTOM], :message=>\"%{value} needs to be :COMPATIBLE, :MODERN, :RESTRICTED, :CUSTOM\"}, allow_nil: true\n\n # @return [:TLS_1_0, :TLS_1_1, :TLS_1_2, nil] The minimum version of SSL protocol that can be used by the clients to establish a connection with the load balancer. This can be one of `TLS_1_0`, `TLS_1_1`, `TLS_1_2`.\n attribute :min_tls_version\n validates :min_tls_version, expression_inclusion: {:in=>[:TLS_1_0, :TLS_1_1, :TLS_1_2], :message=>\"%{value} needs to be :TLS_1_0, :TLS_1_1, :TLS_1_2\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] A list of features enabled when the selected profile is CUSTOM. The method returns the set of features that can be specified in this list. This field must be empty if the profile is not CUSTOM.\n attribute :custom_features\n validates :custom_features, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7228915691375732, "alphanum_fraction": 0.7228915691375732, "avg_line_length": 15.600000381469727, "blob_id": "381ed97fd505cc3eb2d0b5d436084a10a7615a86", "content_id": "72f957432f2879b2da7b5f29af95460bab58fb49", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 83, "license_type": "permissive", "max_line_length": 29, "num_lines": 5, "path": "/spec/rake/nested_tasks/roles/role1/handlers/handler1_test.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nhandler 'reboot' do\n command 'shutdown -r now'\nend\n" }, { "alpha_fraction": 0.6940828561782837, "alphanum_fraction": 0.6988165974617004, "avg_line_length": 51.8125, "blob_id": "6e01f77c09a01d901f1fde75cd7b3e6dddedf7f1", "content_id": "476a48b121b307c6c09b3a1e4abd95e8e8d62eb6", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1690, "license_type": "permissive", "max_line_length": 346, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigiq_regkey_license.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages licenses in a BIG-IQ registration key pool.\n class Bigiq_regkey_license < Base\n # @return [String] The registration key pool that you want to place the license in.,You must be mindful to name your registration pools unique names. While BIG-IQ does not require this, this module does. If you do not do this, the behavior of the module is undefined and you may end up putting licenses in the wrong registration key pool.\n attribute :regkey_pool\n validates :regkey_pool, presence: true, type: String\n\n # @return [String] The license key to put in the pool.\n attribute :license_key\n validates :license_key, presence: true, type: String\n\n # @return [Object, nil] Description of the license.\n attribute :description\n\n # @return [Symbol, nil] A key that signifies that you accept the F5 EULA for this license.,A copy of the EULA can be found here https://askf5.f5.com/csp/article/K12902,This is required when C(state) is C(present).\n attribute :accept_eula\n validates :accept_eula, type: Symbol\n\n # @return [:absent, :present, nil] The state of the regkey license in the pool on the system.,When C(present), guarantees that the license exists in the pool.,When C(absent), removes the license from the pool.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6493168473243713, "alphanum_fraction": 0.6493168473243713, "avg_line_length": 38.410255432128906, "blob_id": "94035ce674588f74a6e570c75eaba0b216f624be", "content_id": "6dcba8947c9557dc04fbbe16ba55a4e84972372e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1537, "license_type": "permissive", "max_line_length": 143, "num_lines": 39, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/ansible_tower/tower_inventory.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, or destroy Ansible Tower inventories. See U(https://www.ansible.com/tower) for an overview.\n class Tower_inventory < Base\n # @return [String] The name to use for the inventory.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The description to use for the inventory.\n attribute :description\n validates :description, type: String\n\n # @return [String] Organization the inventory belongs to.\n attribute :organization\n validates :organization, presence: true, type: String\n\n # @return [Object, nil] Inventory variables. Use C(@) to get from file.\n attribute :variables\n\n # @return [:\"\", :smart, nil] The kind field. Cannot be modified after created.\n attribute :kind\n validates :kind, expression_inclusion: {:in=>[:\"\", :smart], :message=>\"%{value} needs to be :\\\"\\\", :smart\"}, allow_nil: true\n\n # @return [Object, nil] The host_filter field. Only useful when C(kind=smart).\n attribute :host_filter\n\n # @return [:present, :absent, nil] Desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6348178386688232, "alphanum_fraction": 0.6364372372627258, "avg_line_length": 45.3125, "blob_id": "2610e80fd8666548eb8ac5f2b6dc1ddd301cc322", "content_id": "fde860f9e0de1ac670763ea703d7db093f37ded5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3705, "license_type": "permissive", "max_line_length": 275, "num_lines": 80, "path": "/lib/ansible/ruby/modules/generated/system/ufw.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage firewall with UFW.\n class Ufw < Base\n # @return [:disabled, :enabled, :reloaded, :reset, nil] C(enabled) reloads firewall and enables firewall on boot.,C(disabled) unloads firewall and disables firewall on boot.,C(reloaded) reloads firewall.,C(reset) disables and resets firewall to installation defaults.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:disabled, :enabled, :reloaded, :reset], :message=>\"%{value} needs to be :disabled, :enabled, :reloaded, :reset\"}, allow_nil: true\n\n # @return [:allow, :deny, :reject, nil] Change the default policy for incoming or outgoing traffic.\n attribute :policy\n validates :policy, expression_inclusion: {:in=>[:allow, :deny, :reject], :message=>\"%{value} needs to be :allow, :deny, :reject\"}, allow_nil: true\n\n # @return [:in, :incoming, :out, :outgoing, :routed, nil] Select direction for a rule or default policy command.\n attribute :direction\n validates :direction, expression_inclusion: {:in=>[:in, :incoming, :out, :outgoing, :routed], :message=>\"%{value} needs to be :in, :incoming, :out, :outgoing, :routed\"}, allow_nil: true\n\n # @return [:low, :medium, :high, :full, Boolean, nil] Toggles logging. Logged packets use the LOG_KERN syslog facility.\n attribute :logging\n validates :logging, expression_inclusion: {:in=>[true, false, :low, :medium, :high, :full], :message=>\"%{value} needs to be true, false, :low, :medium, :high, :full\"}, allow_nil: true\n\n # @return [Object, nil] Insert the corresponding rule as rule number NUM\n attribute :insert\n\n # @return [:allow, :deny, :limit, :reject, nil] Add firewall rule\n attribute :rule\n validates :rule, expression_inclusion: {:in=>[:allow, :deny, :limit, :reject], :message=>\"%{value} needs to be :allow, :deny, :limit, :reject\"}, allow_nil: true\n\n # @return [Symbol, nil] Log new connections matched to this rule\n attribute :log\n validates :log, type: Symbol\n\n # @return [String, nil] Source IP address.\n attribute :from_ip\n validates :from_ip, type: String\n\n # @return [Integer, nil] Source port.\n attribute :from_port\n validates :from_port, type: Integer\n\n # @return [String, nil] Destination IP address.\n attribute :to_ip\n validates :to_ip, type: String\n\n # @return [Integer, nil] Destination port.\n attribute :to_port\n validates :to_port, type: Integer\n\n # @return [:any, :tcp, :udp, :ipv6, :esp, :ah, nil] TCP/IP protocol.\n attribute :proto\n validates :proto, expression_inclusion: {:in=>[:any, :tcp, :udp, :ipv6, :esp, :ah], :message=>\"%{value} needs to be :any, :tcp, :udp, :ipv6, :esp, :ah\"}, allow_nil: true\n\n # @return [String, nil] Use profile located in C(/etc/ufw/applications.d).\n attribute :name\n validates :name, type: String\n\n # @return [Symbol, nil] Delete rule.\n attribute :delete\n validates :delete, type: Symbol\n\n # @return [String, nil] Specify interface for rule.\n attribute :interface\n validates :interface, type: String\n\n # @return [Symbol, nil] Apply the rule to routed/forwarded packets.\n attribute :route\n validates :route, type: Symbol\n\n # @return [String, nil] Add a comment to the rule. Requires UFW version >=0.35.\n attribute :comment\n validates :comment, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6610113978385925, "alphanum_fraction": 0.6623165011405945, "avg_line_length": 40.41891860961914, "blob_id": "b60710ce43fc5076348c28d57b6f150c83222c2f", "content_id": "6e5d3837242b625a880d3c058b800df09c6586b6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3065, "license_type": "permissive", "max_line_length": 235, "num_lines": 74, "path": "/lib/ansible/ruby/modules/generated/cloud/vultr/vr_server.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Deploy, start, stop, update, restart, reinstall servers.\n class Vultr_server < Base\n # @return [String] Name of the server.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Hostname to assign to this server.\n attribute :hostname\n\n # @return [String, nil] The operating system.,Required if the server does not yet exist.\n attribute :os\n validates :os, type: String\n\n # @return [Object, nil] The firewall group to assign this server to.\n attribute :firewall_group\n\n # @return [Array<String>, String, nil] Plan to use for the server.,Required if the server does not yet exist.\n attribute :plan\n validates :plan, type: TypeGeneric.new(String)\n\n # @return [Symbol, nil] Force stop/start the server if required to apply changes,Otherwise a running server will not be changed.\n attribute :force\n validates :force, type: Symbol\n\n # @return [Symbol, nil] Whether to send an activation email when the server is ready or not.,Only considered on creation.\n attribute :notify_activate\n validates :notify_activate, type: Symbol\n\n # @return [Symbol, nil] Whether to enable private networking or not.\n attribute :private_network_enabled\n validates :private_network_enabled, type: Symbol\n\n # @return [Symbol, nil] Whether to enable automatic backups or not.\n attribute :auto_backup_enabled\n validates :auto_backup_enabled, type: Symbol\n\n # @return [Symbol, nil] Whether to enable IPv6 or not.\n attribute :ipv6_enabled\n validates :ipv6_enabled, type: Symbol\n\n # @return [Object, nil] Tag for the server.\n attribute :tag\n\n # @return [Object, nil] User data to be passed to the server.\n attribute :user_data\n\n # @return [Object, nil] Name of the startup script to execute on boot.,Only considered while creating the server.\n attribute :startup_script\n\n # @return [Object, nil] List of SSH keys passed to the server on creation.\n attribute :ssh_keys\n\n # @return [Object, nil] IP address of the floating IP to use as the main IP of this server.,Only considered on creation.\n attribute :reserved_ip_v4\n\n # @return [String, nil] Region the server is deployed into.,Required if the server does not yet exist.\n attribute :region\n validates :region, type: String\n\n # @return [:present, :absent, :restarted, :reinstalled, :started, :stopped, nil] State of the server.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :restarted, :reinstalled, :started, :stopped], :message=>\"%{value} needs to be :present, :absent, :restarted, :reinstalled, :started, :stopped\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6379720568656921, "alphanum_fraction": 0.6400535106658936, "avg_line_length": 37.21590805053711, "blob_id": "91fb47db55a03f26c49694b3d03e220a27a9364f", "content_id": "4eef18c843975311f1cfba813ef279eab581025d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6726, "license_type": "permissive", "max_line_length": 176, "num_lines": 176, "path": "/lib/ansible/ruby/modules/generated/cloud/univention/udm_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows to manage posix users on a univention corporate server (UCS). It uses the python API of the UCS to create a new object or edit it.\n class Udm_user < Base\n # @return [:present, :absent, nil] Whether the user is present or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object] User name\n attribute :username\n validates :username, presence: true\n\n # @return [String, nil] First name. Required if C(state=present).\n attribute :firstname\n validates :firstname, type: String\n\n # @return [String, nil] Last name. Required if C(state=present).\n attribute :lastname\n validates :lastname, type: String\n\n # @return [String, nil] Password. Required if C(state=present).\n attribute :password\n validates :password, type: String\n\n # @return [Object, nil] Birthday\n attribute :birthday\n\n # @return [Object, nil] City of users business address.\n attribute :city\n\n # @return [Object, nil] Country of users business address.\n attribute :country\n\n # @return [Object, nil] Department number of users business address.\n attribute :department_number\n\n # @return [Object, nil] Description (not gecos)\n attribute :description\n\n # @return [Object, nil] Display name (not gecos)\n attribute :display_name\n\n # @return [Object, nil] A list of e-mail addresses.\n attribute :email\n\n # @return [Object, nil] Employee number\n attribute :employee_number\n\n # @return [Object, nil] Employee type\n attribute :employee_type\n\n # @return [Object, nil] GECOS\n attribute :gecos\n\n # @return [Object, nil] POSIX groups, the LDAP DNs of the groups will be found with the LDAP filter for each group as $GROUP: C((&(objectClass=posixGroup)(cn=$GROUP))).\n attribute :groups\n\n # @return [Object, nil] Home NFS share. Must be a LDAP DN, e.g. C(cn=home,cn=shares,ou=school,dc=example,dc=com).\n attribute :home_share\n\n # @return [Object, nil] Path to home NFS share, inside the homeShare.\n attribute :home_share_path\n\n # @return [Object, nil] List of private telephone numbers.\n attribute :home_telephone_number\n\n # @return [Object, nil] Windows home drive, e.g. C(\"H:\").\n attribute :homedrive\n\n # @return [Object, nil] List of alternative e-mail addresses.\n attribute :mail_alternative_address\n\n # @return [Object, nil] FQDN of mail server\n attribute :mail_home_server\n\n # @return [Object, nil] Primary e-mail address\n attribute :mail_primary_address\n\n # @return [Object, nil] Mobile phone number\n attribute :mobile_telephone_number\n\n # @return [Object, nil] Organisation\n attribute :organisation\n\n # @return [:yes, :no, nil] Override password history\n attribute :override_pw_history\n validates :override_pw_history, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Override password check\n attribute :override_pw_length\n validates :override_pw_length, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] List of pager telephone numbers.\n attribute :pager_telephonenumber\n\n # @return [Object, nil] List of telephone numbers.\n attribute :phone\n\n # @return [Object, nil] Postal code of users business address.\n attribute :postcode\n\n # @return [Array<String>, String, nil] Primary group. This must be the group LDAP DN.\n attribute :primary_group\n validates :primary_group, type: TypeGeneric.new(String)\n\n # @return [Object, nil] Windows profile directory\n attribute :profilepath\n\n # @return [0, 1, nil] Change password on next login.\n attribute :pwd_change_next_login\n validates :pwd_change_next_login, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [Object, nil] Room number of users business address.\n attribute :room_number\n\n # @return [Object, nil] Samba privilege, like allow printer administration, do domain join.\n attribute :samba_privileges\n\n # @return [Object, nil] Allow the authentication only on this Microsoft Windows host.\n attribute :samba_user_workstations\n\n # @return [Object, nil] Windows home path, e.g. C('\\\\\\\\$FQDN\\\\$USERNAME').\n attribute :sambahome\n\n # @return [Object, nil] Windows logon script.\n attribute :scriptpath\n\n # @return [Object, nil] A list of superiors as LDAP DNs.\n attribute :secretary\n\n # @return [Object, nil] Enable user for the following service providers.\n attribute :serviceprovider\n\n # @return [String, nil] Login shell\n attribute :shell\n validates :shell, type: String\n\n # @return [Object, nil] Street of users business address.\n attribute :street\n\n # @return [Object, nil] Title, e.g. C(Prof.).\n attribute :title\n\n # @return [String, nil] Unix home directory\n attribute :unixhome\n validates :unixhome, type: String\n\n # @return [String, nil] Account expiry date, e.g. C(1999-12-31).\n attribute :userexpiry\n validates :userexpiry, type: String\n\n # @return [String, nil] Define the whole position of users object inside the LDAP tree, e.g. C(cn=employee,cn=users,ou=school,dc=example,dc=com).\n attribute :position\n validates :position, type: String\n\n # @return [String, nil] C(always) will update passwords if they differ. C(on_create) will only set the password for newly created users.\n attribute :update_password\n validates :update_password, type: String\n\n # @return [String, nil] Organizational Unit inside the LDAP Base DN, e.g. C(school) for LDAP OU C(ou=school,dc=example,dc=com).\n attribute :ou\n validates :ou, type: String\n\n # @return [String, nil] LDAP subpath inside the organizational unit, e.g. C(cn=teachers,cn=users) for LDAP container C(cn=teachers,cn=users,dc=example,dc=com).\n attribute :subpath\n validates :subpath, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.699939489364624, "alphanum_fraction": 0.7045775651931763, "avg_line_length": 87.55357360839844, "blob_id": "3bb1bb334e6e5b7a07322108bc81ce1dd99424ee", "content_id": "654d349b9099c7e31c6bb5ef5a7cd4821a80772e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4959, "license_type": "permissive", "max_line_length": 824, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/files/copy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The C(copy) module copies a file from the local or remote machine to a location on the remote machine. Use the M(fetch) module to copy files from remote locations to the local box. If you need variable interpolation in copied files, use the M(template) module.\n # For Windows targets, use the M(win_copy) module instead.\n class Copy < Base\n # @return [String, nil] Local path to a file to copy to the remote server; can be absolute or relative. If path is a directory, it is copied recursively. In this case, if path ends with \"/\", only inside contents of that directory are copied to destination. Otherwise, if it does not end with \"/\", the directory itself with all contents is copied. This behavior is similar to Rsync.\n attribute :src\n validates :src, type: String\n\n # @return [String, nil] When used instead of I(src), sets the contents of a file directly to the specified value. For anything advanced or with formatting also look at the template module.\n attribute :content\n validates :content, type: String\n\n # @return [String] Remote absolute path where the file should be copied to. If I(src) is a directory, this must be a directory too. If I(dest) is a nonexistent path and if either I(dest) ends with \"/\" or I(src) is a directory, I(dest) is created. If I(src) and I(dest) are files, the parent directory of I(dest) isn't created: the task fails if it doesn't already exist.\n attribute :dest\n validates :dest, presence: true, type: String\n\n # @return [:yes, :no, nil] Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.\n attribute :backup\n validates :backup, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] the default is C(yes), which will replace the remote file when contents are different than the source. If C(no), the file will only be transferred if the destination does not exist.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, Array<String>, String, nil] Mode the file or directory should be. For those used to I(/usr/bin/chmod) remember that modes are actually octal numbers. You must either add a leading zero so that Ansible's YAML parser knows it is an octal number (like C(0644) or C(01777)) or quote it (like C('644') or C('1777')) so Ansible receives a string and can do its own conversion from string into number. Giving Ansible a number without following one of these rules will end up with a decimal number which will have unexpected results. As of version 1.8, the mode may be specified as a symbolic mode (for example, C(u+rwx) or C(u=rw,g=r,o=r)). As of version 2.3, the mode may also be the special string C(preserve). C(preserve) means that the file will be given the same permissions as the source file.\n attribute :mode\n validates :mode, type: TypeGeneric.new(String)\n\n # @return [Object, nil] When doing a recursive copy set the mode for the directories. If this is not set we will use the system defaults. The mode is only set on directories which are newly created, and will not affect those that already existed.\n attribute :directory_mode\n\n # @return [:yes, :no, nil] If C(no), it will search for I(src) at originating/master machine.,If C(yes) it will go to the remote/target machine for the I(src). Default is C(no).,Currently I(remote_src) does not support recursive copying.,I(remote_src) only works with C(mode=preserve) as of version 2.6.\n attribute :remote_src\n validates :remote_src, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] This flag indicates that filesystem links in the destination, if they exist, should be followed.\n attribute :follow\n validates :follow, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] This flag indicates that filesystem links in the source tree, if they exist, should be followed.\n attribute :local_follow\n validates :local_follow, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] SHA1 checksum of the file being transferred. Used to validate that the copy of the file was successful.,If this is not provided, ansible will use the local calculated checksum of the src file.\n attribute :checksum\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6820135116577148, "alphanum_fraction": 0.6850828528404236, "avg_line_length": 41.8684196472168, "blob_id": "ed60e85525510de945299259a2d1290d5aea1a80", "content_id": "2fd6c53a62215df727bea2a0bba990e35107c55c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1629, "license_type": "permissive", "max_line_length": 211, "num_lines": 38, "path": "/lib/ansible/ruby/modules/generated/network/netvisor/pn_vrouterlbif.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Execute vrouter-loopback-interface-add, vrouter-loopback-interface-remove commands.\n # Each fabric, cluster, standalone switch, or virtual network (VNET) can provide its tenants with a virtual router (vRouter) service that forwards traffic between networks and implements Layer 3 protocols.\n class Pn_vrouterlbif < Base\n # @return [Object, nil] Provide login username if user is not root.\n attribute :pn_cliusername\n\n # @return [Object, nil] Provide login password if user is not root.\n attribute :pn_clipassword\n\n # @return [Object, nil] Target switch(es) to run the cli on.\n attribute :pn_cliswitch\n\n # @return [:present, :absent] State the action to perform. Use 'present' to add vrouter loopback interface and 'absent' to remove vrouter loopback interface.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String] Specify the name of the vRouter.\n attribute :pn_vrouter_name\n validates :pn_vrouter_name, presence: true, type: String\n\n # @return [Object, nil] Specify the interface index from 1 to 255.\n attribute :pn_index\n\n # @return [String] Specify the IP address.\n attribute :pn_interface_ip\n validates :pn_interface_ip, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7079234719276428, "alphanum_fraction": 0.7105191349983215, "avg_line_length": 76.0526351928711, "blob_id": "dbca7443cafceaea1d3607a5c59fd8ab133c739b", "content_id": "dd96d95512ae08bda2038ace0ac1e04104203553", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 7320, "license_type": "permissive", "max_line_length": 444, "num_lines": 95, "path": "/lib/ansible/ruby/modules/generated/windows/win_chocolatey.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage packages using Chocolatey (U(http://chocolatey.org/)).\n # If Chocolatey is missing from the system, the module will install it.\n # List of packages can be found at U(http://chocolatey.org/packages).\n class Win_chocolatey < Base\n # @return [:yes, :no, nil] Allow empty checksums to be used for downloaded resource from non-secure locations.,Use M(win_chocolatey_feature) with the name C(allowEmptyChecksums) to control this option globally.\n attribute :allow_empty_checksums\n validates :allow_empty_checksums, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Allow the installation of pre-release packages.,If I(state) is C(latest), the latest pre-release package will be installed.\n attribute :allow_prerelease\n validates :allow_prerelease, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:default, :x86, nil] Force Chocolatey to install the package of a specific process architecture.,When setting C(x86), will ensure Chocolatey installs the x86 package even when on an x64 bit OS.\n attribute :architecture\n validates :architecture, expression_inclusion: {:in=>[:default, :x86], :message=>\"%{value} needs to be :default, :x86\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Forces the install of a package, even if it already is installed.,Using I(force) will cause Ansible to always report that a change was made.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Arguments to pass to the native installer.,These are arguments that are passed directly to the installer the Chocolatey package runs, this is generally an advanced option.\n attribute :install_args\n validates :install_args, type: String\n\n # @return [:yes, :no, nil] Ignore the checksums provided by the package.,Use M(win_chocolatey_feature) with the name C(checksumFiles) to control this option globally.\n attribute :ignore_checksums\n validates :ignore_checksums, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Ignore dependencies, only install/upgrade the package itself.\n attribute :ignore_dependencies\n validates :ignore_dependencies, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Array<String>, String] Name of the package(s) to be installed.,Set to C(all) to run the action on all the installed packages.\n attribute :name\n validates :name, presence: true, type: TypeGeneric.new(String)\n\n # @return [String, nil] Parameters to pass to the package.,These are parameters specific to the Chocolatey package and are generally documented by the package itself.,Before Ansible 2.7, this option was just I(params).\n attribute :package_params\n validates :package_params, type: String\n\n # @return [String, nil] Proxy URL used to install chocolatey and the package.,Use M(win_chocolatey_config) with the name C(proxy) to control this option globally.\n attribute :proxy_url\n validates :proxy_url, type: String\n\n # @return [String, nil] Proxy username used to install Chocolatey and the package.,Before Ansible 2.7, users with double quote characters C(\") would need to be escaped with C(\\) beforehand. This is no longer necessary.,Use M(win_chocolatey_config) with the name C(proxyUser) to control this option globally.\n attribute :proxy_username\n validates :proxy_username, type: String\n\n # @return [String, nil] Proxy password used to install Chocolatey and the package.,This value is exposed as a command argument and any privileged account can see this value when the module is running Chocolatey, define the password on the global config level with M(win_chocolatey_config) with name C(proxyPassword) to avoid this.\n attribute :proxy_password\n validates :proxy_password, type: String\n\n # @return [:yes, :no, nil] Do not run I(chocolateyInstall.ps1) or I(chocolateyUninstall.ps1) scripts when installing a package.\n attribute :skip_scripts\n validates :skip_scripts, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Specify the source to retrieve the package from.,Use M(win_chocolatey_source) to manage global sources.,This value can either be the URL to a Chocolatey feed, a path to a folder containing C(.nupkg) packages or the name of a source defined by M(win_chocolatey_source).,This value is also used when Chocolatey is not installed as the location of the install.ps1 script and only supports URLs for this case.\n attribute :source\n validates :source, type: String\n\n # @return [String, nil] A username to use with I(source) when accessing a feed that requires authentication.,It is recommended you define the credentials on a source with M(win_chocolatey_source) instead of passing it per task.\n attribute :source_username\n validates :source_username, type: String\n\n # @return [String, nil] The password for I(source_username).,This value is exposed as a command argument and any privileged account can see this value when the module is running Chocolatey, define the credentials with a source with M(win_chocolatey_source) to avoid this.\n attribute :source_password\n validates :source_password, type: String\n\n # @return [String, nil] State of the package on the system.,When C(absent), will ensure the package is not installed.,When C(present), will ensure the package is installed.,When C(downgrade), will allow Chocolatey to downgrade a package if I(version) is older than the installed version.,When C(latest), will ensure the package is installed to the latest available version.,When C(reinstalled), will uninstall and reinstall the package.\n attribute :state\n validates :state, type: String\n\n # @return [Integer, nil] The time to allow chocolatey to finish before timing out.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [:yes, :no, nil] Used when downloading the Chocolatey install script if Chocolatey is not already installed, this does not affect the Chocolatey package install process.,When C(no), no SSL certificates will be validated.,This should only be used on personally controlled sites using self-signed certificate.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Specific version of the package to be installed.,Ignored when I(state) is set to C(absent).\n attribute :version\n validates :version, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7005758285522461, "alphanum_fraction": 0.7005758285522461, "avg_line_length": 73.42857360839844, "blob_id": "51ffcf350093f36493deea8ff633808254c2561f", "content_id": "8bc48e7361622dc1a77f41518a19c130a4052b05", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3126, "license_type": "permissive", "max_line_length": 716, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/windows/win_regedit.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add, modify or remove registry keys and values.\n # More information about the windows registry from Wikipedia U(https://en.wikipedia.org/wiki/Windows_Registry).\n class Win_regedit < Base\n # @return [String] Name of the registry path.,Should be in one of the following registry hives: HKCC, HKCR, HKCU, HKLM, HKU.\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [String, nil] Name of the registry entry in the above C(path) parameters.,If not provided, or empty then the '(Default)' property for the key will be used.\n attribute :name\n validates :name, type: String\n\n # @return [Integer, Array<String>, String, nil] Value of the registry entry C(name) in C(path).,If not specified then the value for the property will be null for the corresponding C(type).,Binary and None data should be expressed in a yaml byte array or as comma separated hex values.,An easy way to generate this is to run C(regedit.exe) and use the I(export) option to save the registry values to a file.,In the exported file, binary value will look like C(hex:be,ef,be,ef), the C(hex:) prefix is optional.,DWORD and QWORD values should either be represented as a decimal number or a hex value.,Multistring values should be passed in as a list.,See the examples for more details on how to format this data.\n attribute :data\n validates :data, type: TypeGeneric.new(String, Integer)\n\n # @return [:binary, :dword, :expandstring, :multistring, :string, :qword, nil] The registry value data type.\n attribute :type\n validates :type, expression_inclusion: {:in=>[:binary, :dword, :expandstring, :multistring, :string, :qword], :message=>\"%{value} needs to be :binary, :dword, :expandstring, :multistring, :string, :qword\"}, allow_nil: true\n\n # @return [:absent, :present, nil] The state of the registry entry.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:yes, :no, nil] When C(state) is 'absent' then this will delete the entire key.,If C(no) then it will only clear out the '(Default)' property for that key.\n attribute :delete_key\n validates :delete_key, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] A path to a hive key like C:\\Users\\Default\\NTUSER.DAT to load in the registry.,This hive is loaded under the HKLM:\\ANSIBLE key which can then be used in I(name) like any other path.,This can be used to load the default user profile registry hive or any other hive saved as a file.,Using this function requires the user to have the C(SeRestorePrivilege) and C(SeBackupPrivilege) privileges enabled.\n attribute :hive\n validates :hive, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7235968708992004, "alphanum_fraction": 0.7235968708992004, "avg_line_length": 79.82926940917969, "blob_id": "634f16319ce0731821f3a3367d7862c2a803cd19", "content_id": "7fe4b59e58aa86d0f6e0de22e8a91db0558ce3f7", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3314, "license_type": "permissive", "max_line_length": 391, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/network/junos/junos_command.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Sends an arbitrary set of commands to an JUNOS node and returns the results read from the device. This module includes an argument that will cause the module to wait for a specific condition before returning or timing out if the condition is not met.\n class Junos_command < Base\n # @return [Array<String>, String, nil] The commands to send to the remote junos device over the configured provider. The resulting output from the command is returned. If the I(wait_for) argument is provided, the module is not returned until the condition is satisfied or the number of I(retries) has been exceeded.\n attribute :commands\n validates :commands, type: TypeGeneric.new(String)\n\n # @return [String, nil] The C(rpcs) argument accepts a list of RPCs to be executed over a netconf session and the results from the RPC execution is return to the playbook via the modules results dictionary.\n attribute :rpcs\n validates :rpcs, type: String\n\n # @return [Array<String>, String, nil] Specifies what to evaluate from the output of the command and what conditionals to apply. This argument will cause the task to wait for a particular conditional to be true before moving forward. If the conditional is not true by the configured retries, the task fails. See examples.\n attribute :wait_for\n validates :wait_for, type: TypeGeneric.new(String)\n\n # @return [:any, :all, nil] The I(match) argument is used in conjunction with the I(wait_for) argument to specify the match policy. Valid values are C(all) or C(any). If the value is set to C(all) then all conditionals in the I(wait_for) must be satisfied. If the value is set to C(any) then only one of the values must be satisfied.\n attribute :match\n validates :match, expression_inclusion: {:in=>[:any, :all], :message=>\"%{value} needs to be :any, :all\"}, allow_nil: true\n\n # @return [Integer, nil] Specifies the number of retries a command should be tried before it is considered failed. The command is run on the target device every retry and evaluated against the I(wait_for) conditionals.\n attribute :retries\n validates :retries, type: Integer\n\n # @return [Integer, nil] Configures the interval in seconds to wait between retries of the command. If the command does not pass the specified conditional, the interval indicates how to long to wait before trying the command again.\n attribute :interval\n validates :interval, type: Integer\n\n # @return [:text, :json, :xml, :set, nil] Encoding scheme to use when serializing output from the device. This handles how to properly understand the output and apply the conditionals path to the result set. For I(rpcs) argument default display is C(xml) and for I(commands) argument default display is C(text). Value C(set) is applicable only for fetching configuration from device.\n attribute :display\n validates :display, expression_inclusion: {:in=>[:text, :json, :xml, :set], :message=>\"%{value} needs to be :text, :json, :xml, :set\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7306900024414062, "alphanum_fraction": 0.7306900024414062, "avg_line_length": 70.9259262084961, "blob_id": "d06306e2d18ad12d19782bfb96b3e6dc9bf7342d", "content_id": "24dbc76fb20138078e9b4190f6b37e1e7c1fcbc4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1942, "license_type": "permissive", "max_line_length": 361, "num_lines": 27, "path": "/lib/ansible/ruby/modules/generated/network/cnos/cnos_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Collects a base set of device facts from a remote Lenovo device running on CNOS. This module prepends all of the base network fact keys with C(ansible_net_<fact>). The facts module will always collect a base set of facts from the device and can enable or disable collection of additional facts.\n class Cnos_facts < Base\n # @return [:yes, :no, nil] Instructs the module to enter privileged mode on the remote device before sending any commands. If not specified, the device will attempt to execute all commands in non-privileged mode. If the value is not specified in the task, the value of environment variable C(ANSIBLE_NET_AUTHORIZE) will be used instead.\n attribute :authorize\n validates :authorize, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the password to use if required to enter privileged mode on the remote device. If I(authorize) is false, then this argument does nothing. If the value is not specified in the task, the value of environment variable C(ANSIBLE_NET_AUTH_PASS) will be used instead.\n attribute :auth_pass\n\n # @return [Object, nil] A dict object containing connection details.\n attribute :provider\n\n # @return [String, nil] When supplied, this argument will restrict the facts collected to a given subset. Possible values for this argument include all, hardware, config, and interfaces. Can specify a list of values to include a larger subset. Values can also be used with an initial C(M(!)) to specify that a specific subset should not be collected.\n attribute :gather_subset\n validates :gather_subset, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6538181900978088, "alphanum_fraction": 0.6538181900978088, "avg_line_length": 40.66666793823242, "blob_id": "eac83708295b10d5157929f0aefd113fbcc97fb0", "content_id": "beedcfa854cc2bb0118c92e3c54881b47be85b3a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1375, "license_type": "permissive", "max_line_length": 220, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/monitoring/zabbix/zabbix_hostmacro.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # manages Zabbix host macros, it can create, update or delete them.\n class Zabbix_hostmacro < Base\n # @return [String] Name of the host.\n attribute :host_name\n validates :host_name, presence: true, type: String\n\n # @return [String] Name of the host macro.\n attribute :macro_name\n validates :macro_name, presence: true, type: String\n\n # @return [String] Value of the host macro.\n attribute :macro_value\n validates :macro_value, presence: true, type: String\n\n # @return [:present, :absent, nil] State of the macro.,On C(present), it will create if macro does not exist or update the macro if the associated data is different.,On C(absent) will remove a macro if it exists.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Only updates an existing macro if set to C(yes).\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6534755825996399, "alphanum_fraction": 0.6538196802139282, "avg_line_length": 38.27027130126953, "blob_id": "b17b8fa64c3ab61b642abd2fab8bc98226729f7b", "content_id": "3360584f2acc34974f7afb51769a543e503566da", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2906, "license_type": "permissive", "max_line_length": 173, "num_lines": 74, "path": "/lib/ansible/ruby/modules/generated/network/meraki/meraki_device.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Visibility into devices associated to a Meraki environment.\n class Meraki_device < Base\n # @return [:absent, :present, :query, nil] Query an organization.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n\n # @return [String, nil] Name of organization.,If C(clone) is specified, C(org_name) is the name of the new organization.\n attribute :org_name\n validates :org_name, type: String\n\n # @return [Object, nil] ID of organization.\n attribute :org_id\n\n # @return [String, nil] Name of a network.\n attribute :net_name\n validates :net_name, type: String\n\n # @return [Object, nil] ID of a network.\n attribute :net_id\n\n # @return [String, nil] Serial number of a device to query.\n attribute :serial\n validates :serial, type: String\n\n # @return [String, nil] Hostname of network device to search for.\n attribute :hostname\n validates :hostname, type: String\n\n # @return [String, nil] Model of network device to search for.\n attribute :model\n validates :model, type: String\n\n # @return [String, nil] Space delimited list of tags to assign to device.\n attribute :tags\n validates :tags, type: String\n\n # @return [Float, nil] Latitude of device's geographic location.,Use negative number for southern hemisphere.\n attribute :lat\n validates :lat, type: Float\n\n # @return [Float, nil] Longitude of device's geographic location.,Use negative number for western hemisphere.\n attribute :lng\n validates :lng, type: Float\n\n # @return [Array<String>, String, nil] Postal address of device's location.\n attribute :address\n validates :address, type: TypeGeneric.new(String)\n\n # @return [Symbol, nil] Whether or not to set the latitude and longitude of a device based on the new address.,Only applies when C(lat) and C(lng) are not specified.\n attribute :move_map_marker\n validates :move_map_marker, type: Symbol\n\n # @return [String, nil] Serial number of device to query LLDP/CDP information from.\n attribute :serial_lldp_cdp\n validates :serial_lldp_cdp, type: String\n\n # @return [Object, nil] Timespan, in seconds, used to query LLDP and CDP information.,Must be less than 1 month.\n attribute :lldp_cdp_timespan\n\n # @return [String, nil] Serial number of device to query uplink information from.\n attribute :serial_uplink\n validates :serial_uplink, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7237011790275574, "alphanum_fraction": 0.7371578812599182, "avg_line_length": 80.64286041259766, "blob_id": "17c7c0a6314d964b7a921c3ca66d7b7efad21811", "content_id": "a55a54f3d471808ec2ca3b869de13e05c4277abd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 24003, "license_type": "permissive", "max_line_length": 596, "num_lines": 294, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_analyticsprofile.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure AnalyticsProfile object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_analyticsprofile < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Integer, nil] If a client receives an http response in less than the satisfactory latency threshold, the request is considered satisfied.,It is considered tolerated if it is not satisfied and less than tolerated latency factor multiplied by the satisfactory latency threshold.,Greater than this number and the client's request is considered frustrated.,Allowed values are 1-30000.,Default value when not specified in API or module is interpreted by Avi Controller as 500.,Units(MILLISECONDS).\n attribute :apdex_response_threshold\n validates :apdex_response_threshold, type: Integer\n\n # @return [Float, nil] Client tolerated response latency factor.,Client must receive a response within this factor times the satisfactory threshold (apdex_response_threshold) to be considered tolerated.,Allowed values are 1-1000.,Default value when not specified in API or module is interpreted by Avi Controller as 4.0.\n attribute :apdex_response_tolerated_factor\n validates :apdex_response_tolerated_factor, type: Float\n\n # @return [Integer, nil] Satisfactory client to avi round trip time(rtt).,Allowed values are 1-2000.,Default value when not specified in API or module is interpreted by Avi Controller as 250.,Units(MILLISECONDS).\n attribute :apdex_rtt_threshold\n validates :apdex_rtt_threshold, type: Integer\n\n # @return [Float, nil] Tolerated client to avi round trip time(rtt) factor.,It is a multiple of apdex_rtt_tolerated_factor.,Allowed values are 1-1000.,Default value when not specified in API or module is interpreted by Avi Controller as 4.0.\n attribute :apdex_rtt_tolerated_factor\n validates :apdex_rtt_tolerated_factor, type: Float\n\n # @return [Integer, nil] If a client is able to load a page in less than the satisfactory latency threshold, the pageload is considered satisfied.,It is considered tolerated if it is greater than satisfied but less than the tolerated latency multiplied by satisifed latency.,Greater than this number and the client's request is considered frustrated.,A pageload includes the time for dns lookup, download of all http objects, and page render time.,Allowed values are 1-30000.,Default value when not specified in API or module is interpreted by Avi Controller as 5000.,Units(MILLISECONDS).\n attribute :apdex_rum_threshold\n validates :apdex_rum_threshold, type: Integer\n\n # @return [Float, nil] Virtual service threshold factor for tolerated page load time (plt) as multiple of apdex_rum_threshold.,Allowed values are 1-1000.,Default value when not specified in API or module is interpreted by Avi Controller as 4.0.\n attribute :apdex_rum_tolerated_factor\n validates :apdex_rum_tolerated_factor, type: Float\n\n # @return [Integer, nil] A server http response is considered satisfied if latency is less than the satisfactory latency threshold.,The response is considered tolerated when it is greater than satisfied but less than the tolerated latency factor * s_latency.,Greater than this number and the server response is considered frustrated.,Allowed values are 1-30000.,Default value when not specified in API or module is interpreted by Avi Controller as 400.,Units(MILLISECONDS).\n attribute :apdex_server_response_threshold\n validates :apdex_server_response_threshold, type: Integer\n\n # @return [Float, nil] Server tolerated response latency factor.,Servermust response within this factor times the satisfactory threshold (apdex_server_response_threshold) to be considered tolerated.,Allowed values are 1-1000.,Default value when not specified in API or module is interpreted by Avi Controller as 4.0.\n attribute :apdex_server_response_tolerated_factor\n validates :apdex_server_response_tolerated_factor, type: Float\n\n # @return [Integer, nil] Satisfactory client to avi round trip time(rtt).,Allowed values are 1-2000.,Default value when not specified in API or module is interpreted by Avi Controller as 125.,Units(MILLISECONDS).\n attribute :apdex_server_rtt_threshold\n validates :apdex_server_rtt_threshold, type: Integer\n\n # @return [Float, nil] Tolerated client to avi round trip time(rtt) factor.,It is a multiple of apdex_rtt_tolerated_factor.,Allowed values are 1-1000.,Default value when not specified in API or module is interpreted by Avi Controller as 4.0.\n attribute :apdex_server_rtt_tolerated_factor\n validates :apdex_server_rtt_tolerated_factor, type: Float\n\n # @return [Object, nil] Configure which logs are sent to the avi controller from ses and how they are processed.\n attribute :client_log_config\n\n # @return [Object, nil] Configure to stream logs to an external server.,Field introduced in 17.1.1.\n attribute :client_log_streaming_config\n\n # @return [Integer, nil] A connection between client and avi is considered lossy when more than this percentage of out of order packets are received.,Allowed values are 1-100.,Default value when not specified in API or module is interpreted by Avi Controller as 50.,Units(PERCENT).\n attribute :conn_lossy_ooo_threshold\n validates :conn_lossy_ooo_threshold, type: Integer\n\n # @return [Integer, nil] A connection between client and avi is considered lossy when more than this percentage of packets are retransmitted due to timeout.,Allowed values are 1-100.,Default value when not specified in API or module is interpreted by Avi Controller as 20.,Units(PERCENT).\n attribute :conn_lossy_timeo_rexmt_threshold\n validates :conn_lossy_timeo_rexmt_threshold, type: Integer\n\n # @return [Integer, nil] A connection between client and avi is considered lossy when more than this percentage of packets are retransmitted.,Allowed values are 1-100.,Default value when not specified in API or module is interpreted by Avi Controller as 50.,Units(PERCENT).\n attribute :conn_lossy_total_rexmt_threshold\n validates :conn_lossy_total_rexmt_threshold, type: Integer\n\n # @return [Integer, nil] A client connection is considered lossy when percentage of times a packet could not be trasmitted due to tcp zero window is above this threshold.,Allowed values are 0-100.,Default value when not specified in API or module is interpreted by Avi Controller as 2.,Units(PERCENT).\n attribute :conn_lossy_zero_win_size_event_threshold\n validates :conn_lossy_zero_win_size_event_threshold, type: Integer\n\n # @return [Integer, nil] A connection between avi and server is considered lossy when more than this percentage of out of order packets are received.,Allowed values are 1-100.,Default value when not specified in API or module is interpreted by Avi Controller as 50.,Units(PERCENT).\n attribute :conn_server_lossy_ooo_threshold\n validates :conn_server_lossy_ooo_threshold, type: Integer\n\n # @return [Integer, nil] A connection between avi and server is considered lossy when more than this percentage of packets are retransmitted due to timeout.,Allowed values are 1-100.,Default value when not specified in API or module is interpreted by Avi Controller as 20.,Units(PERCENT).\n attribute :conn_server_lossy_timeo_rexmt_threshold\n validates :conn_server_lossy_timeo_rexmt_threshold, type: Integer\n\n # @return [Integer, nil] A connection between avi and server is considered lossy when more than this percentage of packets are retransmitted.,Allowed values are 1-100.,Default value when not specified in API or module is interpreted by Avi Controller as 50.,Units(PERCENT).\n attribute :conn_server_lossy_total_rexmt_threshold\n validates :conn_server_lossy_total_rexmt_threshold, type: Integer\n\n # @return [Integer, nil] A server connection is considered lossy when percentage of times a packet could not be trasmitted due to tcp zero window is above this threshold.,Allowed values are 0-100.,Default value when not specified in API or module is interpreted by Avi Controller as 2.,Units(PERCENT).\n attribute :conn_server_lossy_zero_win_size_event_threshold\n validates :conn_server_lossy_zero_win_size_event_threshold, type: Integer\n\n # @return [Object, nil] User defined description for the object.\n attribute :description\n\n # @return [Symbol, nil] Disable node (service engine) level analytics forvs metrics.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :disable_se_analytics\n validates :disable_se_analytics, type: Symbol\n\n # @return [Symbol, nil] Disable analytics on backend servers.,This may be desired in container environment when there are large number of ephemeral servers.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :disable_server_analytics\n validates :disable_server_analytics, type: Symbol\n\n # @return [Symbol, nil] Exclude client closed connection before an http request could be completed from being classified as an error.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :exclude_client_close_before_request_as_error\n validates :exclude_client_close_before_request_as_error, type: Symbol\n\n # @return [Symbol, nil] Exclude dns policy drops from the list of errors.,Field introduced in 17.2.2.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :exclude_dns_policy_drop_as_significant\n validates :exclude_dns_policy_drop_as_significant, type: Symbol\n\n # @return [Symbol, nil] Exclude queries to gslb services that are operationally down from the list of errors.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :exclude_gs_down_as_error\n validates :exclude_gs_down_as_error, type: Symbol\n\n # @return [Object, nil] List of http status codes to be excluded from being classified as an error.,Error connections or responses impacts health score, are included as significant logs, and may be classified as part of a dos attack.\n attribute :exclude_http_error_codes\n\n # @return [Symbol, nil] Exclude dns queries to domains outside the domains configured in the dns application profile from the list of errors.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :exclude_invalid_dns_domain_as_error\n validates :exclude_invalid_dns_domain_as_error, type: Symbol\n\n # @return [Symbol, nil] Exclude invalid dns queries from the list of errors.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :exclude_invalid_dns_query_as_error\n validates :exclude_invalid_dns_query_as_error, type: Symbol\n\n # @return [Symbol, nil] Exclude queries to domains that did not have configured services/records from the list of errors.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :exclude_no_dns_record_as_error\n validates :exclude_no_dns_record_as_error, type: Symbol\n\n # @return [Symbol, nil] Exclude queries to gslb services that have no available members from the list of errors.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :exclude_no_valid_gs_member_as_error\n validates :exclude_no_valid_gs_member_as_error, type: Symbol\n\n # @return [Symbol, nil] Exclude persistence server changed while load balancing' from the list of errors.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :exclude_persistence_change_as_error\n validates :exclude_persistence_change_as_error, type: Symbol\n\n # @return [Symbol, nil] Exclude server dns error response from the list of errors.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :exclude_server_dns_error_as_error\n validates :exclude_server_dns_error_as_error, type: Symbol\n\n # @return [Symbol, nil] Exclude server tcp reset from errors.,It is common for applications like ms exchange.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :exclude_server_tcp_reset_as_error\n validates :exclude_server_tcp_reset_as_error, type: Symbol\n\n # @return [Symbol, nil] Exclude 'server unanswered syns' from the list of errors.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :exclude_syn_retransmit_as_error\n validates :exclude_syn_retransmit_as_error, type: Symbol\n\n # @return [Symbol, nil] Exclude tcp resets by client from the list of potential errors.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :exclude_tcp_reset_as_error\n validates :exclude_tcp_reset_as_error, type: Symbol\n\n # @return [Symbol, nil] Exclude unsupported dns queries from the list of errors.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :exclude_unsupported_dns_query_as_error\n validates :exclude_unsupported_dns_query_as_error, type: Symbol\n\n # @return [Integer, nil] Time window (in secs) within which only unique health change events should occur.,Default value when not specified in API or module is interpreted by Avi Controller as 1209600.\n attribute :hs_event_throttle_window\n validates :hs_event_throttle_window, type: Integer\n\n # @return [Integer, nil] Maximum penalty that may be deducted from health score for anomalies.,Allowed values are 0-100.,Default value when not specified in API or module is interpreted by Avi Controller as 10.\n attribute :hs_max_anomaly_penalty\n validates :hs_max_anomaly_penalty, type: Integer\n\n # @return [Integer, nil] Maximum penalty that may be deducted from health score for high resource utilization.,Allowed values are 0-100.,Default value when not specified in API or module is interpreted by Avi Controller as 25.\n attribute :hs_max_resources_penalty\n validates :hs_max_resources_penalty, type: Integer\n\n # @return [Integer, nil] Maximum penalty that may be deducted from health score based on security assessment.,Allowed values are 0-100.,Default value when not specified in API or module is interpreted by Avi Controller as 100.\n attribute :hs_max_security_penalty\n validates :hs_max_security_penalty, type: Integer\n\n # @return [Integer, nil] Dos connection rate below which the dos security assessment will not kick in.,Default value when not specified in API or module is interpreted by Avi Controller as 1000.\n attribute :hs_min_dos_rate\n validates :hs_min_dos_rate, type: Integer\n\n # @return [Integer, nil] Adds free performance score credits to health score.,It can be used for compensating health score for known slow applications.,Allowed values are 0-100.,Default value when not specified in API or module is interpreted by Avi Controller as 0.\n attribute :hs_performance_boost\n validates :hs_performance_boost, type: Integer\n\n # @return [Float, nil] Threshold number of connections in 5min, below which apdexr, apdexc, rum_apdex, and other network quality metrics are not computed.,Default value when not specified in API or module is interpreted by Avi Controller as 10.0.\n attribute :hs_pscore_traffic_threshold_l4_client\n validates :hs_pscore_traffic_threshold_l4_client, type: Float\n\n # @return [Float, nil] Threshold number of connections in 5min, below which apdexr, apdexc, rum_apdex, and other network quality metrics are not computed.,Default value when not specified in API or module is interpreted by Avi Controller as 10.0.\n attribute :hs_pscore_traffic_threshold_l4_server\n validates :hs_pscore_traffic_threshold_l4_server, type: Float\n\n # @return [Float, nil] Score assigned when the certificate has expired.,Allowed values are 0-5.,Default value when not specified in API or module is interpreted by Avi Controller as 0.0.\n attribute :hs_security_certscore_expired\n validates :hs_security_certscore_expired, type: Float\n\n # @return [Float, nil] Score assigned when the certificate expires in more than 30 days.,Allowed values are 0-5.,Default value when not specified in API or module is interpreted by Avi Controller as 5.0.\n attribute :hs_security_certscore_gt30d\n validates :hs_security_certscore_gt30d, type: Float\n\n # @return [Float, nil] Score assigned when the certificate expires in less than or equal to 7 days.,Allowed values are 0-5.,Default value when not specified in API or module is interpreted by Avi Controller as 2.0.\n attribute :hs_security_certscore_le07d\n validates :hs_security_certscore_le07d, type: Float\n\n # @return [Float, nil] Score assigned when the certificate expires in less than or equal to 30 days.,Allowed values are 0-5.,Default value when not specified in API or module is interpreted by Avi Controller as 4.0.\n attribute :hs_security_certscore_le30d\n validates :hs_security_certscore_le30d, type: Float\n\n # @return [Float, nil] Penalty for allowing certificates with invalid chain.,Allowed values are 0-5.,Default value when not specified in API or module is interpreted by Avi Controller as 1.0.\n attribute :hs_security_chain_invalidity_penalty\n validates :hs_security_chain_invalidity_penalty, type: Float\n\n # @return [Float, nil] Score assigned when the minimum cipher strength is 0 bits.,Allowed values are 0-5.,Default value when not specified in API or module is interpreted by Avi Controller as 0.0.\n attribute :hs_security_cipherscore_eq000b\n validates :hs_security_cipherscore_eq000b, type: Float\n\n # @return [Float, nil] Score assigned when the minimum cipher strength is greater than equal to 128 bits.,Allowed values are 0-5.,Default value when not specified in API or module is interpreted by Avi Controller as 5.0.\n attribute :hs_security_cipherscore_ge128b\n validates :hs_security_cipherscore_ge128b, type: Float\n\n # @return [Float, nil] Score assigned when the minimum cipher strength is less than 128 bits.,Allowed values are 0-5.,Default value when not specified in API or module is interpreted by Avi Controller as 3.5.\n attribute :hs_security_cipherscore_lt128b\n validates :hs_security_cipherscore_lt128b, type: Float\n\n # @return [Float, nil] Score assigned when no algorithm is used for encryption.,Allowed values are 0-5.,Default value when not specified in API or module is interpreted by Avi Controller as 0.0.\n attribute :hs_security_encalgo_score_none\n validates :hs_security_encalgo_score_none, type: Float\n\n # @return [Float, nil] Score assigned when rc4 algorithm is used for encryption.,Allowed values are 0-5.,Default value when not specified in API or module is interpreted by Avi Controller as 2.5.\n attribute :hs_security_encalgo_score_rc4\n validates :hs_security_encalgo_score_rc4, type: Float\n\n # @return [Float, nil] Penalty for not enabling hsts.,Allowed values are 0-5.,Default value when not specified in API or module is interpreted by Avi Controller as 1.0.\n attribute :hs_security_hsts_penalty\n validates :hs_security_hsts_penalty, type: Float\n\n # @return [Float, nil] Penalty for allowing non-pfs handshakes.,Allowed values are 0-5.,Default value when not specified in API or module is interpreted by Avi Controller as 1.0.\n attribute :hs_security_nonpfs_penalty\n validates :hs_security_nonpfs_penalty, type: Float\n\n # @return [Float, nil] Deprecated.,Allowed values are 0-5.,Default value when not specified in API or module is interpreted by Avi Controller as 1.0.\n attribute :hs_security_selfsignedcert_penalty\n validates :hs_security_selfsignedcert_penalty, type: Float\n\n # @return [Float, nil] Score assigned when supporting ssl3.0 encryption protocol.,Allowed values are 0-5.,Default value when not specified in API or module is interpreted by Avi Controller as 3.5.\n attribute :hs_security_ssl30_score\n validates :hs_security_ssl30_score, type: Float\n\n # @return [Float, nil] Score assigned when supporting tls1.0 encryption protocol.,Allowed values are 0-5.,Default value when not specified in API or module is interpreted by Avi Controller as 5.0.\n attribute :hs_security_tls10_score\n validates :hs_security_tls10_score, type: Float\n\n # @return [Float, nil] Score assigned when supporting tls1.1 encryption protocol.,Allowed values are 0-5.,Default value when not specified in API or module is interpreted by Avi Controller as 5.0.\n attribute :hs_security_tls11_score\n validates :hs_security_tls11_score, type: Float\n\n # @return [Float, nil] Score assigned when supporting tls1.2 encryption protocol.,Allowed values are 0-5.,Default value when not specified in API or module is interpreted by Avi Controller as 5.0.\n attribute :hs_security_tls12_score\n validates :hs_security_tls12_score, type: Float\n\n # @return [Float, nil] Penalty for allowing weak signature algorithm(s).,Allowed values are 0-5.,Default value when not specified in API or module is interpreted by Avi Controller as 1.0.\n attribute :hs_security_weak_signature_algo_penalty\n validates :hs_security_weak_signature_algo_penalty, type: Float\n\n # @return [String] The name of the analytics profile.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] List of http status code ranges to be excluded from being classified as an error.\n attribute :ranges\n\n # @return [Object, nil] Block of http response codes to be excluded from being classified as an error.,Enum options - AP_HTTP_RSP_4XX, AP_HTTP_RSP_5XX.\n attribute :resp_code_block\n\n # @return [String, nil] It is a reference to an object of type tenant.\n attribute :tenant_ref\n validates :tenant_ref, type: String\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Uuid of the analytics profile.\n attribute :uuid\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6706124544143677, "alphanum_fraction": 0.6724137663841248, "avg_line_length": 49.467533111572266, "blob_id": "35cf28f6caa23063e0f307904f41668bfeb4e10a", "content_id": "1a82f0cfc0fc11ef9fa5b6e0cb3979b8e26578f9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3886, "license_type": "permissive", "max_line_length": 242, "num_lines": 77, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_cluster.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and remove clusters.\n class Cs_cluster < Base\n # @return [String] name of the cluster.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Name of the zone in which the cluster belongs to.,If not set, default zone is used.\n attribute :zone\n validates :zone, type: String\n\n # @return [Object, nil] Name of the pod in which the cluster belongs to.\n attribute :pod\n\n # @return [:CloudManaged, :ExternalManaged, nil] Type of the cluster.,Required if C(state=present)\n attribute :cluster_type\n validates :cluster_type, expression_inclusion: {:in=>[:CloudManaged, :ExternalManaged], :message=>\"%{value} needs to be :CloudManaged, :ExternalManaged\"}, allow_nil: true\n\n # @return [:KVM, :VMware, :BareMetal, :XenServer, :LXC, :HyperV, :UCS, :OVM, nil] Name the hypervisor to be used.,Required if C(state=present).\n attribute :hypervisor\n validates :hypervisor, expression_inclusion: {:in=>[:KVM, :VMware, :BareMetal, :XenServer, :LXC, :HyperV, :UCS, :OVM], :message=>\"%{value} needs to be :KVM, :VMware, :BareMetal, :XenServer, :LXC, :HyperV, :UCS, :OVM\"}, allow_nil: true\n\n # @return [Object, nil] URL for the cluster\n attribute :url\n\n # @return [Object, nil] Username for the cluster.\n attribute :username\n\n # @return [Object, nil] Password for the cluster.\n attribute :password\n\n # @return [Object, nil] Name of virtual switch used for guest traffic in the cluster.,This would override zone wide traffic label setting.\n attribute :guest_vswitch_name\n\n # @return [:vmwaresvs, :vmwaredvs, nil] Type of virtual switch used for guest traffic in the cluster.,Allowed values are, vmwaresvs (for VMware standard vSwitch) and vmwaredvs (for VMware distributed vSwitch)\n attribute :guest_vswitch_type\n validates :guest_vswitch_type, expression_inclusion: {:in=>[:vmwaresvs, :vmwaredvs], :message=>\"%{value} needs to be :vmwaresvs, :vmwaredvs\"}, allow_nil: true\n\n # @return [Object, nil] Name of virtual switch used for public traffic in the cluster.,This would override zone wide traffic label setting.\n attribute :public_vswitch_name\n\n # @return [:vmwaresvs, :vmwaredvs, nil] Type of virtual switch used for public traffic in the cluster.,Allowed values are, vmwaresvs (for VMware standard vSwitch) and vmwaredvs (for VMware distributed vSwitch)\n attribute :public_vswitch_type\n validates :public_vswitch_type, expression_inclusion: {:in=>[:vmwaresvs, :vmwaredvs], :message=>\"%{value} needs to be :vmwaresvs, :vmwaredvs\"}, allow_nil: true\n\n # @return [Object, nil] IP address of the VSM associated with this cluster.\n attribute :vms_ip_address\n\n # @return [Object, nil] Username for the VSM associated with this cluster.\n attribute :vms_username\n\n # @return [Object, nil] Password for the VSM associated with this cluster.\n attribute :vms_password\n\n # @return [Object, nil] Ovm3 native OCFS2 clustering enabled for cluster.\n attribute :ovm3_cluster\n\n # @return [Object, nil] Ovm3 native pooling enabled for cluster.\n attribute :ovm3_pool\n\n # @return [Object, nil] Ovm3 vip to use for pool (and cluster).\n attribute :ovm3_vip\n\n # @return [:present, :absent, :disabled, :enabled, nil] State of the cluster.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :disabled, :enabled], :message=>\"%{value} needs to be :present, :absent, :disabled, :enabled\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.687609076499939, "alphanum_fraction": 0.687609076499939, "avg_line_length": 38.517242431640625, "blob_id": "3b2f83b7b75a6cfec7c7a955a19ab28b3f80f674", "content_id": "30ca264ad96774f1810ca3b9e18877004f6715b6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1146, "license_type": "permissive", "max_line_length": 143, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/cloudfront_origin_access_identity.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows for easy creation, updating and deletion of origin access identities.\n class Cloudfront_origin_access_identity < Base\n # @return [:present, :absent, nil] If the named resource should exist.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] The origin_access_identity_id of the cloudfront distribution.\n attribute :origin_access_identity_id\n validates :origin_access_identity_id, type: String\n\n # @return [String, nil] A comment to describe the cloudfront origin access identity.\n attribute :comment\n validates :comment, type: String\n\n # @return [String, nil] A unique identifier to reference the origin access identity by.\n attribute :caller_reference\n validates :caller_reference, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6739457845687866, "alphanum_fraction": 0.6739457845687866, "avg_line_length": 44.7931022644043, "blob_id": "b383db14a880b7b0b5f455c992d0e321e48397fe", "content_id": "bb1942cc82924d2c1687b0360886df8a17f1d958", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1328, "license_type": "permissive", "max_line_length": 160, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_aep.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Connect to external virtual and physical domains by using attachable Access Entity Profiles (AEP) on Cisco ACI fabrics.\n class Aci_aep < Base\n # @return [String] The name of the Attachable Access Entity Profile.\n attribute :aep\n validates :aep, presence: true, type: String\n\n # @return [String, nil] Description for the AEP.\n attribute :description\n validates :description, type: String\n\n # @return [:yes, :no, nil] Enable infrastructure VLAN.,The hypervisor functions of the AEP.,C(no) will disable the infrastructure vlan if it is enabled.\n attribute :infra_vlan\n validates :infra_vlan, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6997690796852112, "alphanum_fraction": 0.7026559114456177, "avg_line_length": 49.94117736816406, "blob_id": "818a6e2e52f7b46d43684b2865cfec6ab46542da", "content_id": "c8cc3e61c27d1f4441ce412341e9d0e1835dec2d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1732, "license_type": "permissive", "max_line_length": 194, "num_lines": 34, "path": "/lib/ansible/ruby/modules/generated/windows/win_domain.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Ensure that the domain named by C(dns_domain_name) exists and is reachable.\n # If the domain is not reachable, the domain is created in a new forest on the target Windows Server 2012R2+ host.\n # This module may require subsequent use of the M(win_reboot) action if changes are made.\n class Win_domain < Base\n # @return [String] The DNS name of the domain which should exist and be reachable or reside on the target Windows host.\n attribute :dns_domain_name\n validates :dns_domain_name, presence: true, type: String\n\n # @return [Object, nil] The netbios name of the domain.,If not set, then the default netbios name will be the first section of dns_domain_name, up to, but not including the first period.\n attribute :domain_netbios_name\n\n # @return [String] Safe mode password for the domain controller.\n attribute :safe_mode_password\n validates :safe_mode_password, presence: true, type: String\n\n # @return [String, nil] The path to a directory on a fixed disk of the Windows host where the domain database will be created.,If not set then the default path is C(%SYSTEMROOT%\\NTDS).\n attribute :database_path\n validates :database_path, type: String\n\n # @return [String, nil] The path to a directory on a fixed disk of the Windows host where the Sysvol file will be created.,If not set then the default path is C(%SYSTEMROOT%\\SYSVOL).\n attribute :sysvol_path\n validates :sysvol_path, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6596638560295105, "alphanum_fraction": 0.6632652878761292, "avg_line_length": 51.0625, "blob_id": "eaf3c86c53afd63485175dc5110fd3a1d71253d7", "content_id": "377d9c4ef19e7d4e5db8ae0f002bf8242ab33fba", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1666, "license_type": "permissive", "max_line_length": 258, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/cloud/univention/udm_dns_record.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows to manage dns records on a univention corporate server (UCS). It uses the python API of the UCS to create a new object or edit it.\n class Udm_dns_record < Base\n # @return [:present, :absent, nil] Whether the dns record is present or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] Name of the record, this is also the DNS record. E.g. www for www.example.com.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] Corresponding DNS zone for this record, e.g. example.com.\n attribute :zone\n validates :zone, presence: true, type: String\n\n # @return [:host_record, :alias, :ptr_record, :srv_record, :txt_record] Define the record type. C(host_record) is a A or AAAA record, C(alias) is a CNAME, C(ptr_record) is a PTR record, C(srv_record) is a SRV record and C(txt_record) is a TXT record.\n attribute :type\n validates :type, presence: true, expression_inclusion: {:in=>[:host_record, :alias, :ptr_record, :srv_record, :txt_record], :message=>\"%{value} needs to be :host_record, :alias, :ptr_record, :srv_record, :txt_record\"}\n\n # @return [Object, nil] Additional data for this record, e.g. ['a': '192.0.2.1']. Required if C(state=present).\n attribute :data\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6397334337234497, "alphanum_fraction": 0.6534777283668518, "avg_line_length": 47.50505065917969, "blob_id": "1093c5b4a7261f641173ded34ada82f09ed988a7", "content_id": "75d0d6cf0b6c6c48e5c6f3310ab2f3fa134c0c0d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4802, "license_type": "permissive", "max_line_length": 238, "num_lines": 99, "path": "/lib/ansible/ruby/modules/generated/network/netvisor/pn_trunk.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Execute trunk-create or trunk-delete command.\n # Trunks can be used to aggregate network links at Layer 2 on the local switch. Use this command to create a new trunk.\n class Pn_trunk < Base\n # @return [Object, nil] Provide login username if user is not root.\n attribute :pn_cliusername\n\n # @return [Object, nil] Provide login password if user is not root.\n attribute :pn_clipassword\n\n # @return [Object, nil] Target switch(es) to run the cli on.\n attribute :pn_cliswitch\n\n # @return [:present, :absent, :update] State the action to perform. Use 'present' to create trunk, 'absent' to delete trunk and 'update' to modify trunk.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent, :update], :message=>\"%{value} needs to be :present, :absent, :update\"}\n\n # @return [String] Specify the name for the trunk configuration.\n attribute :pn_name\n validates :pn_name, presence: true, type: String\n\n # @return [Array<Integer>, Integer, nil] Specify the port number(s) for the link(s) to aggregate into the trunk.,Required for trunk-create.\n attribute :pn_ports\n validates :pn_ports, type: TypeGeneric.new(Integer)\n\n # @return [:disable, :\"10m\", :\"100m\", :\"1g\", :\"2.5g\", :\"10g\", :\"40g\", nil] Specify the port speed or disable the port.\n attribute :pn_speed\n validates :pn_speed, expression_inclusion: {:in=>[:disable, :\"10m\", :\"100m\", :\"1g\", :\"2.5g\", :\"10g\", :\"40g\"], :message=>\"%{value} needs to be :disable, :\\\"10m\\\", :\\\"100m\\\", :\\\"1g\\\", :\\\"2.5g\\\", :\\\"10g\\\", :\\\"40g\\\"\"}, allow_nil: true\n\n # @return [Object, nil] Specify an egress port data rate limit for the configuration.\n attribute :pn_egress_rate_limit\n\n # @return [Object, nil] Specify if the port can receive jumbo frames.\n attribute :pn_jumbo\n\n # @return [:off, :passive, :active, nil] Specify the LACP mode for the configuration.\n attribute :pn_lacp_mode\n validates :pn_lacp_mode, expression_inclusion: {:in=>[:off, :passive, :active], :message=>\"%{value} needs to be :off, :passive, :active\"}, allow_nil: true\n\n # @return [Object, nil] Specify the LACP priority. This is a number between 1 and 65535 with a default value of 32768.\n attribute :pn_lacp_priority\n\n # @return [:slow, :fast, nil] Specify the LACP time out as slow (30 seconds) or fast (4seconds). The default value is slow.\n attribute :pn_lacp_timeout\n validates :pn_lacp_timeout, expression_inclusion: {:in=>[:slow, :fast], :message=>\"%{value} needs to be :slow, :fast\"}, allow_nil: true\n\n # @return [:bundle, :individual, nil] Specify the LACP fallback mode as bundles or individual.\n attribute :pn_lacp_fallback\n validates :pn_lacp_fallback, expression_inclusion: {:in=>[:bundle, :individual], :message=>\"%{value} needs to be :bundle, :individual\"}, allow_nil: true\n\n # @return [Object, nil] Specify the LACP fallback timeout in seconds. The range is between 30 and 60 seconds with a default value of 50 seconds.\n attribute :pn_lacp_fallback_timeout\n\n # @return [Object, nil] Specify if the switch is an edge switch.\n attribute :pn_edge_switch\n\n # @return [Object, nil] Specify if pause frames are sent.\n attribute :pn_pause\n\n # @return [Object, nil] Specify a description for the trunk configuration.\n attribute :pn_description\n\n # @return [Object, nil] Specify loopback if you want to use loopback.\n attribute :pn_loopback\n\n # @return [Object, nil] Specify if the configuration receives mirrored traffic.\n attribute :pn_mirror_receive\n\n # @return [Object, nil] Specify an unknown unicast level in percent. The default value is 100%.\n attribute :pn_unknown_ucast_level\n\n # @return [Object, nil] Specify an unknown multicast level in percent. The default value is 100%.\n attribute :pn_unknown_mcast_level\n\n # @return [Object, nil] Specify a broadcast level in percent. The default value is 100%.\n attribute :pn_broadcast_level\n\n # @return [Object, nil] Specify the MAC address of the port.\n attribute :pn_port_macaddr\n\n # @return [Object, nil] Specify a list of looping vlans.\n attribute :pn_loopvlans\n\n # @return [Object, nil] Specify if the port participates in routing on the network.\n attribute :pn_routing\n\n # @return [Object, nil] Host facing port control setting.\n attribute :pn_host\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6379517912864685, "alphanum_fraction": 0.6379517912864685, "avg_line_length": 35.88888931274414, "blob_id": "26169e6869cbd6539d171307c58331fe68671678", "content_id": "0e5da550bcf4fae284b244e4c60eaffd09f3303e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1660, "license_type": "permissive", "max_line_length": 143, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_network_acl.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create and remove network ACLs.\n class Cs_network_acl < Base\n # @return [String] Name of the network ACL.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Description of the network ACL.,If not set, identical to C(name).\n attribute :description\n validates :description, type: String\n\n # @return [String] VPC the network ACL is related to.\n attribute :vpc\n validates :vpc, presence: true, type: String\n\n # @return [:present, :absent, nil] State of the network ACL.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Domain the network ACL rule is related to.\n attribute :domain\n\n # @return [Object, nil] Account the network ACL rule is related to.\n attribute :account\n\n # @return [Object, nil] Name of the project the network ACL is related to.\n attribute :project\n\n # @return [Object, nil] Name of the zone the VPC is related to.,If not set, default zone is used.\n attribute :zone\n\n # @return [:yes, :no, nil] Poll async jobs until job has finished.\n attribute :poll_async\n validates :poll_async, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6692667603492737, "alphanum_fraction": 0.6692667603492737, "avg_line_length": 29.5238094329834, "blob_id": "9fecec9c1610ede3b85ff1307d7d947746f5609d", "content_id": "519854477d76c878f92605c376ffcae5bb6ab51a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 641, "license_type": "permissive", "max_line_length": 97, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/ansible_tower/tower_settings.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Get, Modify Ansible Tower settings. See U(https://www.ansible.com/tower) for an overview.\n class Tower_settings < Base\n # @return [String, nil] Name of setting to get/modify\n attribute :name\n validates :name, type: String\n\n # @return [Array<String>, String, nil] Value to be modified for given setting.\n attribute :value\n validates :value, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6843792796134949, "alphanum_fraction": 0.6843792796134949, "avg_line_length": 52.24390411376953, "blob_id": "bdb77732899b71a1f6a3e89692389371766abcc0", "content_id": "7bc7cbe37d51f560356b7fa8538008bc67fb283c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2183, "license_type": "permissive", "max_line_length": 321, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/remote_management/manageiq/manageiq_alerts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The manageiq_alerts module supports adding, updating and deleting alerts in ManageIQ.\n class Manageiq_alerts < Base\n # @return [:absent, :present, nil] absent - alert should not exist,,present - alert should exist,\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] The unique alert description in ManageIQ.,Required when state is \"absent\" or \"present\".\n attribute :description\n validates :description, type: String\n\n # @return [:Vm, :ContainerNode, :MiqServer, :Host, :Storage, :EmsCluster, :ExtManagementSystem, :MiddlewareServer, nil] The entity type for the alert in ManageIQ. Required when state is \"present\".\n attribute :resource_type\n validates :resource_type, expression_inclusion: {:in=>[:Vm, :ContainerNode, :MiqServer, :Host, :Storage, :EmsCluster, :ExtManagementSystem, :MiddlewareServer], :message=>\"%{value} needs to be :Vm, :ContainerNode, :MiqServer, :Host, :Storage, :EmsCluster, :ExtManagementSystem, :MiddlewareServer\"}, allow_nil: true\n\n # @return [:hash, :miq, nil] Expression type.\n attribute :expression_type\n validates :expression_type, expression_inclusion: {:in=>[:hash, :miq], :message=>\"%{value} needs to be :hash, :miq\"}, allow_nil: true\n\n # @return [Hash, nil] The alert expression for ManageIQ.,Can either be in the \"Miq Expression\" format or the \"Hash Expression format\".,Required if state is \"present\".\n attribute :expression\n validates :expression, type: Hash\n\n # @return [Symbol, nil] Enable or disable the alert. Required if state is \"present\".\n attribute :enabled\n validates :enabled, type: Symbol\n\n # @return [Hash, nil] Additional alert options, such as notification type and frequency\n attribute :options\n validates :options, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7143231630325317, "alphanum_fraction": 0.7169464826583862, "avg_line_length": 68.30908966064453, "blob_id": "0c24a53047b8f86e760ea25d524d0d204c6ee4af", "content_id": "404fc0d45ab49c23adaae3a0853f8e018f59101f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3812, "license_type": "permissive", "max_line_length": 515, "num_lines": 55, "path": "/lib/ansible/ruby/modules/generated/database/proxysql/proxysql_backend_servers.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The M(proxysql_backend_servers) module adds or removes mysql hosts using the proxysql admin interface.\n class Proxysql_backend_servers < Base\n # @return [Integer, nil] The hostgroup in which this mysqld instance is included. An instance can be part of one or more hostgroups.\n attribute :hostgroup_id\n validates :hostgroup_id, type: Integer\n\n # @return [String] The ip address at which the mysqld instance can be contacted.\n attribute :hostname\n validates :hostname, presence: true, type: String\n\n # @return [Integer, nil] The port at which the mysqld instance can be contacted.\n attribute :port\n validates :port, type: Integer\n\n # @return [:ONLINE, :OFFLINE_SOFT, :OFFLINE_HARD, nil] ONLINE - Backend server is fully operational. OFFLINE_SOFT - When a server is put into C(OFFLINE_SOFT) mode, connections are kept in use until the current transaction is completed. This allows to gracefully detach a backend. OFFLINE_HARD - When a server is put into C(OFFLINE_HARD) mode, the existing connections are dropped, while new incoming connections aren't accepted either.\\r\\nIf omitted the proxysql database default for I(status) is C(ONLINE).\n attribute :status\n validates :status, expression_inclusion: {:in=>[:ONLINE, :OFFLINE_SOFT, :OFFLINE_HARD], :message=>\"%{value} needs to be :ONLINE, :OFFLINE_SOFT, :OFFLINE_HARD\"}, allow_nil: true\n\n # @return [Object, nil] The bigger the weight of a server relative to other weights, the higher the probability of the server being chosen from the hostgroup. If omitted the proxysql database default for I(weight) is 1.\n attribute :weight\n\n # @return [Object, nil] If the value of I(compression) is greater than 0, new connections to that server will use compression. If omitted the proxysql database default for I(compression) is 0.\n attribute :compression\n\n # @return [Object, nil] The maximum number of connections ProxySQL will open to this backend server. If omitted the proxysql database default for I(max_connections) is 1000.\n attribute :max_connections\n\n # @return [Object, nil] If greater than 0, ProxySQL will reguarly monitor replication lag. If replication lag goes above I(max_replication_lag), proxysql will temporarily shun the server until replication catches up. If omitted the proxysql database default for I(max_replication_lag) is 0.\n attribute :max_replication_lag\n\n # @return [Object, nil] If I(use_ssl) is set to C(True), connections to this server will be made using SSL connections. If omitted the proxysql database default for I(use_ssl) is C(False).\n attribute :use_ssl\n\n # @return [Object, nil] Ping time is monitored regularly. If a host has a ping time greater than I(max_latency_ms) it is excluded from the connection pool (although the server stays ONLINE). If omitted the proxysql database default for I(max_latency_ms) is 0.\n attribute :max_latency_ms\n\n # @return [String, nil] Text field that can be used for any purposed defined by the user. Could be a description of what the host stores, a reminder of when the host was added or disabled, or a JSON processed by some checker script.\n attribute :comment\n validates :comment, type: String\n\n # @return [:present, :absent, nil] When C(present) - adds the host, when C(absent) - removes the host.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6670339107513428, "alphanum_fraction": 0.6674746870994568, "avg_line_length": 62.02777862548828, "blob_id": "95e9d6658d44089579be5cc9595c609209c954bc", "content_id": "24e12f2bcab9d589803b0ef9dd4e748eed4a9ea6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4538, "license_type": "permissive", "max_line_length": 898, "num_lines": 72, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_metric_alarm.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Can create or delete AWS metric alarms.\n # Metrics you wish to alarm on must already exist.\n class Ec2_metric_alarm < Base\n # @return [:present, :absent] register or deregister the alarm\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String] Unique name for the alarm\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Name of the monitored metric (e.g. CPUUtilization),Metric must already exist\n attribute :metric\n validates :metric, type: String\n\n # @return [String, nil] Name of the appropriate namespace ('AWS/EC2', 'System/Linux', etc.), which determines the category it will appear under in cloudwatch\n attribute :namespace\n validates :namespace, type: String\n\n # @return [:SampleCount, :Average, :Sum, :Minimum, :Maximum, nil] Operation applied to the metric,Works in conjunction with period and evaluation_periods to determine the comparison value\n attribute :statistic\n validates :statistic, expression_inclusion: {:in=>[:SampleCount, :Average, :Sum, :Minimum, :Maximum], :message=>\"%{value} needs to be :SampleCount, :Average, :Sum, :Minimum, :Maximum\"}, allow_nil: true\n\n # @return [:<=, :<, :>, :>=, nil] Determines how the threshold value is compared\n attribute :comparison\n validates :comparison, expression_inclusion: {:in=>[:<=, :<, :>, :>=], :message=>\"%{value} needs to be :<=, :<, :>, :>=\"}, allow_nil: true\n\n # @return [Float, nil] Sets the min/max bound for triggering the alarm\n attribute :threshold\n validates :threshold, type: Float\n\n # @return [Integer, nil] The time (in seconds) between metric evaluations\n attribute :period\n validates :period, type: Integer\n\n # @return [Integer, nil] The number of times in which the metric is evaluated before final calculation\n attribute :evaluation_periods\n validates :evaluation_periods, type: Integer\n\n # @return [:Seconds, :Microseconds, :Milliseconds, :Bytes, :Kilobytes, :Megabytes, :Gigabytes, :Terabytes, :Bits, :Kilobits, :Megabits, :Gigabits, :Terabits, :Percent, :Count, :\"Bytes/Second\", :\"Kilobytes/Second\", :\"Megabytes/Second\", :\"Gigabytes/Second\", :\"Terabytes/Second\", :\"Bits/Second\", :\"Kilobits/Second\", :\"Megabits/Second\", :\"Gigabits/Second\", :\"Terabits/Second\", :\"Count/Second\", :None, nil] The threshold's unit of measurement\n attribute :unit\n validates :unit, expression_inclusion: {:in=>[:Seconds, :Microseconds, :Milliseconds, :Bytes, :Kilobytes, :Megabytes, :Gigabytes, :Terabytes, :Bits, :Kilobits, :Megabits, :Gigabits, :Terabits, :Percent, :Count, :\"Bytes/Second\", :\"Kilobytes/Second\", :\"Megabytes/Second\", :\"Gigabytes/Second\", :\"Terabytes/Second\", :\"Bits/Second\", :\"Kilobits/Second\", :\"Megabits/Second\", :\"Gigabits/Second\", :\"Terabits/Second\", :\"Count/Second\", :None], :message=>\"%{value} needs to be :Seconds, :Microseconds, :Milliseconds, :Bytes, :Kilobytes, :Megabytes, :Gigabytes, :Terabytes, :Bits, :Kilobits, :Megabits, :Gigabits, :Terabits, :Percent, :Count, :\\\"Bytes/Second\\\", :\\\"Kilobytes/Second\\\", :\\\"Megabytes/Second\\\", :\\\"Gigabytes/Second\\\", :\\\"Terabytes/Second\\\", :\\\"Bits/Second\\\", :\\\"Kilobits/Second\\\", :\\\"Megabits/Second\\\", :\\\"Gigabits/Second\\\", :\\\"Terabits/Second\\\", :\\\"Count/Second\\\", :None\"}, allow_nil: true\n\n # @return [String, nil] A longer description of the alarm\n attribute :description\n validates :description, type: String\n\n # @return [Hash, nil] Describes to what the alarm is applied\n attribute :dimensions\n validates :dimensions, type: Hash\n\n # @return [Array<String>, String, nil] A list of the names action(s) taken when the alarm is in the 'alarm' status\n attribute :alarm_actions\n validates :alarm_actions, type: TypeGeneric.new(String)\n\n # @return [Object, nil] A list of the names of action(s) to take when the alarm is in the 'insufficient_data' status\n attribute :insufficient_data_actions\n\n # @return [Object, nil] A list of the names of action(s) to take when the alarm is in the 'ok' status\n attribute :ok_actions\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6631578803062439, "alphanum_fraction": 0.6885964870452881, "avg_line_length": 39.71428680419922, "blob_id": "a4a34e41a2a55db533c74985bbfdc8fe826cf280", "content_id": "e92e754a94d8c7270daada57c5490fc6243440cf", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1140, "license_type": "permissive", "max_line_length": 242, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/notification/hall.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The C(hall) module connects to the U(https://hall.com) messaging API and allows you to deliver notication messages to rooms.\n class Hall < Base\n # @return [String] Room token provided to you by setting up the Ansible room integation on U(https://hall.com)\n attribute :room_token\n validates :room_token, presence: true, type: String\n\n # @return [String] The message you wish to deliver as a notification\n attribute :msg\n validates :msg, presence: true, type: String\n\n # @return [String] The title of the message\n attribute :title\n validates :title, presence: true, type: String\n\n # @return [Object, nil] The full URL to the image you wish to use for the Icon of the message. Defaults to U(http://cdn2.hubspot.net/hub/330046/file-769078210-png/Official_Logos/ansible_logo_black_square_small.png?t=1421076128627)\\r\\n\n attribute :picture\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.699205756187439, "alphanum_fraction": 0.699205756187439, "avg_line_length": 57.25373077392578, "blob_id": "8930af06345b5fa69cd683423b6a2a159561b2d9", "content_id": "6e96e076f77f42dd2b85dc644623dad2cc5360e7", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3903, "license_type": "permissive", "max_line_length": 265, "num_lines": 67, "path": "/lib/ansible/ruby/modules/generated/network/radware/vdirect_runnable.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Runs configuration templates, creates workflows and runs workflow actions in Radware vDirect server.\n class Vdirect_runnable < Base\n # @return [String] Primary vDirect server IP address, may be set as C(VDIRECT_IP) environment variable.\n attribute :vdirect_ip\n validates :vdirect_ip, presence: true, type: String\n\n # @return [String] vDirect server username, may be set as C(VDIRECT_USER) environment variable.\n attribute :vdirect_user\n validates :vdirect_user, presence: true, type: String\n\n # @return [String] vDirect server password, may be set as C(VDIRECT_PASSWORD) environment variable.\n attribute :vdirect_password\n validates :vdirect_password, presence: true, type: String\n\n # @return [Object, nil] Secondary vDirect server IP address, may be set as C(VDIRECT_SECONDARY_IP) environment variable.\n attribute :vdirect_secondary_ip\n\n # @return [:yes, :no, nil] Wait for async operation to complete, may be set as C(VDIRECT_WAIT) environment variable.\n attribute :vdirect_wait\n validates :vdirect_wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] vDirect server HTTPS port number, may be set as C(VDIRECT_HTTPS_PORT) environment variable.\n attribute :vdirect_https_port\n validates :vdirect_https_port, type: Integer\n\n # @return [Integer, nil] vDirect server HTTP port number, may be set as C(VDIRECT_HTTP_PORT) environment variable.\n attribute :vdirect_http_port\n validates :vdirect_http_port, type: Integer\n\n # @return [Integer, nil] Amount of time to wait for async operation completion [seconds],,may be set as C(VDIRECT_TIMEOUT) environment variable.\n attribute :vdirect_timeout\n validates :vdirect_timeout, type: Integer\n\n # @return [:yes, :no, nil] If C(no), an HTTP connection will be used instead of the default HTTPS connection,,may be set as C(VDIRECT_HTTPS) or C(VDIRECT_USE_SSL) environment variable.\n attribute :vdirect_use_ssl\n validates :vdirect_use_ssl, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated,,may be set as C(VDIRECT_VALIDATE_CERTS) or C(VDIRECT_VERIFY) environment variable.,This should only set to C(no) used on personally controlled sites using self-signed certificates.\n attribute :vdirect_validate_certs\n validates :vdirect_validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:ConfigurationTemplate, :Workflow, :WorkflowTemplate] vDirect runnable type.\n attribute :runnable_type\n validates :runnable_type, presence: true, expression_inclusion: {:in=>[:ConfigurationTemplate, :Workflow, :WorkflowTemplate], :message=>\"%{value} needs to be :ConfigurationTemplate, :Workflow, :WorkflowTemplate\"}\n\n # @return [String] vDirect runnable name to run.,May be configuration template name, workflow template name or workflow instance name.\n attribute :runnable_name\n validates :runnable_name, presence: true, type: String\n\n # @return [Object, nil] Workflow action name to run.,Required if I(runnable_type=Workflow).\n attribute :action_name\n\n # @return [Hash, nil] Action parameters dictionary. In case of C(ConfigurationTemplate) runnable type,,the device connection details should always be passed as a parameter.\n attribute :parameters\n validates :parameters, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6636455059051514, "alphanum_fraction": 0.6636455059051514, "avg_line_length": 38.720001220703125, "blob_id": "077381ae32505b73e2c96a750e9357072adc67a5", "content_id": "c8e631c25b25c1186c9d67a38b335766135ae01b", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 993, "license_type": "permissive", "max_line_length": 153, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_iscsi.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # create, delete, start, stop iSCSI service on SVM.\n class Na_ontap_iscsi < Base\n # @return [:present, :absent, nil] Whether the service should be present or deleted.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:started, :stopped, nil] Whether the specified service should running .\n attribute :service_state\n validates :service_state, expression_inclusion: {:in=>[:started, :stopped], :message=>\"%{value} needs to be :started, :stopped\"}, allow_nil: true\n\n # @return [String] The name of the vserver to use.\n attribute :vserver\n validates :vserver, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7012259364128113, "alphanum_fraction": 0.7015761733055115, "avg_line_length": 58.47916793823242, "blob_id": "9716fadb6066e514989486d93d49f556d849d200", "content_id": "01c3ed699c054c034624e1d569e2a7471e99e6ec", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2855, "license_type": "permissive", "max_line_length": 282, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_selfip.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage Self-IPs on a BIG-IP system.\n class Bigip_selfip < Base\n # @return [String, nil] The IP addresses for the new self IP. This value is ignored upon update as addresses themselves cannot be changed after they are created.,This value is required when creating new self IPs.\n attribute :address\n validates :address, type: String\n\n # @return [Array<String>, String, nil] Configure port lockdown for the Self IP. By default, the Self IP has a \"default deny\" policy. This can be changed to allow TCP and UDP ports as well as specific protocols. This list should contain C(protocol):C(port) values.\n attribute :allow_service\n validates :allow_service, type: TypeGeneric.new(String)\n\n # @return [String] The self IP to create.,If this parameter is not specified, then it will default to the value supplied in the C(address) parameter.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The netmask for the self IP. When creating a new Self IP, this value is required.\n attribute :netmask\n validates :netmask, type: String\n\n # @return [:absent, :present, nil] When C(present), guarantees that the Self-IP exists with the provided attributes.,When C(absent), removes the Self-IP from the system.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [Object, nil] The traffic group for the Self IP addresses in an active-active, redundant load balancer configuration. When creating a new Self IP, if this value is not specified, the default of C(/Common/traffic-group-local-only) will be used.\n attribute :traffic_group\n\n # @return [String, nil] The VLAN that the new self IPs will be on. When creating a new Self IP, this value is required.\n attribute :vlan\n validates :vlan, type: String\n\n # @return [Integer, nil] The route domain id of the system. When creating a new Self IP, if this value is not specified, a default value of C(0) will be used.,This value cannot be changed after it is set.\n attribute :route_domain\n validates :route_domain, type: Integer\n\n # @return [String, nil] Device partition to manage resources on. You can set different partitions for Self IPs, but the address used may not match any other address used by a Self IP. In that sense, Self IPs are not isolated by partitions as other resources on a BIG-IP are.\n attribute :partition\n validates :partition, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6706827282905579, "alphanum_fraction": 0.6706827282905579, "avg_line_length": 37.90625, "blob_id": "036170805e3e1df13cb855623a1bf1565d348309", "content_id": "a4eb175527a94c35a2e236e3ad8f80d87e316649", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1245, "license_type": "permissive", "max_line_length": 143, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_routetable.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update or delete a route table.\n class Azure_rm_routetable < Base\n # @return [String] name of resource group.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] name of the route table.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, nil] Assert the state of the route table. Use 'present' to create or update and 'absent' to delete.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [Symbol, nil] Specified whether to disable the routes learned by BGP on that route table.\n attribute :disable_bgp_route_propagation\n validates :disable_bgp_route_propagation, type: Symbol\n\n # @return [Object, nil] Region of the resource.,Derived from C(resource_group) if not specified\n attribute :location\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6538313627243042, "alphanum_fraction": 0.6619176268577576, "avg_line_length": 50.939998626708984, "blob_id": "29e42b2351e891cb93c750585653bebdac8a6aaf", "content_id": "ddd8e15d4329112da5d6fbb6bcd2ad6be8bd0f64", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2597, "license_type": "permissive", "max_line_length": 450, "num_lines": 50, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_snmp_host.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages SNMP host configuration parameters.\n class Nxos_snmp_host < Base\n # @return [String] IP address of hostname of target host.\n attribute :snmp_host\n validates :snmp_host, presence: true, type: String\n\n # @return [:v1, :v2c, :v3, nil] SNMP version. If this is not specified, v1 is used.\n attribute :version\n validates :version, expression_inclusion: {:in=>[:v1, :v2c, :v3], :message=>\"%{value} needs to be :v1, :v2c, :v3\"}, allow_nil: true\n\n # @return [:noauth, :auth, :priv, nil] Use this when verion is v3. SNMPv3 Security level.\n attribute :v3\n validates :v3, expression_inclusion: {:in=>[:noauth, :auth, :priv], :message=>\"%{value} needs to be :noauth, :auth, :priv\"}, allow_nil: true\n\n # @return [String, nil] Community string or v3 username.\n attribute :community\n validates :community, type: String\n\n # @return [Integer, nil] UDP port number (0-65535).\n attribute :udp\n validates :udp, type: Integer\n\n # @return [:trap, :inform, nil] type of message to send to host. If this is not specified, trap type is used.\n attribute :snmp_type\n validates :snmp_type, expression_inclusion: {:in=>[:trap, :inform], :message=>\"%{value} needs to be :trap, :inform\"}, allow_nil: true\n\n # @return [Object, nil] VRF to use to source traffic to source. If state = absent, the vrf is removed.\n attribute :vrf\n\n # @return [Object, nil] Name of VRF to filter. If state = absent, the vrf is removed from the filter.\n attribute :vrf_filter\n\n # @return [Object, nil] Source interface. Must be fully qualified interface name. If state = absent, the interface is removed.\n attribute :src_intf\n\n # @return [:present, :absent, nil] Manage the state of the resource. If state = present, the host is added to the configuration. If only vrf and/or vrf_filter and/or src_intf are given, they will be added to the existing host configuration. If state = absent, the host is removed if community parameter is given. It is possible to remove only vrf and/or src_int and/or vrf_filter by providing only those parameters and no community parameter.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6540504693984985, "alphanum_fraction": 0.6540504693984985, "avg_line_length": 39.702701568603516, "blob_id": "9a6387580b44ee44b6d179e3a18190355109ce03", "content_id": "47f30d04f0576dcd126fa7406cbf61e79f64c7d4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1506, "license_type": "permissive", "max_line_length": 143, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/network/illumos/dladm_vnic.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or delete VNICs on Solaris/illumos systems.\n class Dladm_vnic < Base\n # @return [String] VNIC name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] VNIC underlying link name.\n attribute :link\n validates :link, presence: true, type: String\n\n # @return [Symbol, nil] Specifies that the VNIC is temporary. Temporary VNICs do not persist across reboots.\n attribute :temporary\n validates :temporary, type: Symbol\n\n # @return [Boolean, nil] Sets the VNIC's MAC address. Must be valid unicast MAC address.\n attribute :mac\n validates :mac, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Enable VLAN tagging for this VNIC. The VLAN tag will have id I(vlan).\n attribute :vlan\n validates :vlan, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Create or delete Solaris/illumos VNIC.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6698641180992126, "alphanum_fraction": 0.6698641180992126, "avg_line_length": 36.90909194946289, "blob_id": "2a2239584852e3381ea25e2c398aaa4c4cc220b9", "content_id": "1558d0b31b5b3e069246ae2f8308d3e82e295122", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1251, "license_type": "permissive", "max_line_length": 159, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/network/illumos/dladm_linkprop.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Set / reset link properties on Solaris/illumos systems.\n class Dladm_linkprop < Base\n # @return [Object] Link interface name.\n attribute :link\n validates :link, presence: true\n\n # @return [String] Specifies the name of the property we want to manage.\n attribute :property\n validates :property, presence: true, type: String\n\n # @return [String, nil] Specifies the value we want to set for the link property.\n attribute :value\n validates :value, type: String\n\n # @return [Symbol, nil] Specifies that lin property configuration is temporary. Temporary link property configuration does not persist across reboots.\n attribute :temporary\n validates :temporary, type: Symbol\n\n # @return [:present, :absent, :reset, nil] Set or reset the property value.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :reset], :message=>\"%{value} needs to be :present, :absent, :reset\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6410048604011536, "alphanum_fraction": 0.6790924072265625, "avg_line_length": 41.55172348022461, "blob_id": "f4de98ddcdc550964d8ad516533ec40a4fb005a9", "content_id": "695a3b8a0a6a7ff51deb381e06849de36bc6d8fc", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1234, "license_type": "permissive", "max_line_length": 211, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_mtu.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages MTU settings on HUAWEI CloudEngine switches.\n class Ce_mtu < Base\n # @return [Object, nil] Full name of interface, i.e. 40GE1/0/22.\n attribute :interface\n\n # @return [Object, nil] MTU for a specific interface. The value is an integer ranging from 46 to 9600, in bytes.\n attribute :mtu\n\n # @return [Object, nil] Maximum frame size. The default value is 9216. The value is an integer and expressed in bytes. The value range is 1536 to 12224 for the CE12800 and 1536 to 12288 for ToR switches.\n attribute :jumbo_max\n\n # @return [Object, nil] Non-jumbo frame size threshod. The default value is 1518. The value is an integer that ranges from 1518 to jumbo_max, in bytes.\n attribute :jumbo_min\n\n # @return [:present, :absent, nil] Specify desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.706131100654602, "alphanum_fraction": 0.7251585721969604, "avg_line_length": 25.27777862548828, "blob_id": "7c6300d48ecde413278b3a27b1029d1dec896c57", "content_id": "3e15cac12bace0645a42c609183eff7d16438cd9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 473, "license_type": "permissive", "max_line_length": 66, "num_lines": 18, "path": "/lib/ansible/ruby/modules/custom/net_tools/basics/uri.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# VALIDATED_CHECKSUM: FxhniNgW1GXxUXF6XTrMY60VgePavi9dDL58W3CF8Tw=\n\nrequire 'ansible/ruby/modules/generated/net_tools/basics/uri'\n\nmodule Ansible\n module Ruby\n module Modules\n class Uri\n remove_existing_validations :body\n # Only picked up a single Integer in the generated class\n remove_existing_validations :status_code\n validates :status_code, type: TypeGeneric.new(Integer)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5731707215309143, "alphanum_fraction": 0.6250782012939453, "avg_line_length": 56.10714340209961, "blob_id": "e6a259fe1dc350c7569beb84e06a4133e8580171", "content_id": "ab275e5e0b7081dfdd4a09249d14ba839bda7aaa", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3198, "license_type": "permissive", "max_line_length": 608, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/cloud/scaleway/scaleway_compute.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module manages compute instances on Scaleway.\n class Scaleway_compute < Base\n # @return [Symbol, nil] Enable public IPv6 connectivity on the instance\n attribute :enable_ipv6\n validates :enable_ipv6, type: Symbol\n\n # @return [String] Image identifier used to start the instance with\n attribute :image\n validates :image, presence: true, type: String\n\n # @return [String, nil] Name of the instance\n attribute :name\n validates :name, type: String\n\n # @return [String] Organization identifier\n attribute :organization\n validates :organization, presence: true, type: String\n\n # @return [:present, :absent, :running, :restarted, :stopped, nil] Indicate desired state of the instance.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :running, :restarted, :stopped], :message=>\"%{value} needs to be :present, :absent, :running, :restarted, :stopped\"}, allow_nil: true\n\n # @return [Object, nil] List of tags to apply to the instance (5 max)\n attribute :tags\n\n # @return [:ams1, :\"EMEA-NL-EVS\", :par1, :\"EMEA-FR-PAR1\"] Scaleway compute zone\n attribute :region\n validates :region, presence: true, expression_inclusion: {:in=>[:ams1, :\"EMEA-NL-EVS\", :par1, :\"EMEA-FR-PAR1\"], :message=>\"%{value} needs to be :ams1, :\\\"EMEA-NL-EVS\\\", :par1, :\\\"EMEA-FR-PAR1\\\"\"}\n\n # @return [:\"ARM64-2GB\", :\"ARM64-4GB\", :\"ARM64-8GB\", :\"ARM64-16GB\", :\"ARM64-32GB\", :\"ARM64-64GB\", :\"ARM64-128GB\", :C1, :C2S, :C2M, :C2L, :\"START1-XS\", :\"START1-S\", :\"START1-M\", :\"START1-L\", :\"X64-15GB\", :\"X64-30GB\", :\"X64-60GB\", :\"X64-120GB\"] Commercial name of the compute node\n attribute :commercial_type\n validates :commercial_type, presence: true, expression_inclusion: {:in=>[:\"ARM64-2GB\", :\"ARM64-4GB\", :\"ARM64-8GB\", :\"ARM64-16GB\", :\"ARM64-32GB\", :\"ARM64-64GB\", :\"ARM64-128GB\", :C1, :C2S, :C2M, :C2L, :\"START1-XS\", :\"START1-S\", :\"START1-M\", :\"START1-L\", :\"X64-15GB\", :\"X64-30GB\", :\"X64-60GB\", :\"X64-120GB\"], :message=>\"%{value} needs to be :\\\"ARM64-2GB\\\", :\\\"ARM64-4GB\\\", :\\\"ARM64-8GB\\\", :\\\"ARM64-16GB\\\", :\\\"ARM64-32GB\\\", :\\\"ARM64-64GB\\\", :\\\"ARM64-128GB\\\", :C1, :C2S, :C2M, :C2L, :\\\"START1-XS\\\", :\\\"START1-S\\\", :\\\"START1-M\\\", :\\\"START1-L\\\", :\\\"X64-15GB\\\", :\\\"X64-30GB\\\", :\\\"X64-60GB\\\", :\\\"X64-120GB\\\"\"}\n\n # @return [:yes, :no, nil] Wait for the instance to reach its desired state before returning.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Time to wait for the server to reach the expected state\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [Integer, nil] Time to wait before every attempt to check the state of the server\n attribute :wait_sleep_time\n validates :wait_sleep_time, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7195537686347961, "alphanum_fraction": 0.7195537686347961, "avg_line_length": 64.85713958740234, "blob_id": "e5e7899f9b373e0be8e3121fd17108bf23467717", "content_id": "2586ecf0119347793caeaf312eee48165bb81808", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3227, "license_type": "permissive", "max_line_length": 312, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/network/junos/junos_vrf.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of VRF definitions on Juniper JUNOS devices. It allows playbooks to manage individual or the entire VRF collection.\n class Junos_vrf < Base\n # @return [String, nil] The name of the VRF definition to be managed on the remote IOS device. The VRF definition name is an ASCII string name used to uniquely identify the VRF. This argument is mutually exclusive with the C(aggregate) argument\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] Provides a short description of the VRF definition in the current active configuration. The VRF definition value accepts alphanumeric characters used to provide additional information about the VRF.\n attribute :description\n validates :description, type: String\n\n # @return [String, nil] The router-distinguisher value uniquely identifies the VRF to routing processes on the remote IOS system. The RD value takes the form of C(A:B) where C(A) and C(B) are both numeric values.\n attribute :rd\n validates :rd, type: String\n\n # @return [Array<String>, String, nil] Identifies the set of interfaces that should be configured in the VRF. Interfaces must be routed interfaces in order to be placed into a VRF.\n attribute :interfaces\n validates :interfaces, type: TypeGeneric.new(String)\n\n # @return [String, nil] It configures VRF target community configuration. The target value takes the form of C(target:A:B) where C(A) and C(B) are both numeric values.\n attribute :target\n validates :target, type: String\n\n # @return [Symbol, nil] Causes JUNOS to allocate a VPN label per VRF rather than per VPN FEC. This allows for forwarding of traffic to directly connected subnets, COS Egress filtering etc.\n attribute :table_label\n validates :table_label, type: Symbol\n\n # @return [Array<Hash>, Hash, nil] The set of VRF definition objects to be configured on the remote JUNOS device. Ths list entries can either be the VRF name or a hash of VRF definitions and attributes. This argument is mutually exclusive with the C(name) argument.\n attribute :aggregate\n validates :aggregate, type: TypeGeneric.new(Hash)\n\n # @return [:present, :absent, nil] Configures the state of the VRF definition as it relates to the device operational configuration. When set to I(present), the VRF should be configured in the device active configuration and when set to I(absent) the VRF should not be in the device active configuration\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Boolean, nil] Specifies whether or not the configuration is active or deactivated\n attribute :active\n validates :active, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6798387169837952, "alphanum_fraction": 0.6798387169837952, "avg_line_length": 41.75862121582031, "blob_id": "92bc9d0ad39adcedc796b2d186231cf531cdeb8c", "content_id": "9ec4c90eccdc9816206e226e9ea5f5466f7cfe99", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1240, "license_type": "permissive", "max_line_length": 213, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_keyvaultsecret.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or delete a secret within a given keyvault. By using Key Vault, you can encrypt keys and secrets (such as authentication keys, storage account keys, data encryption keys, .PFX files, and passwords).\n class Azure_rm_keyvaultsecret < Base\n # @return [String] URI of the keyvault endpoint.\n attribute :keyvault_uri\n validates :keyvault_uri, presence: true, type: String\n\n # @return [String] Name of the keyvault secret.\n attribute :secret_name\n validates :secret_name, presence: true, type: String\n\n # @return [String, nil] Secret to be secured by keyvault.\n attribute :secret_value\n validates :secret_value, type: String\n\n # @return [:absent, :present, nil] Assert the state of the subnet. Use 'present' to create or update a secret and 'absent' to delete a secret .\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6510215401649475, "alphanum_fraction": 0.6510215401649475, "avg_line_length": 47.945945739746094, "blob_id": "cf33d91882a2b19e8b7b6676f8973e84ba4a4491", "content_id": "7b68ed8429577a1a854e70a0c86b83dac4328d2b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1811, "license_type": "permissive", "max_line_length": 170, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/packaging/os/urpmi.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages packages with I(urpmi) (such as for Mageia or Mandriva)\n class Urpmi < Base\n # @return [String] A list of package names to install, upgrade or remove.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, nil] Indicates the desired package state.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Update the package database first C(urpmi.update -a).\n attribute :update_cache\n validates :update_cache, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Corresponds to the C(--no-recommends) option for I(urpmi).\n attribute :no_recommends, original_name: 'no-recommends'\n validates :no_recommends, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Assume \"yes\" is the answer to any question urpmi has to ask. Corresponds to the C(--force) option for I(urpmi).\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Specifies an alternative install root, relative to which all packages will be installed. Corresponds to the C(--root) option for I(urpmi).\n attribute :root\n validates :root, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6650698781013489, "alphanum_fraction": 0.6770458817481995, "avg_line_length": 50.1224479675293, "blob_id": "f9724cd5b24b2a23b0e12711c53917276134fb08", "content_id": "8f683a531ea7adb24d2562395e9bb2ebd178ffda", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2505, "license_type": "permissive", "max_line_length": 263, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/network/iosxr/iosxr_logging.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management configuration of system logging (syslog) on Cisco IOS XR devices.\n class Iosxr_logging < Base\n # @return [:host, :console, :monitor, :buffered, :file, nil] Destination for system logging (syslog) messages.\n attribute :dest\n validates :dest, expression_inclusion: {:in=>[:host, :console, :monitor, :buffered, :file], :message=>\"%{value} needs to be :host, :console, :monitor, :buffered, :file\"}, allow_nil: true\n\n # @return [String, nil] When C(dest) = I(file) name indicates file-name,When C(dest) = I(host) name indicates the host-name or ip-address of syslog server.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] vrf name when syslog server is configured, C(dest) = C(host)\n attribute :vrf\n validates :vrf, type: String\n\n # @return [Integer, nil] Size of buffer when C(dest) = C(buffered). The acceptable value is in the range I(307200 to 125000000 bytes). Default 307200,Size of file when C(dest) = C(file). The acceptable value is in the range I(1 to 2097152)KB. Default 2 GB\n attribute :size\n validates :size, type: Integer\n\n # @return [String, nil] To configure the type of syslog facility in which system logging (syslog) messages are sent to syslog servers Optional config for C(dest) = C(host)\n attribute :facility\n validates :facility, type: String\n\n # @return [String, nil] To append a hostname prefix to system logging (syslog) messages logged to syslog servers. Optional config for C(dest) = C(host)\n attribute :hostnameprefix\n validates :hostnameprefix, type: String\n\n # @return [String, nil] Specifies the severity level for the logging.\n attribute :level\n validates :level, type: String\n\n # @return [Array<Hash>, Hash, nil] List of syslog logging configuration definitions.\n attribute :aggregate\n validates :aggregate, type: TypeGeneric.new(Hash)\n\n # @return [:present, :absent, nil] Existential state of the logging configuration on the node.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6612179279327393, "alphanum_fraction": 0.6612179279327393, "avg_line_length": 68.33333587646484, "blob_id": "f2bf7265ed2096d981304f6af3f551e344e647ec", "content_id": "6831c80ca21753dd6e6f6474f36e907266afe60a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3120, "license_type": "permissive", "max_line_length": 706, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/remote_management/ipmi/ipmi_boot.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Use this module to manage order of boot devices\n class Ipmi_boot < Base\n # @return [String] Hostname or ip address of the BMC.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Integer, nil] Remote RMCP port.\n attribute :port\n validates :port, type: Integer\n\n # @return [String] Username to use to connect to the BMC.\n attribute :user\n validates :user, presence: true, type: String\n\n # @return [String] Password to connect to the BMC.\n attribute :password\n validates :password, presence: true, type: String\n\n # @return [:\"network -- Request network boot\", :\"floppy -- Boot from floppy\", :\"hd -- Boot from hard drive\", :\"safe -- Boot from hard drive, requesting 'safe mode'\", :\"optical -- boot from CD/DVD/BD drive\", :\"setup -- Boot into setup utility\", :\"default -- remove any IPMI directed boot device request\"] Set boot device to use on next reboot\n attribute :bootdev\n validates :bootdev, presence: true, expression_inclusion: {:in=>[:\"network -- Request network boot\", :\"floppy -- Boot from floppy\", :\"hd -- Boot from hard drive\", :\"safe -- Boot from hard drive, requesting 'safe mode'\", :\"optical -- boot from CD/DVD/BD drive\", :\"setup -- Boot into setup utility\", :\"default -- remove any IPMI directed boot device request\"], :message=>\"%{value} needs to be :\\\"network -- Request network boot\\\", :\\\"floppy -- Boot from floppy\\\", :\\\"hd -- Boot from hard drive\\\", :\\\"safe -- Boot from hard drive, requesting 'safe mode'\\\", :\\\"optical -- boot from CD/DVD/BD drive\\\", :\\\"setup -- Boot into setup utility\\\", :\\\"default -- remove any IPMI directed boot device request\\\"\"}\n\n # @return [:\"present -- Request system turn on\", :\"absent -- Request system turn on\", nil] Whether to ensure that boot devices is desired.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:\"present -- Request system turn on\", :\"absent -- Request system turn on\"], :message=>\"%{value} needs to be :\\\"present -- Request system turn on\\\", :\\\"absent -- Request system turn on\\\"\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If set, ask that system firmware uses this device beyond next boot. Be aware many systems do not honor this.\n attribute :persistent\n validates :persistent, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If set, request UEFI boot explicitly. Strictly speaking, the spec suggests that if not set, the system should BIOS boot and offers no \"don't care\" option. In practice, this flag not being set does not preclude UEFI boot on any system I've encountered.\n attribute :uefiboot\n validates :uefiboot, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7079242467880249, "alphanum_fraction": 0.708976149559021, "avg_line_length": 62.377777099609375, "blob_id": "4b858c4288f38ac0a582e0babdfe1d1c35561659", "content_id": "0277169934483134310286815ef59dd3ac37ce5e", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2852, "license_type": "permissive", "max_line_length": 552, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigiq_regkey_license_assignment.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages the assignment of regkey licenses on a BIG-IQ. Assignment means that the license is assigned to a BIG-IP, or, it needs to be assigned to a BIG-IP. Additionally, this module supported revoking the assignments from BIG-IP devices.\n class Bigiq_regkey_license_assignment < Base\n # @return [String] The registration key pool to use.\n attribute :pool\n validates :pool, presence: true, type: String\n\n # @return [String] The registration key that you want to assign from the pool.\n attribute :key\n validates :key, presence: true, type: String\n\n # @return [String, nil] When C(managed) is C(no), specifies the address, or hostname, where the BIG-IQ can reach the remote device to register.,When C(managed) is C(yes), specifies the managed device, or device UUID, that you want to register.,If C(managed) is C(yes), it is very important that you do not have more than one device with the same name. BIG-IQ internally recognizes devices by their ID, and therefore, this module's cannot guarantee that the correct device will be registered. The device returned is the device that will be used.\n attribute :device\n validates :device, type: String\n\n # @return [Symbol, nil] Whether the specified device is a managed or un-managed device.,When C(state) is C(present), this parameter is required.\n attribute :managed\n validates :managed, type: Symbol\n\n # @return [Integer, nil] Specifies the port of the remote device to connect to.,If this parameter is not specified, the default of C(443) will be used.\n attribute :device_port\n validates :device_port, type: Integer\n\n # @return [String, nil] The username used to connect to the remote device.,This username should be one that has sufficient privileges on the remote device to do licensing. Usually this is the C(Administrator) role.,When C(managed) is C(no), this parameter is required.\n attribute :device_username\n validates :device_username, type: String\n\n # @return [String, nil] The password of the C(device_username).,When C(managed) is C(no), this parameter is required.\n attribute :device_password\n validates :device_password, type: String\n\n # @return [:present, :absent, nil] When C(present), ensures that the device is assigned the specified license.,When C(absent), ensures the license is revokes from the remote device and freed on the BIG-IQ.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6894065737724304, "alphanum_fraction": 0.6921796798706055, "avg_line_length": 49.08333206176758, "blob_id": "b18b5616cbea8e0c951607c4410418c5a53ad73d", "content_id": "150a0fdff823aa2ae3fc53d7f5a062e6f3f09c42", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1803, "license_type": "permissive", "max_line_length": 260, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_config_delivery_channel.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module manages AWS Config delivery locations for rule checks and configuration info\n class Aws_config_delivery_channel < Base\n # @return [String] The name of the AWS Config resource.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Whether the Config rule should be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] The name of the Amazon S3 bucket to which AWS Config delivers configuration snapshots and configuration history files.\n attribute :s3_bucket\n validates :s3_bucket, type: String\n\n # @return [Object, nil] The prefix for the specified Amazon S3 bucket.\n attribute :s3_prefix\n\n # @return [String, nil] The Amazon Resource Name (ARN) of the Amazon SNS topic to which AWS Config sends notifications about configuration changes.\n attribute :sns_topic_arn\n validates :sns_topic_arn, type: String\n\n # @return [:One_Hour, :Three_Hours, :Six_Hours, :Twelve_Hours, :TwentyFour_Hours, nil] The frequency with which AWS Config delivers configuration snapshots.\n attribute :delivery_frequency\n validates :delivery_frequency, expression_inclusion: {:in=>[:One_Hour, :Three_Hours, :Six_Hours, :Twelve_Hours, :TwentyFour_Hours], :message=>\"%{value} needs to be :One_Hour, :Three_Hours, :Six_Hours, :Twelve_Hours, :TwentyFour_Hours\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7180192470550537, "alphanum_fraction": 0.7317743897438049, "avg_line_length": 41.764705657958984, "blob_id": "35306638ae01021be6c0766843fcc296dcf22810", "content_id": "0673a1162ee518700578d36dcb2e9c1cdfbfb121", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 727, "license_type": "permissive", "max_line_length": 336, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_link_status.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Get interface link status on HUAWEI CloudEngine switches.\n class Ce_link_status < Base\n # @return [Object] For the interface parameter, you can enter C(all) to display information about all interface, an interface type such as C(40GE) to display information about interfaces of the specified type, or full name of an interface such as C(40GE1/0/22) or C(vlanif10) to display information about the specific interface.\n attribute :interface\n validates :interface, presence: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6743649244308472, "alphanum_fraction": 0.6743649244308472, "avg_line_length": 33.63999938964844, "blob_id": "3f8dfe47790a26b07bb11b7d8ce728bc80422ee0", "content_id": "654047825590770a8caf9e962e7a56d63a7b3cd2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 866, "license_type": "permissive", "max_line_length": 174, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcpubsub_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # List Topics/Subscriptions from Google PubSub. Use the gcpubsub module for topic/subscription management. See U(https://cloud.google.com/pubsub/docs) for an overview.\n class Gcpubsub_facts < Base\n # @return [String, nil] GCP pubsub topic name. Only the name, not the full path, is required.\n attribute :topic\n validates :topic, type: String\n\n # @return [String] Choices are 'topics' or 'subscriptions'\n attribute :view\n validates :view, presence: true, type: String\n\n # @return [String, nil] list is the only valid option.\n attribute :state\n validates :state, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.727477490901947, "alphanum_fraction": 0.7297297120094299, "avg_line_length": 28.600000381469727, "blob_id": "0a5f2ffad4ef72328a76fed28954af45fae92f25", "content_id": "93992c17e7870f8e60ba31e12de6f877d10aad70", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 444, "license_type": "permissive", "max_line_length": 197, "num_lines": 15, "path": "/lib/ansible/ruby/modules/generated/clustering/k8s/k8s_scale.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Similar to the kubectl scale command. Use to set the number of replicas for a Deployment, ReplicatSet, or Replication Controller, or the parallelism attribute of a Job. Supports check mode.\n class K8s_scale < Base\n\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7210442423820496, "alphanum_fraction": 0.7262018322944641, "avg_line_length": 71.3732681274414, "blob_id": "08e5a05046b4d7f9a25f6fff671eb4e760e543da", "content_id": "c4931abdb270251074a3e7b9e19759c3a53fa0fd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 15705, "license_type": "permissive", "max_line_length": 535, "num_lines": 217, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_pool.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure Pool object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_pool < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Object, nil] Name of container cloud application that constitutes a pool in a a-b pool configuration, if different from vs app.\n attribute :a_pool\n\n # @return [Object, nil] A/b pool configuration.\n attribute :ab_pool\n\n # @return [Object, nil] Priority of this pool in a a-b pool pair.,Internally used.\n attribute :ab_priority\n\n # @return [Object, nil] Synchronize cisco apic epg members with pool servers.\n attribute :apic_epg_name\n\n # @return [Object, nil] Persistence will ensure the same user sticks to the same server for a desired duration of time.,It is a reference to an object of type applicationpersistenceprofile.\n attribute :application_persistence_profile_ref\n\n # @return [Object, nil] If configured then avi will trigger orchestration of pool server creation and deletion.,It is only supported for container clouds like mesos, opensift, kubernates, docker etc.,It is a reference to an object of type autoscalelaunchconfig.\n attribute :autoscale_launch_config_ref\n\n # @return [Object, nil] Network ids for the launch configuration.\n attribute :autoscale_networks\n\n # @return [Object, nil] Reference to server autoscale policy.,It is a reference to an object of type serverautoscalepolicy.\n attribute :autoscale_policy_ref\n\n # @return [Symbol, nil] Inline estimation of capacity of servers.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :capacity_estimation\n validates :capacity_estimation, type: Symbol\n\n # @return [Object, nil] The maximum time-to-first-byte of a server.,Allowed values are 1-5000.,Special values are 0 - 'automatic'.,Default value when not specified in API or module is interpreted by Avi Controller as 0.,Units(MILLISECONDS).\n attribute :capacity_estimation_ttfb_thresh\n\n # @return [Object, nil] Checksum of cloud configuration for pool.,Internally set by cloud connector.\n attribute :cloud_config_cksum\n\n # @return [Object, nil] It is a reference to an object of type cloud.\n attribute :cloud_ref\n\n # @return [Object, nil] Duration for which new connections will be gradually ramped up to a server recently brought online.,Useful for lb algorithms that are least connection based.,Allowed values are 1-300.,Special values are 0 - 'immediate'.,Default value when not specified in API or module is interpreted by Avi Controller as 10.,Units(MIN).\n attribute :connection_ramp_duration\n\n # @return [Object, nil] Creator name.\n attribute :created_by\n\n # @return [Object, nil] Traffic sent to servers will use this destination server port unless overridden by the server's specific port attribute.,The ssl checkbox enables avi to server encryption.,Allowed values are 1-65535.,Default value when not specified in API or module is interpreted by Avi Controller as 80.\n attribute :default_server_port\n\n # @return [String, nil] A description of the pool.\n attribute :description\n validates :description, type: String\n\n # @return [Object, nil] Comma separated list of domain names which will be used to verify the common names or subject alternative names presented by server certificates.,It is performed only when common name check host_check_enabled is enabled.\n attribute :domain_name\n\n # @return [Symbol, nil] Inherited config from virtualservice.\n attribute :east_west\n validates :east_west, type: Symbol\n\n # @return [Symbol, nil] Enable or disable the pool.,Disabling will terminate all open connections and pause health monitors.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :enabled\n validates :enabled, type: Symbol\n\n # @return [Object, nil] Names of external auto-scale groups for pool servers.,Currently available only for aws and azure.,Field introduced in 17.1.2.\n attribute :external_autoscale_groups\n\n # @return [Object, nil] Enable an action - close connection, http redirect or local http response - when a pool failure happens.,By default, a connection will be closed, in case the pool experiences a failure.\n attribute :fail_action\n\n # @return [Object, nil] Periodicity of feedback for fewest tasks server selection algorithm.,Allowed values are 1-300.,Default value when not specified in API or module is interpreted by Avi Controller as 10.,Units(SEC).\n attribute :fewest_tasks_feedback_delay\n\n # @return [Object, nil] Used to gracefully disable a server.,Virtual service waits for the specified time before terminating the existing connections to the servers that are disabled.,Allowed values are 1-7200.,Special values are 0 - 'immediate', -1 - 'infinite'.,Default value when not specified in API or module is interpreted by Avi Controller as 1.,Units(MIN).\n attribute :graceful_disable_timeout\n\n # @return [Symbol, nil] Indicates if the pool is a site-persistence pool.,Field introduced in 17.2.1.\n attribute :gslb_sp_enabled\n validates :gslb_sp_enabled, type: Symbol\n\n # @return [Array<String>, String, nil] Verify server health by applying one or more health monitors.,Active monitors generate synthetic traffic from each service engine and mark a server up or down based on the response.,The passive monitor listens only to client to server communication.,It raises or lowers the ratio of traffic destined to a server based on successful responses.,It is a reference to an object of type healthmonitor.\n attribute :health_monitor_refs\n validates :health_monitor_refs, type: TypeGeneric.new(String)\n\n # @return [Symbol, nil] Enable common name check for server certificate.,If enabled and no explicit domain name is specified, avi will use the incoming host header to do the match.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :host_check_enabled\n validates :host_check_enabled, type: Symbol\n\n # @return [Symbol, nil] The passive monitor will monitor client to server connections and requests and adjust traffic load to servers based on successful responses.,This may alter the expected behavior of the lb method, such as round robin.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :inline_health_monitor\n validates :inline_health_monitor, type: Symbol\n\n # @return [Object, nil] Use list of servers from ip address group.,It is a reference to an object of type ipaddrgroup.\n attribute :ipaddrgroup_ref\n\n # @return [Object, nil] The load balancing algorithm will pick a server within the pool's list of available servers.,Enum options - LB_ALGORITHM_LEAST_CONNECTIONS, LB_ALGORITHM_ROUND_ROBIN, LB_ALGORITHM_FASTEST_RESPONSE, LB_ALGORITHM_CONSISTENT_HASH,,LB_ALGORITHM_LEAST_LOAD, LB_ALGORITHM_FEWEST_SERVERS, LB_ALGORITHM_RANDOM, LB_ALGORITHM_FEWEST_TASKS, LB_ALGORITHM_NEAREST_SERVER,,LB_ALGORITHM_CORE_AFFINITY.,Default value when not specified in API or module is interpreted by Avi Controller as LB_ALGORITHM_LEAST_CONNECTIONS.\n attribute :lb_algorithm\n\n # @return [Object, nil] Http header name to be used for the hash key.\n attribute :lb_algorithm_consistent_hash_hdr\n\n # @return [Object, nil] Degree of non-affinity for core afffinity based server selection.,Allowed values are 1-65535.,Field introduced in 17.1.3.,Default value when not specified in API or module is interpreted by Avi Controller as 2.\n attribute :lb_algorithm_core_nonaffinity\n\n # @return [Object, nil] Criteria used as a key for determining the hash between the client and server.,Enum options - LB_ALGORITHM_CONSISTENT_HASH_SOURCE_IP_ADDRESS, LB_ALGORITHM_CONSISTENT_HASH_SOURCE_IP_ADDRESS_AND_PORT,,LB_ALGORITHM_CONSISTENT_HASH_URI, LB_ALGORITHM_CONSISTENT_HASH_CUSTOM_HEADER, LB_ALGORITHM_CONSISTENT_HASH_CUSTOM_STRING.,Default value when not specified in API or module is interpreted by Avi Controller as LB_ALGORITHM_CONSISTENT_HASH_SOURCE_IP_ADDRESS.\n attribute :lb_algorithm_hash\n\n # @return [Symbol, nil] Allow server lookup by name.,Field introduced in 17.1.11,17.2.4.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :lookup_server_by_name\n validates :lookup_server_by_name, type: Symbol\n\n # @return [Object, nil] The maximum number of concurrent connections allowed to each server within the pool.,Note applied value will be no less than the number of service engines that the pool is placed on.,If set to 0, no limit is applied.,Default value when not specified in API or module is interpreted by Avi Controller as 0.\n attribute :max_concurrent_connections_per_server\n\n # @return [Object, nil] Rate limit connections to each server.\n attribute :max_conn_rate_per_server\n\n # @return [String] The name of the pool.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] (internal-use) networks designated as containing servers for this pool.,The servers may be further narrowed down by a filter.,This field is used internally by avi, not editable by the user.\n attribute :networks\n\n # @return [Object, nil] A list of nsx service groups where the servers for the pool are created.,Field introduced in 17.1.1.\n attribute :nsx_securitygroup\n\n # @return [Object, nil] Avi will validate the ssl certificate present by a server against the selected pki profile.,It is a reference to an object of type pkiprofile.\n attribute :pki_profile_ref\n\n # @return [Object, nil] Manually select the networks and subnets used to provide reachability to the pool's servers.,Specify the subnet using the following syntax 10-1-1-0/24.,Use static routes in vrf configuration when pool servers are not directly connected butroutable from the service engine.\n attribute :placement_networks\n\n # @return [Object, nil] Header name for custom header persistence.\n attribute :prst_hdr_name\n\n # @return [Object, nil] Minimum number of requests to be queued when pool is full.,Default value when not specified in API or module is interpreted by Avi Controller as 128.\n attribute :request_queue_depth\n\n # @return [Symbol, nil] Enable request queue when pool is full.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :request_queue_enabled\n validates :request_queue_enabled, type: Symbol\n\n # @return [Symbol, nil] Rewrite incoming host header to server name of the server to which the request is proxied.,Enabling this feature rewrites host header for requests to all servers in the pool.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :rewrite_host_header_to_server_name\n validates :rewrite_host_header_to_server_name, type: Symbol\n\n # @return [Symbol, nil] If sni server name is specified, rewrite incoming host header to the sni server name.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :rewrite_host_header_to_sni\n validates :rewrite_host_header_to_sni, type: Symbol\n\n # @return [Symbol, nil] Server autoscale.,Not used anymore.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :server_auto_scale\n validates :server_auto_scale, type: Symbol\n\n # @return [Object, nil] Number of server_count.,Default value when not specified in API or module is interpreted by Avi Controller as 0.\n attribute :server_count\n\n # @return [Object, nil] Fully qualified dns hostname which will be used in the tls sni extension in server connections if sni is enabled.,If no value is specified, avi will use the incoming host header instead.\n attribute :server_name\n\n # @return [Object, nil] Server reselect configuration for http requests.\n attribute :server_reselect\n\n # @return [Array<Hash>, Hash, nil] The pool directs load balanced traffic to this list of destination servers.,The servers can be configured by ip address, name, network or via ip address group.\n attribute :servers\n validates :servers, type: TypeGeneric.new(Hash)\n\n # @return [Symbol, nil] Enable tls sni for server connections.,If disabled, avi will not send the sni extension as part of the handshake.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :sni_enabled\n validates :sni_enabled, type: Symbol\n\n # @return [Object, nil] Service engines will present a client ssl certificate to the server.,It is a reference to an object of type sslkeyandcertificate.\n attribute :ssl_key_and_certificate_ref\n\n # @return [Object, nil] When enabled, avi re-encrypts traffic to the backend servers.,The specific ssl profile defines which ciphers and ssl versions will be supported.,It is a reference to an object of type sslprofile.\n attribute :ssl_profile_ref\n\n # @return [Object, nil] It is a reference to an object of type tenant.\n attribute :tenant_ref\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Symbol, nil] Do not translate the client's destination port when sending the connection to the server.,The pool or servers specified service port will still be used for health monitoring.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :use_service_port\n validates :use_service_port, type: Symbol\n\n # @return [Object, nil] Uuid of the pool.\n attribute :uuid\n\n # @return [Object, nil] Virtual routing context that the pool is bound to.,This is used to provide the isolation of the set of networks the pool is attached to.,The pool inherits the virtual routing conext of the virtual service, and this field is used only internally, and is set by pb-transform.,It is a reference to an object of type vrfcontext.\n attribute :vrf_ref\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6709367632865906, "alphanum_fraction": 0.6709367632865906, "avg_line_length": 38.03125, "blob_id": "bc9595980e8e5ed018ee0c43f797bd9f582881e0", "content_id": "498d595cad27fd915ef762bffc0a89ec570edeea", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1249, "license_type": "permissive", "max_line_length": 211, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_nova_host_aggregate.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, or delete OpenStack host aggregates. If a aggregate with the supplied name already exists, it will be updated with the new name, new availability zone, new metadata and new list of hosts.\n class Os_nova_host_aggregate < Base\n # @return [String] Name of the aggregate.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Hash, nil] Metadata dict.\n attribute :metadata\n validates :metadata, type: Hash\n\n # @return [Object, nil] Availability zone to create aggregate into.\n attribute :availability_zone\n\n # @return [Array<String>, String, nil] List of hosts to set for an aggregate.\n attribute :hosts\n validates :hosts, type: TypeGeneric.new(String)\n\n # @return [:present, :absent, nil] Should the resource be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7041916251182556, "alphanum_fraction": 0.7041916251182556, "avg_line_length": 46.71428680419922, "blob_id": "6751d8a28d9d6b40b04ce26be32bd522b2d4afb0", "content_id": "90d1a3af09f3c474fdce224c6f95ef4603eb123d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1670, "license_type": "permissive", "max_line_length": 219, "num_lines": 35, "path": "/lib/ansible/ruby/modules/generated/network/ftd/ftd_configuration.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages configuration on Cisco FTD devices including creating, updating, removing configuration objects, scheduling and staring jobs, deploying pending changes, etc. All operation are performed over REST API.\n class Ftd_configuration < Base\n # @return [String] The name of the operation to execute. Commonly, the operation starts with 'add', 'edit', 'get' or 'delete' verbs, but can have an arbitrary name too.\n attribute :operation\n validates :operation, presence: true, type: String\n\n # @return [Hash, nil] Key-value pairs that should be sent as body parameters in a REST API call\n attribute :data\n validates :data, type: Hash\n\n # @return [Object, nil] Key-value pairs that should be sent as query parameters in a REST API call.\n attribute :query_params\n\n # @return [Hash, nil] Key-value pairs that should be sent as path parameters in a REST API call.\n attribute :path_params\n validates :path_params, type: Hash\n\n # @return [String, nil] Specifies Ansible fact name that is used to register received response from the FTD device.\n attribute :register_as\n validates :register_as, type: String\n\n # @return [Object, nil] Key-value dict that represents equality filters. Every key is a property name and value is its desired value. If multiple filters are present, they are combined with logical operator AND.\n attribute :filters\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6059681177139282, "alphanum_fraction": 0.6224143505096436, "avg_line_length": 52.135135650634766, "blob_id": "ae86088f89f7eadf25c83ba0e7641bc7b0f05a81", "content_id": "3046365d7244e7c74dcb0cab884297b7659a96d9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5898, "license_type": "permissive", "max_line_length": 386, "num_lines": 111, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_acl.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages access list entries for ACLs.\n class Nxos_acl < Base\n # @return [Integer, nil] Sequence number of the entry (ACE).\n attribute :seq\n validates :seq, type: Integer\n\n # @return [String] Case sensitive name of the access list (ACL).\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:permit, :deny, :remark, nil] Action of the ACE.\n attribute :action\n validates :action, expression_inclusion: {:in=>[:permit, :deny, :remark], :message=>\"%{value} needs to be :permit, :deny, :remark\"}, allow_nil: true\n\n # @return [Object, nil] If action is set to remark, this is the description.\n attribute :remark\n\n # @return [String, nil] Port number or protocol (as supported by the switch).\n attribute :proto\n validates :proto, type: String\n\n # @return [String, nil] Source ip and mask using IP/MASK notation and supports keyword 'any'.\n attribute :src\n validates :src, type: String\n\n # @return [:any, :eq, :gt, :lt, :neq, :range, nil] Source port operands such as eq, neq, gt, lt, range.\n attribute :src_port_op\n validates :src_port_op, expression_inclusion: {:in=>[:any, :eq, :gt, :lt, :neq, :range], :message=>\"%{value} needs to be :any, :eq, :gt, :lt, :neq, :range\"}, allow_nil: true\n\n # @return [Object, nil] Port/protocol and also first (lower) port when using range operand.\n attribute :src_port1\n\n # @return [Object, nil] Second (end) port when using range operand.\n attribute :src_port2\n\n # @return [String, nil] Destination ip and mask using IP/MASK notation and supports the keyword 'any'.\n attribute :dest\n validates :dest, type: String\n\n # @return [:any, :eq, :gt, :lt, :neq, :range, nil] Destination port operands such as eq, neq, gt, lt, range.\n attribute :dest_port_op\n validates :dest_port_op, expression_inclusion: {:in=>[:any, :eq, :gt, :lt, :neq, :range], :message=>\"%{value} needs to be :any, :eq, :gt, :lt, :neq, :range\"}, allow_nil: true\n\n # @return [Object, nil] Port/protocol and also first (lower) port when using range operand.\n attribute :dest_port1\n\n # @return [Object, nil] Second (end) port when using range operand.\n attribute :dest_port2\n\n # @return [:enable, nil] Log matches against this entry.\n attribute :log\n validates :log, expression_inclusion: {:in=>[:enable], :message=>\"%{value} needs to be :enable\"}, allow_nil: true\n\n # @return [:enable, nil] Match on the URG bit.\n attribute :urg\n validates :urg, expression_inclusion: {:in=>[:enable], :message=>\"%{value} needs to be :enable\"}, allow_nil: true\n\n # @return [:enable, nil] Match on the ACK bit.\n attribute :ack\n validates :ack, expression_inclusion: {:in=>[:enable], :message=>\"%{value} needs to be :enable\"}, allow_nil: true\n\n # @return [:enable, nil] Match on the PSH bit.\n attribute :psh\n validates :psh, expression_inclusion: {:in=>[:enable], :message=>\"%{value} needs to be :enable\"}, allow_nil: true\n\n # @return [:enable, nil] Match on the RST bit.\n attribute :rst\n validates :rst, expression_inclusion: {:in=>[:enable], :message=>\"%{value} needs to be :enable\"}, allow_nil: true\n\n # @return [:enable, nil] Match on the SYN bit.\n attribute :syn\n validates :syn, expression_inclusion: {:in=>[:enable], :message=>\"%{value} needs to be :enable\"}, allow_nil: true\n\n # @return [:enable, nil] Match on the FIN bit.\n attribute :fin\n validates :fin, expression_inclusion: {:in=>[:enable], :message=>\"%{value} needs to be :enable\"}, allow_nil: true\n\n # @return [:enable, nil] Match established connections.\n attribute :established\n validates :established, expression_inclusion: {:in=>[:enable], :message=>\"%{value} needs to be :enable\"}, allow_nil: true\n\n # @return [:enable, nil] Check non-initial fragments.\n attribute :fragments\n validates :fragments, expression_inclusion: {:in=>[:enable], :message=>\"%{value} needs to be :enable\"}, allow_nil: true\n\n # @return [Object, nil] Name of time-range to apply.\n attribute :time_range\n\n # @return [:critical, :flash, :\"flash-override\", :immediate, :internet, :network, :priority, :routine, nil] Match packets with given precedence.\n attribute :precedence\n validates :precedence, expression_inclusion: {:in=>[:critical, :flash, :\"flash-override\", :immediate, :internet, :network, :priority, :routine], :message=>\"%{value} needs to be :critical, :flash, :\\\"flash-override\\\", :immediate, :internet, :network, :priority, :routine\"}, allow_nil: true\n\n # @return [:af11, :af12, :af13, :af21, :af22, :af23, :af31, :af32, :af33, :af41, :af42, :af43, :cs1, :cs2, :cs3, :cs4, :cs5, :cs6, :cs7, :default, :ef, nil] Match packets with given dscp value.\n attribute :dscp\n validates :dscp, expression_inclusion: {:in=>[:af11, :af12, :af13, :af21, :af22, :af23, :af31, :af32, :af33, :af41, :af42, :af43, :cs1, :cs2, :cs3, :cs4, :cs5, :cs6, :cs7, :default, :ef], :message=>\"%{value} needs to be :af11, :af12, :af13, :af21, :af22, :af23, :af31, :af32, :af33, :af41, :af42, :af43, :cs1, :cs2, :cs3, :cs4, :cs5, :cs6, :cs7, :default, :ef\"}, allow_nil: true\n\n # @return [:present, :absent, :delete_acl, nil] Specify desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :delete_acl], :message=>\"%{value} needs to be :present, :absent, :delete_acl\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6945392489433289, "alphanum_fraction": 0.6962457299232483, "avg_line_length": 45.880001068115234, "blob_id": "3599f0939cd4d29e29d62125bcca44aab0b92075", "content_id": "b1426f4a19d17569e80ff5f5291d391f247a43e5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1172, "license_type": "permissive", "max_line_length": 277, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/windows/win_security_policy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows you to set the local security policies that are configured by SecEdit.exe.\n class Win_security_policy < Base\n # @return [String] The ini section the key exists in.,If the section does not exist then the module will return an error.,Example sections to use are 'Account Policies', 'Local Policies', 'Event Log', 'Restricted Groups', 'System Services', 'Registry' and 'File System'\n attribute :section\n validates :section, presence: true, type: String\n\n # @return [String] The ini key of the section or policy name to modify.,The module will return an error if this key is invalid.\n attribute :key\n validates :key, presence: true, type: String\n\n # @return [String, Integer] The value for the ini key or policy name.,If the key takes in a boolean value then 0 = False and 1 = True.\n attribute :value\n validates :value, presence: true, type: MultipleTypes.new(String, Integer)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6616871953010559, "alphanum_fraction": 0.6616871953010559, "avg_line_length": 38.24137878417969, "blob_id": "560e309cb2656b8115b8999d4a1a58c1183867a7", "content_id": "24c02863fb7f348110c7b687750294fb56dc1087", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1138, "license_type": "permissive", "max_line_length": 143, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/storage/purestorage/purefb_snap.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or delete volumes and filesystem snapshots on Pure Storage FlashBlades.\n class Purefb_snap < Base\n # @return [String] The name of the source filesystem.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Suffix of snapshot name.\n attribute :suffix\n validates :suffix, type: String\n\n # @return [:absent, :present, nil] Define whether the filesystem snapshot should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Define whether to eradicate the snapshot on delete or leave in trash.\n attribute :eradicate\n validates :eradicate, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6854928135871887, "alphanum_fraction": 0.6877076625823975, "avg_line_length": 36.625, "blob_id": "99cf1ad0087afa92572f91f75d5001ddf7bef9b4", "content_id": "a5b4207758434ef98f9bd83c8fa268f8e9b24bf1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 903, "license_type": "permissive", "max_line_length": 143, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_config_aggregation_authorization.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Module manages AWS Config resources\n class Aws_config_aggregation_authorization < Base\n # @return [:present, :absent, nil] Whether the Config rule should be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] The 12-digit account ID of the account authorized to aggregate data.\n attribute :authorized_account_id\n validates :authorized_account_id, type: String\n\n # @return [Object, nil] The region authorized to collect aggregated data.\n attribute :authorized_aws_region\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7038570642471313, "alphanum_fraction": 0.7117018699645996, "avg_line_length": 73.01612854003906, "blob_id": "f895b95db13f4a75d6db31422ed1bc3e8cfe811a", "content_id": "9245500c4c2e2b59921cccd878fbfc18fc6ef5d9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4589, "license_type": "permissive", "max_line_length": 537, "num_lines": 62, "path": "/lib/ansible/ruby/modules/generated/packaging/language/pip.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage Python library dependencies. To use this module, one of the following keys is required: C(name) or C(requirements).\n class Pip < Base\n # @return [Array<String>, String, nil] The name of a Python library to install or the url(bzr+,hg+,git+,svn+) of the remote package.,This can be a list (since 2.2) and contain version specifiers (since 2.7).\n attribute :name\n validates :name, type: TypeGeneric.new(String)\n\n # @return [Object, nil] The version number to install of the Python library specified in the I(name) parameter.\n attribute :version\n\n # @return [String, nil] The path to a pip requirements file, which should be local to the remote system. File can be specified as a relative path if using the chdir option.\n attribute :requirements\n validates :requirements, type: String\n\n # @return [String, nil] An optional path to a I(virtualenv) directory to install into. It cannot be specified together with the 'executable' parameter (added in 2.1). If the virtualenv does not exist, it will be created before installing packages. The optional virtualenv_site_packages, virtualenv_command, and virtualenv_python options affect the creation of the virtualenv.\n attribute :virtualenv\n validates :virtualenv, type: String\n\n # @return [:yes, :no, nil] Whether the virtual environment will inherit packages from the global site-packages directory. Note that if this setting is changed on an already existing virtual environment it will not have any effect, the environment must be deleted and newly created.\n attribute :virtualenv_site_packages\n validates :virtualenv_site_packages, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] The command or a pathname to the command to create the virtual environment with. For example C(pyvenv), C(virtualenv), C(virtualenv2), C(~/bin/virtualenv), C(/usr/local/bin/virtualenv).\n attribute :virtualenv_command\n validates :virtualenv_command, type: String\n\n # @return [Object, nil] The Python executable used for creating the virtual environment. For example C(python3.5), C(python2.7). When not specified, the Python version used to run the ansible module is used. This parameter should not be used when C(virtualenv_command) is using C(pyvenv) or the C(-m venv) module.\n attribute :virtualenv_python\n\n # @return [:absent, :forcereinstall, :latest, :present, nil] The state of module,The 'forcereinstall' option is only available in Ansible 2.1 and above.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :forcereinstall, :latest, :present], :message=>\"%{value} needs to be :absent, :forcereinstall, :latest, :present\"}, allow_nil: true\n\n # @return [String, nil] Extra arguments passed to pip.\n attribute :extra_args\n validates :extra_args, type: String\n\n # @return [:yes, :no, nil] Pass the editable flag.\n attribute :editable\n validates :editable, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] cd into this directory before running the command\n attribute :chdir\n\n # @return [String, nil] The explicit executable or a pathname to the executable to be used to run pip for a specific version of Python installed in the system. For example C(pip-3.3), if there are both Python 2.7 and 3.3 installations in the system and you want to run pip for the Python 3.3 installation. It cannot be specified together with the 'virtualenv' parameter (added in 2.1). By default, it will take the appropriate version for the python interpreter use by ansible, e.g. pip3 on python 3, and pip2 or pip on python 2.\n attribute :executable\n validates :executable, type: String\n\n # @return [String, nil] The system umask to apply before installing the pip package. This is useful, for example, when installing on systems that have a very restrictive umask by default (e.g., 0077) and you want to pip install packages which are to be used by all users. Note that this requires you to specify desired umask mode in octal, with a leading 0 (e.g., 0077).\n attribute :umask\n validates :umask, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.658099889755249, "alphanum_fraction": 0.6760034561157227, "avg_line_length": 53.96825408935547, "blob_id": "8ca54b82b5221a3eaaf43d75059efae885b07016", "content_id": "294d62d7cf21c001b0b9d9bc86f9118574c553ee", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3463, "license_type": "permissive", "max_line_length": 319, "num_lines": 63, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_acl.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages base ACL configurations on HUAWEI CloudEngine switches.\n class Ce_acl < Base\n # @return [:present, :absent, :delete_acl, nil] Specify desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :delete_acl], :message=>\"%{value} needs to be :present, :absent, :delete_acl\"}, allow_nil: true\n\n # @return [Object] ACL number or name. For a numbered rule group, the value ranging from 2000 to 2999 indicates a basic ACL. For a named rule group, the value is a string of 1 to 32 case-sensitive characters starting with a letter, spaces not supported.\n attribute :acl_name\n validates :acl_name, presence: true\n\n # @return [Object, nil] ACL number. The value is an integer ranging from 2000 to 2999.\n attribute :acl_num\n\n # @return [Object, nil] ACL step. The value is an integer ranging from 1 to 20. The default value is 5.\n attribute :acl_step\n\n # @return [Object, nil] ACL description. The value is a string of 1 to 127 characters.\n attribute :acl_description\n\n # @return [Object, nil] Name of a basic ACL rule. The value is a string of 1 to 32 characters. The value is case-insensitive, and cannot contain spaces or begin with an underscore (_).\n attribute :rule_name\n\n # @return [Object, nil] ID of a basic ACL rule in configuration mode. The value is an integer ranging from 0 to 4294967294.\n attribute :rule_id\n\n # @return [:permit, :deny, nil] Matching mode of basic ACL rules.\n attribute :rule_action\n validates :rule_action, expression_inclusion: {:in=>[:permit, :deny], :message=>\"%{value} needs to be :permit, :deny\"}, allow_nil: true\n\n # @return [Object, nil] Source IP address. The value is a string of 0 to 255 characters.The default value is 0.0.0.0. The value is in dotted decimal notation.\n attribute :source_ip\n\n # @return [Object, nil] Mask of a source IP address. The value is an integer ranging from 1 to 32.\n attribute :src_mask\n\n # @return [:fragment, :clear_fragment, nil] Type of packet fragmentation.\n attribute :frag_type\n validates :frag_type, expression_inclusion: {:in=>[:fragment, :clear_fragment], :message=>\"%{value} needs to be :fragment, :clear_fragment\"}, allow_nil: true\n\n # @return [Object, nil] VPN instance name. The value is a string of 1 to 31 characters.The default value is _public_.\n attribute :vrf_name\n\n # @return [Object, nil] Name of a time range in which an ACL rule takes effect. The value is a string of 1 to 32 characters. The value is case-insensitive, and cannot contain spaces. The name must start with an uppercase or lowercase letter. In addition, the word \"all\" cannot be specified as a time range name.\n attribute :time_range\n\n # @return [Object, nil] Description about an ACL rule. The value is a string of 1 to 127 characters.\n attribute :rule_description\n\n # @return [:yes, :no, nil] Flag of logging matched data packets.\n attribute :log_flag\n validates :log_flag, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6701388955116272, "alphanum_fraction": 0.6722221970558167, "avg_line_length": 37.91891860961914, "blob_id": "abfd66468cab6f948be88ff40120f7e99d1f1870", "content_id": "3555a2b85044542ae227c78b1133530778693662", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1440, "license_type": "permissive", "max_line_length": 143, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/packaging/os/pkg5_publisher.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # IPS packages are the native packages in Solaris 11 and higher.\n # This modules will configure which publishers a client will download IPS packages from.\n class Pkg5_publisher < Base\n # @return [String] The publisher's name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Whether to ensure that a publisher is present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Symbol, nil] Packages installed from a sticky repository can only receive updates from that repository.\n attribute :sticky\n validates :sticky, type: Symbol\n\n # @return [Symbol, nil] Is the repository enabled or disabled?\n attribute :enabled\n validates :enabled, type: Symbol\n\n # @return [String, nil] A path or URL to the repository.,Multiple values may be provided.\n attribute :origin\n validates :origin, type: String\n\n # @return [Object, nil] A path or URL to the repository mirror.,Multiple values may be provided.\n attribute :mirror\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7266355156898499, "alphanum_fraction": 0.7393190860748291, "avg_line_length": 82.22222137451172, "blob_id": "dbffc8e0142ea33da5757d6ffc78dc8addc76b8c", "content_id": "f302fb2a2550e27d6e61c440b85962609d3982b9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2996, "license_type": "permissive", "max_line_length": 577, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_compute_network.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Represents a Network resource.\n # Your Cloud Platform Console project can contain multiple networks, and each network can have multiple instances attached to it. A network allows you to define a gateway IP and the network range for the instances attached to that network. Every project is provided with a default network with preset configurations and firewall rules. You can choose to customize the default network by adding or removing rules, or you can create new networks in that project. Generally, most users only need one network, although you can have up to five networks per project by default.\n # A network belongs to only one project, and each instance can only belong to one network. All Compute Engine networks use the IPv4 protocol. Compute Engine currently does not support IPv6. However, Google is a major advocate of IPv6 and it is an important future direction.\n class Gcp_compute_network < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] An optional description of this resource. Provide this property when you create the resource.\n attribute :description\n\n # @return [Object, nil] A gateway address for default routing to other networks. This value is read only and is selected by the Google Compute Engine, typically as the first usable address in the IPv4Range.\n attribute :gateway_ipv4\n\n # @return [Object, nil] The range of internal addresses that are legal on this network. This range is a CIDR specification, for example: 192.168.0.0/16. Provided by the client when the network is created.\n attribute :ipv4_range\n\n # @return [String, nil] Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash.\n attribute :name\n validates :name, type: String\n\n # @return [Symbol, nil] When set to true, the network is created in \"auto subnet mode\". When set to false, the network is in \"custom subnet mode\".,In \"auto subnet mode\", a newly created network is assigned the default CIDR of 10.128.0.0/9 and it automatically creates one subnetwork per region.\n attribute :auto_create_subnetworks\n validates :auto_create_subnetworks, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6638246178627014, "alphanum_fraction": 0.6638246178627014, "avg_line_length": 42.21052551269531, "blob_id": "fade79d2750ba40d37ed271bfc6a098eb10c306a", "content_id": "b795f556efbe1b238cf5b22178fd49d05db8accf", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2463, "license_type": "permissive", "max_line_length": 244, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/network/slxos/slxos_interface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of Interfaces on Extreme SLX-OS network devices.\n class Slxos_interface < Base\n # @return [String] Name of the Interface.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Description of Interface.\n attribute :description\n validates :description, type: String\n\n # @return [Boolean, nil] Interface link status.\n attribute :enabled\n validates :enabled, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Integer, nil] Interface link speed.\n attribute :speed\n validates :speed, type: Integer\n\n # @return [Integer, nil] Maximum size of transmit packet.\n attribute :mtu\n validates :mtu, type: Integer\n\n # @return [String, nil] Transmit rate in bits per second (bps).\n attribute :tx_rate\n validates :tx_rate, type: String\n\n # @return [String, nil] Receiver rate in bits per second (bps).\n attribute :rx_rate\n validates :rx_rate, type: String\n\n # @return [Array<Hash>, Hash, nil] Check the operational state of given interface C(name) for LLDP neighbor.,The following suboptions are available.\n attribute :neighbors\n validates :neighbors, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash, nil] List of Interfaces definitions.\n attribute :aggregate\n validates :aggregate, type: TypeGeneric.new(Hash)\n\n # @return [Integer, nil] Time in seconds to wait before checking for the operational state on remote device. This wait is applicable for operational state argument which are I(state) with values C(up)/C(down), I(tx_rate) and I(rx_rate).\n attribute :delay\n validates :delay, type: Integer\n\n # @return [:present, :absent, :up, :down, nil] State of the Interface configuration, C(up) means present and operationally up and C(down) means present and operationally C(down)\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :up, :down], :message=>\"%{value} needs to be :present, :absent, :up, :down\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6709163188934326, "alphanum_fraction": 0.6892430186271667, "avg_line_length": 43.82143020629883, "blob_id": "63ffa24bbeba91ba9f7d4cc5dd9f72c7a08fbd3d", "content_id": "0958ce397672ae59f090223e5dc0024d31a085d7", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1255, "license_type": "permissive", "max_line_length": 218, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_local_role_manager.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage local roles on an ESXi host\n class Vmware_local_role_manager < Base\n # @return [String] The local role name to be managed.\n attribute :local_role_name\n validates :local_role_name, presence: true, type: String\n\n # @return [Object, nil] The list of privileges that role needs to have.,Please see U(https://docs.vmware.com/en/VMware-vSphere/6.0/com.vmware.vsphere.security.doc/GUID-ED56F3C4-77D0-49E3-88B6-B99B8B437B62.html)\n attribute :local_privilege_ids\n\n # @return [:present, :absent, nil] Indicate desired state of the role.,If the role already exists when C(state=present), the role info is updated.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Symbol, nil] If set to C(False) then prevents the role from being removed if any permissions are using it.\n attribute :force_remove\n validates :force_remove, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6917256712913513, "alphanum_fraction": 0.694654643535614, "avg_line_length": 48.96341323852539, "blob_id": "0f29ef1fe40dbcff0bfe3ddd22f30efbb9c21d82", "content_id": "4b7c1e2af223d3c1025663e322d90a652fed399d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4097, "license_type": "permissive", "max_line_length": 590, "num_lines": 82, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gce_lb.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can create and destroy Google Compute Engine C(loadbalancer) and C(httphealthcheck) resources. The primary LB resource is the C(load_balancer) resource and the health check parameters are all prefixed with I(httphealthcheck). The full documentation for Google Compute Engine load balancing is at U(https://developers.google.com/compute/docs/load-balancing/). However, the ansible module simplifies the configuration by following the libcloud model. Full install/configuration instructions for the gce* modules can be found in the comments of ansible/test/gce_tests.py.\n class Gce_lb < Base\n # @return [String, nil] the name identifier for the HTTP health check\n attribute :httphealthcheck_name\n validates :httphealthcheck_name, type: String\n\n # @return [Integer, nil] the TCP port to use for HTTP health checking\n attribute :httphealthcheck_port\n validates :httphealthcheck_port, type: Integer\n\n # @return [String, nil] the url path to use for HTTP health checking\n attribute :httphealthcheck_path\n validates :httphealthcheck_path, type: String\n\n # @return [Integer, nil] the duration in seconds between each health check request\n attribute :httphealthcheck_interval\n validates :httphealthcheck_interval, type: Integer\n\n # @return [Integer, nil] the timeout in seconds before a request is considered a failed check\n attribute :httphealthcheck_timeout\n validates :httphealthcheck_timeout, type: Integer\n\n # @return [Integer, nil] number of consecutive failed checks before marking a node unhealthy\n attribute :httphealthcheck_unhealthy_count\n validates :httphealthcheck_unhealthy_count, type: Integer\n\n # @return [Integer, nil] number of consecutive successful checks before marking a node healthy\n attribute :httphealthcheck_healthy_count\n validates :httphealthcheck_healthy_count, type: Integer\n\n # @return [Object, nil] host header to pass through on HTTP check requests\n attribute :httphealthcheck_host\n\n # @return [String, nil] name of the load-balancer resource\n attribute :name\n validates :name, type: String\n\n # @return [:tcp, :udp, nil] the protocol used for the load-balancer packet forwarding, tcp or udp\n attribute :protocol\n validates :protocol, expression_inclusion: {:in=>[:tcp, :udp], :message=>\"%{value} needs to be :tcp, :udp\"}, allow_nil: true\n\n # @return [String, nil] the GCE region where the load-balancer is defined\n attribute :region\n validates :region, type: String\n\n # @return [Object, nil] the external static IPv4 (or auto-assigned) address for the LB\n attribute :external_ip\n\n # @return [Object, nil] the port (range) to forward, e.g. 80 or 8000-8888 defaults to all ports\n attribute :port_range\n\n # @return [Array<String>, String, nil] a list of zone/nodename pairs, e.g ['us-central1-a/www-a', ...]\n attribute :members\n validates :members, type: TypeGeneric.new(String)\n\n # @return [:active, :present, :absent, :deleted, nil] desired state of the LB\n attribute :state\n validates :state, expression_inclusion: {:in=>[:active, :present, :absent, :deleted], :message=>\"%{value} needs to be :active, :present, :absent, :deleted\"}, allow_nil: true\n\n # @return [Object, nil] service account email\n attribute :service_account_email\n\n # @return [Object, nil] path to the pem file associated with the service account email This option is deprecated. Use 'credentials_file'.\n attribute :pem_file\n\n # @return [Object, nil] path to the JSON file associated with the service account email\n attribute :credentials_file\n\n # @return [Object, nil] your GCE project ID\n attribute :project_id\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6499999761581421, "alphanum_fraction": 0.6509259343147278, "avg_line_length": 37.57143020629883, "blob_id": "0b909c3168cdafea538f95ea8dcfa42e74ec268d", "content_id": "7e95b828cf9d9a7e4ac0f446dabdc0c4f4c7ca61", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1080, "license_type": "permissive", "max_line_length": 161, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/cloud/digital_ocean/digital_ocean_domain.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create/delete a DNS domain in DigitalOcean.\n class Digital_ocean_domain < Base\n # @return [:present, :absent, nil] Indicate desired state of the target.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Numeric, the droplet id you want to operate on.\n attribute :id\n\n # @return [String, nil] String, this is the name of the droplet - must be formatted by hostname rules, or the name of a SSH key, or the name of a domain.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] An 'A' record for '@' ($ORIGIN) will be created with the value 'ip'. 'ip' is an IP version 4 address.\n attribute :ip\n validates :ip, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6808916926383972, "alphanum_fraction": 0.6840764284133911, "avg_line_length": 46.57575607299805, "blob_id": "afffca79969f8cab3d25c6cb8d9dc543dae29a16", "content_id": "cdaea3d86c2c197d5da33a0cc572cea1ed11453b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1570, "license_type": "permissive", "max_line_length": 291, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_win_password.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gets the default administrator password from any EC2 Windows instance. The instance is referenced by its id (e.g. C(i-XXXXXXX)). This module has a dependency on python-boto.\n class Ec2_win_password < Base\n # @return [String] The instance id to get the password data from.\n attribute :instance_id\n validates :instance_id, presence: true, type: String\n\n # @return [String] Path to the file containing the key pair used on the instance.\n attribute :key_file\n validates :key_file, presence: true, type: String\n\n # @return [String, nil] The passphrase for the instance key pair. The key must use DES or 3DES encryption for this module to decrypt it. You can use openssl to convert your password protected keys if they do not use DES or 3DES. ex) C(openssl rsa -in current_key -out new_key -des3).\n attribute :key_passphrase\n validates :key_passphrase, type: String\n\n # @return [:yes, :no, nil] Whether or not to wait for the password to be available before returning.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Number of seconds to wait before giving up.\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6865339875221252, "alphanum_fraction": 0.6935210824012756, "avg_line_length": 68.97036743164062, "blob_id": "d8d7538cdb3f2351702a90aeff5efc7dac4fb8ae", "content_id": "8639eb827ffe3e3a3dfb0b492f2e15693dfd0b87", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 9446, "license_type": "permissive", "max_line_length": 751, "num_lines": 135, "path": "/lib/ansible/ruby/modules/generated/network/netscaler/netscaler_servicegroup.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage service group configuration in Netscaler.\n # This module is intended to run either on the ansible control node or a bastion (jumpserver) with access to the actual netscaler instance.\n class Netscaler_servicegroup < Base\n # @return [String, nil] Name of the service group. Must begin with an ASCII alphabetic or underscore C(_) character, and must contain only ASCII alphanumeric, underscore C(_), hash C(#), period C(.), space C( ), colon C(:), at C(@), equals C(=), and hyphen C(-) characters. Can be changed after the name is created.,Minimum length = 1\n attribute :servicegroupname\n validates :servicegroupname, type: String\n\n # @return [:HTTP, :FTP, :TCP, :UDP, :SSL, :SSL_BRIDGE, :SSL_TCP, :DTLS, :NNTP, :RPCSVR, :DNS, :ADNS, :SNMP, :RTSP, :DHCPRA, :ANY, :SIP_UDP, :SIP_TCP, :SIP_SSL, :DNS_TCP, :ADNS_TCP, :MYSQL, :MSSQL, :ORACLE, :RADIUS, :RADIUSListener, :RDP, :DIAMETER, :SSL_DIAMETER, :TFTP, :SMPP, :PPTP, :GRE, :SYSLOGTCP, :SYSLOGUDP, :FIX, :SSL_FIX, nil] Protocol used to exchange data with the service.\n attribute :servicetype\n validates :servicetype, expression_inclusion: {:in=>[:HTTP, :FTP, :TCP, :UDP, :SSL, :SSL_BRIDGE, :SSL_TCP, :DTLS, :NNTP, :RPCSVR, :DNS, :ADNS, :SNMP, :RTSP, :DHCPRA, :ANY, :SIP_UDP, :SIP_TCP, :SIP_SSL, :DNS_TCP, :ADNS_TCP, :MYSQL, :MSSQL, :ORACLE, :RADIUS, :RADIUSListener, :RDP, :DIAMETER, :SSL_DIAMETER, :TFTP, :SMPP, :PPTP, :GRE, :SYSLOGTCP, :SYSLOGUDP, :FIX, :SSL_FIX], :message=>\"%{value} needs to be :HTTP, :FTP, :TCP, :UDP, :SSL, :SSL_BRIDGE, :SSL_TCP, :DTLS, :NNTP, :RPCSVR, :DNS, :ADNS, :SNMP, :RTSP, :DHCPRA, :ANY, :SIP_UDP, :SIP_TCP, :SIP_SSL, :DNS_TCP, :ADNS_TCP, :MYSQL, :MSSQL, :ORACLE, :RADIUS, :RADIUSListener, :RDP, :DIAMETER, :SSL_DIAMETER, :TFTP, :SMPP, :PPTP, :GRE, :SYSLOGTCP, :SYSLOGUDP, :FIX, :SSL_FIX\"}, allow_nil: true\n\n # @return [:TRANSPARENT, :REVERSE, :FORWARD, nil] Cache type supported by the cache server.\n attribute :cachetype\n validates :cachetype, expression_inclusion: {:in=>[:TRANSPARENT, :REVERSE, :FORWARD], :message=>\"%{value} needs to be :TRANSPARENT, :REVERSE, :FORWARD\"}, allow_nil: true\n\n # @return [Object, nil] Maximum number of simultaneous open connections for the service group.,Minimum value = C(0),Maximum value = C(4294967294)\n attribute :maxclient\n\n # @return [Object, nil] Maximum number of requests that can be sent on a persistent connection to the service group.,Note: Connection requests beyond this value are rejected.,Minimum value = C(0),Maximum value = C(65535)\n attribute :maxreq\n\n # @return [Symbol, nil] Use the transparent cache redirection virtual server to forward the request to the cache server.,Note: Do not set this parameter if you set the Cache Type.\n attribute :cacheable\n validates :cacheable, type: Symbol\n\n # @return [:enabled, :disabled, nil] Insert the Client IP header in requests forwarded to the service.\n attribute :cip\n validates :cip, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [Object, nil] Name of the HTTP header whose value must be set to the IP address of the client. Used with the Client IP parameter. If client IP insertion is enabled, and the client IP header is not specified, the value of Client IP Header parameter or the value set by the set ns config command is used as client's IP header name.,Minimum length = 1\n attribute :cipheader\n\n # @return [Object, nil] Use client's IP address as the source IP address when initiating connection to the server. With the NO setting, which is the default, a mapped IP (MIP) address or subnet IP (SNIP) address is used as the source IP address to initiate server side connections.\n attribute :usip\n\n # @return [Object, nil] Path monitoring for clustering.\n attribute :pathmonitor\n\n # @return [Object, nil] Individual Path monitoring decisions.\n attribute :pathmonitorindv\n\n # @return [Symbol, nil] Use the proxy port as the source port when initiating connections with the server. With the NO setting, the client-side connection port is used as the source port for the server-side connection.,Note: This parameter is available only when the Use Source IP C(usip) parameter is set to C(yes).\n attribute :useproxyport\n validates :useproxyport, type: Symbol\n\n # @return [Symbol, nil] Monitor the health of this service. Available settings function as follows:,C(yes) - Send probes to check the health of the service.,C(no) - Do not send probes to check the health of the service. With the NO option, the appliance shows the service as UP at all times.\n attribute :healthmonitor\n validates :healthmonitor, type: Symbol\n\n # @return [Symbol, nil] Enable surge protection for the service group.\n attribute :sp\n validates :sp, type: Symbol\n\n # @return [Symbol, nil] Enable RTSP session ID mapping for the service group.\n attribute :rtspsessionidremap\n validates :rtspsessionidremap, type: Symbol\n\n # @return [Object, nil] Time, in seconds, after which to terminate an idle client connection.,Minimum value = C(0),Maximum value = C(31536000)\n attribute :clttimeout\n\n # @return [Object, nil] Time, in seconds, after which to terminate an idle server connection.,Minimum value = C(0),Maximum value = C(31536000)\n attribute :svrtimeout\n\n # @return [Symbol, nil] Enable client keep-alive for the service group.\n attribute :cka\n validates :cka, type: Symbol\n\n # @return [Symbol, nil] Enable TCP buffering for the service group.\n attribute :tcpb\n validates :tcpb, type: Symbol\n\n # @return [Symbol, nil] Enable compression for the specified service.\n attribute :cmp\n validates :cmp, type: Symbol\n\n # @return [Object, nil] Maximum bandwidth, in Kbps, allocated for all the services in the service group.,Minimum value = C(0),Maximum value = C(4294967287)\n attribute :maxbandwidth\n\n # @return [Object, nil] Minimum sum of weights of the monitors that are bound to this service. Used to determine whether to mark a service as UP or DOWN.,Minimum value = C(0),Maximum value = C(65535)\n attribute :monthreshold\n\n # @return [:enabled, :disabled, nil] Flush all active transactions associated with all the services in the service group whose state transitions from UP to DOWN. Do not enable this option for applications that must complete their transactions.\n attribute :downstateflush\n validates :downstateflush, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [Object, nil] Name of the TCP profile that contains TCP configuration settings for the service group.,Minimum length = 1,Maximum length = 127\n attribute :tcpprofilename\n\n # @return [Object, nil] Name of the HTTP profile that contains HTTP configuration settings for the service group.,Minimum length = 1,Maximum length = 127\n attribute :httpprofilename\n\n # @return [Object, nil] Any information about the service group.\n attribute :comment\n\n # @return [:enabled, :disabled, nil] Enable logging of AppFlow information for the specified service group.\n attribute :appflowlog\n validates :appflowlog, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [Object, nil] Network profile for the service group.,Minimum length = 1,Maximum length = 127\n attribute :netprofile\n\n # @return [:DISABLED, :DNS, :POLICY, nil] Auto scale option for a servicegroup.\n attribute :autoscale\n validates :autoscale, expression_inclusion: {:in=>[:DISABLED, :DNS, :POLICY], :message=>\"%{value} needs to be :DISABLED, :DNS, :POLICY\"}, allow_nil: true\n\n # @return [Object, nil] member port.\n attribute :memberport\n\n # @return [Symbol, nil] Wait for all existing connections to the service to terminate before shutting down the service.\n attribute :graceful\n validates :graceful, type: Symbol\n\n # @return [Array<Hash>, Hash, nil] A list of dictionaries describing each service member of the service group.\n attribute :servicemembers\n validates :servicemembers, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash, nil] A list of monitornames to bind to this service,Note that the monitors must have already been setup possibly using the M(netscaler_lb_monitor) module or some other method\n attribute :monitorbindings\n validates :monitorbindings, type: TypeGeneric.new(Hash)\n\n # @return [Symbol, nil] When set to C(yes) the service group state will be set to DISABLED.,When set to C(no) the service group state will be set to ENABLED.,Note that due to limitations of the underlying NITRO API a C(disabled) state change alone does not cause the module result to report a changed status.\n attribute :disabled\n validates :disabled, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.682692289352417, "alphanum_fraction": 0.6842948794364929, "avg_line_length": 44.38181686401367, "blob_id": "d56c559cfc58b396898bf58c507d05b1bf8bae6d", "content_id": "644b4e964706c29cf0fb0b321e59bf4b84452316", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2496, "license_type": "permissive", "max_line_length": 269, "num_lines": 55, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_elementsw_snapshot.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, Modify or Delete Snapshot on Element OS Cluster.\n class Na_elementsw_snapshot < Base\n # @return [String, nil] Name of new snapshot create.,If unspecified, date and time when the snapshot was taken is used.\n attribute :name\n validates :name, type: String\n\n # @return [:present, :absent, nil] Whether the specified snapshot should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Integer, String] ID or Name of active volume.\n attribute :src_volume_id\n validates :src_volume_id, presence: true, type: MultipleTypes.new(Integer, String)\n\n # @return [String] Account ID or Name of Parent/Source Volume.\n attribute :account_id\n validates :account_id, presence: true, type: String\n\n # @return [Object, nil] Retention period for the snapshot.,Format is 'HH:mm:ss'.\n attribute :retention\n\n # @return [String, nil] ID or Name of an existing snapshot.,Required when C(state=present), to modify snapshot properties.,Required when C(state=present), to create snapshot from another snapshot in the volume.,Required when C(state=absent), to delete snapshot.\n attribute :src_snapshot_id\n validates :src_snapshot_id, type: String\n\n # @return [Symbol, nil] Flag, whether to replicate the snapshot created to a remote replication cluster.,To enable specify 'true' value.\n attribute :enable_remote_replication\n validates :enable_remote_replication, type: Symbol\n\n # @return [Object, nil] Label used by SnapMirror software to specify snapshot retention policy on SnapMirror endpoint.\n attribute :snap_mirror_label\n\n # @return [String, nil] The date and time (format ISO 8601 date string) at which this snapshot will expire.\n attribute :expiration_time\n validates :expiration_time, type: String\n\n # @return [String, nil] Element OS access account password\n attribute :password\n validates :password, type: String\n\n # @return [String, nil] Element OS access account user-name\n attribute :username\n validates :username, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7259324789047241, "alphanum_fraction": 0.7301954030990601, "avg_line_length": 80.59420013427734, "blob_id": "b95ea5dd7d8af40aea31f6ac3285b9cbdd637737", "content_id": "34e4a289e5255be6ee158dcee5800d1fab330aee", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5630, "license_type": "permissive", "max_line_length": 558, "num_lines": 69, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_gtm_monitor_firepass.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages F5 BIG-IP GTM FirePass monitors.\n class Bigip_gtm_monitor_firepass < Base\n # @return [String] Monitor name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The parent template of this monitor template. Once this value has been set, it cannot be changed. By default, this value is the C(tcp) parent on the C(Common) partition.\n attribute :parent\n validates :parent, type: String\n\n # @return [String, nil] IP address part of the IP/port definition. If this parameter is not provided when creating a new monitor, then the default value will be '*'.,If this value is an IP address, then a C(port) number must be specified.\n attribute :ip\n validates :ip, type: String\n\n # @return [Integer, nil] Port address part of the IP/port definition. If this parameter is not provided when creating a new monitor, then the default value will be '*'. Note that if specifying an IP address, a value between 1 and 65535 must be specified.\n attribute :port\n validates :port, type: Integer\n\n # @return [Object, nil] The interval specifying how frequently the monitor instance of this template will run.,If this parameter is not provided when creating a new monitor, then the default value will be 30.,This value B(must) be less than the C(timeout) value.\n attribute :interval\n\n # @return [Object, nil] The number of seconds in which the node or service must respond to the monitor request. If the target responds within the set time period, it is considered up. If the target does not respond within the set time period, it is considered down. You can change this number to any number you want, however, it should be 3 times the interval number of seconds plus 1 second.,If this parameter is not provided when creating a new monitor, then the default value will be 90.\n attribute :timeout\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [:present, :absent, nil] When C(present), ensures that the monitor exists.,When C(absent), ensures the monitor is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the number of seconds after which the system times out the probe request to the system.,When creating a new monitor, if this parameter is not provided, then the default value will be C(5).\n attribute :probe_timeout\n\n # @return [Symbol, nil] Specifies that the monitor allows more than one probe attempt per interval.,When C(yes), specifies that the monitor ignores down responses for the duration of the monitor timeout. Once the monitor timeout is reached without the system receiving an up response, the system marks the object down.,When C(no), specifies that the monitor immediately marks an object down when it receives a down response.,When creating a new monitor, if this parameter is not provided, then the default value will be C(no).\n attribute :ignore_down_response\n validates :ignore_down_response, type: Symbol\n\n # @return [Object, nil] Specifies the user name, if the monitored target requires authentication.\n attribute :target_username\n\n # @return [Object, nil] Specifies the password, if the monitored target requires authentication.\n attribute :target_password\n\n # @return [:always, :on_create, nil] C(always) will update passwords if the C(target_password) is specified.,C(on_create) will only set the password for newly created monitors.\n attribute :update_password\n validates :update_password, expression_inclusion: {:in=>[:always, :on_create], :message=>\"%{value} needs to be :always, :on_create\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the list of ciphers for this monitor.,The items in the cipher list are separated with the colon C(:) symbol.,When creating a new monitor, if this parameter is not specified, the default list is C(HIGH:!ADH).\n attribute :cipher_list\n\n # @return [Object, nil] Specifies the number that the monitor uses to mark the Secure Access Manager system up or down.,The system compares the Max Load Average setting against a one-minute average of the Secure Access Manager system load.,When the Secure Access Manager system-load average falls within the specified Max Load Average, the monitor marks the Secure Access Manager system up.,When the average exceeds the setting, the monitor marks the system down.,When creating a new monitor, if this parameter is not specified, the default is C(12).\n attribute :max_load_average\n\n # @return [Object, nil] Specifies the maximum percentage of licensed connections currently in use under which the monitor marks the Secure Access Manager system up.,As an example, a setting of 95 percent means that the monitor marks the Secure Access Manager system up until 95 percent of licensed connections are in use.,When the number of in-use licensed connections exceeds 95 percent, the monitor marks the Secure Access Manager system down.,When creating a new monitor, if this parameter is not specified, the default is C(95).\n attribute :concurrency_limit\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7056783437728882, "alphanum_fraction": 0.708712637424469, "avg_line_length": 63.08333206176758, "blob_id": "ca232fd26af5c1b0f0a006a42f3ad645425ea9c9", "content_id": "54d0b37ea3355f31680a3422af5c5caee0174a96", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2307, "license_type": "permissive", "max_line_length": 413, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_snmp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manipulate general SNMP settings on a BIG-IP.\n class Bigip_snmp < Base\n # @return [Object, nil] Configures the IP addresses of the SNMP clients from which the snmpd daemon accepts requests.,This value can be hostnames, IP addresses, or IP networks.,You may specify a single list item of C(default) to set the value back to the system's default of C(127.0.0.0/8).,You can remove all allowed addresses by either providing the word C(none), or by providing the empty string C(\"\").\n attribute :allowed_addresses\n\n # @return [String, nil] Specifies the name of the person who administers the SNMP service for this system.\n attribute :contact\n validates :contact, type: String\n\n # @return [:enabled, :disabled, nil] When C(enabled), ensures that the system sends a trap whenever the SNMP agent starts running or stops running. This is usually enabled by default on a BIG-IP.\n attribute :agent_status_traps\n validates :agent_status_traps, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] When C(enabled), ensures that the system sends authentication warning traps to the trap destinations. This is usually disabled by default on a BIG-IP.\n attribute :agent_authentication_traps\n validates :agent_authentication_traps, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] When C(enabled), ensures that the system sends device warning traps to the trap destinations. This is usually enabled by default on a BIG-IP.\n attribute :device_warning_traps\n validates :device_warning_traps, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [String, nil] Specifies the description of this system's physical location.\n attribute :location\n validates :location, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.68694669008255, "alphanum_fraction": 0.6877001523971558, "avg_line_length": 57.988887786865234, "blob_id": "7770069eff8a9b15d090661ddad36d754177dd83", "content_id": "63cc1d1fb111d1e567ca835775a1ff25649a7aba", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5309, "license_type": "permissive", "max_line_length": 292, "num_lines": 90, "path": "/lib/ansible/ruby/modules/generated/monitoring/datadog_monitor.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages monitors within Datadog\n # Options like described on http://docs.datadoghq.com/api/\n class Datadog_monitor < Base\n # @return [String] Your DataDog API key.\n attribute :api_key\n validates :api_key, presence: true, type: String\n\n # @return [String] Your DataDog app key.\n attribute :app_key\n validates :app_key, presence: true, type: String\n\n # @return [:present, :absent, :mute, :unmute] The designated state of the monitor.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent, :mute, :unmute], :message=>\"%{value} needs to be :present, :absent, :mute, :unmute\"}\n\n # @return [Object, nil] A list of tags to associate with your monitor when creating or updating. This can help you categorize and filter monitors.\n attribute :tags\n\n # @return [:\"metric alert\", :\"service check\", :\"event alert\", nil] The type of the monitor.,The 'event alert'is available starting at Ansible 2.1\n attribute :type\n validates :type, expression_inclusion: {:in=>[:\"metric alert\", :\"service check\", :\"event alert\"], :message=>\"%{value} needs to be :\\\"metric alert\\\", :\\\"service check\\\", :\\\"event alert\\\"\"}, allow_nil: true\n\n # @return [String, nil] The monitor query to notify on with syntax varying depending on what type of monitor you are creating.\n attribute :query\n validates :query, type: String\n\n # @return [String] The name of the alert.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] A message to include with notifications for this monitor. Email notifications can be sent to specific users by using the same '@username' notation as events. Monitor message template variables can be accessed by using double square brackets, i.e '[[' and ']]'.\n attribute :message\n validates :message, type: String\n\n # @return [String, nil] Dictionary of scopes to timestamps or None. Each scope will be muted until the given POSIX timestamp or forever if the value is None. \n attribute :silenced\n validates :silenced, type: String\n\n # @return [:yes, :no, nil] A boolean indicating whether this monitor will notify when data stops reporting..\n attribute :notify_no_data\n validates :notify_no_data, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] The number of minutes before a monitor will notify when data stops reporting. Must be at least 2x the monitor timeframe for metric alerts or 2 minutes for service checks.\n attribute :no_data_timeframe\n validates :no_data_timeframe, type: Integer\n\n # @return [Object, nil] The number of hours of the monitor not reporting data before it will automatically resolve from a triggered state.\n attribute :timeout_h\n\n # @return [Object, nil] The number of minutes after the last notification before a monitor will re-notify on the current status. It will only re-notify if it's not resolved.\n attribute :renotify_interval\n\n # @return [Object, nil] A message to include with a re-notification. Supports the '@username' notification we allow elsewhere. Not applicable if renotify_interval is None\n attribute :escalation_message\n\n # @return [:yes, :no, nil] A boolean indicating whether tagged users will be notified on changes to this monitor.\n attribute :notify_audit\n validates :notify_audit, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] A dictionary of thresholds by status. This option is only available for service checks and metric alerts. Because each of them can have multiple thresholds, we don't define them directly in the query.\"]\n attribute :thresholds\n validates :thresholds, type: TypeGeneric.new(String)\n\n # @return [:yes, :no, nil] A boolean indicating whether changes to this monitor should be restricted to the creator or admins.\n attribute :locked\n validates :locked, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] A boolean indicating whether this monitor needs a full window of data before it's evaluated. We highly recommend you set this to False for sparse metrics, otherwise some evaluations will be skipped.\n attribute :require_full_window\n\n # @return [Object, nil] A positive integer representing the number of seconds to wait before evaluating the monitor for new hosts. This gives the host time to fully initialize.\n attribute :new_host_delay\n\n # @return [Object, nil] Time to delay evaluation (in seconds). It is effective for sparse values.\n attribute :evaluation_delay\n\n # @return [Object, nil] The id of the alert. If set, will be used instead of the name to locate the alert.\n attribute :id\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6484083533287048, "alphanum_fraction": 0.6484083533287048, "avg_line_length": 43.70512771606445, "blob_id": "533d248074ed3942d60dd8caddab9804cf58d890", "content_id": "dbb67ac309d6c639d6c3d4b0b1dd928b8d6ea95d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3487, "license_type": "permissive", "max_line_length": 187, "num_lines": 78, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_volume.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, destroy, attach, detach volumes.\n class Cs_volume < Base\n # @return [String] Name of the volume.,C(name) can only contain ASCII letters.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Account the volume is related to.\n attribute :account\n\n # @return [Object, nil] Custom id to the resource.,Allowed to Root Admins only.\n attribute :custom_id\n\n # @return [String, nil] Name of the disk offering to be used.,Required one of C(disk_offering), C(snapshot) if volume is not already C(state=present).\n attribute :disk_offering\n validates :disk_offering, type: String\n\n # @return [Boolean, nil] Whether to display the volume to the end user or not.,Allowed to Root Admins only.\n attribute :display_volume\n validates :display_volume, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] Name of the domain the volume to be deployed in.\n attribute :domain\n\n # @return [Object, nil] Max iops\n attribute :max_iops\n\n # @return [Object, nil] Min iops\n attribute :min_iops\n\n # @return [String, nil] Name of the project the volume to be deployed in.\n attribute :project\n validates :project, type: String\n\n # @return [Integer, nil] Size of disk in GB\n attribute :size\n validates :size, type: Integer\n\n # @return [Object, nil] The snapshot name for the disk volume.,Required one of C(disk_offering), C(snapshot) if volume is not already C(state=present).\n attribute :snapshot\n\n # @return [Boolean, nil] Force removal of volume even it is attached to a VM.,Considered on C(state=absnet) only.\n attribute :force\n validates :force, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Whether to allow to shrink the volume.\n attribute :shrink_ok\n validates :shrink_ok, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] Name of the virtual machine to attach the volume to.\n attribute :vm\n validates :vm, type: String\n\n # @return [String, nil] Name of the zone in which the volume should be deployed.,If not set, default zone is used.\n attribute :zone\n validates :zone, type: String\n\n # @return [:present, :absent, :attached, :detached, nil] State of the volume.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :attached, :detached], :message=>\"%{value} needs to be :present, :absent, :attached, :detached\"}, allow_nil: true\n\n # @return [Boolean, nil] Poll async jobs until job has finished.\n attribute :poll_async\n validates :poll_async, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] List of tags. Tags are a list of dictionaries having keys C(key) and C(value).,To delete all tags, set a empty list e.g. C(tags: []).\n attribute :tags\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6905781626701355, "alphanum_fraction": 0.6905781626701355, "avg_line_length": 36.36000061035156, "blob_id": "0084b9648623e7cc047e174aa53ee41e7d724569", "content_id": "52f28bed3167358862f56f2511066296c202a2e3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 934, "license_type": "permissive", "max_line_length": 128, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_networkinterface_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Get facts for a specific network interface or all network interfaces within a resource group.\n class Azure_rm_networkinterface_facts < Base\n # @return [String, nil] Only show results for a specific network interface.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] Name of the resource group containing the network interface(s). Required when searching by name.\n attribute :resource_group\n validates :resource_group, type: String\n\n # @return [Array<String>, String, nil] Limit results by providing a list of tags. Format tags as 'key' or 'key:value'.\n attribute :tags\n validates :tags, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.722403347492218, "alphanum_fraction": 0.7233349084854126, "avg_line_length": 70.56666564941406, "blob_id": "c2e391418029873aa519311ff250274cb67ac5ef", "content_id": "2186501cbe92c3a41acbf5765ca6f701af3b2be2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2147, "license_type": "permissive", "max_line_length": 718, "num_lines": 30, "path": "/lib/ansible/ruby/modules/generated/system/setup.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is automatically called by playbooks to gather useful variables about remote hosts that can be used in playbooks. It can also be executed directly by C(/usr/bin/ansible) to check what variables are available to a host. Ansible provides many I(facts) about the system, automatically.\n # This module is also supported for Windows targets.\n class Setup < Base\n # @return [String, nil] if supplied, restrict the additional facts collected to the given subset. Possible values: C(all), C(min), C(hardware), C(network), C(virtual), C(ohai), and C(facter). Can specify a list of values to specify a larger subset. Values can also be used with an initial C(!) to specify that that specific subset should not be collected. For instance: C(!hardware,!network,!virtual,!ohai,!facter). If C(!all) is specified then only the min subset is collected. To avoid collecting even the min subset, specify C(!all,!min). To collect only specific facts, use C(!all,!min), and specify the particular fact subsets. Use the filter parameter if you do not want to display some collected facts.\n attribute :gather_subset\n validates :gather_subset, type: String\n\n # @return [Integer, nil] Set the default timeout in seconds for individual fact gathering\n attribute :gather_timeout\n validates :gather_timeout, type: Integer\n\n # @return [String, nil] if supplied, only return facts that match this shell-style (fnmatch) wildcard.\n attribute :filter\n validates :filter, type: String\n\n # @return [String, nil] path used for local ansible facts (C(*.fact)) - files in this dir will be run (if executable) and their results be added to C(ansible_local) facts if a file is not executable it is read. Check notes for Windows options. (from 2.1 on) File/results format can be json or ini-format\n attribute :fact_path\n validates :fact_path, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.679401159286499, "alphanum_fraction": 0.679401159286499, "avg_line_length": 46.24390411376953, "blob_id": "10b4f5389cd89b76cb38286608825e216ef56016", "content_id": "9da6cb4e8631e8de9278ff76aaa5f1f8bc670d52", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1937, "license_type": "permissive", "max_line_length": 166, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_seproperties.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure SeProperties object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_seproperties < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Object, nil] Seagentproperties settings for seproperties.\n attribute :se_agent_properties\n\n # @return [Object, nil] Sebootupproperties settings for seproperties.\n attribute :se_bootup_properties\n\n # @return [Object, nil] Seruntimeproperties settings for seproperties.\n attribute :se_runtime_properties\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Unique object identifier of the object.,Default value when not specified in API or module is interpreted by Avi Controller as default.\n attribute :uuid\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6998079419136047, "alphanum_fraction": 0.7011375427246094, "avg_line_length": 70.25263214111328, "blob_id": "101328585c9a1e838438c21daab2c8f725be644b", "content_id": "1cd15bf5e4b036acbc5c64968526fcd3a892cfb9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6769, "license_type": "permissive", "max_line_length": 552, "num_lines": 95, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_disk.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Module to manage Virtual Machine and floating disks in oVirt/RHV.\n class Ovirt_disk < Base\n # @return [String, nil] ID of the disk to manage. Either C(id) or C(name) is required.\n attribute :id\n validates :id, type: String\n\n # @return [String, nil] Name of the disk to manage. Either C(id) or C(name)/C(alias) is required.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] Description of the disk image to manage.\n attribute :description\n validates :description, type: String\n\n # @return [String, nil] Name of the Virtual Machine to manage. Either C(vm_id) or C(vm_name) is required if C(state) is I(attached) or I(detached).\n attribute :vm_name\n validates :vm_name, type: String\n\n # @return [Object, nil] ID of the Virtual Machine to manage. Either C(vm_id) or C(vm_name) is required if C(state) is I(attached) or I(detached).\n attribute :vm_id\n\n # @return [:present, :absent, :attached, :detached, nil] Should the Virtual Machine disk be present/absent/attached/detached.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :attached, :detached], :message=>\"%{value} needs to be :present, :absent, :attached, :detached\"}, allow_nil: true\n\n # @return [String, nil] Path on a file system where disk should be downloaded.,Note that you must have an valid oVirt/RHV engine CA in your system trust store or you must provide it in C(ca_file) parameter.,Note that the disk is not downloaded when the file already exists, but you can forcibly download the disk when using C(force) I (true).\n attribute :download_image_path\n validates :download_image_path, type: String\n\n # @return [Object, nil] Path to disk image, which should be uploaded.,Note that currently we support only compatibility version 0.10 of the qcow disk.,Note that you must have an valid oVirt/RHV engine CA in your system trust store or you must provide it in C(ca_file) parameter.,Note that there is no reliable way to achieve idempotency, so if you want to upload the disk even if the disk with C(id) or C(name) exists, then please use C(force) I(true). If you will use C(force) I(false), which is default, then the disk image won't be uploaded.\n attribute :upload_image_path\n\n # @return [String, nil] Size of the disk. Size should be specified using IEC standard units. For example 10GiB, 1024MiB, etc.,Size can be only increased, not decreased.\n attribute :size\n validates :size, type: String\n\n # @return [:virtio, :ide, :virtio_scsi, nil] Driver of the storage interface.,It's required parameter when creating the new disk.\n attribute :interface\n validates :interface, expression_inclusion: {:in=>[:virtio, :ide, :virtio_scsi], :message=>\"%{value} needs to be :virtio, :ide, :virtio_scsi\"}, allow_nil: true\n\n # @return [:raw, :cow, nil] Specify format of the disk.,Note that this option isn't idempotent as it's not currently possible to change format of the disk via API.\n attribute :format\n validates :format, expression_inclusion: {:in=>[:raw, :cow], :message=>\"%{value} needs to be :raw, :cow\"}, allow_nil: true\n\n # @return [Object, nil] I(True) if the disk should be sparse (also known as I(thin provision)). If the parameter is omitted, cow disks will be created as sparse and raw disks as I(preallocated),Note that this option isn't idempotent as it's not currently possible to change sparseness of the disk via API.\n attribute :sparse\n\n # @return [String, nil] Storage domain name where disk should be created. By default storage is chosen by oVirt/RHV engine.\n attribute :storage_domain\n validates :storage_domain, type: String\n\n # @return [Object, nil] Storage domain names where disk should be copied.,C(**IMPORTANT**),There is no reliable way to achieve idempotency, so every time you specify this parameter the disks are copied, so please handle your playbook accordingly to not copy the disks all the time. This is valid only for VM and floating disks, template disks works as expected.\n attribute :storage_domains\n\n # @return [Object, nil] Please take a look at C(image_path) documentation to see the correct usage of this parameter.\n attribute :force\n\n # @return [Object, nil] Disk profile name to be attached to disk. By default profile is chosen by oVirt/RHV engine.\n attribute :profile\n\n # @return [String, nil] Disk quota ID to be used for disk. By default quota is chosen by oVirt/RHV engine.\n attribute :quota_id\n validates :quota_id, type: String\n\n # @return [Object, nil] I(True) if the disk should be bootable. By default when disk is created it isn't bootable.\n attribute :bootable\n\n # @return [Object, nil] I(True) if the disk should be shareable. By default when disk is created it isn't shareable.\n attribute :shareable\n\n # @return [Hash, nil] Dictionary which describes LUN to be directly attached to VM:,C(address) - Address of the storage server. Used by iSCSI.,C(port) - Port of the storage server. Used by iSCSI.,C(target) - iSCSI target.,C(lun_id) - LUN id.,C(username) - CHAP Username to be used to access storage server. Used by iSCSI.,C(password) - CHAP Password of the user to be used to access storage server. Used by iSCSI.,C(storage_type) - Storage type either I(fcp) or I(iscsi).\n attribute :logical_unit\n validates :logical_unit, type: Hash\n\n # @return [Object, nil] I(True) if the disk should be sparsified.,Sparsification frees space in the disk image that is not used by its filesystem. As a result, the image will occupy less space on the storage.,Note that this parameter isn't idempotent, as it's not possible to check if the disk should be or should not be sparsified.\n attribute :sparsify\n\n # @return [Object, nil] Name of the openstack volume type. This is valid when working with cinder.\n attribute :openstack_volume_type\n\n # @return [String, nil] When C(state) is I(exported) disk is exported to given Glance image provider.,C(**IMPORTANT**),There is no reliable way to achieve idempotency, so every time you specify this parameter the disk is exported, so please handle your playbook accordingly to not export the disk all the time. This option is valid only for template disks.\n attribute :image_provider\n validates :image_provider, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7009475827217102, "alphanum_fraction": 0.7079152464866638, "avg_line_length": 84.42857360839844, "blob_id": "7c35fedffe834234474ebb7889a1ab466d32c030", "content_id": "143846f9b1bb079a1989d91cefdbabdec2ca9fa8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3592, "license_type": "permissive", "max_line_length": 668, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/remote_management/ucs/ucs_vlans.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configures VLANs on Cisco UCS Manager.\n # Examples can be used with the UCS Platform Emulator U(https://communities.cisco.com/ucspe).\n class Ucs_vlans < Base\n # @return [:present, :absent, nil] If C(present), will verify VLANs are present and will create if needed.,If C(absent), will verify VLANs are absent and will delete if needed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The name assigned to the VLAN.,The VLAN name is case sensitive.,This name can be between 1 and 32 alphanumeric characters.,You cannot use spaces or any special characters other than - (hyphen), \"_\" (underscore), : (colon), and . (period).,You cannot change this name after the VLAN is created.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The multicast policy associated with this VLAN.,This option is only valid if the Sharing Type field is set to None or Primary.\n attribute :multicast_policy\n validates :multicast_policy, type: String\n\n # @return [:common, :A, :B, nil] The fabric configuration of the VLAN. This can be one of the following:,common - The VLAN applies to both fabrics and uses the same configuration parameters in both cases.,A — The VLAN only applies to fabric A.,B — The VLAN only applies to fabric B.,For upstream disjoint L2 networks, Cisco recommends that you choose common to create VLANs that apply to both fabrics.\n attribute :fabric\n validates :fabric, expression_inclusion: {:in=>[:common, :A, :B], :message=>\"%{value} needs to be :common, :A, :B\"}, allow_nil: true\n\n # @return [String] The unique string identifier assigned to the VLAN.,A VLAN ID can be between '1' and '3967', or between '4048' and '4093'.,You cannot create VLANs with IDs from 4030 to 4047. This range of VLAN IDs is reserved.,The VLAN IDs you specify must also be supported on the switch that you are using.,VLANs in the LAN cloud and FCoE VLANs in the SAN cloud must have different IDs.,Optional if state is absent.\n attribute :id\n validates :id, presence: true, type: String\n\n # @return [:none, :primary, :isolated, :community, nil] The Sharing Type field.,Whether this VLAN is subdivided into private or secondary VLANs. This can be one of the following:,none - This VLAN does not have any secondary or private VLANs. This is a regular VLAN.,primary - This VLAN can have one or more secondary VLANs, as shown in the Secondary VLANs area. This VLAN is a primary VLAN in the private VLAN domain.,isolated - This is a private VLAN associated with a primary VLAN. This VLAN is an Isolated VLAN.,community - This VLAN can communicate with other ports on the same community VLAN as well as the promiscuous port. This VLAN is a Community VLAN.\n attribute :sharing\n validates :sharing, expression_inclusion: {:in=>[:none, :primary, :isolated, :community], :message=>\"%{value} needs to be :none, :primary, :isolated, :community\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Designates the VLAN as a native VLAN.\n attribute :native\n validates :native, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6712121367454529, "alphanum_fraction": 0.6712121367454529, "avg_line_length": 29, "blob_id": "8ca0cb1f82c73c84bee78690efc5098b8f417885", "content_id": "50897adbc60fd291edbfe95f508f217cb6385902", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 660, "license_type": "permissive", "max_line_length": 81, "num_lines": 22, "path": "/lib/ansible/ruby/modules/generated/network/panos/panos_check.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Check if PAN-OS device is ready for being configured (no pending jobs).\n # The check could be done once or multiple times until the device is ready.\n class Panos_check < Base\n # @return [String, nil] timeout of API calls\n attribute :timeout\n validates :timeout, type: String\n\n # @return [String, nil] time waited between checks\n attribute :interval\n validates :interval, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7252252101898193, "alphanum_fraction": 0.7252252101898193, "avg_line_length": 60.66666793823242, "blob_id": "5f4474a93ac00f4bec261bbff84b5566cda972b4", "content_id": "8eba3af80af808d3e615a3708b83ef0b7bca5ed4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1110, "license_type": "permissive", "max_line_length": 442, "num_lines": 18, "path": "/lib/ansible/ruby/modules/generated/cloud/digital_ocean/digital_ocean_image_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to gather facts about DigitalOcean provided images.\n # These images can be either of type C(distribution), C(application) and C(private).\n class Digital_ocean_image_facts < Base\n # @return [:all, :application, :distribution, :private, nil] Specifies the type of image facts to be retrived.,If set to C(application), then facts are gathered related to all application images.,If set to C(distribution), then facts are gathered related to all distribution images.,If set to C(private), then facts are gathered related to all private images.,If not set to any of above, then facts are gathered related to all images.\n attribute :image_type\n validates :image_type, expression_inclusion: {:in=>[:all, :application, :distribution, :private], :message=>\"%{value} needs to be :all, :application, :distribution, :private\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6615384817123413, "alphanum_fraction": 0.6615384817123413, "avg_line_length": 47.75, "blob_id": "18b390057772382ad586e758c9a30198a2bfc4c6", "content_id": "ef48cc1d4dd1b2624bf6015a15f7ac9cfba4f17d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2145, "license_type": "permissive", "max_line_length": 187, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/database/misc/riak.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to join nodes to a cluster, check the status of the cluster.\n class Riak < Base\n # @return [:ping, :kv_test, :join, :plan, :commit, nil] The command you would like to perform against the cluster.\n attribute :command\n validates :command, expression_inclusion: {:in=>[:ping, :kv_test, :join, :plan, :commit], :message=>\"%{value} needs to be :ping, :kv_test, :join, :plan, :commit\"}, allow_nil: true\n\n # @return [String, nil] The path to the riak configuration directory\n attribute :config_dir\n validates :config_dir, type: String\n\n # @return [String, nil] The ip address and port that is listening for Riak HTTP queries\n attribute :http_conn\n validates :http_conn, type: String\n\n # @return [String, nil] The target node for certain operations (join, ping)\n attribute :target_node\n validates :target_node, type: String\n\n # @return [Boolean, nil] Number of seconds to wait for handoffs to complete.\n attribute :wait_for_handoffs\n validates :wait_for_handoffs, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] Number of seconds to wait for all nodes to agree on the ring.\n attribute :wait_for_ring\n\n # @return [:kv, nil] Waits for a riak service to come online before continuing.\n attribute :wait_for_service\n validates :wait_for_service, expression_inclusion: {:in=>[:kv], :message=>\"%{value} needs to be :kv\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6902561187744141, "alphanum_fraction": 0.6902561187744141, "avg_line_length": 55.52238845825195, "blob_id": "12c0a6c8cc3fd018cda6fa1c58d3408cec884a56", "content_id": "39198f20581fb630616fa9e4de652fc007f3037d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3787, "license_type": "permissive", "max_line_length": 236, "num_lines": 67, "path": "/lib/ansible/ruby/modules/generated/identity/ipa/ipa_hbacrule.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add, modify or delete an IPA HBAC rule using IPA API.\n class Ipa_hbacrule < Base\n # @return [Object] Canonical name.,Can not be changed as it is the unique identifier.\n attribute :cn\n validates :cn, presence: true\n\n # @return [String, nil] Description\n attribute :description\n validates :description, type: String\n\n # @return [Object, nil] List of host names to assign.,If an empty list is passed all hosts will be removed from the rule.,If option is omitted hosts will not be checked or changed.\n attribute :host\n\n # @return [:all, nil] Host category\n attribute :hostcategory\n validates :hostcategory, expression_inclusion: {:in=>[:all], :message=>\"%{value} needs to be :all\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] List of hostgroup names to assign.,If an empty list is passed all hostgroups will be removed. from the rule,If option is omitted hostgroups will not be checked or changed.\n attribute :hostgroup\n validates :hostgroup, type: TypeGeneric.new(String)\n\n # @return [Object, nil] List of service names to assign.,If an empty list is passed all services will be removed from the rule.,If option is omitted services will not be checked or changed.\n attribute :service\n\n # @return [:all, nil] Service category\n attribute :servicecategory\n validates :servicecategory, expression_inclusion: {:in=>[:all], :message=>\"%{value} needs to be :all\"}, allow_nil: true\n\n # @return [Object, nil] List of service group names to assign.,If an empty list is passed all assigned service groups will be removed from the rule.,If option is omitted service groups will not be checked or changed.\n attribute :servicegroup\n\n # @return [Object, nil] List of source host names to assign.,If an empty list if passed all assigned source hosts will be removed from the rule.,If option is omitted source hosts will not be checked or changed.\n attribute :sourcehost\n\n # @return [:all, nil] Source host category\n attribute :sourcehostcategory\n validates :sourcehostcategory, expression_inclusion: {:in=>[:all], :message=>\"%{value} needs to be :all\"}, allow_nil: true\n\n # @return [Object, nil] List of source host group names to assign.,If an empty list if passed all assigned source host groups will be removed from the rule.,If option is omitted source host groups will not be checked or changed.\n attribute :sourcehostgroup\n\n # @return [:present, :absent, :enabled, :disabled, nil] State to ensure\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :enabled, :disabled], :message=>\"%{value} needs to be :present, :absent, :enabled, :disabled\"}, allow_nil: true\n\n # @return [Object, nil] List of user names to assign.,If an empty list if passed all assigned users will be removed from the rule.,If option is omitted users will not be checked or changed.\n attribute :user\n\n # @return [:all, nil] User category\n attribute :usercategory\n validates :usercategory, expression_inclusion: {:in=>[:all], :message=>\"%{value} needs to be :all\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] List of user group names to assign.,If an empty list if passed all assigned user groups will be removed from the rule.,If option is omitted user groups will not be checked or changed.\n attribute :usergroup\n validates :usergroup, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5164017677307129, "alphanum_fraction": 0.5222635269165039, "avg_line_length": 25.014663696289062, "blob_id": "2e65b9af0da3aae85390260049635f1ad51522a7", "content_id": "d6a20ae887fa46b52ea2f8d5cd5ae9e44c083a80", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 8871, "license_type": "permissive", "max_line_length": 114, "num_lines": 341, "path": "/lib/ansible/ruby/dsl_builders/tasks_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# See LICENSE.txt for license\nrequire 'spec_helper'\nrequire 'ansible-ruby'\n\ndescribe Ansible::Ruby::DslBuilders::Tasks do\n let(:context) { :tasks }\n let(:builder) { Ansible::Ruby::DslBuilders::Tasks.new context }\n\n def evaluate\n builder.instance_eval ruby\n builder._result\n end\n\n subject(:tasks) { evaluate }\n\n before do\n klass = Class.new(Ansible::Ruby::Modules::Base) do\n attribute :src\n validates :src, presence: true\n attribute :dest\n validates :dest, presence: true\n end\n stub_const 'Ansible::Ruby::Modules::Copy', klass\n end\n\n context 'task' do\n let(:ruby) do\n <<-RUBY\n task 'Copy something' do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n end\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Tasks }\n it do\n is_expected.to have_attributes items: include(be_a(Ansible::Ruby::Models::Task))\n end\n\n describe 'hash keys' do\n subject { tasks.items.map { |task| task.to_h.stringify_keys.keys } }\n\n it { is_expected.to eq [%w[name copy]] }\n end\n end\n\n context 'register variables' do\n context 'no usage outside of task' do\n let(:ruby) do\n <<-RUBY\n task 'Copy something' do\n result = copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n\n changed_when \"'No upgrade available' not in \\#{result.stdout}\"\n end\n task 'middle task' do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n end\n task 'Copy something else' do\n result = copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n\n changed_when \"'yes' not in \\#{result.stdout}\"\n end\n RUBY\n end\n\n describe 'task 1' do\n subject { tasks.items[0] }\n\n it do\n is_expected.to have_attributes register: 'result_1',\n changed_when: \"'No upgrade available' not in result_1.stdout\"\n end\n end\n\n describe 'task 3' do\n subject { tasks.items[2] }\n\n it do\n is_expected.to have_attributes register: 'result_4',\n changed_when: \"'yes' not in result_4.stdout\"\n end\n end\n end\n\n context 'usage between tasks' do\n let(:ruby) do\n <<-RUBY\n stuff = task 'Copy something' do\n result = copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n\n changed_when \"'No upgrade available' not in \\#{result.stdout}\"\n end\n\n task 'Copy something else' do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n\n ansible_when \"'yes' not in \\#{stuff.stdout}\"\n end\n RUBY\n end\n\n it 'uses result from first task' do\n items = tasks.items\n expect(items[0]).to have_attributes register: 'result_5',\n changed_when: \"'No upgrade available' not in result_5.stdout\"\n second = items[1]\n expect(second).to have_attributes when: \"'yes' not in result_5.stdout\",\n register: nil\n end\n end\n\n context 'usage between task without use in first task' do\n let(:ruby) do\n <<-RUBY\n stuff = task 'Copy something' do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n end\n\n task 'Copy something else' do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n\n ansible_when \"'yes' not in \\#{stuff.stdout}\"\n end\n RUBY\n end\n\n it 'uses result from first task' do\n items = tasks.items\n expect(items[0]).to have_attributes register: 'result_6'\n second = items[1]\n expect(second).to have_attributes when: \"'yes' not in result_6.stdout\",\n register: nil\n end\n end\n\n context 'usage within tasks and multiple register' do\n let(:ruby) do\n <<-RUBY\n stuff = task 'Copy something' do\n result = copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n\n changed_when \"'No upgrade available' not in \\#{result.stdout}\"\n end\n task 'Copy something else' do\n result = copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n\n changed_when \"'yes' not in \\#{result.stdout}\"\n ansible_when \"'yes' not in \\#{stuff.stdout}\"\n end\n RUBY\n end\n\n it 'uses result from first task' do\n items = tasks.items\n expect(items[0]).to have_attributes register: 'result_7',\n changed_when: \"'No upgrade available' not in result_7.stdout\"\n second = items[1]\n expect(second).to have_attributes when: \"'yes' not in result_7.stdout\",\n register: 'result_8',\n changed_when: \"'yes' not in result_8.stdout\"\n end\n end\n end\n\n context 'include' do\n subject(:inclusion) { tasks.inclusions.first }\n\n context 'with tasks' do\n subject { evaluate }\n\n let(:ruby) do\n <<-RUBY\n ansible_include '/some_file.yml'\n\n task 'Copy something' do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n end\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Tasks }\n it do\n is_expected.to have_attributes items: include(be_a(Ansible::Ruby::Models::Task)),\n inclusions: include(be_a(Ansible::Ruby::Models::Inclusion))\n end\n\n describe 'inclusion' do\n subject { inclusion }\n\n it { is_expected.to have_attributes file: '/some_file.yml' }\n end\n end\n\n context 'with variables' do\n let(:ruby) do\n <<-RUBY\n ansible_include '/some_file.yml' do\n static true\n variables stuff: true\n end\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Inclusion }\n it do\n is_expected.to have_attributes file: '/some_file.yml',\n static: true,\n variables: { stuff: true }\n end\n end\n\n context 'jinja' do\n let(:ruby) do\n <<-RUBY\n ansible_include '/some_file.yml' do\n static true\n variables stuff: jinja('toodles')\n end\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Inclusion }\n it do\n is_expected.to have_attributes file: '/some_file.yml',\n variables: { stuff: Ansible::Ruby::Models::JinjaExpression.new('toodles') }\n end\n end\n\n context 'static' do\n let(:ruby) do\n <<-RUBY\n ansible_include '/some_file.yml' do\n static true\n end\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Inclusion }\n it do\n is_expected.to have_attributes file: '/some_file.yml',\n static: true\n end\n end\n end\n\n context 'invalid method' do\n let(:ruby) { 'foobar()' }\n\n context 'tasks context' do\n let(:context) { :tasks }\n\n it 'should raise an error' do\n expect {evaluate}.to raise_error \"Invalid method/local variable `foobar'. Only [:task] is valid\"\n end\n end\n\n context 'handler context' do\n let(:context) { :handlers }\n\n it 'should raise an error' do\n expect {evaluate}.to raise_error \"Invalid method/local variable `foobar'. Only [:handler] is valid\"\n end\n end\n end\n\n context 'no name supplied' do\n %i[handlers tasks].each do |type|\n context type do\n let(:context) { type }\n let(:singular) { type[0..-2] }\n let(:ruby) { \"#{singular} { copy { src 'file1'\\n dest 'file2'} }\" }\n\n it 'should raise an error' do\n expect {evaluate}.to raise_error \"Validation failed: Name can't be blank\"\n end\n end\n end\n end\n\n context 'handler' do\n let(:context) { :handlers }\n\n let(:ruby) do\n <<-RUBY\n handler 'Copy something' do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n end\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Tasks }\n it do\n is_expected.to have_attributes items: include(be_a(Ansible::Ruby::Models::Handler))\n end\n\n describe 'hash keys' do\n subject { tasks.items.map { |task| task.to_h.stringify_keys.keys } }\n\n it { is_expected.to eq [%w[name copy]] }\n end\n end\nend\n" }, { "alpha_fraction": 0.653085470199585, "alphanum_fraction": 0.653085470199585, "avg_line_length": 37.30303192138672, "blob_id": "7cde757baa2d84c7bddad49d985487d95d03b83e", "content_id": "f8c9b8d571bd9b8e5e0b75efe4523c0808495bdb", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2528, "license_type": "permissive", "max_line_length": 143, "num_lines": 66, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_image.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or Remove images from the OpenStack Image Repository\n class Os_image < Base\n # @return [String] Name that has to be given to the image\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] The Id of the image\n attribute :id\n\n # @return [Object, nil] The checksum of the image\n attribute :checksum\n\n # @return [String, nil] The format of the disk that is getting uploaded\n attribute :disk_format\n validates :disk_format, type: String\n\n # @return [String, nil] The format of the container\n attribute :container_format\n validates :container_format, type: String\n\n # @return [Object, nil] The owner of the image\n attribute :owner\n\n # @return [Object, nil] The minimum disk space (in GB) required to boot this image\n attribute :min_disk\n\n # @return [Object, nil] The minimum ram (in MB) required to boot this image\n attribute :min_ram\n\n # @return [:yes, :no, nil] Whether the image can be accessed publicly. Note that publicizing an image requires admin role by default.\n attribute :is_public\n validates :is_public, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] The path to the file which has to be uploaded\n attribute :filename\n validates :filename, type: String\n\n # @return [String, nil] The name of an existing ramdisk image that will be associated with this image\n attribute :ramdisk\n validates :ramdisk, type: String\n\n # @return [String, nil] The name of an existing kernel image that will be associated with this image\n attribute :kernel\n validates :kernel, type: String\n\n # @return [Object, nil] Additional properties to be associated with this image\n attribute :properties\n\n # @return [:present, :absent, nil] Should the resource be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6662738919258118, "alphanum_fraction": 0.6728729605674744, "avg_line_length": 44.13829803466797, "blob_id": "2d45e9738dd8fac34f5862dae98701cb3f267134", "content_id": "cf71df8635e261759dc363906e474eef0ff47ed7", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4243, "license_type": "permissive", "max_line_length": 195, "num_lines": 94, "path": "/lib/ansible/ruby/modules/generated/network/netvisor/pn_vrouterbgp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Execute vrouter-bgp-add, vrouter-bgp-remove, vrouter-bgp-modify command.\n # Each fabric, cluster, standalone switch, or virtual network (VNET) can provide its tenants with a vRouter service that forwards traffic between networks and implements Layer 4 protocols.\n class Pn_vrouterbgp < Base\n # @return [Object, nil] Provide login username if user is not root.\n attribute :pn_cliusername\n\n # @return [Object, nil] Provide login password if user is not root.\n attribute :pn_clipassword\n\n # @return [Object, nil] Target switch(es) to run the cli on.\n attribute :pn_cliswitch\n\n # @return [:present, :absent, :update] State the action to perform. Use 'present' to add bgp, 'absent' to remove bgp and 'update' to modify bgp.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent, :update], :message=>\"%{value} needs to be :present, :absent, :update\"}\n\n # @return [String] Specify a name for the vRouter service.\n attribute :pn_vrouter_name\n validates :pn_vrouter_name, presence: true, type: String\n\n # @return [String, nil] Specify a neighbor IP address to use for BGP.,Required for vrouter-bgp-add.\n attribute :pn_neighbor\n validates :pn_neighbor, type: String\n\n # @return [Integer, nil] Specify the remote Autonomous System(AS) number. This value is between 1 and 4294967295.,Required for vrouter-bgp-add.\n attribute :pn_remote_as\n validates :pn_remote_as, type: Integer\n\n # @return [Object, nil] Specify if the next-hop is the same router or not.\n attribute :pn_next_hop_self\n\n # @return [Object, nil] Specify a password, if desired.\n attribute :pn_password\n\n # @return [Object, nil] Specify a value for external BGP to accept or attempt BGP connections to external peers, not directly connected, on the network. This is a value between 1 and 255.\n attribute :pn_ebgp\n\n # @return [Object, nil] Specify the prefix list to filter traffic inbound.\n attribute :pn_prefix_listin\n\n # @return [Object, nil] Specify the prefix list to filter traffic outbound.\n attribute :pn_prefix_listout\n\n # @return [Object, nil] Specify if a route reflector client is used.\n attribute :pn_route_reflector\n\n # @return [Object, nil] Specify if you want to override capability.\n attribute :pn_override_capability\n\n # @return [Object, nil] Specify if you want a soft reconfiguration of inbound traffic.\n attribute :pn_soft_reconfig\n\n # @return [Object, nil] Specify the maximum number of prefixes.\n attribute :pn_max_prefix\n\n # @return [Object, nil] Specify if you want a warning message when the maximum number of prefixes is exceeded.\n attribute :pn_max_prefix_warn\n\n # @return [Object, nil] Specify if you want BFD protocol support for fault detection.\n attribute :pn_bfd\n\n # @return [:\"ipv4-unicast\", :\"ipv6-unicast\", nil] Specify a multi-protocol for BGP.\n attribute :pn_multiprotocol\n validates :pn_multiprotocol, expression_inclusion: {:in=>[:\"ipv4-unicast\", :\"ipv6-unicast\"], :message=>\"%{value} needs to be :\\\"ipv4-unicast\\\", :\\\"ipv6-unicast\\\"\"}, allow_nil: true\n\n # @return [Object, nil] Specify a default weight value between 0 and 65535 for the neighbor routes.\n attribute :pn_weight\n\n # @return [Object, nil] Specify if you want announce default routes to the neighbor or not.\n attribute :pn_default_originate\n\n # @return [Object, nil] Specify BGP neighbor keepalive interval in seconds.\n attribute :pn_keepalive\n\n # @return [Object, nil] Specify BGP neighbor holdtime in seconds.\n attribute :pn_holdtime\n\n # @return [Object, nil] Specify inbound route map for neighbor.\n attribute :pn_route_mapin\n\n # @return [Object, nil] Specify outbound route map for neighbor.\n attribute :pn_route_mapout\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6695682406425476, "alphanum_fraction": 0.6695682406425476, "avg_line_length": 50.28571319580078, "blob_id": "a1826826a9e296c55015688f46b9727cac7e95da", "content_id": "def356ece75a5504df4e76bac3625af9f1e17049", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2872, "license_type": "permissive", "max_line_length": 228, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_floating_ip.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or Remove a floating IP to an instance\n class Os_floating_ip < Base\n # @return [String] The name or ID of the instance to which the IP address should be assigned.\n attribute :server\n validates :server, presence: true, type: String\n\n # @return [String, nil] The name or ID of a neutron external network or a nova pool name.\n attribute :network\n validates :network, type: String\n\n # @return [String, nil] A floating IP address to attach or to detach. Required only if I(state) is absent. When I(state) is present can be used to specify a IP address to attach.\n attribute :floating_ip_address\n validates :floating_ip_address, type: String\n\n # @return [:yes, :no, nil] When I(state) is present, and I(floating_ip_address) is not present, this parameter can be used to specify whether we should try to reuse a floating IP address already allocated to the project.\n attribute :reuse\n validates :reuse, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] To which fixed IP of server the floating IP address should be attached to.\n attribute :fixed_address\n validates :fixed_address, type: String\n\n # @return [String, nil] The name or id of a neutron private network that the fixed IP to attach floating IP is on\n attribute :nat_destination\n validates :nat_destination, type: String\n\n # @return [:yes, :no, nil] When attaching a floating IP address, specify whether we should wait for it to appear as attached.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Time to wait for an IP address to appear as attached. See wait.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [:present, :absent, nil] Should the resource be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:yes, :no, nil] When I(state) is absent, indicates whether or not to delete the floating IP completely, or only detach it from the server. Default is to detach only.\n attribute :purge\n validates :purge, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6412742137908936, "alphanum_fraction": 0.6412742137908936, "avg_line_length": 31.08888816833496, "blob_id": "9ff597f4ed51942fcd6c5e4053233c87410b1ad3", "content_id": "561d8804acf38fa203052928adbfb72561b1a86f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1444, "license_type": "permissive", "max_line_length": 128, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/network/panos/panos_pg.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create a security profile group\n class Panos_pg < Base\n # @return [String] name of the security profile group\n attribute :pg_name\n validates :pg_name, presence: true, type: String\n\n # @return [Object, nil] name of the data filtering profile\n attribute :data_filtering\n\n # @return [Object, nil] name of the file blocking profile\n attribute :file_blocking\n\n # @return [String, nil] name of the spyware profile\n attribute :spyware\n validates :spyware, type: String\n\n # @return [Object, nil] name of the url filtering profile\n attribute :url_filtering\n\n # @return [String, nil] name of the anti-virus profile\n attribute :virus\n validates :virus, type: String\n\n # @return [String, nil] name of the vulnerability profile\n attribute :vulnerability\n validates :vulnerability, type: String\n\n # @return [Object, nil] name of the wildfire analysis profile\n attribute :wildfire\n\n # @return [:yes, :no, nil] commit if changed\n attribute :commit\n validates :commit, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6825061440467834, "alphanum_fraction": 0.6825061440467834, "avg_line_length": 48.842105865478516, "blob_id": "6de41b54a80d82f568de32c069d2246e4619c8a5", "content_id": "62d03eaf92e4a2de5bfdcf0dfb9460ad3ce33293", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2841, "license_type": "permissive", "max_line_length": 196, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_access_port_to_interface_policy_leaf_profile.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage Fabric interface policy leaf profile interface selectors on Cisco ACI fabrics.\n class Aci_access_port_to_interface_policy_leaf_profile < Base\n # @return [String] The name of the Fabric access policy leaf interface profile.\n attribute :leaf_interface_profile\n validates :leaf_interface_profile, presence: true, type: String\n\n # @return [String] The name of the Fabric access policy leaf interface profile access port selector.\n attribute :access_port_selector\n validates :access_port_selector, presence: true, type: String\n\n # @return [Object, nil] The description to assign to the C(access_port_selector)\n attribute :description\n\n # @return [String] The name of the Fabric access policy leaf interface profile access port block.\n attribute :leaf_port_blk\n validates :leaf_port_blk, presence: true, type: String\n\n # @return [Object, nil] The description to assign to the C(leaf_port_blk)\n attribute :leaf_port_blk_description\n\n # @return [Integer] The beginning (from-range) of the port range block for the leaf access port block.\n attribute :from_port\n validates :from_port, presence: true, type: Integer\n\n # @return [Integer] The end (to-range) of the port range block for the leaf access port block.\n attribute :to_port\n validates :to_port, presence: true, type: Integer\n\n # @return [Object, nil] The beginning (from-range) of the card range block for the leaf access port block.\n attribute :from_card\n\n # @return [Object, nil] The end (to-range) of the card range block for the leaf access port block.\n attribute :to_card\n\n # @return [String, nil] The name of the fabric access policy group to be associated with the leaf interface profile interface selector.\n attribute :policy_group\n validates :policy_group, type: String\n\n # @return [:fex, :port_channel, :switch_port, :vpc, nil] The type of interface for the static EPG deployement.\n attribute :interface_type\n validates :interface_type, expression_inclusion: {:in=>[:fex, :port_channel, :switch_port, :vpc], :message=>\"%{value} needs to be :fex, :port_channel, :switch_port, :vpc\"}, allow_nil: true\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6709876656532288, "alphanum_fraction": 0.6709876656532288, "avg_line_length": 42.783782958984375, "blob_id": "86e942b3c633571feed151bcdaf32f2235cb87b8", "content_id": "603d5d8f8eba05404c6d21b6cba38a91294e66ad", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1620, "license_type": "permissive", "max_line_length": 143, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ecs_ecr.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage Elastic Container Registry repositories\n class Ecs_ecr < Base\n # @return [String] the name of the repository\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] AWS account id associated with the registry.,If not specified, the default registry is assumed.\n attribute :registry_id\n validates :registry_id, type: String\n\n # @return [Hash, String, nil] JSON or dict that represents the new policy\n attribute :policy\n validates :policy, type: MultipleTypes.new(Hash, String)\n\n # @return [Boolean, nil] if no, prevents setting a policy that would prevent you from setting another policy in the future.\n attribute :force_set_policy\n validates :force_set_policy, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] if yes, remove the policy from the repository\n attribute :delete_policy\n validates :delete_policy, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:present, :absent, nil] create or destroy the repository\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6883453130722046, "alphanum_fraction": 0.6900719404220581, "avg_line_length": 64.5660400390625, "blob_id": "1bd11510560c94bb2d0c6e55d8209c2b0f7bf2cc", "content_id": "a3083ac01336dacf6412667c54eae08164c45491", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3475, "license_type": "permissive", "max_line_length": 549, "num_lines": 53, "path": "/lib/ansible/ruby/modules/generated/system/mount.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module controls active and configured mount points in C(/etc/fstab).\n class Mount < Base\n # @return [String] Path to the mount point (e.g. C(/mnt/files)).,Before 2.3 this option was only usable as I(dest), I(destfile) and I(name).\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [String, nil] Device to be mounted on I(path). Required when I(state) set to C(present) or C(mounted).\n attribute :src\n validates :src, type: String\n\n # @return [String, nil] Filesystem type. Required when I(state) is C(present) or C(mounted).\n attribute :fstype\n validates :fstype, type: String\n\n # @return [Array<String>, String, nil] Mount options (see fstab(5), or vfstab(4) on Solaris).\n attribute :opts\n validates :opts, type: TypeGeneric.new(String)\n\n # @return [Integer, nil] Dump (see fstab(5)). Note that if set to C(null) and I(state) set to C(present), it will cease to work and duplicate entries will be made with subsequent runs.,Has no effect on Solaris systems.\n attribute :dump\n validates :dump, type: Integer\n\n # @return [Integer, nil] Passno (see fstab(5)). Note that if set to C(null) and I(state) set to C(present), it will cease to work and duplicate entries will be made with subsequent runs.,Deprecated on Solaris systems.\n attribute :passno\n validates :passno, type: Integer\n\n # @return [:absent, :mounted, :present, :unmounted] If C(mounted), the device will be actively mounted and appropriately configured in I(fstab). If the mount point is not present, the mount point will be created.,If C(unmounted), the device will be unmounted without changing I(fstab).,C(present) only specifies that the device is to be configured in I(fstab) and does not trigger or require a mount.,C(absent) specifies that the device mount's entry will be removed from I(fstab) and will also unmount the device and remove the mount point.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:absent, :mounted, :present, :unmounted], :message=>\"%{value} needs to be :absent, :mounted, :present, :unmounted\"}\n\n # @return [String, nil] File to use instead of C(/etc/fstab). You shouldn't use this option unless you really know what you are doing. This might be useful if you need to configure mountpoints in a chroot environment. OpenBSD does not allow specifying alternate fstab files with mount so do not use this on OpenBSD with any state that operates on the live filesystem.\n attribute :fstab\n validates :fstab, type: String\n\n # @return [:yes, :no, nil] Determines if the filesystem should be mounted on boot.,Only applies to Solaris systems.\n attribute :boot\n validates :boot, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.\n attribute :backup\n validates :backup, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6790035367012024, "alphanum_fraction": 0.6790035367012024, "avg_line_length": 49.17856979370117, "blob_id": "8ffb82982705da26f4bc168a3b46b3e004ff6574", "content_id": "6f30c54584f7d9d5ae062e680769ca0fe314555d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2810, "license_type": "permissive", "max_line_length": 211, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/cloud/rackspace/rax_clb_ssl.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Set up, reconfigure, or remove SSL termination for an existing load balancer.\n class Rax_clb_ssl < Base\n # @return [String] Name or ID of the load balancer on which to manage SSL termination.\n attribute :loadbalancer\n validates :loadbalancer, presence: true, type: String\n\n # @return [:present, :absent, nil] If set to \"present\", SSL termination will be added to this load balancer.,If \"absent\", SSL termination will be removed instead.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Boolean, nil] If set to \"false\", temporarily disable SSL termination without discarding,existing credentials.\n attribute :enabled\n validates :enabled, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] The private SSL key as a string in PEM format.\n attribute :private_key\n validates :private_key, type: String\n\n # @return [String, nil] The public SSL certificates as a string in PEM format.\n attribute :certificate\n validates :certificate, type: String\n\n # @return [String, nil] One or more intermediate certificate authorities as a string in PEM,format, concatenated into a single string.\n attribute :intermediate_certificate\n validates :intermediate_certificate, type: String\n\n # @return [Integer, nil] The port to listen for secure traffic.\n attribute :secure_port\n validates :secure_port, type: Integer\n\n # @return [Boolean, nil] If \"true\", the load balancer will *only* accept secure traffic.\n attribute :secure_traffic_only\n validates :secure_traffic_only, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] If \"true\", the load balancer will redirect HTTP traffic to HTTPS.,Requires \"secure_traffic_only\" to be true. Incurs an implicit wait if SSL,termination is also applied or removed.\n attribute :https_redirect\n\n # @return [Boolean, nil] Wait for the balancer to be in state \"running\" before turning.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Integer, nil] How long before \"wait\" gives up, in seconds.\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7045977115631104, "alphanum_fraction": 0.7068965435028076, "avg_line_length": 40.42856979370117, "blob_id": "151cf208da79bf5a0066ffc36bed868492609be7", "content_id": "877f5242ea3303b7d217f07b83c179662b8bf5d8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 870, "license_type": "permissive", "max_line_length": 294, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/cloud/memset/memset_dns_reload.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Request a reload of Memset's DNS infrastructure, and optionally poll until it finishes.\n class Memset_dns_reload < Base\n # @return [String] The API key obtained from the Memset control panel.\n attribute :api_key\n validates :api_key, presence: true, type: String\n\n # @return [Symbol, nil] Boolean value, if set will poll the reload job's status and return when the job has completed (unless the 30 second timeout is reached first). If the timeout is reached then the task will not be marked as failed, but stderr will indicate that the polling failed.\n attribute :poll\n validates :poll, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6841587424278259, "alphanum_fraction": 0.6874384880065918, "avg_line_length": 61.224491119384766, "blob_id": "341e69df65d2432434dd49c3bb2c7be5243c69f5", "content_id": "58df3cbdd36041e1aa9c8dbfdff8c65cd570c96f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3049, "license_type": "permissive", "max_line_length": 293, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/cloud/rackspace/rax_files_objects.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Upload, download, and delete objects in Rackspace Cloud Files\n class Rax_files_objects < Base\n # @return [:yes, :no, nil] Optionally clear existing metadata when applying metadata to existing objects. Selecting this option is only appropriate when setting type=meta\n attribute :clear_meta\n validates :clear_meta, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object] The container to use for file object operations.\n attribute :container\n validates :container, presence: true\n\n # @return [Object, nil] The destination of a \"get\" operation; i.e. a local directory, \"/home/user/myfolder\". Used to specify the destination of an operation on a remote object; i.e. a file name, \"file1\", or a comma-separated list of remote objects, \"file1,file2,file17\"\n attribute :dest\n\n # @return [Object, nil] Used to set an expiration on a file or folder uploaded to Cloud Files. Requires an integer, specifying expiration in seconds\n attribute :expires\n\n # @return [Object, nil] A hash of items to set as metadata values on an uploaded file or folder\n attribute :meta\n\n # @return [:get, :put, :delete, nil] The method of operation to be performed. For example, put to upload files to Cloud Files, get to download files from Cloud Files or delete to delete remote objects in Cloud Files\n attribute :method\n validates :method, expression_inclusion: {:in=>[:get, :put, :delete], :message=>\"%{value} needs to be :get, :put, :delete\"}, allow_nil: true\n\n # @return [Object, nil] Source from which to upload files. Used to specify a remote object as a source for an operation, i.e. a file name, \"file1\", or a comma-separated list of remote objects, \"file1,file2,file17\". src and dest are mutually exclusive on remote-only object operations\n attribute :src\n\n # @return [:yes, :no, nil] Used to specify whether to maintain nested directory structure when downloading objects from Cloud Files. Setting to false downloads the contents of a container to a single, flat directory\n attribute :structure\n validates :structure, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Indicate desired state of the resource\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:file, :meta, nil] Type of object to do work on,Metadata object or a file object\n attribute :type\n validates :type, expression_inclusion: {:in=>[:file, :meta], :message=>\"%{value} needs to be :file, :meta\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.684440553188324, "alphanum_fraction": 0.684440553188324, "avg_line_length": 44.7599983215332, "blob_id": "303b7e8c2bd40870c918d559ef20e5662d7e4900", "content_id": "018aaed35eb8c4f709ceccfa01a01c7621b6062e", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1144, "license_type": "permissive", "max_line_length": 239, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_device_ntp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage NTP servers on a BIG-IP.\n class Bigip_device_ntp < Base\n # @return [Array<String>, String, nil] A list of NTP servers to set on the device. At least one of C(ntp_servers) or C(timezone) is required.\n attribute :ntp_servers\n validates :ntp_servers, type: TypeGeneric.new(String)\n\n # @return [:absent, :present, nil] The state of the NTP servers on the system. When C(present), guarantees that the NTP servers are set on the system. When C(absent), removes the specified NTP servers from the device configuration.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] The timezone to set for NTP lookups. At least one of C(ntp_servers) or C(timezone) is required.\n attribute :timezone\n validates :timezone, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6940745711326599, "alphanum_fraction": 0.6970705986022949, "avg_line_length": 70.52381134033203, "blob_id": "1bd14434c16df1113db7693c9a111f29a6ccc8bb", "content_id": "6823aa3e9a8f09a7f4e74456ccc5e06a4120e358", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3004, "license_type": "permissive", "max_line_length": 516, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_info_center_log.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Setting the Timestamp Format of Logs. Configuring the Device to Output Logs to the Log Buffer.\n class Ce_info_center_log < Base\n # @return [:date_boot, :date_second, :date_tenthsecond, :date_millisecond, :shortdate_second, :shortdate_tenthsecond, :shortdate_millisecond, :formatdate_second, :formatdate_tenthsecond, :formatdate_millisecond, nil] Sets the timestamp format of logs.\n attribute :log_time_stamp\n validates :log_time_stamp, expression_inclusion: {:in=>[:date_boot, :date_second, :date_tenthsecond, :date_millisecond, :shortdate_second, :shortdate_tenthsecond, :shortdate_millisecond, :formatdate_second, :formatdate_tenthsecond, :formatdate_millisecond], :message=>\"%{value} needs to be :date_boot, :date_second, :date_tenthsecond, :date_millisecond, :shortdate_second, :shortdate_tenthsecond, :shortdate_millisecond, :formatdate_second, :formatdate_tenthsecond, :formatdate_millisecond\"}, allow_nil: true\n\n # @return [:no_use, :true, :false, nil] Enables the Switch to send logs to the log buffer.\n attribute :log_buff_enable\n validates :log_buff_enable, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the maximum number of logs in the log buffer. The value is an integer that ranges from 0 to 10240. If logbuffer-size is 0, logs are not displayed.\n attribute :log_buff_size\n\n # @return [Object, nil] Specifies the name of a module. The value is a module name in registration logs.\n attribute :module_name\n\n # @return [Object, nil] Specifies a channel ID. The value is an integer ranging from 0 to 9.\n attribute :channel_id\n\n # @return [:no_use, :true, :false, nil] Indicates whether log filtering is enabled.\n attribute :log_enable\n validates :log_enable, expression_inclusion: {:in=>[:no_use, :true, :false], :message=>\"%{value} needs to be :no_use, :true, :false\"}, allow_nil: true\n\n # @return [:emergencies, :alert, :critical, :error, :warning, :notification, :informational, :debugging, nil] Specifies a log severity.\n attribute :log_level\n validates :log_level, expression_inclusion: {:in=>[:emergencies, :alert, :critical, :error, :warning, :notification, :informational, :debugging], :message=>\"%{value} needs to be :emergencies, :alert, :critical, :error, :warning, :notification, :informational, :debugging\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Determines whether the config should be present or not on the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6719524264335632, "alphanum_fraction": 0.6719524264335632, "avg_line_length": 35.03571319580078, "blob_id": "79911b9b963d9d34d1ee073ae7921dd8093529a6", "content_id": "8c437a64fca373188eb118249032e56ca4555961", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1009, "license_type": "permissive", "max_line_length": 143, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_config_aggregator.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Module manages AWS Config resources\n class Aws_config_aggregator < Base\n # @return [String] The name of the AWS Config resource.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Whether the Config rule should be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Hash, nil] Provides a list of source accounts and regions to be aggregated.\n attribute :account_sources\n validates :account_sources, type: Hash\n\n # @return [Object, nil] The region authorized to collect aggregated data.\n attribute :organization_source\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6735042929649353, "alphanum_fraction": 0.6735042929649353, "avg_line_length": 34.45454406738281, "blob_id": "df3b4c4ee9217ed6d6191676ad5dbd8431d66fc2", "content_id": "c161d2cc0c8cd240fd6f08c7db48b5c2a325db56", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1170, "license_type": "permissive", "max_line_length": 131, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/remote_management/foreman/foreman.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows the management of Foreman resources inside your Foreman server.\n class Foreman < Base\n # @return [String] URL of Foreman server.\n attribute :server_url\n validates :server_url, presence: true, type: String\n\n # @return [String] Username on Foreman server.\n attribute :username\n validates :username, presence: true, type: String\n\n # @return [String] Password for user accessing Foreman server.\n attribute :password\n validates :password, presence: true, type: String\n\n # @return [String] The Foreman resource that the action will be performed on (e.g. organization, host).\n attribute :entity\n validates :entity, presence: true, type: String\n\n # @return [Hash] Parameters associated to the entity resource to set or edit in dictionary format (e.g. name, description).\n attribute :params\n validates :params, presence: true, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6789321899414062, "alphanum_fraction": 0.6789321899414062, "avg_line_length": 41, "blob_id": "2aa037a9442544d186b612429040cf3beb4d8d2e", "content_id": "b294d6ad8b085ff880a48bb0e0f7fe4fb10aa3dd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1386, "license_type": "permissive", "max_line_length": 159, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_interface_policy_lldp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage LLDP interface policies on Cisco ACI fabrics.\n class Aci_interface_policy_lldp < Base\n # @return [String] The LLDP interface policy name.\n attribute :lldp_policy\n validates :lldp_policy, presence: true, type: String\n\n # @return [String, nil] The description for the LLDP interface policy name.\n attribute :description\n validates :description, type: String\n\n # @return [Symbol, nil] Enable or disable Receive state.,The APIC defaults to C(yes) when unset during creation.\n attribute :receive_state\n validates :receive_state, type: Symbol\n\n # @return [Symbol, nil] Enable or Disable Transmit state.,The APIC defaults to C(yes) when unset during creation.\n attribute :transmit_state\n validates :transmit_state, type: Symbol\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7323135733604431, "alphanum_fraction": 0.7323135733604431, "avg_line_length": 31.6875, "blob_id": "cf9afc06152c1a319ce38be32355add53b8d8760", "content_id": "30cd90bea5ce0390c64e3368760f1b48eb9a8afe", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 523, "license_type": "permissive", "max_line_length": 151, "num_lines": 16, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_caller_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module returns information about the account and user / role from which the AWS access tokens originate.\n # The primary use of this is to get the account id for templating into ARNs or similar to avoid needing to specify this information in inventory.\n class Aws_caller_facts < Base\n\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6731821894645691, "alphanum_fraction": 0.6731821894645691, "avg_line_length": 37.75757598876953, "blob_id": "abccc4cbc5f5fa33bfa0a74721278f723f30eaed", "content_id": "644355436e553cb66565f748384fad08aac1d26a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1279, "license_type": "permissive", "max_line_length": 159, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/network/illumos/ipadm_prop.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Modify protocol properties on Solaris/illumos systems.\n class Ipadm_prop < Base\n # @return [String] Specifies the procotol for which we want to manage properties.\n attribute :protocol\n validates :protocol, presence: true, type: String\n\n # @return [String] Specifies the name of property we want to manage.\n attribute :property\n validates :property, presence: true, type: String\n\n # @return [String, nil] Specifies the value we want to set for the property.\n attribute :value\n validates :value, type: String\n\n # @return [Symbol, nil] Specifies that the property value is temporary. Temporary property values do not persist across reboots.\n attribute :temporary\n validates :temporary, type: Symbol\n\n # @return [:present, :absent, :reset, nil] Set or reset the property value.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :reset], :message=>\"%{value} needs to be :present, :absent, :reset\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7036849856376648, "alphanum_fraction": 0.7036849856376648, "avg_line_length": 59.9538459777832, "blob_id": "31514a27ec7f4b4c03aa39f3a66e312bb6bbe86a", "content_id": "2f61158651ba86e2775dc78136736ce37df3fc6e", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3962, "license_type": "permissive", "max_line_length": 368, "num_lines": 65, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/netapp_e_snapshot_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, delete snapshot groups for NetApp E-series storage arrays\n class Netapp_e_snapshot_group < Base\n # @return [String] The username to authenticate with the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_username\n validates :api_username, presence: true, type: String\n\n # @return [String] The password to authenticate with the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_password\n validates :api_password, presence: true, type: String\n\n # @return [String] The url to the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_url\n validates :api_url, presence: true, type: String\n\n # @return [Boolean, nil] Should https certificates be validated?\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:present, :absent] Whether to ensure the group is present or absent.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [Object] The name to give the snapshot group\n attribute :name\n validates :name, presence: true\n\n # @return [String] The name of the base volume or thin volume to use as the base for the new snapshot group.,If a snapshot group with an identical C(name) already exists but with a different base volume an error will be returned.\n attribute :base_volume_name\n validates :base_volume_name, presence: true, type: String\n\n # @return [Integer, nil] The size of the repository in relation to the size of the base volume\n attribute :repo_pct\n validates :repo_pct, type: Integer\n\n # @return [Integer, nil] The repository utilization warning threshold, as a percentage of the repository volume capacity.\n attribute :warning_threshold\n validates :warning_threshold, type: Integer\n\n # @return [Integer, nil] The automatic deletion indicator.,If non-zero, the oldest snapshot image will be automatically deleted when creating a new snapshot image to keep the total number of snapshot images limited to the number specified.,This value is overridden by the consistency group setting if this snapshot group is associated with a consistency group.\n attribute :delete_limit\n validates :delete_limit, type: Integer\n\n # @return [:purgepit, :unknown, :failbasewrites, :__UNDEFINED, nil] The behavior on when the data repository becomes full.,This value is overridden by consistency group setting if this snapshot group is associated with a consistency group\n attribute :full_policy\n validates :full_policy, expression_inclusion: {:in=>[:purgepit, :unknown, :failbasewrites, :__UNDEFINED], :message=>\"%{value} needs to be :purgepit, :unknown, :failbasewrites, :__UNDEFINED\"}, allow_nil: true\n\n # @return [String] The name of the storage pool on which to allocate the repository volume.\n attribute :storage_pool_name\n validates :storage_pool_name, presence: true, type: String\n\n # @return [:highest, :high, :medium, :low, :lowest, :__UNDEFINED, nil] The importance of the rollback operation.,This value is overridden by consistency group setting if this snapshot group is associated with a consistency group\n attribute :rollback_priority\n validates :rollback_priority, expression_inclusion: {:in=>[:highest, :high, :medium, :low, :lowest, :__UNDEFINED], :message=>\"%{value} needs to be :highest, :high, :medium, :low, :lowest, :__UNDEFINED\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7006711363792419, "alphanum_fraction": 0.7006711363792419, "avg_line_length": 34.47618865966797, "blob_id": "ccd7104aa72e3e181e55a74b53bd4cd50dad597d", "content_id": "4b96cb14947c8542ab461ce77e4b26cb70e84f33", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 745, "license_type": "permissive", "max_line_length": 131, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/database/proxysql/proxysql_global_variables.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The M(proxysql_global_variables) module gets or sets the proxysql global variables.\n class Proxysql_global_variables < Base\n # @return [String] Defines which variable should be returned, or if I(value) is specified which variable should be updated.\n attribute :variable\n validates :variable, presence: true, type: String\n\n # @return [Integer, nil] Defines a value the variable specified using I(variable) should be set to.\n attribute :value\n validates :value, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6943005323410034, "alphanum_fraction": 0.6979274749755859, "avg_line_length": 63.33333206176758, "blob_id": "22b0526b4b014f9b530ac9283ba1de55f4ff215f", "content_id": "77106e0207888154623b205d93bda282548debc3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1930, "license_type": "permissive", "max_line_length": 368, "num_lines": 30, "path": "/lib/ansible/ruby/modules/generated/remote_management/ucs/ucs_timezone.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configures timezone on Cisco UCS Manager.\n # Examples can be used with the L(UCS Platform Emulator,https://communities.cisco.com/ucspe).\n class Ucs_timezone < Base\n # @return [:absent, :present, nil] If C(absent), will unset timezone.,If C(present), will set or update timezone.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:disabled, :enabled, nil] The admin_state setting,The enabled admin_state indicates the timezone confguration is utilized by UCS Manager.,The disabled admin_state indicates the timezone confguration is ignored by UCS Manager.\n attribute :admin_state\n validates :admin_state, expression_inclusion: {:in=>[:disabled, :enabled], :message=>\"%{value} needs to be :disabled, :enabled\"}, allow_nil: true\n\n # @return [String, nil] A user-defined description of the timezone.,Enter up to 256 characters.,You can use any characters or spaces except the following:,` (accent mark), (backslash), ^ (carat), \" (double quote), = (equal sign), > (greater than), < (less than), or ' (single quote).\n attribute :description\n validates :description, type: String\n\n # @return [String, nil] The timezone name.,Time zone names are from the L(tz database,https://en.wikipedia.org/wiki/List_of_tz_database_time_zones),The timezone name is case sensitive.,The timezone name can be between 0 and 510 alphanumeric characters.,You cannot use spaces or any special characters other than,\"-\" (hyphen), \"_\" (underscore), \"/\" (backslash).\n attribute :timezone\n validates :timezone, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5293816924095154, "alphanum_fraction": 0.5329630374908447, "avg_line_length": 37.324928283691406, "blob_id": "2d99135ee6f3846a9e7f485220db630da2a3d88b", "content_id": "8da8fda50b2693ed75f6001f1d23f52ca055ac57", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 13682, "license_type": "permissive", "max_line_length": 327, "num_lines": 357, "path": "/util/parser_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# See LICENSE.txt for license\nrequire 'spec_helper'\nrequire 'ansible-ruby'\nrequire_relative './parser'\n\ndescribe Ansible::Ruby::Parser do\n describe '::from_yaml_string' do\n subject { Ansible::Ruby::Parser.from_yaml_string desc_yaml, example_yaml, example_fail_is_ok }\n let(:example_fail_is_ok) { false }\n\n let(:desc_yaml) do\n <<~YAML\n ---\n module: postgresql_db\n short_description: Add or remove PostgreSQL databases from a remote host.\n description:\n - Add or remove PostgreSQL databases from a remote host.\n - And do other things too.\n version_added: \"0.6\"\n options:\n name:\n description:\n - name of the database to add or remove\n required: true\n default: null\n login_user:\n description:\n - The username used to authenticate with\n required: false\n default: null\n port:\n description:\n - Database port to connect to.\n required: false\n default: 5432\n state:\n description:\n - The database state\n required: false\n default: present\n choices: [ \"present\", \"absent\" ]\n notes:\n - The default authentication assumes that you are either logging in as or sudo'ing to the C(postgres) account on the host.\n - This module uses I(psycopg2), a Python PostgreSQL database adapter. You must ensure that psycopg2 is installed on\n the host before using this module. If the remote host is the PostgreSQL server (which is the default case), then PostgreSQL must also be installed on the remote host. For Ubuntu-based systems, install the C(postgresql), C(libpq-dev), and C(python-psycopg2) packages on the remote host before using this module.\n requirements: [ psycopg2 ]\n author: \"Ansible Core Team\"\n YAML\n end\n\n let(:example_yaml) do\n <<~YAML\n # Create a new database with name \"acme\"\n - postgresql_db: name=acme\n # Create a new database with name \"acme\" and specific encoding and locale\n # settings. If a template different from \"template0\" is specified, encoding\n # and locale settings must match those of the template.\n - postgresql_db: name=acme\n encoding='UTF-8'\n lc_collate='de_DE.UTF-8'\n lc_ctype='de_DE.UTF-8'\n template='template0'\n YAML\n end\n\n context 'standard' do\n it do\n is_expected.to eq <<~RUBY\n # frozen_string_literal: true\n # See LICENSE.txt at root of repository\n # GENERATED FILE - DO NOT EDIT!!\n require 'ansible/ruby/modules/base'\n\n module Ansible\n module Ruby\n module Modules\n # Add or remove PostgreSQL databases from a remote host.\n # And do other things too.\n class Postgresql_db < Base\n # @return [String] name of the database to add or remove\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] The username used to authenticate with\n attribute :login_user\n\n # @return [Integer, nil] Database port to connect to.\n attribute :port\n validates :port, type: Integer\n\n # @return [:present, :absent, nil] The database state\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\n end\n RUBY\n end\n end\n\n context 'description is string' do\n let(:desc_yaml) do\n <<~YAML\n ---\n module: postgresql_db\n short_description: Add or remove PostgreSQL databases from a remote host.\n description: Add or remove PostgreSQL databases from a remote host.\n version_added: \"0.6\"\n options:\n name:\n description:\n - name of the database to add or remove\n required: true\n default: null\n login_user:\n description:\n - The username used to authenticate with\n required: false\n default: null\n port:\n description:\n - Database port to connect to.\n required: false\n default: 5432\n state:\n description:\n - The database state\n required: false\n default: present\n choices: [ \"present\", \"absent\" ]\n notes:\n - The default authentication assumes that you are either logging in as or sudo'ing to the C(postgres) account on the host.\n - This module uses I(psycopg2), a Python PostgreSQL database adapter. You must ensure that psycopg2 is installed on\n the host before using this module. If the remote host is the PostgreSQL server (which is the default case), then PostgreSQL must also be installed on the remote host. For Ubuntu-based systems, install the C(postgresql), C(libpq-dev), and C(python-psycopg2) packages on the remote host before using this module.\n requirements: [ psycopg2 ]\n author: \"Ansible Core Team\"\n YAML\n end\n\n it do\n is_expected.to eq <<~RUBY\n # frozen_string_literal: true\n # See LICENSE.txt at root of repository\n # GENERATED FILE - DO NOT EDIT!!\n require 'ansible/ruby/modules/base'\n\n module Ansible\n module Ruby\n module Modules\n # Add or remove PostgreSQL databases from a remote host.\n class Postgresql_db < Base\n # @return [String] name of the database to add or remove\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] The username used to authenticate with\n attribute :login_user\n\n # @return [Integer, nil] Database port to connect to.\n attribute :port\n validates :port, type: Integer\n\n # @return [:present, :absent, nil] The database state\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\n end\n RUBY\n end\n end\n\n context 'no description' do\n context 'short is available' do\n let(:desc_yaml) do\n <<~YAML\n ---\n module: postgresql_db\n short_description: Add or remove PostgreSQL databases from a remote host.\n version_added: \"0.6\"\n options:\n name:\n description:\n - name of the database to add or remove\n required: true\n default: null\n login_user:\n description:\n - The username used to authenticate with\n required: false\n default: null\n port:\n description:\n - Database port to connect to.\n required: false\n default: 5432\n state:\n description:\n - The database state\n required: false\n default: present\n choices: [ \"present\", \"absent\" ]\n notes:\n - The default authentication assumes that you are either logging in as or sudo'ing to the C(postgres) account on the host.\n - This module uses I(psycopg2), a Python PostgreSQL database adapter. You must ensure that psycopg2 is installed on\n the host before using this module. If the remote host is the PostgreSQL server (which is the default case), then PostgreSQL must also be installed on the remote host. For Ubuntu-based systems, install the C(postgresql), C(libpq-dev), and C(python-psycopg2) packages on the remote host before using this module.\n requirements: [ psycopg2 ]\n author: \"Ansible Core Team\"\n YAML\n end\n it do\n is_expected.to eq <<~RUBY\n # frozen_string_literal: true\n # See LICENSE.txt at root of repository\n # GENERATED FILE - DO NOT EDIT!!\n require 'ansible/ruby/modules/base'\n\n module Ansible\n module Ruby\n module Modules\n # Add or remove PostgreSQL databases from a remote host.\n class Postgresql_db < Base\n # @return [String] name of the database to add or remove\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] The username used to authenticate with\n attribute :login_user\n\n # @return [Integer, nil] Database port to connect to.\n attribute :port\n validates :port, type: Integer\n\n # @return [:present, :absent, nil] The database state\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\n end\n RUBY\n end\n end\n\n context 'nothing available' do\n let(:desc_yaml) do\n <<~YAML\n ---\n module: postgresql_db\n version_added: \"0.6\"\n options:\n name:\n description:\n - name of the database to add or remove\n required: true\n default: null\n login_user:\n description:\n - The username used to authenticate with\n required: false\n default: null\n port:\n description:\n - Database port to connect to.\n required: false\n default: 5432\n state:\n description:\n - The database state\n required: false\n default: present\n choices: [ \"present\", \"absent\" ]\n notes:\n - The default authentication assumes that you are either logging in as or sudo'ing to the C(postgres) account on the host.\n - This module uses I(psycopg2), a Python PostgreSQL database adapter. You must ensure that psycopg2 is installed on\n the host before using this module. If the remote host is the PostgreSQL server (which is the default case), then PostgreSQL must also be installed on the remote host. For Ubuntu-based systems, install the C(postgresql), C(libpq-dev), and C(python-psycopg2) packages on the remote host before using this module.\n requirements: [ psycopg2 ]\n author: \"Ansible Core Team\"\n YAML\n end\n it do\n is_expected.to eq <<~RUBY\n # frozen_string_literal: true\n # See LICENSE.txt at root of repository\n # GENERATED FILE - DO NOT EDIT!!\n require 'ansible/ruby/modules/base'\n\n module Ansible\n module Ruby\n module Modules\n class Postgresql_db < Base\n # @return [String] name of the database to add or remove\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] The username used to authenticate with\n attribute :login_user\n\n # @return [Integer, nil] Database port to connect to.\n attribute :port\n validates :port, type: Integer\n\n # @return [:present, :absent, nil] The database state\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\n end\n RUBY\n end\n end\n end\n\n context 'no options' do\n let(:desc_yaml) do\n <<~YAML\n ---\n module: os_auth\n short_description: Retrieve an auth token\n version_added: \"2.0\"\n author: \"Monty Taylor (@emonty)\"\n description:\n - Retrieve an auth token from an OpenStack Cloud\n requirements:\n - \"python >= 2.6\"\n - \"shade\"\n extends_documentation_fragment: openstack\n YAML\n end\n\n it do\n is_expected.to eq <<~RUBY\n # frozen_string_literal: true\n # See LICENSE.txt at root of repository\n # GENERATED FILE - DO NOT EDIT!!\n require 'ansible/ruby/modules/base'\n\n module Ansible\n module Ruby\n module Modules\n # Retrieve an auth token from an OpenStack Cloud\n class Os_auth < Base\n\n end\n end\n end\n end\n RUBY\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.700386106967926, "alphanum_fraction": 0.7027027010917664, "avg_line_length": 50.79999923706055, "blob_id": "d71cc3c3adf8a8b6a2f75d555d2d89a63ebc05fd", "content_id": "bafffdf6a9293fcf7cc8ce24479a747fe7d02863", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1295, "license_type": "permissive", "max_line_length": 262, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_placement_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create an EC2 Placement Group; if the placement group already exists, nothing is done. Or, delete an existing placement group. If the placement group is absent, do nothing. See also http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html\n class Ec2_placement_group < Base\n # @return [String] The name for the placement group.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Create or delete placement group.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:cluster, :spread, nil] Placement group strategy. Cluster will cluster instances into a low-latency group in a single Availability Zone, while Spread spreads instances across underlying hardware.\n attribute :strategy\n validates :strategy, expression_inclusion: {:in=>[:cluster, :spread], :message=>\"%{value} needs to be :cluster, :spread\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6929460763931274, "alphanum_fraction": 0.6929460763931274, "avg_line_length": 27.352941513061523, "blob_id": "d9b6134ec7322fa9de0efbf87965d41c37babc5c", "content_id": "2715323c7ef0cbcaeb0f1dff0ea8cdcc625fa04a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 482, "license_type": "permissive", "max_line_length": 77, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ecs_taskdefinition_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Describes a task definition in ecs.\n class Ecs_taskdefinition_facts < Base\n # @return [String] The name of the task definition to get details for\n attribute :task_definition\n validates :task_definition, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7141255736351013, "alphanum_fraction": 0.7141255736351013, "avg_line_length": 37.78260803222656, "blob_id": "311634e2bcc86bbc57ddbcb5fc83b2ab10d10afd", "content_id": "067422118d1da7ac6e19af810cf0a519a58a20f1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 892, "license_type": "permissive", "max_line_length": 178, "num_lines": 23, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_storage_templates_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Retrieve facts about one or more oVirt/RHV templates relate to a storage domain.\n class Ovirt_storage_template_facts < Base\n # @return [Symbol, nil] Flag which indicates whether to get unregistered templates which contain one or more disks which reside on a storage domain or diskless templates.\n attribute :unregistered\n validates :unregistered, type: Symbol\n\n # @return [Object, nil] Sets the maximum number of templates to return. If not specified all the templates are returned.\n attribute :max\n\n # @return [Object, nil] The storage domain name where the templates should be listed.\n attribute :storage_domain\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6560605764389038, "alphanum_fraction": 0.6560605764389038, "avg_line_length": 25.399999618530273, "blob_id": "81b1b6454b04d7832c0b4a4240ea511cfa8876dd", "content_id": "f80669b715a89cf687278000aaa6a811b3b659d0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 660, "license_type": "permissive", "max_line_length": 87, "num_lines": 25, "path": "/lib/ansible/ruby/models/tasks.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'ansible/ruby/models/base'\nrequire 'ansible/ruby/models/task'\nrequire 'ansible/ruby/models/block'\nrequire 'ansible/ruby/models/inclusion'\n\nmodule Ansible\n module Ruby\n module Models\n class Tasks < Base\n attribute :items\n validates :items, presence: true, type: TypeGeneric.new(Task, Block, Inclusion)\n attribute :inclusions\n validates :inclusions, type: TypeGeneric.new(Inclusion)\n\n def to_h\n super_result = super\n # Don't need to return highest level\n (super_result[:inclusions] || []) + super_result[:items]\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6964539289474487, "alphanum_fraction": 0.7014184594154358, "avg_line_length": 49.35714340209961, "blob_id": "5fa2fa6f8560ce85c1b6a1f1c1ae7542828a802c", "content_id": "9e506429387b726b2f810fb45ecc09f60f2c854a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1410, "license_type": "permissive", "max_line_length": 291, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_spanner_database.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # A Cloud Spanner Database which is hosted on a Spanner instance.\n class Gcp_spanner_database < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] A unique identifier for the database, which cannot be changed after the instance is created. Values are of the form projects/<project>/instances/[a-z][-a-z0-9]*[a-z0-9]. The final segment of the name must be between 6 and 30 characters in length.\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] An optional list of DDL statements to run inside the newly created database. Statements can create tables, indexes, etc. These statements execute atomically with the creation of the database: if there is an error in any statement, the database is not created.\n attribute :extra_statements\n\n # @return [String] The instance to create the database on.\n attribute :instance\n validates :instance, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.655083417892456, "alphanum_fraction": 0.6677919030189514, "avg_line_length": 53.739131927490234, "blob_id": "d28beb395493122e75c3508abbbccdb85a150366", "content_id": "e3266471f3b61f99b689fc01d775d99e9e7d989f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5036, "license_type": "permissive", "max_line_length": 197, "num_lines": 92, "path": "/lib/ansible/ruby/modules/generated/remote_management/cpm/cpm_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Get/Add/Edit Delete Users from WTI OOB and PDU devices\n class Cpm_user < Base\n # @return [:getuser, :adduser, :edituser, :deleteuser] This is the Action to send the module.\n attribute :cpm_action\n validates :cpm_action, presence: true, expression_inclusion: {:in=>[:getuser, :adduser, :edituser, :deleteuser], :message=>\"%{value} needs to be :getuser, :adduser, :edituser, :deleteuser\"}\n\n # @return [String] This is the URL of the WTI device to send the module.\n attribute :cpm_url\n validates :cpm_url, presence: true, type: String\n\n # @return [String] This is the Basic Authentication Username of the WTI device to send the module.\n attribute :cpm_username\n validates :cpm_username, presence: true, type: String\n\n # @return [String] This is the Basic Authentication Password of the WTI device to send the module.\n attribute :cpm_password\n validates :cpm_password, presence: true, type: String\n\n # @return [Boolean, nil] Designates to use an https connection or http connection.\n attribute :use_https\n validates :use_https, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] If false, SSL certificates will not be validated. This should only be used,on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Symbol, nil] Flag to control if the lookup will observe HTTP proxy environment variables when present.\n attribute :use_proxy\n validates :use_proxy, type: Symbol\n\n # @return [String] This is the User Name that needs to be create/modified/deleted\n attribute :user_name\n validates :user_name, presence: true, type: String\n\n # @return [String, nil] This is the User Password that needs to be create/modified/deleted,If the user is being Created this parameter is required\n attribute :user_pass\n validates :user_pass, type: String\n\n # @return [0, 1, 2, 3, nil] This is the access level that needs to be create/modified/deleted,0 View, 1 User, 2 SuperUser, 3 Adminstrator\n attribute :user_accesslevel\n validates :user_accesslevel, expression_inclusion: {:in=>[0, 1, 2, 3], :message=>\"%{value} needs to be 0, 1, 2, 3\"}, allow_nil: true\n\n # @return [0, 1, nil] If the user has access to the WTI device via SSH,0 No , 1 Yes\n attribute :user_accessssh\n validates :user_accessssh, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [0, 1, nil] If the user has access to the WTI device via Serial ports,0 No , 1 Yes\n attribute :user_accessserial\n validates :user_accessserial, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [0, 1, nil] If the user has access to the WTI device via Web,0 No , 1 Yes\n attribute :user_accessweb\n validates :user_accessweb, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [0, 1, nil] If the user has access to the WTI device via RESTful APIs,0 No , 1 Yes\n attribute :user_accessapi\n validates :user_accessapi, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [0, 1, nil] If the user has ability to monitor connection sessions,0 No , 1 Yes\n attribute :user_accessmonitor\n validates :user_accessmonitor, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [0, 1, nil] If the user has ability to initiate Outbound connection,0 No , 1 Yes\n attribute :user_accessoutbound\n validates :user_accessoutbound, expression_inclusion: {:in=>[0, 1], :message=>\"%{value} needs to be 0, 1\"}, allow_nil: true\n\n # @return [String, nil] If AccessLevel is lower than Administrator, which ports the user has access\n attribute :user_portaccess\n validates :user_portaccess, type: String\n\n # @return [String, nil] If AccessLevel is lower than Administrator, which plugs the user has access\n attribute :user_plugaccess\n validates :user_plugaccess, type: String\n\n # @return [String, nil] If AccessLevel is lower than Administrator, which Groups the user has access\n attribute :user_groupaccess\n validates :user_groupaccess, type: String\n\n # @return [Object, nil] This is the Call Back phone number used for POTS modem connections\n attribute :user_callbackphone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.718120813369751, "alphanum_fraction": 0.718120813369751, "avg_line_length": 42.82352828979492, "blob_id": "662dc236e9318045bfa00af75dedc6f12b0743fd", "content_id": "faaab4b926a3fdfcf4868f78ca002a10b7142e7b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 745, "license_type": "permissive", "max_line_length": 303, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/network/nso/nso_config.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides support for managing configuration in Cisco NSO and can also ensure services are in sync.\n class Nso_config < Base\n # @return [Hash] NSO data in format as | display json converted to YAML. List entries can be annotated with a __state entry. Set to in-sync/deep-in-sync for services to verify service is in sync with the network. Set to absent in list entries to ensure they are deleted if they exist in NSO.\\r\\n\n attribute :data\n validates :data, presence: true, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.689518392086029, "alphanum_fraction": 0.690651535987854, "avg_line_length": 66.88461303710938, "blob_id": "02ca72d207cc616f95d782e442fe5bf8f31f246b", "content_id": "7a58d1fd4a6fb46ec3c036fd71fb372e129ef906", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3530, "license_type": "permissive", "max_line_length": 423, "num_lines": 52, "path": "/lib/ansible/ruby/modules/generated/system/authorized_key.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Adds or removes SSH authorized keys for particular user accounts\n class Authorized_key < Base\n # @return [String] The username on the remote host whose authorized_keys file will be modified\n attribute :user\n validates :user, presence: true, type: String\n\n # @return [String] The SSH public key(s), as a string or (since 1.9) url (https://github.com/username.keys)\n attribute :key\n validates :key, presence: true, type: String\n\n # @return [String, nil] Alternate path to the authorized_keys file\n attribute :path\n validates :path, type: String\n\n # @return [:yes, :no, nil] Whether this module should manage the directory of the authorized key file. If set, the module will create the directory, as well as set the owner and permissions of an existing directory. Be sure to set C(manage_dir=no) if you are using an alternate directory for authorized_keys, as set with C(path), since you could lock yourself out of SSH access. See the example below.\n attribute :manage_dir\n validates :manage_dir, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Whether the given key (with the given key_options) should or should not be in the file\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] A string of ssh key options to be prepended to the key in the authorized_keys file\n attribute :key_options\n validates :key_options, type: TypeGeneric.new(String)\n\n # @return [:yes, :no, nil] Whether to remove all other non-specified keys from the authorized_keys file. Multiple keys can be specified in a single C(key) string value by separating them by newlines.,This option is not loop aware, so if you use C(with_) , it will be exclusive per iteration of the loop, if you want multiple keys in the file you need to pass them all to C(key) in a single batch as mentioned above.\n attribute :exclusive\n validates :exclusive, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] This only applies if using a https url as the source of the keys. If set to C(no), the SSL certificates will not be validated.,This should only set to C(no) used on personally controlled sites using self-signed certificates as it avoids verifying the source site.,Prior to 2.1 the code worked as if this was set to C(yes).\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Change the comment on the public key. Rewriting the comment is useful in cases such as fetching it from GitHub or GitLab.,If no comment is specified, the existing comment will be kept.\n attribute :comment\n\n # @return [:yes, :no, nil] Follow path symlink instead of replacing it\n attribute :follow\n validates :follow, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6558380126953125, "alphanum_fraction": 0.660075306892395, "avg_line_length": 56.4054069519043, "blob_id": "c7cdcb809b6b3536524000b8b7914e37c8ac0a52", "content_id": "da8cd17515205631b668340c65841809c38a17ed", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2124, "license_type": "permissive", "max_line_length": 450, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/identity/ipa/ipa_dnsrecord.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add, modify and delete an IPA DNS Record using IPA API.\n class Ipa_dnsrecord < Base\n # @return [String] The DNS zone name to which DNS record needs to be managed.\n attribute :zone_name\n validates :zone_name, presence: true, type: String\n\n # @return [String, Integer] The DNS record name to manage.\n attribute :record_name\n validates :record_name, presence: true, type: MultipleTypes.new(String, Integer)\n\n # @return [:A, :AAAA, :A6, :CNAME, :DNAME, :PTR, :TXT, nil] The type of DNS record name.,Currently, 'A', 'AAAA', 'A6', 'CNAME', 'DNAME', 'PTR' and 'TXT' are supported.,'A6', 'CNAME', 'DNAME' and 'TXT' are added in version 2.5.\n attribute :record_type\n validates :record_type, expression_inclusion: {:in=>[:A, :AAAA, :A6, :CNAME, :DNAME, :PTR, :TXT], :message=>\"%{value} needs to be :A, :AAAA, :A6, :CNAME, :DNAME, :PTR, :TXT\"}, allow_nil: true\n\n # @return [String] Manage DNS record name with this value.,In the case of 'A' or 'AAAA' record types, this will be the IP address.,In the case of 'A6' record type, this will be the A6 Record data.,In the case of 'CNAME' record type, this will be the hostname.,In the case of 'DNAME' record type, this will be the DNAME target.,In the case of 'PTR' record type, this will be the hostname.,In the case of 'TXT' record type, this will be a text.\n attribute :record_value\n validates :record_value, presence: true, type: String\n\n # @return [Integer, nil] Set the TTL for the record.,Applies only when adding a new or changing the value of record_value.\n attribute :record_ttl\n validates :record_ttl, type: Integer\n\n # @return [:present, :absent, nil] State to ensure\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.671525776386261, "alphanum_fraction": 0.6756559610366821, "avg_line_length": 43.25806427001953, "blob_id": "1e771eb96b78a223cb6db6e4ab6cb0b0a4125ca9", "content_id": "f904e5161c2bd8bd9187380fb32365bd1cd00d2e", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4116, "license_type": "permissive", "max_line_length": 251, "num_lines": 93, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_elementsw_snapshot_schedule.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, destroy, or update accounts on ElementSW\n class Na_elementsw_snapshot_schedule < Base\n # @return [:present, :absent] Whether the specified schedule should exist or not.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [Symbol, nil] Pause / Resume a schedule.\n attribute :paused\n validates :paused, type: Symbol\n\n # @return [Symbol, nil] Should the schedule recur?\n attribute :recurring\n validates :recurring, type: Symbol\n\n # @return [:DaysOfWeekFrequency, :DaysOfMonthFrequency, :TimeIntervalFrequency, nil] Schedule type for creating schedule.\n attribute :schedule_type\n validates :schedule_type, expression_inclusion: {:in=>[:DaysOfWeekFrequency, :DaysOfMonthFrequency, :TimeIntervalFrequency], :message=>\"%{value} needs to be :DaysOfWeekFrequency, :DaysOfMonthFrequency, :TimeIntervalFrequency\"}, allow_nil: true\n\n # @return [Integer, nil] Time interval in days.\n attribute :time_interval_days\n validates :time_interval_days, type: Integer\n\n # @return [Integer, nil] Time interval in hours.\n attribute :time_interval_hours\n validates :time_interval_hours, type: Integer\n\n # @return [Integer, nil] Time interval in minutes.\n attribute :time_interval_minutes\n validates :time_interval_minutes, type: Integer\n\n # @return [Object, nil] List of days of the week (Sunday to Saturday)\n attribute :days_of_week_weekdays\n\n # @return [Integer, nil] Time specified in hours\n attribute :days_of_week_hours\n validates :days_of_week_hours, type: Integer\n\n # @return [Integer, nil] Time specified in minutes.\n attribute :days_of_week_minutes\n validates :days_of_week_minutes, type: Integer\n\n # @return [Object, nil] List of days of the month (1-31)\n attribute :days_of_month_monthdays\n\n # @return [Integer, nil] Time specified in hours\n attribute :days_of_month_hours\n validates :days_of_month_hours, type: Integer\n\n # @return [Integer, nil] Time specified in minutes.\n attribute :days_of_month_minutes\n validates :days_of_month_minutes, type: Integer\n\n # @return [String, Integer, nil] Name for the snapshot schedule.,It accepts either schedule_id or schedule_name,if name is digit, it will consider as schedule_id,If name is string, it will consider as schedule_name\n attribute :name\n validates :name, type: MultipleTypes.new(String, Integer)\n\n # @return [Object, nil] Name for the created snapshots.\n attribute :snapshot_name\n\n # @return [Array<Integer>, Integer, nil] Volume IDs that you want to set the snapshot schedule for.,It accepts both volume_name and volume_id\n attribute :volumes\n validates :volumes, type: TypeGeneric.new(Integer)\n\n # @return [Integer, nil] Account ID for the owner of this volume.,It accepts either account_name or account_id,if account_id is digit, it will consider as account_id,If account_id is string, it will consider as account_name\n attribute :account_id\n validates :account_id, type: Integer\n\n # @return [Object, nil] Retention period for the snapshot.,Format is 'HH:mm:ss'.\n attribute :retention\n\n # @return [String, nil] Starting date for the schedule.,Required when C(state=present).,Format: C(2016-12-01T00:00:00Z)\n attribute :starting_date\n validates :starting_date, type: String\n\n # @return [String, nil] Element SW access account password\n attribute :password\n validates :password, type: String\n\n # @return [String, nil] Element SW access account user-name\n attribute :username\n validates :username, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6691599488258362, "alphanum_fraction": 0.6691599488258362, "avg_line_length": 45.97297286987305, "blob_id": "e514e282cb97988eeb57b7007837044d10bc7b42", "content_id": "1f93f90189b045f563454c69b6c126cffb2c37d7", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5214, "license_type": "permissive", "max_line_length": 216, "num_lines": 111, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_service_offering.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create and delete service offerings for guest and system VMs.\n # Update display_text of existing service offering.\n class Cs_service_offering < Base\n # @return [Object, nil] Bytes read rate of the disk offering.\n attribute :bytes_read_rate\n\n # @return [Object, nil] Bytes write rate of the disk offering.\n attribute :bytes_write_rate\n\n # @return [Integer, nil] The number of CPUs of the service offering.\n attribute :cpu_number\n validates :cpu_number, type: Integer\n\n # @return [Integer, nil] The CPU speed of the service offering in MHz.\n attribute :cpu_speed\n validates :cpu_speed, type: Integer\n\n # @return [Symbol, nil] Restrict the CPU usage to committed service offering.\n attribute :limit_cpu_usage\n validates :limit_cpu_usage, type: Symbol\n\n # @return [Object, nil] The deployment planner heuristics used to deploy a VM of this offering.,If not set, the value of global config C(vm.deployment.planner) is used.\n attribute :deployment_planner\n\n # @return [String, nil] Display text of the service offering.,If not set, C(name) will be used as C(display_text) while creating.\n attribute :display_text\n validates :display_text, type: String\n\n # @return [Object, nil] Domain the service offering is related to.,Public for all domains and subdomains if not set.\n attribute :domain\n\n # @return [String, nil] The host tagsfor this service offering.\n attribute :host_tags\n validates :host_tags, type: String\n\n # @return [Object, nil] Hypervisor snapshot reserve space as a percent of a volume.,Only for managed storage using Xen or VMware.\n attribute :hypervisor_snapshot_reserve\n\n # @return [Boolean, nil] Whether compute offering iops is custom or not.\n attribute :disk_iops_customized\n validates :disk_iops_customized, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] IO requests read rate of the disk offering.\n attribute :disk_iops_read_rate\n\n # @return [Object, nil] IO requests write rate of the disk offering.\n attribute :disk_iops_write_rate\n\n # @return [Object, nil] Max. iops of the compute offering.\n attribute :disk_iops_max\n\n # @return [Object, nil] Min. iops of the compute offering.\n attribute :disk_iops_min\n\n # @return [Symbol, nil] Whether it is a system VM offering or not.\n attribute :is_system\n validates :is_system, type: Symbol\n\n # @return [Symbol, nil] Whether the virtual machine needs to be volatile or not.,Every reboot of VM the root disk is detached then destroyed and a fresh root disk is created and attached to VM.\n attribute :is_volatile\n validates :is_volatile, type: Symbol\n\n # @return [Integer, nil] The total memory of the service offering in MB.\n attribute :memory\n validates :memory, type: Integer\n\n # @return [String] Name of the service offering.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Data transfer rate in Mb/s allowed.,Supported only for non-system offering and system offerings having C(system_vm_type=domainrouter).\n attribute :network_rate\n\n # @return [Symbol, nil] Whether HA is set for the service offering.\n attribute :offer_ha\n validates :offer_ha, type: Symbol\n\n # @return [:thin, :sparse, :fat, nil] Provisioning type used to create volumes.\n attribute :provisioning_type\n validates :provisioning_type, expression_inclusion: {:in=>[:thin, :sparse, :fat], :message=>\"%{value} needs to be :thin, :sparse, :fat\"}, allow_nil: true\n\n # @return [Object, nil] Details for planner, used to store specific parameters.\n attribute :service_offering_details\n\n # @return [:present, :absent, nil] State of the service offering.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:local, :shared, nil] The storage type of the service offering.\n attribute :storage_type\n validates :storage_type, expression_inclusion: {:in=>[:local, :shared], :message=>\"%{value} needs to be :local, :shared\"}, allow_nil: true\n\n # @return [:domainrouter, :consoleproxy, :secondarystoragevm, nil] The system VM type.,Required if C(is_system=true).\n attribute :system_vm_type\n validates :system_vm_type, expression_inclusion: {:in=>[:domainrouter, :consoleproxy, :secondarystoragevm], :message=>\"%{value} needs to be :domainrouter, :consoleproxy, :secondarystoragevm\"}, allow_nil: true\n\n # @return [String, nil] The storage tags for this service offering.\n attribute :storage_tags\n validates :storage_tags, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6802992224693298, "alphanum_fraction": 0.6802992224693298, "avg_line_length": 47.90243911743164, "blob_id": "c5477f1833e9679d432ff0dad2d327d4932a9fe8", "content_id": "a4d542490f20f5059e8ef9b582f86b1510544e6c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2005, "license_type": "permissive", "max_line_length": 255, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/monitoring/zabbix/zabbix_maintenance.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module will let you create Zabbix maintenance windows.\n class Zabbix_maintenance < Base\n # @return [:present, :absent, nil] Create or remove a maintenance window. Maintenance window to remove is identified by name.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] Hosts to manage maintenance window for. Separate multiple hosts with commas. C(host_name) is an alias for C(host_names). B(Required) option when C(state) is I(present) and no C(host_groups) specified.\n attribute :host_names\n validates :host_names, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] Host groups to manage maintenance window for. Separate multiple groups with commas. C(host_group) is an alias for C(host_groups). B(Required) option when C(state) is I(present) and no C(host_names) specified.\n attribute :host_groups\n validates :host_groups, type: TypeGeneric.new(String)\n\n # @return [Integer, nil] Length of maintenance window in minutes.\n attribute :minutes\n validates :minutes, type: Integer\n\n # @return [String] Unique name of maintenance window.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] Short description of maintenance window.\n attribute :desc\n validates :desc, presence: true, type: String\n\n # @return [:yes, :no, nil] Type of maintenance. With data collection, or without.\n attribute :collect_data\n validates :collect_data, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7266528010368347, "alphanum_fraction": 0.7275999188423157, "avg_line_length": 91.6140365600586, "blob_id": "b3f1c6de835d280a788f4216e08805e05a15a698", "content_id": "0e8540c0eee241380861ed26c467f63af9dda063", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5279, "license_type": "permissive", "max_line_length": 673, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/network/netscaler/netscaler_gslb_site.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage gslb site entities in Netscaler.\n class Netscaler_gslb_site < Base\n # @return [String, nil] Name for the GSLB site. Must begin with an ASCII alphanumeric or underscore C(_) character, and must contain only ASCII alphanumeric, underscore C(_), hash C(#), period C(.), space C( ), colon C(:), at C(@), equals C(=), and hyphen C(-) characters. Cannot be changed after the virtual server is created.,Minimum length = 1\n attribute :sitename\n validates :sitename, type: String\n\n # @return [:REMOTE, :LOCAL, nil] Type of site to create. If the type is not specified, the appliance automatically detects and sets the type on the basis of the IP address being assigned to the site. If the specified site IP address is owned by the appliance (for example, a MIP address or SNIP address), the site is a local site. Otherwise, it is a remote site.\n attribute :sitetype\n validates :sitetype, expression_inclusion: {:in=>[:REMOTE, :LOCAL], :message=>\"%{value} needs to be :REMOTE, :LOCAL\"}, allow_nil: true\n\n # @return [String, nil] IP address for the GSLB site. The GSLB site uses this IP address to communicate with other GSLB sites. For a local site, use any IP address that is owned by the appliance (for example, a SNIP or MIP address, or the IP address of the ADNS service).,Minimum length = 1\n attribute :siteipaddress\n validates :siteipaddress, type: String\n\n # @return [String, nil] Public IP address for the local site. Required only if the appliance is deployed in a private address space and the site has a public IP address hosted on an external firewall or a NAT device.,Minimum length = 1\n attribute :publicip\n validates :publicip, type: String\n\n # @return [:enabled, :disabled, nil] Exchange metrics with other sites. Metrics are exchanged by using Metric Exchange Protocol (MEP). The appliances in the GSLB setup exchange health information once every second.,If you disable metrics exchange, you can use only static load balancing methods (such as round robin, static proximity, or the hash-based methods), and if you disable metrics exchange when a dynamic load balancing method (such as least connection) is in operation, the appliance falls back to round robin. Also, if you disable metrics exchange, you must use a monitor to determine the state of GSLB services. Otherwise, the service is marked as DOWN.\n attribute :metricexchange\n validates :metricexchange, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] Exchange, with other GSLB sites, network metrics such as round-trip time (RTT), learned from communications with various local DNS (LDNS) servers used by clients. RTT information is used in the dynamic RTT load balancing method, and is exchanged every 5 seconds.\n attribute :nwmetricexchange\n validates :nwmetricexchange, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] Exchange persistent session entries with other GSLB sites every five seconds.\n attribute :sessionexchange\n validates :sessionexchange, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:ALWAYS, :MEPDOWN, :MEPDOWN_SVCDOWN, nil] Specify the conditions under which the GSLB service must be monitored by a monitor, if one is bound. Available settings function as follows:,* C(ALWAYS) - Monitor the GSLB service at all times.,* C(MEPDOWN) - Monitor the GSLB service only when the exchange of metrics through the Metrics Exchange Protocol (MEP) is disabled.,C(MEPDOWN_SVCDOWN) - Monitor the service in either of the following situations:,* The exchange of metrics through MEP is disabled.,* The exchange of metrics through MEP is enabled but the status of the service, learned through metrics exchange, is DOWN.\n attribute :triggermonitor\n validates :triggermonitor, expression_inclusion: {:in=>[:ALWAYS, :MEPDOWN, :MEPDOWN_SVCDOWN], :message=>\"%{value} needs to be :ALWAYS, :MEPDOWN, :MEPDOWN_SVCDOWN\"}, allow_nil: true\n\n # @return [Object, nil] Parent site of the GSLB site, in a parent-child topology.\n attribute :parentsite\n\n # @return [Object, nil] Cluster IP address. Specify this parameter to connect to the remote cluster site for GSLB auto-sync. Note: The cluster IP address is defined when creating the cluster.\n attribute :clip\n\n # @return [Object, nil] IP address to be used to globally access the remote cluster when it is deployed behind a NAT. It can be same as the normal cluster IP address.\n attribute :publicclip\n\n # @return [Object, nil] The naptr replacement suffix configured here will be used to construct the naptr replacement field in NAPTR record.,Minimum length = 1\n attribute :naptrreplacementsuffix\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7291666865348816, "alphanum_fraction": 0.7395833134651184, "avg_line_length": 31, "blob_id": "52bfd8caee021f580e68f5b5f19072eccdce2160", "content_id": "a54a2f3a7fcaa581f75a71bf4de4942d7b0e2eae", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 480, "license_type": "permissive", "max_line_length": 224, "num_lines": 15, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_metadata_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module fetches data from the instance metadata endpoint in ec2 as per http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html. The module must be called from within the EC2 instance itself.\n class Ec2_metadata_facts < Base\n\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7032535076141357, "alphanum_fraction": 0.7039685249328613, "avg_line_length": 50.796295166015625, "blob_id": "ff7872ee6874e3d5f879391d688df05df03dab74", "content_id": "0d75b99ef42d823d0ad4be7e549c8e12d946f7ae", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2797, "license_type": "permissive", "max_line_length": 576, "num_lines": 54, "path": "/lib/ansible/ruby/modules/generated/windows/win_wait_for_process.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Waiting for a process to start or stop.\n # This is useful when Windows services behave poorly and do not enumerate external dependencies in their manifest.\n class Win_wait_for_process < Base\n # @return [String, nil] The name of the process(es) for which to wait.\n attribute :process_name_exact\n validates :process_name_exact, type: String\n\n # @return [String, nil] RegEx pattern matching desired process(es).\n attribute :process_name_pattern\n validates :process_name_pattern, type: String\n\n # @return [Integer, nil] Number of seconds to sleep between checks.,Only applies when waiting for a process to start. Waiting for a process to start does not have a native non-polling mechanism. Waiting for a stop uses native PowerShell and does not require polling.\n attribute :sleep\n validates :sleep, type: Integer\n\n # @return [Integer, nil] Minimum number of process matching the supplied pattern to satisfy C(present) condition.,Only applies to C(present).\n attribute :process_min_count\n validates :process_min_count, type: Integer\n\n # @return [Integer, nil] The PID of the process.\n attribute :pid\n validates :pid, type: Integer\n\n # @return [String, nil] The owner of the process.,Requires PowerShell version 4.0 or newer.\n attribute :owner\n validates :owner, type: String\n\n # @return [Integer, nil] Seconds to wait before checking processes.\n attribute :pre_wait_delay\n validates :pre_wait_delay, type: Integer\n\n # @return [Integer, nil] Seconds to wait after checking for processes.\n attribute :post_wait_delay\n validates :post_wait_delay, type: Integer\n\n # @return [String, nil] When checking for a running process C(present) will block execution until the process exists, or until the timeout has been reached. C(absent) will block execution untile the processs no longer exists, or until the timeout has been reached.,When waiting for C(present), the module will return changed only if the process was not present on the initial check but became present on subsequent checks.,If, while waiting for C(absent), new processes matching the supplied pattern are started, these new processes will not be included in the action.\n attribute :state\n validates :state, type: String\n\n # @return [Integer, nil] The maximum number of seconds to wait for a for a process to start or stop before erroring out.\n attribute :timeout\n validates :timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6676148176193237, "alphanum_fraction": 0.6680211424827576, "avg_line_length": 41.431034088134766, "blob_id": "3c4a004d13938896041917f1a7fa3f121a219b50", "content_id": "9b76e04c741fe76033452f1863397b19aefad777", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2461, "license_type": "permissive", "max_line_length": 222, "num_lines": 58, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/sns.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The C(sns) module sends notifications to a topic on your Amazon SNS account\n class Sns < Base\n # @return [String] Default message to send.\n attribute :msg\n validates :msg, presence: true, type: String\n\n # @return [String, nil] Subject line for email delivery.\n attribute :subject\n validates :subject, type: String\n\n # @return [String] The topic you want to publish to.\n attribute :topic\n validates :topic, presence: true, type: String\n\n # @return [Object, nil] Message to send to email-only subscription\n attribute :email\n\n # @return [Object, nil] Message to send to SQS-only subscription\n attribute :sqs\n\n # @return [String, nil] Message to send to SMS-only subscription\n attribute :sms\n validates :sms, type: String\n\n # @return [Object, nil] Message to send to HTTP-only subscription\n attribute :http\n\n # @return [Object, nil] Message to send to HTTPS-only subscription\n attribute :https\n\n # @return [Object, nil] AWS secret key. If not set then the value of the AWS_SECRET_KEY environment variable is used.\n attribute :aws_secret_key\n\n # @return [Object, nil] AWS access key. If not set then the value of the AWS_ACCESS_KEY environment variable is used.\n attribute :aws_access_key\n\n # @return [Object, nil] The AWS region to use. If not specified then the value of the EC2_REGION environment variable, if any, is used.\n attribute :region\n\n # @return [Hash, nil] Dictionary of message attributes. These are optional structured data entries to be sent along to the endpoint.,This is in AWS's distinct Name/Type/Value format; see example below.\n attribute :message_attributes\n validates :message_attributes, type: Hash\n\n # @return [:json, :string] The payload format to use for the message.,This must be 'json' to support non-default messages (`http`, `https`, `email`, `sms`, `sqs`). It must be 'string' to support message_attributes.\n attribute :message_structure\n validates :message_structure, presence: true, expression_inclusion: {:in=>[:json, :string], :message=>\"%{value} needs to be :json, :string\"}\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6820899248123169, "alphanum_fraction": 0.6820899248123169, "avg_line_length": 56.417911529541016, "blob_id": "97c7aa0fb87c287f0bb826b9dcf61539c1168696", "content_id": "0cc2dfd33eb8841d53319d30cd9f0a5dcce28001", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3847, "license_type": "permissive", "max_line_length": 289, "num_lines": 67, "path": "/lib/ansible/ruby/modules/generated/identity/ipa/ipa_sudorule.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add, modify or delete sudo rule within IPA server using IPA API.\n class Ipa_sudorule < Base\n # @return [Object] Canonical name.,Can not be changed as it is the unique identifier.\n attribute :cn\n validates :cn, presence: true\n\n # @return [:all, nil] Command category the rule applies to.\n attribute :cmdcategory\n validates :cmdcategory, expression_inclusion: {:in=>[:all], :message=>\"%{value} needs to be :all\"}, allow_nil: true\n\n # @return [Object, nil] List of commands assigned to the rule.,If an empty list is passed all commands will be removed from the rule.,If option is omitted commands will not be checked or changed.\n attribute :cmd\n\n # @return [String, nil] Description of the sudo rule.\n attribute :description\n validates :description, type: String\n\n # @return [Array<String>, String, nil] List of hosts assigned to the rule.,If an empty list is passed all hosts will be removed from the rule.,If option is omitted hosts will not be checked or changed.,Option C(hostcategory) must be omitted to assign hosts.\n attribute :host\n validates :host, type: TypeGeneric.new(String)\n\n # @return [:all, nil] Host category the rule applies to.,If 'all' is passed one must omit C(host) and C(hostgroup).,Option C(host) and C(hostgroup) must be omitted to assign 'all'.\n attribute :hostcategory\n validates :hostcategory, expression_inclusion: {:in=>[:all], :message=>\"%{value} needs to be :all\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] List of host groups assigned to the rule.,If an empty list is passed all host groups will be removed from the rule.,If option is omitted host groups will not be checked or changed.,Option C(hostcategory) must be omitted to assign host groups.\n attribute :hostgroup\n validates :hostgroup, type: TypeGeneric.new(String)\n\n # @return [:all, nil] RunAs User category the rule applies to.\n attribute :runasusercategory\n validates :runasusercategory, expression_inclusion: {:in=>[:all], :message=>\"%{value} needs to be :all\"}, allow_nil: true\n\n # @return [:all, nil] RunAs Group category the rule applies to.\n attribute :runasgroupcategory\n validates :runasgroupcategory, expression_inclusion: {:in=>[:all], :message=>\"%{value} needs to be :all\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] List of options to add to the sudo rule.\n attribute :sudoopt\n validates :sudoopt, type: TypeGeneric.new(String)\n\n # @return [Object, nil] List of users assigned to the rule.,If an empty list is passed all users will be removed from the rule.,If option is omitted users will not be checked or changed.\n attribute :user\n\n # @return [:all, nil] User category the rule applies to.\n attribute :usercategory\n validates :usercategory, expression_inclusion: {:in=>[:all], :message=>\"%{value} needs to be :all\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] List of user groups assigned to the rule.,If an empty list is passed all user groups will be removed from the rule.,If option is omitted user groups will not be checked or changed.\n attribute :usergroup\n validates :usergroup, type: TypeGeneric.new(String)\n\n # @return [:present, :absent, :enabled, :disabled, nil] State to ensure\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :enabled, :disabled], :message=>\"%{value} needs to be :present, :absent, :enabled, :disabled\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6748120188713074, "alphanum_fraction": 0.6785714030265808, "avg_line_length": 28.55555534362793, "blob_id": "9deb8da3b8c0fb0804e5f4373f192b1758612a24", "content_id": "f5f299db64d4162251afd2f3b1f7a61d9bcbdcf4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 532, "license_type": "permissive", "max_line_length": 111, "num_lines": 18, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_zone_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gathering facts from the API of a zone.\n # Sets Ansible facts accessable by the key C(cloudstack_zone) and since version 2.6 also returns results.\n class Cs_zone_facts < Base\n # @return [String] Name of the zone.\n attribute :name\n validates :name, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6843137145042419, "alphanum_fraction": 0.6852940917015076, "avg_line_length": 39.79999923706055, "blob_id": "7cf67e0ff3937375b42e9073046890f06fa8d759", "content_id": "0136a03b7a17fe945e92b7beae884ad1b18a1a71", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1020, "license_type": "permissive", "max_line_length": 143, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_inspector_target.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates, updates, or deletes Amazon Inspector Assessment Targets and manages the required Resource Groups.\n class Aws_inspector_target < Base\n # @return [String] The user-defined name that identifies the assessment target. The name must be unique within the AWS account.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, nil] The state of the assessment target.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [Hash, nil] Tags of the EC2 instances to be added to the assessment target.,Required if C(state=present).\n attribute :tags\n validates :tags, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6948853731155396, "alphanum_fraction": 0.6984127163887024, "avg_line_length": 32.35293960571289, "blob_id": "6d3645fb932195645b36512b0b48b9541d89eee9", "content_id": "e18173a58bf1ba0cbc071e699573a9ec4d92cf4c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 567, "license_type": "permissive", "max_line_length": 175, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_elb_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gather facts about EC2 Elastic Load Balancers in AWS\n class Ec2_elb_facts < Base\n # @return [Array<String>, String, nil] List of ELB names to gather facts about. Pass this option to gather facts about a set of ELBs, otherwise, all ELBs are returned.\n attribute :names\n validates :names, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6706036925315857, "alphanum_fraction": 0.6706036925315857, "avg_line_length": 38.41379165649414, "blob_id": "da02576164c118954f1f3bd24b8cd7c2f0c53668", "content_id": "49789ae147a19699e86944668280366ab6803cda", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2286, "license_type": "permissive", "max_line_length": 143, "num_lines": 58, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_direct_connect_virtual_interface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, delete, or modify a Direct Connect public or private virtual interface.\n class Aws_direct_connect_virtual_interface < Base\n # @return [:present, :absent, nil] The desired state of the Direct Connect virtual interface.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] The ID of the link aggrecation group or connection to associate with the virtual interface.\n attribute :id_to_associate\n\n # @return [Symbol, nil] The type of virtual interface.\n attribute :public\n validates :public, type: Symbol\n\n # @return [String, nil] The name of the virtual interface.\n attribute :name\n validates :name, type: String\n\n # @return [Integer, nil] The VLAN ID.\n attribute :vlan\n validates :vlan, type: Integer\n\n # @return [Integer, nil] The autonomous system (AS) number for Border Gateway Protocol (BGP) configuration.\n attribute :bgp_asn\n validates :bgp_asn, type: Integer\n\n # @return [Object, nil] The authentication key for BGP configuration.\n attribute :authentication_key\n\n # @return [Object, nil] The amazon address CIDR with which to create the virtual interface.\n attribute :amazon_address\n\n # @return [Object, nil] The customer address CIDR with which to create the virtual interface.\n attribute :customer_address\n\n # @return [Object, nil] The type of IP address for the BGP peer.\n attribute :address_type\n\n # @return [Object, nil] A list of route filter prefix CIDRs with which to create the public virtual interface.\n attribute :cidr\n\n # @return [Object, nil] The virtual gateway ID required for creating a private virtual interface.\n attribute :virtual_gateway_id\n\n # @return [String, nil] The virtual interface ID.\n attribute :virtual_interface_id\n validates :virtual_interface_id, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6855962872505188, "alphanum_fraction": 0.6855962872505188, "avg_line_length": 46.24390411376953, "blob_id": "2b92ab93b5970aba4c318c6520ba8f0ecb751932", "content_id": "d532b9f00fdb3c306cfacce7dc02ce35d82c151e", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1937, "license_type": "permissive", "max_line_length": 186, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_autosupport.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Enable/Disable Autosupport\n class Na_ontap_autosupport < Base\n # @return [:present, :absent, nil] Specifies whether the AutoSupport daemon is present or absent.,When this setting is absent, delivery of all AutoSupport messages is turned off.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The name fo the filer that owns the AutoSupport Configuration.\n attribute :node_name\n validates :node_name, presence: true, type: String\n\n # @return [:http, :https, :smtp, nil] The name of the transport protocol used to deliver AutoSupport messages\n attribute :transport\n validates :transport, expression_inclusion: {:in=>[:http, :https, :smtp], :message=>\"%{value} needs to be :http, :https, :smtp\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] Specifies up to five recipients of full AutoSupport e-mail messages.\n attribute :noteto\n validates :noteto, type: TypeGeneric.new(String)\n\n # @return [String, nil] The URL used to deliver AutoSupport messages via HTTP POST\n attribute :post_url\n validates :post_url, type: String\n\n # @return [Array<String>, String, nil] List of mail server(s) used to deliver AutoSupport messages via SMTP.,Both host names and IP addresses may be used as valid input.\n attribute :mail_hosts\n validates :mail_hosts, type: TypeGeneric.new(String)\n\n # @return [Symbol, nil] Specifies whether AutoSupport notification to technical support is enabled.\n attribute :support\n validates :support, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6408790946006775, "alphanum_fraction": 0.6430768966674805, "avg_line_length": 45.42856979370117, "blob_id": "0f6a615fcaf68832d628b296a12871eece9bda84", "content_id": "0dcc8a8eecbe262086dfb8c1af4230d8b05dadd7", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2275, "license_type": "permissive", "max_line_length": 201, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/notification/hipchat.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Send a message to a Hipchat room, with options to control the formatting.\n class Hipchat < Base\n # @return [String] API token.\n attribute :token\n validates :token, presence: true, type: String\n\n # @return [String] ID or name of the room.\n attribute :room\n validates :room, presence: true, type: String\n\n # @return [String, nil] Name the message will appear to be sent from. Max length is 15 characters - above this it will be truncated.\n attribute :from\n validates :from, type: String\n\n # @return [String] The message body.\n attribute :msg\n validates :msg, presence: true, type: String\n\n # @return [:yellow, :red, :green, :purple, :gray, :random, nil] Background color for the message.\n attribute :color\n validates :color, expression_inclusion: {:in=>[:yellow, :red, :green, :purple, :gray, :random], :message=>\"%{value} needs to be :yellow, :red, :green, :purple, :gray, :random\"}, allow_nil: true\n\n # @return [:text, :html, nil] Message format.\n attribute :msg_format\n validates :msg_format, expression_inclusion: {:in=>[:text, :html], :message=>\"%{value} needs to be :text, :html\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If true, a notification will be triggered for users in the room.\n attribute :notify\n validates :notify, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] API url if using a self-hosted hipchat server. For Hipchat API version 2 use the default URI with C(/v2) instead of C(/v1).\n attribute :api\n validates :api, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7054329514503479, "alphanum_fraction": 0.7071307301521301, "avg_line_length": 46.119998931884766, "blob_id": "31367739933822b099925e4f33fab78ecc9a9bb3", "content_id": "4d7bd254241b121f5f59a1cefdd5ad685bbcebb7", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1178, "license_type": "permissive", "max_line_length": 230, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_vpc_endpoint_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gets various details related to AWS VPC Endpoints\n class Ec2_vpc_endpoint_facts < Base\n # @return [:services, :endpoints] Specifies the query action to take. Services returns the supported AWS services that can be specified when creating an endpoint.\n attribute :query\n validates :query, presence: true, expression_inclusion: {:in=>[:services, :endpoints], :message=>\"%{value} needs to be :services, :endpoints\"}\n\n # @return [Array<String>, String, nil] Get details of specific endpoint IDs,Provide this value as a list\n attribute :vpc_endpoint_ids\n validates :vpc_endpoint_ids, type: TypeGeneric.new(String)\n\n # @return [Hash, nil] A dict of filters to apply. Each dict item consists of a filter key and a filter value. See U(http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeVpcEndpoints.html) for possible filters.\n attribute :filters\n validates :filters, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6601385474205017, "alphanum_fraction": 0.6608550548553467, "avg_line_length": 52.67948532104492, "blob_id": "889a6360e3b6bb20a6123cecf1de10c48ee45217", "content_id": "86180952443173aecc2c8233505ceb8b9ec6c437", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4187, "license_type": "permissive", "max_line_length": 238, "num_lines": 78, "path": "/lib/ansible/ruby/modules/generated/windows/win_psexec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Run commands (remotely) through the PsExec service\n # Run commands as another (domain) user (with elevated privileges)\n class Win_psexec < Base\n # @return [String] The command line to run through PsExec (limited to 260 characters).\n attribute :command\n validates :command, presence: true, type: String\n\n # @return [String, nil] The location of the PsExec utility (in case it is not located in your PATH).\n attribute :executable\n validates :executable, type: String\n\n # @return [Array<String>, String, nil] The hostnames to run the command.,If not provided, the command is run locally.\n attribute :hostnames\n validates :hostnames, type: TypeGeneric.new(String)\n\n # @return [String, nil] The (remote) user to run the command as.,If not provided, the current user is used.\n attribute :username\n validates :username, type: String\n\n # @return [String, nil] The password for the (remote) user to run the command as.,This is mandatory in order authenticate yourself.\n attribute :password\n validates :password, type: String\n\n # @return [String, nil] Run the command from this (remote) directory.\n attribute :chdir\n validates :chdir, type: String\n\n # @return [:yes, :no, nil] Do not display the startup banner and copyright message.,This only works for specific versions of the PsExec binary.\n attribute :nobanner\n validates :nobanner, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Run the command without loading the account's profile.\n attribute :noprofile\n validates :noprofile, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Run the command with elevated privileges.\n attribute :elevated\n validates :elevated, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Run the program so that it interacts with the desktop on the remote system.\n attribute :interactive\n validates :interactive, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Specifies the session ID to use.,This parameter works in conjunction with I(interactive).,It has no effect when I(interactive) is set to C(no).\n attribute :session\n validates :session, type: Integer\n\n # @return [:yes, :no, nil] Run the command as limited user (strips the Administrators group and allows only privileges assigned to the Users group).\n attribute :limited\n validates :limited, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Run the remote command in the System account.\n attribute :system\n validates :system, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:background, :low, :belownormal, :abovenormal, :high, :realtime, nil] Used to run the command at a different priority.\n attribute :priority\n validates :priority, expression_inclusion: {:in=>[:background, :low, :belownormal, :abovenormal, :high, :realtime], :message=>\"%{value} needs to be :background, :low, :belownormal, :abovenormal, :high, :realtime\"}, allow_nil: true\n\n # @return [Integer, nil] The connection timeout in seconds\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [:yes, :no, nil] Wait for the application to terminate.,Only use for non-interactive applications.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6652719378471375, "alphanum_fraction": 0.668061375617981, "avg_line_length": 42.8979606628418, "blob_id": "f44f8c2195bcb2ad30e07b8e9deedbcae391a1fb", "content_id": "67631003b8bf41d05c75c7d0aa64f7ffc922e835", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2151, "license_type": "permissive", "max_line_length": 214, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/windows/win_iis_webbinding.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates, removes and configures a binding to an existing IIS Web site.\n class Win_iis_webbinding < Base\n # @return [String] Names of web site.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, nil] State of the binding.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [Integer, nil] The port to bind to / use for the new site.\n attribute :port\n validates :port, type: Integer\n\n # @return [String, nil] The IP address to bind to / use for the new site.\n attribute :ip\n validates :ip, type: String\n\n # @return [String, nil] The host header to bind to / use for the new site.,If you are creating/removing a catch-all binding, omit this parameter rather than defining it as '*'.\n attribute :host_header\n validates :host_header, type: String\n\n # @return [String, nil] The protocol to be used for the Web binding (usually HTTP, HTTPS, or FTP).\n attribute :protocol\n validates :protocol, type: String\n\n # @return [String, nil] Certificate hash (thumbprint) for the SSL binding. The certificate hash is the unique identifier for the certificate.\n attribute :certificate_hash\n validates :certificate_hash, type: String\n\n # @return [String, nil] Name of the certificate store where the certificate for the binding is located.\n attribute :certificate_store_name\n validates :certificate_store_name, type: String\n\n # @return [Integer, nil] This parameter is only valid on Server 2012 and newer.,Primarily used for enabling and disabling server name indication (SNI).,Set to c(0) to disable SNI.,Set to c(1) to enable SNI.\n attribute :ssl_flags\n validates :ssl_flags, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7072354555130005, "alphanum_fraction": 0.7084901928901672, "avg_line_length": 71.45454406738281, "blob_id": "27d1932e22caf0af0b879275fdae6453eee96cbe", "content_id": "27fca775a13dbd1e164b595adc7fd90c963da475", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2391, "license_type": "permissive", "max_line_length": 526, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vcenter_folder.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to create, delete, move and rename folder on then given datacenter.\n class Vcenter_folder < Base\n # @return [String] Name of the datacenter.\n attribute :datacenter\n validates :datacenter, presence: true, type: String\n\n # @return [String] Name of folder to be managed.,This is case sensitive parameter.,Folder name should be under 80 characters. This is a VMware restriction.\n attribute :folder_name\n validates :folder_name, presence: true, type: String\n\n # @return [String, nil] Name of the parent folder under which new folder needs to be created.,This is case sensitive parameter.,Please specify unique folder name as there is no way to detect duplicate names.,If user wants to create a folder under '/DC0/vm/vm_folder', this value will be 'vm_folder'.\n attribute :parent_folder\n validates :parent_folder, type: String\n\n # @return [:datastore, :host, :network, :vm, nil] This is type of folder.,If set to C(vm), then 'VM and Template Folder' is created under datacenter.,If set to C(host), then 'Host and Cluster Folder' is created under datacenter.,If set to C(datastore), then 'Storage Folder' is created under datacenter.,If set to C(network), then 'Network Folder' is created under datacenter.,This parameter is required, if C(state) is set to C(present) and parent_folder is absent.,This option is ignored, if C(parent_folder) is set.\n attribute :folder_type\n validates :folder_type, expression_inclusion: {:in=>[:datastore, :host, :network, :vm], :message=>\"%{value} needs to be :datastore, :host, :network, :vm\"}, allow_nil: true\n\n # @return [:present, :absent, nil] State of folder.,If set to C(present) without parent folder parameter, then folder with C(folder_type) is created.,If set to C(present) with parent folder parameter, then folder in created under parent folder. C(folder_type) is ignored.,If set to C(absent), then folder is unregistered and destroyed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.4570484459400177, "alphanum_fraction": 0.47099852561950684, "avg_line_length": 21.51239585876465, "blob_id": "2b4369a750e222075b493434d9c3e9835bed7668", "content_id": "6d02569c3a5234a5c0cadd04f00032258a3e9207", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2724, "license_type": "permissive", "max_line_length": 115, "num_lines": 121, "path": "/lib/ansible/ruby/models/playbook_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'spec_helper'\nrequire 'ansible-ruby'\n\ndescribe Ansible::Ruby::Models::Playbook do\n before do\n stub_const('Ansible::Ruby::Modules::Ec2', module_klass)\n end\n\n let(:module_klass) do\n Class.new(Ansible::Ruby::Modules::Base) do\n attribute :foo\n validates :foo, presence: true\n end\n end\n\n let(:tasks_model) { Ansible::Ruby::Models::Tasks.new items: task_array }\n let(:task_array) { [task] }\n\n let(:task) do\n Ansible::Ruby::Models::Task.new name: 'do stuff on EC2',\n module: module_klass.new(foo: 123)\n end\n\n let(:play1) do\n Ansible::Ruby::Models::Play.new tasks: tasks_model,\n name: 'play 1',\n hosts: %w[host1 host2]\n end\n\n let(:play2) do\n Ansible::Ruby::Models::Play.new tasks: tasks_model,\n name: 'play 2',\n hosts: 'host3'\n end\n\n subject(:hash) { instance.to_h }\n\n context 'basic' do\n let(:instance) do\n Ansible::Ruby::Models::Playbook.new plays: [play1, play2]\n end\n\n it do\n is_expected.to eq [\n {\n hosts: 'host1:host2',\n name: 'play 1',\n tasks: [\n {\n name: 'do stuff on EC2',\n ec2: {\n foo: 123\n }\n }\n ]\n },\n {\n hosts: 'host3',\n name: 'play 2',\n tasks: [\n {\n name: 'do stuff on EC2',\n ec2: {\n foo: 123\n }\n }\n ]\n }\n ]\n end\n end\n\n context 'includes' do\n let(:instance) do\n Ansible::Ruby::Models::Playbook.new plays: [play1],\n inclusions: [Ansible::Ruby::Models::Inclusion.new(file: 'something.yml')]\n end\n\n it do\n is_expected.to eq [\n {\n hosts: 'host1:host2',\n name: 'play 1',\n tasks: [\n {\n name: 'do stuff on EC2',\n ec2: {\n foo: 123\n }\n }\n ]\n },\n {\n include: 'something.yml'\n }\n ]\n end\n end\n\n context 'no plays' do\n let(:instance) do\n Ansible::Ruby::Models::Playbook.new\n end\n\n it 'should raise an error' do\n expect {instance.to_h}.to raise_error \"Validation failed: Plays can't be blank\"\n end\n end\n\n context 'empty plays' do\n let(:instance) do\n Ansible::Ruby::Models::Playbook.new plays: []\n end\n\n it 'should raise an error' do\n expect {instance.to_h}.to raise_error \"Validation failed: Plays can't be blank\"\n end\n end\nend\n" }, { "alpha_fraction": 0.6974548697471619, "alphanum_fraction": 0.6974548697471619, "avg_line_length": 53.13333511352539, "blob_id": "e45d7ae2b001f71b1e364c449385990822afa221", "content_id": "b76d031fa9262a186da5d4dc7fc7e5961352ade0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2436, "license_type": "permissive", "max_line_length": 308, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_trafficmanagerprofile.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and delete a Traffic Manager profile.\n class Azure_rm_trafficmanagerprofile < Base\n # @return [String] Name of a resource group where the Traffic Manager profile exists or will be created.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] Name of the Traffic Manager profile.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, nil] Assert the state of the Traffic Manager profile. Use C(present) to create or update a Traffic Manager profile and C(absent) to delete it.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] Valid azure location. Defaults to 'global' because in default public Azure cloud, Traffic Manager profile can only be deployed globally.,Reference https://docs.microsoft.com/en-us/azure/traffic-manager/quickstart-create-traffic-manager-profile#create-a-traffic-manager-profile\n attribute :location\n validates :location, type: String\n\n # @return [:enabled, :disabled, nil] The status of the Traffic Manager profile.\n attribute :profile_status\n validates :profile_status, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:performance, :priority, :weighted, :geographic, nil] The traffic routing method of the Traffic Manager profile.\n attribute :routing_method\n validates :routing_method, expression_inclusion: {:in=>[:performance, :priority, :weighted, :geographic], :message=>\"%{value} needs to be :performance, :priority, :weighted, :geographic\"}, allow_nil: true\n\n # @return [Hash, nil] The DNS settings of the Traffic Manager profile.\n attribute :dns_config\n validates :dns_config, type: Hash\n\n # @return [Array<String>, String, nil] The endpoint monitoring settings of the Traffic Manager profile.\n attribute :monitor_config\n validates :monitor_config, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7089108824729919, "alphanum_fraction": 0.7148514986038208, "avg_line_length": 30.5625, "blob_id": "bf12f93f3322ff6a7c44110e8e36dcdbd7e1bbb1", "content_id": "994bf3d204ec0241b8f3df6cf2c600bc8c8386f8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 505, "license_type": "permissive", "max_line_length": 191, "num_lines": 16, "path": "/lib/ansible/ruby/modules/generated/crypto/acme/acme_account_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows to retrieve information on accounts a CA supporting the L(ACME protocol,https://tools.ietf.org/html/draft-ietf-acme-acme-14), such as L(Let's Encrypt,https://letsencrypt.org/).\n # This module only works with the ACME v2 protocol.\n class Acme_account_facts < Base\n\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6431424617767334, "alphanum_fraction": 0.6431424617767334, "avg_line_length": 70.52381134033203, "blob_id": "b3df2819a5e1dba1b10b8a54e233c7e5c3e83c2e", "content_id": "7bdc58a154866d82bc5c8c4db7a0d8d28bcb86f0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1502, "license_type": "permissive", "max_line_length": 628, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_snmp_traps.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages SNMP traps configurations.\n class Nxos_snmp_traps < Base\n # @return [:aaa, :bfd, :bgp, :bridge, :callhome, :cfs, :config, :eigrp, :entity, :\"feature-control\", :generic, :hsrp, :license, :link, :lldp, :mmode, :ospf, :pim, :rf, :rmon, :snmp, :\"storm-control\", :stpx, :switchfabric, :syslog, :sysmgr, :system, :upgrade, :vtp, :all] Case sensitive group.\n attribute :group\n validates :group, presence: true, expression_inclusion: {:in=>[:aaa, :bfd, :bgp, :bridge, :callhome, :cfs, :config, :eigrp, :entity, :\"feature-control\", :generic, :hsrp, :license, :link, :lldp, :mmode, :ospf, :pim, :rf, :rmon, :snmp, :\"storm-control\", :stpx, :switchfabric, :syslog, :sysmgr, :system, :upgrade, :vtp, :all], :message=>\"%{value} needs to be :aaa, :bfd, :bgp, :bridge, :callhome, :cfs, :config, :eigrp, :entity, :\\\"feature-control\\\", :generic, :hsrp, :license, :link, :lldp, :mmode, :ospf, :pim, :rf, :rmon, :snmp, :\\\"storm-control\\\", :stpx, :switchfabric, :syslog, :sysmgr, :system, :upgrade, :vtp, :all\"}\n\n # @return [:enabled, :disabled, nil] Manage the state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6799601316452026, "alphanum_fraction": 0.6809571385383606, "avg_line_length": 39.119998931884766, "blob_id": "eed51cea0cf0a70e3e3b995abf8bd87877ab531d", "content_id": "08e8416282c8a2a7badc2a305edab653381c9f11", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1003, "license_type": "permissive", "max_line_length": 143, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/system/capabilities.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module manipulates files privileges using the Linux capabilities(7) system.\n class Capabilities < Base\n # @return [String] Specifies the path to the file to be managed.\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [String] Desired capability to set (with operator and flags, if state is C(present)) or remove (if state is C(absent))\n attribute :capability\n validates :capability, presence: true, type: String\n\n # @return [:absent, :present, nil] Whether the entry should be present or absent in the file's capabilities.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6749634146690369, "alphanum_fraction": 0.6866764426231384, "avg_line_length": 46.10344696044922, "blob_id": "80e787ea01ba5db1f99e32df86f79c414a5c6566", "content_id": "0d1cf8062ac1ddbd1a7403bb1201ced8f359e988", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1366, "license_type": "permissive", "max_line_length": 239, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_acl_interface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages applying ACLs to interfaces on HUAWEI CloudEngine switches.\n class Ce_acl_interface < Base\n # @return [Object] ACL number or name. For a numbered rule group, the value ranging from 2000 to 4999. For a named rule group, the value is a string of 1 to 32 case-sensitive characters starting with a letter, spaces not supported.\n attribute :acl_name\n validates :acl_name, presence: true\n\n # @return [Object] Interface name. Only support interface full name, such as \"40GE2/0/1\".\n attribute :interface\n validates :interface, presence: true\n\n # @return [:inbound, :outbound] Direction ACL to be applied in on the interface.\n attribute :direction\n validates :direction, presence: true, expression_inclusion: {:in=>[:inbound, :outbound], :message=>\"%{value} needs to be :inbound, :outbound\"}\n\n # @return [:present, :absent, nil] Determines whether the config should be present or not on the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7181699275970459, "alphanum_fraction": 0.7181699275970459, "avg_line_length": 66.10526275634766, "blob_id": "e807511df1858b67e59549c9389072c87c87a08f", "content_id": "6dc40044cf60f7c0ed35fe6224ba81573e077888", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3825, "license_type": "permissive", "max_line_length": 357, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_deployment.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or destroy Azure Resource Manager template deployments via the Azure SDK for Python. You can find some quick start templates in GitHub here https://github.com/azure/azure-quickstart-templates. For more information on Azue resource manager templates see https://azure.microsoft.com/en-us/documentation/articles/resource-group-template-deploy/.\n class Azure_rm_deployment < Base\n # @return [String] The resource group name to use or create to host the deployed template\n attribute :resource_group_name\n validates :resource_group_name, presence: true, type: String\n\n # @return [String, nil] The geo-locations in which the resource group will be located.\n attribute :location\n validates :location, type: String\n\n # @return [:complete, :incremental, nil] In incremental mode, resources are deployed without deleting existing resources that are not included in the template. In complete mode resources are deployed and existing resources in the resource group not included in the template are deleted.\n attribute :deployment_mode\n validates :deployment_mode, expression_inclusion: {:in=>[:complete, :incremental], :message=>\"%{value} needs to be :complete, :incremental\"}, allow_nil: true\n\n # @return [:present, :absent, nil] If state is \"present\", template will be created. If state is \"present\" and if deployment exists, it will be updated. If state is \"absent\", stack will be removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Hash, nil] A hash containing the templates inline. This parameter is mutually exclusive with 'template_link'. Either one of them is required if \"state\" parameter is \"present\".\n attribute :template\n validates :template, type: Hash\n\n # @return [String, nil] Uri of file containing the template body. This parameter is mutually exclusive with 'template'. Either one of them is required if \"state\" parameter is \"present\".\n attribute :template_link\n validates :template_link, type: String\n\n # @return [Hash, nil] A hash of all the required template variables for the deployment template. This parameter is mutually exclusive with 'parameters_link'. Either one of them is required if \"state\" parameter is \"present\".\n attribute :parameters\n validates :parameters, type: Hash\n\n # @return [String, nil] Uri of file containing the parameters body. This parameter is mutually exclusive with 'parameters'. Either one of them is required if \"state\" parameter is \"present\".\n attribute :parameters_link\n validates :parameters_link, type: String\n\n # @return [String, nil] The name of the deployment to be tracked in the resource group deployment history. Re-using a deployment name will overwrite the previous value in the resource group's deployment history.\n attribute :deployment_name\n validates :deployment_name, type: String\n\n # @return [:yes, :no, nil] Whether or not to block until the deployment has completed.\n attribute :wait_for_deployment_completion\n validates :wait_for_deployment_completion, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Time (in seconds) to wait between polls when waiting for deployment completion.\n attribute :wait_for_deployment_polling_period\n validates :wait_for_deployment_polling_period, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7505738139152527, "alphanum_fraction": 0.7505738139152527, "avg_line_length": 51.279998779296875, "blob_id": "f8c1edc67ac777ba73541cd74540f695d29f246c", "content_id": "177b5472bd292115634c3daeaca2bc396c401be1", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1307, "license_type": "permissive", "max_line_length": 392, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_gtm_global.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages global GTM settings. These settings include general, load balancing, and metrics related settings.\n class Bigip_gtm_global < Base\n # @return [Symbol, nil] Specifies whether this system is a member of a synchronization group.,When you enable synchronization, the system periodically queries other systems in the synchronization group to obtain and distribute configuration and metrics collection updates.,The synchronization group may contain systems configured as Global Traffic Manager and Link Controller systems.\n attribute :synchronization\n validates :synchronization, type: Symbol\n\n # @return [String, nil] Specifies the name of the synchronization group to which the system belongs.\n attribute :synchronization_group_name\n validates :synchronization_group_name, type: String\n\n # @return [Symbol, nil] Specifies that the system synchronizes Domain Name System (DNS) zone files among the synchronization group members.\n attribute :synchronize_zone_files\n validates :synchronize_zone_files, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6841967105865479, "alphanum_fraction": 0.6944517493247986, "avg_line_length": 61.344261169433594, "blob_id": "1bec194828eb252810f3316d0ccbd100e3bf7476", "content_id": "25873dfc76d8bc9b69e4ae5523deecf4722c291a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3803, "license_type": "permissive", "max_line_length": 740, "num_lines": 61, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_vpc_vpn.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module creates, modifies, and deletes VPN connections. Idempotence is achieved by using the filters option or specifying the VPN connection identifier.\n class Ec2_vpc_vpn < Base\n # @return [:present, :absent, nil] The desired state of the VPN connection.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] The ID of the customer gateway.\n attribute :customer_gateway_id\n validates :customer_gateway_id, type: String\n\n # @return [:\"ipsec.1\", nil] The type of VPN connection.\n attribute :connection_type\n validates :connection_type, expression_inclusion: {:in=>[:\"ipsec.1\"], :message=>\"%{value} needs to be :\\\"ipsec.1\\\"\"}, allow_nil: true\n\n # @return [String, nil] The ID of the virtual private gateway.\n attribute :vpn_gateway_id\n validates :vpn_gateway_id, type: String\n\n # @return [String, nil] The ID of the VPN connection. Required to modify or delete a connection if the filters option does not provide a unique match.\n attribute :vpn_connection_id\n validates :vpn_connection_id, type: String\n\n # @return [Hash, nil] Tags to attach to the VPN connection.\n attribute :tags\n validates :tags, type: Hash\n\n # @return [Symbol, nil] Whether or not to delete VPN connections tags that are associated with the connection but not specified in the task.\n attribute :purge_tags\n validates :purge_tags, type: Symbol\n\n # @return [Boolean, nil] Indicates whether the VPN connection uses static routes only. Static routes must be used for devices that don't support BGP.\n attribute :static_only\n validates :static_only, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash, nil] An optional list object containing no more than two dict members, each of which may contain 'TunnelInsideCidr' and/or 'PreSharedKey' keys with appropriate string values. AWS defaults will apply in absence of either of the aforementioned keys.\n attribute :tunnel_options\n validates :tunnel_options, type: TypeGeneric.new(Hash)\n\n # @return [Hash, nil] An alternative to using vpn_connection_id. If multiple matches are found, vpn_connection_id is required. If one of the following suboptions is a list of items to filter by, only one item needs to match to find the VPN that correlates. e.g. if the filter 'cidr' is ['194.168.2.0/24', '192.168.2.0/24'] and the VPN route only has the destination cidr block of '192.168.2.0/24' it will be found with this filter (assuming there are not multiple VPNs that are matched). Another example, if the filter 'vpn' is equal to ['vpn-ccf7e7ad', 'vpn-cb0ae2a2'] and one of of the VPNs has the state deleted (exists but is unmodifiable) and the other exists and is not deleted, it will be found via this filter. See examples.\n attribute :filters\n validates :filters, type: Hash\n\n # @return [Array<String>, String, nil] Routes to add to the connection.\n attribute :routes\n validates :routes, type: TypeGeneric.new(String, NilClass)\n\n # @return [Boolean, nil] Whether or not to delete VPN connections routes that are not specified in the task.\n attribute :purge_routes\n validates :purge_routes, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6937119960784912, "alphanum_fraction": 0.6957403421401978, "avg_line_length": 45.9523811340332, "blob_id": "4467451fcd223a3847153964af2527afa99cd0f0", "content_id": "b899310602f205de124485184f92d4c647863077", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 986, "license_type": "permissive", "max_line_length": 339, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/monitoring/icinga2_feature.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to enable or disable an Icinga2 feature.\n class Icinga2_feature < Base\n # @return [String] This is the feature name to enable or disable.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] If set to C(present) and feature is disabled, then feature is enabled.,If set to C(present) and feature is already enabled, then nothing is changed.,If set to C(absent) and feature is enabled, then feature is disabled.,If set to C(absent) and feature is already disabled, then nothing is changed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6844143271446228, "alphanum_fraction": 0.6844143271446228, "avg_line_length": 40.31999969482422, "blob_id": "04f58175d4c5d05da0424c645cc3f50e67ac8938", "content_id": "a7cd74a6021d6b905ee66833135ec6d125b562e2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1033, "license_type": "permissive", "max_line_length": 176, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/system/selinux.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configures the SELinux mode and policy. A reboot may be required after usage. Ansible will not issue this reboot but will let you know when it is required.\n class Selinux < Base\n # @return [String, nil] name of the SELinux policy to use (example: C(targeted)) will be required if state is not C(disabled)\n attribute :policy\n validates :policy, type: String\n\n # @return [:enforcing, :permissive, :disabled] The SELinux mode\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:enforcing, :permissive, :disabled], :message=>\"%{value} needs to be :enforcing, :permissive, :disabled\"}\n\n # @return [String, nil] path to the SELinux configuration file, if non-standard\n attribute :conf\n validates :conf, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6888708472251892, "alphanum_fraction": 0.689683198928833, "avg_line_length": 42.96428680419922, "blob_id": "c3f79d55d72868b81f63bb51bbee0343b8bdafbb", "content_id": "8b429cbacbefe4d771e709f3279644a31e06cdcf", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1231, "license_type": "permissive", "max_line_length": 295, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/system/selinux_permissive.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add and remove domain from the list of permissive domain.\n class Selinux_permissive < Base\n # @return [Object] the domain that will be added or removed from the list of permissive domains\n attribute :domain\n validates :domain, presence: true\n\n # @return [Symbol] indicate if the domain should or should not be set as permissive\n attribute :permissive\n validates :permissive, presence: true, type: Symbol\n\n # @return [:yes, :no, nil] automatically reload the policy after a change,default is set to 'false' as that's what most people would want after changing one domain,Note that this doesn't work on older version of the library (example EL 6), the module will silently ignore it in this case\n attribute :no_reload\n validates :no_reload, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] name of the SELinux policy store to use\n attribute :store\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6753782629966736, "alphanum_fraction": 0.6774415373802185, "avg_line_length": 46.6721305847168, "blob_id": "e7d37a58197291f8e0e481882cdb7193f575529d", "content_id": "49c75704c7a04e64913b818d9bf54ec9a2afe507", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2908, "license_type": "permissive", "max_line_length": 304, "num_lines": 61, "path": "/lib/ansible/ruby/modules/generated/identity/ipa/ipa_host.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add, modify and delete an IPA host using IPA API\n class Ipa_host < Base\n # @return [Object] Full qualified domain name.,Can not be changed as it is the unique identifier.\n attribute :fqdn\n validates :fqdn, presence: true\n\n # @return [String, nil] A description of this host.\n attribute :description\n validates :description, type: String\n\n # @return [Symbol, nil] Force host name even if not in DNS.\n attribute :force\n validates :force, type: Symbol\n\n # @return [String, nil] Add the host to DNS with this IP address.\n attribute :ip_address\n validates :ip_address, type: String\n\n # @return [Array<String>, String, nil] List of Hardware MAC address(es) off this host.,If option is omitted MAC addresses will not be checked or changed.,If an empty list is passed all assigned MAC addresses will be removed.,MAC addresses that are already assigned but not passed will be removed.\n attribute :mac_address\n validates :mac_address, type: TypeGeneric.new(String)\n\n # @return [String, nil] Host location (e.g. \"Lab 2\")\n attribute :ns_host_location\n validates :ns_host_location, type: String\n\n # @return [String, nil] Host hardware platform (e.g. \"Lenovo T61\")\n attribute :ns_hardware_platform\n validates :ns_hardware_platform, type: String\n\n # @return [String, nil] Host operating system and version (e.g. \"Fedora 9\")\n attribute :ns_os_version\n validates :ns_os_version, type: String\n\n # @return [Array<NilClass>, NilClass, nil] List of Base-64 encoded server certificates.,If option is omitted certificates will not be checked or changed.,If an empty list is passed all assigned certificates will be removed.,Certificates already assigned but not passed will be removed.\n attribute :user_certificate\n validates :user_certificate, type: TypeGeneric.new(NilClass)\n\n # @return [:present, :absent, :enabled, :disabled, nil] State to ensure\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :enabled, :disabled], :message=>\"%{value} needs to be :present, :absent, :enabled, :disabled\"}, allow_nil: true\n\n # @return [Symbol, nil] If set C(\"True\") with state as C(\"absent\"), then removes DNS records of the host managed by FreeIPA DNS.,This option has no effect for states other than \"absent\".\n attribute :update_dns\n validates :update_dns, type: Symbol\n\n # @return [Symbol, nil] Generate a random password to be used in bulk enrollment\n attribute :random_password\n validates :random_password, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6804407835006714, "alphanum_fraction": 0.6804407835006714, "avg_line_length": 50.85714340209961, "blob_id": "ba498c63c7ed95be63e98f410a486a1199ab9f67", "content_id": "170c55695c23e8f01889d3c9605db41a62e4f317", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2178, "license_type": "permissive", "max_line_length": 211, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/system/beadm.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, delete or activate ZFS boot environments.\n # Mount and unmount ZFS boot environments.\n class Beadm < Base\n # @return [String] ZFS boot environment name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Boolean, nil] If specified, the new boot environment will be cloned from the given snapshot or inactive boot environment.\n attribute :snapshot\n validates :snapshot, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Associate a description with a new boot environment. This option is available only on Solarish platforms.\n attribute :description\n validates :description, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Create the datasets for new BE with specific ZFS properties. Multiple options can be specified. This option is available only on Solarish platforms.\n attribute :options\n validates :options, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Path where to mount the ZFS boot environment\n attribute :mountpoint\n validates :mountpoint, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:present, :absent, :activated, :mounted, :unmounted, nil] Create or delete ZFS boot environment.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :activated, :mounted, :unmounted], :message=>\"%{value} needs to be :present, :absent, :activated, :mounted, :unmounted\"}, allow_nil: true\n\n # @return [Symbol, nil] Specifies if the unmount should be forced.\n attribute :force\n validates :force, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6748377680778503, "alphanum_fraction": 0.6748377680778503, "avg_line_length": 41.030303955078125, "blob_id": "32db390555d11499b4632c3c2c73edfe7d916222", "content_id": "c1e43c4bde5ea081e1374aaa85df941807f88fbd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1387, "license_type": "permissive", "max_line_length": 264, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_snapshot.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Module to manage Virtual Machine Snapshots in oVirt/RHV\n class Ovirt_snapshot < Base\n # @return [String, nil] ID of the snapshot to manage.\n attribute :snapshot_id\n validates :snapshot_id, type: String\n\n # @return [String] Name of the Virtual Machine to manage.\n attribute :vm_name\n validates :vm_name, presence: true, type: String\n\n # @return [:restore, :present, :absent, nil] Should the Virtual Machine snapshot be restore/present/absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:restore, :present, :absent], :message=>\"%{value} needs to be :restore, :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Description of the snapshot.\n attribute :description\n validates :description, type: String\n\n # @return [Symbol, nil] If I(true) and C(state) is I(present) save memory of the Virtual Machine if it's running.,If I(true) and C(state) is I(restore) restore memory of the Virtual Machine.,Note that Virtual Machine will be paused while saving the memory.\n attribute :use_memory\n validates :use_memory, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6637246012687683, "alphanum_fraction": 0.6637246012687683, "avg_line_length": 33.33333206176758, "blob_id": "a824d466ad586f3e144383ee1e3064bf9f92b548", "content_id": "3150cc064c3e8d9d98449f5bb576ae26b90581f0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1133, "license_type": "permissive", "max_line_length": 128, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/network/panos/panos_mgtconfig.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configure management settings of device\n class Panos_mgtconfig < Base\n # @return [String, nil] address of primary DNS server\n attribute :dns_server_primary\n validates :dns_server_primary, type: String\n\n # @return [String, nil] address of secondary DNS server\n attribute :dns_server_secondary\n validates :dns_server_secondary, type: String\n\n # @return [String, nil] address of primary Panorama server\n attribute :panorama_primary\n validates :panorama_primary, type: String\n\n # @return [String, nil] address of secondary Panorama server\n attribute :panorama_secondary\n validates :panorama_secondary, type: String\n\n # @return [:yes, :no, nil] commit if changed\n attribute :commit\n validates :commit, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6465256810188293, "alphanum_fraction": 0.6471970677375793, "avg_line_length": 39.80821990966797, "blob_id": "fbaa44f3b10df99858539d6980d2f689bbd5bea6", "content_id": "34d8285666640dbd61ec5e48a2caca2080b2559f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2979, "license_type": "permissive", "max_line_length": 147, "num_lines": 73, "path": "/lib/ansible/ruby/modules/generated/source_control/gitlab_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # When the user does not exist in Gitlab, it will be created.\n # When the user does exists and state=absent, the user will be deleted.\n # When changes are made to user, the user will be updated.\n class Gitlab_user < Base\n # @return [String] Url of Gitlab server, with protocol (http or https).\n attribute :server_url\n validates :server_url, presence: true, type: String\n\n # @return [:yes, :no, nil] When using https if SSL certificate needs to be verified.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Gitlab user name.\n attribute :login_user\n validates :login_user, type: String\n\n # @return [String, nil] Gitlab password for login_user\n attribute :login_password\n validates :login_password, type: String\n\n # @return [String, nil] Gitlab token for logging in.\n attribute :login_token\n validates :login_token, type: String\n\n # @return [String] Name of the user you want to create\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] The username of the user.\n attribute :username\n validates :username, presence: true, type: String\n\n # @return [String] The password of the user.,GitLab server enforces minimum password length to 8, set this value with 8 or more characters.\n attribute :password\n validates :password, presence: true, type: String\n\n # @return [String] The email that belongs to the user.\n attribute :email\n validates :email, presence: true, type: String\n\n # @return [String, nil] The name of the sshkey\n attribute :sshkey_name\n validates :sshkey_name, type: String\n\n # @return [String, nil] The ssh key itself.\n attribute :sshkey_file\n validates :sshkey_file, type: String\n\n # @return [Object, nil] Add user as an member to this group.\n attribute :group\n\n # @return [Object, nil] The access level to the group. One of the following can be used.,guest,reporter,developer,master,owner\n attribute :access_level\n\n # @return [:present, :absent, nil] create or delete group.,Possible values are present and absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Require confirmation.\n attribute :confirm\n validates :confirm, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6690140962600708, "alphanum_fraction": 0.669718325138092, "avg_line_length": 43.375, "blob_id": "383ee4e17f44e2b8aa89c5fcda9e90d8ddcb21bf", "content_id": "6e710af204e27dea8994f1441f3feb566b6ab995", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1420, "license_type": "permissive", "max_line_length": 360, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_resourcelimit.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage limits of resources for domains, accounts and projects.\n class Cs_resourcelimit < Base\n # @return [:instance, :ip_address, :volume, :snapshot, :template, :network, :vpc, :cpu, :memory, :primary_storage, :secondary_storage] Type of the resource.\n attribute :resource_type\n validates :resource_type, presence: true, expression_inclusion: {:in=>[:instance, :ip_address, :volume, :snapshot, :template, :network, :vpc, :cpu, :memory, :primary_storage, :secondary_storage], :message=>\"%{value} needs to be :instance, :ip_address, :volume, :snapshot, :template, :network, :vpc, :cpu, :memory, :primary_storage, :secondary_storage\"}\n\n # @return [Integer, nil] Maximum number of the resource.,Default is unlimited C(-1).\n attribute :limit\n validates :limit, type: Integer\n\n # @return [String, nil] Domain the resource is related to.\n attribute :domain\n validates :domain, type: String\n\n # @return [String, nil] Account the resource is related to.\n attribute :account\n validates :account, type: String\n\n # @return [Object, nil] Name of the project the resource is related to.\n attribute :project\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6690179109573364, "alphanum_fraction": 0.6690179109573364, "avg_line_length": 48.81081008911133, "blob_id": "a726946a95646a5559ecbd95750f10028a30914d", "content_id": "f98ac65a23ca1f6cf2ef906a8ced73d4805da828", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1843, "license_type": "permissive", "max_line_length": 336, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/packaging/os/homebrew.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages Homebrew packages\n class Homebrew < Base\n # @return [Array<String>, String, nil] list of names of packages to install/remove\n attribute :name\n validates :name, type: TypeGeneric.new(String)\n\n # @return [String, nil] A ':' separated list of paths to search for 'brew' executable. Since a package (I(formula) in homebrew parlance) location is prefixed relative to the actual path of I(brew) command, providing an alternative I(brew) path enables managing different set of packages in an alternative location in the system.\n attribute :path\n validates :path, type: String\n\n # @return [:head, :latest, :present, :absent, :linked, :unlinked, nil] state of the package\n attribute :state\n validates :state, expression_inclusion: {:in=>[:head, :latest, :present, :absent, :linked, :unlinked], :message=>\"%{value} needs to be :head, :latest, :present, :absent, :linked, :unlinked\"}, allow_nil: true\n\n # @return [:yes, :no, nil] update homebrew itself first\n attribute :update_homebrew\n validates :update_homebrew, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] upgrade all homebrew packages\n attribute :upgrade_all\n validates :upgrade_all, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] options flags to install a package\n attribute :install_options\n validates :install_options, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7023809552192688, "alphanum_fraction": 0.7023809552192688, "avg_line_length": 31.66666603088379, "blob_id": "3fe357ef152cc15114147cfedb0c89f424549791", "content_id": "5bf530d927eedcbab188449c203aab2c17cfe64c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 588, "license_type": "permissive", "max_line_length": 151, "num_lines": 18, "path": "/lib/ansible/ruby/modules/generated/cloud/atomic/atomic_host.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage the atomic host platform.\n # Rebooting of Atomic host platform should be done outside this module.\n class Atomic_host < Base\n # @return [String, nil] The version number of the atomic host to be deployed. Providing C(latest) will upgrade to the latest available version.\n attribute :revision\n validates :revision, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6636011600494385, "alphanum_fraction": 0.6636011600494385, "avg_line_length": 42.04166793823242, "blob_id": "bbfe30ba6a58fd792d5e4c5bc2a25b7ade867a23", "content_id": "c445fc01134fd7af0de468d628b5b0800e518f1c", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2066, "license_type": "permissive", "max_line_length": 145, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_volume_clone.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create NetApp ONTAP volume clones.\n # A FlexClone License is required to use this module\n class Na_ontap_volume_clone < Base\n # @return [:present, nil] Whether volume clone should be created.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present], :message=>\"%{value} needs to be :present\"}, allow_nil: true\n\n # @return [String] The parent volume of the volume clone being created.\n attribute :parent_volume\n validates :parent_volume, presence: true, type: String\n\n # @return [String] The name of the volume clone being created.\n attribute :volume\n validates :volume, presence: true, type: String\n\n # @return [String] Vserver in which the volume clone should be created.\n attribute :vserver\n validates :vserver, presence: true, type: String\n\n # @return [String, nil] Parent snapshot in which volume clone is created off.\n attribute :parent_snapshot\n validates :parent_snapshot, type: String\n\n # @return [Object, nil] Vserver of parent volume in which clone is created off.\n attribute :parent_vserver\n\n # @return [Object, nil] The qos-policy-group-name which should be set for volume clone.\n attribute :qos_policy_group_name\n\n # @return [:volume, :none, nil] The space_reserve setting which should be used for the volume clone.\n attribute :space_reserve\n validates :space_reserve, expression_inclusion: {:in=>[:volume, :none], :message=>\"%{value} needs to be :volume, :none\"}, allow_nil: true\n\n # @return [:rw, :dp, nil] The volume-type setting which should be used for the volume clone.\n attribute :volume_type\n validates :volume_type, expression_inclusion: {:in=>[:rw, :dp], :message=>\"%{value} needs to be :rw, :dp\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6790270209312439, "alphanum_fraction": 0.687629759311676, "avg_line_length": 55.18333435058594, "blob_id": "2adf50bcfe94a7d910a02592e04d2a4d003f775e", "content_id": "738610126a4688825cabd2a6f88634a974c17551", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3371, "license_type": "permissive", "max_line_length": 307, "num_lines": 60, "path": "/lib/ansible/ruby/modules/generated/windows/win_chocolatey_source.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Used to managed Chocolatey sources configured on the client.\n # Requires Chocolatey to be already installed on the remote host.\n class Win_chocolatey_source < Base\n # @return [Symbol, nil] Makes the source visible to Administrators only.,Requires Chocolatey >= 0.10.8.,When creating a new source, this defaults to C(False).\n attribute :admin_only\n validates :admin_only, type: Symbol\n\n # @return [Symbol, nil] Allow the source to be used with self-service,Requires Chocolatey >= 0.10.4.,When creating a new source, this defaults to C(False).\n attribute :allow_self_service\n validates :allow_self_service, type: Symbol\n\n # @return [Symbol, nil] Bypass the proxy when using this source.,Requires Chocolatey >= 0.10.4.,When creating a new source, this defaults to C(False).\n attribute :bypass_proxy\n validates :bypass_proxy, type: Symbol\n\n # @return [Object, nil] The path to a .pfx file to use for X509 authenticated feeds.,Requires Chocolatey >= 0.9.10.\n attribute :certificate\n\n # @return [Object, nil] The password for I(certificate) if required.,Requires Chocolatey >= 0.9.10.\n attribute :certificate_password\n\n # @return [String] The name of the source to configure.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Integer, nil] The priority order of this source compared to other sources, lower is better.,All priorities above C(0) will be evaluated first, then zero-based values will be evaluated in config file order.,Requires Chocolatey >= 0.9.9.9.,When creating a new source, this defaults to C(0).\n attribute :priority\n validates :priority, type: Integer\n\n # @return [String, nil] The file/folder/url of the source.,Required when I(state) is C(present) or C(disabled).\n attribute :source\n validates :source, type: String\n\n # @return [String, nil] The username used to access I(source).\n attribute :source_username\n validates :source_username, type: String\n\n # @return [String, nil] The password for I(source_username).,Required if I(source_username) is set.\n attribute :source_password\n validates :source_password, type: String\n\n # @return [:absent, :disabled, :present, nil] When C(absent), will remove the source.,When C(disabled), will ensure the source exists but is disabled.,When C(present), will ensure the source exists and is enabled.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :disabled, :present], :message=>\"%{value} needs to be :absent, :disabled, :present\"}, allow_nil: true\n\n # @return [:always, :on_create, nil] When C(always), the module will always set the password and report a change if I(certificate_password) or I(source_password) is set.,When C(on_create), the module will only set the password if the source is being created.\n attribute :update_password\n validates :update_password, expression_inclusion: {:in=>[:always, :on_create], :message=>\"%{value} needs to be :always, :on_create\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7044812440872192, "alphanum_fraction": 0.7081146836280823, "avg_line_length": 59.414634704589844, "blob_id": "12a16c2009fa64db93e1a9f6f313049e2b5128c1", "content_id": "9a5fcbaf1a00092b426986d4d453c04856f742ae", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2477, "license_type": "permissive", "max_line_length": 323, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_direct_connect_connection.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, or delete a Direct Connect connection between a network and a specific AWS Direct Connect location. Upon creation the connection may be added to a link aggregation group or established as a standalone connection. The connection may later be associated or disassociated with a link aggregation group.\n class Aws_direct_connect_connection < Base\n # @return [:present, :absent, nil] The state of the Direct Connect connection.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] The name of the Direct Connect connection. This is required to create a new connection. To recreate or delete a connection I(name) or I(connection_id) is required.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] The ID of the Direct Connect connection. I(name) or I(connection_id) is required to recreate or delete a connection. Modifying attributes of a connection with I(forced_update) will result in a new Direct Connect connection ID.\n attribute :connection_id\n validates :connection_id, type: String\n\n # @return [String, nil] Where the Direct Connect connection is located. Required when I(state=present).\n attribute :location\n validates :location, type: String\n\n # @return [:\"1Gbps\", :\"10Gbps\", nil] The bandwidth of the Direct Connect connection. Required when I(state=present).\n attribute :bandwidth\n validates :bandwidth, expression_inclusion: {:in=>[:\"1Gbps\", :\"10Gbps\"], :message=>\"%{value} needs to be :\\\"1Gbps\\\", :\\\"10Gbps\\\"\"}, allow_nil: true\n\n # @return [String, nil] The ID of the link aggregation group you want to associate with the connection. This is optional in case a stand-alone connection is desired.\n attribute :link_aggregation_group\n validates :link_aggregation_group, type: String\n\n # @return [Symbol, nil] To modify bandwidth or location the connection will need to be deleted and recreated. By default this will not happen - this option must be set to True.\n attribute :forced_update\n validates :forced_update, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6491777896881104, "alphanum_fraction": 0.6574001312255859, "avg_line_length": 44.60714340209961, "blob_id": "f5d47c55e044e8ac73f8b19feac8d98e34cfaf6e", "content_id": "1eebc7d61058f86e6ca330733f6b25119d9f483c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2554, "license_type": "permissive", "max_line_length": 170, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_security_group_rule.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or Remove rule from an existing security group\n class Os_security_group_rule < Base\n # @return [String] Name or ID of the security group\n attribute :security_group\n validates :security_group, presence: true, type: String\n\n # @return [:tcp, :udp, :icmp, 112, :None, nil] IP protocols TCP UDP ICMP 112 (VRRP)\n attribute :protocol\n validates :protocol, expression_inclusion: {:in=>[:tcp, :udp, :icmp, 112, :None], :message=>\"%{value} needs to be :tcp, :udp, :icmp, 112, :None\"}, allow_nil: true\n\n # @return [Integer, nil] Starting port\n attribute :port_range_min\n validates :port_range_min, type: Integer\n\n # @return [Integer, nil] Ending port\n attribute :port_range_max\n validates :port_range_max, type: Integer\n\n # @return [String, nil] Source IP address(es) in CIDR notation (exclusive with remote_group)\n attribute :remote_ip_prefix\n validates :remote_ip_prefix, type: String\n\n # @return [String, nil] Name or ID of the Security group to link (exclusive with remote_ip_prefix)\n attribute :remote_group\n validates :remote_group, type: String\n\n # @return [:IPv4, :IPv6, nil] Must be IPv4 or IPv6, and addresses represented in CIDR must match the ingress or egress rules. Not all providers support IPv6.\n attribute :ethertype\n validates :ethertype, expression_inclusion: {:in=>[:IPv4, :IPv6], :message=>\"%{value} needs to be :IPv4, :IPv6\"}, allow_nil: true\n\n # @return [:egress, :ingress, nil] The direction in which the security group rule is applied. Not all providers support egress.\n attribute :direction\n validates :direction, expression_inclusion: {:in=>[:egress, :ingress], :message=>\"%{value} needs to be :egress, :ingress\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Should the resource be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Unique name or ID of the project.\n attribute :project\n validates :project, type: String\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.666536808013916, "alphanum_fraction": 0.666536808013916, "avg_line_length": 39.74603271484375, "blob_id": "3eb53f770ba532b5c89454185fdeb9c4f594df80", "content_id": "8711b7419fc55d14fed3d21fe13577581181e604", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2567, "license_type": "permissive", "max_line_length": 184, "num_lines": 63, "path": "/lib/ansible/ruby/modules/generated/network/fortimanager/fmgr_script.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create/edit/delete scripts and execute the scripts on the FortiManager using jsonrpc API\n class Fmgr_script < Base\n # @return [String] The administrative domain (admon) the configuration belongs to\n attribute :adom\n validates :adom, presence: true, type: String\n\n # @return [Object, nil] The virtual domain (vdom) the configuration belongs to\n attribute :vdom\n\n # @return [String] The FortiManager's Address.\n attribute :host\n validates :host, presence: true, type: String\n\n # @return [String] The username to log into the FortiManager\n attribute :username\n validates :username, presence: true, type: String\n\n # @return [String, nil] The password associated with the username account.\n attribute :password\n validates :password, type: String\n\n # @return [:present, :execute, :delete, nil] The desired state of the specified object.,present - will create a script.,execute - execute the scipt.,delete - delete the script.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :execute, :delete], :message=>\"%{value} needs to be :present, :execute, :delete\"}, allow_nil: true\n\n # @return [String] The name of the script.\n attribute :script_name\n validates :script_name, presence: true, type: String\n\n # @return [String, nil] The type of script (CLI or TCL).\n attribute :script_type\n validates :script_type, type: String\n\n # @return [String, nil] The target of the script to be run.\n attribute :script_target\n validates :script_target, type: String\n\n # @return [String, nil] The description of the script.\n attribute :script_description\n validates :script_description, type: String\n\n # @return [String, nil] The script content that will be executed.\n attribute :script_content\n validates :script_content, type: String\n\n # @return [Array<String>, String, nil] (datasource) The devices that the script will run on, can have both device member and device group member.\n attribute :script_scope\n validates :script_scope, type: TypeGeneric.new(String)\n\n # @return [Object, nil] (datasource) Policy package object to run the script against\n attribute :script_package\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6846889853477478, "alphanum_fraction": 0.6846889853477478, "avg_line_length": 45.44444274902344, "blob_id": "5139f40b209fc6486f8e413077ae34cafa227205", "content_id": "5917861a4229f3f9c22a1161e64cb75bd81a8ffb", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2090, "license_type": "permissive", "max_line_length": 147, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/netapp_e_amg_role.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Update a storage array to become the primary or secondary instance in an asynchronous mirror group\n class Netapp_e_amg_role < Base\n # @return [String] The username to authenticate with the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_username\n validates :api_username, presence: true, type: String\n\n # @return [String] The password to authenticate with the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_password\n validates :api_password, presence: true, type: String\n\n # @return [String] The url to the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_url\n validates :api_url, presence: true, type: String\n\n # @return [Boolean, nil] Should https certificates be validated?\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String] The ID of the primary storage array for the async mirror action\n attribute :ssid\n validates :ssid, presence: true, type: String\n\n # @return [:primary, :secondary] Whether the array should be the primary or secondary array for the AMG\n attribute :role\n validates :role, presence: true, expression_inclusion: {:in=>[:primary, :secondary], :message=>\"%{value} needs to be :primary, :secondary\"}\n\n # @return [Symbol, nil] Whether to avoid synchronization prior to role reversal\n attribute :noSync\n validates :noSync, type: Symbol\n\n # @return [Boolean, nil] Whether to force the role reversal regardless of the online-state of the primary\n attribute :force\n validates :force, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6482861638069153, "alphanum_fraction": 0.6497764587402344, "avg_line_length": 36.27777862548828, "blob_id": "0e5afed302971daa23438a53d1d844a1fdc2e13f", "content_id": "d60c9bd256e9e33af11e04ceb096633335390063", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1342, "license_type": "permissive", "max_line_length": 143, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/cloud/packet/packet_sshkey.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create/delete an SSH key in Packet host.\n # API is documented at U(https://www.packet.net/help/api/#page:ssh-keys,header:ssh-keys-ssh-keys-post).\n class Packet_sshkey < Base\n # @return [:present, :absent, nil] Indicate desired state of the target.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Packet api token. You can also supply it in env var C(PACKET_API_TOKEN).\n attribute :auth_token\n\n # @return [Object, nil] Label for the key. If you keep it empty, it will be read from key string.\n attribute :label\n\n # @return [Object, nil] UUID of the key which you want to remove.\n attribute :id\n\n # @return [Object, nil] Fingerprint of the key which you want to remove.\n attribute :fingerprint\n\n # @return [Object, nil] Public Key string ({type} {base64 encoded key} {description}).\n attribute :key\n\n # @return [Object, nil] File with the public key.\n attribute :key_file\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6578947305679321, "alphanum_fraction": 0.6589267253875732, "avg_line_length": 43.04545593261719, "blob_id": "ea45b8388d9269309b7111d8d55cd4e55d6affa7", "content_id": "2bc8f3345ccf4dc0a1cf6e753ae4a22494b69cca", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1938, "license_type": "permissive", "max_line_length": 146, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_snapshot_copy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Copies an EC2 Snapshot from a source region to a destination region.\n class Ec2_snapshot_copy < Base\n # @return [String] The source region the Snapshot should be copied from.\n attribute :source_region\n validates :source_region, presence: true, type: String\n\n # @return [String] The ID of the Snapshot in source region that should be copied.\n attribute :source_snapshot_id\n validates :source_snapshot_id, presence: true, type: String\n\n # @return [Object, nil] An optional human-readable string describing purpose of the new Snapshot.\n attribute :description\n\n # @return [:yes, :no, nil] Whether or not the destination Snapshot should be encrypted.\n attribute :encrypted\n validates :encrypted, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] KMS key id used to encrypt snapshot. If not specified, defaults to EBS Customer Master Key (CMK) for that account.\n attribute :kms_key_id\n validates :kms_key_id, type: String\n\n # @return [:yes, :no, nil] Wait for the copied Snapshot to be in 'Available' state before returning.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] How long before wait gives up, in seconds.\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [Hash, nil] A hash/dictionary of tags to add to the new Snapshot; '{\"key\":\"value\"}' and '{\"key\":\"value\",\"key\":\"value\"}'\n attribute :tags\n validates :tags, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7086011171340942, "alphanum_fraction": 0.7098369002342224, "avg_line_length": 58.5, "blob_id": "60a4b4f66802eb880cd05f1fe21c323152a92bce", "content_id": "732c756abbd06d88de7e273bb0125dc207bb32c3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4046, "license_type": "permissive", "max_line_length": 470, "num_lines": 68, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_applicationpersistenceprofile.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure ApplicationPersistenceProfile object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_applicationpersistenceprofile < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the application cookie persistence profile parameters.\n attribute :app_cookie_persistence_profile\n\n # @return [Object, nil] User defined description for the object.\n attribute :description\n\n # @return [Object, nil] Specifies the custom http header persistence profile parameters.\n attribute :hdr_persistence_profile\n\n # @return [Hash, nil] Specifies the http cookie persistence profile parameters.\n attribute :http_cookie_persistence_profile\n validates :http_cookie_persistence_profile, type: Hash\n\n # @return [Object, nil] Specifies the client ip persistence profile parameters.\n attribute :ip_persistence_profile\n\n # @return [Symbol, nil] This field describes the object's replication scope.,If the field is set to false, then the object is visible within the controller-cluster and its associated service-engines.,If the field is set to true, then the object is replicated across the federation.,Field introduced in 17.1.3.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :is_federated\n validates :is_federated, type: Symbol\n\n # @return [String] A user-friendly name for the persistence profile.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] Method used to persist clients to the same server for a duration of time or a session.,Enum options - PERSISTENCE_TYPE_CLIENT_IP_ADDRESS, PERSISTENCE_TYPE_HTTP_COOKIE, PERSISTENCE_TYPE_TLS, PERSISTENCE_TYPE_CLIENT_IPV6_ADDRESS,,PERSISTENCE_TYPE_CUSTOM_HTTP_HEADER, PERSISTENCE_TYPE_APP_COOKIE, PERSISTENCE_TYPE_GSLB_SITE.,Default value when not specified in API or module is interpreted by Avi Controller as PERSISTENCE_TYPE_CLIENT_IP_ADDRESS.\n attribute :persistence_type\n validates :persistence_type, presence: true, type: String\n\n # @return [String, nil] Specifies behavior when a persistent server has been marked down by a health monitor.,Enum options - HM_DOWN_PICK_NEW_SERVER, HM_DOWN_ABORT_CONNECTION, HM_DOWN_CONTINUE_PERSISTENT_SERVER.,Default value when not specified in API or module is interpreted by Avi Controller as HM_DOWN_PICK_NEW_SERVER.\n attribute :server_hm_down_recovery\n validates :server_hm_down_recovery, type: String\n\n # @return [String, nil] It is a reference to an object of type tenant.\n attribute :tenant_ref\n validates :tenant_ref, type: String\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Uuid of the persistence profile.\n attribute :uuid\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5784695148468018, "alphanum_fraction": 0.5784695148468018, "avg_line_length": 24.700000762939453, "blob_id": "ba2fd6838072903ba93658510c0c4365517aa5a6", "content_id": "9f39ccda713bb81f237bb213cd994806cc618d84", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 771, "license_type": "permissive", "max_line_length": 73, "num_lines": 30, "path": "/lib/ansible/ruby/models/inclusion.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# see LICENSE.txt in project root\nmodule Ansible\n module Ruby\n module Models\n class Inclusion < Base\n attribute :file\n validates :file, presence: true, type: String\n attribute :static\n validates :static, type: MultipleTypes.new(TrueClass, FalseClass)\n attribute :variables\n validates :variables, type: Hash\n\n def to_h\n initial = super\n # gets rendered as include\n result = {\n include: initial[:file]\n }\n # a more intuitive name\n vars = initial[:variables]\n result[:vars] = vars if vars\n result[:static] = static unless static.is_a?(NilClass)\n result\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.684297502040863, "alphanum_fraction": 0.684297502040863, "avg_line_length": 42.21428680419922, "blob_id": "52e5fc6a6b7ab259d226a0b098fa884edcd40366", "content_id": "159b5b90cbbc064ac7bbf513eb9d043ede9db313", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1210, "license_type": "permissive", "max_line_length": 202, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_users.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Module to manage users in oVirt/RHV.\n class Ovirt_user < Base\n # @return [String] Name of the user to manage. In most LDAPs it's I(uid) of the user, but in Active Directory you must specify I(UPN) of the user.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, nil] Should the user be present/absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] Authorization provider of the user. In previous versions of oVirt/RHV known as domain.\n attribute :authz_name\n validates :authz_name, presence: true, type: String\n\n # @return [Object, nil] Namespace where the user resides. When using the authorization provider that stores users in the LDAP server, this attribute equals the naming context of the LDAP server.\n attribute :namespace\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7193460464477539, "alphanum_fraction": 0.7465940117835999, "avg_line_length": 19.38888931274414, "blob_id": "5527033d88e006e0b72db3c5e0c472533330ba18", "content_id": "2ce26bca4fb34eac558548366e6a29b5bb16d7c4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 367, "license_type": "permissive", "max_line_length": 66, "num_lines": 18, "path": "/lib/ansible/ruby/modules/custom/cloud/core/amazon/iam_policy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# VALIDATED_CHECKSUM: 0q0k3jl40Ssgb5i3snikBFDpfpg3pXSW1AykDzt4qZk=\n\n# See LICENSE.txt for license\n\nrequire 'ansible/ruby/modules/generated/cloud/amazon/iam_policy'\nrequire 'ansible/ruby/modules/helpers/aws'\n\nmodule Ansible\n module Ruby\n module Modules\n class Iam_policy\n include Helpers::Aws\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6792452931404114, "alphanum_fraction": 0.6792452931404114, "avg_line_length": 29.91666603088379, "blob_id": "3574aa10ef4777a3f20be751aff5a20da266c57c", "content_id": "8a3ebd26c4eff707f11fbd4a7184924c4784b222", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 742, "license_type": "permissive", "max_line_length": 93, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_availabilityset_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Get facts for a specific availability set or all availability sets.\n class Azure_rm_availabilityset_facts < Base\n # @return [String, nil] Limit results to a specific availability set\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] The resource group to search for the desired availability set\n attribute :resource_group\n validates :resource_group, type: String\n\n # @return [Object, nil] List of tags to be matched\n attribute :tags\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6921672224998474, "alphanum_fraction": 0.7075892686843872, "avg_line_length": 62.17948532104492, "blob_id": "10b9ff8e3f104f7bb70e7b83ad2b524f519dfce4", "content_id": "ac9ad4a117c9a347643bc3620d29b85facb87a7d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4928, "license_type": "permissive", "max_line_length": 414, "num_lines": 78, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_igmp_interface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages IGMP interface configuration settings.\n class Nxos_igmp_interface < Base\n # @return [String] The full interface name for IGMP configuration. e.g. I(Ethernet1/2).\n attribute :interface\n validates :interface, presence: true, type: String\n\n # @return [2, 3, :default, nil] IGMP version. It can be 2 or 3 or keyword 'default'.\n attribute :version\n validates :version, expression_inclusion: {:in=>[2, 3, :default], :message=>\"%{value} needs to be 2, 3, :default\"}, allow_nil: true\n\n # @return [Integer, nil] Query interval used when the IGMP process starts up. The range is from 1 to 18000 or keyword 'default'. The default is 31.\n attribute :startup_query_interval\n validates :startup_query_interval, type: Integer\n\n # @return [Object, nil] Query count used when the IGMP process starts up. The range is from 1 to 10 or keyword 'default'. The default is 2.\n attribute :startup_query_count\n\n # @return [Object, nil] Sets the robustness variable. Values can range from 1 to 7 or keyword 'default'. The default is 2.\n attribute :robustness\n\n # @return [Object, nil] Sets the querier timeout that the software uses when deciding to take over as the querier. Values can range from 1 to 65535 seconds or keyword 'default'. The default is 255 seconds.\n attribute :querier_timeout\n\n # @return [Object, nil] Sets the response time advertised in IGMP queries. Values can range from 1 to 25 seconds or keyword 'default'. The default is 10 seconds.\n attribute :query_mrt\n\n # @return [Object, nil] Sets the frequency at which the software sends IGMP host query messages. Values can range from 1 to 18000 seconds or keyword 'default'. The default is 125 seconds.\n attribute :query_interval\n\n # @return [Object, nil] Sets the query interval waited after sending membership reports before the software deletes the group state. Values can range from 1 to 25 seconds or keyword 'default'. The default is 1 second.\n attribute :last_member_qrt\n\n # @return [Object, nil] Sets the number of times that the software sends an IGMP query in response to a host leave message. Values can range from 1 to 5 or keyword 'default'. The default is 2.\n attribute :last_member_query_count\n\n # @return [Object, nil] Sets the group membership timeout for IGMPv2. Values can range from 3 to 65,535 seconds or keyword 'default'. The default is 260 seconds.\n attribute :group_timeout\n\n # @return [Symbol, nil] Configures report-link-local-groups. Enables sending reports for groups in 224.0.0.0/24. Reports are always sent for nonlink local groups. By default, reports are not sent for link local groups.\n attribute :report_llg\n validates :report_llg, type: Symbol\n\n # @return [Symbol, nil] Enables the device to remove the group entry from the multicast routing table immediately upon receiving a leave message for the group. Use this command to minimize the leave latency of IGMPv2 group memberships on a given IGMP interface because the device does not send group-specific queries. The default is disabled.\n attribute :immediate_leave\n validates :immediate_leave, type: Symbol\n\n # @return [Object, nil] Configure a routemap for static outgoing interface (OIF) or keyword 'default'.\n attribute :oif_routemap\n\n # @return [Object, nil] This argument is deprecated, please use oif_ps instead. Configure a prefix for static outgoing interface (OIF).\n attribute :oif_prefix\n\n # @return [Object, nil] This argument is deprecated, please use oif_ps instead. Configure a source for static outgoing interface (OIF).\n attribute :oif_source\n\n # @return [Array<Hash>, Hash, nil] Configure prefixes and sources for static outgoing interface (OIF). This is a list of dict where each dict has source and prefix defined or just prefix if source is not needed. The specified values will be configured on the device and if any previous prefix/sources exist, they will be removed. Keyword 'default' is also accpted which removes all existing prefix/sources.\n attribute :oif_ps\n validates :oif_ps, type: TypeGeneric.new(Hash)\n\n # @return [Symbol, nil] Restart IGMP. This is NOT idempotent as this is action only.\n attribute :restart\n validates :restart, type: Symbol\n\n # @return [:present, :absent, :default, nil] Manages desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :default], :message=>\"%{value} needs to be :present, :absent, :default\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7194066643714905, "alphanum_fraction": 0.7214668393135071, "avg_line_length": 81.27118682861328, "blob_id": "12c4b27494b9e20dda9371075cf11cb8b4473c2b", "content_id": "179376c26c56da192cc596dba8e5a7efba639985", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 9708, "license_type": "permissive", "max_line_length": 672, "num_lines": 118, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_instance.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create and manage AWS EC2 instance\n class Ec2_instance < Base\n # @return [Array<String>, String, nil] If you specify one or more instance IDs, only instances that have the specified IDs are returned.\n attribute :instance_ids\n validates :instance_ids, type: TypeGeneric.new(String)\n\n # @return [:present, :terminated, :running, :started, :stopped, :restarted, :rebooted, :absent, nil] Goal state for the instances\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :terminated, :running, :started, :stopped, :restarted, :rebooted, :absent], :message=>\"%{value} needs to be :present, :terminated, :running, :started, :stopped, :restarted, :rebooted, :absent\"}, allow_nil: true\n\n # @return [Boolean, nil] Whether or not to wait for the desired state (use wait_timeout to customize this)\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Integer, nil] How long to wait (in seconds) for the instance to finish booting/terminating\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [String, nil] Instance type to use for the instance, see U(http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) Only required when instance is not already present\n attribute :instance_type\n validates :instance_type, type: String\n\n # @return [Object, nil] Opaque blob of data which is made available to the ec2 instance\n attribute :user_data\n\n # @return [Hash, nil] Preconfigured user-data to enable an instance to perform a Tower callback (Linux only).,Mutually exclusive with I(user_data).,For Windows instances, to enable remote access via Ansible set I(tower_callback.windows) to true, and optionally set an admin password.,If using 'windows' and 'set_password', callback to Tower will not be performed but the instance will be ready to receive winrm connections from Ansible.\n attribute :tower_callback\n validates :tower_callback, type: Hash\n\n # @return [Hash, nil] A hash/dictionary of tags to add to the new instance or to add/remove from an existing one.\n attribute :tags\n validates :tags, type: Hash\n\n # @return [Boolean, nil] Delete any tags not specified in the task that are on the instance. This means you have to specify all the desired tags on each task affecting an instance.\n attribute :purge_tags\n validates :purge_tags, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] An image to use for the instance. The ec2_ami_facts module may be used to retrieve images. One of I(image) or I(image_id) are required when instance is not already present.,Complex object containing I(image.id), I(image.ramdisk), and I(image.kernel).,I(image.id) is the AMI ID.,I(image.ramdisk) overrides the AMI's default ramdisk ID.,I(image.kernel) is a string AKI to override the AMI kernel.\n attribute :image\n\n # @return [String, nil] I(ami) ID to use for the instance. One of I(image) or I(image_id) are required when instance is not already present.,This is an alias for I(image.id).\n attribute :image_id\n validates :image_id, type: String\n\n # @return [Object, nil] A list of security group IDs or names (strings). Mutually exclusive with I(security_group).\n attribute :security_groups\n\n # @return [String, nil] A security group ID or name. Mutually exclusive with I(security_groups).\n attribute :security_group\n validates :security_group, type: String\n\n # @return [String, nil] The Name tag for the instance.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] The subnet ID in which to launch the instance (VPC) If none is provided, ec2_instance will chose the default zone of the default VPC\n attribute :vpc_subnet_id\n validates :vpc_subnet_id, type: String\n\n # @return [Hash, nil] Either a dictionary containing the key 'interfaces' corresponding to a list of network interface IDs or containing specifications for a single network interface.,If specifications for a single network are given, accepted keys are assign_public_ip (bool), private_ip_address (str), ipv6_addresses (list), source_dest_check (bool), description (str), delete_on_termination (bool), device_index (int), groups (list of security group IDs), private_ip_addresses (list), subnet_id (str).,I(network.interfaces) should be a list of ENI IDs (strings) or a list of objects containing the key I(id).,Use the ec2_eni to create ENIs with special settings.\n attribute :network\n validates :network, type: Hash\n\n # @return [Object, nil] A list of block device mappings, by default this will always use the AMI root device so the volumes option is primarily for adding more storage.,A mapping contains the (optional) keys device_name, virtual_name, ebs.volume_type, ebs.volume_size, ebs.kms_key_id, ebs.iops, and ebs.delete_on_termination.,For more information about each parameter, see U(https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_BlockDeviceMapping.html)\n attribute :volumes\n\n # @return [Object, nil] The EC2 launch template to base instance configuration on.,I(launch_template.id) the ID or the launch template (optional if name is specified),I(launch_template.name) the pretty name of the launch template (optional if id is specified),I(launch_template.version) the specific version of the launch template to use. If unspecified, the template default is chosen.\n attribute :launch_template\n\n # @return [String, nil] Name of the SSH access key to assign to the instance - must exist in the region the instance is created.\n attribute :key_name\n validates :key_name, type: String\n\n # @return [Object, nil] Specify an availability zone to use the default subnet it. Useful if not specifying the I(vpc_subnet_id) parameter.,If no subnet, ENI, or availability zone is provided, the default subnet in the default VPC will be used in the first AZ (alphabetically sorted).\n attribute :availability_zone\n\n # @return [:stop, :terminate, nil] Whether to stop or terminate an instance upon shutdown.\n attribute :instance_initiated_shutdown_behavior\n validates :instance_initiated_shutdown_behavior, expression_inclusion: {:in=>[:stop, :terminate], :message=>\"%{value} needs to be :stop, :terminate\"}, allow_nil: true\n\n # @return [:dedicated, :default, nil] What type of tenancy to allow an instance to use. Default is shared tenancy. Dedicated tenancy will incur additional charges.\n attribute :tenancy\n validates :tenancy, expression_inclusion: {:in=>[:dedicated, :default], :message=>\"%{value} needs to be :dedicated, :default\"}, allow_nil: true\n\n # @return [Object, nil] Whether to enable termination protection. This module will not terminate an instance with termination protection active, it must be turned off first.\n attribute :termination_protection\n\n # @return [:unlimited, :standard, nil] For T2 series instances, choose whether to allow increased charges to buy CPU credits if the default pool is depleted.,Choose I(unlimited) to enable buying additional CPU credits.\n attribute :cpu_credit_specification\n validates :cpu_credit_specification, expression_inclusion: {:in=>[:unlimited, :standard], :message=>\"%{value} needs to be :unlimited, :standard\"}, allow_nil: true\n\n # @return [Object, nil] Reduce the number of vCPU exposed to the instance.,Those parameters can only be set at instance launch. The two suboptions threads_per_core and core_count are mandatory.,See U(https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-optimize-cpu.html) for combinations available.,Requires botocore >= 1.10.16\n attribute :cpu_options\n\n # @return [Object, nil] Whether to allow detailed cloudwatch metrics to be collected, enabling more detailed alerting.\n attribute :detailed_monitoring\n\n # @return [Object, nil] Whether instance is should use optimized EBS volumes, see U(http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSOptimized.html)\n attribute :ebs_optimized\n\n # @return [Array<String>, String, nil] A dict of filters to apply when deciding whether existing instances match and should be altered. Each dict item consists of a filter key and a filter value. See U(http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances.html) for possible filters. Filter names and values are case sensitive. By default, instances are filtered for counting by their \"Name\" tag, base AMI, state (running, by default), and subnet ID. Any queryable filter can be used. Good candidates are specific tags, SSH keys, or security groups.\n attribute :filters\n validates :filters, type: TypeGeneric.new(String)\n\n # @return [Object, nil] The ARN or name of an EC2-enabled instance role to be used. If a name is not provided in arn format then the ListInstanceProfiles permission must also be granted. U(https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListInstanceProfiles.html) If no full ARN is provided, the role with a matching name will be used from the active AWS account.\n attribute :instance_role\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6655604839324951, "alphanum_fraction": 0.6733038425445557, "avg_line_length": 53.2400016784668, "blob_id": "c4d1b63142eca8456bb2b73489d13d1ce58d4b47", "content_id": "1db276a11e0d6d413037f4cf9b51b1694928a05e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2712, "license_type": "permissive", "max_line_length": 233, "num_lines": 50, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_aaa_server.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages AAA server global configuration on HUAWEI CloudEngine switches.\n class Ce_aaa_server < Base\n # @return [:present, :absent, nil] Specify desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Name of an authentication scheme. The value is a string of 1 to 32 characters.\n attribute :authen_scheme_name\n\n # @return [:invalid, :local, :hwtacacs, :radius, :none, nil] Preferred authentication mode.\n attribute :first_authen_mode\n validates :first_authen_mode, expression_inclusion: {:in=>[:invalid, :local, :hwtacacs, :radius, :none], :message=>\"%{value} needs to be :invalid, :local, :hwtacacs, :radius, :none\"}, allow_nil: true\n\n # @return [Object, nil] Name of an authorization scheme. The value is a string of 1 to 32 characters.\n attribute :author_scheme_name\n\n # @return [:invalid, :local, :hwtacacs, :\"if-authenticated\", :none, nil] Preferred authorization mode.\n attribute :first_author_mode\n validates :first_author_mode, expression_inclusion: {:in=>[:invalid, :local, :hwtacacs, :\"if-authenticated\", :none], :message=>\"%{value} needs to be :invalid, :local, :hwtacacs, :\\\"if-authenticated\\\", :none\"}, allow_nil: true\n\n # @return [Object, nil] Accounting scheme name. The value is a string of 1 to 32 characters.\n attribute :acct_scheme_name\n\n # @return [:invalid, :hwtacacs, :radius, :none, nil] Accounting Mode.\n attribute :accounting_mode\n validates :accounting_mode, expression_inclusion: {:in=>[:invalid, :hwtacacs, :radius, :none], :message=>\"%{value} needs to be :invalid, :hwtacacs, :radius, :none\"}, allow_nil: true\n\n # @return [Object, nil] Name of a domain. The value is a string of 1 to 64 characters.\n attribute :domain_name\n\n # @return [Object, nil] RADIUS server group's name. The value is a string of 1 to 32 case-insensitive characters.\n attribute :radius_server_group\n\n # @return [Object, nil] Name of a HWTACACS template. The value is a string of 1 to 32 case-insensitive characters.\n attribute :hwtacas_template\n\n # @return [Object, nil] Name of the user group where the user belongs. The user inherits all the rights of the user group. The value is a string of 1 to 32 characters.\n attribute :local_user_group\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7071269750595093, "alphanum_fraction": 0.7143652439117432, "avg_line_length": 58.86666488647461, "blob_id": "d29600766eb5a22fcfa074d56e25d6502acd4fcb", "content_id": "ca5a8acaa22e7abd5efc708827f848676fe7edfa", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1796, "license_type": "permissive", "max_line_length": 363, "num_lines": 30, "path": "/lib/ansible/ruby/modules/generated/cloud/rackspace/rax_mon_entity.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or delete a Rackspace Cloud Monitoring entity, which represents a device to monitor. Entities associate checks and alarms with a target system and provide a convenient, centralized place to store IP addresses. Rackspace monitoring module flow | *rax_mon_entity* -> rax_mon_check -> rax_mon_notification -> rax_mon_notification_plan -> rax_mon_alarm\n class Rax_mon_entity < Base\n # @return [Object] Defines a name for this entity. Must be a non-empty string between 1 and 255 characters long.\n attribute :label\n validates :label, presence: true\n\n # @return [:present, :absent, nil] Ensure that an entity with this C(name) exists or does not exist.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Rackspace monitoring agent on the target device to which this entity is bound. Necessary to collect C(agent.) rax_mon_checks against this entity.\n attribute :agent_id\n\n # @return [Object, nil] Hash of IP addresses that may be referenced by name by rax_mon_checks added to this entity. Must be a dictionary of with keys that are names between 1 and 64 characters long, and values that are valid IPv4 or IPv6 addresses.\n attribute :named_ip_addresses\n\n # @return [Object, nil] Hash of arbitrary C(name), C(value) pairs that are passed to associated rax_mon_alarms. Names and values must all be between 1 and 255 characters long.\n attribute :metadata\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.4713970124721527, "alphanum_fraction": 0.4760618805885315, "avg_line_length": 25.9735107421875, "blob_id": "d8dd3f57729f94bb319a07c2963ca54081a7c9cb", "content_id": "2a6f16ded4dcb9d0fd073a291a56e2ced03b533d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4073, "license_type": "permissive", "max_line_length": 130, "num_lines": 151, "path": "/util/parser/yaml_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# See LICENSE.txt for license\nrequire 'spec_helper'\nrequire 'ansible-ruby'\nrequire_relative './yaml'\n\ndescribe Ansible::Ruby::Parser::Yaml do\n describe '::parse' do\n let(:description) { 'unit_test' }\n let(:module_name) { nil }\n\n subject { Ansible::Ruby::Parser::Yaml.parse input_yaml, description, module_name }\n\n context 'standard' do\n let(:input_yaml) do\n <<~YAML\n ---\n # Create a new database with name \"acme\"\n - postgresql_db: name=acme\n # Create a new database with name \"acme\" and specific encoding and locale\n # settings. If a template different from \"template0\" is specified, encoding\n # and locale settings must match those of the template.\n - postgresql_db: name=acme\n encoding='UTF-8'\n lc_collate='de_DE.UTF-8'\n lc_ctype='de_DE.UTF-8'\n template='template0'\n YAML\n end\n\n it do\n is_expected.to eq [\n { 'postgresql_db' => 'name=acme' },\n { 'postgresql_db' => \"name=acme encoding='UTF-8' lc_collate='de_DE.UTF-8' lc_ctype='de_DE.UTF-8' template='template0'\" }\n ]\n end\n end\n\n context 'array item colon issues' do\n context 'missing' do\n let(:module_name) { 'postgresql_db' }\n\n let(:input_yaml) do\n <<~YAML\n ---\n - postgresql_db\n aws_access_key: xxxxxxxxxxxxxxxxxxxxxxx\n register: instance\n YAML\n end\n\n it do\n is_expected.to eq [\n {\n 'postgresql_db' => {\n 'aws_access_key' => 'xxxxxxxxxxxxxxxxxxxxxxx'\n },\n 'register' => 'instance'\n }\n ]\n end\n end\n\n context 'extra space' do\n let(:module_name) { 'svc' }\n\n let(:input_yaml) do\n <<~YAML\n\n # Example action to stop svc dnscache, if running\n - svc: name=dnscache state=stopped\n\n # Example action to kill svc dnscache, in all cases\n - svc : name=dnscache state=killed\n # Example action to kill svc dnscache, in all cases\n - svc : name=dnscache state=restarted\n YAML\n end\n\n it do\n is_expected.to eq [\n { 'svc' => 'name=dnscache state=stopped' },\n { 'svc' => 'name=dnscache state=killed' },\n { 'svc' => 'name=dnscache state=restarted' }\n ]\n end\n end\n end\n\n context 'inline keys' do\n let(:input_yaml) do\n <<~YAML\n # Example action to start svc dnscache, if not running\n - svc: name=dnscache state=started\n\n # Example action to stop svc dnscache, if running\n - svc: name=dnscache state=stopped\n YAML\n end\n\n it do\n is_expected.to eq [\n { 'svc' => 'name=dnscache state=started' },\n { 'svc' => 'name=dnscache state=stopped' }\n ]\n end\n end\n\n context 'hash containing array' do\n let(:input_yaml) do\n <<~YAML\n ---\n module: datadog_monitor\n description:\n - \"Manages monitors within Datadog\"\n version_added: \"2.0\"\n YAML\n end\n\n it do\n is_expected.to eq('module' => 'datadog_monitor',\n 'description' => [\n 'Manages monitors within Datadog'\n ],\n 'version_added' => '2.0')\n end\n end\n\n context 'line continuation' do\n let(:input_yaml) do\n <<~YAML\n ---\n hash:\n - value 1\n - value 2 \\\\\n goes on to next line\n - value 3\n YAML\n end\n\n it do\n is_expected.to eq('hash' => [\n 'value 1',\n 'value 2goes on to next line',\n 'value 3'\n ])\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7059321999549866, "alphanum_fraction": 0.7084745764732361, "avg_line_length": 46.20000076293945, "blob_id": "b335b246906fe96bf465bbe72eb2cc2e83a6facc", "content_id": "57f9d56a321281701423c85a54bcfdcd62f3ca3f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1180, "license_type": "permissive", "max_line_length": 283, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_snapshot_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gather facts about ec2 volume snapshots in AWS\n class Ec2_snapshot_facts < Base\n # @return [Object, nil] If you specify one or more snapshot IDs, only snapshots that have the specified IDs are returned.\n attribute :snapshot_ids\n\n # @return [Object, nil] If you specify one or more snapshot owners, only snapshots from the specified owners and for which you have access are returned.\n attribute :owner_ids\n\n # @return [Object, nil] If you specify a list of restorable users, only snapshots with create snapshot permissions for those users are returned.\n attribute :restorable_by_user_ids\n\n # @return [Object, nil] A dict of filters to apply. Each dict item consists of a filter key and a filter value. See U(http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeSnapshots.html) for possible filters. Filter names and values are case sensitive.\n attribute :filters\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6748299598693848, "alphanum_fraction": 0.6748299598693848, "avg_line_length": 34, "blob_id": "36ebb1e6ef9982118fab62664718968b8f7d665a", "content_id": "094098fd28e5399e27ae09eac9fb1dfe48fc60d4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 735, "license_type": "permissive", "max_line_length": 147, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/windows/win_firewall.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Enable or Disable Windows Firewall profiles.\n class Win_firewall < Base\n # @return [Array<String>, String, nil] Specify one or more profiles to change.\n attribute :profiles\n validates :profiles, type: TypeGeneric.new(String)\n\n # @return [:enabled, :disabled, nil] Set state of firewall for given profile.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6653929948806763, "alphanum_fraction": 0.6681222915649414, "avg_line_length": 43.682926177978516, "blob_id": "df86ff4855af0246afaf45fdacd15c9f8948a6ac", "content_id": "081736c9cb6ebffef75d53824c84a13919d2c42a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1832, "license_type": "permissive", "max_line_length": 152, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/network/eos/eos_linkagg.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of link aggregation groups on Arista EOS network devices.\n class Eos_linkagg < Base\n # @return [Integer, nil] Channel-group number for the port-channel Link aggregation group. Range 1-2000.\n attribute :group\n validates :group, type: Integer\n\n # @return [:active, :on, :passive, nil] Mode of the link aggregation group.\n attribute :mode\n validates :mode, expression_inclusion: {:in=>[:active, :on, :passive], :message=>\"%{value} needs to be :active, :on, :passive\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] List of members of the link aggregation group.\n attribute :members\n validates :members, type: TypeGeneric.new(String)\n\n # @return [Integer, nil] Minimum number of ports required up before bringing up the link aggregation group.\n attribute :min_links\n validates :min_links, type: Integer\n\n # @return [Array<Hash>, Hash, nil] List of link aggregation definitions.\n attribute :aggregate\n validates :aggregate, type: TypeGeneric.new(Hash)\n\n # @return [:present, :absent, nil] State of the link aggregation group.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Boolean, nil] Purge links not defined in the I(aggregate) parameter.\n attribute :purge\n validates :purge, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6798493266105652, "alphanum_fraction": 0.6804770827293396, "avg_line_length": 62.720001220703125, "blob_id": "5f613b9dfad5a318004264dd0d97ec2514c3cbaf", "content_id": "bf9b000099841ebe0e9a1583bc5979fcc8199b4e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3186, "license_type": "permissive", "max_line_length": 667, "num_lines": 50, "path": "/lib/ansible/ruby/modules/generated/windows/win_template.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Templates are processed by the Jinja2 templating language (U(http://jinja.pocoo.org/docs/)) - documentation on the template formatting can be found in the Template Designer Documentation (U(http://jinja.pocoo.org/docs/templates/)).\n # Six additional variables can be used in templates: C(ansible_managed) (configurable via the C(defaults) section of C(ansible.cfg)) contains a string which can be used to describe the template name, host, modification time of the template file and the owner uid, C(template_host) contains the node name of the template's machine, C(template_uid) the owner, C(template_path) the absolute path of the template, C(template_fullpath) is the absolute path of the template, and C(template_run_date) is the date that the template was rendered. Note that including a string that uses a date in the template will result in the template being marked 'changed' each time.\n class Win_template < Base\n # @return [String] Path of a Jinja2 formatted template on the local server. This can be a relative or absolute path.\n attribute :src\n validates :src, presence: true, type: String\n\n # @return [String] Location to render the template to on the remote machine.\n attribute :dest\n validates :dest, presence: true, type: String\n\n # @return [:\"\\\\n\", :\"\\\\r\", :\"\\\\r\\\\n\", nil] Specify the newline sequence to use for templating files.\n attribute :newline_sequence\n validates :newline_sequence, expression_inclusion: {:in=>[:\"\\\\n\", :\"\\\\r\", :\"\\\\r\\\\n\"], :message=>\"%{value} needs to be :\\\"\\\\\\\\n\\\", :\\\"\\\\\\\\r\\\", :\\\"\\\\\\\\r\\\\\\\\n\\\"\"}, allow_nil: true\n\n # @return [String, nil] The string marking the beginning of a block.\n attribute :block_start_string\n validates :block_start_string, type: String\n\n # @return [String, nil] The string marking the end of a block.\n attribute :block_end_string\n validates :block_end_string, type: String\n\n # @return [String, nil] The string marking the beginning of a print statement.\n attribute :variable_start_string\n validates :variable_start_string, type: String\n\n # @return [String, nil] The string marking the end of a print statement.\n attribute :variable_end_string\n validates :variable_end_string, type: String\n\n # @return [:yes, :no, nil] If this is set to C(yes) the first newline after a block is removed (block, not variable tag!).\n attribute :trim_blocks\n validates :trim_blocks, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(yes), will replace the remote file when contents are different from the source.,If C(no), the file will only be transferred if the destination does not exist.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6590163707733154, "alphanum_fraction": 0.6627634763717651, "avg_line_length": 49.83333206176758, "blob_id": "53807c98a917da1a3aac63e9d0dd9a2940f8197a", "content_id": "79331a927021e863513aefd177a1a96bb0307860", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2135, "license_type": "permissive", "max_line_length": 233, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/database/mysql/mysql_db.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove MySQL databases from a remote host.\n class Mysql_db < Base\n # @return [String] name of the database to add or remove,name=all May only be provided if I(state) is C(dump) or C(import).,if name=all Works like --all-databases option for mysqldump (Added in 2.0)\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:present, :absent, :dump, :import, nil] The database state\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :dump, :import], :message=>\"%{value} needs to be :present, :absent, :dump, :import\"}, allow_nil: true\n\n # @return [Object, nil] Collation mode (sorting). This only applies to new table/databases and does not update existing ones, this is a limitation of MySQL.\n attribute :collation\n\n # @return [Object, nil] Encoding mode to use, examples include C(utf8) or C(latin1_swedish_ci)\n attribute :encoding\n\n # @return [String, nil] Location, on the remote host, of the dump file to read from or write to. Uncompressed SQL files (C(.sql)) as well as bzip2 (C(.bz2)), gzip (C(.gz)) and xz (Added in 2.0) compressed files are supported.\n attribute :target\n validates :target, type: String\n\n # @return [:yes, :no, nil] Execute the dump in a single transaction\n attribute :single_transaction\n validates :single_transaction, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Option used for dumping large tables\n attribute :quick\n validates :quick, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] A list of table names that will be ignored in the dump of the form database_name.table_name\n attribute :ignore_tables\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6807979941368103, "alphanum_fraction": 0.6807979941368103, "avg_line_length": 40.482757568359375, "blob_id": "7611d71a407794d8940eb71275b660db18ddb0e6", "content_id": "44df0ba392025a47b16fd5b096614a47cb939bc5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1203, "license_type": "permissive", "max_line_length": 143, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_gslbservice_patch_member.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used for calling any resources defined in Avi REST API. U(https://avinetworks.com/)\n # This module is useful for invoking HTTP Patch methods and accessing resources that do not have an REST object associated with them.\n class Avi_gslbservice_patch_member < Base\n # @return [Hash, nil] HTTP body of GSLB Service Member in YAML or JSON format.\n attribute :data\n validates :data, type: Hash\n\n # @return [Object, nil] Query parameters passed to the HTTP API.\n attribute :params\n\n # @return [String] Name of the GSLB Service\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, nil] The state that should be applied to the member. Member is,identified using field member.ip.addr.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6557279229164124, "alphanum_fraction": 0.6736276745796204, "avg_line_length": 51.375, "blob_id": "8d426587a287861d3c3eb210a126fbbc43e820c2", "content_id": "2d5da4fd1421d8bc8b690a52e5d9fb3c7dde54b6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1676, "license_type": "permissive", "max_line_length": 260, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/elasticache_parameter_group.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage cache security groups in Amazon Elasticache.\n # Returns information about the specified cache cluster.\n class Elasticache_parameter_group < Base\n # @return [:\"memcached1.4\", :\"redis2.6\", :\"redis2.8\", :\"redis3.2\", :\"redis4.0\", nil] The name of the cache parameter group family that the cache parameter group can be used with. Required when creating a cache parameter group.\n attribute :group_family\n validates :group_family, expression_inclusion: {:in=>[:\"memcached1.4\", :\"redis2.6\", :\"redis2.8\", :\"redis3.2\", :\"redis4.0\"], :message=>\"%{value} needs to be :\\\"memcached1.4\\\", :\\\"redis2.6\\\", :\\\"redis2.8\\\", :\\\"redis3.2\\\", :\\\"redis4.0\\\"\"}, allow_nil: true\n\n # @return [String] A user-specified name for the cache parameter group.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] A user-specified description for the cache parameter group.\n attribute :description\n\n # @return [:present, :absent, :reset] Idempotent actions that will create/modify, destroy, or reset a cache parameter group as needed.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent, :reset], :message=>\"%{value} needs to be :present, :absent, :reset\"}\n\n # @return [Object, nil] A user-specified dictionary of parameters to reset or modify for the cache parameter group.\n attribute :values\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6796537041664124, "alphanum_fraction": 0.6839826703071594, "avg_line_length": 27.875, "blob_id": "3523d503868ce0c6e6856d5ad8cd5544aa6e3340", "content_id": "089fbc805895944d492126b2f09d4641544149a7", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 462, "license_type": "permissive", "max_line_length": 135, "num_lines": 16, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_eip_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # List details of EC2 Elastic IP addresses.\n class Ec2_eip_facts < Base\n # @return [Object, nil] A set of filters to use. Each filter is a name:value pair. The value may be a list or a single element.\n attribute :filters\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6455696225166321, "alphanum_fraction": 0.6470588445663452, "avg_line_length": 39.69696807861328, "blob_id": "5f1ca2afb7b00f0bfe013467cabde09bc57dbd4c", "content_id": "9463a6d529ae1dff54a2b1fa28e10afafc29a1ab", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1343, "license_type": "permissive", "max_line_length": 142, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/system/seport.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages SELinux network port type definitions.\n class Seport < Base\n # @return [Integer, Array<String>, String] Ports or port ranges. Can be a list (since 2.6) or comma separated string.\n attribute :ports\n validates :ports, presence: true, type: TypeGeneric.new(String)\n\n # @return [:tcp, :udp] Protocol for the specified port.\n attribute :proto\n validates :proto, presence: true, expression_inclusion: {:in=>[:tcp, :udp], :message=>\"%{value} needs to be :tcp, :udp\"}\n\n # @return [String] SELinux type for the specified port.\n attribute :setype\n validates :setype, presence: true, type: String\n\n # @return [:absent, :present] Desired boolean value.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}\n\n # @return [:yes, :no, nil] Reload SELinux policy after commit.\n attribute :reload\n validates :reload, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6628216505050659, "alphanum_fraction": 0.6628216505050659, "avg_line_length": 45.95833206176758, "blob_id": "9c999b1c200d56a2acfeb071b5c201e437b3bbb7", "content_id": "33a60c9590f79c1ef5b348587962f12aea0d9c27", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2254, "license_type": "permissive", "max_line_length": 278, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_network.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove network from OpenStack.\n class Os_network < Base\n # @return [String] Name to be assigned to the network.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:yes, :no, nil] Whether this network is shared or not.\n attribute :shared\n validates :shared, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Whether the state should be marked as up or down.\n attribute :admin_state_up\n validates :admin_state_up, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Whether this network is externally accessible.\n attribute :external\n validates :external, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Indicate desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] The physical network where this network object is implemented.\n attribute :provider_physical_network\n\n # @return [Object, nil] The type of physical network that maps to this network resource.\n attribute :provider_network_type\n\n # @return [Object, nil] An isolated segment on the physical network. The I(network_type) attribute defines the segmentation model. For example, if the I(network_type) value is vlan, this ID is a vlan identifier. If the I(network_type) value is gre, this ID is a gre key.\n attribute :provider_segmentation_id\n\n # @return [Object, nil] Project name or ID containing the network (name admin-only)\n attribute :project\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6641104221343994, "alphanum_fraction": 0.6641104221343994, "avg_line_length": 27.34782600402832, "blob_id": "6f7daee05c6651741bc9612b0a56a73bba4ce44a", "content_id": "45311ce43ac45ef26001471a81da7fe4afcc540b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 652, "license_type": "permissive", "max_line_length": 113, "num_lines": 23, "path": "/lib/ansible/ruby/modules/generated/cloud/rackspace/rax_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gather facts for Rackspace Cloud Servers.\n class Rax_facts < Base\n # @return [Object, nil] Server IP address to retrieve facts for, will match any IP assigned to the server\n attribute :address\n\n # @return [Object, nil] Server ID to retrieve facts for\n attribute :id\n\n # @return [String, nil] Server name to retrieve facts for\n attribute :name\n validates :name, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6672199368476868, "alphanum_fraction": 0.6672199368476868, "avg_line_length": 36.65625, "blob_id": "c371ed619eba448ec49cf0236300cadad72f7f9e", "content_id": "f21e4f8af2764642a79fd926cdebed8d36c779e4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1205, "license_type": "permissive", "max_line_length": 143, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_sql_database.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Represents a SQL database inside the Cloud SQL instance, hosted in Google's cloud.\n class Gcp_sql_database < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] The MySQL charset value.\n attribute :charset\n validates :charset, type: String\n\n # @return [Object, nil] The MySQL collation value.\n attribute :collation\n\n # @return [String, nil] The name of the database in the Cloud SQL instance.,This does not include the project ID or instance name.\n attribute :name\n validates :name, type: String\n\n # @return [String] The name of the Cloud SQL instance. This does not include the project ID.\n attribute :instance\n validates :instance, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6139088869094849, "alphanum_fraction": 0.6139088869094849, "avg_line_length": 22.16666603088379, "blob_id": "59f79664674feeae55036020822455cc6cba6307", "content_id": "ef0b440888238beea25ce6814a1a4e57bb49606a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 417, "license_type": "permissive", "max_line_length": 75, "num_lines": 18, "path": "/lib/ansible/ruby/modules/helpers/aws.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# see LICENSE.txt in project root\nmodule Ansible\n module Ruby\n module Modules\n module Helpers\n # For some of the AWS modules, we don't detect the region attribute\n module Aws\n def self.included(base)\n base.attribute :region\n base.validates :region, type: String, presence: true\n end\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7178317904472351, "alphanum_fraction": 0.7178317904472351, "avg_line_length": 58.818180084228516, "blob_id": "1480893fde48dcf457da51be58b3619c13e9f186", "content_id": "c14aaff6af29dce770fe9386fd726057eeb72d0c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1974, "license_type": "permissive", "max_line_length": 464, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/network/junos/junos_lldp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of LLDP service on Juniper JUNOS network devices.\n class Junos_lldp < Base\n # @return [Integer, nil] Frequency at which LLDP advertisements are sent (in seconds).\n attribute :interval\n validates :interval, type: Integer\n\n # @return [Integer, nil] Specify the number of seconds the device waits before sending advertisements to neighbors after a change is made in local system.\n attribute :transmit_delay\n validates :transmit_delay, type: Integer\n\n # @return [Integer, nil] Specify the number of seconds that LLDP information is held before it is discarded. The multiplier value is used in combination with the C(interval) value.\n attribute :hold_multiplier\n validates :hold_multiplier, type: Integer\n\n # @return [:present, :absent, :enabled, :disabled, nil] Value of C(present) ensures given LLDP configuration is present on device and LLDP is enabled, for value of C(absent) LLDP configuration is deleted and LLDP is in disabled state. Value C(enabled) ensures LLDP protocol is enabled and LLDP configuration if any is configured on remote device, for value of C(disabled) it ensures LLDP protocol is disabled any LLDP configuration if any is still present.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :enabled, :disabled], :message=>\"%{value} needs to be :present, :absent, :enabled, :disabled\"}, allow_nil: true\n\n # @return [Boolean, nil] Specifies whether or not the configuration is active or deactivated\n attribute :active\n validates :active, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6953322887420654, "alphanum_fraction": 0.7063692808151245, "avg_line_length": 69.1451644897461, "blob_id": "83d757ea728e804b4c464bebbd075ba5327657be", "content_id": "b60a648a121cfb4445e1d2d09b61b5e5400008b9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4349, "license_type": "permissive", "max_line_length": 370, "num_lines": 62, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_vxlan_gateway.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configuring Centralized All-Active Gateways or Distributed Gateway for the VXLAN Network on HUAWEI CloudEngine devices.\n class Ce_vxlan_gateway < Base\n # @return [Object, nil] Specifies the ID of a DFS group. The value must be 1.\n attribute :dfs_id\n\n # @return [Object, nil] Specifies the IPv4 address bound to a DFS group. The value is in dotted decimal notation.\n attribute :dfs_source_ip\n\n # @return [Object, nil] Specifies the name of a VPN instance bound to a DFS group. The value is a string of 1 to 31 case-sensitive characters without spaces. If the character string is quoted by double quotation marks, the character string can contain spaces. The value C(_public_) is reserved and cannot be used as the VPN instance name.\n attribute :dfs_source_vpn\n\n # @return [Object, nil] Specifies the UDP port number of the DFS group. The value is an integer that ranges from 1025 to 65535.\n attribute :dfs_udp_port\n\n # @return [:enable, :disable, nil] Creates all-active gateways.\n attribute :dfs_all_active\n validates :dfs_all_active, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [Object, nil] Configure the IP address of an all-active gateway peer. The value is in dotted decimal notation.\n attribute :dfs_peer_ip\n\n # @return [Object, nil] Specifies the name of the VPN instance that is associated with all-active gateway peer. The value is a string of 1 to 31 case-sensitive characters, spaces not supported. When double quotation marks are used around the string, spaces are allowed in the string. The value C(_public_) is reserved and cannot be used as the VPN instance name.\n attribute :dfs_peer_vpn\n\n # @return [Object, nil] Specifies the name of a VPN instance. The value is a string of 1 to 31 case-sensitive characters, spaces not supported. When double quotation marks are used around the string, spaces are allowed in the string. The value C(_public_) is reserved and cannot be used as the VPN instance name.\n attribute :vpn_instance\n\n # @return [Object, nil] Specifies a VNI ID. Binds a VXLAN network identifier (VNI) to a virtual private network (VPN) instance. The value is an integer ranging from 1 to 16000000.\n attribute :vpn_vni\n\n # @return [Object, nil] Full name of VBDIF interface, i.e. Vbdif100.\n attribute :vbdif_name\n\n # @return [Object, nil] Specifies the name of the VPN instance that is associated with the interface. The value is a string of 1 to 31 case-sensitive characters, spaces not supported. When double quotation marks are used around the string, spaces are allowed in the string. The value C(_public_) is reserved and cannot be used as the VPN instance name.\n attribute :vbdif_bind_vpn\n\n # @return [Object, nil] Specifies a MAC address for a VBDIF interface. The value is in the format of H-H-H. Each H is a 4-digit hexadecimal number, such as C(00e0) or C(fc01). If an H contains less than four digits, 0s are added ahead. For example, C(e0) is equal to C(00e0). A MAC address cannot be all 0s or 1s or a multicast MAC address.\n attribute :vbdif_mac\n\n # @return [:enable, :disable, nil] Enable the distributed gateway function on VBDIF interface.\n attribute :arp_distribute_gateway\n validates :arp_distribute_gateway, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:enable, :disable, nil] Enable VLINK direct route on VBDIF interface.\n attribute :arp_direct_route\n validates :arp_direct_route, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Determines whether the config should be present or not on the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6748855113983154, "alphanum_fraction": 0.6759422421455383, "avg_line_length": 53.596153259277344, "blob_id": "a6188216c2d639fabf6fc1c015165edbb1e17a26", "content_id": "f71d6c559bbe1b7222b9972ea17886a002079f3b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2839, "license_type": "permissive", "max_line_length": 220, "num_lines": 52, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_vpc_net.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, modify, and terminate AWS virtual private clouds.\n class Ec2_vpc_net < Base\n # @return [String] The name to give your VPC. This is used in combination with C(cidr_block) to determine if a VPC already exists.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] The primary CIDR of the VPC. After 2.5 a list of CIDRs can be provided. The first in the list will be used as the primary CIDR and is used in conjunction with the C(name) to ensure idempotence.\n attribute :cidr_block\n validates :cidr_block, presence: true, type: String\n\n # @return [Symbol, nil] Remove CIDRs that are associated with the VPC and are not specified in C(cidr_block).\n attribute :purge_cidrs\n validates :purge_cidrs, type: Symbol\n\n # @return [:default, :dedicated, nil] Whether to be default or dedicated tenancy. This cannot be changed after the VPC has been created.\n attribute :tenancy\n validates :tenancy, expression_inclusion: {:in=>[:default, :dedicated], :message=>\"%{value} needs to be :default, :dedicated\"}, allow_nil: true\n\n # @return [Boolean, nil] Whether to enable AWS DNS support.\n attribute :dns_support\n validates :dns_support, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Whether to enable AWS hostname support.\n attribute :dns_hostnames\n validates :dns_hostnames, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] the id of the DHCP options to use for this vpc\n attribute :dhcp_opts_id\n\n # @return [Hash, nil] The tags you want attached to the VPC. This is independent of the name value, note if you pass a 'Name' key it would override the Name of the VPC if it's different.\n attribute :tags\n validates :tags, type: Hash\n\n # @return [:present, :absent, nil] The state of the VPC. Either absent or present.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Boolean, nil] By default the module will not create another VPC if there is another VPC with the same name and CIDR block. Specify this as true if you want duplicate VPCs created.\n attribute :multi_ok\n validates :multi_ok, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6454005837440491, "alphanum_fraction": 0.6513352990150452, "avg_line_length": 38.07246398925781, "blob_id": "458516181b93366570dc6c104f6b71f0d4f60bfb", "content_id": "6a309ea8f3160194a3f7c41310860fbc5270b563", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2696, "license_type": "permissive", "max_line_length": 201, "num_lines": 69, "path": "/lib/ansible/ruby/modules/generated/cloud/ovirt/ovirt_storage_connection.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Module to manage storage connections in oVirt\n class Ovirt_storage_connection < Base\n # @return [String, nil] Id of the storage connection to manage.\n attribute :id\n validates :id, type: String\n\n # @return [:present, :absent, nil] Should the storage connection be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Name of the storage domain to be used with storage connection.\n attribute :storage\n validates :storage, type: String\n\n # @return [String, nil] Address of the storage server. E.g.: myserver.mydomain.com\n attribute :address\n validates :address, type: String\n\n # @return [Object, nil] Path of the mount point of the storage. E.g.: /path/to/my/data\n attribute :path\n\n # @return [Object, nil] NFS version. One of: I(auto), I(v3), I(v4) or I(v4_1).\n attribute :nfs_version\n\n # @return [Object, nil] The time in tenths of a second to wait for a response before retrying NFS requests. Range 0 to 65535.\n attribute :nfs_timeout\n\n # @return [Object, nil] The number of times to retry a request before attempting further recovery actions. Range 0 to 65535.\n attribute :nfs_retrans\n\n # @return [Object, nil] Option which will be passed when mounting storage.\n attribute :mount_options\n\n # @return [Object, nil] A CHAP password for logging into a target.\n attribute :password\n\n # @return [Object, nil] A CHAP username for logging into a target.\n attribute :username\n\n # @return [Integer, nil] Port of the iSCSI storage server.\n attribute :port\n validates :port, type: Integer\n\n # @return [String, nil] The target IQN for the storage device.\n attribute :target\n validates :target, type: String\n\n # @return [String, nil] Storage type. For example: I(nfs), I(iscsi), etc.\n attribute :type\n validates :type, type: String\n\n # @return [Object, nil] Virtual File System type.\n attribute :vfs_type\n\n # @return [Symbol, nil] This parameter is relevant only when updating a connection.,If I(true) the storage domain don't have to be in I(MAINTENANCE) state, so the storage connection is updated.\n attribute :force\n validates :force, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.681118905544281, "alphanum_fraction": 0.681118905544281, "avg_line_length": 56.97297286987305, "blob_id": "18738ea9cc5fe36e505e9aefe0856663c13a514c", "content_id": "471aea6ab890013039fb90f771f957e19c736dd3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2145, "license_type": "permissive", "max_line_length": 264, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/packaging/os/apk.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages I(apk) packages for Alpine Linux.\n class Apk < Base\n # @return [:yes, :no, nil] During upgrade, reset versioned world dependencies and change logic to prefer replacing or downgrading packages (instead of holding them) if the currently installed package is no longer available from any repository.\n attribute :available\n validates :available, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] A package name, like C(foo), or multiple packages, like C(foo, bar).\n attribute :name\n validates :name, type: TypeGeneric.new(String)\n\n # @return [String, nil] A package repository or multiple repositories. Unlike with the underlying apk command, this list will override the system repositories rather than supplement them.\n attribute :repository\n validates :repository, type: String\n\n # @return [:present, :absent, :latest, nil] Indicates the desired package(s) state.,C(present) ensures the package(s) is/are present.,C(absent) ensures the package(s) is/are absent.,C(latest) ensures the package(s) is/are present and the latest version(s).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :latest], :message=>\"%{value} needs to be :present, :absent, :latest\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Update repository indexes. Can be run with other steps or on it's own.\n attribute :update_cache\n validates :update_cache, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Upgrade all installed packages to their latest version.\n attribute :upgrade\n validates :upgrade, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6402957439422607, "avg_line_length": 54.20408248901367, "blob_id": "0eb4c6f4f1810714f61eccea7e20a6f11487128e", "content_id": "bbb4ce40056bee355c6c8ada5df7c112421b0eca", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2705, "license_type": "permissive", "max_line_length": 416, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_l3out.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage Layer 3 Outside (L3Out) on Cisco ACI fabrics.\n class Aci_l3out < Base\n # @return [String] Name of an existing tenant.\n attribute :tenant\n validates :tenant, presence: true, type: String\n\n # @return [Object] Name of L3Out being created.\n attribute :l3out\n validates :l3out, presence: true\n\n # @return [String] Name of the VRF being associated with the L3Out.\n attribute :vrf\n validates :vrf, presence: true, type: String\n\n # @return [String] Name of the external L3 domain being associated with the L3Out.\n attribute :domain\n validates :domain, presence: true, type: String\n\n # @return [:AF11, :AF12, :AF13, :AF21, :AF22, :AF23, :AF31, :AF32, :AF33, :AF41, :AF42, :AF43, :CS0, :CS1, :CS2, :CS3, :CS4, :CS5, :CS6, :CS7, :EF, :VA, :unspecified, nil] The target Differentiated Service (DSCP) value.,The APIC defaults to C(unspecified) when unset during creation.\n attribute :dscp\n validates :dscp, expression_inclusion: {:in=>[:AF11, :AF12, :AF13, :AF21, :AF22, :AF23, :AF31, :AF32, :AF33, :AF41, :AF42, :AF43, :CS0, :CS1, :CS2, :CS3, :CS4, :CS5, :CS6, :CS7, :EF, :VA, :unspecified], :message=>\"%{value} needs to be :AF11, :AF12, :AF13, :AF21, :AF22, :AF23, :AF31, :AF32, :AF33, :AF41, :AF42, :AF43, :CS0, :CS1, :CS2, :CS3, :CS4, :CS5, :CS6, :CS7, :EF, :VA, :unspecified\"}, allow_nil: true\n\n # @return [:export, :import, nil] Route Control enforcement direction. The only allowed values are export or import,export.\n attribute :route_control\n validates :route_control, expression_inclusion: {:in=>[:export, :import], :message=>\"%{value} needs to be :export, :import\"}, allow_nil: true\n\n # @return [:static, :bgp, :ospf, :pim, nil] Routing protocol for the L3Out\n attribute :l3protocol\n validates :l3protocol, expression_inclusion: {:in=>[:static, :bgp, :ospf, :pim], :message=>\"%{value} needs to be :static, :bgp, :ospf, :pim\"}, allow_nil: true\n\n # @return [String, nil] Description for the L3Out.\n attribute :description\n validates :description, type: String\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6805333495140076, "alphanum_fraction": 0.6821333169937134, "avg_line_length": 42.604652404785156, "blob_id": "3e40429a84e20a3c0cc3f40760418e561b99a4e1", "content_id": "01ba73baaa27881146a8799402c675b616b7d559", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1875, "license_type": "permissive", "max_line_length": 220, "num_lines": 43, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_sqlserver.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and delete instance of SQL Server\n class Azure_rm_sqlserver < Base\n # @return [String] The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] The name of the server.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Resource location.\n attribute :location\n validates :location, type: String\n\n # @return [String, nil] Administrator username for the server. Once created it cannot be changed.\n attribute :admin_username\n validates :admin_username, type: String\n\n # @return [String, nil] The administrator login password (required for server creation).\n attribute :admin_password\n validates :admin_password, type: String\n\n # @return [Object, nil] The version of the server. For example '12.0'.\n attribute :version\n\n # @return [Object, nil] The identity type. Set this to 'SystemAssigned' in order to automatically create and assign an Azure Active Directory principal for the resour ce. Possible values include: 'SystemAssigned'\n attribute :identity\n\n # @return [:absent, :present, nil] Assert the state of the SQL server. Use 'present' to create or update a server and 'absent' to delete a server.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6766990423202515, "alphanum_fraction": 0.6786407828330994, "avg_line_length": 46.906978607177734, "blob_id": "633aca2fab2404c56f5850fb3a8005cb13dd27e0", "content_id": "937cabab53b2878c6501ba803559e53df75028c5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2060, "license_type": "permissive", "max_line_length": 214, "num_lines": 43, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_config_snapshot.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage Config Snapshots on Cisco ACI fabrics.\n # Creating new Snapshots is done using the configExportP class.\n # Removing Snapshots is done using the configSnapshot class.\n class Aci_config_snapshot < Base\n # @return [String, nil] The description for the Config Export Policy.\n attribute :description\n validates :description, type: String\n\n # @return [String, nil] The name of the Export Policy to use for Config Snapshots.\n attribute :export_policy\n validates :export_policy, type: String\n\n # @return [:json, :xml, nil] Sets the config backup to be formatted in JSON or XML.,The APIC defaults to C(json) when unset.\n attribute :format\n validates :format, expression_inclusion: {:in=>[:json, :xml], :message=>\"%{value} needs to be :json, :xml\"}, allow_nil: true\n\n # @return [Symbol, nil] Determines if secure information should be included in the backup.,The APIC defaults to C(yes) when unset.\n attribute :include_secure\n validates :include_secure, type: Symbol\n\n # @return [Integer, nil] Determines how many snapshots can exist for the Export Policy before the APIC starts to rollover.,Accepted values range between C(1) and C(10).,The APIC defaults to C(3) when unset.\n attribute :max_count\n validates :max_count, type: Integer\n\n # @return [String, nil] The name of the snapshot to delete.\n attribute :snapshot\n validates :snapshot, type: String\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6933987736701965, "alphanum_fraction": 0.6933987736701965, "avg_line_length": 46, "blob_id": "b41add108c85ec618294f4de9a2ea661e4722ca0", "content_id": "b7a50ef8cd55d48ef0ffe0b49156fcd17d906cc2", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1833, "license_type": "permissive", "max_line_length": 140, "num_lines": 39, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/netapp_e_snapshot_images.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create and delete snapshots images on snapshot groups for NetApp E-series storage arrays.\n # Only the oldest snapshot image can be deleted so consistency is preserved.\n # Related: Snapshot volumes are created from snapshot images.\n class Netapp_e_snapshot_images < Base\n # @return [String] The username to authenticate with the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_username\n validates :api_username, presence: true, type: String\n\n # @return [String] The password to authenticate with the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_password\n validates :api_password, presence: true, type: String\n\n # @return [String] The url to the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_url\n validates :api_url, presence: true, type: String\n\n # @return [Boolean, nil] Should https certificates be validated?\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String] The name of the snapshot group in which you want to create a snapshot image.\n attribute :snapshot_group\n validates :snapshot_group, presence: true, type: String\n\n # @return [:create, :remove] Whether a new snapshot image should be created or oldest be deleted.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:create, :remove], :message=>\"%{value} needs to be :create, :remove\"}\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6612529158592224, "alphanum_fraction": 0.6612529158592224, "avg_line_length": 40.0476188659668, "blob_id": "7b8f850368552ad78d386f9c07f6490e5a49b5f3", "content_id": "624bc645ae2560b7a771264e8041df1425c73350", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1724, "license_type": "permissive", "max_line_length": 277, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/system/sefcontext.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages SELinux file context mapping definitions.\n # Similar to the C(semanage fcontext) command.\n class Sefcontext < Base\n # @return [String] Target path (expression).\n attribute :target\n validates :target, presence: true, type: String\n\n # @return [String, nil] File type.,The following file type options can be passed; C(a) for all files, C(b) for block devices, C(c) for character devices, C(d) for directories, C(f) for regular files, C(l) for symbolic links, C(p) for named pipes, C(s) for socket files.\n attribute :ftype\n validates :ftype, type: String\n\n # @return [String] SELinux type for the specified target.\n attribute :setype\n validates :setype, presence: true, type: String\n\n # @return [String, nil] SELinux user for the specified target.\n attribute :seuser\n validates :seuser, type: String\n\n # @return [String, nil] SELinux range for the specified target.\n attribute :selevel\n validates :selevel, type: String\n\n # @return [String, nil] Whether the SELinux file context must be C(absent) or C(present).\n attribute :state\n validates :state, type: String\n\n # @return [:yes, :no, nil] Reload SELinux policy after commit.,Note that this does not apply SELinux file contexts to existing files.\n attribute :reload\n validates :reload, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7262371182441711, "alphanum_fraction": 0.7262371182441711, "avg_line_length": 62.84090805053711, "blob_id": "e2d8d0c28db7e093d36b19fbffa0ab42581bfa2d", "content_id": "56ed6329ffa76b68e45139159f52a42427671e3b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2809, "license_type": "permissive", "max_line_length": 300, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/network/iosxr/iosxr_system.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of node system attributes on Cisco IOS XR devices. It provides an option to configure host system parameters or remove those parameters from the device active configuration.\n class Iosxr_system < Base\n # @return [String, nil] Configure the device hostname parameter. This option takes an ASCII string value.\n attribute :hostname\n validates :hostname, type: String\n\n # @return [String, nil] VRF name for domain services\n attribute :vrf\n validates :vrf, type: String\n\n # @return [String, nil] Configure the IP domain name on the remote device to the provided value. Value should be in the dotted name form and will be appended to the C(hostname) to create a fully-qualified domain name.\n attribute :domain_name\n validates :domain_name, type: String\n\n # @return [Object, nil] Provides the list of domain suffixes to append to the hostname for the purpose of doing name resolution. This argument accepts a list of names and will be reconciled with the current active configuration on the running node.\n attribute :domain_search\n\n # @return [String, nil] The C(lookup_source) argument provides one or more source interfaces to use for performing DNS lookups. The interface provided in C(lookup_source) must be a valid interface configured on the device.\n attribute :lookup_source\n validates :lookup_source, type: String\n\n # @return [Symbol, nil] Provides administrative control for enabling or disabling DNS lookups. When this argument is set to True, lookups are performed and when it is set to False, lookups are not performed.\n attribute :lookup_enabled\n validates :lookup_enabled, type: Symbol\n\n # @return [Array<String>, String, nil] The C(name_serves) argument accepts a list of DNS name servers by way of either FQDN or IP address to use to perform name resolution lookups. This argument accepts wither a list of DNS servers See examples.\n attribute :name_servers\n validates :name_servers, type: TypeGeneric.new(String)\n\n # @return [:present, :absent, nil] State of the configuration values in the device's current active configuration. When set to I(present), the values should be configured in the device active configuration and when set to I(absent) the values should not be in the device active configuration\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.707975447177887, "alphanum_fraction": 0.707975447177887, "avg_line_length": 37.80952453613281, "blob_id": "887e3565c8d6b2bb4f45a477b0bac316776c0820", "content_id": "0ef06bec57bab73a3a7d90e27c032acccc348daf", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 815, "license_type": "permissive", "max_line_length": 280, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/remote_management/oneview/oneview_enclosure_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Retrieve facts about one or more of the Enclosures from OneView.\n class Oneview_enclosure_facts < Base\n # @return [String, nil] Enclosure name.\n attribute :name\n validates :name, type: String\n\n # @return [Array<String>, String, nil] List with options to gather additional facts about an Enclosure and related resources. Options allowed: C(script), C(environmentalConfiguration), and C(utilization). For the option C(utilization), you can provide specific parameters.\n attribute :options\n validates :options, type: TypeGeneric.new(String, Hash)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6767676472663879, "alphanum_fraction": 0.6767676472663879, "avg_line_length": 39.965518951416016, "blob_id": "0bf17211062020de3bd0722c61430bc56451279f", "content_id": "12bdacd240987fa088b43ce03bc24d77d6daef1e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1188, "license_type": "permissive", "max_line_length": 240, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/identity/ipa/ipa_sudocmdgroup.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add, modify or delete sudo command group within IPA server using IPA API.\n class Ipa_sudocmdgroup < Base\n # @return [Object] Sudo Command Group.\n attribute :cn\n validates :cn, presence: true\n\n # @return [String, nil] Group description.\n attribute :description\n validates :description, type: String\n\n # @return [:present, :absent, :enabled, :disabled, nil] State to ensure\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :enabled, :disabled], :message=>\"%{value} needs to be :present, :absent, :enabled, :disabled\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] List of sudo commands to assign to the group.,If an empty list is passed all assigned commands will be removed from the group.,If option is omitted sudo commands will not be checked or changed.\n attribute :sudocmd\n validates :sudocmd, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7037671208381653, "alphanum_fraction": 0.7037671208381653, "avg_line_length": 31.44444465637207, "blob_id": "181d3906249030ef37b83c0087525847e0d69139", "content_id": "eb80f6df071b56b8045025b0515343fdc2797d65", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 584, "license_type": "permissive", "max_line_length": 99, "num_lines": 18, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_useraccount.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used for updating the password of a user.\n # This module is useful for setting up admin password for Controller bootstrap.\n class Avi_useraccount < Base\n # @return [String, nil] Old password for update password or default password for bootstrap.\n attribute :old_password\n validates :old_password, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6692675352096558, "alphanum_fraction": 0.671784520149231, "avg_line_length": 60.123077392578125, "blob_id": "97ffbdbe6f23ae1c8e15dcf4c0708d598a4f3ebc", "content_id": "5a2de8ec786511591885454091546a924c5e6bd4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3973, "license_type": "permissive", "max_line_length": 210, "num_lines": 65, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_stp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages STP configurations on HUAWEI CloudEngine switches.\n class Ce_stp < Base\n # @return [:present, :absent, nil] Specify desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:stp, :rstp, :mstp, nil] Set an operation mode for the current MSTP process. The mode can be STP, RSTP, or MSTP.\n attribute :stp_mode\n validates :stp_mode, expression_inclusion: {:in=>[:stp, :rstp, :mstp], :message=>\"%{value} needs to be :stp, :rstp, :mstp\"}, allow_nil: true\n\n # @return [:enable, :disable, nil] Enable or disable STP on a switch.\n attribute :stp_enable\n validates :stp_enable, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:fast, :normal, nil] STP convergence mode. Fast means set STP aging mode to Fast. Normal means set STP aging mode to Normal.\n attribute :stp_converge\n validates :stp_converge, expression_inclusion: {:in=>[:fast, :normal], :message=>\"%{value} needs to be :fast, :normal\"}, allow_nil: true\n\n # @return [:enable, :disable, nil] Configure BPDU protection on an edge port. This function prevents network flapping caused by attack packets.\n attribute :bpdu_protection\n validates :bpdu_protection, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:enable, :disable, nil] Configure the TC BPDU protection function for an MSTP process.\n attribute :tc_protection\n validates :tc_protection, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [Object, nil] Set the time the MSTP device takes to handle the maximum number of TC BPDUs and immediately refresh forwarding entries. The value is an integer ranging from 1 to 600, in seconds.\n attribute :tc_protection_interval\n\n # @return [Object, nil] Set the maximum number of TC BPDUs that the MSTP can handle. The value is an integer ranging from 1 to 255. The default value is 1 on the switch.\n attribute :tc_protection_threshold\n\n # @return [Object, nil] Interface name. If the value is C(all), will apply configuration to all interfaces. if the value is a special name, only support input the full name.\n attribute :interface\n\n # @return [:enable, :disable, nil] Set the current port as an edge port.\n attribute :edged_port\n validates :edged_port, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:enable, :disable, nil] Specify a port as a BPDU filter port.\n attribute :bpdu_filter\n validates :bpdu_filter, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [Object, nil] Set the path cost of the current port. The default instance is 0.\n attribute :cost\n\n # @return [:enable, :disable, nil] Enable root protection on the current port.\n attribute :root_protection\n validates :root_protection, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:enable, :disable, nil] Enable loop protection on the current port.\n attribute :loop_protection\n validates :loop_protection, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7199113368988037, "alphanum_fraction": 0.7335492372512817, "avg_line_length": 92.11111450195312, "blob_id": "1917b1588f38b0a3bc88bbec85a09112d6cf9b34", "content_id": "4063e585a1fc5a17fe0c1b9069a19610260d2a9f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5866, "license_type": "permissive", "max_line_length": 953, "num_lines": 63, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_interface_policy_ospf.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage OSPF interface policies on Cisco ACI fabrics.\n class Aci_interface_policy_ospf < Base\n # @return [String] The name of the Tenant the OSPF interface policy should belong to.\n attribute :tenant\n validates :tenant, presence: true, type: String\n\n # @return [String] The OSPF interface policy name.,This name can be between 1 and 64 alphanumeric characters.,Note that you cannot change this name after the object has been saved.\n attribute :ospf\n validates :ospf, presence: true, type: String\n\n # @return [Object, nil] The description for the OSPF interface.\n attribute :description\n\n # @return [:bcast, :p2p, nil] The OSPF interface policy network type.,OSPF supports broadcast and point-to-point.,The APIC defaults to C(unspecified) when unset during creation.\n attribute :network_type\n validates :network_type, expression_inclusion: {:in=>[:bcast, :p2p], :message=>\"%{value} needs to be :bcast, :p2p\"}, allow_nil: true\n\n # @return [Object, nil] The OSPF cost of the interface.,The cost (also called metric) of an interface in OSPF is an indication of the overhead required to send packets across a certain interface. The cost of an interface is inversely proportional to the bandwidth of that interface. A higher bandwidth indicates a lower cost. There is more overhead (higher cost) and time delays involved in crossing a 56k serial line than crossing a 10M ethernet line. The formula used to calculate the cost is C(cost= 10000 0000/bandwith in bps) For example, it will cost 10 EXP8/10 EXP7 = 10 to cross a 10M Ethernet line and will cost 10 EXP8/1544000 = 64 to cross a T1 line.,By default, the cost of an interface is calculated based on the bandwidth; you can force the cost of an interface with the ip ospf cost value interface subconfiguration mode command.,Accepted values range between C(1) and C(450).,The APIC defaults to C(0) when unset during creation.\n attribute :cost\n\n # @return [:\"advert-subnet\", :bfd, :\"mtu-ignore\", :passive, nil] The interface policy controls.,This is a list of one or more of the following controls:,C(advert-subnet) -- Advertise IP subnet instead of a host mask in the router LSA.,C(bfd) -- Bidirectional Forwarding Detection,C(mtu-ignore) -- Disables MTU mismatch detection on an interface.,C(passive) -- The interface does not participate in the OSPF protocol and will not establish adjacencies or send routing updates. However the interface is announced as part of the routing network.\n attribute :controls\n validates :controls, expression_inclusion: {:in=>[:\"advert-subnet\", :bfd, :\"mtu-ignore\", :passive], :message=>\"%{value} needs to be :\\\"advert-subnet\\\", :bfd, :\\\"mtu-ignore\\\", :passive\"}, allow_nil: true\n\n # @return [Integer, nil] The interval between hello packets from a neighbor before the router declares the neighbor as down.,This value must be the same for all networking devices on a specific network.,Specifying a smaller dead interval (seconds) will give faster detection of a neighbor being down and improve convergence, but might cause more routing instability.,Accepted values range between C(1) and C(65535).,The APIC defaults to C(40) when unset during creation.\n attribute :dead_interval\n validates :dead_interval, type: Integer\n\n # @return [Integer, nil] The interval between hello packets that OSPF sends on the interface.,Note that the smaller the hello interval, the faster topological changes will be detected, but more routing traffic will ensue.,This value must be the same for all routers and access servers on a specific network.,Accepted values range between C(1) and C(65535).,The APIC defaults to C(10) when unset during creation.\n attribute :hello_interval\n validates :hello_interval, type: Integer\n\n # @return [Symbol, nil] Whether prefix suppressions is enabled or disabled.,The APIC defaults to C(inherit) when unset during creation.\n attribute :prefix_suppression\n validates :prefix_suppression, type: Symbol\n\n # @return [Integer, nil] The priority for the OSPF interface profile.,Accepted values ranges between C(0) and C(255).,The APIC defaults to C(1) when unset during creation.\n attribute :priority\n validates :priority, type: Integer\n\n # @return [Integer, nil] The interval between LSA retransmissions.,The retransmit interval occurs while the router is waiting for an acknowledgement from the neighbor router that it received the LSA.,If no acknowlegment is received at the end of the interval, then the LSA is resent.,Accepted values range between C(1) and C(65535).,The APIC defaults to C(5) when unset during creation.\n attribute :retransmit_interval\n validates :retransmit_interval, type: Integer\n\n # @return [Integer, nil] The delay time needed to send an LSA update packet.,OSPF increments the LSA age time by the transmit delay amount before transmitting the LSA update.,You should take into account the transmission and propagation delays for the interface when you set this value.,Accepted values range between C(1) and C(450).,The APIC defaults to C(1) when unset during creation.\n attribute :transmit_delay\n validates :transmit_delay, type: Integer\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6789862513542175, "alphanum_fraction": 0.6789862513542175, "avg_line_length": 32.82143020629883, "blob_id": "c756e114d64c14bb664b74a94885757567303abb", "content_id": "a692a96fb631ce4de0277faacb40c1263d5fcf72", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 947, "license_type": "permissive", "max_line_length": 111, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_containerregistry_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Get facts for Container Registry.\n class Azure_rm_containerregistry_facts < Base\n # @return [String] The name of the resource group to which the container registry belongs.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String, nil] The name of the container registry.\n attribute :name\n validates :name, type: String\n\n # @return [Symbol, nil] Retrieve credentials for container registry.\n attribute :retrieve_credentials\n validates :retrieve_credentials, type: Symbol\n\n # @return [Object, nil] Limit results by providing a list of tags. Format tags as 'key' or 'key:value'.\n attribute :tags\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6816479563713074, "alphanum_fraction": 0.6816479563713074, "avg_line_length": 41.720001220703125, "blob_id": "95f06a938c55a69064c8179fe9097824669a9475", "content_id": "5beec7e69ad3b31a5e259da6a63a02106c844e39", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1068, "license_type": "permissive", "max_line_length": 214, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gce_eip.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create (reserve) or Destroy (release) Regional or Global IP Addresses. See U(https://cloud.google.com/compute/docs/configure-instance-ip-addresses#reserve_new_static) for more on reserving static addresses.\n class Gce_eip < Base\n # @return [String] Name of Address.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] Region to create the address in. Set to 'global' to create a global address.\n attribute :region\n validates :region, presence: true, type: String\n\n # @return [:present, :absent, nil] The state the address should be in. C(present) or C(absent) are the only valid options.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6853677034378052, "alphanum_fraction": 0.6861258745193481, "avg_line_length": 41.54838562011719, "blob_id": "df0e4667e52212ae75b448838cfaf546c20c9156", "content_id": "10a62927f483359bdfe3900875f63ac1ce2c93ef", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1319, "license_type": "permissive", "max_line_length": 259, "num_lines": 31, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/lambda_alias.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows the management of AWS Lambda functions aliases via the Ansible framework. It is idempotent and supports \"Check\" mode. Use module M(lambda) to manage the lambda function itself and M(lambda_event) to manage event source mappings.\n class Lambda_alias < Base\n # @return [Object] The name of the function alias.\n attribute :function_name\n validates :function_name, presence: true\n\n # @return [:present, :absent] Describes the desired state.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String] Name of the function alias.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] A short, user-defined function alias description.\n attribute :description\n\n # @return [Object, nil] Version associated with the Lambda function alias. A value of 0 (or omitted parameter) sets the alias to the $LATEST version.\n attribute :version\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6984127163887024, "alphanum_fraction": 0.6984127163887024, "avg_line_length": 35.75, "blob_id": "9180405a9785480e27639f538f065918325504f9", "content_id": "b24ad5e2d81c4038aa2ce7de083b722b57438476", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 882, "license_type": "permissive", "max_line_length": 125, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/network/ftd/ftd_file_upload.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Uploads files to Cisco FTD devices including disk files, backups, and upgrades.\n class Ftd_file_upload < Base\n # @return [String] The name of the operation to execute.,Only operations that upload file can be used in this module.\n attribute :operation\n validates :operation, presence: true, type: String\n\n # @return [String] Absolute path to the file that should be uploaded.\n attribute :fileToUpload\n validates :fileToUpload, presence: true, type: String\n\n # @return [Object, nil] Specifies Ansible fact name that is used to register received response from the FTD device.\n attribute :register_as\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7289300560951233, "alphanum_fraction": 0.7310221195220947, "avg_line_length": 87.0526351928711, "blob_id": "bf136de8a213bf3e477fefee88d76cf2ab30648e", "content_id": "71090b0c2b88cc6fc4b4b6c2a775fb75ae5f87b7", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6692, "license_type": "permissive", "max_line_length": 618, "num_lines": 76, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_tunnel.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages tunnels on a BIG-IP. Tunnels are usually based upon a tunnel profile which defines both default arguments and constraints for the tunnel.\n # Due to this, this module exposes a number of settings that may or may not be related to the type of tunnel you are working with. It is important that you take this into consideration when declaring your tunnel config.\n # If a specific tunnel does not support the parameter you are considering, the documentation of the parameter will usually make mention of this. Otherwise, when configuring that parameter on the device, the device will notify you.\n class Bigip_tunnel < Base\n # @return [String] Specifies the name of the tunnel.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Description of the tunnel.\n attribute :description\n\n # @return [Object, nil] Specifies the profile to associate with the tunnel for handling traffic.,Depending on your selection, other settings become available or disappear.,This parameter may not be changed after it is set.\n attribute :profile\n\n # @return [Integer, nil] When applied to a GRE tunnel, this value specifies an optional field in the GRE header, used to authenticate the source of the packet.,When applied to a VXLAN or Geneve tunnel, this value specifies the Virtual Network Identifier (VNI).,When applied to an NVGRE tunnel, this value specifies the Virtual Subnet Identifier (VSID).,When creating a new tunnel, if this parameter is supported by the tunnel profile but not specified, the default value is C(0).\n attribute :key\n validates :key, type: Integer\n\n # @return [String, nil] Specifies the IP address of the local endpoint of the tunnel.\n attribute :local_address\n validates :local_address, type: String\n\n # @return [Object, nil] Specifies the IP address of the remote endpoint of the tunnel.,For C(dslite), C(fec) (when configuring the FEC tunnel for receiving traffic only), C(v6rd) (configured as a border relay), or C(map), the tunnel must have an unspecified remote address (any).\n attribute :remote_address\n\n # @return [String, nil] Specifies a non-floating IP address for the tunnel, to be used with host-initiated traffic.\n attribute :secondary_address\n validates :secondary_address, type: String\n\n # @return [Integer, nil] Specifies the maximum transmission unit (MTU) of the tunnel.,When creating a new tunnel, if this parameter is supported by the tunnel profile but not specified, the default value is C(0).,The valid range is from C(0) to C(65515).\n attribute :mtu\n validates :mtu, type: Integer\n\n # @return [Symbol, nil] Enables or disables the tunnel to use the PMTU (Path MTU) information provided by ICMP NeedFrag error messages.,If C(yes) and the tunnel C(mtu) is set to C(0), the tunnel will use the PMTU information.,If C(yes) and the tunnel C(mtu) is fixed to a non-zero value, the tunnel will use the minimum of PMTU and MTU.,If C(no), the tunnel will use fixed MTU or calculate its MTU using tunnel encapsulation configurations.\n attribute :use_pmtu\n validates :use_pmtu, type: Symbol\n\n # @return [String, nil] Specifies the Type of Service (TOS) value to insert in the encapsulating header of transmitted packets.,When creating a new tunnel, if this parameter is supported by the tunnel profile but not specified, the default value is C(preserve).,When C(preserve), the system copies the TOS value from the inner header to the outer header.,You may also specify a numeric value. The possible values are from C(0) to C(255).\n attribute :tos\n validates :tos, type: String\n\n # @return [:default, :enabled, :disabled, nil] Allows you to configure auto last hop on a per-tunnel basis.,When creating a new tunnel, if this parameter is supported by the tunnel profile but not specified, the default is C(default).,When C(default), means that the system uses the global auto-lasthop setting to send back the request.,When C(enabled), allows the system to send return traffic to the MAC address that transmitted the request, even if the routing table points to a different network or interface. As a result, the system can send return traffic to clients even when there is no matching route.\n attribute :auto_last_hop\n validates :auto_last_hop, expression_inclusion: {:in=>[:default, :enabled, :disabled], :message=>\"%{value} needs to be :default, :enabled, :disabled\"}, allow_nil: true\n\n # @return [String, nil] Specifies the traffic group to associate with the tunnel.,This value cannot be changed after it is set. This is a limitation of BIG-IP.\n attribute :traffic_group\n validates :traffic_group, type: String\n\n # @return [:bidirectional, :inbound, :outbound, nil] Specifies how the tunnel carries traffic.,When creating a new tunnel, if this parameter is supported by the tunnel profile but not specified, the default is C(bidirectional).,When C(bidirectional), specifies that the tunnel carries both inbound and outbound traffic.,When C(inbound), specifies that the tunnel carries only incoming traffic.,When C(outbound), specifies that the tunnel carries only outgoing traffic.\n attribute :mode\n validates :mode, expression_inclusion: {:in=>[:bidirectional, :inbound, :outbound], :message=>\"%{value} needs to be :bidirectional, :inbound, :outbound\"}, allow_nil: true\n\n # @return [Symbol, nil] Specifies that the tunnel operates in transparent mode.,When C(yes), you can inspect and manipulate the encapsulated traffic flowing through the BIG-IP system.,A transparent tunnel terminates a tunnel while presenting the illusion that the tunnel transits the device unmodified (that is, the BIG-IP system appears as if it were an intermediate router that simply routes IP traffic through the device).\n attribute :transparent\n validates :transparent, type: Symbol\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [:present, :absent, nil] When C(present), ensures that the tunnel exists.,When C(absent), ensures the tunnel is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6540540456771851, "alphanum_fraction": 0.6540540456771851, "avg_line_length": 34, "blob_id": "d70c6c2e401fde1bb71a169bab2589357872b669", "content_id": "aa02bce0828b660f25c65fac4782b4d672257e18", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1295, "license_type": "permissive", "max_line_length": 143, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/messaging/rabbitmq_parameter.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage dynamic, cluster-wide parameters for RabbitMQ\n class Rabbitmq_parameter < Base\n # @return [String] Name of the component of which the parameter is being set\n attribute :component\n validates :component, presence: true, type: String\n\n # @return [String] Name of the parameter being set\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Value of the parameter, as a JSON term\n attribute :value\n validates :value, type: String\n\n # @return [String, nil] vhost to apply access privileges.\n attribute :vhost\n validates :vhost, type: String\n\n # @return [String, nil] erlang node name of the rabbit we wish to configure\n attribute :node\n validates :node, type: String\n\n # @return [:present, :absent, nil] Specify if user is to be added or removed\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6675045490264893, "alphanum_fraction": 0.6761882901191711, "avg_line_length": 68.46031951904297, "blob_id": "3bff6c88f617d40db402e8fd72cd4310eb99e5da", "content_id": "875d0c5bbdee1337fdea0f951574bb8632e22be8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4376, "license_type": "permissive", "max_line_length": 355, "num_lines": 63, "path": "/lib/ansible/ruby/modules/generated/windows/win_find.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Return a list of files based on specified criteria.\n # Multiple criteria are AND'd together.\n # For non-Windows targets, use the M(find) module instead.\n class Win_find < Base\n # @return [Integer, String, nil] Select files or folders whose age is equal to or greater than the specified time. Use a negative age to find files equal to or less than the specified time. You can choose seconds, minutes, hours, days or weeks by specifying the first letter of an of those words (e.g., \"2s\", \"10d\", 1w\").\n attribute :age\n validates :age, type: MultipleTypes.new(Integer, String)\n\n # @return [:atime, :ctime, :mtime, nil] Choose the file property against which we compare C(age). The default attribute we compare with is the last modification time.\n attribute :age_stamp\n validates :age_stamp, expression_inclusion: {:in=>[:atime, :ctime, :mtime], :message=>\"%{value} needs to be :atime, :ctime, :mtime\"}, allow_nil: true\n\n # @return [:md5, :sha1, :sha256, :sha384, :sha512, nil] Algorithm to determine the checksum of a file. Will throw an error if the host is unable to use specified algorithm.\n attribute :checksum_algorithm\n validates :checksum_algorithm, expression_inclusion: {:in=>[:md5, :sha1, :sha256, :sha384, :sha512], :message=>\"%{value} needs to be :md5, :sha1, :sha256, :sha384, :sha512\"}, allow_nil: true\n\n # @return [:directory, :file, nil] Type of file to search for.\n attribute :file_type\n validates :file_type, expression_inclusion: {:in=>[:directory, :file], :message=>\"%{value} needs to be :directory, :file\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Set this to C(yes) to follow symlinks in the path.,This needs to be used in conjunction with C(recurse).\n attribute :follow\n validates :follow, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Whether to return a checksum of the file in the return info (default sha1), use C(checksum_algorithm) to change from the default.\n attribute :get_checksum\n validates :get_checksum, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Set this to include hidden files or folders.\n attribute :hidden\n validates :hidden, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Array<String>, String] List of paths of directories to search for files or folders in. This can be supplied as a single path or a list of paths.\n attribute :paths\n validates :paths, presence: true, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] One or more (powershell or regex) patterns to compare filenames with. The type of pattern matching is controlled by C(use_regex) option. The patterns retrict the list of files or folders to be returned based on the filenames. For a file to be matched it only has to match with one pattern in a list provided.\n attribute :patterns\n validates :patterns, type: TypeGeneric.new(String)\n\n # @return [:yes, :no, nil] Will recursively descend into the directory looking for files or folders.\n attribute :recurse\n validates :recurse, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, String, nil] Select files or folders whose size is equal to or greater than the specified size. Use a negative value to find files equal to or less than the specified size. You can specify the size with a suffix of the byte type i.e. kilo = k, mega = m... Size is not evaluated for symbolic links.\n attribute :size\n validates :size, type: MultipleTypes.new(Integer, String)\n\n # @return [:yes, :no, nil] Will set patterns to run as a regex check if set to C(yes).\n attribute :use_regex\n validates :use_regex, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6950151324272156, "alphanum_fraction": 0.7027093172073364, "avg_line_length": 74.88198852539062, "blob_id": "498482aefa43f97c5d26ca5515890bef1bf7af6e", "content_id": "7f9bff9fb3c397a7ed33f7a06ee68c08178a2b44", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 12217, "license_type": "permissive", "max_line_length": 751, "num_lines": 161, "path": "/lib/ansible/ruby/modules/generated/network/netscaler/netscaler_service.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage service configuration in Netscaler.\n # This module allows the creation, deletion and modification of Netscaler services.\n # This module is intended to run either on the ansible control node or a bastion (jumpserver) with access to the actual netscaler instance.\n # This module supports check mode.\n class Netscaler_service < Base\n # @return [String, nil] Name for the service. Must begin with an ASCII alphabetic or underscore C(_) character, and must contain only ASCII alphanumeric, underscore C(_), hash C(#), period C(.), space C( ), colon C(:), at C(@), equals C(=), and hyphen C(-) characters. Cannot be changed after the service has been created.,Minimum length = 1\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] IP to assign to the service.,Minimum length = 1\n attribute :ip\n\n # @return [Object, nil] Name of the server that hosts the service.,Minimum length = 1\n attribute :servername\n\n # @return [:HTTP, :FTP, :TCP, :UDP, :SSL, :SSL_BRIDGE, :SSL_TCP, :DTLS, :NNTP, :RPCSVR, :DNS, :ADNS, :SNMP, :RTSP, :DHCPRA, :ANY, :SIP_UDP, :SIP_TCP, :SIP_SSL, :DNS_TCP, :ADNS_TCP, :MYSQL, :MSSQL, :ORACLE, :RADIUS, :RADIUSListener, :RDP, :DIAMETER, :SSL_DIAMETER, :TFTP, :SMPP, :PPTP, :GRE, :SYSLOGTCP, :SYSLOGUDP, :FIX, :SSL_FIX, nil] Protocol in which data is exchanged with the service.\n attribute :servicetype\n validates :servicetype, expression_inclusion: {:in=>[:HTTP, :FTP, :TCP, :UDP, :SSL, :SSL_BRIDGE, :SSL_TCP, :DTLS, :NNTP, :RPCSVR, :DNS, :ADNS, :SNMP, :RTSP, :DHCPRA, :ANY, :SIP_UDP, :SIP_TCP, :SIP_SSL, :DNS_TCP, :ADNS_TCP, :MYSQL, :MSSQL, :ORACLE, :RADIUS, :RADIUSListener, :RDP, :DIAMETER, :SSL_DIAMETER, :TFTP, :SMPP, :PPTP, :GRE, :SYSLOGTCP, :SYSLOGUDP, :FIX, :SSL_FIX], :message=>\"%{value} needs to be :HTTP, :FTP, :TCP, :UDP, :SSL, :SSL_BRIDGE, :SSL_TCP, :DTLS, :NNTP, :RPCSVR, :DNS, :ADNS, :SNMP, :RTSP, :DHCPRA, :ANY, :SIP_UDP, :SIP_TCP, :SIP_SSL, :DNS_TCP, :ADNS_TCP, :MYSQL, :MSSQL, :ORACLE, :RADIUS, :RADIUSListener, :RDP, :DIAMETER, :SSL_DIAMETER, :TFTP, :SMPP, :PPTP, :GRE, :SYSLOGTCP, :SYSLOGUDP, :FIX, :SSL_FIX\"}, allow_nil: true\n\n # @return [Integer, nil] Port number of the service.,Range 1 - 65535,* in CLI is represented as 65535 in NITRO API\n attribute :port\n validates :port, type: Integer\n\n # @return [Object, nil] Port to which clear text data must be sent after the appliance decrypts incoming SSL traffic. Applicable to transparent SSL services.,Minimum value = 1\n attribute :cleartextport\n\n # @return [:TRANSPARENT, :REVERSE, :FORWARD, nil] Cache type supported by the cache server.\n attribute :cachetype\n validates :cachetype, expression_inclusion: {:in=>[:TRANSPARENT, :REVERSE, :FORWARD], :message=>\"%{value} needs to be :TRANSPARENT, :REVERSE, :FORWARD\"}, allow_nil: true\n\n # @return [Object, nil] Maximum number of simultaneous open connections to the service.,Minimum value = 0,Maximum value = 4294967294\n attribute :maxclient\n\n # @return [Boolean, nil] Monitor the health of this service\n attribute :healthmonitor\n validates :healthmonitor, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] Maximum number of requests that can be sent on a persistent connection to the service.,Note: Connection requests beyond this value are rejected.,Minimum value = 0,Maximum value = 65535\n attribute :maxreq\n\n # @return [Boolean, nil] Use the transparent cache redirection virtual server to forward requests to the cache server.,Note: Do not specify this parameter if you set the Cache Type parameter.\n attribute :cacheable\n validates :cacheable, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:enabled, :disabled, nil] Before forwarding a request to the service, insert an HTTP header with the client's IPv4 or IPv6 address as its value. Used if the server needs the client's IP address for security, accounting, or other purposes, and setting the Use Source IP parameter is not a viable option.\n attribute :cip\n validates :cip, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [Object, nil] Name for the HTTP header whose value must be set to the IP address of the client. Used with the Client IP parameter. If you set the Client IP parameter, and you do not specify a name for the header, the appliance uses the header name specified for the global Client IP Header parameter (the cipHeader parameter in the set ns param CLI command or the Client IP Header parameter in the Configure HTTP Parameters dialog box at System > Settings > Change HTTP parameters). If the global Client IP Header parameter is not specified, the appliance inserts a header with the name \"client-ip.\".,Minimum length = 1\n attribute :cipheader\n\n # @return [Object, nil] Use the client's IP address as the source IP address when initiating a connection to the server. When creating a service, if you do not set this parameter, the service inherits the global Use Source IP setting (available in the enable ns mode and disable ns mode CLI commands, or in the System > Settings > Configure modes > Configure Modes dialog box). However, you can override this setting after you create the service.\n attribute :usip\n\n # @return [Object, nil] Path monitoring for clustering.\n attribute :pathmonitor\n\n # @return [Object, nil] Individual Path monitoring decisions.\n attribute :pathmonitorindv\n\n # @return [Object, nil] Use the proxy port as the source port when initiating connections with the server. With the NO setting, the client-side connection port is used as the source port for the server-side connection.,Note: This parameter is available only when the Use Source IP (USIP) parameter is set to YES.\n attribute :useproxyport\n\n # @return [Object, nil] Enable surge protection for the service.\n attribute :sp\n\n # @return [Boolean, nil] Enable RTSP session ID mapping for the service.\n attribute :rtspsessionidremap\n validates :rtspsessionidremap, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] Time, in seconds, after which to terminate an idle client connection.,Minimum value = 0,Maximum value = 31536000\n attribute :clttimeout\n\n # @return [Object, nil] Time, in seconds, after which to terminate an idle server connection.,Minimum value = 0,Maximum value = 31536000\n attribute :svrtimeout\n\n # @return [Object, nil] Unique identifier for the service. Used when the persistency type for the virtual server is set to Custom Server ID.\n attribute :customserverid\n\n # @return [Object, nil] The identifier for the service. This is used when the persistency type is set to Custom Server ID.\n attribute :serverid\n\n # @return [Object, nil] Enable client keep-alive for the service.\n attribute :cka\n\n # @return [Object, nil] Enable TCP buffering for the service.\n attribute :tcpb\n\n # @return [Object, nil] Enable compression for the service.\n attribute :cmp\n\n # @return [Object, nil] Maximum bandwidth, in Kbps, allocated to the service.,Minimum value = 0,Maximum value = 4294967287\n attribute :maxbandwidth\n\n # @return [Boolean, nil] Use Layer 2 mode to bridge the packets sent to this service if it is marked as DOWN. If the service is DOWN, and this parameter is disabled, the packets are dropped.\n attribute :accessdown\n validates :accessdown, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] Minimum sum of weights of the monitors that are bound to this service. Used to determine whether to mark a service as UP or DOWN.,Minimum value = 0,Maximum value = 65535\n attribute :monthreshold\n\n # @return [:enabled, :disabled, nil] Flush all active transactions associated with a service whose state transitions from UP to DOWN. Do not enable this option for applications that must complete their transactions.\n attribute :downstateflush\n validates :downstateflush, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [Object, nil] Name of the TCP profile that contains TCP configuration settings for the service.,Minimum length = 1,Maximum length = 127\n attribute :tcpprofilename\n\n # @return [Object, nil] Name of the HTTP profile that contains HTTP configuration settings for the service.,Minimum length = 1,Maximum length = 127\n attribute :httpprofilename\n\n # @return [Object, nil] A numerical identifier that can be used by hash based load balancing methods. Must be unique for each service.,Minimum value = 1\n attribute :hashid\n\n # @return [Object, nil] Any information about the service.\n attribute :comment\n\n # @return [:enabled, :disabled, nil] Enable logging of AppFlow information.\n attribute :appflowlog\n validates :appflowlog, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [Object, nil] Network profile to use for the service.,Minimum length = 1,Maximum length = 127\n attribute :netprofile\n\n # @return [Object, nil] Integer value that uniquely identifies the traffic domain in which you want to configure the entity. If you do not specify an ID, the entity becomes part of the default traffic domain, which has an ID of 0.,Minimum value = 0,Maximum value = 4094\n attribute :td\n\n # @return [:enabled, :disabled, nil] By turning on this option packets destined to a service in a cluster will not under go any steering. Turn this option for single packet request response mode or when the upstream device is performing a proper RSS for connection based distribution.\n attribute :processlocal\n validates :processlocal, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [Object, nil] Name of the DNS profile to be associated with the service. DNS profile properties will applied to the transactions processed by a service. This parameter is valid only for ADNS and ADNS-TCP services.,Minimum length = 1,Maximum length = 127\n attribute :dnsprofilename\n\n # @return [String, nil] The new IP address of the service.\n attribute :ipaddress\n validates :ipaddress, type: String\n\n # @return [Boolean, nil] Shut down gracefully, not accepting any new connections, and disabling the service when all of its connections are closed.\n attribute :graceful\n validates :graceful, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] A list of load balancing monitors to bind to this service.,Each monitor entry is a dictionary which may contain the following options.,Note that if not using the built in monitors they must first be setup.\n attribute :monitor_bindings\n validates :monitor_bindings, type: TypeGeneric.new(String)\n\n # @return [Symbol, nil] When set to C(yes) the service state will be set to DISABLED.,When set to C(no) the service state will be set to ENABLED.,Note that due to limitations of the underlying NITRO API a C(disabled) state change alone does not cause the module result to report a changed status.\n attribute :disabled\n validates :disabled, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7147960662841797, "alphanum_fraction": 0.7200059294700623, "avg_line_length": 91.02739715576172, "blob_id": "0b499828818e23d7471e197bed1cf303c7c6da94", "content_id": "11e24d18fae40a74527b3192b873bee0d27392a1", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6718, "license_type": "permissive", "max_line_length": 790, "num_lines": 73, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_node.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages F5 BIG-IP LTM nodes.\n class Bigip_node < Base\n # @return [:present, :absent, :enabled, :disabled, :offline, nil] Specifies the current state of the node. C(enabled) (All traffic allowed), specifies that system sends traffic to this node regardless of the node's state. C(disabled) (Only persistent or active connections allowed), Specifies that the node can handle only persistent or active connections. C(offline) (Only active connections allowed), Specifies that the node can handle only active connections. In all cases except C(absent), the node will be created if it does not yet exist.,Be particularly careful about changing the status of a node whose FQDN cannot be resolved. These situations disable your ability to change their C(state) to C(disabled) or C(offline). They will remain in an *Unavailable - Enabled* state.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :enabled, :disabled, :offline], :message=>\"%{value} needs to be :present, :absent, :enabled, :disabled, :offline\"}, allow_nil: true\n\n # @return [String] Specifies the name of the node.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:and_list, :m_of_n, :single, nil] Monitor rule type when C(monitors) is specified. When creating a new pool, if this value is not specified, the default of 'and_list' will be used.,Both C(single) and C(and_list) are functionally identical since BIG-IP considers all monitors as \"a list\". BIG=IP either has a list of many, or it has a list of one. Where they differ is in the extra guards that C(single) provides; namely that it only allows a single monitor.\n attribute :monitor_type\n validates :monitor_type, expression_inclusion: {:in=>[:and_list, :m_of_n, :single], :message=>\"%{value} needs to be :and_list, :m_of_n, :single\"}, allow_nil: true\n\n # @return [Object, nil] Monitor quorum value when C(monitor_type) is C(m_of_n).\n attribute :quorum\n\n # @return [Array<String>, String, nil] Specifies the health monitors that the system currently uses to monitor this node.\n attribute :monitors\n validates :monitors, type: TypeGeneric.new(String)\n\n # @return [Object, nil] IP address of the node. This can be either IPv4 or IPv6. When creating a new node, one of either C(address) or C(fqdn) must be provided. This parameter cannot be updated after it is set.\n attribute :address\n\n # @return [String, nil] FQDN name of the node. This can be any name that is a valid RFC 1123 DNS name. Therefore, the only characters that can be used are \"A\" to \"Z\", \"a\" to \"z\", \"0\" to \"9\", the hyphen (\"-\") and the period (\".\").,FQDN names must include at lease one period; delineating the host from the domain. ex. C(host.domain).,FQDN names must end with a letter or a number.,When creating a new node, one of either C(address) or C(fqdn) must be provided. This parameter cannot be updated after it is set.\n attribute :fqdn\n validates :fqdn, type: String\n\n # @return [:ipv4, :ipv6, :all, nil] Specifies whether the FQDN of the node resolves to an IPv4 or IPv6 address.,When creating a new node, if this parameter is not specified and C(fqdn) is specified, this parameter will default to C(ipv4).,This parameter cannot be changed after it has been set.\n attribute :fqdn_address_type\n validates :fqdn_address_type, expression_inclusion: {:in=>[:ipv4, :ipv6, :all], :message=>\"%{value} needs to be :ipv4, :ipv6, :all\"}, allow_nil: true\n\n # @return [Symbol, nil] Specifies whether the system automatically creates ephemeral nodes using the IP addresses returned by the resolution of a DNS query for a node defined by an FQDN.,When C(yes), the system generates an ephemeral node for each IP address returned in response to a DNS query for the FQDN of the node. Additionally, when a DNS response indicates the IP address of an ephemeral node no longer exists, the system deletes the ephemeral node.,When C(no), the system resolves a DNS query for the FQDN of the node with the single IP address associated with the FQDN.,When creating a new node, if this parameter is not specified and C(fqdn) is specified, this parameter will default to C(yes).,This parameter cannot be changed after it has been set.\n attribute :fqdn_auto_populate\n validates :fqdn_auto_populate, type: Symbol\n\n # @return [Object, nil] Specifies the interval in which a query occurs, when the DNS server is up. The associated monitor attempts to probe three times, and marks the server down if it there is no response within the span of three times the interval value, in seconds.,This parameter accepts a value of C(ttl) to query based off of the TTL of the FQDN. The default TTL interval is akin to specifying C(3600).,When creating a new node, if this parameter is not specified and C(fqdn) is specified, this parameter will default to C(3600).\n attribute :fqdn_up_interval\n\n # @return [Object, nil] Specifies the interval in which a query occurs, when the DNS server is down. The associated monitor continues polling as long as the DNS server is down.,When creating a new node, if this parameter is not specified and C(fqdn) is specified, this parameter will default to C(5).\n attribute :fqdn_down_interval\n\n # @return [String, nil] Specifies descriptive text that identifies the node.,You can remove a description by either specifying an empty string, or by specifying the special value C(none).\n attribute :description\n validates :description, type: String\n\n # @return [Object, nil] Node connection limit. Setting this to 0 disables the limit.\n attribute :connection_limit\n\n # @return [Object, nil] Node rate limit (connections-per-second). Setting this to 0 disables the limit.\n attribute :rate_limit\n\n # @return [Object, nil] Node ratio weight. Valid values range from 1 through 100.,When creating a new node, if this parameter is not specified, the default of C(1) will be used.\n attribute :ratio\n\n # @return [Object, nil] The dynamic ratio number for the node. Used for dynamic ratio load balancing.,When creating a new node, if this parameter is not specified, the default of C(1) will be used.\n attribute :dynamic_ratio\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6940298676490784, "alphanum_fraction": 0.6940298676490784, "avg_line_length": 30.52941131591797, "blob_id": "81d8b3f0a421416b8642f3ccb77598eb282446e9", "content_id": "9102876ac2368d797412dad25c6574bf3520bf58", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 536, "license_type": "permissive", "max_line_length": 105, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/cloudwatchlogs_log_group_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Lists the specified log groups. You can list all your log groups or filter the results by prefix.\n class Cloudwatchlogs_log_group_facts < Base\n # @return [String, nil] The name or prefix of the log group to filter by.\n attribute :log_group_name\n validates :log_group_name, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6822066903114319, "alphanum_fraction": 0.6822066903114319, "avg_line_length": 38, "blob_id": "5a9520c417217f03cc0bd46e9540b9e9008abd0d", "content_id": "9e73107b8f58ad51235b92221aefeb8ba20a0ed3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1287, "license_type": "permissive", "max_line_length": 149, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/cloud/digital_ocean/digital_ocean_certificate.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, Retrieve and remove certificates DigitalOcean.\n class Digital_ocean_certificate < Base\n # @return [String] The name of the certificate.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] A PEM-formatted private key content of SSL Certificate.\n attribute :private_key\n validates :private_key, type: String\n\n # @return [String, nil] A PEM-formatted public SSL Certificate.\n attribute :leaf_certificate\n validates :leaf_certificate, type: String\n\n # @return [String, nil] The full PEM-formatted trust chain between the certificate authority's certificate and your domain's SSL certificate.\n attribute :certificate_chain\n validates :certificate_chain, type: String\n\n # @return [:present, :absent, nil] Whether the certificate should be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.706135630607605, "alphanum_fraction": 0.706135630607605, "avg_line_length": 45.45000076293945, "blob_id": "5a75bda9357e1b8c9ad5c2c14aaa6d5099480a57", "content_id": "c721889d50206dd9896748e2011e71b3df2c75e9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 929, "license_type": "permissive", "max_line_length": 238, "num_lines": 20, "path": "/lib/ansible/ruby/modules/generated/system/ping.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # A trivial test module, this module always returns C(pong) on successful contact. It does not make sense in playbooks, but it is useful from C(/usr/bin/ansible) to verify the ability to login and that a usable Python is configured.\n # This is NOT ICMP ping, this is just a trivial test module that requires Python on the remote-node.\n # For Windows targets, use the M(win_ping) module instead.\n # For Network targets, use the M(net_ping) module instead.\n class Ping < Base\n # @return [String, nil] Data to return for the C(ping) return value.,If this parameter is set to C(crash), the module will cause an exception.\n attribute :data\n validates :data, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7016689777374268, "alphanum_fraction": 0.7051460146903992, "avg_line_length": 48.58620834350586, "blob_id": "32f29f792fb8a100d7f19e5ab9a59d6a77f747af", "content_id": "e37f7b8ff72e0e74984c25d53c06ac361fad6708", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1438, "license_type": "permissive", "max_line_length": 459, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_virtualmachine_scaleset_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Get facts for a virtual machine scale set\n class Azure_rm_virtualmachine_scaleset_facts < Base\n # @return [String, nil] Limit results to a specific virtual machine scale set\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] The resource group to search for the desired virtual machine scale set\n attribute :resource_group\n validates :resource_group, type: String\n\n # @return [Array<String>, String, nil] List of tags to be matched\n attribute :tags\n validates :tags, type: TypeGeneric.new(String)\n\n # @return [:curated, :raw, nil] Format of the data returned.,If C(raw) is selected information will be returned in raw format from Azure Python SDK.,If C(curated) is selected the structure will be identical to input parameters of azure_rm_virtualmachine_scaleset module.,In Ansible 2.5 and lower facts are always returned in raw format.,Please note that this option will be deprecated in 2.10 when curated format will become the only supported format.\n attribute :format\n validates :format, expression_inclusion: {:in=>[:curated, :raw], :message=>\"%{value} needs to be :curated, :raw\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6749647855758667, "alphanum_fraction": 0.6759041547775269, "avg_line_length": 56.5405387878418, "blob_id": "8a268f86a9410633bcc8c5123225366a263dafde", "content_id": "235c5abf75690b3547822d26454337333a5ff2b9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2129, "license_type": "permissive", "max_line_length": 397, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/cloud/misc/virt_net.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage I(libvirt) networks.\n class Virt_net < Base\n # @return [String] name of the network being managed. Note that network must be previously defined with xml.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:active, :inactive, :present, :absent, nil] specify which state you want a network to be in. If 'active', network will be started. If 'present', ensure that network is present but do not change its state; if it's missing, you need to specify xml argument. If 'inactive', network will be stopped. If 'undefined' or 'absent', network will be removed from I(libvirt) configuration.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:active, :inactive, :present, :absent], :message=>\"%{value} needs to be :active, :inactive, :present, :absent\"}, allow_nil: true\n\n # @return [:define, :create, :start, :stop, :destroy, :undefine, :get_xml, :list_nets, :facts, :info, :status, :modify, nil] in addition to state management, various non-idempotent commands are available. See examples. Modify was added in version 2.1\n attribute :command\n validates :command, expression_inclusion: {:in=>[:define, :create, :start, :stop, :destroy, :undefine, :get_xml, :list_nets, :facts, :info, :status, :modify], :message=>\"%{value} needs to be :define, :create, :start, :stop, :destroy, :undefine, :get_xml, :list_nets, :facts, :info, :status, :modify\"}, allow_nil: true\n\n # @return [Symbol, nil] Specify if a given network should be started automatically on system boot.\n attribute :autostart\n validates :autostart, type: Symbol\n\n # @return [String, nil] libvirt connection uri.\n attribute :uri\n validates :uri, type: String\n\n # @return [String, nil] XML document used with the define command.\n attribute :xml\n validates :xml, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6855196952819824, "alphanum_fraction": 0.6861119270324707, "avg_line_length": 47.9420280456543, "blob_id": "d1fb1fed8decd94b6cf94353a74cc82899039b4a", "content_id": "774c3daf2a716987608e16acdd96727e52811c75", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3377, "license_type": "permissive", "max_line_length": 246, "num_lines": 69, "path": "/lib/ansible/ruby/modules/generated/packaging/language/composer.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Composer is a tool for dependency management in PHP. It allows you to declare the dependent libraries your project needs and it will install them in your project for you.\n\n class Composer < Base\n # @return [String, nil] Composer command like \"install\", \"update\" and so on.\n attribute :command\n validates :command, type: String\n\n # @return [String, nil] Composer arguments like required package, version and so on.\n attribute :arguments\n validates :arguments, type: String\n\n # @return [Object, nil] Path to PHP Executable on the remote host, if PHP is not in PATH.\n attribute :executable\n\n # @return [String, nil] Directory of your project (see --working-dir). This is required when the command is not run globally.,Will be ignored if C(global_command=true).\n attribute :working_dir\n validates :working_dir, type: String\n\n # @return [Symbol, nil] Runs the specified command globally.\n attribute :global_command\n validates :global_command, type: Symbol\n\n # @return [Symbol, nil] Forces installation from package sources when possible (see --prefer-source).\n attribute :prefer_source\n validates :prefer_source, type: Symbol\n\n # @return [Symbol, nil] Forces installation from package dist even for dev versions (see --prefer-dist).\n attribute :prefer_dist\n validates :prefer_dist, type: Symbol\n\n # @return [Boolean, nil] Disables installation of require-dev packages (see --no-dev).\n attribute :no_dev\n validates :no_dev, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Symbol, nil] Skips the execution of all scripts defined in composer.json (see --no-scripts).\n attribute :no_scripts\n validates :no_scripts, type: Symbol\n\n # @return [Symbol, nil] Disables all plugins ( see --no-plugins ).\n attribute :no_plugins\n validates :no_plugins, type: Symbol\n\n # @return [Boolean, nil] Optimize autoloader during autoloader dump (see --optimize-autoloader).,Convert PSR-0/4 autoloading to classmap to get a faster autoloader.,Recommended especially for production, but can take a bit of time to run.\n attribute :optimize_autoloader\n validates :optimize_autoloader, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Symbol, nil] Autoload classes from classmap only.,Implicitely enable optimize_autoloader.,Recommended especially for production, but can take a bit of time to run.\n attribute :classmap_authoritative\n validates :classmap_authoritative, type: Symbol\n\n # @return [Symbol, nil] Uses APCu to cache found/not-found classes\n attribute :apcu_autoloader\n validates :apcu_autoloader, type: Symbol\n\n # @return [Symbol, nil] Ignore php, hhvm, lib-* and ext-* requirements and force the installation even if the local machine does not fulfill these.\n attribute :ignore_platform_reqs\n validates :ignore_platform_reqs, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6726832389831543, "alphanum_fraction": 0.6740039587020874, "avg_line_length": 55.08641815185547, "blob_id": "e301a85fdd64f14e928b58bcc6c03fab621f33f5", "content_id": "cc3790564da752d24b5c6fdc109b0b5e4812f7cc", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4543, "license_type": "permissive", "max_line_length": 226, "num_lines": 81, "path": "/lib/ansible/ruby/modules/generated/network/netvisor/pn_vrouter.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Execute vrouter-create, vrouter-delete, vrouter-modify command.\n # Each fabric, cluster, standalone switch, or virtual network (VNET) can provide its tenants with a virtual router (vRouter) service that forwards traffic between networks and implements Layer 3 protocols.\n # C(vrouter-create) creates a new vRouter service.\n # C(vrouter-delete) deletes a vRouter service.\n # C(vrouter-modify) modifies a vRouter service.\n class Pn_vrouter < Base\n # @return [Object, nil] Provide login username if user is not root.\n attribute :pn_cliusername\n\n # @return [Object, nil] Provide login password if user is not root.\n attribute :pn_clipassword\n\n # @return [Object, nil] Target switch(es) to run the CLI on.\n attribute :pn_cliswitch\n\n # @return [:present, :absent, :update] State the action to perform. Use 'present' to create vrouter, 'absent' to delete vrouter and 'update' to modify vrouter.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent, :update], :message=>\"%{value} needs to be :present, :absent, :update\"}\n\n # @return [String] Specify the name of the vRouter.\n attribute :pn_name\n validates :pn_name, presence: true, type: String\n\n # @return [String, nil] Specify the name of the VNET.,Required for vrouter-create.\n attribute :pn_vnet\n validates :pn_vnet, type: String\n\n # @return [:dedicated, :shared, nil] Specify if the vRouter is a dedicated or shared VNET service.\n attribute :pn_service_type\n validates :pn_service_type, expression_inclusion: {:in=>[:dedicated, :shared], :message=>\"%{value} needs to be :dedicated, :shared\"}, allow_nil: true\n\n # @return [:enable, :disable, nil] Specify to enable or disable vRouter service.\n attribute :pn_service_state\n validates :pn_service_state, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:hardware, :software, nil] Specify if the vRouter uses software or hardware.,Note that if you specify hardware as router type, you cannot assign IP addresses using DHCP. You must specify a static IP address.\n attribute :pn_router_type\n validates :pn_router_type, expression_inclusion: {:in=>[:hardware, :software], :message=>\"%{value} needs to be :hardware, :software\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the VRRP ID for a hardware vrouter.\n attribute :pn_hw_vrrp_id\n\n # @return [String, nil] Specify the vRouter IP address.\n attribute :pn_router_id\n validates :pn_router_id, type: String\n\n # @return [Object, nil] Specify the Autonomous System Number(ASN) if the vRouter runs Border Gateway Protocol(BGP).\n attribute :pn_bgp_as\n\n # @return [:static, :connected, :rip, :ospf, nil] Specify how BGP routes are redistributed.\n attribute :pn_bgp_redistribute\n validates :pn_bgp_redistribute, expression_inclusion: {:in=>[:static, :connected, :rip, :ospf], :message=>\"%{value} needs to be :static, :connected, :rip, :ospf\"}, allow_nil: true\n\n # @return [Object, nil] Specify the maximum number of paths for BGP. This is a number between 1 and 255 or 0 to unset.\n attribute :pn_bgp_max_paths\n\n # @return [Object, nil] Specify other BGP options as a whitespaces separated string within single quotes ''.\n attribute :pn_bgp_options\n\n # @return [:static, :connected, :ospf, :bgp, nil] Specify how RIP routes are redistributed.\n attribute :pn_rip_redistribute\n validates :pn_rip_redistribute, expression_inclusion: {:in=>[:static, :connected, :ospf, :bgp], :message=>\"%{value} needs to be :static, :connected, :ospf, :bgp\"}, allow_nil: true\n\n # @return [:static, :connected, :bgp, :rip, nil] Specify how OSPF routes are redistributed.\n attribute :pn_ospf_redistribute\n validates :pn_ospf_redistribute, expression_inclusion: {:in=>[:static, :connected, :bgp, :rip], :message=>\"%{value} needs to be :static, :connected, :bgp, :rip\"}, allow_nil: true\n\n # @return [Object, nil] Specify other OSPF options as a whitespaces separated string within single quotes ''.\n attribute :pn_ospf_options\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6453551650047302, "alphanum_fraction": 0.6453551650047302, "avg_line_length": 37.9361686706543, "blob_id": "61e98afb3027a4fbae9306f8afaa389792d3e214", "content_id": "fae205a658b1bccd9c7d8b3825df630d8a59a2d1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1830, "license_type": "permissive", "max_line_length": 167, "num_lines": 47, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_nic.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add and remove secondary IPs to and from a NIC.\n class Cs_nic < Base\n # @return [String] Name of instance.\n attribute :vm\n validates :vm, presence: true, type: String\n\n # @return [Object, nil] Name of the network.,Required to find the NIC if instance has multiple networks assigned.\n attribute :network\n\n # @return [String, nil] Secondary IP address to be added to the instance nic.,If not set, the API always returns a new IP address and idempotency is not given.\n attribute :vm_guest_ip\n validates :vm_guest_ip, type: String\n\n # @return [Object, nil] Name of the VPC the C(vm) is related to.\n attribute :vpc\n\n # @return [Object, nil] Domain the instance is related to.\n attribute :domain\n\n # @return [Object, nil] Account the instance is related to.\n attribute :account\n\n # @return [Object, nil] Name of the project the instance is deployed in.\n attribute :project\n\n # @return [Object, nil] Name of the zone in which the instance is deployed in.,If not set, default zone is used.\n attribute :zone\n\n # @return [:absent, :present, nil] State of the ipaddress.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Poll async jobs until job has finished.\n attribute :poll_async\n validates :poll_async, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6635906100273132, "alphanum_fraction": 0.6635906100273132, "avg_line_length": 40.10344696044922, "blob_id": "a5bcb62897d201766944b73b7a98aa9f4320b233", "content_id": "c21647eea50bbea6c7698dd5842eadc076778f99", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1192, "license_type": "permissive", "max_line_length": 143, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_motd.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows you to manipulate motd on cDOT\n class Na_ontap_motd < Base\n # @return [:present, :absent, nil] If C(state=present) sets MOTD given in I(message) C(state=absent) removes it.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] MOTD Text message, required when C(state=present).\n attribute :message\n validates :message, type: String\n\n # @return [String] The name of the SVM motd should be set for.\n attribute :vserver\n validates :vserver, presence: true, type: String\n\n # @return [Boolean, nil] Set to I(false) if Cluster-level Message of the Day should not be shown\n attribute :show_cluster_motd\n validates :show_cluster_motd, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6932440400123596, "alphanum_fraction": 0.6962872743606567, "avg_line_length": 73.68181610107422, "blob_id": "1eda322bd917fe3f926a5d40a1ca735ad2f2f5c7", "content_id": "7f455364060870b0119064efb7e72f4755fcfdaf", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3286, "license_type": "permissive", "max_line_length": 426, "num_lines": 44, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_gtm_wide_ip.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages F5 BIG-IP GTM wide ip.\n class Bigip_gtm_wide_ip < Base\n # @return [:\"round-robin\", :ratio, :topology, :\"global-availability\", :global_availability, :round_robin] Specifies the load balancing method used to select a pool in this wide IP. This setting is relevant only when multiple pools are configured for a wide IP.,The C(round_robin) value is deprecated and will be removed in Ansible 2.9.,The C(global_availability) value is deprecated and will be removed in Ansible 2.9.\n attribute :pool_lb_method\n validates :pool_lb_method, presence: true, expression_inclusion: {:in=>[:\"round-robin\", :ratio, :topology, :\"global-availability\", :global_availability, :round_robin], :message=>\"%{value} needs to be :\\\"round-robin\\\", :ratio, :topology, :\\\"global-availability\\\", :global_availability, :round_robin\"}\n\n # @return [String] Wide IP name. This name must be formatted as a fully qualified domain name (FQDN). You can also use the alias C(wide_ip) but this is deprecated and will be removed in a future Ansible version.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:a, :aaaa, :cname, :mx, :naptr, :srv, nil] Specifies the type of wide IP. GTM wide IPs need to be keyed by query type in addition to name, since pool members need different attributes depending on the response RDATA they are meant to supply. This value is required if you are using BIG-IP versions >= 12.0.0.\n attribute :type\n validates :type, expression_inclusion: {:in=>[:a, :aaaa, :cname, :mx, :naptr, :srv], :message=>\"%{value} needs to be :a, :aaaa, :cname, :mx, :naptr, :srv\"}, allow_nil: true\n\n # @return [:present, :absent, :disabled, :enabled, nil] When C(present) or C(enabled), ensures that the Wide IP exists and is enabled.,When C(absent), ensures that the Wide IP has been removed.,When C(disabled), ensures that the Wide IP exists and is disabled.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :disabled, :enabled], :message=>\"%{value} needs to be :present, :absent, :disabled, :enabled\"}, allow_nil: true\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [Array<Hash>, Hash, nil] The pools that you want associated with the Wide IP.,If C(ratio) is not provided when creating a new Wide IP, it will default to 1.\n attribute :pools\n validates :pools, type: TypeGeneric.new(Hash)\n\n # @return [Array<String>, String, nil] List of rules to be applied.,If you want to remove all existing iRules, specify a single empty value; C(\"\"). See the documentation for an example.\n attribute :irules\n validates :irules, type: TypeGeneric.new(String)\n\n # @return [Object, nil] Specifies alternate domain names for the web site content you are load balancing.,You can use the same wildcard characters for aliases as you can for actual wide IP names.\n attribute :aliases\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6697207689285278, "alphanum_fraction": 0.6697207689285278, "avg_line_length": 45.775508880615234, "blob_id": "9980eef2c840d45030b16ac214b2c0889e893124", "content_id": "1aaf85b24673c7f5a58d827c8390b26bc2c4d2a2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2292, "license_type": "permissive", "max_line_length": 209, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_cluster.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure Cluster object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_cluster < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [String] Name of the object.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] List of clusternode.\n attribute :nodes\n\n # @return [Symbol, nil] Re-join cluster nodes automatically in the event one of the node is reset to factory.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :rejoin_nodes_automatically\n validates :rejoin_nodes_automatically, type: Symbol\n\n # @return [Object, nil] It is a reference to an object of type tenant.\n attribute :tenant_ref\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Unique object identifier of the object.\n attribute :uuid\n\n # @return [Object, nil] A virtual ip address.,This ip address will be dynamically reconfigured so that it always is the ip of the cluster leader.\n attribute :virtual_ip\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6780432462692261, "alphanum_fraction": 0.6951080560684204, "avg_line_length": 52.81632614135742, "blob_id": "f2ffb8341e3ea645282c1f7e81e6e4cc560aa6f3", "content_id": "6a569c7e00c76dd2070942129e5aebcc488b2353", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2637, "license_type": "permissive", "max_line_length": 177, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_bfd_view.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages BFD session view configuration on HUAWEI CloudEngine devices.\n class Ce_bfd_view < Base\n # @return [Object] Specifies the name of a BFD session. The value is a string of 1 to 15 case-sensitive characters without spaces.\n attribute :session_name\n validates :session_name, presence: true\n\n # @return [Object, nil] Specifies the local discriminator of a BFD session. The value is an integer that ranges from 1 to 16384.\n attribute :local_discr\n\n # @return [Object, nil] Specifies the remote discriminator of a BFD session. The value is an integer that ranges from 1 to 4294967295.\n attribute :remote_discr\n\n # @return [Object, nil] Specifies the minimum interval for receiving BFD packets. The value is an integer that ranges from 50 to 1000, in milliseconds.\n attribute :min_tx_interval\n\n # @return [Object, nil] Specifies the minimum interval for sending BFD packets. The value is an integer that ranges from 50 to 1000, in milliseconds.\n attribute :min_rx_interval\n\n # @return [Object, nil] Specifies the local detection multiplier of a BFD session. The value is an integer that ranges from 3 to 50.\n attribute :detect_multi\n\n # @return [Object, nil] Specifies the WTR time of a BFD session. The value is an integer that ranges from 1 to 60, in minutes. The default value is 0.\n attribute :wtr_interval\n\n # @return [Object, nil] Specifies a priority for BFD control packets. The value is an integer ranging from 0 to 7. The default value is 7, which is the highest priority.\n attribute :tos_exp\n\n # @return [:yes, :no, nil] Enables the BFD session to enter the AdminDown state. By default, a BFD session is enabled. The default value is bool type.\n attribute :admin_down\n validates :admin_down, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the description of a BFD session. The value is a string of 1 to 51 case-sensitive characters with spaces.\n attribute :description\n\n # @return [:present, :absent, nil] Determines whether the config should be present or not on the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6777178049087524, "alphanum_fraction": 0.6842713952064514, "avg_line_length": 53.04166793823242, "blob_id": "578681a742bca820dd39bfe35cd04e5f64a78312", "content_id": "0f64bd74963890c1efd5b8632f1460fa3ff0bb27", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2594, "license_type": "permissive", "max_line_length": 515, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/cloud/lxd/lxd_profile.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Management of LXD profiles\n class Lxd_profile < Base\n # @return [String] Name of a profile.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Description of the profile.\n attribute :description\n\n # @return [Object, nil] The config for the container (e.g. {\"limits.memory\": \"4GB\"}). See U(https://github.com/lxc/lxd/blob/master/doc/rest-api.md#patch-3),If the profile already exists and its \"config\" value in metadata obtained from GET /1.0/profiles/<name> U(https://github.com/lxc/lxd/blob/master/doc/rest-api.md#get-19) are different, they this module tries to apply the configurations.,Not all config values are supported to apply the existing profile. Maybe you need to delete and recreate a profile.\n attribute :config\n\n # @return [Object, nil] The devices for the profile (e.g. {\"rootfs\": {\"path\": \"/dev/kvm\", \"type\": \"unix-char\"}). See U(https://github.com/lxc/lxd/blob/master/doc/rest-api.md#patch-3)\n attribute :devices\n\n # @return [Object, nil] A new name of a profile.,If this parameter is specified a profile will be renamed to this name. See U(https://github.com/lxc/lxd/blob/master/doc/rest-api.md#post-11)\n attribute :new_name\n\n # @return [:present, :absent, nil] Define the state of a profile.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] The unix domain socket path or the https URL for the LXD server.\n attribute :url\n validates :url, type: String\n\n # @return [String, nil] The client certificate key file path.\n attribute :key_file\n validates :key_file, type: String\n\n # @return [String, nil] The client certificate file path.\n attribute :cert_file\n validates :cert_file, type: String\n\n # @return [Object, nil] The client trusted password.,You need to set this password on the LXD server before running this module using the following command. lxc config set core.trust_password <some random password> See U(https://www.stgraber.org/2016/04/18/lxd-api-direct-interaction/),If trust_password is set, this module send a request for authentication before sending any requests.\n attribute :trust_password\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6850393414497375, "alphanum_fraction": 0.6850393414497375, "avg_line_length": 42.65625, "blob_id": "3e7f0a56ca5fb306f933033ad5b2a440c89c6615", "content_id": "701b2c90877833b56cbe1496bff8b372e0e3d36a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1397, "license_type": "permissive", "max_line_length": 160, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/network/vyos/vyos_system.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Runs one or more commands on remote devices running VyOS. This module can also be introspected to validate key parameters before returning successfully.\n class Vyos_system < Base\n # @return [String, nil] Configure the device hostname parameter. This option takes an ASCII string value.\n attribute :host_name\n validates :host_name, type: String\n\n # @return [String, nil] The new domain name to apply to the device.\n attribute :domain_name\n validates :domain_name, type: String\n\n # @return [Object, nil] A list of name servers to use with the device. Mutually exclusive with I(domain_search)\n attribute :name_servers\n\n # @return [Array<String>, String, nil] A list of domain names to search. Mutually exclusive with I(name_server)\n attribute :domain_search\n validates :domain_search, type: TypeGeneric.new(String)\n\n # @return [:present, :absent, nil] Whether to apply (C(present)) or remove (C(absent)) the settings.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6563693284988403, "alphanum_fraction": 0.6563693284988403, "avg_line_length": 48.67241287231445, "blob_id": "6ef738862f3dd86d5cd800988529df5ef79b141e", "content_id": "95d23d66d6f3c2756b5e48045e5e9cb478ca7b79", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2881, "license_type": "permissive", "max_line_length": 444, "num_lines": 58, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/dynamodb_table.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or delete AWS Dynamo DB tables.\n # Can update the provisioned throughput on existing tables.\n # Returns the status of the specified table.\n class Dynamodb_table < Base\n # @return [:present, :absent, nil] Create or delete the table\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] Name of the table.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Name of the hash key.,Required when C(state=present).\n attribute :hash_key_name\n validates :hash_key_name, type: String\n\n # @return [:STRING, :NUMBER, :BINARY, nil] Type of the hash key.\n attribute :hash_key_type\n validates :hash_key_type, expression_inclusion: {:in=>[:STRING, :NUMBER, :BINARY], :message=>\"%{value} needs to be :STRING, :NUMBER, :BINARY\"}, allow_nil: true\n\n # @return [String, nil] Name of the range key.\n attribute :range_key_name\n validates :range_key_name, type: String\n\n # @return [:STRING, :NUMBER, :BINARY, nil] Type of the range key.\n attribute :range_key_type\n validates :range_key_type, expression_inclusion: {:in=>[:STRING, :NUMBER, :BINARY], :message=>\"%{value} needs to be :STRING, :NUMBER, :BINARY\"}, allow_nil: true\n\n # @return [Integer, nil] Read throughput capacity (units) to provision.\n attribute :read_capacity\n validates :read_capacity, type: Integer\n\n # @return [Integer, nil] Write throughput capacity (units) to provision.\n attribute :write_capacity\n validates :write_capacity, type: Integer\n\n # @return [Object, nil] list of dictionaries describing indexes to add to the table. global indexes can be updated. local indexes don't support updates or have throughput.,required options: ['name', 'type', 'hash_key_name'],valid types: ['all', 'global_all', 'global_include', 'global_keys_only', 'include', 'keys_only'],other options: ['hash_key_type', 'range_key_name', 'range_key_type', 'includes', 'read_capacity', 'write_capacity']\n attribute :indexes\n\n # @return [Hash, nil] a hash/dictionary of tags to add to the new instance or for starting/stopping instance by tag; '{\"key\":\"value\"}' and '{\"key\":\"value\",\"key\":\"value\"}'\n attribute :tags\n validates :tags, type: Hash\n\n # @return [Integer, nil] how long before wait gives up, in seconds. only used when tags is set\n attribute :wait_for_active_timeout\n validates :wait_for_active_timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.702342689037323, "alphanum_fraction": 0.7032613754272461, "avg_line_length": 52.09756088256836, "blob_id": "b38040d700cb027f77c0f90efe15184aff9407c3", "content_id": "bdd7b3636c052b7e6fc54ee3b647b9f1565bc025", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2177, "license_type": "permissive", "max_line_length": 268, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/netapp_e_alerts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Certain E-Series systems have the capability to send email notifications on potentially critical events.\n # This module will allow the owner of the system to specify email recipients for these messages.\n class Netapp_e_alerts < Base\n # @return [:enabled, :disabled, nil] Enable/disable the sending of email-based alerts.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [String, nil] A fully qualified domain name, IPv4 address, or IPv6 address of a mail server.,To use a fully qualified domain name, you must configure a DNS server on both controllers using M(netapp_e_mgmt_interface). - Required when I(state=enabled).\n attribute :server\n validates :server, type: String\n\n # @return [String, nil] This is the sender that the recipient will see. It doesn't necessarily need to be a valid email account.,Required when I(state=enabled).\n attribute :sender\n validates :sender, type: String\n\n # @return [String, nil] Allows the owner to specify some free-form contact information to be included in the emails.,This is typically utilized to provide a contact phone number.\n attribute :contact\n validates :contact, type: String\n\n # @return [Array<String>, String, nil] The email addresses that will receive the email notifications.,Required when I(state=enabled).\n attribute :recipients\n validates :recipients, type: TypeGeneric.new(String)\n\n # @return [Symbol, nil] When a change is detected in the configuration, a test email will be sent.,This may take a few minutes to process.,Only applicable if I(state=enabled).\n attribute :test\n validates :test, type: Symbol\n\n # @return [Object, nil] Path to a file on the Ansible control node to be used for debug logging\n attribute :log_path\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6865234375, "alphanum_fraction": 0.6865234375, "avg_line_length": 38.38461685180664, "blob_id": "929821b8be3cf82c348fa828608ec66aad7830d8", "content_id": "34040cf778e463d896be6c655aba792fbbaf94fb", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1024, "license_type": "permissive", "max_line_length": 143, "num_lines": 26, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_datastore_cluster.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to add and delete datastore cluster in given VMware environment.\n # All parameters and VMware object values are case sensitive.\n class Vmware_datastore_cluster < Base\n # @return [String] The name of the datacenter.\n attribute :datacenter_name\n validates :datacenter_name, presence: true, type: String\n\n # @return [String] The name of the datastore cluster.\n attribute :datastore_cluster_name\n validates :datastore_cluster_name, presence: true, type: String\n\n # @return [:present, :absent, nil] If the datastore cluster should be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7356321811676025, "alphanum_fraction": 0.7442528605461121, "avg_line_length": 19.47058868408203, "blob_id": "83d1b4f9571e14485a924bdc80863c7976151735", "content_id": "3ae1a81668c9059993cbb6ebc5feebb0d9e61af2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 348, "license_type": "permissive", "max_line_length": 66, "num_lines": 17, "path": "/lib/ansible/ruby/modules/custom/commands/script.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# VALIDATED_CHECKSUM: 7xG8FK2+LyCSviFhSMMarZshnWdQ/FipZRLvXbtOJhc=\n# See LICENSE.txt for license\n\nrequire 'ansible/ruby/modules/free_form'\nrequire 'ansible/ruby/modules/generated/commands/script'\n\nmodule Ansible\n module Ruby\n module Modules\n class Script\n include FreeForm\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6862319111824036, "alphanum_fraction": 0.6887680888175964, "avg_line_length": 52.07692337036133, "blob_id": "e91c67c51b65b98140cacf92ee5bb020b76c06c8", "content_id": "f4bb5d6f9201e9667e65210852e87403adcda056", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2760, "license_type": "permissive", "max_line_length": 620, "num_lines": 52, "path": "/lib/ansible/ruby/modules/generated/database/postgresql/postgresql_db.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove PostgreSQL databases from a remote host.\n class Postgresql_db < Base\n # @return [String] name of the database to add or remove\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Name of the role to set as owner of the database\n attribute :owner\n\n # @return [String, nil] Template used to create the database\n attribute :template\n validates :template, type: String\n\n # @return [String, nil] Encoding of the database\n attribute :encoding\n validates :encoding, type: String\n\n # @return [String, nil] Collation order (LC_COLLATE) to use in the database. Must match collation order of template database unless C(template0) is used as template.\n attribute :lc_collate\n validates :lc_collate, type: String\n\n # @return [String, nil] Character classification (LC_CTYPE) to use in the database (e.g. lower, upper, ...) Must match LC_CTYPE of template database unless C(template0) is used as template.\n attribute :lc_ctype\n validates :lc_ctype, type: String\n\n # @return [:present, :absent, :dump, :restore, nil] The database state. present implies that the database should be created if necessary.\\r\\nabsent implies that the database should be removed if present.\\r\\ndump requires a target definition to which the database will be backed up.\\r\\n(Added in 2.4) restore also requires a target definition from which the database will be restored.\\r\\n(Added in 2.4) The format of the backup will be detected based on the target name.\\r\\nSupported compression formats for dump and restore are: .bz2, .gz, and .xz\\r\\nSupported formats for dump and restore are: .sql and .tar\\r\\n\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :dump, :restore], :message=>\"%{value} needs to be :present, :absent, :dump, :restore\"}, allow_nil: true\n\n # @return [String, nil] File to back up or restore from. Used when state is \"dump\" or \"restore\"\n attribute :target\n validates :target, type: String\n\n # @return [String, nil] Further arguments for pg_dump or pg_restore. Used when state is \"dump\" or \"restore\"\n attribute :target_opts\n validates :target_opts, type: String\n\n # @return [String, nil] The value specifies the initial database (which is also called as maintenance DB) that Ansible connects to.\n attribute :maintenance_db\n validates :maintenance_db, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6694473624229431, "alphanum_fraction": 0.6885644793510437, "avg_line_length": 53.28302001953125, "blob_id": "09ce65f0ddad2f03099ffb8e6b27846ab08543c2", "content_id": "97cea61229e26222b46e461c3f3a7cb80fd85efc", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2877, "license_type": "permissive", "max_line_length": 207, "num_lines": 53, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_tenant_ep_retention_policy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage End Point (EP) retention protocol policies on Cisco ACI fabrics.\n class Aci_tenant_ep_retention_policy < Base\n # @return [String, nil] The name of an existing tenant.\n attribute :tenant\n validates :tenant, type: String\n\n # @return [String, nil] The name of the end point retention policy.\n attribute :epr_policy\n validates :epr_policy, type: String\n\n # @return [Integer, nil] Bounce entry aging interval in seconds.,Accepted values range between C(150) and C(65535); 0 is used for infinite.,The APIC defaults to C(630) when unset during creation.\n attribute :bounce_age\n validates :bounce_age, type: Integer\n\n # @return [:coop, :flood, nil] Determines if the bounce entries are installed by RARP Flood or COOP Protocol.,The APIC defaults to C(coop) when unset during creation.\n attribute :bounce_trigger\n validates :bounce_trigger, expression_inclusion: {:in=>[:coop, :flood], :message=>\"%{value} needs to be :coop, :flood\"}, allow_nil: true\n\n # @return [Integer, nil] Hold interval in seconds.,Accepted values range between C(5) and C(65535).,The APIC defaults to C(300) when unset during creation.\n attribute :hold_interval\n validates :hold_interval, type: Integer\n\n # @return [Integer, nil] Local end point aging interval in seconds.,Accepted values range between C(120) and C(65535); 0 is used for infinite.,The APIC defaults to C(900) when unset during creation.\n attribute :local_ep_interval\n validates :local_ep_interval, type: Integer\n\n # @return [Integer, nil] Remote end point aging interval in seconds.,Accepted values range between C(120) and C(65535); 0 is used for infinite.,The APIC defaults to C(300) when unset during creation.\n attribute :remote_ep_interval\n validates :remote_ep_interval, type: Integer\n\n # @return [Integer, nil] Move frequency per second.,Accepted values range between C(0) and C(65535); 0 is used for none.,The APIC defaults to C(256) when unset during creation.\n attribute :move_frequency\n validates :move_frequency, type: Integer\n\n # @return [String, nil] Description for the End point rentention policy.\n attribute :description\n validates :description, type: String\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6986506581306458, "alphanum_fraction": 0.6986506581306458, "avg_line_length": 52.36000061035156, "blob_id": "8c18ebbe0a14c10cd45341264ef95d4e3838d37a", "content_id": "d662e9da9c23486d972662d601cf73f13d3f24a1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1334, "license_type": "permissive", "max_line_length": 204, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/network/vyos/vyos_banner.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This will configure both pre-login and post-login banners on remote devices running VyOS. It allows playbooks to add or remote banner text from the active running configuration.\n class Vyos_banner < Base\n # @return [:\"pre-login\", :\"post-login\"] Specifies which banner that should be configured on the remote device.\n attribute :banner\n validates :banner, presence: true, expression_inclusion: {:in=>[:\"pre-login\", :\"post-login\"], :message=>\"%{value} needs to be :\\\"pre-login\\\", :\\\"post-login\\\"\"}\n\n # @return [String, nil] The banner text that should be present in the remote device running configuration. This argument accepts a multiline string, with no empty lines. Requires I(state=present).\n attribute :text\n validates :text, type: String\n\n # @return [:present, :absent, nil] Specifies whether or not the configuration is present in the current devices active running configuration.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7046821117401123, "alphanum_fraction": 0.7079038023948669, "avg_line_length": 70.63076782226562, "blob_id": "e7f11d85b6e73d42f1e74760e3ec0660f6ab828c", "content_id": "6df527b43cde9b9e1f0d65ab0d22d86b6a16040b", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4656, "license_type": "permissive", "max_line_length": 769, "num_lines": 65, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_guest_snapshot.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to create, delete and update snapshot(s) of the given virtual machine.\n # All parameters and VMware object names are case sensitive.\n class Vmware_guest_snapshot < Base\n # @return [:present, :absent, :revert, :remove_all] Manage snapshot(s) attached to a specific virtual machine.,If set to C(present) and snapshot absent, then will create a new snapshot with the given name.,If set to C(present) and snapshot present, then no changes are made.,If set to C(absent) and snapshot present, then snapshot with the given name is removed.,If set to C(absent) and snapshot absent, then no changes are made.,If set to C(revert) and snapshot present, then virtual machine state is reverted to the given snapshot.,If set to C(revert) and snapshot absent, then no changes are made.,If set to C(remove_all) and snapshot(s) present, then all snapshot(s) will be removed.,If set to C(remove_all) and snapshot(s) absent, then no changes are made.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent, :revert, :remove_all], :message=>\"%{value} needs to be :present, :absent, :revert, :remove_all\"}\n\n # @return [String, nil] Name of the virtual machine to work with.,This is required parameter, if C(uuid) is not supplied.\n attribute :name\n validates :name, type: String\n\n # @return [:first, :last, nil] If multiple VMs matching the name, use the first or last found.\n attribute :name_match\n validates :name_match, expression_inclusion: {:in=>[:first, :last], :message=>\"%{value} needs to be :first, :last\"}, allow_nil: true\n\n # @return [Object, nil] UUID of the instance to manage if known, this is VMware's unique identifier.,This is required parameter, if C(name) is not supplied.\n attribute :uuid\n\n # @return [String, nil] Destination folder, absolute or relative path to find an existing guest.,This is required parameter, if C(name) is supplied.,The folder should include the datacenter. ESX's datacenter is ha-datacenter.,Examples:, folder: /ha-datacenter/vm, folder: ha-datacenter/vm, folder: /datacenter1/vm, folder: datacenter1/vm, folder: /datacenter1/vm/folder1, folder: datacenter1/vm/folder1, folder: /folder1/datacenter1/vm, folder: folder1/datacenter1/vm, folder: /folder1/datacenter1/vm/folder2, folder: vm/folder2, folder: folder2\n attribute :folder\n validates :folder, type: String\n\n # @return [String] Destination datacenter for the deploy operation.\n attribute :datacenter\n validates :datacenter, presence: true, type: String\n\n # @return [String, nil] Sets the snapshot name to manage.,This param is required only if state is not C(remove_all)\n attribute :snapshot_name\n validates :snapshot_name, type: String\n\n # @return [String, nil] Define an arbitrary description to attach to snapshot.\n attribute :description\n validates :description, type: String\n\n # @return [Symbol, nil] If set to C(true) and virtual machine is powered on, it will quiesce the file system in virtual machine.,Note that VMWare Tools are required for this flag.,If virtual machine is powered off or VMware Tools are not available, then this flag is set to C(false).,If virtual machine does not provide capability to take quiesce snapshot, then this flag is set to C(false).\n attribute :quiesce\n validates :quiesce, type: Symbol\n\n # @return [Symbol, nil] If set to C(true), memory dump of virtual machine is also included in snapshot.,Note that memory snapshots take time and resources, this will take longer time to create.,If virtual machine does not provide capability to take memory snapshot, then this flag is set to C(false).\n attribute :memory_dump\n validates :memory_dump, type: Symbol\n\n # @return [Symbol, nil] If set to C(true) and state is set to C(absent), then entire snapshot subtree is set for removal.\n attribute :remove_children\n validates :remove_children, type: Symbol\n\n # @return [String, nil] Value to rename the existing snapshot to.\n attribute :new_snapshot_name\n validates :new_snapshot_name, type: String\n\n # @return [String, nil] Value to change the description of an existing snapshot to.\n attribute :new_description\n validates :new_description, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5050065517425537, "alphanum_fraction": 0.5140348076820374, "avg_line_length": 23.916154861450195, "blob_id": "1e156af1339dd490fcda097f1f945cb9f53ff55e", "content_id": "86a3f1f5c03c6b1f7134b189d868092955ee09c6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 12184, "license_type": "permissive", "max_line_length": 156, "num_lines": 489, "path": "/lib/ansible/ruby/dsl_builders/play_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'spec_helper'\nrequire 'ansible-ruby'\n\ndescribe Ansible::Ruby::DslBuilders::Play do\n let(:name) { 'another play' }\n let(:builder) { Ansible::Ruby::DslBuilders::Play.new name }\n\n def evaluate\n builder.instance_eval ruby\n builder._result\n end\n\n subject(:play) { evaluate }\n\n before do\n klass = Class.new(Ansible::Ruby::Modules::Base) do\n attribute :src\n validates :src, presence: true\n attribute :dest\n validates :dest, presence: true\n end\n stub_const 'Ansible::Ruby::Modules::Copy', klass\n end\n\n context 'with name' do\n let(:ruby) do\n <<-RUBY\n hosts 'host1'\n\n task 'Copy something' do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n end\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Play }\n it do\n is_expected.to have_attributes hosts: 'host1',\n name: 'another play'\n end\n\n describe 'tasks' do\n subject { play.tasks }\n\n it { is_expected.to be_a Ansible::Ruby::Models::Tasks }\n it { is_expected.to have_attributes items: include(be_a(Ansible::Ruby::Models::Task)) }\n end\n\n describe 'hash keys' do\n subject { play.to_h.stringify_keys.keys }\n\n it { is_expected.to eq %w[hosts name tasks] }\n end\n end\n\n context 'vars' do\n let(:ruby) do\n <<-RUBY\n hosts 'host1'\n\n vars var1: 'value1'\n\n task 'Copy something' do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n end\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Play }\n it do\n is_expected.to have_attributes hosts: 'host1',\n name: 'another play',\n vars: { var1: 'value1' }\n end\n end\n\n context 'multiple tasks' do\n let(:ruby) do\n <<-RUBY\n hosts 'host1'\n\n task 'Copy something' do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n end\n\n task 'Copy something else' do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n end\n RUBY\n end\n\n subject { play.tasks }\n\n it { is_expected.to be_a Ansible::Ruby::Models::Tasks }\n it do\n is_expected.to have_attributes items: include(be_a(Ansible::Ruby::Models::Task),\n be_a(Ansible::Ruby::Models::Task))\n end\n end\n\n context 'include' do\n context 'with roles' do\n let(:ruby) do\n <<-RUBY\n hosts 'host1'\n ansible_include '/some_file.yml'\n roles %w(role1 role2)\n RUBY\n end\n\n it 'should raise an error' do\n expect {evaluate}.to raise_error 'Includes cannot be used in a play using a role. They can only be used in task files or in plays with a task list.'\n end\n end\n\n context 'with tasks' do\n let(:ruby) do\n <<-RUBY\n hosts 'host1'\n\n ansible_include '/some_file.yml'\n\n task 'Copy something' do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n end\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Play }\n it do\n is_expected.to have_attributes hosts: 'host1',\n name: 'another play'\n end\n\n describe 'tasks' do\n subject { play.tasks }\n\n it { is_expected.to be_a Ansible::Ruby::Models::Tasks }\n it do\n is_expected.to have_attributes items: include(be_a(Ansible::Ruby::Models::Task)),\n inclusions: include(be_a(Ansible::Ruby::Models::Inclusion))\n end\n end\n\n describe 'hash keys' do\n subject { play.to_h.stringify_keys.keys }\n\n it { is_expected.to eq %w[hosts name tasks] }\n end\n end\n end\n\n context 'no name' do\n let(:ruby) do\n <<-RUBY\n hosts 'host1'\n\n task 'Copy something' do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n end\n RUBY\n end\n let(:name) { nil }\n\n it { is_expected.to be_a Ansible::Ruby::Models::Play }\n it { is_expected.to have_attributes hosts: 'host1' }\n\n describe 'hash keys' do\n subject { play.to_h.stringify_keys.keys }\n\n it { is_expected.to eq %w[hosts tasks] }\n end\n end\n\n context 'block' do\n context 'valid' do\n let(:ruby) do\n <<-RUBY\n hosts 'host1'\n\n block do\n task 'copy' do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n end\n\n ansible_when \"ansible_distribution == 'CentOS'\"\n end\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Play }\n it { is_expected.to have_attributes hosts: 'host1' }\n\n describe 'tasks' do\n subject { play.tasks }\n\n it { is_expected.to be_a Ansible::Ruby::Models::Tasks }\n it { is_expected.to have_attributes items: include(be_a(Ansible::Ruby::Models::Block)) }\n end\n\n describe 'hash keys' do\n subject { play.to_h.stringify_keys.keys }\n\n it { is_expected.to eq %w[hosts name tasks] }\n end\n end\n\n context 'no task' do\n let(:ruby) do\n <<-RUBY\n hosts 'host1'\n\n block do\n ansible_when \"ansible_distribution == 'CentOS'\"\n end\n RUBY\n end\n\n it 'should raise an error' do\n expect {evaluate}.to raise_error 'Validation failed: Tasks Must have at least 1 task in your block!'\n end\n end\n\n context 'no block' do\n let(:ruby) do\n <<-RUBY\n hosts 'host1'\n\n block\n RUBY\n end\n\n it 'should raise an error' do\n expect {evaluate}.to raise_error 'wrong number of arguments (given 0, expected 1..3)'\n end\n end\n end\n\n context 'localhost shortcut' do\n let(:ruby) do\n <<-RUBY\n local_host\n\n task 'Copy something' do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n end\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Play }\n\n it do\n is_expected.to have_attributes hosts: 'localhost',\n connection: :local\n end\n end\n\n context 'no name provided' do\n let(:builder) { Ansible::Ruby::DslBuilders::Play.new }\n\n let(:ruby) do\n <<-RUBY\n hosts 'host1'\n\n task 'Copy something' do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n end\n RUBY\n end\n\n describe 'hash keys' do\n subject { play.to_h.stringify_keys.keys }\n\n it { is_expected.to eq %w[hosts tasks] }\n end\n end\n\n context 'tag for entire playbook' do\n let(:ruby) do\n <<-RUBY\n hosts 'host1'\n roles 'role1'\n tags :foo_123\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Play }\n it { is_expected.to_not have_attributes tasks: be_truthy }\n it do\n is_expected.to have_attributes roles: 'role1',\n hosts: 'host1',\n tags: [:foo_123]\n end\n end\n\n context 'tags for entire playbook' do\n let(:ruby) do\n <<-RUBY\n hosts 'host1'\n roles 'role1'\n tags :foo_123, :bar\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Play }\n it { is_expected.to_not have_attributes tasks: be_truthy }\n it do\n is_expected.to have_attributes roles: 'role1',\n hosts: 'host1',\n tags: %i[foo_123 bar]\n end\n end\n\n context 'roles' do\n context '1 line' do\n let(:ruby) do\n <<-RUBY\n hosts 'host1'\n roles %w(role1 role2)\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Play }\n it { is_expected.to_not have_attributes tasks: be_truthy }\n it do\n is_expected.to have_attributes roles: %w[role1 role2],\n hosts: 'host1'\n end\n end\n\n context 'shorthand' do\n let(:ruby) do\n <<-RUBY\n hosts 'host1'\n role 'role1'\n role 'role2'\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Play }\n it { is_expected.to_not have_attributes tasks: be_truthy }\n it do\n is_expected.to have_attributes roles: [{ role: 'role1' }, { role: 'role2' }],\n hosts: 'host1'\n end\n end\n\n context '1 line with role tags' do\n let(:ruby) do\n <<-RUBY\n hosts 'host1'\n roles [{role:'role1', tags: ['clone']}, {role:'role2', tags: ['clone2']}]\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Play }\n it { is_expected.to_not have_attributes tasks: be_truthy }\n it do\n is_expected.to have_attributes roles: [{ role: 'role1', tags: ['clone'] },\n { role: 'role2', tags: ['clone2'] }],\n hosts: 'host1'\n end\n end\n\n context '2 lines with role tags' do\n let(:ruby) do\n <<-RUBY\n hosts 'host1'\n role 'role1', tag: 'clone'\n role 'role2', tag: 'clone2'\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Play }\n it { is_expected.to_not have_attributes tasks: be_truthy }\n it do\n is_expected.to have_attributes roles: [{ role: 'role1', tags: ['clone'] },\n { role: 'role2', tags: ['clone2'] }],\n hosts: 'host1'\n end\n end\n\n context 'Multiple role tags' do\n let(:ruby) do\n <<-RUBY\n hosts 'host1'\n role 'role1', tags: ['clone', 'foo']\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Play }\n it { is_expected.to_not have_attributes tasks: be_truthy }\n it do\n is_expected.to have_attributes roles: [{ role: 'role1', tags: %w[clone foo] }],\n hosts: 'host1'\n end\n end\n\n context 'role when expression' do\n let(:ruby) do\n <<-RUBY\n hosts 'host1'\n role 'role1', when: 'some_expression'\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Play }\n it { is_expected.to_not have_attributes tasks: be_truthy }\n it do\n is_expected.to have_attributes roles: [{ role: 'role1', when: 'some_expression' }],\n hosts: 'host1'\n end\n end\n end\n\n context 'invalid keyword' do\n let(:ruby) { 'foobar' }\n\n it 'should raise an error' do\n expect {evaluate}.to raise_error(%r{Invalid method/local variable `foobar'. Only valid options are \\[:ansible_include.*})\n end\n end\n\n context 'other attributes' do\n # We don't build name or tasks the same way as others\n (Ansible::Ruby::Models::Play.instance_methods - Object.instance_methods - %i[name= tasks= inclusions= attributes= tags=])\n .select { |method| method.to_s.end_with?('=') }\n .map { |method| method.to_s[0..-2] }\n .each do |method|\n\n context method do\n let(:ruby) { \"#{method} 'some_value'\" }\n\n it { is_expected.to be_a Ansible::Ruby::Models::Play }\n\n it 'has the builder value' do\n expect(play.send(method)).to eq 'some_value'\n end\n end\n end\n end\n\n context 'jinja' do\n let(:ruby) do\n <<~RUBY\n hosts 'host1'\n roles %w(role1 role2)\n user jinja('centos')\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Play }\n it do\n is_expected.to have_attributes roles: %w[role1 role2],\n user: Ansible::Ruby::Models::JinjaExpression.new('centos'),\n name: 'another play',\n hosts: 'host1'\n end\n end\nend\n" }, { "alpha_fraction": 0.7237955331802368, "alphanum_fraction": 0.7260022163391113, "avg_line_length": 74.52777862548828, "blob_id": "f9bf6b95663dea4ec0d45f42aac0069ee2cc21da", "content_id": "9d93b5f7e052b238610f9aa45ac164b3298ab60a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2719, "license_type": "permissive", "max_line_length": 935, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/lambda_event.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows the management of AWS Lambda function event source mappings such as DynamoDB and Kinesis stream events via the Ansible framework. These event source mappings are relevant only in the AWS Lambda pull model, where AWS Lambda invokes the function. It is idempotent and supports \"Check\" mode. Use module M(lambda) to manage the lambda function itself and M(lambda_alias) to manage function aliases.\n class Lambda_event < Base\n # @return [Object] The name or ARN of the lambda function.\n attribute :lambda_function_arn\n validates :lambda_function_arn, presence: true\n\n # @return [:present, :absent] Describes the desired state.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [Object] Name of the function alias. Mutually exclusive with C(version).\n attribute :alias\n validates :alias, presence: true\n\n # @return [Object, nil] Version of the Lambda function. Mutually exclusive with C(alias).\n attribute :version\n\n # @return [:stream, :sqs, nil] Source of the event that triggers the lambda function.,For DynamoDB and Kinesis events, select 'stream',For SQS queues, select 'sqs'\n attribute :event_source\n validates :event_source, expression_inclusion: {:in=>[:stream, :sqs], :message=>\"%{value} needs to be :stream, :sqs\"}, allow_nil: true\n\n # @return [Object] Sub-parameters required for event source.,I(== stream event source ==),C(source_arn) The Amazon Resource Name (ARN) of the Kinesis or DynamoDB stream that is the event source.,C(enabled) Indicates whether AWS Lambda should begin polling the event source. Default is True.,C(batch_size) The largest number of records that AWS Lambda will retrieve from your event source at the time of invoking your function. Default is 100.,C(starting_position) The position in the stream where AWS Lambda should start reading. Choices are TRIM_HORIZON or LATEST.,I(== sqs event source ==),C(source_arn) The Amazon Resource Name (ARN) of the SQS queue to read events from.,C(enabled) Indicates whether AWS Lambda should begin reading from the event source. Default is True.,C(batch_size) The largest number of records that AWS Lambda will retrieve from your event source at the time of invoking your function. Default is 100.\n attribute :source_params\n validates :source_params, presence: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7113401889801025, "alphanum_fraction": 0.7113401889801025, "avg_line_length": 35.9523811340332, "blob_id": "a98b192a1febc07d36a26e7dbf87ee8995301a56", "content_id": "0cfd879318270ee43c43d7ccb79d63d97e5eb57b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 776, "license_type": "permissive", "max_line_length": 148, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_rollback.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module offers the ability to set a configuration checkpoint file or rollback to a configuration checkpoint file on Cisco NXOS switches.\n class Nxos_rollback < Base\n # @return [String, nil] Name of checkpoint file to create. Mutually exclusive with rollback_to.\n attribute :checkpoint_file\n validates :checkpoint_file, type: String\n\n # @return [String, nil] Name of checkpoint file to rollback to. Mutually exclusive with checkpoint_file.\n attribute :rollback_to\n validates :rollback_to, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6710963249206543, "alphanum_fraction": 0.6710963249206543, "avg_line_length": 44.150001525878906, "blob_id": "a50b7cfbfa4c5e422e7a3900462dda12c01099e5", "content_id": "96204af63ca28a368545decf69ba84ae022e740d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1806, "license_type": "permissive", "max_line_length": 217, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/commands/shell.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The C(shell) module takes the command name followed by a list of space-delimited arguments. It is almost exactly like the M(command) module but runs the command through a shell (C(/bin/sh)) on the remote node.\n # For Windows targets, use the M(win_shell) module instead.\n class Shell < Base\n # @return [Object] The shell module takes a free form command to run, as a string. There's not an actual option named \"free form\". See the examples!\n attribute :free_form\n validates :free_form, presence: true\n\n # @return [String, nil] a filename, when it already exists, this step will B(not) be run.\n attribute :creates\n validates :creates, type: String\n\n # @return [Object, nil] a filename, when it does not exist, this step will B(not) be run.\n attribute :removes\n\n # @return [String, nil] cd into this directory before running the command\n attribute :chdir\n validates :chdir, type: String\n\n # @return [String, nil] change the shell used to execute the command. Should be an absolute path to the executable.\n attribute :executable\n validates :executable, type: String\n\n # @return [:yes, :no, nil] if command warnings are on in ansible.cfg, do not warn about this particular line if set to no/false.\n attribute :warn\n validates :warn, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Set the stdin of the command directly to the specified value.\n attribute :stdin\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.650697648525238, "alphanum_fraction": 0.6567441821098328, "avg_line_length": 27.289474487304688, "blob_id": "6ade84420789cb3b092f8745a9b5e0f1eaf53c8e", "content_id": "f3a95fe3f10d42644d797f89240f7fc21c7f5460", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2150, "license_type": "permissive", "max_line_length": 171, "num_lines": 76, "path": "/lib/ansible/ruby/rake/compile_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# See LICENSE.txt in root of repository\nrequire 'spec_helper'\nrequire 'ansible-ruby'\nrequire 'ansible/ruby/rake/compile'\n\ndescribe Ansible::Ruby::Rake::Compile do\n include_context :rake_testing\n include_context :rake_invoke\n\n let(:yaml_file) { 'playbook1_test.yml' }\n let(:ruby_file) { 'playbook1_test.rb' }\n\n context 'dependent task' do\n let(:test_file) { 'foobar_test.yml' }\n let(:task) do\n ::Rake::Task.define_task :foobar do\n FileUtils.touch test_file\n end\n\n Ansible::Ruby::Rake::Compile.new default: :foobar do |task|\n task.files = ruby_file\n end\n end\n\n it { is_expected.to_not execute_commands }\n it { is_expected.to have_yaml yaml_file, that: include('host1:host2') }\n\n it 'executes the dependency' do\n expect(File.exist?(test_file)).to be_truthy\n end\n end\n\n context 'no files' do\n def execute_task\n # overriding parent so we can test error\n end\n\n it 'should raise an error' do\n expect {Ansible::Ruby::Rake::Compile.new}.to raise_error 'You did not supply any files!'\n end\n end\n\n context 'YML and Ruby files' do\n def execute_task\n File.write 'sample3_test.yml', 'original YML file'\n super\n end\n\n let(:task) do\n Ansible::Ruby::Rake::Compile.new do |task|\n task.files = %w[playbook1_test.rb sample3_test.yml]\n end\n end\n\n it { is_expected.to_not execute_commands }\n it { is_expected.to have_yaml 'playbook1_test.yml', that: include('host1:host2') }\n it { is_expected.to have_yaml 'sample3_test.yml', that: include('original YML file') }\n end\n\n context 'compile error' do\n def execute_task\n # overriding parent so we can test error\n end\n\n it 'should raise an error' do\n Ansible::Ruby::Rake::Compile.new do |task|\n task.files = 'playbook_error.rb'\n end\n error = \"Invalid method/local variable `ansible_iinclude'\\\\. Only valid options are \\\\[:ansible_include.*.*Error Location:.*playbook_error.rb:6.*playbook_error.rb:3\"\n\n expect {Rake::Task[:default].invoke}.to raise_error Regexp.new(error.strip, Regexp::MULTILINE)\n end\n end\nend\n" }, { "alpha_fraction": 0.7447217106819153, "alphanum_fraction": 0.7447217106819153, "avg_line_length": 25.049999237060547, "blob_id": "9c642b8a488f4b1fddd2e710ec4a14ff5483625f", "content_id": "8c3d7016d0f00f2ce7a107178aa2befc276e649d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 521, "license_type": "permissive", "max_line_length": 57, "num_lines": 20, "path": "/spec/rake/no_nested_tasks/Rakefile_test.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# rubocop: disable Naming/FileName\n# frozen_string_literal: true\n\nrequire 'ansible/ruby/rake/tasks'\n\ndesc 'the ansible task default'\nAnsible::Ruby::Rake::Execute.new do |task|\n task.playbooks = 'lib/ansible/ruby/rake/sample_test.rb'\nend\n\ndesc 'named ansible task'\nAnsible::Ruby::Rake::Execute.new :stuff do |task|\n task.playbooks = 'lib/ansible/ruby/rake/sample_test.rb'\nend\n# rubocop: enable Naming/FileName\n\ndesc 'explicit compile task'\nAnsible::Ruby::Rake::Compile.new :compile do |task|\n task.files = 'foobar'\nend\n" }, { "alpha_fraction": 0.6461538672447205, "alphanum_fraction": 0.6461538672447205, "avg_line_length": 17.05555534362793, "blob_id": "944183697a4a538d75505d8864fd6b4e139c9a7b", "content_id": "efda12500f7bc886ca0a7c044f83e97a5e71a71c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 325, "license_type": "permissive", "max_line_length": 39, "num_lines": 18, "path": "/spec/rake/copy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# See LICENSE.txt for license\n\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n class Copy < Base\n attribute :src\n validates :src, presence: true\n attribute :dest\n validates :dest, presence: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6482213735580444, "alphanum_fraction": 0.6482213735580444, "avg_line_length": 36.024391174316406, "blob_id": "2dbade7c5082a73fd288ff821bab7de6674b8b5a", "content_id": "7a709fa7d6a5355d46d116b3e1e479d26a9418b0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1518, "license_type": "permissive", "max_line_length": 143, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_affinitygroup.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create and remove affinity groups.\n class Cs_affinitygroup < Base\n # @return [String] Name of the affinity group.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Type of the affinity group. If not specified, first found affinity type is used.\n attribute :affinity_type\n validates :affinity_type, type: String\n\n # @return [Object, nil] Description of the affinity group.\n attribute :description\n\n # @return [:present, :absent, nil] State of the affinity group.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Domain the affinity group is related to.\n attribute :domain\n\n # @return [Object, nil] Account the affinity group is related to.\n attribute :account\n\n # @return [Object, nil] Name of the project the affinity group is related to.\n attribute :project\n\n # @return [:yes, :no, nil] Poll async jobs until job has finished.\n attribute :poll_async\n validates :poll_async, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6680850982666016, "alphanum_fraction": 0.6680850982666016, "avg_line_length": 44.85365676879883, "blob_id": "f085c4b353bc3372e0bf39bd7c17e2f7b9c33de4", "content_id": "05b98af061030eac40cd9bc975cd1768455c287b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1880, "license_type": "permissive", "max_line_length": 252, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/cloud/atomic/atomic_container.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage the containers on the atomic host platform\n # Allows to manage the lifecycle of a container on the atomic host platform\n class Atomic_container < Base\n # @return [:docker, :ostree] Define the backend to use for the container\n attribute :backend\n validates :backend, presence: true, expression_inclusion: {:in=>[:docker, :ostree], :message=>\"%{value} needs to be :docker, :ostree\"}\n\n # @return [String] Name of the container\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] The image to use to install the container\n attribute :image\n validates :image, presence: true, type: String\n\n # @return [Object, nil] Define the rootfs of the image\n attribute :rootfs\n\n # @return [:latest, :present, :absent, :rollback] State of the container\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:latest, :present, :absent, :rollback], :message=>\"%{value} needs to be :latest, :present, :absent, :rollback\"}\n\n # @return [:user, :system] Define if it is an user or a system container\n attribute :mode\n validates :mode, presence: true, expression_inclusion: {:in=>[:user, :system], :message=>\"%{value} needs to be :user, :system\"}\n\n # @return [Array<String>, String, nil] Values for the installation of the container. This option is permitted only with mode 'user' or 'system'. The values specified here will be used at installation time as --set arguments for atomic install.\n attribute :values\n validates :values, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6885086297988892, "alphanum_fraction": 0.6911519169807434, "avg_line_length": 74.66315460205078, "blob_id": "4aac90389451701822276900665e7088c463410c", "content_id": "3e951b2f8fec3aadaefd7038b44d05971bf0b619", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 7188, "license_type": "permissive", "max_line_length": 566, "num_lines": 95, "path": "/lib/ansible/ruby/modules/generated/net_tools/basics/uri.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Interacts with HTTP and HTTPS web services and supports Digest, Basic and WSSE HTTP authentication mechanisms.\n # For Windows targets, use the M(win_uri) module instead.\n class Uri < Base\n # @return [String] HTTP or HTTPS URL in the form (http|https)://host.domain[:port]/path\n attribute :url\n validates :url, presence: true, type: String\n\n # @return [Object, nil] A path of where to download the file to (if desired). If I(dest) is a directory, the basename of the file on the remote server will be used.\n attribute :dest\n\n # @return [String, nil] A username for the module to use for Digest, Basic or WSSE authentication.\n attribute :user\n validates :user, type: String\n\n # @return [String, nil] A password for the module to use for Digest, Basic or WSSE authentication.\n attribute :password\n validates :password, type: String\n\n # @return [String, Hash, Array<Array>, Array, nil] The body of the http request/response to the web service. If C(body_format) is set to 'json' it will take an already formatted JSON string or convert a data structure into JSON. If C(body_format) is set to 'form-urlencoded' it will convert a dictionary or list of tuples into an 'application/x-www-form-urlencoded' string. (Added in v2.7)\n attribute :body\n validates :body, type: TypeGeneric.new(Array)\n\n # @return [:\"form-urlencoded\", :json, :raw, nil] The serialization format of the body. When set to C(json) or C(form-urlencoded), encodes the body argument, if needed, and automatically sets the Content-Type header accordingly. As of C(2.3) it is possible to override the `Content-Type` header, when set to C(json) or C(form-urlencoded) via the I(headers) option.\n attribute :body_format\n validates :body_format, expression_inclusion: {:in=>[:\"form-urlencoded\", :json, :raw], :message=>\"%{value} needs to be :\\\"form-urlencoded\\\", :json, :raw\"}, allow_nil: true\n\n # @return [:GET, :POST, :PUT, :HEAD, :DELETE, :OPTIONS, :PATCH, :TRACE, :CONNECT, :REFRESH, nil] The HTTP method of the request or response. It MUST be uppercase.\n attribute :method\n validates :method, expression_inclusion: {:in=>[:GET, :POST, :PUT, :HEAD, :DELETE, :OPTIONS, :PATCH, :TRACE, :CONNECT, :REFRESH], :message=>\"%{value} needs to be :GET, :POST, :PUT, :HEAD, :DELETE, :OPTIONS, :PATCH, :TRACE, :CONNECT, :REFRESH\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Whether or not to return the body of the response as a \"content\" key in the dictionary result. If the reported Content-type is \"application/json\", then the JSON is additionally loaded into a key called C(json) in the dictionary results.\n attribute :return_content\n validates :return_content, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] The library used by the uri module only sends authentication information when a webservice responds to an initial request with a 401 status. Since some basic auth services do not properly send a 401, logins will fail. This option forces the sending of the Basic authentication header upon initial request.\n attribute :force_basic_auth\n validates :force_basic_auth, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:all, :none, :safe, nil] Whether or not the URI module should follow redirects. C(all) will follow all redirects. C(safe) will follow only \"safe\" redirects, where \"safe\" means that the client is only doing a GET or HEAD on the URI to which it is being redirected. C(none) will not follow any redirects. Note that C(yes) and C(no) choices are accepted for backwards compatibility, where C(yes) is the equivalent of C(all) and C(no) is the equivalent of C(safe). C(yes) and C(no) are deprecated and will be removed in some future version of Ansible.\n attribute :follow_redirects\n validates :follow_redirects, expression_inclusion: {:in=>[:all, :none, :safe], :message=>\"%{value} needs to be :all, :none, :safe\"}, allow_nil: true\n\n # @return [Object, nil] A filename, when it already exists, this step will not be run.\n attribute :creates\n\n # @return [Object, nil] A filename, when it does not exist, this step will not be run.\n attribute :removes\n\n # @return [Integer, nil] A list of valid, numeric, HTTP status codes that signifies success of the request.\n attribute :status_code\n validates :status_code, type: Integer\n\n # @return [Integer, nil] The socket level timeout in seconds\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [Object, nil] Any parameter starting with \"HEADER_\" is a sent with your request as a header. For example, HEADER_Content-Type=\"application/json\" would send the header \"Content-Type\" along with your request with a value of \"application/json\". This option is deprecated as of C(2.1) and will be removed in Ansible-2.9. Use I(headers) instead.\n attribute :HEADER_\n\n # @return [Hash, nil] Add custom HTTP headers to a request in the format of a YAML hash. As of C(2.3) supplying C(Content-Type) here will override the header generated by supplying C(json) or C(form-urlencoded) for I(body_format).\n attribute :headers\n validates :headers, type: Hash\n\n # @return [Object, nil] All arguments accepted by the M(file) module also work here\n attribute :others\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated. This should only set to C(no) used on personally controlled sites using self-signed certificates. Prior to 1.9.2 the code defaulted to C(no).\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] PEM formatted certificate chain file to be used for SSL client authentication. This file can also include the key as well, and if the key is included, I(client_key) is not required\n attribute :client_cert\n\n # @return [Object, nil] PEM formatted file that contains your private key to be used for SSL client authentication. If I(client_cert) contains both the certificate and key, this option is not required.\n attribute :client_key\n\n # @return [String, nil] Path to file to be submitted to the remote server. Cannot be used with I(body).\n attribute :src\n validates :src, type: String\n\n # @return [:yes, :no, nil] If C(no), the module will search for src on originating/master machine, if C(yes) the module will use the C(src) path on the remote/target machine.\n attribute :remote_src\n validates :remote_src, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6719692945480347, "alphanum_fraction": 0.6780033111572266, "avg_line_length": 43.46341323852539, "blob_id": "958ff0d88bba1d975970e9c405a88636b7a45856", "content_id": "9b6e66568b6dd50b89d3eb3322bc27aa06dd1b74", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1823, "license_type": "permissive", "max_line_length": 234, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/windows/win_eventlog_entry.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Write log entries to a given event log from a specified source.\n class Win_eventlog_entry < Base\n # @return [String] Name of the event log to write an entry to.\n attribute :log\n validates :log, presence: true, type: String\n\n # @return [String] Name of the log source to indicate where the entry is from.\n attribute :source\n validates :source, presence: true, type: String\n\n # @return [Integer] The numeric event identifier for the entry.,Value must be between 0 and 65535.\n attribute :event_id\n validates :event_id, presence: true, type: Integer\n\n # @return [String] The message for the given log entry.\n attribute :message\n validates :message, presence: true, type: String\n\n # @return [:Error, :FailureAudit, :Information, :SuccessAudit, :Warning, nil] Indicates the entry being written to the log is of a specific type.\n attribute :entry_type\n validates :entry_type, expression_inclusion: {:in=>[:Error, :FailureAudit, :Information, :SuccessAudit, :Warning], :message=>\"%{value} needs to be :Error, :FailureAudit, :Information, :SuccessAudit, :Warning\"}, allow_nil: true\n\n # @return [Integer, nil] A numeric task category associated with the category message file for the log source.\n attribute :category\n validates :category, type: Integer\n\n # @return [Integer, nil] Binary data associated with the log entry.,Value must be a comma-separated array of 8-bit unsigned integers (0 to 255).\n attribute :raw_data\n validates :raw_data, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6168582439422607, "alphanum_fraction": 0.6436781883239746, "avg_line_length": 15.3125, "blob_id": "b7ab380a9e2043922b6191b4ff6ab4215a52e79b", "content_id": "721138831c9fba441d50902569e7b78f6337a28d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 261, "license_type": "permissive", "max_line_length": 37, "num_lines": 16, "path": "/spec/rake/no_nested_tasks/playbook_error.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nplay 'the play name' do\n hosts %w[host1 host2]\n\n ansible_iinclude 'inclusion.yml' do\n variables howdy: 123\n end\n\n task 'Copy something over' do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n end\nend\n" }, { "alpha_fraction": 0.6973947882652283, "alphanum_fraction": 0.6973947882652283, "avg_line_length": 19.79166603088379, "blob_id": "bee65dbc1cf82fb43cdbdc76d95c05af7ce97ac3", "content_id": "7d701e4fa874b9a481d1c7e18963996809bcad3e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 499, "license_type": "permissive", "max_line_length": 65, "num_lines": 24, "path": "/spec/support/matchers/execute_command.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nRSpec::Matchers.define :execute_command do |expected|\n def commands(actual)\n actual[:commands]\n end\n\n match do |actual|\n @matcher = eq([*expected])\n @matcher.matches? commands(actual)\n end\n\n match_when_negated do |actual|\n expect(expected).to be_nil\n @matcher = be_empty\n @matcher.matches? commands(actual)\n end\n\n failure_message do |_|\n @matcher.failure_message\n end\nend\n\nRSpec::Matchers.alias_matcher :execute_commands, :execute_command\n" }, { "alpha_fraction": 0.6982006430625916, "alphanum_fraction": 0.700678825378418, "avg_line_length": 57.74050521850586, "blob_id": "0ecd2d7212ecc201d7153a30b3bc567bc4f23ab5", "content_id": "f6e5e91da29772641e02fb52c2705b4796819d14", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 9281, "license_type": "permissive", "max_line_length": 778, "num_lines": 158, "path": "/lib/ansible/ruby/modules/generated/crypto/openssl_certificate.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module allows one to (re)generate OpenSSL certificates. It implements a notion of provider (ie. C(selfsigned), C(ownca), C(acme), C(assertonly)) for your certificate. The 'assertonly' provider is intended for use cases where one is only interested in checking properties of a supplied certificate. The 'ownca' provider is intended for generate OpenSSL certificate signed with your own CA (Certificate Authority) certificate (self-signed certificate). Many properties that can be specified in this module are for validation of an existing or newly generated certificate. The proper place to specify them, if you want to receive a certificate with these properties is a CSR (Certificate Signing Request). It uses the pyOpenSSL python library to interact with OpenSSL.\n class Openssl_certificate < Base\n # @return [:present, :absent, nil] Whether the certificate should exist or not, taking action if the state is different from what is stated.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] Remote absolute path where the generated certificate file should be created or is already located.\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [:selfsigned, :ownca, :assertonly, :acme] Name of the provider to use to generate/retrieve the OpenSSL certificate. The C(assertonly) provider will not generate files and fail if the certificate file is missing.\n attribute :provider\n validates :provider, presence: true, expression_inclusion: {:in=>[:selfsigned, :ownca, :assertonly, :acme], :message=>\"%{value} needs to be :selfsigned, :ownca, :assertonly, :acme\"}\n\n # @return [Symbol, nil] Generate the certificate, even if it already exists.\n attribute :force\n validates :force, type: Symbol\n\n # @return [String, nil] Path to the Certificate Signing Request (CSR) used to generate this certificate. This is not required in C(assertonly) mode.\n attribute :csr_path\n validates :csr_path, type: String\n\n # @return [String, nil] Path to the private key to use when signing the certificate.\n attribute :privatekey_path\n validates :privatekey_path, type: String\n\n # @return [Object, nil] The passphrase for the I(privatekey_path).\n attribute :privatekey_passphrase\n\n # @return [Integer, nil] Version of the C(selfsigned) certificate. Nowadays it should almost always be C(3).\n attribute :selfsigned_version\n validates :selfsigned_version, type: Integer\n\n # @return [String, nil] Digest algorithm to be used when self-signing the certificate\n attribute :selfsigned_digest\n validates :selfsigned_digest, type: String\n\n # @return [Object, nil] The timestamp at which the certificate starts being valid. The timestamp is formatted as an ASN.1 TIME. If this value is not specified, certificate will start being valid from now.\n attribute :selfsigned_not_before\n\n # @return [Object, nil] The timestamp at which the certificate stops being valid. The timestamp is formatted as an ASN.1 TIME. If this value is not specified, certificate will stop being valid 10 years from now.\n attribute :selfsigned_not_after\n\n # @return [String, nil] Remote absolute path of the CA (Certificate Authority) certificate.\n attribute :ownca_path\n validates :ownca_path, type: String\n\n # @return [String, nil] Path to the CA (Certificate Authority) private key to use when signing the certificate.\n attribute :ownca_privatekey_path\n validates :ownca_privatekey_path, type: String\n\n # @return [Object, nil] The passphrase for the I(ownca_privatekey_path).\n attribute :ownca_privatekey_passphrase\n\n # @return [String, nil] Digest algorithm to be used for the C(ownca) certificate.\n attribute :ownca_digest\n validates :ownca_digest, type: String\n\n # @return [Integer, nil] Version of the C(ownca) certificate. Nowadays it should almost always be C(3).\n attribute :ownca_version\n validates :ownca_version, type: Integer\n\n # @return [Object, nil] The timestamp at which the certificate starts being valid. The timestamp is formatted as an ASN.1 TIME. If this value is not specified, certificate will start being valid from now.\n attribute :ownca_not_before\n\n # @return [Object, nil] The timestamp at which the certificate stops being valid. The timestamp is formatted as an ASN.1 TIME. If this value is not specified, certificate will stop being valid 10 years from now.\n attribute :ownca_not_after\n\n # @return [String, nil] Path to the accountkey for the C(acme) provider\n attribute :acme_accountkey_path\n validates :acme_accountkey_path, type: String\n\n # @return [String, nil] Path to the ACME challenge directory that is served on U(http://<HOST>:80/.well-known/acme-challenge/)\n attribute :acme_challenge_path\n validates :acme_challenge_path, type: String\n\n # @return [Boolean, nil] Include the intermediate certificate to the generated certificate\n attribute :acme_chain\n validates :acme_chain, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] list of algorithms that you would accept the certificate to be signed with (e.g. ['sha256WithRSAEncryption', 'sha512WithRSAEncryption']).\n attribute :signature_algorithms\n validates :signature_algorithms, type: TypeGeneric.new(String)\n\n # @return [Hash, nil] Key/value pairs that must be present in the issuer name field of the certificate. If you need to specify more than one value with the same key, use a list as value.\n attribute :issuer\n validates :issuer, type: Hash\n\n # @return [Symbol, nil] If set to True, the I(issuer) field must contain only these values.\n attribute :issuer_strict\n validates :issuer_strict, type: Symbol\n\n # @return [Object, nil] Key/value pairs that must be present in the subject name field of the certificate. If you need to specify more than one value with the same key, use a list as value.\n attribute :subject\n\n # @return [Symbol, nil] If set to True, the I(subject) field must contain only these values.\n attribute :subject_strict\n validates :subject_strict, type: Symbol\n\n # @return [Symbol, nil] Checks if the certificate is expired/not expired at the time the module is executed.\n attribute :has_expired\n validates :has_expired, type: Symbol\n\n # @return [Object, nil] Version of the certificate. Nowadays it should almost always be 3.\n attribute :version\n\n # @return [String, nil] The certificate must be valid at this point in time. The timestamp is formatted as an ASN.1 TIME.\n attribute :valid_at\n validates :valid_at, type: String\n\n # @return [Object, nil] The certificate must be invalid at this point in time. The timestamp is formatted as an ASN.1 TIME.\n attribute :invalid_at\n\n # @return [Object, nil] The certificate must start to become valid at this point in time. The timestamp is formatted as an ASN.1 TIME.\n attribute :not_before\n\n # @return [Object, nil] The certificate must expire at this point in time. The timestamp is formatted as an ASN.1 TIME.\n attribute :not_after\n\n # @return [Integer, nil] The certificate must still be valid in I(valid_in) seconds from now.\n attribute :valid_in\n validates :valid_in, type: Integer\n\n # @return [Array<String>, String, nil] The I(key_usage) extension field must contain all these values.\n attribute :key_usage\n validates :key_usage, type: TypeGeneric.new(String)\n\n # @return [Symbol, nil] If set to True, the I(key_usage) extension field must contain only these values.\n attribute :key_usage_strict\n validates :key_usage_strict, type: Symbol\n\n # @return [Array<String>, String, nil] The I(extended_key_usage) extension field must contain all these values.\n attribute :extended_key_usage\n validates :extended_key_usage, type: TypeGeneric.new(String)\n\n # @return [Symbol, nil] If set to True, the I(extended_key_usage) extension field must contain only these values.\n attribute :extended_key_usage_strict\n validates :extended_key_usage_strict, type: Symbol\n\n # @return [Array<String>, String, nil] The I(subject_alt_name) extension field must contain these values.\n attribute :subject_alt_name\n validates :subject_alt_name, type: TypeGeneric.new(String)\n\n # @return [Symbol, nil] If set to True, the I(subject_alt_name) extension field must contain only these values.\n attribute :subject_alt_name_strict\n validates :subject_alt_name_strict, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.723971962928772, "alphanum_fraction": 0.7246596217155457, "avg_line_length": 99.98611450195312, "blob_id": "b620d6180c7b9990064a378d2e65feb332e0fb83", "content_id": "ad7bde257025058b71d555964be3039e514bd0c8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 7271, "license_type": "permissive", "max_line_length": 629, "num_lines": 72, "path": "/lib/ansible/ruby/modules/generated/network/netconf/netconf_config.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Netconf is a network management protocol developed and standardized by the IETF. It is documented in RFC 6241.\n # This module allows the user to send a configuration XML file to a netconf device, and detects if there was a configuration change.\n class Netconf_config < Base\n # @return [String, nil] The configuration data as defined by the device's data models, the value can be either in xml string format or text format. The format of the configuration should be supported by remote Netconf server\n attribute :content\n validates :content, type: String\n\n # @return [String, nil] Name of the configuration datastore to be edited. - auto, uses candidate and fallback to running - candidate, edit <candidate/> datastore and then commit - running, edit <running/> datastore directly\n attribute :target\n validates :target, type: String\n\n # @return [Object, nil] Name of the configuration datastore to use as the source to copy the configuration to the datastore mentioned by C(target) option. The values can be either I(running), I(candidate), I(startup) or a remote URL\n attribute :source_datastore\n\n # @return [:xml, :text, nil] The format of the configuration provided as value of C(content). Accepted values are I(xml) and I(text) and the given configuration format should be supported by remote Netconf server.\n attribute :format\n validates :format, expression_inclusion: {:in=>[:xml, :text], :message=>\"%{value} needs to be :xml, :text\"}, allow_nil: true\n\n # @return [:never, :always, :\"if-supported\", nil] Instructs the module to explicitly lock the datastore specified as C(target). By setting the option value I(always) is will explicitly lock the datastore mentioned in C(target) option. It the value is I(never) it will not lock the C(target) datastore. The value I(if-supported) lock the C(target) datastore only if it is supported by the remote Netconf server.\n attribute :lock\n validates :lock, expression_inclusion: {:in=>[:never, :always, :\"if-supported\"], :message=>\"%{value} needs to be :never, :always, :\\\"if-supported\\\"\"}, allow_nil: true\n\n # @return [:merge, :replace, :none, nil] The default operation for <edit-config> rpc, valid values are I(merge), I(replace) and I(none). If the default value is merge, the configuration data in the C(content) option is merged at the corresponding level in the C(target) datastore. If the value is replace the data in the C(content) option completely replaces the configuration in the C(target) datastore. If the value is none the C(target) datastore is unaffected by the configuration in the config option, unless and until the incoming configuration data uses the C(operation) operation to request a different operation.\n attribute :default_operation\n validates :default_operation, expression_inclusion: {:in=>[:merge, :replace, :none], :message=>\"%{value} needs to be :merge, :replace, :none\"}, allow_nil: true\n\n # @return [Integer, nil] This argument will configure a timeout value for the commit to be confirmed before it is automatically rolled back. If the C(confirm_commit) argument is set to False, this argument is silently ignored. If the value of this argument is set to 0, the commit is confirmed immediately. The remote host MUST support :candidate and :confirmed-commit capability for this option to .\n attribute :confirm\n validates :confirm, type: Integer\n\n # @return [:yes, :no, nil] This argument will execute commit operation on remote device. It can be used to confirm a previous commit.\n attribute :confirm_commit\n validates :confirm_commit, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:\"stop-on-error\", :\"continue-on-error\", :\"rollback-on-error\", nil] This option control the netconf server action after a error is occured while editing the configuration. If the value is I(stop-on-error) abort the config edit on first error, if value is I(continue-on-error) it continues to process configuration data on error, error is recorded and negative response is generated if any errors occur. If value is C(rollback-on-error) it rollback to the original configuration in case any error occurs, this requires the remote Netconf server to support the :rollback-on-error capability.\n attribute :error_option\n validates :error_option, expression_inclusion: {:in=>[:\"stop-on-error\", :\"continue-on-error\", :\"rollback-on-error\"], :message=>\"%{value} needs to be :\\\"stop-on-error\\\", :\\\"continue-on-error\\\", :\\\"rollback-on-error\\\"\"}, allow_nil: true\n\n # @return [Boolean, nil] The C(save) argument instructs the module to save the configuration in C(target) datastore to the startup-config if changed and if :startup capability is supported by Netconf server.\n attribute :save\n validates :save, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:yes, :no, nil] This argument will cause the module to create a full backup of the current C(running-config) from the remote device before any changes are made. The backup file is written to the C(backup) folder in the playbook root directory or role root directory, if playbook is part of an ansible role. If the directory does not exist, it is created.\n attribute :backup\n validates :backup, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] It instructs the module to delete the configuration from value mentioned in C(target) datastore.\n attribute :delete\n validates :delete, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Boolean, nil] This boolean flag controls if the configuration changes should be committed or not after editing the candidate datastore. This option is supported only if remote Netconf server supports :candidate capability. If the value is set to I(False) commit won't be issued after edit-config operation and user needs to handle commit or discard-changes explicitly.\n attribute :commit\n validates :commit, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Symbol, nil] This boolean flag if set validates the content of datastore given in C(target) option. For this option to work remote Netconf server shoule support :validate capability.\n attribute :validate\n validates :validate, type: Symbol\n\n # @return [Object, nil] Specifies the source path to the xml file that contains the configuration or configuration template to load. The path to the source file can either be the full path on the Ansible control host or a relative path from the playbook or role root directory. This argument is mutually exclusive with I(xml).\n attribute :src\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6608442664146423, "alphanum_fraction": 0.6608442664146423, "avg_line_length": 34.534481048583984, "blob_id": "d9fc8581b9650788eeefd0fac65700bea1177d33", "content_id": "83d14e67c11c2bd55c36b8f4f4be5285b89ae1b2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2061, "license_type": "permissive", "max_line_length": 115, "num_lines": 58, "path": "/lib/ansible/ruby/modules/generated/commands/telnet.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Executes a low-down and dirty telnet command, not going through the module subsystem.\n # This is mostly to be used for enabling ssh on devices that only have telnet enabled by default.\n class Telnet < Base\n # @return [Array<String>, String] List of commands to be executed in the telnet session.\n attribute :command\n validates :command, presence: true, type: TypeGeneric.new(String)\n\n # @return [String, nil] The host/target on which to execute the command\n attribute :host\n validates :host, type: String\n\n # @return [String, nil] The user for login\n attribute :user\n validates :user, type: String\n\n # @return [String, nil] The password for login\n attribute :password\n validates :password, type: String\n\n # @return [Integer, nil] Remote port to use\n attribute :port\n validates :port, type: Integer\n\n # @return [Integer, nil] timeout for remote operations\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [String, nil] List of prompts expected before sending next command\n attribute :prompts\n validates :prompts, type: String\n\n # @return [String, nil] Login or username prompt to expect\n attribute :login_prompt\n validates :login_prompt, type: String\n\n # @return [String, nil] Login or username prompt to expect\n attribute :password_prompt\n validates :password_prompt, type: String\n\n # @return [Integer, nil] Seconds to pause between each command issued\n attribute :pause\n validates :pause, type: Integer\n\n # @return [Symbol, nil] Sends a newline character upon successful connection to start the terminal session.\n attribute :send_newline\n validates :send_newline, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6682027578353882, "alphanum_fraction": 0.6682027578353882, "avg_line_length": 39.6875, "blob_id": "d77d51b1ff92162cd6b5ccb39321516c49b3b1bd", "content_id": "0e2edbfa2d1396154dbabedf61fa4f44a9f5a358", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1302, "license_type": "permissive", "max_line_length": 180, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_keystone_domain.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, or delete OpenStack Identity domains. If a domain with the supplied name already exists, it will be updated with the new description and enabled attributes.\n class Os_keystone_domain < Base\n # @return [String] Name that has to be given to the instance\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Description of the domain\n attribute :description\n validates :description, type: String\n\n # @return [:yes, :no, nil] Is the domain enabled\n attribute :enabled\n validates :enabled, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Should the resource be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7240725755691528, "alphanum_fraction": 0.7270511984825134, "avg_line_length": 71.4117660522461, "blob_id": "adef9047d583b4998535084db21bfd50e33058a8", "content_id": "1f28786f98d033af593872d9a16f25532ff76ec9", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3693, "license_type": "permissive", "max_line_length": 552, "num_lines": 51, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_profile_persistence_src_addr.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages source address persistence profiles.\n class Bigip_profile_persistence_src_addr < Base\n # @return [String] Specifies the name of the profile.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Specifies the profile from which this profile inherits settings.,When creating a new profile, if this parameter is not specified, the default is the system-supplied C(source_addr) profile.\n attribute :parent\n\n # @return [Symbol, nil] When C(yes), specifies that all persistent connections from a client IP address that go to the same virtual IP address also go to the same node.,When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.\n attribute :match_across_services\n validates :match_across_services, type: Symbol\n\n # @return [Symbol, nil] When C(yes), specifies that all persistent connections from the same client IP address go to the same node.,When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.\n attribute :match_across_virtuals\n validates :match_across_virtuals, type: Symbol\n\n # @return [Symbol, nil] When C(yes), specifies that the system can use any pool that contains this persistence record.,When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.\n attribute :match_across_pools\n validates :match_across_pools, type: Symbol\n\n # @return [:default, :carp, nil] Specifies the algorithm the system uses for hash persistence load balancing. The hash result is the input for the algorithm.,When C(default), specifies that the system uses the index of pool members to obtain the hash result for the input to the algorithm.,When C(carp), specifies that the system uses the Cache Array Routing Protocol (CARP) to obtain the hash result for the input to the algorithm.,When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.\n attribute :hash_algorithm\n validates :hash_algorithm, expression_inclusion: {:in=>[:default, :carp], :message=>\"%{value} needs to be :default, :carp\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the duration of the persistence entries.,When creating a new profile, if this parameter is not specified, the default is provided by the parent profile.,To specify an indefinite timeout, use the value C(indefinite).,If specifying a numeric timeout, the value must be between C(1) and C(4294967295).\n attribute :entry_timeout\n\n # @return [Symbol, nil] When C(yes), specifies that the system allows you to specify that pool member connection limits will be overridden for persisted clients.,Per-virtual connection limits remain hard limits and are not overridden.\n attribute :override_connection_limit\n validates :override_connection_limit, type: Symbol\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [:present, :absent, nil] When C(present), ensures that the profile exists.,When C(absent), ensures the profile is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6928499341011047, "alphanum_fraction": 0.6941927075386047, "avg_line_length": 55.20754623413086, "blob_id": "af450d91239c4176c10f0dda921b3515807cc0cf", "content_id": "e6b4d47d6454cfe3bca58dd361b5600d5a18aa65", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2979, "license_type": "permissive", "max_line_length": 201, "num_lines": 53, "path": "/lib/ansible/ruby/modules/generated/windows/win_domain_controller.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Ensure that a Windows Server 2012+ host is configured as a domain controller or demoted to member server. This module may require subsequent use of the M(win_reboot) action if changes are made.\n class Win_domain_controller < Base\n # @return [String, nil] When C(state) is C(domain_controller), the DNS name of the domain for which the targeted Windows host should be a DC.\n attribute :dns_domain_name\n validates :dns_domain_name, type: String\n\n # @return [String] Username of a domain admin for the target domain (necessary to promote or demote a domain controller).\n attribute :domain_admin_user\n validates :domain_admin_user, presence: true, type: String\n\n # @return [String] Password for the specified C(domain_admin_user).\n attribute :domain_admin_password\n validates :domain_admin_password, presence: true, type: String\n\n # @return [String, nil] Safe mode password for the domain controller (required when C(state) is C(domain_controller)).\n attribute :safe_mode_password\n validates :safe_mode_password, type: String\n\n # @return [String, nil] Password to be assigned to the local C(Administrator) user (required when C(state) is C(member_server)).\n attribute :local_admin_password\n validates :local_admin_password, type: String\n\n # @return [:yes, :no, nil] Whether to install the domain controller as a read only replica for an existing domain.\n attribute :read_only\n validates :read_only, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Specifies the name of an existing site where you can place the new domain controller.,This option is required when I(read_only) is C(yes).\n attribute :site_name\n validates :site_name, type: String\n\n # @return [:domain_controller, :member_server, nil] Whether the target host should be a domain controller or a member server.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:domain_controller, :member_server], :message=>\"%{value} needs to be :domain_controller, :member_server\"}, allow_nil: true\n\n # @return [String, nil] The path to a directory on a fixed disk of the Windows host where the domain database will be created..,If not set then the default path is C(%SYSTEMROOT%\\NTDS).\n attribute :database_path\n validates :database_path, type: String\n\n # @return [String, nil] The path to a directory on a fixed disk of the Windows host where the Sysvol folder will be created.,If not set then the default path is C(%SYSTEMROOT%\\SYSVOL).\n attribute :sysvol_path\n validates :sysvol_path, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6742309927940369, "alphanum_fraction": 0.6742309927940369, "avg_line_length": 40.3125, "blob_id": "f7de2650356863e301c4b94e6be5c8ccf789d43e", "content_id": "bd0d43b6bf4a97943c306459ba04437e851c91c3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1983, "license_type": "permissive", "max_line_length": 143, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_aks.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and delete a managed Azure Container Service (AKS) Instance.\n class Azure_rm_aks < Base\n # @return [String] Name of a resource group where the managed Azure Container Services (AKS) exists or will be created.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] Name of the managed Azure Container Services (AKS) instance.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, nil] Assert the state of the AKS. Use C(present) to create or update an AKS and C(absent) to delete it.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] Valid azure location. Defaults to location of the resource group.\n attribute :location\n validates :location, type: String\n\n # @return [String, nil] DNS prefix specified when creating the managed cluster.\n attribute :dns_prefix\n validates :dns_prefix, type: String\n\n # @return [Object, nil] Version of Kubernetes specified when creating the managed cluster.\n attribute :kubernetes_version\n\n # @return [Hash, nil] The linux profile suboptions.\n attribute :linux_profile\n validates :linux_profile, type: Hash\n\n # @return [Array<Hash>, Hash, nil] The agent pool profile suboptions.\n attribute :agent_pool_profiles\n validates :agent_pool_profiles, type: TypeGeneric.new(Hash)\n\n # @return [Hash, nil] The service principal suboptions.\n attribute :service_principal\n validates :service_principal, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6774193644523621, "alphanum_fraction": 0.6782682538032532, "avg_line_length": 39.620689392089844, "blob_id": "e21dc94455a9c9203daeebfa9f838e18f437b74d", "content_id": "65cb99e1240bf41f1ee7b4afe9e2644728c92b9a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1178, "license_type": "permissive", "max_line_length": 188, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/network/panos/panos_interface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Configure data-port (DP) network interface for DHCP. By default DP interfaces are static.\n class Panos_interface < Base\n # @return [String] Name of the interface to configure.\n attribute :if_name\n validates :if_name, presence: true, type: String\n\n # @return [String] Name of the zone for the interface. If the zone does not exist it is created but if the zone exists and it is not of the layer3 type the operation will fail.\\r\\n\n attribute :zone_name\n validates :zone_name, presence: true, type: String\n\n # @return [String, nil] Whether or not to add default route with router learned via DHCP.\n attribute :create_default_route\n validates :create_default_route, type: String\n\n # @return [Boolean, nil] Commit if changed\n attribute :commit\n validates :commit, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6615853905677795, "alphanum_fraction": 0.6644163727760315, "avg_line_length": 44.01960754394531, "blob_id": "d9deb27c3161846ff6e4d0f0c147169bb4f8ed04", "content_id": "9cd8a1bf0dd1b755aed7f8ff4ce6d26764055c92", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4592, "license_type": "permissive", "max_line_length": 187, "num_lines": 102, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_network.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, restart and delete networks.\n class Cs_network < Base\n # @return [String] Name (case sensitive) of the network.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Display text of the network.,If not specified, C(name) will be used as C(display_text).\n attribute :display_text\n validates :display_text, type: String\n\n # @return [String, nil] Name of the offering for the network.,Required if C(state=present).\n attribute :network_offering\n validates :network_offering, type: String\n\n # @return [Object, nil] The beginning IPv4 address of the network belongs to.,Only considered on create.\n attribute :start_ip\n\n # @return [Object, nil] The ending IPv4 address of the network belongs to.,If not specified, value of C(start_ip) is used.,Only considered on create.\n attribute :end_ip\n\n # @return [String, nil] The gateway of the network.,Required for shared networks and isolated networks when it belongs to a VPC.,Only considered on create.\n attribute :gateway\n validates :gateway, type: String\n\n # @return [String, nil] The netmask of the network.,Required for shared networks and isolated networks when it belongs to a VPC.,Only considered on create.\n attribute :netmask\n validates :netmask, type: String\n\n # @return [Object, nil] The beginning IPv6 address of the network belongs to.,Only considered on create.\n attribute :start_ipv6\n\n # @return [Object, nil] The ending IPv6 address of the network belongs to.,If not specified, value of C(start_ipv6) is used.,Only considered on create.\n attribute :end_ipv6\n\n # @return [Object, nil] CIDR of IPv6 network, must be at least /64.,Only considered on create.\n attribute :cidr_ipv6\n\n # @return [Object, nil] The gateway of the IPv6 network.,Required for shared networks.,Only considered on create.\n attribute :gateway_ipv6\n\n # @return [Object, nil] The ID or VID of the network.\n attribute :vlan\n\n # @return [String, nil] Name of the VPC of the network.\n attribute :vpc\n validates :vpc, type: String\n\n # @return [Object, nil] The isolated private VLAN for this network.\n attribute :isolated_pvlan\n\n # @return [Symbol, nil] Cleanup old network elements.,Only considered on C(state=restarted).\n attribute :clean_up\n validates :clean_up, type: Symbol\n\n # @return [:account, :domain, nil] Access control type for the VPC network tier.,Only considered on create.\n attribute :acl_type\n validates :acl_type, expression_inclusion: {:in=>[:account, :domain], :message=>\"%{value} needs to be :account, :domain\"}, allow_nil: true\n\n # @return [String, nil] The name of the access control list for the VPC network tier.\n attribute :acl\n validates :acl, type: String\n\n # @return [Symbol, nil] Defines whether to allow subdomains to use networks dedicated to their parent domain(s).,Should be used with C(acl_type=domain).,Only considered on create.\n attribute :subdomain_access\n validates :subdomain_access, type: Symbol\n\n # @return [String, nil] The network domain.\n attribute :network_domain\n validates :network_domain, type: String\n\n # @return [:present, :absent, :restarted, nil] State of the network.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :restarted], :message=>\"%{value} needs to be :present, :absent, :restarted\"}, allow_nil: true\n\n # @return [String, nil] Name of the zone in which the network should be deployed.,If not set, default zone is used.\n attribute :zone\n validates :zone, type: String\n\n # @return [Object, nil] Name of the project the network to be deployed in.\n attribute :project\n\n # @return [Object, nil] Domain the network is related to.\n attribute :domain\n\n # @return [Object, nil] Account the network is related to.\n attribute :account\n\n # @return [Boolean, nil] Poll async jobs until job has finished.\n attribute :poll_async\n validates :poll_async, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7038905024528503, "alphanum_fraction": 0.7038905024528503, "avg_line_length": 46.86206817626953, "blob_id": "8e4e064f67fb62b345876a9b14398eb05b9d3233", "content_id": "e6d4c70627c6d7329f56f2ecd964e71c111e9eb2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1388, "license_type": "permissive", "max_line_length": 336, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/files/tempfile.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The C(tempfile) module creates temporary files and directories. C(mktemp) command takes different parameters on various systems, this module helps to avoid troubles related to that. Files/directories created by module are accessible only by creator. In case you need to make them world-accessible you need to use M(file) module.\n # For Windows targets, use the M(win_tempfile) module instead.\n class Tempfile < Base\n # @return [:directory, :file, nil] Whether to create file or directory.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:directory, :file], :message=>\"%{value} needs to be :directory, :file\"}, allow_nil: true\n\n # @return [Object, nil] Location where temporary file or directory should be created. If path is not specified default system temporary directory will be used.\n attribute :path\n\n # @return [String, nil] Prefix of file/directory name created by module.\n attribute :prefix\n validates :prefix, type: String\n\n # @return [String, nil] Suffix of file/directory name created by module.\n attribute :suffix\n validates :suffix, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6754428148269653, "alphanum_fraction": 0.6802297830581665, "avg_line_length": 53.97368240356445, "blob_id": "445b0e19fea10084223275312add6c1c7b737a8d", "content_id": "e3caaf746ec46170b77cb7fcf9af0329fc3dcbd9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2089, "license_type": "permissive", "max_line_length": 344, "num_lines": 38, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/htpasswd.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add and remove username/password entries in a password file using htpasswd.\n # This is used by web servers such as Apache and Nginx for basic authentication.\n class Htpasswd < Base\n # @return [String] Path to the file that contains the usernames and passwords\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [String] User name to add or remove\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Password associated with user.,Must be specified if user does not exist yet.\n attribute :password\n validates :password, type: String\n\n # @return [:apr_md5_crypt, :des_crypt, :ldap_sha1, :plaintext, nil] Encryption scheme to be used. As well as the four choices listed here, you can also use any other hash supported by passlib, such as md5_crypt and sha256_crypt, which are linux passwd hashes. If you do so the password file will not be compatible with Apache or Nginx\n attribute :crypt_scheme\n validates :crypt_scheme, expression_inclusion: {:in=>[:apr_md5_crypt, :des_crypt, :ldap_sha1, :plaintext], :message=>\"%{value} needs to be :apr_md5_crypt, :des_crypt, :ldap_sha1, :plaintext\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Whether the user entry should be present or not\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Used with C(state=present). If specified, the file will be created if it does not already exist. If set to \"no\", will fail if the file does not exist\n attribute :create\n validates :create, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7318231463432312, "alphanum_fraction": 0.7336499691009521, "avg_line_length": 79.5, "blob_id": "564d499203eb148c8370b81d245b70492cef67fb", "content_id": "dec9685d3cd484a1cc14135e92d736d8d6126e59", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2737, "license_type": "permissive", "max_line_length": 340, "num_lines": 34, "path": "/lib/ansible/ruby/modules/generated/network/vyos/vyos_command.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The command module allows running one or more commands on remote devices running VyOS. This module can also be introspected to validate key parameters before returning successfully. If the conditional statements are not met in the wait period, the task fails.\n # Certain C(show) commands in VyOS produce many lines of output and use a custom pager that can cause this module to hang. If the value of the environment variable C(ANSIBLE_VYOS_TERMINAL_LENGTH) is not set, the default number of 10000 is used.\n class Vyos_command < Base\n # @return [Array<String>, String] The ordered set of commands to execute on the remote device running VyOS. The output from the command execution is returned to the playbook. If the I(wait_for) argument is provided, the module is not returned until the condition is satisfied or the number of retries has been exceeded.\n attribute :commands\n validates :commands, presence: true, type: TypeGeneric.new(String, Hash)\n\n # @return [Array<String>, String, nil] Specifies what to evaluate from the output of the command and what conditionals to apply. This argument will cause the task to wait for a particular conditional to be true before moving forward. If the conditional is not true by the configured I(retries), the task fails. See examples.\n attribute :wait_for\n validates :wait_for, type: TypeGeneric.new(String)\n\n # @return [:any, :all, nil] The I(match) argument is used in conjunction with the I(wait_for) argument to specify the match policy. Valid values are C(all) or C(any). If the value is set to C(all) then all conditionals in the wait_for must be satisfied. If the value is set to C(any) then only one of the values must be satisfied.\n attribute :match\n validates :match, expression_inclusion: {:in=>[:any, :all], :message=>\"%{value} needs to be :any, :all\"}, allow_nil: true\n\n # @return [Integer, nil] Specifies the number of retries a command should be tried before it is considered failed. The command is run on the target device every retry and evaluated against the I(wait_for) conditionals.\n attribute :retries\n validates :retries, type: Integer\n\n # @return [Integer, nil] Configures the interval in seconds to wait between I(retries) of the command. If the command does not pass the specified conditions, the interval indicates how long to wait before trying the command again.\n attribute :interval\n validates :interval, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7084639668464661, "alphanum_fraction": 0.7084639668464661, "avg_line_length": 52.16666793823242, "blob_id": "e98207cc4e1d9c6e47a9a1d984cff46cbbe02822", "content_id": "5ff2993f336ab8da52c59c6c25135420c73029d6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1595, "license_type": "permissive", "max_line_length": 372, "num_lines": 30, "path": "/lib/ansible/ruby/modules/generated/cloud/opennebula/one_image_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gather facts about OpenNebula images\n class One_image_facts < Base\n # @return [Object, nil] URL of the OpenNebula RPC server.,It is recommended to use HTTPS so that the username/password are not,transferred over the network unencrypted.,If not set then the value of the C(ONE_URL) environment variable is used.\n attribute :api_url\n\n # @return [Object, nil] Name of the user to login into the OpenNebula RPC server. If not set,then the value of the C(ONE_USERNAME) environment variable is used.\n attribute :api_username\n\n # @return [Object, nil] Password of the user to login into OpenNebula RPC server. If not set,then the value of the C(ONE_PASSWORD) environment variable is used.\n attribute :api_password\n\n # @return [Array<Integer>, Integer, nil] A list of images ids whose facts you want to gather.\n attribute :ids\n validates :ids, type: TypeGeneric.new(Integer)\n\n # @return [String, nil] A C(name) of the image whose facts will be gathered.,If the C(name) begins with '~' the C(name) will be used as regex pattern,which restricts the list of images (whose facts will be returned) whose names match specified regex.,Also, if the C(name) begins with '~*' case-insensitive matching will be performed.,See examples for more details.\n attribute :name\n validates :name, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6977724432945251, "alphanum_fraction": 0.6977724432945251, "avg_line_length": 50.90625, "blob_id": "c6a72a75366fed5d35fcad4489aca9225da381dd", "content_id": "6aaf21419520505be5b2fbb4230bf70999ccf27e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1661, "license_type": "permissive", "max_line_length": 337, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/identity/ipa/ipa_hostgroup.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add, modify and delete an IPA host-group using IPA API\n class Ipa_hostgroup < Base\n # @return [Object] Name of host-group.,Can not be changed as it is the unique identifier.\n attribute :cn\n validates :cn, presence: true\n\n # @return [Object, nil] Description\n attribute :description\n\n # @return [Array<String>, String, nil] List of hosts that belong to the host-group.,If an empty list is passed all hosts will be removed from the group.,If option is omitted hosts will not be checked or changed.,If option is passed all assigned hosts that are not passed will be unassigned from the group.\n attribute :host\n validates :host, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] List of host-groups than belong to that host-group.,If an empty list is passed all host-groups will be removed from the group.,If option is omitted host-groups will not be checked or changed.,If option is passed all assigned hostgroups that are not passed will be unassigned from the group.\n attribute :hostgroup\n validates :hostgroup, type: TypeGeneric.new(String)\n\n # @return [:present, :absent, :enabled, :disabled, nil] State to ensure.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :enabled, :disabled], :message=>\"%{value} needs to be :present, :absent, :enabled, :disabled\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6631844639778137, "alphanum_fraction": 0.670749306678772, "avg_line_length": 51.377357482910156, "blob_id": "c75038b8214a498b41f06f9e4e14e572618fe7e3", "content_id": "671c7511d0102f30374c52e136b85ad2f875cf9e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2776, "license_type": "permissive", "max_line_length": 254, "num_lines": 53, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_ami_copy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Copies AMI from a source region to a destination region. B(Since version 2.3 this module depends on boto3.)\n class Ec2_ami_copy < Base\n # @return [String] The source region the AMI should be copied from.\n attribute :source_region\n validates :source_region, presence: true, type: String\n\n # @return [String] The ID of the AMI in source region that should be copied.\n attribute :source_image_id\n validates :source_image_id, presence: true, type: String\n\n # @return [String, nil] The name of the new AMI to copy. (As of 2.3 the default is 'default', in prior versions it was 'null'.)\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] An optional human-readable string describing the contents and purpose of the new AMI.\n attribute :description\n validates :description, type: String\n\n # @return [Boolean, nil] Whether or not the destination snapshots of the copied AMI should be encrypted.\n attribute :encrypted\n validates :encrypted, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] KMS key id used to encrypt image. If not specified, uses default EBS Customer Master Key (CMK) for your account.\n attribute :kms_key_id\n validates :kms_key_id, type: String\n\n # @return [:yes, :no, nil] Wait for the copied AMI to be in state 'available' before returning.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] How long before wait gives up, in seconds. Prior to 2.3 the default was 1200.,From 2.3-2.5 this option was deprecated in favor of boto3 waiter defaults. This was reenabled in 2.6 to allow timeouts greater than 10 minutes.\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [Hash, nil] A hash/dictionary of tags to add to the new copied AMI; '{\"key\":\"value\"}' and '{\"key\":\"value\",\"key\":\"value\"}'\n attribute :tags\n validates :tags, type: Hash\n\n # @return [Boolean, nil] Whether to use tags if the source AMI already exists in the target region. If this is set, and all tags match in an existing AMI, the AMI will not be copied again.\n attribute :tag_equality\n validates :tag_equality, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6464380025863647, "alphanum_fraction": 0.6534740328788757, "avg_line_length": 42.730770111083984, "blob_id": "29bf206b9c7475f9bd23a8354be03020ecabe1db", "content_id": "ba1668ab0d1d5862d237baf5467da23ed0a167b2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2274, "license_type": "permissive", "max_line_length": 161, "num_lines": 52, "path": "/lib/ansible/ruby/modules/generated/cloud/oneandone/oneandone_public_ip.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, and remove public IPs. This module has a dependency on 1and1 >= 1.0\n class Oneandone_public_ip < Base\n # @return [:present, :absent, :update, nil] Define a public ip state to create, remove, or update.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :update], :message=>\"%{value} needs to be :present, :absent, :update\"}, allow_nil: true\n\n # @return [String] Authenticating API token provided by 1&1.\n attribute :auth_token\n validates :auth_token, presence: true, type: String\n\n # @return [Object, nil] Custom API URL. Overrides the ONEANDONE_API_URL environement variable.\n attribute :api_url\n\n # @return [String, nil] Reverse DNS name. maxLength=256\n attribute :reverse_dns\n validates :reverse_dns, type: String\n\n # @return [String, nil] ID of the datacenter where the IP will be created (only for unassigned IPs).\n attribute :datacenter\n validates :datacenter, type: String\n\n # @return [:IPV4, :IPV6, nil] Type of IP. Currently, only IPV4 is available.\n attribute :type\n validates :type, expression_inclusion: {:in=>[:IPV4, :IPV6], :message=>\"%{value} needs to be :IPV4, :IPV6\"}, allow_nil: true\n\n # @return [String] The ID of the public IP used with update and delete states.\n attribute :public_ip_id\n validates :public_ip_id, presence: true, type: String\n\n # @return [:yes, :no, nil] wait for the instance to be in state 'running' before returning\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] how long before wait gives up, in seconds\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [Integer, nil] Defines the number of seconds to wait when using the _wait_for methods\n attribute :wait_interval\n validates :wait_interval, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6768594980239868, "alphanum_fraction": 0.6768594980239868, "avg_line_length": 47.400001525878906, "blob_id": "cea058e15b29e236dba3269ec506a7794dee7728", "content_id": "42f6538e79cd37e83f06bace37e6956e3a30fa1e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1210, "license_type": "permissive", "max_line_length": 212, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/system/awall.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This modules allows for enable/disable/activate of I(awall) policies. Alpine Wall (I(awall)) generates a firewall configuration from the enabled policy files and activates the configuration on the system.\n class Awall < Base\n # @return [Array<String>, String, nil] A policy name, like C(foo), or multiple policies, like C(foo, bar).\n attribute :name\n validates :name, type: TypeGeneric.new(String)\n\n # @return [:enabled, :disabled, nil] The policy(ies) will be C(enabled),The policy(ies) will be C(disabled)\n attribute :state\n validates :state, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Activate the new firewall rules. Can be run with other steps or on it's own.\n attribute :activate\n validates :activate, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6835442781448364, "alphanum_fraction": 0.6835442781448364, "avg_line_length": 43.83783721923828, "blob_id": "ea99046a5da7c066a147c8e11b866e24ca9ee222", "content_id": "a51399ed1a6cf4068c1f4dd128da1327fe8539b9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1659, "license_type": "permissive", "max_line_length": 214, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcdns_zone.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates or removes managed zones in Google Cloud DNS.\n class Gcdns_zone < Base\n # @return [:present, :absent, nil] Whether the given zone should or should not be present.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The DNS domain name of the zone.,This is NOT the Google Cloud DNS zone ID (e.g., example-com). If you attempt to specify a zone ID, this module will attempt to create a TLD and will fail.\n attribute :zone\n validates :zone, presence: true, type: String\n\n # @return [String, nil] An arbitrary text string to use for the zone description.\n attribute :description\n validates :description, type: String\n\n # @return [Object, nil] The e-mail address for a service account with access to Google Cloud DNS.\n attribute :service_account_email\n\n # @return [Object, nil] The path to the PEM file associated with the service account email.,This option is deprecated and may be removed in a future release. Use I(credentials_file) instead.\n attribute :pem_file\n\n # @return [Object, nil] The path to the JSON file associated with the service account email.\n attribute :credentials_file\n\n # @return [Object, nil] The Google Cloud Platform project ID to use.\n attribute :project_id\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7013698816299438, "alphanum_fraction": 0.7035616636276245, "avg_line_length": 56.03125, "blob_id": "2f3202fb13f178dee37f91668c5a35e158974d29", "content_id": "39660188e290c032cf8ed004acdb7126fbb21f46", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1825, "license_type": "permissive", "max_line_length": 575, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_firewall_rule_list.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages AFM security firewall policies on a BIG-IP.\n class Bigip_firewall_rule_list < Base\n # @return [String] The name of the policy to create.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] The description to attach to the policy.,This parameter is only supported on versions of BIG-IP >= 12.1.0. On earlier versions it will simply be ignored.\n attribute :description\n\n # @return [:present, :absent, nil] When C(state) is C(present), ensures that the rule list exists.,When C(state) is C(absent), ensures that the rule list is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] Specifies a list of rules that you want associated with this policy. The order of this list is the order they will be evaluated by BIG-IP. If the specified rules do not exist (for example when creating a new policy) then they will be created.,Rules specified here, if they do not exist, will be created with \"default deny\" behavior. It is expected that you follow-up this module with the actual configuration for these rules.,The C(bigip_firewall_rule) module can be used to also create, as well as edit, existing and new rules.\n attribute :rules\n validates :rules, type: TypeGeneric.new(String)\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6703928709030151, "alphanum_fraction": 0.672309160232544, "avg_line_length": 51.18333435058594, "blob_id": "f39ba01755f2e86030e4372c1f4b43d091959dd7", "content_id": "5db846f844bd8868f8a333e10890a6925195e70c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3131, "license_type": "permissive", "max_line_length": 215, "num_lines": 60, "path": "/lib/ansible/ruby/modules/generated/notification/rocketchat.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The C(rocketchat) module sends notifications to Rocket Chat via the Incoming WebHook integration\n class Rocketchat < Base\n # @return [String] The domain for your environment without protocol. (i.e. C(example.com) or C(chat.example.com))\n attribute :domain\n validates :domain, presence: true, type: String\n\n # @return [String] Rocket Chat Incoming Webhook integration token. This provides authentication to Rocket Chat's Incoming webhook for posting messages.\n attribute :token\n validates :token, presence: true, type: String\n\n # @return [:http, :https, nil] Specify the protocol used to send notification messages before the webhook url. (i.e. http or https)\n attribute :protocol\n validates :protocol, expression_inclusion: {:in=>[:http, :https], :message=>\"%{value} needs to be :http, :https\"}, allow_nil: true\n\n # @return [String, nil] Message to be sent.\n attribute :msg\n validates :msg, type: String\n\n # @return [NilClass, nil] Channel to send the message to. If absent, the message goes to the channel selected for the I(token) specified during the creation of webhook.\n attribute :channel\n validates :channel, type: NilClass\n\n # @return [String, nil] This is the sender of the message.\n attribute :username\n validates :username, type: String\n\n # @return [String, nil] URL for the message sender's icon.\n attribute :icon_url\n validates :icon_url, type: String\n\n # @return [Object, nil] Emoji for the message sender. The representation for the available emojis can be got from Rocket Chat. (for example :thumbsup:) (if I(icon_emoji) is set, I(icon_url) will not be used)\n attribute :icon_emoji\n\n # @return [1, 0, nil] Automatically create links for channels and usernames in I(msg).\n attribute :link_names\n validates :link_names, expression_inclusion: {:in=>[1, 0], :message=>\"%{value} needs to be 1, 0\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:normal, :good, :warning, :danger, nil] Allow text to use default colors - use the default of 'normal' to not send a custom color bar at the start of the message\n attribute :color\n validates :color, expression_inclusion: {:in=>[:normal, :good, :warning, :danger], :message=>\"%{value} needs to be :normal, :good, :warning, :danger\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash, nil] Define a list of attachments.\n attribute :attachments\n validates :attachments, type: TypeGeneric.new(Hash)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.686302661895752, "alphanum_fraction": 0.686302661895752, "avg_line_length": 53.94736862182617, "blob_id": "68b697761817bd498652d115b7d8898be902c37a", "content_id": "7ee9a04d2d9327465c29b951e4c205da3f2e9fca", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2088, "license_type": "permissive", "max_line_length": 402, "num_lines": 38, "path": "/lib/ansible/ruby/modules/generated/system/interfaces_file.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage (add, remove, change) individual interface options in an interfaces-style file without having to manage the file as a whole with, say, M(template) or M(assemble). Interface has to be presented in a file.\n # Read information about interfaces from interfaces-styled files\n class Interfaces_file < Base\n # @return [String, nil] Path to the interfaces file\n attribute :dest\n validates :dest, type: String\n\n # @return [String, nil] Name of the interface, required for value changes or option remove\n attribute :iface\n validates :iface, type: String\n\n # @return [String, nil] Name of the option, required for value changes or option remove\n attribute :option\n validates :option, type: String\n\n # @return [Integer, nil] If I(option) is not presented for the I(interface) and I(state) is C(present) option will be added. If I(option) already exists and is not C(pre-up), C(up), C(post-up) or C(down), it's value will be updated. C(pre-up), C(up), C(post-up) and C(down) options can't be updated, only adding new options, removing existing ones or cleaning the whole option set are supported\n attribute :value\n validates :value, type: Integer\n\n # @return [:yes, :no, nil] Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.\n attribute :backup\n validates :backup, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, nil] If set to C(absent) the option or section will be removed if present instead of created.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7218284606933594, "alphanum_fraction": 0.7218284606933594, "avg_line_length": 61.71111297607422, "blob_id": "6c054641278bee014d59dfe45a26638868db9b3e", "content_id": "36ef680a0497a4f7cbf40c6ea29ef32658df29ab", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2822, "license_type": "permissive", "max_line_length": 579, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/netapp_e_amg_sync.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows for the initialization, suspension and resumption of an asynchronous mirror group's synchronization for NetApp E-series storage arrays.\n class Netapp_e_amg_sync < Base\n # @return [String] The username to authenticate with the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_username\n validates :api_username, presence: true, type: String\n\n # @return [String] The password to authenticate with the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_password\n validates :api_password, presence: true, type: String\n\n # @return [String] The url to the SANtricity WebServices Proxy or embedded REST API.\n attribute :api_url\n validates :api_url, presence: true, type: String\n\n # @return [Boolean, nil] Should https certificates be validated?\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] The ID of the storage array containing the AMG you wish to target\n attribute :ssid\n validates :ssid, type: String\n\n # @return [String] The name of the async mirror group you wish to target\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:running, :suspended] The synchronization action you'd like to take.,If C(running) then it will begin syncing if there is no active sync or will resume a suspended sync. If there is already a sync in progress, it will return with an OK status.,If C(suspended) it will suspend any ongoing sync action, but return OK if there is no active sync or if the sync is already suspended\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:running, :suspended], :message=>\"%{value} needs to be :running, :suspended\"}\n\n # @return [Symbol, nil] Indicates whether the failures point can be deleted on the secondary if necessary to achieve the synchronization.,If true, and if the amount of unsynchronized data exceeds the CoW repository capacity on the secondary for any member volume, the last failures point will be deleted and synchronization will continue.,If false, the synchronization will be suspended if the amount of unsynchronized data exceeds the CoW Repository capacity on the secondary and the failures point will be preserved.,NOTE: This only has impact for newly launched syncs.\n attribute :delete_recovery_point\n validates :delete_recovery_point, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6813739538192749, "alphanum_fraction": 0.682092547416687, "avg_line_length": 60.03508758544922, "blob_id": "1e57e1a18612cd921e88b0545671273b493ea821", "content_id": "22b7d34184f1797bda1c1572633e525488fdd2c4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6958, "license_type": "permissive", "max_line_length": 476, "num_lines": 114, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_server.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or Remove compute instances from OpenStack.\n class Os_server < Base\n # @return [String] Name that has to be given to the instance. It is also possible to specify the ID of the instance instead of its name if I(state) is I(absent).\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] The name or id of the base image to boot.\n attribute :image\n validates :image, presence: true, type: String\n\n # @return [Object, nil] Text to use to filter image names, for the case, such as HP, where there are multiple image names matching the common identifying portions. image_exclude is a negative match filter - it is text that may not exist in the image name. Defaults to \"(deprecated)\"\n attribute :image_exclude\n\n # @return [Integer, nil] The name or id of the flavor in which the new instance has to be created. Mutually exclusive with flavor_ram\n attribute :flavor\n validates :flavor, type: Integer\n\n # @return [Integer, nil] The minimum amount of ram in MB that the flavor in which the new instance has to be created must have. Mutually exclusive with flavor.\n attribute :flavor_ram\n validates :flavor_ram, type: Integer\n\n # @return [Object, nil] Text to use to filter flavor names, for the case, such as Rackspace, where there are multiple flavors that have the same ram count. flavor_include is a positive match filter - it must exist in the flavor name.\n attribute :flavor_include\n\n # @return [String, nil] The key pair name to be used when creating a instance\n attribute :key_name\n validates :key_name, type: String\n\n # @return [Object, nil] Names of the security groups to which the instance should be added. This may be a YAML list or a comma separated string.\n attribute :security_groups\n\n # @return [String, nil] Name or ID of a network to attach this instance to. A simpler version of the nics parameter, only one of network or nics should be supplied.\n attribute :network\n validates :network, type: String\n\n # @return [Array<Hash>, Hash, nil] A list of networks to which the instance's interface should be attached. Networks may be referenced by net-id/net-name/port-id or port-name.,Also this accepts a string containing a list of (net/port)-(id/name) Eg: nics: \"net-id=uuid-1,port-name=myport\" Only one of network or nics should be supplied.\n attribute :nics\n validates :nics, type: TypeGeneric.new(Hash)\n\n # @return [:yes, :no, nil] Ensure instance has public ip however the cloud wants to do that\n attribute :auto_ip\n validates :auto_ip, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] list of valid floating IPs that pre-exist to assign to this node\n attribute :floating_ips\n\n # @return [Object, nil] Name of floating IP pool from which to choose a floating IP\n attribute :floating_ip_pools\n\n # @return [Hash, Array<String>, String, nil] A list of key value pairs that should be provided as a metadata to the new instance or a string containing a list of key-value pairs. Eg: meta: \"key1=value1,key2=value2\"\n attribute :meta\n validates :meta, type: TypeGeneric.new(String)\n\n # @return [:yes, :no, nil] If the module should wait for the instance to be created.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] The amount of time the module should wait for the instance to get into active state.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [:yes, :no, nil] Whether to boot the server with config drive enabled\n attribute :config_drive\n validates :config_drive, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Opaque blob of data which is made available to the instance\n attribute :userdata\n\n # @return [:yes, :no, nil] Should the instance boot from a persistent volume created based on the image given. Mututally exclusive with boot_volume.\n attribute :boot_from_volume\n validates :boot_from_volume, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] The size of the volume to create in GB if booting from volume based on an image.\n attribute :volume_size\n\n # @return [Object, nil] Volume name or id to use as the volume to boot from. Implies boot_from_volume. Mutually exclusive with image and boot_from_volume.\n attribute :boot_volume\n\n # @return [:yes, :no, nil] If C(yes), delete volume when deleting instance (if booted from volume)\n attribute :terminate_volume\n validates :terminate_volume, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] A list of preexisting volumes names or ids to attach to the instance\n attribute :volumes\n\n # @return [Object, nil] Arbitrary key/value pairs to the scheduler for custom use\n attribute :scheduler_hints\n\n # @return [:present, :absent, nil] Should the resource be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:yes, :no, nil] When I(state) is absent and this option is true, any floating IP associated with the instance will be deleted along with the instance.\n attribute :delete_fip\n validates :delete_fip, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] When I(auto_ip) is true and this option is true, the I(auto_ip) code will attempt to re-use unassigned floating ips in the project before creating a new one. It is important to note that it is impossible to safely do this concurrently, so if your use case involves concurrent server creation, it is highly recommended to set this to false and to delete the floating ip associated with a server when the server is deleted using I(delete_fip).\n attribute :reuse_ips\n validates :reuse_ips, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Availability zone in which to create the server.\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6871291399002075, "alphanum_fraction": 0.6893799901008606, "avg_line_length": 58.59756088256836, "blob_id": "32f31a9fca649df1bf00662141ee3bec1e572852", "content_id": "020d6680b8d98d864a578fcfbdb9c8b2f0ab68dd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4887, "license_type": "permissive", "max_line_length": 367, "num_lines": 82, "path": "/lib/ansible/ruby/modules/generated/network/netscaler/netscaler_nitro_request.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Issue Nitro API requests to a Netscaler instance.\n # This is intended to be a short hand for using the uri Ansible module to issue the raw HTTP requests directly.\n # It provides consistent return values and has no other dependencies apart from the base Ansible runtime environment.\n # This module is intended to run either on the Ansible control node or a bastion (jumpserver) with access to the actual Netscaler instance\n class Netscaler_nitro_request < Base\n # @return [String, nil] The IP address of the Netscaler or MAS instance where the Nitro API calls will be made.,The port can be specified with the colon C(:). E.g. C(192.168.1.1:555).\n attribute :nsip\n validates :nsip, type: String\n\n # @return [String] The username with which to authenticate to the Netscaler node.\n attribute :nitro_user\n validates :nitro_user, presence: true, type: String\n\n # @return [String] The password with which to authenticate to the Netscaler node.\n attribute :nitro_pass\n validates :nitro_pass, presence: true, type: String\n\n # @return [:http, :https, nil] Which protocol to use when accessing the Nitro API objects.\n attribute :nitro_protocol\n validates :nitro_protocol, expression_inclusion: {:in=>[:http, :https], :message=>\"%{value} needs to be :http, :https\"}, allow_nil: true\n\n # @return [String, nil] If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, type: String\n\n # @return [String, nil] The authentication token provided by the C(mas_login) operation. It is required when issuing Nitro API calls through a MAS proxy.\n attribute :nitro_auth_token\n validates :nitro_auth_token, type: String\n\n # @return [String, nil] The type of resource we are operating on.,It is required for all I(operation) values except C(mas_login) and C(save_config).\n attribute :resource\n validates :resource, type: String\n\n # @return [String, nil] The name of the resource we are operating on.,It is required for the following I(operation) values: C(update), C(get), C(delete).\n attribute :name\n validates :name, type: String\n\n # @return [Hash, nil] The attributes of the Nitro object we are operating on.,It is required for the following I(operation) values: C(add), C(update), C(action).\n attribute :attributes\n validates :attributes, type: Hash\n\n # @return [Hash, nil] A dictionary which defines the key arguments by which we will select the Nitro object to operate on.,It is required for the following I(operation) values: C(get_by_args), C('delete_by_args').\n attribute :args\n validates :args, type: Hash\n\n # @return [Hash, nil] A dictionary which defines the filter with which to refine the Nitro objects returned by the C(get_filtered) I(operation).\n attribute :filter\n validates :filter, type: Hash\n\n # @return [:add, :update, :get, :get_by_args, :get_filtered, :get_all, :delete, :delete_by_args, :count, :mas_login, :save_config, :action, nil] Define the Nitro operation that we want to perform.\n attribute :operation\n validates :operation, expression_inclusion: {:in=>[:add, :update, :get, :get_by_args, :get_filtered, :get_all, :delete, :delete_by_args, :count, :mas_login, :save_config, :action], :message=>\"%{value} needs to be :add, :update, :get, :get_by_args, :get_filtered, :get_all, :delete, :delete_by_args, :count, :mas_login, :save_config, :action\"}, allow_nil: true\n\n # @return [Integer] A list of numeric values that signify that the operation was successful.\n attribute :expected_nitro_errorcode\n validates :expected_nitro_errorcode, presence: true, type: Integer\n\n # @return [String, nil] The action to perform when the I(operation) value is set to C(action).,Some common values for this parameter are C(enable), C(disable), C(rename).\n attribute :action\n validates :action, type: String\n\n # @return [String, nil] The IP address of the target Netscaler instance when issuing a Nitro request through a MAS proxy.\n attribute :instance_ip\n validates :instance_ip, type: String\n\n # @return [Object, nil] The name of the target Netscaler instance when issuing a Nitro request through a MAS proxy.\n attribute :instance_name\n\n # @return [Object, nil] The id of the target Netscaler instance when issuing a Nitro request through a MAS proxy.\n attribute :instance_id\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5427334904670715, "alphanum_fraction": 0.5430940985679626, "avg_line_length": 29.14130401611328, "blob_id": "bbe3f269a9ee3c03eca9e6e984f7cfd141173643", "content_id": "5621dffaeb6fa50ef3809a9dc2dbf8bf3e2e6199", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2773, "license_type": "permissive", "max_line_length": 110, "num_lines": 92, "path": "/lib/ansible/ruby/dsl_builders/file_level.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'ansible/ruby/dsl_builders/play'\nrequire 'ansible/ruby/models/playbook'\nrequire 'ansible/ruby/models/tasks'\n\nmodule Ansible\n module Ruby\n module DslBuilders\n class FileLevel < Base\n def initialize\n @plays = []\n @tasks_builder = nil\n @context = nil\n @includes = []\n end\n\n def play(name = nil, &block)\n _validate_context :playbook\n @context = :playbook\n play_builder = Play.new name\n play_builder.instance_eval(&block)\n @plays << play_builder._result\n end\n\n def task(name, &block)\n _validate_context :tasks\n @context = :tasks\n @tasks_builder ||= Tasks.new(:tasks)\n @tasks_builder.task name, &block\n end\n\n def handler(name, &block)\n _validate_context :handlers\n @context = :handlers\n @tasks_builder ||= Tasks.new(:handlers)\n @tasks_builder.handler name, &block\n end\n\n def ansible_include(filename, &block)\n @includes << _ansible_include(filename, &block)\n end\n\n def _handled_eval(ruby_filename)\n ruby_code = File.read ruby_filename\n instance_eval ruby_code, ruby_filename\n # error code\n nil\n rescue StandardError => e\n only_user_code = e.backtrace_locations\n .select { |trace| trace.absolute_path == ruby_filename }\n .map { |trace| format_trace_line(trace) }\n message = \"#{e.message}\\n****Error Location:****\\n#{only_user_code.join(\"\\n\")}\"\n Exception.new message\n end\n\n def format_trace_line(trace)\n \"#{trace.path}:#{trace.lineno}\"\n end\n\n # any order/lazy result\n # :reek:NilCheck - when nil is the simplest way to check this\n def _result\n case @context\n when :playbook\n # TODO: Add a playbook DSL and do this like tasks\n Models::Playbook.new plays: @plays,\n inclusions: @includes\n when :tasks, :handlers\n tasks_model = @tasks_builder._result\n tasks_model.inclusions += @includes\n tasks_model\n when nil\n raise 'Must supply at least 1 handler/task/play!'\n else\n raise \"Unknown context #{@context}\"\n end\n end\n\n def _process_method(id, *)\n no_method_error id, 'Only valid options are [:task, :handler, :play]'\n end\n\n private\n\n def _validate_context(expected)\n raise \"This is a #{@context} file, cannot use #{expected} here!\" if @context && @context != expected\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7313476800918579, "alphanum_fraction": 0.7313476800918579, "avg_line_length": 79.73809814453125, "blob_id": "04dec2836faac299e7324b8874d1e133ca0b67df", "content_id": "a1583b1637119ce311520c3e8ce02aac771c5bc9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3391, "license_type": "permissive", "max_line_length": 355, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of the local usernames configured on Cisco Nexus devices. It allows playbooks to manage either individual usernames or the collection of usernames in the current running config. It also supports purging usernames from the configuration that are not explicitly defined.\n class Nxos_user < Base\n # @return [Object, nil] The set of username objects to be configured on the remote Cisco Nexus device. The list entries can either be the username or a hash of username and properties. This argument is mutually exclusive with the C(name) argument.\n attribute :aggregate\n\n # @return [String, nil] The username to be configured on the remote Cisco Nexus device. This argument accepts a string value and is mutually exclusive with the C(aggregate) argument.\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] The password to be configured on the network device. The password needs to be provided in cleartext and it will be encrypted on the device. Please note that this option is not same as C(provider password).\n attribute :configured_password\n\n # @return [:on_create, :always, nil] Since passwords are encrypted in the device running config, this argument will instruct the module when to change the password. When set to C(always), the password will always be updated in the device and when set to C(on_create) the password will be updated only if the username is created.\n attribute :update_password\n validates :update_password, expression_inclusion: {:in=>[:on_create, :always], :message=>\"%{value} needs to be :on_create, :always\"}, allow_nil: true\n\n # @return [Object, nil] The C(role) argument configures the role for the username in the device running configuration. The argument accepts a string value defining the role name. This argument does not check if the role has been configured on the device.\n attribute :role\n\n # @return [String, nil] The C(sshkey) argument defines the SSH public key to configure for the username. This argument accepts a valid SSH key value.\n attribute :sshkey\n validates :sshkey, type: String\n\n # @return [:yes, :no, nil] The C(purge) argument instructs the module to consider the resource definition absolute. It will remove any previously configured usernames on the device with the exception of the `admin` user which cannot be deleted per nxos constraints.\n attribute :purge\n validates :purge, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, nil] The C(state) argument configures the state of the username definition as it relates to the device operational configuration. When set to I(present), the username(s) should be configured in the device active configuration and when set to I(absent) the username(s) should not be in the device active configuration\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.665859580039978, "alphanum_fraction": 0.665859580039978, "avg_line_length": 32.486488342285156, "blob_id": "d45032d193ff0c4b1bf8b7d856aa5fddcb947ba9", "content_id": "fb79ce250b6c7490dde0621aff842d68709be9b2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1239, "license_type": "permissive", "max_line_length": 116, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/cloudformation_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gets information about an AWS CloudFormation stack\n class Cloudformation_facts < Base\n # @return [String, nil] The name or id of the CloudFormation stack. Gathers facts for all stacks by default.\n attribute :stack_name\n validates :stack_name, type: String\n\n # @return [String, nil] Get all stack information for the stack\n attribute :all_facts\n validates :all_facts, type: String\n\n # @return [String, nil] Get stack events for the stack\n attribute :stack_events\n validates :stack_events, type: String\n\n # @return [String, nil] Get stack template body for the stack\n attribute :stack_template\n validates :stack_template, type: String\n\n # @return [String, nil] Get stack resources for the stack\n attribute :stack_resources\n validates :stack_resources, type: String\n\n # @return [String, nil] Get stack policy for the stack\n attribute :stack_policy\n validates :stack_policy, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6445901393890381, "alphanum_fraction": 0.6445901393890381, "avg_line_length": 40.216217041015625, "blob_id": "cd1617af1c538ebbfff47f9c034a52adfb8a16da", "content_id": "4a0c6de689fa971e032bdf5c028fe9aeb2c86fc0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1525, "license_type": "permissive", "max_line_length": 143, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/storage/purestorage/purefa_volume.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, delete or extend the capacity of a volume on Pure Storage FlashArray.\n class Purefa_volume < Base\n # @return [String] The name of the volume.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The name of the target volume, if copying.\n attribute :target\n validates :target, type: String\n\n # @return [:absent, :present, nil] Define whether the volume should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Define whether to eradicate the volume on delete or leave in trash.\n attribute :eradicate\n validates :eradicate, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Define whether to overwrite a target volume if it already exisits.\n attribute :overwrite\n validates :overwrite, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Volume size in M, G, T or P units.\n attribute :size\n validates :size, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7200161814689636, "alphanum_fraction": 0.7230551242828369, "avg_line_length": 73.78787994384766, "blob_id": "7fd3706fba577d320c8c14f8bd656fe7c2f6ccdb", "content_id": "a3c11bf18d0d44a199cf1d7b65a4579af74e7947", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4936, "license_type": "permissive", "max_line_length": 568, "num_lines": 66, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_gtm_monitor_tcp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages F5 BIG-IP GTM tcp monitors.\n class Bigip_gtm_monitor_tcp < Base\n # @return [String] Monitor name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The parent template of this monitor template. Once this value has been set, it cannot be changed. By default, this value is the C(tcp) parent on the C(Common) partition.\n attribute :parent\n validates :parent, type: String\n\n # @return [String, nil] The send string for the monitor call.\n attribute :send\n validates :send, type: String\n\n # @return [String, nil] The receive string for the monitor call.\n attribute :receive\n validates :receive, type: String\n\n # @return [String, nil] IP address part of the IP/port definition. If this parameter is not provided when creating a new monitor, then the default value will be '*'.,If this value is an IP address, then a C(port) number must be specified.\n attribute :ip\n validates :ip, type: String\n\n # @return [Integer, nil] Port address part of the IP/port definition. If this parameter is not provided when creating a new monitor, then the default value will be '*'. Note that if specifying an IP address, a value between 1 and 65535 must be specified\n attribute :port\n validates :port, type: Integer\n\n # @return [Object, nil] The interval specifying how frequently the monitor instance of this template will run.,If this parameter is not provided when creating a new monitor, then the default value will be 30.,This value B(must) be less than the C(timeout) value.\n attribute :interval\n\n # @return [Object, nil] The number of seconds in which the node or service must respond to the monitor request. If the target responds within the set time period, it is considered up. If the target does not respond within the set time period, it is considered down. You can change this number to any number you want, however, it should be 3 times the interval number of seconds plus 1 second.,If this parameter is not provided when creating a new monitor, then the default value will be 120.\n attribute :timeout\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [:present, :absent, nil] When C(present), ensures that the monitor exists.,When C(absent), ensures the monitor is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the number of seconds after which the system times out the probe request to the system.,When creating a new monitor, if this parameter is not provided, then the default value will be C(5).\n attribute :probe_timeout\n\n # @return [Symbol, nil] Specifies that the monitor allows more than one probe attempt per interval.,When C(yes), specifies that the monitor ignores down responses for the duration of the monitor timeout. Once the monitor timeout is reached without the system receiving an up response, the system marks the object down.,When C(no), specifies that the monitor immediately marks an object down when it receives a down response.,When creating a new monitor, if this parameter is not provided, then the default value will be C(no).\n attribute :ignore_down_response\n validates :ignore_down_response, type: Symbol\n\n # @return [Symbol, nil] Specifies whether the monitor operates in transparent mode.,A monitor in transparent mode directs traffic through the associated pool members or nodes (usually a router or firewall) to the aliased destination (that is, it probes the C(ip)-C(port) combination specified in the monitor).,If the monitor cannot successfully reach the aliased destination, the pool member or node through which the monitor traffic was sent is marked down.,When creating a new monitor, if this parameter is not provided, then the default value will be C(no).\n attribute :transparent\n validates :transparent, type: Symbol\n\n # @return [Symbol, nil] Instructs the system to mark the target resource down when the test is successful. This setting is useful, for example, if the content on your web site home page is dynamic and changes frequently, you may want to set up a reverse ECV service check that looks for the string Error.,A match for this string means that the web server was down.,To use this option, you must specify values for C(send) and C(receive).\n attribute :reverse\n validates :reverse, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6605141758918762, "alphanum_fraction": 0.6605141758918762, "avg_line_length": 51.31034469604492, "blob_id": "2a3d7fb2421841c2c15f1b936bcbe9158a9a01de", "content_id": "b327a4198f3cd712247636e54cda85c027484925", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1517, "license_type": "permissive", "max_line_length": 389, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/packaging/os/opkg.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages OpenWrt packages\n class Opkg < Base\n # @return [Array<String>, String] name of package to install/remove\n attribute :name\n validates :name, presence: true, type: TypeGeneric.new(String)\n\n # @return [:present, :absent, nil] state of the package\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:\"\", :depends, :maintainer, :reinstall, :overwrite, :downgrade, :space, :postinstall, :remove, :checksum, :\"removal-of-dependent-packages\", nil] opkg --force parameter used\n attribute :force\n validates :force, expression_inclusion: {:in=>[:\"\", :depends, :maintainer, :reinstall, :overwrite, :downgrade, :space, :postinstall, :remove, :checksum, :\"removal-of-dependent-packages\"], :message=>\"%{value} needs to be :\\\"\\\", :depends, :maintainer, :reinstall, :overwrite, :downgrade, :space, :postinstall, :remove, :checksum, :\\\"removal-of-dependent-packages\\\"\"}, allow_nil: true\n\n # @return [:yes, :no, nil] update the package db first\n attribute :update_cache\n validates :update_cache, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6754385828971863, "alphanum_fraction": 0.6754385828971863, "avg_line_length": 47.3636360168457, "blob_id": "661b82b52d53ffd4d44a783aad91a1b8563bcece", "content_id": "8213ca0e0e471d1524ec8312e77991285f5fd10e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1596, "license_type": "permissive", "max_line_length": 236, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/network/aos/aos_template.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Apstra AOS Template module let you manage your Template easily. You can create create and delete Template by Name, ID or by using a JSON File. This module is idempotent and support the I(check) mode. It's using the AOS REST API.\n class Aos_template < Base\n # @return [String] An existing AOS session as obtained by M(aos_login) module.\n attribute :session\n validates :session, presence: true, type: String\n\n # @return [String, nil] Name of the Template to manage. Only one of I(name), I(id) or I(src) can be set.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] AOS Id of the Template to manage (can't be used to create a new Template), Only one of I(name), I(id) or I(src) can be set.\n attribute :id\n validates :id, type: String\n\n # @return [String, nil] Datastructure of the Template to create. The data can be in YAML / JSON or directly a variable. It's the same datastructure that is returned on success in I(value).\n attribute :content\n validates :content, type: String\n\n # @return [:present, :absent, nil] Indicate what is the expected state of the Template (present or not).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6679558157920837, "alphanum_fraction": 0.6712707281112671, "avg_line_length": 45.410255432128906, "blob_id": "6977d768278d10b5f19528ff568f948deb25aaf4", "content_id": "20cce45b89c0c67b4d28d69f9ec1cbb9f4d3b8a2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1810, "license_type": "permissive", "max_line_length": 233, "num_lines": 39, "path": "/lib/ansible/ruby/modules/generated/system/lvg.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module creates, removes or resizes volume groups.\n class Lvg < Base\n # @return [String] The name of the volume group.\n attribute :vg\n validates :vg, presence: true, type: String\n\n # @return [Array<String>, String, nil] List of comma-separated devices to use as physical devices in this volume group. Required when creating or resizing volume group.,The module will take care of running pvcreate if needed.\n attribute :pvs\n validates :pvs, type: TypeGeneric.new(String)\n\n # @return [Integer, nil] The size of the physical extent. pesize must be a power of 2, or multiple of 128KiB. Since version 2.6, pesize can be optionally suffixed by a UNIT (k/K/m/M/g/G), default unit is megabyte.\n attribute :pesize\n validates :pesize, type: Integer\n\n # @return [Object, nil] Additional options to pass to C(pvcreate) when creating the volume group.\n attribute :pv_options\n\n # @return [Object, nil] Additional options to pass to C(vgcreate) when creating the volume group.\n attribute :vg_options\n\n # @return [:absent, :present, nil] Control if the volume group exists.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(yes), allows to remove volume group with logical volumes.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6782077550888062, "alphanum_fraction": 0.6782077550888062, "avg_line_length": 38.279998779296875, "blob_id": "b64ed7aaccdc807e3f0753b1a772ed25e74c28c4", "content_id": "80ceb0d7ac7d85a5458187fef0baeb255d212b3c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 982, "license_type": "permissive", "max_line_length": 185, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/network/illumos/ipadm_if.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, delete, enable or disable IP interfaces on Solaris/illumos systems.\n class Ipadm_if < Base\n # @return [String] IP interface name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Symbol, nil] Specifies that the IP interface is temporary. Temporary IP interfaces do not persist across reboots.\n attribute :temporary\n validates :temporary, type: Symbol\n\n # @return [:present, :absent, :enabled, :disabled, nil] Create or delete Solaris/illumos IP interfaces.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :enabled, :disabled], :message=>\"%{value} needs to be :present, :absent, :enabled, :disabled\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5146627426147461, "alphanum_fraction": 0.5146627426147461, "avg_line_length": 17.94444465637207, "blob_id": "fc82c6a95c34e92578fb4c157a9e00381b51bced", "content_id": "5dc26c4c2e72e191fae8b591895b35555ff2b8a1", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 682, "license_type": "permissive", "max_line_length": 60, "num_lines": 36, "path": "/lib/ansible/ruby/dsl_builders/jinja_item_node.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# see LICENSE.txt in project root\nmodule Ansible\n module Ruby\n module DslBuilders\n class JinjaItemNode\n def initialize(contexts = 'item')\n @contexts = [*contexts]\n end\n\n def +(other)\n to_s + other.to_s\n end\n\n def to_s\n \"{{ #{flat_context} }}\"\n end\n\n def flat_context\n @contexts.join '.'\n end\n\n def to_str\n to_s\n end\n\n # we need to respond to everything, don't want super\n def method_missing(id, *)\n contexts = @contexts + [id]\n JinjaItemNode.new contexts\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6415975093841553, "alphanum_fraction": 0.6415975093841553, "avg_line_length": 22.512195587158203, "blob_id": "8349099563a8e97355ed710aa49dcca2c493fa25", "content_id": "fe8aa1a3dc92872e992152434cd801f51b706a86", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1928, "license_type": "permissive", "max_line_length": 92, "num_lines": 82, "path": "/lib/ansible/ruby/rake/clean_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# See LICENSE.txt in root of repository\nrequire 'spec_helper'\nrequire 'ansible/ruby/rake/clean'\n\ndescribe Ansible::Ruby::Rake::Clean do\n include_context :rake_testing\n include_context :rake_invoke\n\n # need to create file before running\n def execute_task\n create_test_files\n commands = rake_result[:commands] = []\n allow(task).to receive(:sh) do |command, _|\n commands << command\n end\n Rake::Task[:default].invoke\n end\n\n def create_test_files; end\n\n context 'only ansible-ruby generated YAML' do\n def create_test_files\n FileUtils.touch 'something.yml'\n end\n\n let(:task) do\n Ansible::Ruby::Rake::Clean.new do |task|\n task.files = 'something.rb'\n end\n end\n\n it { is_expected.to_not execute_commands }\n it { is_expected.to_not have_yaml }\n end\n\n context 'other YAML too' do\n def create_test_files\n FileUtils.touch %w[something.yml else.yml]\n end\n\n let(:task) do\n Ansible::Ruby::Rake::Clean.new do |task|\n task.files = 'something.rb'\n end\n end\n\n it { is_expected.to_not execute_commands }\n it { is_expected.to have_yaml 'else.yml' }\n it { is_expected.to_not have_yaml 'something.yml' }\n end\n\n context 'dependent task' do\n let(:test_file) { 'foobar_test.yml' }\n let(:task) do\n ::Rake::Task.define_task :foobar do\n FileUtils.touch test_file\n end\n\n Ansible::Ruby::Rake::Clean.new default: :foobar do |task|\n task.files = 'something.rb'\n end\n end\n\n it { is_expected.to_not execute_commands }\n\n it 'executes the dependency' do\n expect(File.exist?(test_file)).to be_truthy\n end\n end\n\n context 'no files given' do\n def execute_task\n # overriding parent so we can test error\n end\n\n it 'should raise an error' do\n expect {Ansible::Ruby::Rake::Clean.new}.to raise_error 'You did not supply any files!'\n end\n end\nend\n" }, { "alpha_fraction": 0.636863112449646, "alphanum_fraction": 0.636863112449646, "avg_line_length": 38.25490188598633, "blob_id": "c0091fbf0fdbc97f058b0ae0c15b7fae72c34d28", "content_id": "5865d4b44ff587b70bef197c6d7673756f8a8db2", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2002, "license_type": "permissive", "max_line_length": 143, "num_lines": 51, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_staticnat.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and remove static NATs.\n class Cs_staticnat < Base\n # @return [String] Public IP address the static NAT is assigned to.\n attribute :ip_address\n validates :ip_address, presence: true, type: String\n\n # @return [String, nil] Name of virtual machine which we make the static NAT for.,Required if C(state=present).\n attribute :vm\n validates :vm, type: String\n\n # @return [:yes, :no, nil] VM guest NIC secondary IP address for the static NAT.\n attribute :vm_guest_ip\n validates :vm_guest_ip, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Network the IP address is related to.\n attribute :network\n\n # @return [Object, nil] VPC the network related to.\n attribute :vpc\n\n # @return [:present, :absent, nil] State of the static NAT.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Object, nil] Domain the static NAT is related to.\n attribute :domain\n\n # @return [Object, nil] Account the static NAT is related to.\n attribute :account\n\n # @return [Object, nil] Name of the project the static NAT is related to.\n attribute :project\n\n # @return [Object, nil] Name of the zone in which the virtual machine is in.,If not set, default zone is used.\n attribute :zone\n\n # @return [:yes, :no, nil] Poll async jobs until job has finished.\n attribute :poll_async\n validates :poll_async, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6718494296073914, "alphanum_fraction": 0.6718494296073914, "avg_line_length": 34.94117736816406, "blob_id": "d38a4f4fd5bade658b87da5bd253c4d62956a759", "content_id": "71f8ac013895d8dc8a7d865e4e5292505903b35c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1222, "license_type": "permissive", "max_line_length": 163, "num_lines": 34, "path": "/lib/ansible/ruby/modules/generated/network/netvisor/pn_show.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Execute show command in the nodes and returns the results read from the device.\n class Pn_show < Base\n # @return [Object, nil] Provide login username if user is not root.\n attribute :pn_cliusername\n\n # @return [Object, nil] Provide login password if user is not root.\n attribute :pn_clipassword\n\n # @return [Object, nil] Target switch(es) to run the cli on.\n attribute :pn_cliswitch\n\n # @return [String] The C(pn_command) takes a CLI show command as value.\n attribute :pn_command\n validates :pn_command, presence: true, type: String\n\n # @return [Array<String>, String, nil] Display output using a specific parameter. Use 'all' to display possible output. List of comma separated parameters.\n attribute :pn_parameters\n validates :pn_parameters, type: TypeGeneric.new(String)\n\n # @return [String, nil] Specify formatting options.\n attribute :pn_options\n validates :pn_options, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6678832173347473, "alphanum_fraction": 0.6692517995834351, "avg_line_length": 43.73469543457031, "blob_id": "e5a4b57bea1dc124865f4dc7e631ec91cab1cb41", "content_id": "c843725ce2c8138bcf524bdd21df0a9b06d3fbd0", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2192, "license_type": "permissive", "max_line_length": 266, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/system/aix_lvol.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module creates, removes or resizes AIX logical volumes. Inspired by lvol module.\n class Aix_lvol < Base\n # @return [String] The volume group this logical volume is part of.\n attribute :vg\n validates :vg, presence: true, type: String\n\n # @return [String] The name of the logical volume.\n attribute :lv\n validates :lv, presence: true, type: String\n\n # @return [String, nil] The type of the logical volume.\n attribute :lv_type\n validates :lv_type, type: String\n\n # @return [String, nil] The size of the logical volume with one of the [MGT] units.\n attribute :size\n validates :size, type: String\n\n # @return [String, nil] The number of copies of the logical volume. Maximum copies are 3.\n attribute :copies\n validates :copies, type: String\n\n # @return [:maximum, :minimum, nil] Sets the interphysical volume allocation policy. C(maximum) allocates logical partitions across the maximum number of physical volumes. C(minimum) allocates logical partitions across the minimum number of physical volumes.\n attribute :policy\n validates :policy, expression_inclusion: {:in=>[:maximum, :minimum], :message=>\"%{value} needs to be :maximum, :minimum\"}, allow_nil: true\n\n # @return [:absent, :present, nil] Control if the logical volume exists. If C(present) and the volume does not already exist then the C(size) option is required.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] Free-form options to be passed to the mklv command.\n attribute :opts\n validates :opts, type: String\n\n # @return [Array<String>, String, nil] Comma separated list of physical volumes e.g. C(hdisk1,hdisk2).\n attribute :pvs\n validates :pvs, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7097457647323608, "alphanum_fraction": 0.7097457647323608, "avg_line_length": 30.46666717529297, "blob_id": "219d01d70f97f6ba1a480d35186c9b48bb928293", "content_id": "b43c05ed3fb3b27d232344c0ebda0583182d9ca3", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 472, "license_type": "permissive", "max_line_length": 230, "num_lines": 15, "path": "/lib/ansible/ruby/modules/generated/system/ohai.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Similar to the M(facter) module, this runs the I(Ohai) discovery program (U(https://docs.chef.io/ohai.html)) on the remote host and returns JSON inventory data. I(Ohai) data is a bit more verbose and nested than I(facter).\n class Ohai < Base\n\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7071734666824341, "alphanum_fraction": 0.7071734666824341, "avg_line_length": 63.41379165649414, "blob_id": "9f2d91e5a3b0c21d8cbf537029e207dd587262be", "content_id": "0ca4fa3d2b5da26851796bfbb8d6bf20e0b85674", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1868, "license_type": "permissive", "max_line_length": 427, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/windows/win_hotfix.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Install, uninstall a Windows hotfix.\n class Win_hotfix < Base\n # @return [String, nil] The name of the hotfix as shown in DISM, see examples for details.,This or C(hotfix_kb) MUST be set when C(state=absent).,If C(state=present) then the hotfix at C(source) will be validated against this value, if it does not match an error will occur.,You can get the identifier by running 'Get-WindowsPackage -Online -PackagePath path-to-cab-in-msu' after expanding the msu file.\n attribute :hotfix_identifier\n validates :hotfix_identifier, type: String\n\n # @return [String, nil] The name of the KB the hotfix relates to, see examples for details.,This of C(hotfix_identifier) MUST be set when C(state=absent).,If C(state=present) then the hotfix at C(source) will be validated against this value, if it does not match an error will occur.,Because DISM uses the identifier as a key and doesn't refer to a KB in all cases it is recommended to use C(hotfix_identifier) instead.\n attribute :hotfix_kb\n validates :hotfix_kb, type: String\n\n # @return [:absent, :present, nil] Whether to install or uninstall the hotfix.,When C(present), C(source) MUST be set.,When C(absent), C(hotfix_identifier) or C(hotfix_kb) MUST be set.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] The path to the downloaded hotfix .msu file.,This MUST be set if C(state=present) and MUST be a .msu hotfix file.\n attribute :source\n validates :source, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6631439924240112, "alphanum_fraction": 0.6677675247192383, "avg_line_length": 46.3125, "blob_id": "1f4e3e3bf89d81c5dca1fd6641e53dae0dd7e378", "content_id": "434fa004a3d1c932705faebc9c2a2b8ed0a07e8a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1514, "license_type": "permissive", "max_line_length": 204, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_netstream_aging.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages timeout mode of NetStream on HUAWEI CloudEngine switches.\n class Ce_netstream_aging < Base\n # @return [Integer, nil] Netstream timeout interval. If is active type the interval is 1-60. If is inactive ,the interval is 5-600.\n attribute :timeout_interval\n validates :timeout_interval, type: Integer\n\n # @return [:ip, :vxlan, nil] Specifies the packet type of netstream timeout active interval.\n attribute :type\n validates :type, expression_inclusion: {:in=>[:ip, :vxlan], :message=>\"%{value} needs to be :ip, :vxlan\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Specify desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:active, :inactive, :\"tcp-session\", :manual, nil] Netstream timeout type.\n attribute :timeout_type\n validates :timeout_type, expression_inclusion: {:in=>[:active, :inactive, :\"tcp-session\", :manual], :message=>\"%{value} needs to be :active, :inactive, :\\\"tcp-session\\\", :manual\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the slot number of netstream manual timeout.\n attribute :manual_slot\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6549209952354431, "alphanum_fraction": 0.6549209952354431, "avg_line_length": 39.14634323120117, "blob_id": "3f945f7a0706c9ff567fc1cab6aaa39ee70a752e", "content_id": "e64d735c8306f3a7b967f7e7c1645091693a2afe", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1646, "license_type": "permissive", "max_line_length": 160, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/remote_management/manageiq/manageiq_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The manageiq_user module supports adding, updating and deleting users in ManageIQ.\n class Manageiq_user < Base\n # @return [:absent, :present, nil] absent - user should not exist, present - user should be.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String] The unique userid in manageiq, often mentioned as username.\n attribute :userid\n validates :userid, presence: true, type: String\n\n # @return [String, nil] The users' full name.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] The users' password.\n attribute :password\n validates :password, type: String\n\n # @return [String, nil] The name of the group to which the user belongs.\n attribute :group\n validates :group, type: String\n\n # @return [String, nil] The users' E-mail address.\n attribute :email\n validates :email, type: String\n\n # @return [:always, :on_create, nil] C(always) will update passwords unconditionally. C(on_create) will only set the password for a newly created user.\n attribute :update_password\n validates :update_password, expression_inclusion: {:in=>[:always, :on_create], :message=>\"%{value} needs to be :always, :on_create\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6740104556083679, "alphanum_fraction": 0.6740104556083679, "avg_line_length": 64.31707000732422, "blob_id": "c68dc69e0a21267866790147fce4315c0d573668", "content_id": "47df5e7de384e5f2c0a27c5d4bf356e2def3335a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2678, "license_type": "permissive", "max_line_length": 481, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/cloud/misc/virt_pool.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage I(libvirt) storage pools.\n class Virt_pool < Base\n # @return [String, nil] name of the storage pool being managed. Note that pool must be previously defined with xml.\n attribute :name\n validates :name, type: String\n\n # @return [:active, :inactive, :present, :absent, :undefined, :deleted, nil] specify which state you want a storage pool to be in. If 'active', pool will be started. If 'present', ensure that pool is present but do not change its state; if it's missing, you need to specify xml argument. If 'inactive', pool will be stopped. If 'undefined' or 'absent', pool will be removed from I(libvirt) configuration. If 'deleted', pool contents will be deleted and then pool undefined.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:active, :inactive, :present, :absent, :undefined, :deleted], :message=>\"%{value} needs to be :active, :inactive, :present, :absent, :undefined, :deleted\"}, allow_nil: true\n\n # @return [:define, :build, :create, :start, :stop, :destroy, :delete, :undefine, :get_xml, :list_pools, :facts, :info, :status, nil] in addition to state management, various non-idempotent commands are available. See examples.\n attribute :command\n validates :command, expression_inclusion: {:in=>[:define, :build, :create, :start, :stop, :destroy, :delete, :undefine, :get_xml, :list_pools, :facts, :info, :status], :message=>\"%{value} needs to be :define, :build, :create, :start, :stop, :destroy, :delete, :undefine, :get_xml, :list_pools, :facts, :info, :status\"}, allow_nil: true\n\n # @return [Symbol, nil] Specify if a given storage pool should be started automatically on system boot.\n attribute :autostart\n validates :autostart, type: Symbol\n\n # @return [String, nil] I(libvirt) connection uri.\n attribute :uri\n validates :uri, type: String\n\n # @return [String, nil] XML document used with the define command.\n attribute :xml\n validates :xml, type: String\n\n # @return [:new, :repair, :resize, :no_overwrite, :overwrite, :normal, :zeroed, nil] Pass additional parameters to 'build' or 'delete' commands.\n attribute :mode\n validates :mode, expression_inclusion: {:in=>[:new, :repair, :resize, :no_overwrite, :overwrite, :normal, :zeroed], :message=>\"%{value} needs to be :new, :repair, :resize, :no_overwrite, :overwrite, :normal, :zeroed\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6725521683692932, "alphanum_fraction": 0.6725521683692932, "avg_line_length": 40.53333282470703, "blob_id": "1841fb80ecd89899ecf914d3818a7cf112baf11e", "content_id": "1775ff580259a8b147bb59bd6932f1e8980623c7", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1869, "license_type": "permissive", "max_line_length": 197, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/web_infrastructure/jenkins_job_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to query the facts about which Jenkins jobs which already exists.\n class Jenkins_job_facts < Base\n # @return [String, nil] Exact name of the Jenkins job to fetch facts about.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] A shell glob of Jenkins job names to fetch facts about.\n attribute :glob\n validates :glob, type: String\n\n # @return [String, nil] Only fetch jobs with the given status color.\n attribute :color\n validates :color, type: String\n\n # @return [String, nil] Password to authenticate with the Jenkins server.,This is a required parameter, if C(token) is not provided.\n attribute :password\n validates :password, type: String\n\n # @return [String, nil] API token used to authenticate with the Jenkins server.,This is a required parameter, if C(password) is not provided.\n attribute :token\n validates :token, type: String\n\n # @return [String, nil] URL where the Jenkins server is accessible.\n attribute :url\n validates :url, type: String\n\n # @return [String, nil] User to authenticate with the Jenkins server.\n attribute :user\n validates :user, type: String\n\n # @return [Boolean, nil] If set to C(False), the SSL certificates will not be validated.,This should only set to C(False) used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.702479362487793, "alphanum_fraction": 0.7033647894859314, "avg_line_length": 58.438594818115234, "blob_id": "be081dc3abc72620ab5dae6088430b27abbc072c", "content_id": "e8156cd9e4d5da3316fa4f319b46800de3d6e550", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3388, "license_type": "permissive", "max_line_length": 277, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/network/eos/eos_interface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of Interfaces on Arista EOS network devices.\n class Eos_interface < Base\n # @return [String] Name of the Interface to be configured on remote device. The name of interface should be in expanded format and not abbreviated.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Description of Interface upto 240 characters.\n attribute :description\n validates :description, type: String\n\n # @return [Boolean, nil] Interface link status. If the value is I(True) the interface state will be enabled, else if value is I(False) interface will be in disable (shutdown) state.\n attribute :enabled\n validates :enabled, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] This option configures autoneg and speed/duplex/flowcontrol for the interface given in C(name) option.\n attribute :speed\n validates :speed, type: String\n\n # @return [Integer, nil] Set maximum transmission unit size in bytes of transmit packet for the interface given in C(name) option.\n attribute :mtu\n validates :mtu, type: Integer\n\n # @return [String, nil] Transmit rate in bits per second (bps) for the interface given in C(name) option.,This is state check parameter only.,Supports conditionals, see L(Conditionals in Networking Modules,../network/user_guide/network_working_with_command_output.html)\n attribute :tx_rate\n validates :tx_rate, type: String\n\n # @return [String, nil] Receiver rate in bits per second (bps) for the interface given in C(name) option.,This is state check parameter only.,Supports conditionals, see L(Conditionals in Networking Modules,../network/user_guide/network_working_with_command_output.html)\n attribute :rx_rate\n validates :rx_rate, type: String\n\n # @return [Array<Hash>, Hash, nil] Check the operational state of given interface C(name) for LLDP neighbor.,The following suboptions are available.\n attribute :neighbors\n validates :neighbors, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash, nil] List of Interfaces definitions. Each of the entry in aggregate list should define name of interface C(name) and other options as required.\n attribute :aggregate\n validates :aggregate, type: TypeGeneric.new(Hash)\n\n # @return [Integer, nil] Time in seconds to wait before checking for the operational state on remote device. This wait is applicable for operational state argument which are I(state) with values C(up)/C(down), I(tx_rate) and I(rx_rate).\n attribute :delay\n validates :delay, type: Integer\n\n # @return [:present, :absent, :up, :down, nil] State of the Interface configuration, C(up) means present and operationally up and C(down) means present and operationally C(down)\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :up, :down], :message=>\"%{value} needs to be :present, :absent, :up, :down\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6907669901847839, "alphanum_fraction": 0.691255509853363, "avg_line_length": 55.86111068725586, "blob_id": "42773008e7b45225416d1c92cb3125d0b3b476f9", "content_id": "1176fd4e7b8a91a760e8cb3f869a114b720521aa", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2047, "license_type": "permissive", "max_line_length": 383, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/system/crypttab.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Control Linux encrypted block devices that are set up during system boot in C(/etc/crypttab).\n class Crypttab < Base\n # @return [String] Name of the encrypted block device as it appears in the C(/etc/crypttab) file, or optionally prefixed with C(/dev/mapper/), as it appears in the filesystem. I(/dev/mapper/) will be stripped from I(name).\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :opts_absent, :opts_present, :present] Use I(present) to add a line to C(/etc/crypttab) or update it's definition if already present. Use I(absent) to remove a line with matching I(name). Use I(opts_present) to add options to those already present; options with different values will be updated. Use I(opts_absent) to remove options from the existing set.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:absent, :opts_absent, :opts_present, :present], :message=>\"%{value} needs to be :absent, :opts_absent, :opts_present, :present\"}\n\n # @return [Object, nil] Path to the underlying block device or file, or the UUID of a block-device prefixed with I(UUID=).\n attribute :backing_device\n\n # @return [String, nil] Encryption password, the path to a file containing the password, or C(none) or C(-) if the password should be entered at boot.\n attribute :password\n validates :password, type: String\n\n # @return [Array<String>, String, nil] A comma-delimited list of options. See C(crypttab(5) ) for details.\n attribute :opts\n validates :opts, type: TypeGeneric.new(String)\n\n # @return [String, nil] Path to file to use instead of C(/etc/crypttab). This might be useful in a chroot environment.\n attribute :path\n validates :path, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6669414639472961, "alphanum_fraction": 0.6673536896705627, "avg_line_length": 42.32143020629883, "blob_id": "3076f21ca541da829b0560b79a4da0e9f6281d8b", "content_id": "fb46387e26f000122385a23dd23cd749ef027e5c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2426, "license_type": "permissive", "max_line_length": 182, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/monitoring/pagerduty.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module will let you create PagerDuty maintenance windows\n class Pagerduty < Base\n # @return [:running, :started, :ongoing, :absent] Create a maintenance window or get a list of ongoing windows.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:running, :started, :ongoing, :absent], :message=>\"%{value} needs to be :running, :started, :ongoing, :absent\"}\n\n # @return [String, nil] PagerDuty unique subdomain. Obsolete. It is not used with PagerDuty REST v2 API.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] PagerDuty user ID. Obsolete. Please, use I(token) for authorization.\n attribute :user\n validates :user, type: String\n\n # @return [String] A pagerduty token, generated on the pagerduty site. It is used for authorization.\n attribute :token\n validates :token, presence: true, type: String\n\n # @return [Object, nil] ID of user making the request. Only needed when creating a maintenance_window.\n attribute :requester_id\n\n # @return [String, nil] A comma separated list of PagerDuty service IDs.\n attribute :service\n validates :service, type: String\n\n # @return [String, nil] ID of maintenance window. Only needed when absent a maintenance_window.\n attribute :window_id\n validates :window_id, type: String\n\n # @return [Integer, nil] Length of maintenance window in hours.\n attribute :hours\n validates :hours, type: Integer\n\n # @return [Integer, nil] Maintenance window in minutes (this is added to the hours).\n attribute :minutes\n validates :minutes, type: Integer\n\n # @return [String, nil] Short description of maintenance window.\n attribute :desc\n validates :desc, type: String\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6420649886131287, "alphanum_fraction": 0.6439770460128784, "avg_line_length": 49.28845977783203, "blob_id": "69c93df17d9b8d948852f072584d307a3be2647d", "content_id": "340ed7cb90f06167bc7a68e8660f5159eaf6cd02", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2615, "license_type": "permissive", "max_line_length": 278, "num_lines": 52, "path": "/lib/ansible/ruby/modules/generated/packaging/language/cpanm.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage Perl library dependencies.\n class Cpanm < Base\n # @return [String, nil] The name of the Perl library to install. You may use the \"full distribution path\", e.g. MIYAGAWA/Plack-0.99_05.tar.gz\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] The local directory from where to install\n attribute :from_path\n validates :from_path, type: String\n\n # @return [:yes, :no, nil] Do not run unit tests\n attribute :notest\n validates :notest, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Specify the install base to install modules\n attribute :locallib\n validates :locallib, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Specifies the base URL for the CPAN mirror to use\n attribute :mirror\n validates :mirror, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Use the mirror's index file instead of the CPAN Meta DB\n attribute :mirror_only\n validates :mirror_only, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Only install dependencies\n attribute :installdeps\n validates :installdeps, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] minimum version of perl module to consider acceptable\n attribute :version\n validates :version, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Use this if you want to install modules to the system perl include path. You must be root or have \"passwordless\" sudo for this to work.,This uses the cpanm commandline option '--sudo', which has nothing to do with ansible privilege escalation.\n attribute :system_lib\n validates :system_lib, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Override the path to the cpanm executable\n attribute :executable\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6849240660667419, "alphanum_fraction": 0.6908893585205078, "avg_line_length": 45.099998474121094, "blob_id": "f9320392aba193f7276faf14076f2f63ccb72fe3", "content_id": "09306d8bf4fe6b8e0c6aa043c6d80a383e40a0c5", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1844, "license_type": "permissive", "max_line_length": 283, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_elementsw_account.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, destroy, or update accounts on Element SW\n class Na_elementsw_account < Base\n # @return [:present, :absent] Whether the specified account should exist or not.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [String] Unique username for this account. (May be 1 to 64 characters in length).\n attribute :element_username\n validates :element_username, presence: true, type: String\n\n # @return [String, nil] New name for the user account.\n attribute :new_element_username\n validates :new_element_username, type: String\n\n # @return [Object, nil] CHAP secret to use for the initiator. Should be 12-16 characters long and impenetrable.,The CHAP initiator secrets must be unique and cannot be the same as the target CHAP secret.,If not specified, a random secret is created.\n attribute :initiator_secret\n\n # @return [Object, nil] CHAP secret to use for the target (mutual CHAP authentication).,Should be 12-16 characters long and impenetrable.,The CHAP target secrets must be unique and cannot be the same as the initiator CHAP secret.,If not specified, a random secret is created.\n attribute :target_secret\n\n # @return [Object, nil] List of Name/Value pairs in JSON object format.\n attribute :attributes\n\n # @return [Object, nil] The ID of the account to manage or update.\n attribute :account_id\n\n # @return [Object, nil] Status of the account.\n attribute :status\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6540920734405518, "alphanum_fraction": 0.6540920734405518, "avg_line_length": 41.27027130126953, "blob_id": "c475dc63ddf6f890d34dd37f33e5996d7fbe3c85", "content_id": "4f81f17f4bf47c1b2b9be0d2d85ceebd7f67ce46", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1564, "license_type": "permissive", "max_line_length": 157, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/storage/purestorage/purefa_snap.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or delete volumes and volume snapshots on Pure Storage FlashArray.\n class Purefa_snap < Base\n # @return [String] The name of the source volume.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Suffix of snapshot name.\n attribute :suffix\n validates :suffix, type: String\n\n # @return [String, nil] Name of target volume if creating from snapshot.\n attribute :target\n validates :target, type: String\n\n # @return [:yes, :no, nil] Define whether to overwrite existing volume when creating from snapshot.\n attribute :overwrite\n validates :overwrite, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:absent, :copy, :present, nil] Define whether the volume snapshot should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :copy, :present], :message=>\"%{value} needs to be :absent, :copy, :present\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Define whether to eradicate the snapshot on delete or leave in trash.\n attribute :eradicate\n validates :eradicate, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6709073781967163, "alphanum_fraction": 0.6765201091766357, "avg_line_length": 53.54081726074219, "blob_id": "dc860b4367184ee28af244670a3f9e3073a316d6", "content_id": "906278082f999d666fc2910cfdbf2b7d479b7b7c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5345, "license_type": "permissive", "max_line_length": 228, "num_lines": 98, "path": "/lib/ansible/ruby/modules/generated/cloud/oneandone/oneandone_load_balancer.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, remove, update load balancers. This module has a dependency on 1and1 >= 1.0\n class Oneandone_load_balancer < Base\n # @return [:present, :absent, :update, nil] Define a load balancer state to create, remove, or update.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :update], :message=>\"%{value} needs to be :present, :absent, :update\"}, allow_nil: true\n\n # @return [String] Authenticating API token provided by 1&1.\n attribute :auth_token\n validates :auth_token, presence: true, type: String\n\n # @return [String] The identifier (id or name) of the load balancer used with update state.\n attribute :load_balancer\n validates :load_balancer, presence: true, type: String\n\n # @return [Object, nil] Custom API URL. Overrides the ONEANDONE_API_URL environement variable.\n attribute :api_url\n\n # @return [String] Load balancer name used with present state. Used as identifier (id or name) when used with absent state. maxLength=128\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:NONE, :TCP, :HTTP, :ICMP] Type of the health check. At the moment, HTTP is not allowed.\n attribute :health_check_test\n validates :health_check_test, presence: true, expression_inclusion: {:in=>[:NONE, :TCP, :HTTP, :ICMP], :message=>\"%{value} needs to be :NONE, :TCP, :HTTP, :ICMP\"}\n\n # @return [Integer] Health check period in seconds. minimum=5, maximum=300, multipleOf=1\n attribute :health_check_interval\n validates :health_check_interval, presence: true, type: Integer\n\n # @return [Object, nil] Url to call for cheking. Required for HTTP health check. maxLength=1000\n attribute :health_check_path\n\n # @return [Object, nil] Regular expression to check. Required for HTTP health check. maxLength=64\n attribute :health_check_parse\n\n # @return [Boolean] Persistence.\n attribute :persistence\n validates :persistence, presence: true, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}\n\n # @return [Integer] Persistence time in seconds. Required if persistence is enabled. minimum=30, maximum=1200, multipleOf=1\n attribute :persistence_time\n validates :persistence_time, presence: true, type: Integer\n\n # @return [:ROUND_ROBIN, :LEAST_CONNECTIONS] Balancing procedure.\n attribute :method\n validates :method, presence: true, expression_inclusion: {:in=>[:ROUND_ROBIN, :LEAST_CONNECTIONS], :message=>\"%{value} needs to be :ROUND_ROBIN, :LEAST_CONNECTIONS\"}\n\n # @return [:US, :ES, :DE, :GB, nil] ID or country code of the datacenter where the load balancer will be created.\n attribute :datacenter\n validates :datacenter, expression_inclusion: {:in=>[:US, :ES, :DE, :GB], :message=>\"%{value} needs to be :US, :ES, :DE, :GB\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash] A list of rule objects that will be set for the load balancer. Each rule must contain protocol, port_balancer, and port_server parameters, in addition to source parameter, which is optional.\n attribute :rules\n validates :rules, presence: true, type: TypeGeneric.new(Hash)\n\n # @return [String, nil] Description of the load balancer. maxLength=256\n attribute :description\n validates :description, type: String\n\n # @return [Array<String>, String, nil] A list of server identifiers (id or name) to be assigned to a load balancer. Used in combination with update state.\n attribute :add_server_ips\n validates :add_server_ips, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] A list of server IP ids to be unassigned from a load balancer. Used in combination with update state.\n attribute :remove_server_ips\n validates :remove_server_ips, type: TypeGeneric.new(String)\n\n # @return [Array<Hash>, Hash, nil] A list of rules that will be added to an existing load balancer. It is syntax is the same as the one used for rules parameter. Used in combination with update state.\n attribute :add_rules\n validates :add_rules, type: TypeGeneric.new(Hash)\n\n # @return [Array<String>, String, nil] A list of rule ids that will be removed from an existing load balancer. Used in combination with update state.\n attribute :remove_rules\n validates :remove_rules, type: TypeGeneric.new(String)\n\n # @return [:yes, :no, nil] wait for the instance to be in state 'running' before returning\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] how long before wait gives up, in seconds\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n\n # @return [Integer, nil] Defines the number of seconds to wait when using the _wait_for methods\n attribute :wait_interval\n validates :wait_interval, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.676682710647583, "alphanum_fraction": 0.6862980723381042, "avg_line_length": 54.46666717529297, "blob_id": "b79dd7ca06d32b269c008d85a546ab9f95627c88", "content_id": "a92fb006b1729c8265f1034f6fe3cf45f6753423", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2496, "license_type": "permissive", "max_line_length": 179, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_evpn_bgp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module offers the ability to configure a BGP EVPN peer relationship on HUAWEI CloudEngine switches.\n class Ce_evpn_bgp < Base\n # @return [Object] Name of a BGP instance. The value is a string of 1 to 31 case-sensitive characters, spaces not supported.\n attribute :bgp_instance\n validates :bgp_instance, presence: true\n\n # @return [Object, nil] Specifies integral AS number. The value is an integer ranging from 1 to 4294967295.\n attribute :as_number\n\n # @return [Object, nil] Specifies the IPv4 address of a BGP EVPN peer. The value is in dotted decimal notation.\n attribute :peer_address\n\n # @return [Object, nil] Specify the name of a peer group that BGP peers need to join. The value is a string of 1 to 47 case-sensitive characters, spaces not supported.\n attribute :peer_group_name\n\n # @return [:true, :false, nil] Enable or disable a BGP device to exchange routes with a specified peer or peer group in the address family view.\n attribute :peer_enable\n validates :peer_enable, expression_inclusion: {:in=>[:true, :false], :message=>\"%{value} needs to be :true, :false\"}, allow_nil: true\n\n # @return [:arp, :irb, nil] Configures a device to advertise routes to its BGP EVPN peers.\n attribute :advertise_router_type\n validates :advertise_router_type, expression_inclusion: {:in=>[:arp, :irb], :message=>\"%{value} needs to be :arp, :irb\"}, allow_nil: true\n\n # @return [Object, nil] Associates a specified VPN instance with the IPv4 address family. The value is a string of 1 to 31 case-sensitive characters, spaces not supported.\n attribute :vpn_name\n\n # @return [:enable, :disable, nil] Enable or disable a device to advertise IP routes imported to a VPN instance to its EVPN instance.\n attribute :advertise_l2vpn_evpn\n validates :advertise_l2vpn_evpn, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Manage the state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6011644601821899, "alphanum_fraction": 0.608442485332489, "avg_line_length": 23.535715103149414, "blob_id": "c51d849b9e829938ebfe8c4552c0aca97517cb36", "content_id": "91c07f0fb4b3e170cea31f866c45c8e1b905ec20", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 687, "license_type": "permissive", "max_line_length": 66, "num_lines": 28, "path": "/lib/ansible/ruby/modules/custom/net_tools/basics/get_url.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# VALIDATED_CHECKSUM: OVbNiDPhaM2eIJGif1LZUzVEoTkUa7v/rUl8VTQrFN4=\n\nrequire 'ansible/ruby/modules/generated/net_tools/basics/get_url'\nrequire 'ansible/ruby/modules/helpers/file_attributes'\n\nmodule Ansible\n module Ruby\n module Modules\n class Get_url\n include Helpers::FileAttributes\n\n def to_h\n result = super\n data = result[:get_url]\n # Ansible expects a string for some reason\n if data.include? :headers\n data[:headers] = data[:headers].map do |key, value|\n \"#{key}:#{value}\"\n end.join ','\n end\n result\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6499999761581421, "alphanum_fraction": 0.6653845906257629, "avg_line_length": 14.29411792755127, "blob_id": "3926837ed1bbf562902f1c09d25ac2d514aa6758", "content_id": "6498718301f3c1cf70230103f9d652ac5fbf027e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 260, "license_type": "permissive", "max_line_length": 34, "num_lines": 17, "path": "/spec/rake/nested_tasks/roles/role1/tasks/task1_test.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\ntask 'Copy something over' do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\nend\n\nansible_include 'something.yml'\n\ntask 'Copy something else over' do\n copy do\n src '/file3.conf'\n dest '/file4.conf'\n end\nend\n" }, { "alpha_fraction": 0.6856659054756165, "alphanum_fraction": 0.6856659054756165, "avg_line_length": 42.219512939453125, "blob_id": "2f10e50bc923b7887885f8ddc5b09e73dd426723", "content_id": "c238435de2e124fb5c62fb65063c4a3298bea6c7", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1772, "license_type": "permissive", "max_line_length": 207, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gce_snapshot.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages snapshots for GCE instances. This module manages snapshots for the storage volumes of a GCE compute instance. If there are multiple volumes, each snapshot will be prepended with the disk name\n class Gce_snapshot < Base\n # @return [String] The GCE instance to snapshot\n attribute :instance_name\n validates :instance_name, presence: true, type: String\n\n # @return [String, nil] The name of the snapshot to manage\n attribute :snapshot_name\n validates :snapshot_name, type: String\n\n # @return [String, nil] A list of disks to create snapshots for. If none is provided, all of the volumes will be snapshotted\n attribute :disks\n validates :disks, type: String\n\n # @return [:present, :absent, nil] Whether a snapshot should be C(present) or C(absent)\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] GCP service account email for the project where the instance resides\n attribute :service_account_email\n validates :service_account_email, presence: true, type: String\n\n # @return [String] The path to the credentials file associated with the service account\n attribute :credentials_file\n validates :credentials_file, presence: true, type: String\n\n # @return [String] The GCP project ID to use\n attribute :project_id\n validates :project_id, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6878378391265869, "alphanum_fraction": 0.6905405521392822, "avg_line_length": 34.238094329833984, "blob_id": "8996da188c4152b823a7c20293a5d1c3be515576", "content_id": "06d7136fe655c0aca33dc3e4138f8368fd700215", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 740, "license_type": "permissive", "max_line_length": 159, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/elb_application_lb_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gather facts about application ELBs in AWS\n class Elb_application_lb_facts < Base\n # @return [Array<String>, String, nil] The Amazon Resource Names (ARN) of the load balancers. You can specify up to 20 load balancers in a single call.\n attribute :load_balancer_arns\n validates :load_balancer_arns, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] The names of the load balancers.\n attribute :names\n validates :names, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.680594265460968, "alphanum_fraction": 0.680594265460968, "avg_line_length": 37.46428680419922, "blob_id": "4626ff718684e9447316643770a914d367d2b504", "content_id": "ea01c326ac5c937f33ccaa91e19b48eab2ddb934", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1077, "license_type": "permissive", "max_line_length": 143, "num_lines": 28, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_broadcast_domain_ports.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add or remove ONTAP broadcast domain ports. Existing ports that are not listed are kept.\n class Na_ontap_broadcast_domain_ports < Base\n # @return [:present, :absent, nil] Whether the specified broadcast domain should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] Specify the broadcast_domain name\n attribute :broadcast_domain\n validates :broadcast_domain, presence: true, type: String\n\n # @return [Object, nil] Specify the ipspace for the broadcast domain\n attribute :ipspace\n\n # @return [String, nil] Specify the list of ports to add to or remove from this broadcast domain.\n attribute :ports\n validates :ports, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7079265713691711, "alphanum_fraction": 0.7110503911972046, "avg_line_length": 70.13888549804688, "blob_id": "6862a6d4f313b10bb13ec5c3730a39b9686d91fb", "content_id": "af48d6afbc9b3c3d96bcca3584c3578b6e1ee997", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2561, "license_type": "permissive", "max_line_length": 321, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/crypto/acme/acme_account.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows to create, modify or delete accounts with a CA supporting the L(ACME protocol,https://tools.ietf.org/html/draft-ietf-acme-acme-14), such as L(Let's Encrypt,https://letsencrypt.org/).\n # This module only works with the ACME v2 protocol.\n class Acme_account < Base\n # @return [:present, :absent, :changed_key] The state of the account, to be identified by its account key.,If the state is C(absent), the account will either not exist or be deactivated.,If the state is C(changed_key), the account must exist. The account key will be changed; no other information will be touched.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent, :changed_key], :message=>\"%{value} needs to be :present, :absent, :changed_key\"}\n\n # @return [Boolean, nil] Whether account creation is allowed (when state is C(present)).\n attribute :allow_creation\n validates :allow_creation, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] A list of contact URLs.,Email addresses must be prefixed with C(mailto:).,See https://tools.ietf.org/html/draft-ietf-acme-acme-14#section-7.1.2 for what is allowed.,Must be specified when state is C(present). Will be ignored if state is C(absent) or C(changed_key).\n attribute :contact\n\n # @return [Symbol, nil] Boolean indicating whether you agree to the terms of service document.,ACME servers can require this to be true.\n attribute :terms_agreed\n validates :terms_agreed, type: Symbol\n\n # @return [Object, nil] Path to a file containing the ACME account RSA or Elliptic Curve key to change to.,Same restrictions apply as to C(account_key_src).,Mutually exclusive with C(new_account_key_content).,Required if C(new_account_key_content) is not used and state is C(changed_key).\n attribute :new_account_key_src\n\n # @return [String, nil] Content of the ACME account RSA or Elliptic Curve key to change to.,Same restrictions apply as to C(account_key_content).,Mutually exclusive with C(new_account_key_src).,Required if C(new_account_key_src) is not used and state is C(changed_key).\n attribute :new_account_key_content\n validates :new_account_key_content, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6687334179878235, "alphanum_fraction": 0.6806908845901489, "avg_line_length": 47.04255294799805, "blob_id": "c98091a830641b0b790e476ed13fc9815211ec18", "content_id": "b87414a71c5c78ceb50d2935bacdd2d373b01a08", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2258, "license_type": "permissive", "max_line_length": 216, "num_lines": 47, "path": "/lib/ansible/ruby/modules/generated/network/netvisor/pn_vlan.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Execute vlan-create or vlan-delete command.\n # VLANs are used to isolate network traffic at Layer 2.The VLAN identifiers 0 and 4095 are reserved and cannot be used per the IEEE 802.1Q standard. The range of configurable VLAN identifiers is 2 through 4092.\n class Pn_vlan < Base\n # @return [Object, nil] Provide login username if user is not root.\n attribute :pn_cliusername\n\n # @return [Object, nil] Provide login password if user is not root.\n attribute :pn_clipassword\n\n # @return [Object, nil] Target switch(es) to run the cli on.\n attribute :pn_cliswitch\n\n # @return [:present, :absent] State the action to perform. Use 'present' to create vlan and 'absent' to delete vlan.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [Integer] Specify a VLAN identifier for the VLAN. This is a value between 2 and 4092.\n attribute :pn_vlanid\n validates :pn_vlanid, presence: true, type: Integer\n\n # @return [:fabric, :local, nil] Specify a scope for the VLAN.,Required for vlan-create.\n attribute :pn_scope\n validates :pn_scope, expression_inclusion: {:in=>[:fabric, :local], :message=>\"%{value} needs to be :fabric, :local\"}, allow_nil: true\n\n # @return [Object, nil] Specify a description for the VLAN.\n attribute :pn_description\n\n # @return [Object, nil] Specify if you want to collect statistics for a VLAN. Statistic collection is enabled by default.\n attribute :pn_stats\n\n # @return [Object, nil] Specifies the switch network data port number, list of ports, or range of ports. Port numbers must ne in the range of 1 to 64.\n attribute :pn_ports\n\n # @return [Object, nil] Specifies the ports that should have untagged packets mapped to the VLAN. Untagged packets are packets that do not contain IEEE 802.1Q VLAN tags.\n attribute :pn_untagged_ports\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.693708598613739, "alphanum_fraction": 0.693708598613739, "avg_line_length": 34.52941131591797, "blob_id": "0baa88d8eca39628be258e9bf2f3cb9ad753ef02", "content_id": "881bf3678548e2f620a493483a9a036b00838a3d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 604, "license_type": "permissive", "max_line_length": 156, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_evpn_global.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages global configuration of EVPN on HUAWEI CloudEngine switches.\n class Ce_evpn_global < Base\n # @return [:enable, :disable] Configure EVPN as the VXLAN control plane.\n attribute :evpn_overlay_enable\n validates :evpn_overlay_enable, presence: true, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6543624401092529, "alphanum_fraction": 0.6577181220054626, "avg_line_length": 35.121212005615234, "blob_id": "e2b8418f33be5befe3d4086e1600ae04809a88db", "content_id": "246944448be5fc444dea506520115974eec5c28d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1192, "license_type": "permissive", "max_line_length": 185, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/network/onyx/onyx_magp.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides declarative management of MAGP protocol on vlan interface of Mellanox ONYX network devices.\n class Onyx_magp < Base\n # @return [Integer] MAGP instance number 1-255\n attribute :magp_id\n validates :magp_id, presence: true, type: Integer\n\n # @return [String] VLAN Interface name.\n attribute :interface\n validates :interface, presence: true, type: String\n\n # @return [:present, :absent, :enabled, :disabled, nil] MAGP state.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :enabled, :disabled], :message=>\"%{value} needs to be :present, :absent, :enabled, :disabled\"}, allow_nil: true\n\n # @return [String, nil] MAGP router IP address.\n attribute :router_ip\n validates :router_ip, type: String\n\n # @return [String, nil] MAGP router MAC address.\n attribute :router_mac\n validates :router_mac, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6426829099655151, "alphanum_fraction": 0.6487804651260376, "avg_line_length": 31.799999237060547, "blob_id": "79def31e7a4114bab8265922592743422e951737", "content_id": "e4afbc6fe1e784d74cffe1bbe14541c549b6e442", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 820, "license_type": "permissive", "max_line_length": 142, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/aws_s3_cors.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage CORS for S3 buckets in AWS\n class Aws_s3_cors < Base\n # @return [String] Name of the s3 bucket\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Array<Hash>, Hash, nil] Cors rules to put on the s3 bucket\n attribute :rules\n validates :rules, type: TypeGeneric.new(Hash)\n\n # @return [:present, :absent] Create or remove cors on the s3 bucket\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6568364500999451, "alphanum_fraction": 0.6648793816566467, "avg_line_length": 37.58620834350586, "blob_id": "fbcfaa786365aafc5ff79c992f10361444d75bb1", "content_id": "3c12ba4a472b3fd1006aa80e1d8aaa4fa354f8ea", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1119, "license_type": "permissive", "max_line_length": 143, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_dns.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, delete, modify DNS servers.\n class Na_ontap_dns < Base\n # @return [:present, :absent, nil] Whether the DNS servers should be enabled for the given vserver.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The name of the vserver to use.\n attribute :vserver\n validates :vserver, presence: true, type: String\n\n # @return [String, nil] List of DNS domains such as 'sales.bar.com'. The first domain is the one that the Vserver belongs to.\n attribute :domains\n validates :domains, type: String\n\n # @return [Array<String>, String, nil] List of IPv4 addresses of name servers such as '123.123.123.123'.\n attribute :nameservers\n validates :nameservers, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6842629313468933, "alphanum_fraction": 0.6842629313468933, "avg_line_length": 45.69767379760742, "blob_id": "60908e159cc2f4ed47fddd51f0122983e11cabcd", "content_id": "4df0cb588f9e520d448435e03327dfb8576a96d4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2008, "license_type": "permissive", "max_line_length": 181, "num_lines": 43, "path": "/lib/ansible/ruby/modules/generated/cloud/digital_ocean/digital_ocean_block_storage.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create/destroy Block Storage volume in DigitalOcean, or attach/detach Block Storage volume to a droplet.\n class Digital_ocean_block_storage < Base\n # @return [:create, :attach] Which operation do you want to perform.\n attribute :command\n validates :command, presence: true, expression_inclusion: {:in=>[:create, :attach], :message=>\"%{value} needs to be :create, :attach\"}\n\n # @return [:present, :absent] Indicate desired state of the target.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}\n\n # @return [Integer, nil] The size of the Block Storage volume in gigabytes. Required when command=create and state=present. If snapshot_id is included, this will be ignored.\n attribute :block_size\n validates :block_size, type: Integer\n\n # @return [String] The name of the Block Storage volume.\n attribute :volume_name\n validates :volume_name, presence: true, type: String\n\n # @return [Object, nil] Description of the Block Storage volume.\n attribute :description\n\n # @return [String] The slug of the region where your Block Storage volume should be located in. If snapshot_id is included, this will be ignored.\n attribute :region\n validates :region, presence: true, type: String\n\n # @return [Object, nil] The snapshot id you would like the Block Storage volume created with. If included, region and block_size will be ignored and changed to null.\n attribute :snapshot_id\n\n # @return [String, nil] The droplet id you want to operate on. Required when command=attach.\n attribute :droplet_id\n validates :droplet_id, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6705729365348816, "alphanum_fraction": 0.6705729365348816, "avg_line_length": 31, "blob_id": "bcd5f4f4c525a727916cf93371fa8db76fd53c5e", "content_id": "008aa65d9e0e3ede85b3d1d249790f620720ab43", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 768, "license_type": "permissive", "max_line_length": 85, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/elb_target_group_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gather facts about ELB target groups in AWS\n class Elb_target_group_facts < Base\n # @return [String, nil] The Amazon Resource Name (ARN) of the load balancer.\n attribute :load_balancer_arn\n validates :load_balancer_arn, type: String\n\n # @return [Object, nil] The Amazon Resource Names (ARN) of the target groups.\n attribute :target_group_arns\n\n # @return [Array<String>, String, nil] The names of the target groups.\n attribute :names\n validates :names, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6463978886604309, "alphanum_fraction": 0.6463978886604309, "avg_line_length": 34.1860466003418, "blob_id": "66ca95e15d316247adbd62cadfe260bba6b21b17", "content_id": "f23a4ead65f2ccee9d97039da629761f3aff2e21", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1513, "license_type": "permissive", "max_line_length": 143, "num_lines": 43, "path": "/lib/ansible/ruby/modules/generated/database/vertica/vertica_role.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Adds or removes Vertica database role and, optionally, assign other roles.\n class Vertica_role < Base\n # @return [String] Name of the role to add or remove.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Comma separated list of roles to assign to the role.\n attribute :assigned_roles\n\n # @return [:present, :absent, nil] Whether to create C(present), drop C(absent) or lock C(locked) a role.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Name of the Vertica database.\n attribute :db\n validates :db, type: String\n\n # @return [String, nil] Name of the Vertica cluster.\n attribute :cluster\n validates :cluster, type: String\n\n # @return [Integer, nil] Vertica cluster port to connect to.\n attribute :port\n validates :port, type: Integer\n\n # @return [String, nil] The username used to authenticate with.\n attribute :login_user\n validates :login_user, type: String\n\n # @return [Object, nil] The password used to authenticate with.\n attribute :login_password\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6772767305374146, "alphanum_fraction": 0.6772767305374146, "avg_line_length": 38, "blob_id": "3f2a7dbd98bebd28d4a0e7787c08980f42cc75f1", "content_id": "c2afad7bd8f639cf27e755242eed045b250f9423", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1131, "license_type": "permissive", "max_line_length": 229, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_partition.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage BIG-IP partitions.\n class Bigip_partition < Base\n # @return [String] Name of the partition\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] The description to attach to the Partition.\n attribute :description\n validates :description, type: String\n\n # @return [Integer, nil] The default Route Domain to assign to the Partition. If no route domain is specified, then the default route domain for the system (typically zero) will be used only when creating a new partition.\n attribute :route_domain\n validates :route_domain, type: Integer\n\n # @return [:present, :absent, nil] Whether the partition should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6835442781448364, "alphanum_fraction": 0.6835442781448364, "avg_line_length": 34.54999923706055, "blob_id": "cbb60967b67da2204389aac994c7af4d042669fb", "content_id": "7284b103fd8e51aac56311a2f6311298ba23e72a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 711, "license_type": "permissive", "max_line_length": 149, "num_lines": 20, "path": "/lib/ansible/ruby/modules/generated/windows/win_ping.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Checks management connectivity of a windows host.\n # This is NOT ICMP ping, this is just a trivial test module.\n # For non-Windows targets, use the M(ping) module instead.\n # For Network targets, use the M(net_ping) module instead.\n class Win_ping < Base\n # @return [String, nil] Alternate data to return instead of 'pong'.,If this parameter is set to C(crash), the module will cause an exception.\n attribute :data\n validates :data, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.683624804019928, "alphanum_fraction": 0.6936936974525452, "avg_line_length": 56.181819915771484, "blob_id": "5ff4a0c45d9e88cb3afda0893f611c8542e30529", "content_id": "0ae5841e4a9c6d0906161953c416276e8df53d39", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1887, "license_type": "permissive", "max_line_length": 258, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/windows/win_feature.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Installs or uninstalls Windows Roles or Features on Windows Server. This module uses the Add/Remove-WindowsFeature Cmdlets on Windows 2008 R2 and Install/Uninstall-WindowsFeature Cmdlets on Windows 2012, which are not available on client os machines.\n class Win_feature < Base\n # @return [Array<String>, String] Names of roles or features to install as a single feature or a comma-separated list of features.\n attribute :name\n validates :name, presence: true, type: TypeGeneric.new(String)\n\n # @return [:absent, :present, nil] State of the features or roles on the system.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Adds all subfeatures of the specified feature.\n attribute :include_sub_features\n validates :include_sub_features, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Adds the corresponding management tools to the specified feature.,Not supported in Windows 2008 R2 and will be ignored.\n attribute :include_management_tools\n validates :include_management_tools, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Specify a source to install the feature from.,Not supported in Windows 2008 R2 and will be ignored.,Can either be C({driveletter}:\\sources\\sxs) or C(\\\\{IP}\\share\\sources\\sxs).\n attribute :source\n validates :source, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6533277034759521, "alphanum_fraction": 0.6583824753761292, "avg_line_length": 40.64912414550781, "blob_id": "450bb70b1e4673f73f814847eb8ef52960e64d2a", "content_id": "e9742e190f66f82cb0690c23b9fdbd0d07baa2d5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2374, "license_type": "permissive", "max_line_length": 162, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_mysqlserver.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and delete instance of MySQL Server.\n class Azure_rm_mysqlserver < Base\n # @return [String] The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String] The name of the server.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Hash, nil] The SKU (pricing tier) of the server.\n attribute :sku\n validates :sku, type: Hash\n\n # @return [String, nil] Resource location. If not set, location from the resource group will be used as default.\n attribute :location\n validates :location, type: String\n\n # @return [Integer, nil] The maximum storage allowed for a server.\n attribute :storage_mb\n validates :storage_mb, type: Integer\n\n # @return [5.6, 5.7, nil] Server version.\n attribute :version\n validates :version, expression_inclusion: {:in=>[5.6, 5.7], :message=>\"%{value} needs to be 5.6, 5.7\"}, allow_nil: true\n\n # @return [Symbol, nil] Enable SSL enforcement.\n attribute :enforce_ssl\n validates :enforce_ssl, type: Symbol\n\n # @return [String, nil] The administrator's login name of a server. Can only be specified when the server is being created (and is required for creation).\n attribute :admin_username\n validates :admin_username, type: String\n\n # @return [String, nil] The password of the administrator login.\n attribute :admin_password\n validates :admin_password, type: String\n\n # @return [String, nil] Create mode of SQL Server\n attribute :create_mode\n validates :create_mode, type: String\n\n # @return [:absent, :present, nil] Assert the state of the MySQL Server. Use 'present' to create or update a server and 'absent' to delete it.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6777456402778625, "alphanum_fraction": 0.6777456402778625, "avg_line_length": 40.93939208984375, "blob_id": "e27131d335d592806b9cdfc906a1b1f1f5d64ea1", "content_id": "de327c70ffe7a946fa1537d452c881c80d673e7b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1384, "license_type": "permissive", "max_line_length": 248, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_sql_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The Users resource represents a database user in a Cloud SQL instance.\n class Gcp_sql_user < Base\n # @return [:present, :absent, nil] Whether the given object should exist in GCP\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String] The host name from which the user can connect. For insert operations, host defaults to an empty string. For update operations, host is specified as part of the request URL. The host name cannot be updated after insertion.\n attribute :host\n validates :host, presence: true, type: String\n\n # @return [String] The name of the user in the Cloud SQL instance.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] The name of the Cloud SQL instance. This does not include the project ID.\n attribute :instance\n validates :instance, presence: true, type: String\n\n # @return [String, nil] The password for the user.\n attribute :password\n validates :password, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7011930346488953, "alphanum_fraction": 0.7011930346488953, "avg_line_length": 46.28205108642578, "blob_id": "dedf0f651452d345f840b1b4ab1ba05d10bee75e", "content_id": "515235f9e41730fd717f3cdcc3fa5ec30ea53740", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1844, "license_type": "permissive", "max_line_length": 331, "num_lines": 39, "path": "/lib/ansible/ruby/modules/generated/network/meraki/meraki_config_template.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows for querying, deleting, binding, and unbinding of configuration templates.\n class Meraki_config_template < Base\n # @return [:absent, :query, :present, nil] Specifies whether configuration template information should be queried, modified, or deleted.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :query, :present], :message=>\"%{value} needs to be :absent, :query, :present\"}, allow_nil: true\n\n # @return [String, nil] Name of organization containing the configuration template.\n attribute :org_name\n validates :org_name, type: String\n\n # @return [Object, nil] ID of organization associated to a configuration template.\n attribute :org_id\n\n # @return [String, nil] Name of the configuration template within an organization to manipulate.\n attribute :config_template\n validates :config_template, type: String\n\n # @return [String, nil] Name of the network to bind or unbind configuration template to.\n attribute :net_name\n validates :net_name, type: String\n\n # @return [Object, nil] ID of the network to bind or unbind configuration template to.\n attribute :net_id\n\n # @return [Symbol, nil] Optional boolean indicating whether the network's switches should automatically bind to profiles of the same model.,This option only affects switch networks and switch templates.,Auto-bind is not valid unless the switch template has at least one profile and has at most one profile per switch model.\n attribute :auto_bind\n validates :auto_bind, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7083333134651184, "alphanum_fraction": 0.7083333134651184, "avg_line_length": 45.85714340209961, "blob_id": "d14cd55a79ed056a9830ab5e0550efc79d52b98f", "content_id": "8a6471b214eff1eb89dbed9ea5afd80cc9553385", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 984, "license_type": "permissive", "max_line_length": 184, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/packaging/os/rhsm_repository.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage(Enable/Disable) RHSM repositories to the Red Hat Subscription Management entitlement platform using the C(subscription-manager) command.\n class Rhsm_repository < Base\n # @return [:present, :enabled, :absent, :disabled] If state is equal to present or disabled, indicates the desired repository state.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :enabled, :absent, :disabled], :message=>\"%{value} needs to be :present, :enabled, :absent, :disabled\"}\n\n # @return [String] The ID of repositories to enable.,To operate on several repositories this can accept a comma separated list or a YAML list.\n attribute :name\n validates :name, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6802906394004822, "alphanum_fraction": 0.6807447671890259, "avg_line_length": 47.93333435058594, "blob_id": "7e9ea744975b40ce456d78f74ea3289c9e9fbbdf", "content_id": "4252c419037edc66688a47dedd1d71b955d9704a", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2202, "license_type": "permissive", "max_line_length": 299, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_qkview.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages creating and downloading qkviews from a BIG-IP. Various options can be provided when creating qkviews. The qkview is important when dealing with F5 support. It may be required that you upload this qkview to the supported channels during resolution of an SRs that you may have opened.\n class Bigip_qkview < Base\n # @return [String, nil] Name of the qkview to create on the remote BIG-IP.\n attribute :filename\n validates :filename, type: String\n\n # @return [String] Destination on your local filesystem when you want to save the qkview.\n attribute :dest\n validates :dest, presence: true, type: String\n\n # @return [Symbol, nil] When C(True), includes the ASM request log data. When C(False), excludes the ASM request log data.\n attribute :asm_request_log\n validates :asm_request_log, type: Symbol\n\n # @return [Integer, nil] Max file size, in bytes, of the qkview to create. By default, no max file size is specified.\n attribute :max_file_size\n validates :max_file_size, type: Integer\n\n # @return [Symbol, nil] Include complete information in the qkview.\n attribute :complete_information\n validates :complete_information, type: Symbol\n\n # @return [Symbol, nil] Exclude core files from the qkview.\n attribute :exclude_core\n validates :exclude_core, type: Symbol\n\n # @return [:all, :audit, :secure, :bash_history, nil] Exclude various file from the qkview.\n attribute :exclude\n validates :exclude, expression_inclusion: {:in=>[:all, :audit, :secure, :bash_history], :message=>\"%{value} needs to be :all, :audit, :secure, :bash_history\"}, allow_nil: true\n\n # @return [Boolean, nil] If C(no), the file will only be transferred if the destination does not exist.\n attribute :force\n validates :force, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.665587306022644, "alphanum_fraction": 0.6741242408752441, "avg_line_length": 52.078125, "blob_id": "3d59862db7c620589d87ae7b7c635d433c583b07", "content_id": "377458c2cdf1cc89883535e2d21a49a056287a46", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3397, "license_type": "permissive", "max_line_length": 303, "num_lines": 64, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_vlan.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages VLAN configurations on NX-OS switches.\n class Nxos_vlan < Base\n # @return [Integer, nil] Single VLAN ID.\n attribute :vlan_id\n validates :vlan_id, type: Integer\n\n # @return [Array<String>, String, nil] Range of VLANs such as 2-10 or 2,5,10-15, etc.\n attribute :vlan_range\n validates :vlan_range, type: TypeGeneric.new(String)\n\n # @return [String, nil] Name of VLAN or keyword 'default'.\n attribute :name\n validates :name, type: String\n\n # @return [Array<String>, String, nil] List of interfaces that should be associated to the VLAN or keyword 'default'.\n attribute :interfaces\n validates :interfaces, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] This is a intent option and checks the operational state of the for given vlan C(name) for associated interfaces. If the value in the C(associated_interfaces) does not match with the operational state of vlan interfaces on device it will result in failure.\n attribute :associated_interfaces\n validates :associated_interfaces, type: TypeGeneric.new(String)\n\n # @return [:active, :suspend, nil] Manage the vlan operational state of the VLAN\n attribute :vlan_state\n validates :vlan_state, expression_inclusion: {:in=>[:active, :suspend], :message=>\"%{value} needs to be :active, :suspend\"}, allow_nil: true\n\n # @return [:up, :down, nil] Manage the VLAN administrative state of the VLAN equivalent to shut/no shut in VLAN config mode.\n attribute :admin_state\n validates :admin_state, expression_inclusion: {:in=>[:up, :down], :message=>\"%{value} needs to be :up, :down\"}, allow_nil: true\n\n # @return [Object, nil] The Virtual Network Identifier (VNI) ID that is mapped to the VLAN. Valid values are integer and keyword 'default'. Range 4096-16773119.\n attribute :mapped_vni\n\n # @return [:present, :absent, nil] Manage the state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:ce, :fabricpath, nil] Set VLAN mode to classical ethernet or fabricpath. This is a valid option for Nexus 5000 and 7000 series.\n attribute :mode\n validates :mode, expression_inclusion: {:in=>[:ce, :fabricpath], :message=>\"%{value} needs to be :ce, :fabricpath\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash, nil] List of VLANs definitions.\n attribute :aggregate\n validates :aggregate, type: TypeGeneric.new(Hash)\n\n # @return [:yes, :no, nil] Purge VLANs not defined in the I(aggregate) parameter. This parameter can be used without aggregate as well.\n attribute :purge\n validates :purge, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Time in seconds to wait before checking for the operational state on remote device. This wait is applicable for operational state arguments.\n attribute :delay\n validates :delay, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6445895433425903, "alphanum_fraction": 0.6445895433425903, "avg_line_length": 35.965518951416016, "blob_id": "dfd353625783e20a01258eb5307ca58b4c950386", "content_id": "3fa923a110a9dd114554c4e5e96ed6054c7d98a9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1072, "license_type": "permissive", "max_line_length": 143, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/vultr/vr_startup_script.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and remove startup scripts.\n class Vultr_startup_script < Base\n # @return [String] The script name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:boot, :pxe, nil] The script type, can not be changed once created.\n attribute :script_type\n validates :script_type, expression_inclusion: {:in=>[:boot, :pxe], :message=>\"%{value} needs to be :boot, :pxe\"}, allow_nil: true\n\n # @return [String, nil] The script source code.,Required if (state=present).\n attribute :script\n validates :script, type: String\n\n # @return [:present, :absent, nil] State of the script.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6792114973068237, "alphanum_fraction": 0.6792114973068237, "avg_line_length": 48.82143020629883, "blob_id": "530c4989df33c508b28b058dfcbe1eb93019885c", "content_id": "cd2b8e303039f3e8bc79a121b7cf04cf7c03d5a2", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2790, "license_type": "permissive", "max_line_length": 181, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_host_datastore.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to mount/umount datastore on ESXi host.\n # This module only support NFS/VMFS type of datastores.\n # For VMFS datastore, available device must already be connected on ESXi host.\n # All parameters and VMware object names are case sensitive.\n class Vmware_host_datastore < Base\n # @return [String] Name of the datacenter to add the datastore.\n attribute :datacenter_name\n validates :datacenter_name, presence: true, type: String\n\n # @return [String] Name of the datastore to add/remove.\n attribute :datastore_name\n validates :datastore_name, presence: true, type: String\n\n # @return [:nfs, :vmfs] Type of the datastore to configure (nfs/vmfs).\n attribute :datastore_type\n validates :datastore_type, presence: true, expression_inclusion: {:in=>[:nfs, :vmfs], :message=>\"%{value} needs to be :nfs, :vmfs\"}\n\n # @return [String, nil] NFS host serving nfs datastore.,Required if datastore type is set to C(nfs) and state is set to C(present), else unused.\n attribute :nfs_server\n validates :nfs_server, type: String\n\n # @return [String, nil] Resource path on NFS host.,Required if datastore type is set to C(nfs) and state is set to C(present), else unused.\n attribute :nfs_path\n validates :nfs_path, type: String\n\n # @return [Symbol, nil] ReadOnly or ReadWrite mount.,Unused if datastore type is not set to C(nfs) and state is not set to C(present).\n attribute :nfs_ro\n validates :nfs_ro, type: Symbol\n\n # @return [String, nil] Name of the device to be used as VMFS datastore.,Required for VMFS datastore type and state is set to C(present), else unused.\n attribute :vmfs_device_name\n validates :vmfs_device_name, type: String\n\n # @return [Integer, nil] VMFS version to use for datastore creation.,Unused if datastore type is not set to C(vmfs) and state is not set to C(present).\n attribute :vmfs_version\n validates :vmfs_version, type: Integer\n\n # @return [String] ESXi hostname to manage the datastore.\n attribute :esxi_hostname\n validates :esxi_hostname, presence: true, type: String\n\n # @return [:present, :absent, nil] present: Mount datastore on host if datastore is absent else do nothing.,absent: Umount datastore if datastore is present else do nothing.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6787723898887634, "alphanum_fraction": 0.6797953844070435, "avg_line_length": 53.30555725097656, "blob_id": "da76f8546703c8fe45c79c8ba67be5f52acd658e", "content_id": "0b625d82ce4b8e1a55aa577ac3c0cb870e60c050", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1955, "license_type": "permissive", "max_line_length": 405, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/system/svc.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Controls daemontools services on remote hosts using the svc utility.\n class Svc < Base\n # @return [String] Name of the service to manage.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:killed, :once, :reloaded, :restarted, :started, :stopped, nil] C(Started)/C(stopped) are idempotent actions that will not run commands unless necessary. C(restarted) will always bounce the svc (svc -t) and C(killed) will always bounce the svc (svc -k). C(reloaded) will send a sigusr1 (svc -1). C(once) will run a normally downed svc once (svc -o), not really an idempotent operation.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:killed, :once, :reloaded, :restarted, :started, :stopped], :message=>\"%{value} needs to be :killed, :once, :reloaded, :restarted, :started, :stopped\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Should a 'down' file exist or not, if it exists it disables auto startup. defaults to no. Downed does not imply stopped.\n attribute :downed\n validates :downed, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Symbol, nil] Wheater the service is enabled or not, if disabled it also implies stopped. Make note that a service can be enabled and downed (no auto restart).\n attribute :enabled\n validates :enabled, type: Symbol\n\n # @return [String, nil] directory svscan watches for services\n attribute :service_dir\n validates :service_dir, type: String\n\n # @return [Object, nil] directory where services are defined, the source of symlinks to service_dir.\n attribute :service_src\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6658682823181152, "alphanum_fraction": 0.6658682823181152, "avg_line_length": 36.95454406738281, "blob_id": "ac2e894a40c87d2fbd4728dedda56816ec03b31e", "content_id": "e321d4441a6c4e0e4310408d8d2dcb6e771011bd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 835, "license_type": "permissive", "max_line_length": 186, "num_lines": 22, "path": "/lib/ansible/ruby/modules/generated/utilities/logic/async_status.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module gets the status of an asynchronous task.\n # This module is also supported for Windows targets.\n class Async_status < Base\n # @return [Object] Job or task identifier\n attribute :jid\n validates :jid, presence: true\n\n # @return [:status, :cleanup, nil] if C(status), obtain the status; if C(cleanup), clean up the async job cache (by default in C(~/.ansible_async/)) for the specified job I(jid).\n attribute :mode\n validates :mode, expression_inclusion: {:in=>[:status, :cleanup], :message=>\"%{value} needs to be :status, :cleanup\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.642329752445221, "alphanum_fraction": 0.642329752445221, "avg_line_length": 37.09375, "blob_id": "ea5da9557aeee3eab4ab54d530f2dedc729d1c6f", "content_id": "af4653058b2b535b3ed5c003eadf4de7818094bd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1219, "license_type": "permissive", "max_line_length": 199, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_role.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update, delete user roles.\n class Cs_role < Base\n # @return [String] Name of the role.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] ID of the role.,If provided, C(id) is used as key.\n attribute :id\n validates :id, type: String\n\n # @return [:User, :DomainAdmin, :ResourceAdmin, :Admin, nil] Type of the role.,Only considered for creation.\n attribute :role_type\n validates :role_type, expression_inclusion: {:in=>[:User, :DomainAdmin, :ResourceAdmin, :Admin], :message=>\"%{value} needs to be :User, :DomainAdmin, :ResourceAdmin, :Admin\"}, allow_nil: true\n\n # @return [Object, nil] Description of the role.\n attribute :description\n\n # @return [:present, :absent, nil] State of the role.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6812030076980591, "alphanum_fraction": 0.6812030076980591, "avg_line_length": 30.66666603088379, "blob_id": "bcb81c2734b79d3105a84acb87ae533b7035ab82", "content_id": "1603f77b6c56611101626efb92c018a5e51e36ce", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 665, "license_type": "permissive", "max_line_length": 91, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/network/nso/nso_query.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides support for querying data from Cisco NSO using XPath.\n class Nso_query < Base\n # @return [String] XPath selection relative to the root.\n attribute :xpath\n validates :xpath, presence: true, type: String\n\n # @return [Array<String>, String] List of fields to select from matching nodes.\\r\\n\n attribute :fields\n validates :fields, presence: true, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6588652729988098, "alphanum_fraction": 0.6744681000709534, "avg_line_length": 37.10810852050781, "blob_id": "89a03b54b37fa30d0807191c2fb728007a177c58", "content_id": "5b61e1c3cd83fff04f0bf7423d49f5f03503256d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1410, "license_type": "permissive", "max_line_length": 137, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/notification/twilio.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Sends a text message to a phone number through the Twilio messaging API.\n class Twilio < Base\n # @return [String] user's Twilio account token found on the account page\n attribute :account_sid\n validates :account_sid, presence: true, type: String\n\n # @return [String] user's Twilio authentication token\n attribute :auth_token\n validates :auth_token, presence: true, type: String\n\n # @return [String] the body of the text message\n attribute :msg\n validates :msg, presence: true, type: String\n\n # @return [Array<Integer>, Integer] one or more phone numbers to send the text message to, format +15551112222\n attribute :to_number\n validates :to_number, presence: true, type: TypeGeneric.new(Integer)\n\n # @return [Integer] the Twilio number to send the text message from, format +15551112222\n attribute :from_number\n validates :from_number, presence: true, type: Integer\n\n # @return [String, nil] a URL with a picture, video or sound clip to send with an MMS (multimedia message) instead of a plain SMS\n attribute :media_url\n validates :media_url, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7034883499145508, "alphanum_fraction": 0.7267441749572754, "avg_line_length": 20.5, "blob_id": "c74bd31665aaa3ffa8d53c7a06e377176e6e8bbf", "content_id": "223f68c520ff10780f4a71cac8b6da4223ab9986", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 344, "license_type": "permissive", "max_line_length": 66, "num_lines": 16, "path": "/lib/ansible/ruby/modules/custom/utilities/logic/wait_for.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# VALIDATED_CHECKSUM: FNDV+m2tnS3VzvDOwCruOZV1Z7svZwX3snhH4Zf2l4U=\n\nrequire 'ansible/ruby/modules/generated/utilities/logic/wait_for'\n\nmodule Ansible\n module Ruby\n module Modules\n class Wait_for\n remove_existing_validations :port\n validates :port, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.46568626165390015, "alphanum_fraction": 0.4673202633857727, "avg_line_length": 21.66666603088379, "blob_id": "ae80f57a7b6ef91503b0958d34b5748160d3ac95", "content_id": "6e1c21180d8bb9559b5dae60d674c8a8968f7c23", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 612, "license_type": "permissive", "max_line_length": 65, "num_lines": 27, "path": "/lib/ansible/ruby/rake/task_util.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# See LICENSE.txt for license\nmodule Ansible\n module Ruby\n module Rake\n module TaskUtil\n def yaml_filenames(ruby_files)\n ruby_files.map { |file| file.sub(/\\.[^.]+\\z/, '.yml') }\n end\n\n def parse_params(parameters)\n deps = nil\n name = case parameters\n when Hash\n name = parameters.keys[0]\n deps = parameters[name]\n name\n else\n parameters\n end\n [name, deps]\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6520270109176636, "alphanum_fraction": 0.6570945978164673, "avg_line_length": 38.46666717529297, "blob_id": "aec378dda4ad8e86657691a25babb465a416972c", "content_id": "999001e47988521e6e3e29b89e10140ae9888bcd", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1776, "license_type": "permissive", "max_line_length": 139, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_service_processor_network.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Modify a ONTAP service processor network\n class Na_ontap_service_processor_network < Base\n # @return [:present, nil] Whether the specified service processor network should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present], :message=>\"%{value} needs to be :present\"}, allow_nil: true\n\n # @return [:ipv4, :ipv6] Specify address class.\n attribute :address_type\n validates :address_type, presence: true, expression_inclusion: {:in=>[:ipv4, :ipv6], :message=>\"%{value} needs to be :ipv4, :ipv6\"}\n\n # @return [Symbol] Specify whether to enable or disable the service processor network.\n attribute :is_enabled\n validates :is_enabled, presence: true, type: Symbol\n\n # @return [String] The node where the service processor network should be enabled\n attribute :node\n validates :node, presence: true, type: String\n\n # @return [:v4, :none, nil] Specify dhcp type.\n attribute :dhcp\n validates :dhcp, expression_inclusion: {:in=>[:v4, :none], :message=>\"%{value} needs to be :v4, :none\"}, allow_nil: true\n\n # @return [Object, nil] Specify the gateway ip.\n attribute :gateway_ip_address\n\n # @return [Object, nil] Specify the service processor ip address.\n attribute :ip_address\n\n # @return [Object, nil] Specify the service processor netmask.\n attribute :netmask\n\n # @return [Object, nil] Specify the service processor prefix_length.\n attribute :prefix_length\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7107017040252686, "alphanum_fraction": 0.7107017040252686, "avg_line_length": 61.219512939453125, "blob_id": "7fa2401deea7af823e16867815c3b1ab79ad95be", "content_id": "e532db5e65021b28b63f825c2463c2d241e918da", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2551, "license_type": "permissive", "max_line_length": 407, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/network/aos/aos_blueprint_param.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Apstra AOS Blueprint Parameter module let you manage your Blueprint Parameter easily. You can create access, define and delete Blueprint Parameter. The list of Parameters supported is different per Blueprint. The option I(get_param_list) can help you to access the list of supported Parameters for your blueprint. This module is idempotent and support the I(check) mode. It's using the AOS REST API.\n class Aos_blueprint_param < Base\n # @return [String] An existing AOS session as obtained by M(aos_login) module.\n attribute :session\n validates :session, presence: true, type: String\n\n # @return [String] Blueprint Name or Id as defined in AOS.\n attribute :blueprint\n validates :blueprint, presence: true, type: String\n\n # @return [String, nil] Name of blueprint parameter, as defined by AOS design template. You can use the option I(get_param_list) to get the complete list of supported parameters for your blueprint.\n attribute :name\n validates :name, type: String\n\n # @return [Hash, nil] Blueprint parameter value. This value may be transformed by using the I(param_map) field; used when the blueprint parameter requires an AOS unique ID value.\n attribute :value\n validates :value, type: Hash\n\n # @return [Boolean, nil] Get the complete list of supported parameters for this blueprint and the description of those parameters.\n attribute :get_param_list\n validates :get_param_list, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Indicate what is the expected state of the Blueprint Parameter (present or not).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Hash, nil] Defines the aos-pyez collection that will is used to map the user-defined item name into the AOS unique ID value. For example, if the caller provides an IP address pool I(param_value) called \"Server-IpAddrs\", then the aos-pyez collection is 'IpPools'. Some I(param_map) are already defined by default like I(logical_device_maps).\n attribute :param_map\n validates :param_map, type: Hash\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6467620134353638, "alphanum_fraction": 0.6467620134353638, "avg_line_length": 29.487178802490234, "blob_id": "8af0628cd32fd5d551b26b9b37b7ef24c40d3f43", "content_id": "cb8b2f26d67d269b541a395cc0792f212ba84d2f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1189, "license_type": "permissive", "max_line_length": 71, "num_lines": 39, "path": "/lib/ansible/ruby/modules/generated/database/vertica/vertica_configuration.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Updates Vertica configuration parameters.\n class Vertica_configuration < Base\n # @return [String] Name of the parameter to update.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] Value of the parameter to be set.\n attribute :value\n validates :value, presence: true, type: String\n\n # @return [Object, nil] Name of the Vertica database.\n attribute :db\n\n # @return [String, nil] Name of the Vertica cluster.\n attribute :cluster\n validates :cluster, type: String\n\n # @return [Integer, nil] Vertica cluster port to connect to.\n attribute :port\n validates :port, type: Integer\n\n # @return [String, nil] The username used to authenticate with.\n attribute :login_user\n validates :login_user, type: String\n\n # @return [Object, nil] The password used to authenticate with.\n attribute :login_password\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7210333943367004, "alphanum_fraction": 0.7218163013458252, "avg_line_length": 67.42857360839844, "blob_id": "e4745c4e8b384b009ab58bd22a23f6e9bfbc9878", "content_id": "95b697813ffe553e03efe9615eac6cb6e15e4002", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3832, "license_type": "permissive", "max_line_length": 522, "num_lines": 56, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_gtm_virtual_server.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages F5 BIG-IP GTM virtual servers. A GTM server can have many virtual servers associated with it. They are arranged in much the same way that pool members are to pools.\n class Bigip_gtm_virtual_server < Base\n # @return [String, nil] Specifies the name of the virtual server.\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] Specifies the name of the server that the virtual server is associated with.\n attribute :server_name\n validates :server_name, type: String\n\n # @return [Object, nil] Specifies the IP Address of the virtual server.,When creating a new GTM virtual server, this parameter is required.\n attribute :address\n\n # @return [Object, nil] Specifies the service port number for the virtual server or pool member. For example, the HTTP service is typically port 80.,To specify all ports, use an C(*).,When creating a new GTM virtual server, if this parameter is not specified, a default of C(*) will be used.\n attribute :port\n\n # @return [Object, nil] Specifies the translation IP address for the virtual server.,To unset this parameter, provide an empty string (C(\"\")) as a value.,When creating a new GTM virtual server, if this parameter is not specified, a default of C(::) will be used.\n attribute :translation_address\n\n # @return [Object, nil] Specifies the translation port number or service name for the virtual server.,To specify all ports, use an C(*).,When creating a new GTM virtual server, if this parameter is not specified, a default of C(*) will be used.\n attribute :translation_port\n\n # @return [Object, nil] Specifies, if you activate more than one health monitor, the number of health monitors that must receive successful responses in order for the link to be considered available.\n attribute :availability_requirements\n\n # @return [Object, nil] Specifies the health monitors that the system currently uses to monitor this resource.,When C(availability_requirements.type) is C(require), you may only have a single monitor in the C(monitors) list.\n attribute :monitors\n\n # @return [Object, nil] Specifies the virtual servers on which the current virtual server depends.,If any of the specified servers are unavailable, the current virtual server is also listed as unavailable.\n attribute :virtual_server_dependencies\n\n # @return [Object, nil] Specifies a link to assign to the server or virtual server.\n attribute :link\n\n # @return [Object, nil] Specifies resource thresholds or limit requirements at the server level.,When you enable one or more limit settings, the system then uses that data to take servers in and out of service.,You can define limits for any or all of the limit settings. However, when a server does not meet the resource threshold limit requirement, the system marks the entire server as unavailable and directs load-balancing traffic to another resource.,The limit settings available depend on the type of server.\n attribute :limits\n\n # @return [String, nil] Device partition to manage resources on.\n attribute :partition\n validates :partition, type: String\n\n # @return [:present, :absent, :enabled, :disabled, nil] When C(present), ensures that the resource exists.,When C(absent), ensures the resource is removed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :enabled, :disabled], :message=>\"%{value} needs to be :present, :absent, :enabled, :disabled\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6625916957855225, "alphanum_fraction": 0.6625916957855225, "avg_line_length": 34.05714416503906, "blob_id": "79f9932e5f8af24be87eb75e2de2363235f90717", "content_id": "2d58dc43eba81867b799c60cd2d1094b604ffcf4", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1227, "license_type": "permissive", "max_line_length": 125, "num_lines": 35, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_cluster.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create or join or apply licenses to ONTAP clusters\n class Na_ontap_cluster < Base\n # @return [:present, nil] Whether the specified cluster should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present], :message=>\"%{value} needs to be :present\"}, allow_nil: true\n\n # @return [String, nil] The name of the cluster to manage.\n attribute :cluster_name\n validates :cluster_name, type: String\n\n # @return [String, nil] IP address of cluster to be joined\n attribute :cluster_ip_address\n validates :cluster_ip_address, type: String\n\n # @return [String, nil] License code to be applied to the cluster\n attribute :license_code\n validates :license_code, type: String\n\n # @return [Object, nil] License package name of the license to be removed\n attribute :license_package\n\n # @return [Object, nil] Serial number of the cluster node\n attribute :node_serial_number\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.5379188656806946, "alphanum_fraction": 0.5423280596733093, "avg_line_length": 26, "blob_id": "f36af70c265eeba92f68429c77c34df3ecedaa43", "content_id": "69fedc414785f1ff643b07ae52efe1c74773083a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1134, "license_type": "permissive", "max_line_length": 85, "num_lines": 42, "path": "/lib/ansible/ruby/modules/custom/cloud/core/docker/docker_container.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# VALIDATED_CHECKSUM: lHZp9oMwmjDwRE9+hjQipDVUWffkBzvA6grVp2r/t6s=\n\n# See LICENSE.txt for license\n\nrequire 'ansible/ruby/modules/generated/cloud/docker/docker_container'\n\nmodule Ansible\n module Ruby\n module Modules\n class Docker_container\n remove_existing_validations :volumes\n validates :volumes, type: Hash\n remove_existing_validations :network_mode\n validates :network_mode, type: String\n\n def to_h\n result = super\n data = result[:docker_container]\n data[:volumes] = transform_volumes data[:volumes] if data.include? :volumes\n result\n end\n\n private\n\n def transform_volumes(input)\n input.map do |host_path, info|\n image_path = if info.is_a? Hash\n flags = info[:flags]\n path = info[:path]\n [path, flags].join ':'\n else\n info\n end\n [host_path, image_path].join ':'\n end\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6609588861465454, "alphanum_fraction": 0.6609588861465454, "avg_line_length": 35.5, "blob_id": "21cbeabcf3bfe44a22b945611b838ade8686bb7d", "content_id": "3aa099d54e94bad1864a8936287f869aae01c4ea", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1752, "license_type": "permissive", "max_line_length": 210, "num_lines": 48, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gce_img.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can create and delete GCE private images from gzipped compressed tarball containing raw disk data or from existing detached disks in any zone. U(https://cloud.google.com/compute/docs/images)\n class Gce_img < Base\n # @return [String] the name of the image to create or delete\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] an optional description\n attribute :description\n\n # @return [Object, nil] an optional family name\n attribute :family\n\n # @return [String, nil] the source disk or the Google Cloud Storage URI to create the image from\n attribute :source\n validates :source, type: String\n\n # @return [:present, :absent, nil] desired state of the image\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] the zone of the disk specified by source\n attribute :zone\n validates :zone, type: String\n\n # @return [Integer, nil] timeout for the operation\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [Object, nil] service account email\n attribute :service_account_email\n\n # @return [Object, nil] path to the pem file associated with the service account email\n attribute :pem_file\n\n # @return [Object, nil] your GCE project ID\n attribute :project_id\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7012736201286316, "alphanum_fraction": 0.7012736201286316, "avg_line_length": 70.97222137451172, "blob_id": "b46af7e7f1cdae79977a3f532825bae65718bc2e", "content_id": "90ca70830a36e934f02a1a6ccb0079bcc566ccea", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2591, "license_type": "permissive", "max_line_length": 661, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/cloud/openstack/os_flavor_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Retrieve facts about available OpenStack instance flavors. By default, facts about ALL flavors are retrieved. Filters can be applied to get facts for only matching flavors. For example, you can filter on the amount of RAM available to the flavor, or the number of virtual CPUs available to the flavor, or both. When specifying multiple filters, *ALL* filters must match on a flavor before that flavor is returned as a fact.\n class Os_flavor_facts < Base\n # @return [String, nil] A flavor name. Cannot be used with I(ram) or I(vcpus) or I(ephemeral).\n attribute :name\n validates :name, type: String\n\n # @return [:yes, :no, nil] A string used for filtering flavors based on the amount of RAM (in MB) desired. This string accepts the following special values: 'MIN' (return flavors with the minimum amount of RAM), and 'MAX' (return flavors with the maximum amount of RAM).,A specific amount of RAM may also be specified. Any flavors with this exact amount of RAM will be returned.,A range of acceptable RAM may be given using a special syntax. Simply prefix the amount of RAM with one of these acceptable range values: '<', '>', '<=', '>='. These values represent less than, greater than, less than or equal to, and greater than or equal to, respectively.\n attribute :ram\n validates :ram, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] A string used for filtering flavors based on the number of virtual CPUs desired. Format is the same as the I(ram) parameter.\n attribute :vcpus\n validates :vcpus, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Limits the number of flavors returned. All matching flavors are returned by default.\n attribute :limit\n validates :limit, type: Integer\n\n # @return [:yes, :no, nil] A string used for filtering flavors based on the amount of ephemeral storage. Format is the same as the I(ram) parameter\n attribute :ephemeral\n validates :ephemeral, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] Ignored. Present for backwards compatibility\n attribute :availability_zone\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6847484111785889, "alphanum_fraction": 0.7114779949188232, "avg_line_length": 59.57143020629883, "blob_id": "830d602a5d1cf25ef5f6e29d4e527239f4016e8f", "content_id": "838e47d4cf075b8b4a3c1fac915e3598b9ad24f9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2544, "license_type": "permissive", "max_line_length": 229, "num_lines": 42, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_bfd_global.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages BFD global configuration on HUAWEI CloudEngine devices.\n class Ce_bfd_global < Base\n # @return [:enable, :disable, nil] Enables the global Bidirectional Forwarding Detection (BFD) function.\n attribute :bfd_enable\n validates :bfd_enable, expression_inclusion: {:in=>[:enable, :disable], :message=>\"%{value} needs to be :enable, :disable\"}, allow_nil: true\n\n # @return [Object, nil] Specifies the default multicast IP address. The value ranges from 224.0.0.107 to 224.0.0.250.\n attribute :default_ip\n\n # @return [Object, nil] Indicates the priority of BFD control packets for dynamic BFD sessions. The value is an integer ranging from 0 to 7. The default priority is 7, which is the highest priority of BFD control packets.\n attribute :tos_exp_dynamic\n\n # @return [Object, nil] Indicates the priority of BFD control packets for static BFD sessions. The value is an integer ranging from 0 to 7. The default priority is 7, which is the highest priority of BFD control packets.\n attribute :tos_exp_static\n\n # @return [Object, nil] Specifies an initial flapping suppression time for a BFD session. The value is an integer ranging from 1 to 3600000, in milliseconds. The default value is 2000.\n attribute :damp_init_wait_time\n\n # @return [Object, nil] Specifies a maximum flapping suppression time for a BFD session. The value is an integer ranging from 1 to 3600000, in milliseconds. The default value is 15000.\n attribute :damp_max_wait_time\n\n # @return [Object, nil] Specifies a secondary flapping suppression time for a BFD session. The value is an integer ranging from 1 to 3600000, in milliseconds. The default value is 5000.\n attribute :damp_second_wait_time\n\n # @return [Object, nil] Specifies the delay before a BFD session becomes Up. The value is an integer ranging from 1 to 600, in seconds. The default value is 0, indicating that a BFD session immediately becomes Up.\n attribute :delay_up_time\n\n # @return [:present, :absent, nil] Determines whether the config should be present or not on the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7152866125106812, "alphanum_fraction": 0.7152866125106812, "avg_line_length": 63.081634521484375, "blob_id": "646c155de137147cc62217ff3d5d47869a5821bc", "content_id": "f42568cca8610eb4c13b940295d2afce5d783376", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3140, "license_type": "permissive", "max_line_length": 328, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/identity/ipa/ipa_role.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add, modify and delete a role within FreeIPA server using FreeIPA API\n class Ipa_role < Base\n # @return [Object] Role name.,Can not be changed as it is the unique identifier.\n attribute :cn\n validates :cn, presence: true\n\n # @return [String, nil] A description of this role-group.\n attribute :description\n validates :description, type: String\n\n # @return [Array<String>, String, nil] List of group names assign to this role.,If an empty list is passed all assigned groups will be unassigned from the role.,If option is omitted groups will not be checked or changed.,If option is passed all assigned groups that are not passed will be unassigned from the role.\n attribute :group\n validates :group, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] List of host names to assign.,If an empty list is passed all assigned hosts will be unassigned from the role.,If option is omitted hosts will not be checked or changed.,If option is passed all assigned hosts that are not passed will be unassigned from the role.\n attribute :host\n validates :host, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] List of host group names to assign.,If an empty list is passed all assigned host groups will be removed from the role.,If option is omitted host groups will not be checked or changed.,If option is passed all assigned hostgroups that are not passed will be unassigned from the role.\n attribute :hostgroup\n validates :hostgroup, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] List of privileges granted to the role.,If an empty list is passed all assigned privileges will be removed.,If option is omitted privileges will not be checked or changed.,If option is passed all assigned privileges that are not passed will be removed.\n attribute :privilege\n validates :privilege, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] List of service names to assign.,If an empty list is passed all assigned services will be removed from the role.,If option is omitted services will not be checked or changed.,If option is passed all assigned services that are not passed will be removed from the role.\n attribute :service\n validates :service, type: TypeGeneric.new(String)\n\n # @return [:present, :absent, nil] State to ensure\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] List of user names to assign.,If an empty list is passed all assigned users will be removed from the role.,If option is omitted users will not be checked or changed.\n attribute :user\n validates :user, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6660887598991394, "alphanum_fraction": 0.6688627004623413, "avg_line_length": 43.369232177734375, "blob_id": "b8821d17af8ce725f9ccea85973ef9c9c0b9a93a", "content_id": "3195263769ff86578cb249336966bb379e75e3a4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2884, "license_type": "permissive", "max_line_length": 190, "num_lines": 65, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_backupconfiguration.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure BackupConfiguration object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_backupconfiguration < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Object, nil] Prefix of the exported configuration file.,Field introduced in 17.1.1.\n attribute :backup_file_prefix\n\n # @return [Object, nil] Passphrase of backup configuration.\n attribute :backup_passphrase\n\n # @return [Object, nil] Rotate the backup files based on this count.,Allowed values are 1-20.,Default value when not specified in API or module is interpreted by Avi Controller as 4.\n attribute :maximum_backups_stored\n\n # @return [String] Name of backup configuration.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Object, nil] Directory at remote destination with write permission for ssh user.\n attribute :remote_directory\n\n # @return [Object, nil] Remote destination.\n attribute :remote_hostname\n\n # @return [Symbol, nil] Local backup.\n attribute :save_local\n validates :save_local, type: Symbol\n\n # @return [Object, nil] Access credentials for remote destination.,It is a reference to an object of type cloudconnectoruser.\n attribute :ssh_user_ref\n\n # @return [Object, nil] It is a reference to an object of type tenant.\n attribute :tenant_ref\n\n # @return [Symbol, nil] Remote backup.\n attribute :upload_to_remote_host\n validates :upload_to_remote_host, type: Symbol\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Unique object identifier of the object.\n attribute :uuid\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7045260667800903, "alphanum_fraction": 0.7045260667800903, "avg_line_length": 62.87272644042969, "blob_id": "3bb34bef60fb03d8b55ecfde71a096ce82abcb77", "content_id": "91197d7b54acee026dcebb63e6cdce84e2301f4a", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3513, "license_type": "permissive", "max_line_length": 507, "num_lines": 55, "path": "/lib/ansible/ruby/modules/generated/clustering/consul_session.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows the addition, modification and deletion of sessions in a consul cluster. These sessions can then be used in conjunction with key value pairs to implement distributed locks. In depth documentation for working with sessions can be found at http://www.consul.io/docs/internals/sessions.html\n class Consul_session < Base\n # @return [:absent, :info, :list, :node, :present, nil] Whether the session should be present i.e. created if it doesn't exist, or absent, removed if present. If created, the ID for the session is returned in the output. If absent, the name or ID is required to remove the session. Info for a single session, all the sessions for a node or all available sessions can be retrieved by specifying info, node or list for the state; for node or info, the node name or session id is required as parameter.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :info, :list, :node, :present], :message=>\"%{value} needs to be :absent, :info, :list, :node, :present\"}, allow_nil: true\n\n # @return [String, nil] The name that should be associated with the session. This is opaque to Consul and not required.\n attribute :name\n validates :name, type: String\n\n # @return [Integer, nil] The optional lock delay that can be attached to the session when it is created. Locks for invalidated sessions ar blocked from being acquired until this delay has expired. Durations are in seconds.\n attribute :delay\n validates :delay, type: Integer\n\n # @return [Object, nil] The name of the node that with which the session will be associated. by default this is the name of the agent.\n attribute :node\n\n # @return [Object, nil] The name of the datacenter in which the session exists or should be created.\n attribute :datacenter\n\n # @return [Array<String>, String, nil] A list of checks that will be used to verify the session health. If all the checks fail, the session will be invalidated and any locks associated with the session will be release and can be acquired once the associated lock delay has expired.\n attribute :checks\n validates :checks, type: TypeGeneric.new(String)\n\n # @return [String, nil] The host of the consul agent defaults to localhost.\n attribute :host\n validates :host, type: String\n\n # @return [Integer, nil] The port on which the consul agent is running.\n attribute :port\n validates :port, type: Integer\n\n # @return [String, nil] The protocol scheme on which the consul agent is running.\n attribute :scheme\n validates :scheme, type: String\n\n # @return [Boolean, nil] Whether to verify the tls certificate of the consul agent.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:delete, :release, nil] The optional behavior that can be attached to the session when it is created. This controls the behavior when a session is invalidated.\n attribute :behavior\n validates :behavior, expression_inclusion: {:in=>[:delete, :release], :message=>\"%{value} needs to be :delete, :release\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6736508011817932, "alphanum_fraction": 0.6736508011817932, "avg_line_length": 42.75, "blob_id": "58eb87058e269ff15e9523789c495794fd2e5d1f", "content_id": "de89af07b9b974bc185456db2bcb50b194cc86e5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1575, "license_type": "permissive", "max_line_length": 147, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/windows/win_msi.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Installs or uninstalls a Windows MSI file that is already located on the target server.\n class Win_msi < Base\n # @return [String] File system path to the MSI file to install.\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [Object, nil] Additional arguments to pass to the msiexec.exe command.\n attribute :extra_args\n\n # @return [:absent, :present, nil] Whether the MSI file should be installed or uninstalled.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] Path to a file created by installing the MSI to prevent from attempting to reinstall the package on every run.\n attribute :creates\n validates :creates, type: String\n\n # @return [String, nil] Path to a file removed by uninstalling the MSI to prevent from attempting to re-uninstall the package on every run.\n attribute :removes\n validates :removes, type: String\n\n # @return [:yes, :no, nil] Specify whether to wait for install or uninstall to complete before continuing.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6833683252334595, "alphanum_fraction": 0.6838929653167725, "avg_line_length": 51.94444274902344, "blob_id": "9c3271d389aa8e9b2ae5971cdaaf740c236a1174", "content_id": "bfb500ac33c48f24a0a286e24439ba00d4b441c5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3812, "license_type": "permissive", "max_line_length": 785, "num_lines": 72, "path": "/lib/ansible/ruby/modules/generated/cloud/azure/azure_rm_storageblob.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and delete blob containers and blob objects. Use to upload a file and store it as a blob object, or download a blob object to a file.\n class Azure_rm_storageblob < Base\n # @return [String] Name of the storage account to use.\n attribute :storage_account_name\n validates :storage_account_name, presence: true, type: String\n\n # @return [String, nil] Name of a blob object within the container.\n attribute :blob\n validates :blob, type: String\n\n # @return [:block, :page, nil] Type of Blob Object.\n attribute :blob_type\n validates :blob_type, expression_inclusion: {:in=>[:block, :page], :message=>\"%{value} needs to be :block, :page\"}, allow_nil: true\n\n # @return [String] Name of a blob container within the storage account.\n attribute :container\n validates :container, presence: true, type: String\n\n # @return [String, nil] Set the blob content-type header. For example, 'image/png'.\n attribute :content_type\n validates :content_type, type: String\n\n # @return [Object, nil] Set the blob cache-control header.\n attribute :cache_control\n\n # @return [Object, nil] Set the blob content-disposition header.\n attribute :content_disposition\n\n # @return [Object, nil] Set the blob encoding header.\n attribute :content_encoding\n\n # @return [Object, nil] Set the blob content-language header.\n attribute :content_language\n\n # @return [Object, nil] Set the blob md5 hash value.\n attribute :content_md5\n\n # @return [String, nil] Destination file path. Use with state 'present' to download a blob.\n attribute :dest\n validates :dest, type: String\n\n # @return [Symbol, nil] Overwrite existing blob or file when uploading or downloading. Force deletion of a container that contains blobs.\n attribute :force\n validates :force, type: Symbol\n\n # @return [String] Name of the resource group to use.\n attribute :resource_group\n validates :resource_group, presence: true, type: String\n\n # @return [String, nil] Source file path. Use with state 'present' to upload a blob.\n attribute :src\n validates :src, type: String\n\n # @return [:absent, :present, nil] Assert the state of a container or blob.,Use state 'absent' with a container value only to delete a container. Include a blob value to remove a specific blob. A container will not be deleted, if it contains blobs. Use the force option to override, deleting the container and all associated blobs.,Use state 'present' to create or update a container and upload or download a blob. If the container does not exist, it will be created. If it exists, it will be updated with configuration options. Provide a blob name and either src or dest to upload or download. Provide a src path to upload and a dest path to download. If a blob (uploading) or a file (downloading) already exists, it will not be overwritten unless the force parameter is true.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:container, :blob, nil] Determine a container's level of public access. By default containers are private. Can only be set at time of container creation.\n attribute :public_access\n validates :public_access, expression_inclusion: {:in=>[:container, :blob], :message=>\"%{value} needs to be :container, :blob\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7269610166549683, "alphanum_fraction": 0.7278182506561279, "avg_line_length": 79.44827270507812, "blob_id": "fe1456f9305c07c25ac6fc2f784876e06991a431", "content_id": "4e03d5557d05ce2eade04ced9ca49a958b06e488", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2333, "license_type": "permissive", "max_line_length": 792, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/google/gcp_url_map.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, Update or Destory a Url_Map. See U(https://cloud.google.com/compute/docs/load-balancing/http/url-map) for an overview. More details on the Url_Map API can be found at U(https://cloud.google.com/compute/docs/reference/latest/urlMaps#resource).\n class Gcp_url_map < Base\n # @return [String] Name of the Url_Map.\n attribute :url_map_name\n validates :url_map_name, presence: true, type: String\n\n # @return [String] Default Backend Service if no host rules match.\n attribute :default_service\n validates :default_service, presence: true, type: String\n\n # @return [Array<Hash>, Hash, nil] The list of HostRules to use against the URL. Contains a list of hosts and an associated path_matcher.,The 'hosts' parameter is a list of host patterns to match. They must be valid hostnames, except * will match any string of ([a-z0-9-.]*). In that case, * must be the first character and must be followed in the pattern by either - or ..,The 'path_matcher' parameter is name of the PathMatcher to use to match the path portion of the URL if the hostRule matches the URL's host portion.\n attribute :host_rules\n validates :host_rules, type: TypeGeneric.new(Hash)\n\n # @return [Array<Hash>, Hash, nil] The list of named PathMatchers to use against the URL. Contains path_rules, which is a list of paths and an associated service. A default_service can also be specified for each path_matcher.,The 'name' parameter to which this path_matcher is referred by the host_rule.,The 'default_service' parameter is the name of the BackendService resource. This will be used if none of the path_rules defined by this path_matcher is matched by the URL's path portion.,The 'path_rules' parameter is a list of dictionaries containing a list of paths and a service to direct traffic to. Each path item must start with / and the only place a * is allowed is at the end following a /. The string fed to the path matcher does not include any text after the first ? or\n attribute :path_matchers\n validates :path_matchers, type: TypeGeneric.new(Hash)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.675000011920929, "alphanum_fraction": 0.6753623485565186, "avg_line_length": 43.51612854003906, "blob_id": "09c2d268d12bba71e8183ab55e7d185af9bfbb2f", "content_id": "7de2fead3292c4f64e6cf1ecc3149b0f5be7618c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5520, "license_type": "permissive", "max_line_length": 310, "num_lines": 124, "path": "/lib/ansible/ruby/modules/generated/network/panos/panos_security_policy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Security policies allow you to enforce rules and take action, and can be as general or specific as needed. The policy rules are compared against the incoming traffic in sequence, and because the first rule that matches the traffic is applied, the more specific rules must precede the more general ones.\n class Panos_security_policy < Base\n # @return [String] IP address (or hostname) of PAN-OS device being configured.\n attribute :ip_address\n validates :ip_address, presence: true, type: String\n\n # @return [String, nil] Username credentials to use for auth unless I(api_key) is set.\n attribute :username\n validates :username, type: String\n\n # @return [String] Password credentials to use for auth unless I(api_key) is set.\n attribute :password\n validates :password, presence: true, type: String\n\n # @return [Object, nil] API key that can be used instead of I(username)/I(password) credentials.\n attribute :api_key\n\n # @return [String] Name of the security rule.\n attribute :rule_name\n validates :rule_name, presence: true, type: String\n\n # @return [String, nil] Type of security rule (version 6.1 of PanOS and above).\n attribute :rule_type\n validates :rule_type, type: String\n\n # @return [String, nil] Description for the security rule.\n attribute :description\n validates :description, type: String\n\n # @return [Object, nil] Administrative tags that can be added to the rule. Note, tags must be already defined.\n attribute :tag\n\n # @return [String, nil] List of source zones.\n attribute :from_zone\n validates :from_zone, type: String\n\n # @return [String, nil] List of destination zones.\n attribute :to_zone\n validates :to_zone, type: String\n\n # @return [String, nil] List of source addresses.\n attribute :source\n validates :source, type: String\n\n # @return [String, nil] Use users to enforce policy for individual users or a group of users.\n attribute :source_user\n validates :source_user, type: String\n\n # @return [String, nil] If you are using GlobalProtect with host information profile (HIP) enabled, you can also base the policy on information collected by GlobalProtect. For example, the user access level can be determined HIP that notifies the firewall about the user's local configuration.\\r\\n\n attribute :hip_profiles\n validates :hip_profiles, type: String\n\n # @return [String, nil] List of destination addresses.\n attribute :destination\n validates :destination, type: String\n\n # @return [String, nil] List of applications.\n attribute :application\n validates :application, type: String\n\n # @return [String, nil] List of services.\n attribute :service\n validates :service, type: String\n\n # @return [FalseClass, TrueClass, nil] Whether to log at session start.\n attribute :log_start\n validates :log_start, type: MultipleTypes.new(FalseClass, TrueClass)\n\n # @return [Boolean, nil] Whether to log at session end.\n attribute :log_end\n validates :log_end, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] Action to apply once rules maches.\n attribute :action\n validates :action, type: String\n\n # @return [Object, nil] Security profile group that is already defined in the system. This property supersedes antivirus, vulnerability, spyware, url_filtering, file_blocking, data_filtering, and wildfire_analysis properties.\\r\\n\n attribute :group_profile\n\n # @return [String, nil] Name of the already defined antivirus profile.\n attribute :antivirus\n validates :antivirus, type: String\n\n # @return [String, nil] Name of the already defined vulnerability profile.\n attribute :vulnerability\n validates :vulnerability, type: String\n\n # @return [String, nil] Name of the already defined spyware profile.\n attribute :spyware\n validates :spyware, type: String\n\n # @return [String, nil] Name of the already defined url_filtering profile.\n attribute :url_filtering\n validates :url_filtering, type: String\n\n # @return [Object, nil] Name of the already defined file_blocking profile.\n attribute :file_blocking\n\n # @return [Object, nil] Name of the already defined data_filtering profile.\n attribute :data_filtering\n\n # @return [String, nil] Name of the already defined wildfire_analysis profile.\n attribute :wildfire_analysis\n validates :wildfire_analysis, type: String\n\n # @return [String, nil] Device groups are used for the Panorama interaction with Firewall(s). The group must exists on Panorama. If device group is not define we assume that we are contacting Firewall.\\r\\n\n attribute :devicegroup\n validates :devicegroup, type: String\n\n # @return [Boolean, nil] Commit configuration if changed.\n attribute :commit\n validates :commit, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.50950026512146, "alphanum_fraction": 0.5147058963775635, "avg_line_length": 22.0059871673584, "blob_id": "fac2648e77031292ed78e44ca561855cc0328fa8", "content_id": "54f735765ea5e74af7bd0e4d49515f0af4845f1d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 7684, "license_type": "permissive", "max_line_length": 128, "num_lines": 334, "path": "/lib/ansible/ruby/dsl_builders/file_level_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\nrequire 'spec_helper'\nrequire 'ansible-ruby'\n\ndescribe Ansible::Ruby::DslBuilders::FileLevel do\n let(:builder) { Ansible::Ruby::DslBuilders::FileLevel.new }\n\n def evaluate\n builder.instance_eval ruby\n builder._result\n end\n\n subject(:result) { evaluate }\n\n before do\n klass = Class.new(Ansible::Ruby::Modules::Base) do\n attribute :src\n validates :src, presence: true\n attribute :dest\n validates :dest, presence: true\n end\n stub_const 'Ansible::Ruby::Modules::Copy', klass\n end\n\n context 'handlers' do\n context 'empty' do\n let(:ruby) { '' }\n\n it 'should raise an error' do\n expect {evaluate}.to raise_error 'Must supply at least 1 handler/task/play!'\n end\n end\n\n context 'with' do\n let(:ruby) do\n <<-RUBY\n handler 'copy_reboot' do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n end\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Tasks }\n it { is_expected.to have_attributes items: include(be_a(Ansible::Ruby::Models::Handler)) }\n end\n end\n\n context 'includes' do\n context 'inside playbook' do\n let(:ruby) do\n <<-RUBY\n play 'the play name' do\n hosts 'host1'\n\n task 'Copy something' do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n end\n end\n\n ansible_include 'foobar'\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Playbook }\n\n it do\n is_expected.to have_attributes plays: include(be_a(Ansible::Ruby::Models::Play)),\n inclusions: include(be_a(Ansible::Ruby::Models::Inclusion))\n end\n end\n\n context 'inside play' do\n let(:ruby) do\n <<-RUBY\n play 'the play name' do\n hosts 'host1'\n ansible_include 'foobar'\n\n task 'Copy something' do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n end\n end\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Playbook }\n it do\n is_expected.to have_attributes plays: include(be_a(Ansible::Ruby::Models::Play)),\n inclusions: []\n end\n\n describe 'play' do\n subject(:play) { result.plays.first }\n\n it { is_expected.to be_a Ansible::Ruby::Models::Play }\n\n describe 'tasks' do\n subject { play.tasks }\n\n it { is_expected.to be_a Ansible::Ruby::Models::Tasks }\n\n it { is_expected.to have_attributes inclusions: include(be_a(Ansible::Ruby::Models::Inclusion)) }\n end\n end\n end\n\n context 'inside tasks' do\n let(:ruby) do\n <<-RUBY\n ansible_include 'foobar'\n\n task 'Copy something' do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n end\n\n task 'Copy something else' do\n copy do\n src '/file3.conf'\n dest '/file4.conf'\n end\n end\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Tasks }\n it do\n is_expected.to have_attributes items: include(be_a(Ansible::Ruby::Models::Task),\n be_a(Ansible::Ruby::Models::Task)),\n inclusions: include(be_a(Ansible::Ruby::Models::Inclusion))\n end\n end\n end\n\n context 'invalid keyword' do\n let(:ruby) { 'foobar()' }\n\n it 'should raise an error' do\n expect {evaluate}.to raise_error \"Invalid method/local variable `foobar'. Only valid options are [:task, :handler, :play]\"\n end\n end\n\n context 'playbook' do\n context 'named' do\n let(:ruby) do\n <<-RUBY\n play 'the play name' do\n hosts 'host1'\n\n task 'Copy something' do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n end\n end\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Playbook }\n\n it do\n is_expected.to have_attributes plays: include(be_a(Ansible::Ruby::Models::Play))\n end\n end\n\n context 'unnamed' do\n let(:ruby) do\n <<-RUBY\n play do\n hosts 'host1'\n\n task 'Copy something' do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n end\n end\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Playbook }\n\n it do\n is_expected.to have_attributes plays: include(be_a(Ansible::Ruby::Models::Play))\n end\n end\n end\n\n context 'tasks' do\n let(:ruby) do\n <<-RUBY\n task 'Copy something' do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n end\n\n task 'Copy something else' do\n copy do\n src '/file3.conf'\n dest '/file4.conf'\n end\n end\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Tasks }\n it do\n is_expected.to have_attributes items: include(be_a(Ansible::Ruby::Models::Task),\n be_a(Ansible::Ruby::Models::Task))\n end\n end\n\n context 'change from play to task' do\n let(:ruby) do\n <<-RUBY\n play 'the play name' do\n hosts 'host1'\n roles %w(role1 role2)\n end\n\n task 'Copy something else' do\n copy do\n src '/file3.conf'\n dest '/file4.conf'\n end\n end\n RUBY\n end\n\n it 'should raise an error' do\n expect {evaluate}.to raise_error 'This is a playbook file, cannot use tasks here!'\n end\n end\n\n context 'change from task to play' do\n let(:ruby) do\n <<-RUBY\n task 'Copy something else' do\n copy do\n src '/file3.conf'\n dest '/file4.conf'\n end\n end\n\n play 'the play name' do\n hosts 'host1'\n roles %w(role1 role2)\n end\n RUBY\n end\n\n it 'should raise an error' do\n expect {evaluate}.to raise_error 'This is a tasks file, cannot use playbook here!'\n end\n end\n\n describe '#_handled_eval' do\n subject(:result) do\n exception = builder._handled_eval filename\n exception || builder._result\n end\n\n let(:filename) { 'file_level_test.rb' }\n\n around do |example|\n File.write filename, ruby\n example.run\n FileUtils.rm_rf filename\n end\n\n context 'no error' do\n let(:ruby) do\n <<-RUBY\n task 'Copy something' do\n copy do\n src '/file1.conf'\n dest '/file2.conf'\n end\n end\n RUBY\n end\n\n it { is_expected.to be_a Ansible::Ruby::Models::Tasks }\n end\n\n context 'error' do\n let(:ruby) do\n <<-RUBY\n task 'Copy something' do\n copy do\n src '/file1.conf'\n foobar '/file2.conf'\n end\n end\n RUBY\n end\n\n it { is_expected.to be_a Exception }\n\n describe 'message' do\n subject { result.message + \"\\n\" }\n\n it do\n is_expected.to eq <<~ERROR\n Unknown attribute 'foobar' for Ansible::Ruby::Modules::Copy.\n\n Valid attributes are: [:src, :dest]\n\n ****Error Location:****\n file_level_test.rb:4\n file_level_test.rb:2\n file_level_test.rb:1\n ERROR\n end\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6765799522399902, "alphanum_fraction": 0.6765799522399902, "avg_line_length": 47.17910385131836, "blob_id": "396bae1526433da43912159dffca693ce8a9e3c3", "content_id": "e70b6ce0be3812d45dc6360b272c6c67b96487a5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3228, "license_type": "permissive", "max_line_length": 237, "num_lines": 67, "path": "/lib/ansible/ruby/modules/generated/network/avi/avi_network.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used to configure Network object\n # more examples at U(https://github.com/avinetworks/devops)\n class Avi_network < Base\n # @return [:absent, :present, nil] The state that should be applied on the entity.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:put, :patch, nil] Default method for object update is HTTP PUT.,Setting to patch will override that behavior to use HTTP PATCH.\n attribute :avi_api_update_method\n validates :avi_api_update_method, expression_inclusion: {:in=>[:put, :patch], :message=>\"%{value} needs to be :put, :patch\"}, allow_nil: true\n\n # @return [:add, :replace, :delete, nil] Patch operation to use when using avi_api_update_method as patch.\n attribute :avi_api_patch_op\n validates :avi_api_patch_op, expression_inclusion: {:in=>[:add, :replace, :delete], :message=>\"%{value} needs to be :add, :replace, :delete\"}, allow_nil: true\n\n # @return [Object, nil] It is a reference to an object of type cloud.\n attribute :cloud_ref\n\n # @return [Object, nil] List of subnet.\n attribute :configured_subnets\n\n # @return [Symbol, nil] Select the ip address management scheme for this network.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :dhcp_enabled\n validates :dhcp_enabled, type: Symbol\n\n # @return [Symbol, nil] When selected, excludes all discovered subnets in this network from consideration for virtual service placement.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :exclude_discovered_subnets\n validates :exclude_discovered_subnets, type: Symbol\n\n # @return [String] Name of the object.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Symbol, nil] Boolean flag to set synced_from_se.,Default value when not specified in API or module is interpreted by Avi Controller as False.\n attribute :synced_from_se\n validates :synced_from_se, type: Symbol\n\n # @return [Object, nil] It is a reference to an object of type tenant.\n attribute :tenant_ref\n\n # @return [Object, nil] Avi controller URL of the object.\n attribute :url\n\n # @return [Object, nil] Unique object identifier of the object.\n attribute :uuid\n\n # @return [Symbol, nil] Boolean flag to set vcenter_dvs.,Default value when not specified in API or module is interpreted by Avi Controller as True.\n attribute :vcenter_dvs\n validates :vcenter_dvs, type: Symbol\n\n # @return [Object, nil] It is a reference to an object of type vimgrnwruntime.\n attribute :vimgrnw_ref\n\n # @return [Object, nil] It is a reference to an object of type vrfcontext.\n attribute :vrf_context_ref\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6723087430000305, "alphanum_fraction": 0.6865267157554626, "avg_line_length": 43.75757598876953, "blob_id": "f570bcc20f5e628f360c0e02889dc7f51d440527", "content_id": "0613f15a0de6c719c41e3cab26fbbc093fc1d18d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1477, "license_type": "permissive", "max_line_length": 195, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/notification/bearychat.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The M(bearychat) module sends notifications to U(https://bearychat.com) via the Incoming Robot integration.\n class Bearychat < Base\n # @return [String] BearyChat WebHook URL. This authenticates you to the bearychat service. It looks like C(https://hook.bearychat.com/=ae2CF/incoming/e61bd5c57b164e04b11ac02e66f47f60).\n attribute :url\n validates :url, presence: true, type: String\n\n # @return [String, nil] Message to send.\n attribute :text\n validates :text, type: String\n\n # @return [:yes, :no, nil] If C(yes), text will be parsed as markdown.\n attribute :markdown\n validates :markdown, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Channel to send the message to. If absent, the message goes to the default channel selected by the I(url).\n attribute :channel\n validates :channel, type: String\n\n # @return [Array<Hash>, Hash, nil] Define a list of attachments. For more information, see https://github.com/bearyinnovative/bearychat-tutorial/blob/master/robots/incoming.md#attachments\n attribute :attachments\n validates :attachments, type: TypeGeneric.new(Hash)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6706552505493164, "alphanum_fraction": 0.6717948913574219, "avg_line_length": 44, "blob_id": "538cafb95fd681c8cb91f3caced9012c7a8e517c", "content_id": "efa758c05f8e1f952989d2ceea37b5435b269d3d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1755, "license_type": "permissive", "max_line_length": 206, "num_lines": 39, "path": "/lib/ansible/ruby/modules/generated/commands/expect.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # The C(expect) module executes a command and responds to prompts.\n # The given command will be executed on all selected nodes. It will not be processed through the shell, so variables like C($HOME) and operations like C(\"<\"), C(\">\"), C(\"|\"), and C(\"&\") will not work.\n class Expect < Base\n # @return [String] The command module takes command to run.\n attribute :command\n validates :command, presence: true, type: String\n\n # @return [Object, nil] A filename, when it already exists, this step will B(not) be run.\n attribute :creates\n\n # @return [Object, nil] A filename, when it does not exist, this step will B(not) be run.\n attribute :removes\n\n # @return [Object, nil] Change into this directory before running the command.\n attribute :chdir\n\n # @return [Hash] Mapping of expected string/regex and string to respond with. If the response is a list, successive matches return successive responses. List functionality is new in 2.1.\n attribute :responses\n validates :responses, presence: true, type: Hash\n\n # @return [Integer, nil] Amount of time in seconds to wait for the expected strings. Use C(null) to disable timeout.\n attribute :timeout\n validates :timeout, type: Integer\n\n # @return [Boolean, nil] Whether or not to echo out your response strings.\n attribute :echo\n validates :echo, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.49288254976272583, "alphanum_fraction": 0.5142349004745483, "avg_line_length": 22.41666603088379, "blob_id": "174208dd302a8c646496bac60c5121117fdb73b5", "content_id": "dbe01773cef47418e0ae843b50518dfd648ff4b5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 562, "license_type": "permissive", "max_line_length": 71, "num_lines": 24, "path": "/lib/ansible/ruby/modules/custom/net_tools/basics/get_url_spec.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# see LICENSE.txt in project root\nrequire 'spec_helper'\n\ndescribe Ansible::Ruby::Modules::Get_url do\n subject(:mod) do\n Ansible::Ruby::Modules::Get_url.new url: 'http://foobar',\n dest: 'some_file',\n headers: { foo: 123, abc: 456 }\n end\n\n describe '#to_h' do\n subject { mod.to_h }\n\n it do\n is_expected.to eq get_url: {\n url: 'http://foobar',\n dest: 'some_file',\n headers: 'foo:123,abc:456'\n }\n end\n end\nend\n" }, { "alpha_fraction": 0.6492865085601807, "alphanum_fraction": 0.6492865085601807, "avg_line_length": 39.488887786865234, "blob_id": "4e0a885d030aeb95c67d067c5e0dca0aee0b1454", "content_id": "874d2315ebd35c511117afc7f31c5db35248a295", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1822, "license_type": "permissive", "max_line_length": 191, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/network/citrix/netscaler.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages Citrix NetScaler server and service entities.\n class Netscaler < Base\n # @return [String] Hostname or ip of your netscaler.\n attribute :nsc_host\n validates :nsc_host, presence: true, type: String\n\n # @return [String, nil] Protocol used to access netscaler.\n attribute :nsc_protocol\n validates :nsc_protocol, type: String\n\n # @return [String] Username.\n attribute :user\n validates :user, presence: true, type: String\n\n # @return [String] Password.\n attribute :password\n validates :password, presence: true, type: String\n\n # @return [:disable, :enable, nil] The action you want to perform on the entity.\n attribute :action\n validates :action, expression_inclusion: {:in=>[:disable, :enable], :message=>\"%{value} needs to be :disable, :enable\"}, allow_nil: true\n\n # @return [String] Name of the entity.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:server, :service, nil] Type of the entity.\n attribute :type\n validates :type, expression_inclusion: {:in=>[:server, :service], :message=>\"%{value} needs to be :server, :service\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no), SSL certificates for the target url will not be validated.,This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7140238285064697, "alphanum_fraction": 0.7149404287338257, "avg_line_length": 57.97297286987305, "blob_id": "5c2691145c7eaf204bad190328743f7984a815f5", "content_id": "b1d496b9ee0dd0f5f6f57d40ee1ec7a887b8e223", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2182, "license_type": "permissive", "max_line_length": 293, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/net_tools/nios/nios_network.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Adds and/or removes instances of network objects from Infoblox NIOS servers. This module manages NIOS C(network) objects using the Infoblox WAPI interface over REST.\n # Supports both IPV4 and IPV6 internet protocols\n class Nios_network < Base\n # @return [String] Specifies the network to add or remove from the system. The value should use CIDR notation.\n attribute :network\n validates :network, presence: true, type: String\n\n # @return [String] Configures the name of the network view to associate with this configured instance.\n attribute :network_view\n validates :network_view, presence: true, type: String\n\n # @return [Array<Hash>, Hash, nil] Configures the set of DHCP options to be included as part of the configured network instance. This argument accepts a list of values (see suboptions). When configuring suboptions at least one of C(name) or C(num) must be specified.\n attribute :options\n validates :options, type: TypeGeneric.new(Hash)\n\n # @return [Object, nil] Allows for the configuration of Extensible Attributes on the instance of the object. This argument accepts a set of key / value pairs for configuration.\n attribute :extattrs\n\n # @return [String, nil] Configures a text string comment to be associated with the instance of this object. The provided text string will be configured on the object instance.\n attribute :comment\n validates :comment, type: String\n\n # @return [:present, :absent, nil] Configures the intended state of the instance of the object on the NIOS server. When this value is set to C(present), the object is configured on the device and when this value is set to C(absent) the value is removed (if necessary) from the device.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6971108913421631, "alphanum_fraction": 0.6989748477935791, "avg_line_length": 40.269229888916016, "blob_id": "6f505ded1322cdab5a56f69cafcb56e6d5d83357", "content_id": "30be28f3b0199a025299540760f86e5b1fc0c900", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1073, "license_type": "permissive", "max_line_length": 182, "num_lines": 26, "path": "/lib/ansible/ruby/modules/generated/utilities/logic/assert.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module asserts that given expressions are true with an optional custom message.\n # This module is also supported for Windows targets.\n class Assert < Base\n # @return [Array<String>, String] A string expression of the same form that can be passed to the 'when' statement,Alternatively, a list of string expressions\n attribute :that\n validates :that, presence: true, type: TypeGeneric.new(String)\n\n # @return [String, nil] The customized message used for a failing assertion,This argument was called 'msg' before version 2.7, now it's renamed to 'fail_msg' with alias 'msg'\n attribute :fail_msg\n validates :fail_msg, type: String\n\n # @return [String, nil] The customized message used for a successful assertion\n attribute :success_msg\n validates :success_msg, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.705249011516571, "alphanum_fraction": 0.705249011516571, "avg_line_length": 59.24324417114258, "blob_id": "e4824728db81fdddd72440622ed7fa7ef2dcd2bc", "content_id": "d45752f050ef0cdb3efa0c0e4db9e1de7bed516b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2229, "license_type": "permissive", "max_line_length": 339, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/packaging/os/flatpak_remote.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows users to add or remove flatpak remotes.\n # The flatpak remotes concept is comparable to what is called repositories in other packaging formats.\n # Currently, remote addition is only supported via I(flatpakrepo) file URLs.\n # Existing remotes will not be updated.\n # See the M(flatpak) module for managing flatpaks.\n class Flatpak_remote < Base\n # @return [String, nil] The path to the C(flatpak) executable to use.,By default, this module looks for the C(flatpak) executable on the path.\n attribute :executable\n validates :executable, type: String\n\n # @return [String, nil] The URL to the I(flatpakrepo) file representing the repository remote to add.,When used with I(state=present), the flatpak remote specified under the I(flatpakrepo_url) is added using the specified installation C(method).,When used with I(state=absent), this is not required.,Required when I(state=present).\n attribute :flatpakrepo_url\n validates :flatpakrepo_url, type: String\n\n # @return [:system, :user, nil] The installation method to use.,Defines if the I(flatpak) is supposed to be installed globally for the whole C(system) or only for the current C(user).\n attribute :method\n validates :method, expression_inclusion: {:in=>[:system, :user], :message=>\"%{value} needs to be :system, :user\"}, allow_nil: true\n\n # @return [String] The desired name for the flatpak remote to be registered under on the managed host.,When used with I(state=present), the remote will be added to the managed host under the specified I(name).,When used with I(state=absent) the remote with that name will be removed.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, nil] Indicates the desired package state.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6814841628074646, "alphanum_fraction": 0.6841728091239929, "avg_line_length": 58.9892463684082, "blob_id": "6469399b9636f90d2869aa99016d225e719349d4", "content_id": "10b2917821342b3578420d31467ddfe2d8fa93ee", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5579, "license_type": "permissive", "max_line_length": 278, "num_lines": 93, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/route53.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Creates and deletes DNS records in Amazons Route53 service\n class Route53 < Base\n # @return [:present, :absent, :get, :create, :delete] Specifies the state of the resource record. As of Ansible 2.4, the I(command) option has been changed to I(state) as default and the choices 'present' and 'absent' have been added, but I(command) still works as well.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent, :get, :create, :delete], :message=>\"%{value} needs to be :present, :absent, :get, :create, :delete\"}\n\n # @return [String] The DNS zone to modify\n attribute :zone\n validates :zone, presence: true, type: String\n\n # @return [String, nil] The Hosted Zone ID of the DNS zone to modify\n attribute :hosted_zone_id\n validates :hosted_zone_id, type: String\n\n # @return [String] The full DNS record to create or delete\n attribute :record\n validates :record, presence: true, type: String\n\n # @return [String, nil] The TTL to give the new record\n attribute :ttl\n validates :ttl, type: String\n\n # @return [:A, :CNAME, :MX, :AAAA, :TXT, :PTR, :SRV, :SPF, :CAA, :NS, :SOA] The type of DNS record to create\n attribute :type\n validates :type, presence: true, expression_inclusion: {:in=>[:A, :CNAME, :MX, :AAAA, :TXT, :PTR, :SRV, :SPF, :CAA, :NS, :SOA], :message=>\"%{value} needs to be :A, :CNAME, :MX, :AAAA, :TXT, :PTR, :SRV, :SPF, :CAA, :NS, :SOA\"}\n\n # @return [:yes, :no, nil] Indicates if this is an alias record.\n attribute :alias\n validates :alias, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] The hosted zone identifier.\n attribute :alias_hosted_zone_id\n validates :alias_hosted_zone_id, type: String\n\n # @return [Symbol, nil] Whether or not to evaluate an alias target health. Useful for aliases to Elastic Load Balancers.\n attribute :alias_evaluate_target_health\n validates :alias_evaluate_target_health, type: Symbol\n\n # @return [Array<String>, String, nil] The new value when creating a DNS record. YAML lists or multiple comma-spaced values are allowed for non-alias records.,When deleting a record all values for the record must be specified or Route53 will not delete it.\n attribute :value\n validates :value, type: TypeGeneric.new(String)\n\n # @return [Object, nil] Whether an existing record should be overwritten on create if values do not match\n attribute :overwrite\n\n # @return [Integer, nil] In the case that route53 is still servicing a prior request, this module will wait and try again after this many seconds. If you have many domain names, the default of 500 seconds may be too long.\n attribute :retry_interval\n validates :retry_interval, type: Integer\n\n # @return [:yes, :no, nil] If set to C(yes), the private zone matching the requested name within the domain will be used if there are both public and private zones. The default is to use the public zone.\n attribute :private_zone\n validates :private_zone, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Have to be specified for Weighted, latency-based and failover resource record sets only. An identifier that differentiates among multiple resource record sets that have the same combination of DNS name and type.\n attribute :identifier\n validates :identifier, type: String\n\n # @return [Integer, nil] Weighted resource record sets only. Among resource record sets that have the same combination of DNS name and type, a value that determines what portion of traffic for the current resource record set is routed to the associated location.\n attribute :weight\n validates :weight, type: Integer\n\n # @return [Object, nil] Latency-based resource record sets only Among resource record sets that have the same combination of DNS name and type, a value that determines which region this should be associated with for the latency-based routing\n attribute :region\n\n # @return [String, nil] Health check to associate with this record\n attribute :health_check\n validates :health_check, type: String\n\n # @return [Object, nil] Failover resource record sets only. Whether this is the primary or secondary resource record set. Allowed values are PRIMARY and SECONDARY\n attribute :failover\n\n # @return [Object, nil] When used in conjunction with private_zone: true, this will only modify records in the private hosted zone attached to this VPC.,This allows you to have multiple private hosted zones, all with the same name, attached to different VPCs.\n attribute :vpc_id\n\n # @return [:yes, :no, nil] Wait until the changes have been replicated to all Amazon Route 53 DNS servers.\n attribute :wait\n validates :wait, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] How long to wait for the changes to be replicated, in seconds.\n attribute :wait_timeout\n validates :wait_timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7153160572052002, "alphanum_fraction": 0.7174374461174011, "avg_line_length": 64.47222137451172, "blob_id": "d665f454fbe8a9a015afdbaed970cb3136fe2090", "content_id": "26da914d28ed7e1998895394404d647ad1158a94", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2357, "license_type": "permissive", "max_line_length": 300, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/network/edgeos/edgeos_command.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This command module allows running one or more commands on a remote device running EdgeOS, such as the Ubiquiti EdgeRouter.\n # This module does not support running commands in configuration mode.\n # Certain C(show) commands in EdgeOS produce many lines of output and use a custom pager that can cause this module to hang. If the value of the environment variable C(ANSIBLE_EDGEOS_TERMINAL_LENGTH) is not set, the default number of 10000 is used.\n # This is a network module and requires C(connection: network_cli) in order to work properly.\n # For more information please see the L(Network Guide,../network/getting_started/index.html).\n class Edgeos_command < Base\n # @return [String] The commands or ordered set of commands that should be run against the remote device. The output of the command is returned to the playbook. If the C(wait_for) argument is provided, the module is not returned until the condition is met or the number of retries is exceeded.\n attribute :commands\n validates :commands, presence: true, type: String\n\n # @return [Object, nil] Causes the task to wait for a specific condition to be met before moving forward. If the condition is not met before the specified number of retries is exceeded, the task will fail.\n attribute :wait_for\n\n # @return [:any, :all, nil] Used in conjunction with C(wait_for) to create match policy. If set to C(all), then all conditions in C(wait_for) must be met. If set to C(any), then only one condition must match.\n attribute :match\n validates :match, expression_inclusion: {:in=>[:any, :all], :message=>\"%{value} needs to be :any, :all\"}, allow_nil: true\n\n # @return [Integer, nil] Number of times a command should be tried before it is considered failed. The command is run on the target device and evaluated against the C(wait_for) conditionals.\n attribute :retries\n validates :retries, type: Integer\n\n # @return [Integer, nil] The number of seconds to wait between C(retries) of the command.\n attribute :interval\n validates :interval, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6794594526290894, "alphanum_fraction": 0.6821621656417847, "avg_line_length": 55.06060791015625, "blob_id": "8f124966cfb5cc30cf57230cd90252694b692daa", "content_id": "475dbb7ae2b22d165570a8fafd361fb0bd9a9cf6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1850, "license_type": "permissive", "max_line_length": 289, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/files/archive.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Packs an archive. It is the opposite of M(unarchive). By default, it assumes the compression source exists on the target. It will not copy the source file from the local system to the target before archiving. Source files can be deleted after archival by specifying I(remove=True).\n class Archive < Base\n # @return [Array<String>, String] Remote absolute path, glob, or list of paths or globs for the file or files to compress or archive.\n attribute :path\n validates :path, presence: true, type: TypeGeneric.new(String)\n\n # @return [:bz2, :gz, :tar, :xz, :zip, nil] The type of compression to use.,Support for xz was added in version 2.5.\n attribute :format\n validates :format, expression_inclusion: {:in=>[:bz2, :gz, :tar, :xz, :zip], :message=>\"%{value} needs to be :bz2, :gz, :tar, :xz, :zip\"}, allow_nil: true\n\n # @return [String, nil] The file name of the destination archive. This is required when C(path) refers to multiple files by either specifying a glob, a directory or multiple paths in a list.\n attribute :dest\n validates :dest, type: String\n\n # @return [Array<String>, String, nil] Remote absolute path, glob, or list of paths or globs for the file or files to exclude from the archive\n attribute :exclude_path\n validates :exclude_path, type: TypeGeneric.new(String)\n\n # @return [:yes, :no, nil] Remove any added source files and trees after adding to archive.\n attribute :remove\n validates :remove, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6656686663627625, "alphanum_fraction": 0.667664647102356, "avg_line_length": 39.08000183105469, "blob_id": "64b4fe0596707d52b5a03e47e7d282311d8c44f3", "content_id": "7e00426daa750e2a255fe132e7ef7635d545524d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1002, "license_type": "permissive", "max_line_length": 171, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_udld_interface.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages UDLD interface configuration params.\n class Nxos_udld_interface < Base\n # @return [:enabled, :disabled, :aggressive] Manages UDLD mode for an interface.\n attribute :mode\n validates :mode, presence: true, expression_inclusion: {:in=>[:enabled, :disabled, :aggressive], :message=>\"%{value} needs to be :enabled, :disabled, :aggressive\"}\n\n # @return [String] FULL name of the interface, i.e. Ethernet1/1-\n attribute :interface\n validates :interface, presence: true, type: String\n\n # @return [:present, :absent, nil] Manage the state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6828793883323669, "alphanum_fraction": 0.6828793883323669, "avg_line_length": 45.727272033691406, "blob_id": "704654ecb34af82d3bdaa8e7d1e0a90d8e484373", "content_id": "9f33bcf41122a5f36e95135deaacb94d4ec34855", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1542, "license_type": "permissive", "max_line_length": 318, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_elementsw_drive.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add, Erase or Remove drive for nodes on Element Software Cluster.\n class Na_elementsw_drive < Base\n # @return [String, nil] Drive ID or Serial Name of Node drive.,If not specified, add and remove action will be performed on all drives of node_id\n attribute :drive_id\n validates :drive_id, type: String\n\n # @return [:present, :absent, :clean, nil] Element SW Storage Drive operation state.,present - To add drive of node to participate in cluster data storage.,absent - To remove the drive from being part of active cluster.,clean - Clean-up any residual data persistent on a *removed* drive in a secured method.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :clean], :message=>\"%{value} needs to be :present, :absent, :clean\"}, allow_nil: true\n\n # @return [String] ID or Name of cluster node.\n attribute :node_id\n validates :node_id, presence: true, type: String\n\n # @return [Symbol, nil] Flag to force drive operation during upgrade.\n attribute :force_during_upgrade\n validates :force_during_upgrade, type: Symbol\n\n # @return [Symbol, nil] Flag to force during a bin sync operation.\n attribute :force_during_bin_sync\n validates :force_during_bin_sync, type: Symbol\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6955503225326538, "alphanum_fraction": 0.6955503225326538, "avg_line_length": 37.818180084228516, "blob_id": "b285043fc8703bf0a52f9f0b663df8c2168e05a5", "content_id": "5d079439c2d0051a95bcdb8629fd4cc7dd57d5f6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 854, "license_type": "permissive", "max_line_length": 170, "num_lines": 22, "path": "/lib/ansible/ruby/modules/generated/inventory/add_host.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Use variables to create new hosts and groups in inventory for use in later plays of the same playbook. Takes variables so you can define the new hosts more fully.\n # This module is also supported for Windows targets.\n class Add_host < Base\n # @return [String] The hostname/ip of the host to add to the inventory, can include a colon and a port number.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Array<String>, String, nil] The groups to add the hostname to, comma separated.\n attribute :groups\n validates :groups, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6559714674949646, "alphanum_fraction": 0.6571598052978516, "avg_line_length": 42.90434646606445, "blob_id": "e91204e4bc57a0a4f4a532b8cd27791447e3b32b", "content_id": "66401b74c57cdc59ef9c9b270907391f8067730d", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5049, "license_type": "permissive", "max_line_length": 209, "num_lines": 115, "path": "/lib/ansible/ruby/modules/generated/cloud/misc/ovirt.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module only supports oVirt/RHEV version 3. A newer module M(ovirt_vms) supports oVirt/RHV version 4.\n # Allows you to create new instances, either from scratch or an image, in addition to deleting or stopping instances on the oVirt/RHEV platform.\n class Ovirt < Base\n # @return [String] The user to authenticate with.\n attribute :user\n validates :user, presence: true, type: String\n\n # @return [String] The url of the oVirt instance.\n attribute :url\n validates :url, presence: true, type: String\n\n # @return [String] The name of the instance to use.\n attribute :instance_name\n validates :instance_name, presence: true, type: String\n\n # @return [String] Password of the user to authenticate with.\n attribute :password\n validates :password, presence: true, type: String\n\n # @return [String, nil] The template to use for the instance.\n attribute :image\n validates :image, type: String\n\n # @return [:new, :template, nil] Whether you want to deploy an image or create an instance from scratch.\n attribute :resource_type\n validates :resource_type, expression_inclusion: {:in=>[:new, :template], :message=>\"%{value} needs to be :new, :template\"}, allow_nil: true\n\n # @return [String, nil] Deploy the image to this oVirt cluster.\n attribute :zone\n validates :zone, type: String\n\n # @return [Integer, nil] Size of the instance's disk in GB.\n attribute :instance_disksize\n validates :instance_disksize, type: Integer\n\n # @return [Integer, nil] The instance's number of CPUs.\n attribute :instance_cpus\n validates :instance_cpus, type: Integer\n\n # @return [String, nil] The name of the network interface in oVirt/RHEV.\n attribute :instance_nic\n validates :instance_nic, type: String\n\n # @return [String, nil] The logical network the machine should belong to.\n attribute :instance_network\n validates :instance_network, type: String\n\n # @return [Integer, nil] The instance's amount of memory in MB.\n attribute :instance_mem\n validates :instance_mem, type: Integer\n\n # @return [:desktop, :server, :high_performance, nil] Define whether the instance is a server, desktop or high_performance.,I(high_performance) is supported since Ansible 2.5 and oVirt/RHV 4.2.\n attribute :instance_type\n validates :instance_type, expression_inclusion: {:in=>[:desktop, :server, :high_performance], :message=>\"%{value} needs to be :desktop, :server, :high_performance\"}, allow_nil: true\n\n # @return [:preallocated, :thin, nil] Define whether disk is thin or preallocated.\n attribute :disk_alloc\n validates :disk_alloc, expression_inclusion: {:in=>[:preallocated, :thin], :message=>\"%{value} needs to be :preallocated, :thin\"}, allow_nil: true\n\n # @return [:ide, :virtio, nil] Interface type of the disk.\n attribute :disk_int\n validates :disk_int, expression_inclusion: {:in=>[:ide, :virtio], :message=>\"%{value} needs to be :ide, :virtio\"}, allow_nil: true\n\n # @return [String, nil] Type of Operating System.\n attribute :instance_os\n validates :instance_os, type: String\n\n # @return [Integer, nil] Define the instance's number of cores.\n attribute :instance_cores\n validates :instance_cores, type: Integer\n\n # @return [String, nil] The Storage Domain where you want to create the instance's disk on.\n attribute :sdomain\n validates :sdomain, type: String\n\n # @return [String, nil] The oVirt/RHEV datacenter where you want to deploy to.\n attribute :region\n validates :region, type: String\n\n # @return [Object, nil] Define the instance's Primary DNS server.\n attribute :instance_dns\n\n # @return [Object, nil] Define the instance's Domain.\n attribute :instance_domain\n\n # @return [Object, nil] Define the instance's Hostname.\n attribute :instance_hostname\n\n # @return [Object, nil] Define the instance's IP.\n attribute :instance_ip\n\n # @return [Object, nil] Define the instance's Netmask.\n attribute :instance_netmask\n\n # @return [Object, nil] Define the instance's Root password.\n attribute :instance_rootpw\n\n # @return [Object, nil] Define the instance's Authorized key.\n attribute :instance_key\n\n # @return [:absent, :present, :restarted, :shutdown, :started, nil] Create, terminate or remove instances.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :restarted, :shutdown, :started], :message=>\"%{value} needs to be :absent, :present, :restarted, :shutdown, :started\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7174713611602783, "alphanum_fraction": 0.7227904796600342, "avg_line_length": 89.51851654052734, "blob_id": "8ceaffb58a272e40f8b8dfd2df460c7b210f8fd4", "content_id": "e21ec2edde4047b385dbac603fd400e78d226a0e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4888, "license_type": "permissive", "max_line_length": 430, "num_lines": 54, "path": "/lib/ansible/ruby/modules/generated/network/eos/eos_eapi.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Use to enable or disable eAPI access, and set the port and state of http, https, local_http and unix-socket servers.\n # When enabling eAPI access the default is to enable HTTP on port 80, enable HTTPS on port 443, disable local HTTP, and disable Unix socket server. Use the options listed below to override the default configuration.\n # Requires EOS v4.12 or greater.\n class Eos_eapi < Base\n # @return [:yes, :no, nil] The C(http) argument controls the operating state of the HTTP transport protocol when eAPI is present in the running-config. When the value is set to True, the HTTP protocol is enabled and when the value is set to False, the HTTP protocol is disabled. By default, when eAPI is first configured, the HTTP protocol is disabled.\n attribute :http\n validates :http, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Configures the HTTP port that will listen for connections when the HTTP transport protocol is enabled. This argument accepts integer values in the valid range of 1 to 65535.\n attribute :http_port\n validates :http_port, type: Integer\n\n # @return [:yes, :no, nil] The C(https) argument controls the operating state of the HTTPS transport protocol when eAPI is present in the running-config. When the value is set to True, the HTTPS protocol is enabled and when the value is set to False, the HTTPS protocol is disabled. By default, when eAPI is first configured, the HTTPS protocol is enabled.\n attribute :https\n validates :https, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Configures the HTTP port that will listen for connections when the HTTP transport protocol is enabled. This argument accepts integer values in the valid range of 1 to 65535.\n attribute :https_port\n validates :https_port, type: Integer\n\n # @return [:yes, :no, nil] The C(local_http) argument controls the operating state of the local HTTP transport protocol when eAPI is present in the running-config. When the value is set to True, the HTTP protocol is enabled and restricted to connections from localhost only. When the value is set to False, the HTTP local protocol is disabled.,Note is value is independent of the C(http) argument\n attribute :local_http\n validates :local_http, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Configures the HTTP port that will listen for connections when the HTTP transport protocol is enabled. This argument accepts integer values in the valid range of 1 to 65535.\n attribute :local_http_port\n validates :local_http_port, type: Integer\n\n # @return [:yes, :no, nil] The C(socket) argument controls the operating state of the UNIX Domain Socket used to receive eAPI requests. When the value of this argument is set to True, the UDS will listen for eAPI requests. When the value is set to False, the UDS will not be available to handle requests. By default when eAPI is first configured, the UDS is disabled.\n attribute :socket\n validates :socket, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] The C(vrf) argument will configure eAPI to listen for connections in the specified VRF. By default, eAPI transports will listen for connections in the global table. This value requires the VRF to already be created otherwise the task will fail.\n attribute :vrf\n validates :vrf, type: String\n\n # @return [Object, nil] The module, by default, will connect to the remote device and retrieve the current running-config to use as a base for comparing against the contents of source. There are times when it is not desirable to have the task get the current running-config for every task in a playbook. The I(config) argument allows the implementer to pass in the configuration to use as the base config for comparison.\n attribute :config\n\n # @return [:started, :stopped, nil] The C(state) argument controls the operational state of eAPI on the remote device. When this argument is set to C(started), eAPI is enabled to receive requests and when this argument is C(stopped), eAPI is disabled and will not receive requests.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:started, :stopped], :message=>\"%{value} needs to be :started, :stopped\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6590909361839294, "alphanum_fraction": 0.6590909361839294, "avg_line_length": 13.666666984558105, "blob_id": "533e3191ab12e6d640af949f06257a748484bf03", "content_id": "81adb7e5d5d557719a5db08956f7d80f42f9b4f8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 132, "license_type": "permissive", "max_line_length": 29, "num_lines": 9, "path": "/examples/roles/dummy/handlers/handler_include.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\ntask 'another one' do\n debug { msg 'stuff' }\nend\n\ntask 'another two' do\n debug { msg 'stuff' }\nend\n" }, { "alpha_fraction": 0.6793508529663086, "alphanum_fraction": 0.6793508529663086, "avg_line_length": 47.297298431396484, "blob_id": "ee14238ad5e7e32ce3096fdd3b5b49d709eb2e54", "content_id": "c6a6ee4397e48e711d94b9634f27a8cfb716f788", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1787, "license_type": "permissive", "max_line_length": 178, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/iam_managed_policy.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows creating and removing managed IAM policies\n class Iam_managed_policy < Base\n # @return [String] The name of the managed policy.\n attribute :policy_name\n validates :policy_name, presence: true, type: String\n\n # @return [String, nil] A helpful description of this policy, this value is immuteable and only set when creating a new policy.\n attribute :policy_description\n validates :policy_description, type: String\n\n # @return [Array<String>, String, nil] A properly json formatted policy\n attribute :policy\n validates :policy, type: TypeGeneric.new(String)\n\n # @return [Boolean, nil] Make this revision the default revision.\n attribute :make_default\n validates :make_default, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Remove all other non default revisions, if this is used with C(make_default) it will result in all other versions of this policy being deleted.\n attribute :only_version\n validates :only_version, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, nil] Should this managed policy be present or absent. Set to absent to detach all entities from this policy and remove it if found.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7415658831596375, "alphanum_fraction": 0.7415658831596375, "avg_line_length": 67.3043441772461, "blob_id": "bd467553d2472d44674325940a120f9dc90191a1", "content_id": "a543b5252e1006d6378cd87478e126d2a6aefb2c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1571, "license_type": "permissive", "max_line_length": 614, "num_lines": 23, "path": "/lib/ansible/ruby/modules/generated/commands/raw.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Executes a low-down and dirty SSH command, not going through the module subsystem. This is useful and should only be done in a few cases. A common case is installing C(python) on a system without python installed by default. Another is speaking to any devices such as routers that do not have any Python installed. In any other case, using the M(shell) or M(command) module is much more appropriate. Arguments given to C(raw) are run directly through the configured remote shell. Standard output, error output and return code are returned when available. There is no change handler support for this module.\n # This module does not require python on the remote system, much like the M(script) module.\n # This module is also supported for Windows targets.\n class Raw < Base\n # @return [Object] the raw module takes a free form command to run. There is no parameter actually named 'free form'; see the examples!\n attribute :free_form\n validates :free_form, presence: true\n\n # @return [String, nil] change the shell used to execute the command. Should be an absolute path to the executable.,when using privilege escalation (C(become)), a default shell will be assigned if one is not provided as privilege escalation requires a shell.\n attribute :executable\n validates :executable, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7136465311050415, "alphanum_fraction": 0.7136465311050415, "avg_line_length": 41.57143020629883, "blob_id": "d2be56bacc0734fd811ca22f28fb7dd6c178bd02", "content_id": "d23f69d0c6cfb340c81252eeb573780bfa132eec", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 894, "license_type": "permissive", "max_line_length": 203, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_drs_rule_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to gather facts about DRS VM-VM and VM-HOST rules from the given cluster.\n class Vmware_drs_rule_facts < Base\n # @return [String, nil] Name of the cluster.,DRS facts for the given cluster will be returned.,This is required parameter if C(datacenter) parameter is not provided.\n attribute :cluster_name\n validates :cluster_name, type: String\n\n # @return [String, nil] Name of the datacenter.,DRS facts for all the clusters from the given datacenter will be returned.,This is required parameter if C(cluster_name) parameter is not provided.\n attribute :datacenter\n validates :datacenter, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7059739232063293, "alphanum_fraction": 0.709671139717102, "avg_line_length": 71.38027954101562, "blob_id": "f9e609798caa4f36e3ec829cdac36f9e8744eec9", "content_id": "8006a86f87a5d235338b88ce05b1d48be7648e3c", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5139, "license_type": "permissive", "max_line_length": 719, "num_lines": 71, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_pool_member.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages F5 BIG-IP LTM pool members via iControl SOAP API.\n class Bigip_pool_member < Base\n # @return [String, nil] Name of the node to create, or re-use, when creating a new pool member.,This parameter is optional and, if not specified, a node name will be created automatically from either the specified C(address) or C(fqdn).,The C(enabled) state is an alias of C(present).\n attribute :name\n validates :name, type: String\n\n # @return [:present, :absent, :enabled, :disabled, :forced_offline] Pool member state.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent, :enabled, :disabled, :forced_offline], :message=>\"%{value} needs to be :present, :absent, :enabled, :disabled, :forced_offline\"}\n\n # @return [String] Pool name. This pool must exist.\n attribute :pool\n validates :pool, presence: true, type: String\n\n # @return [String, nil] Partition\n attribute :partition\n validates :partition, type: String\n\n # @return [Object, nil] IP address of the pool member. This can be either IPv4 or IPv6. When creating a new pool member, one of either C(address) or C(fqdn) must be provided. This parameter cannot be updated after it is set.\n attribute :address\n\n # @return [Object, nil] FQDN name of the pool member. This can be any name that is a valid RFC 1123 DNS name. Therefore, the only characters that can be used are \"A\" to \"Z\", \"a\" to \"z\", \"0\" to \"9\", the hyphen (\"-\") and the period (\".\").,FQDN names must include at lease one period; delineating the host from the domain. ex. C(host.domain).,FQDN names must end with a letter or a number.,When creating a new pool member, one of either C(address) or C(fqdn) must be provided. This parameter cannot be updated after it is set.\n attribute :fqdn\n\n # @return [Integer] Pool member port.,This value cannot be changed after it has been set.\n attribute :port\n validates :port, presence: true, type: Integer\n\n # @return [Integer, nil] Pool member connection limit. Setting this to 0 disables the limit.\n attribute :connection_limit\n validates :connection_limit, type: Integer\n\n # @return [String, nil] Pool member description.\n attribute :description\n validates :description, type: String\n\n # @return [Integer, nil] Pool member rate limit (connections-per-second). Setting this to 0 disables the limit.\n attribute :rate_limit\n validates :rate_limit, type: Integer\n\n # @return [Integer, nil] Pool member ratio weight. Valid values range from 1 through 100. New pool members -- unless overridden with this value -- default to 1.\n attribute :ratio\n validates :ratio, type: Integer\n\n # @return [Symbol, nil] When state is C(absent) attempts to remove the node that the pool member references.,The node will not be removed if it is still referenced by other pool members. If this happens, the module will not raise an error.,Setting this to C(yes) disables this behavior.\n attribute :preserve_node\n validates :preserve_node, type: Symbol\n\n # @return [String, Integer, nil] Specifies a number representing the priority group for the pool member.,When adding a new member, the default is 0, meaning that the member has no priority.,To specify a priority, you must activate priority group usage when you create a new pool or when adding or removing pool members. When activated, the system load balances traffic according to the priority group number assigned to the pool member.,The higher the number, the higher the priority, so a member with a priority of 3 has higher priority than a member with a priority of 1.\n attribute :priority_group\n validates :priority_group, type: MultipleTypes.new(String, Integer)\n\n # @return [Symbol, nil] Specifies whether the system automatically creates ephemeral nodes using the IP addresses returned by the resolution of a DNS query for a node defined by an FQDN.,When C(yes), the system generates an ephemeral node for each IP address returned in response to a DNS query for the FQDN of the node. Additionally, when a DNS response indicates the IP address of an ephemeral node no longer exists, the system deletes the ephemeral node.,When C(no), the system resolves a DNS query for the FQDN of the node with the single IP address associated with the FQDN.,When creating a new pool member, the default for this parameter is C(yes).,This parameter is ignored when C(reuse_nodes) is C(yes).\n attribute :fqdn_auto_populate\n validates :fqdn_auto_populate, type: Symbol\n\n # @return [Boolean, nil] Reuses node definitions if requested.\n attribute :reuse_nodes\n validates :reuse_nodes, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7189096808433533, "alphanum_fraction": 0.7189096808433533, "avg_line_length": 47.91666793823242, "blob_id": "8360fe676de04bfcc2d11b6fb1b14f2ab149c0b9", "content_id": "1a59a1e5bae9bc99b666c14a5312566d6736b985", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1174, "license_type": "permissive", "max_line_length": 241, "num_lines": 24, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_host_firewall_manager.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module can be used to manage firewall configurations about an ESXi host when ESXi hostname or Cluster name is given.\n class Vmware_host_firewall_manager < Base\n # @return [String, nil] Name of the cluster.,Firewall settings are applied to every ESXi host system in given cluster.,If C(esxi_hostname) is not given, this parameter is required.\n attribute :cluster_name\n validates :cluster_name, type: String\n\n # @return [String, nil] ESXi hostname.,Firewall settings are applied to this ESXi host system.,If C(cluster_name) is not given, this parameter is required.\n attribute :esxi_hostname\n validates :esxi_hostname, type: String\n\n # @return [Object, nil] A list of Rule set which needs to be managed.,Each member of list is rule set name and state to be set the rule.,Both rule name and rule state are required parameters.,Please see examples for more information.\n attribute :rules\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.714606761932373, "alphanum_fraction": 0.71685391664505, "avg_line_length": 41.380950927734375, "blob_id": "1f2c57b6aa0ca6af3c8224b7a2faa5cbcb4f4343", "content_id": "b0bafd6eb91cdca61bee19014310ba7d0100ed8f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 890, "license_type": "permissive", "max_line_length": 234, "num_lines": 21, "path": "/lib/ansible/ruby/modules/generated/cloud/amazon/ec2_customer_gateway_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gather facts about customer gateways in AWS\n class Ec2_customer_gateway_facts < Base\n # @return [Hash, nil] A dict of filters to apply. Each dict item consists of a filter key and a filter value. See U(http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeCustomerGateways.html) for possible filters.\n attribute :filters\n validates :filters, type: Hash\n\n # @return [Array<String>, String, nil] Get details of a specific customer gateways using customer gateway ID/IDs. This value should be provided as a list.\n attribute :customer_gateway_ids\n validates :customer_gateway_ids, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6450048685073853, "alphanum_fraction": 0.6450048685073853, "avg_line_length": 39.431373596191406, "blob_id": "e3d4ca256d66b81acf8709e32868b4421135cc40", "content_id": "c98f67e5eb2f801245be5704934342ce79239fdf", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2062, "license_type": "permissive", "max_line_length": 165, "num_lines": 51, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_vmsnapshot.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, remove and revert VM from snapshots.\n class Cs_vmsnapshot < Base\n # @return [String] Unique Name of the snapshot. In CloudStack terms display name.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] Name of the virtual machine.\n attribute :vm\n validates :vm, presence: true, type: String\n\n # @return [Object, nil] Description of the snapshot.\n attribute :description\n\n # @return [Boolean, nil] Snapshot memory if set to true.\n attribute :snapshot_memory\n validates :snapshot_memory, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] Name of the zone in which the VM is in. If not set, default zone is used.\n attribute :zone\n\n # @return [Object, nil] Name of the project the VM is assigned to.\n attribute :project\n\n # @return [:present, :absent, :revert, nil] State of the snapshot.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent, :revert], :message=>\"%{value} needs to be :present, :absent, :revert\"}, allow_nil: true\n\n # @return [Object, nil] Domain the VM snapshot is related to.\n attribute :domain\n\n # @return [Object, nil] Account the VM snapshot is related to.\n attribute :account\n\n # @return [Boolean, nil] Poll async jobs until job has finished.\n attribute :poll_async\n validates :poll_async, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Object, nil] List of tags. Tags are a list of dictionaries having keys C(key) and C(value).,To delete all tags, set a empty list e.g. C(tags: []).\n attribute :tags\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7371364831924438, "alphanum_fraction": 0.7371364831924438, "avg_line_length": 80.2727279663086, "blob_id": "d183fb56ff89d5956185be690afe1ef6461e2e0a", "content_id": "92aa226d386f915079bef70a9dbef9fabd3a6d4e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2682, "license_type": "permissive", "max_line_length": 634, "num_lines": 33, "path": "/lib/ansible/ruby/modules/generated/network/nxos/nxos_command.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Sends an arbitrary command to an NXOS node and returns the results read from the device. This module includes an argument that will cause the module to wait for a specific condition before returning or timing out if the condition is not met.\n class Nxos_command < Base\n # @return [Array<String>, String] The commands to send to the remote NXOS device. The resulting output from the command is returned. If the I(wait_for) argument is provided, the module is not returned until the condition is satisfied or the number of retires as expired.,The I(commands) argument also accepts an alternative form that allows for complex values that specify the command to run and the output format to return. This can be done on a command by command basis. The complex argument supports the keywords C(command) and C(output) where C(command) is the command to run and C(output) is one of 'text' or 'json'.\n attribute :commands\n validates :commands, presence: true, type: TypeGeneric.new(String, Hash)\n\n # @return [Array<String>, String, nil] Specifies what to evaluate from the output of the command and what conditionals to apply. This argument will cause the task to wait for a particular conditional to be true before moving forward. If the conditional is not true by the configured retries, the task fails. See examples.\n attribute :wait_for\n validates :wait_for, type: TypeGeneric.new(String)\n\n # @return [String, nil] The I(match) argument is used in conjunction with the I(wait_for) argument to specify the match policy. Valid values are C(all) or C(any). If the value is set to C(all) then all conditionals in the I(wait_for) must be satisfied. If the value is set to C(any) then only one of the values must be satisfied.\n attribute :match\n validates :match, type: String\n\n # @return [Integer, nil] Specifies the number of retries a command should by tried before it is considered failed. The command is run on the target device every retry and evaluated against the I(wait_for) conditionals.\n attribute :retries\n validates :retries, type: Integer\n\n # @return [Integer, nil] Configures the interval in seconds to wait between retries of the command. If the command does not pass the specified conditional, the interval indicates how to long to wait before trying the command again.\n attribute :interval\n validates :interval, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6418988704681396, "alphanum_fraction": 0.6418988704681396, "avg_line_length": 32.41379165649414, "blob_id": "a6c5e872a9a4dc6c8f50370c9a3ae2558d6b61c0", "content_id": "d3bf28e75d733656c11cc2c026ab011e1b58cabd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 969, "license_type": "permissive", "max_line_length": 143, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/cloud/cloudstack/cs_region.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Add, update and remove regions.\n class Cs_region < Base\n # @return [Integer] ID of the region.,Must be an number (int).\n attribute :id\n validates :id, presence: true, type: Integer\n\n # @return [String, nil] Name of the region.,Required if C(state=present)\n attribute :name\n validates :name, type: String\n\n # @return [String, nil] Endpoint URL of the region.,Required if C(state=present)\n attribute :endpoint\n validates :endpoint, type: String\n\n # @return [:present, :absent, nil] State of the region.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6622264385223389, "alphanum_fraction": 0.6622264385223389, "avg_line_length": 35.24137878417969, "blob_id": "3442906cc8641fb3cad5c62e076957110a946f96", "content_id": "d7be2127689159d9d08059caacfb409193be6c0e", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1051, "license_type": "permissive", "max_line_length": 141, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/network/meraki/meraki_organization.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows for creation, management, and visibility into organizations within Meraki.\n class Meraki_organization < Base\n # @return [:present, :query, nil] Create or modify an organization.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :query], :message=>\"%{value} needs to be :present, :query\"}, allow_nil: true\n\n # @return [String, nil] Organization to clone to a new organization.\n attribute :clone\n validates :clone, type: String\n\n # @return [String, nil] Name of organization.,If C(clone) is specified, C(org_name) is the name of the new organization.\n attribute :org_name\n validates :org_name, type: String\n\n # @return [Integer, nil] ID of organization.\n attribute :org_id\n validates :org_id, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.683538556098938, "alphanum_fraction": 0.686274528503418, "avg_line_length": 52.4878044128418, "blob_id": "e3ac5c6047a5b2fa87c95d5f4b26415b4186b5e5", "content_id": "1426cebd08238a864e95210043d0d9e073a74241", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2193, "license_type": "permissive", "max_line_length": 346, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/network/a10/a10_virtual_server.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage SLB (Server Load Balancing) virtual server objects on A10 Networks devices via aXAPIv2.\n class A10_virtual_server < Base\n # @return [:present, :absent, nil] If the specified virtual server should exist.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] set active-partition\n attribute :partition\n validates :partition, type: String\n\n # @return [String] The SLB (Server Load Balancing) virtual server name.\n attribute :virtual_server\n validates :virtual_server, presence: true, type: String\n\n # @return [String, nil] The SLB virtual server IPv4 address.\n attribute :virtual_server_ip\n validates :virtual_server_ip, type: String\n\n # @return [:enabled, :disabled, nil] The SLB virtual server status, such as enabled or disabled.\n attribute :virtual_server_status\n validates :virtual_server_status, expression_inclusion: {:in=>[:enabled, :disabled], :message=>\"%{value} needs to be :enabled, :disabled\"}, allow_nil: true\n\n # @return [Array<Hash>, Hash, nil] A list of ports to create for the virtual server. Each list item should be a dictionary which specifies the C(port:) and C(type:), but can also optionally specify the C(service_group:) as well as the C(status:). See the examples below for details. This parameter is required when C(state) is C(present).\n attribute :virtual_server_ports\n validates :virtual_server_ports, type: TypeGeneric.new(Hash)\n\n # @return [:yes, :no, nil] If C(no), SSL certificates will not be validated. This should only be used on personally controlled devices using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6676470637321472, "alphanum_fraction": 0.6694852709770203, "avg_line_length": 46.71929931640625, "blob_id": "0a0fde8619db0664e927b06949e2de0f37914919", "content_id": "7cc74d7cc91a69777b281be01777056e3271bc05", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2720, "license_type": "permissive", "max_line_length": 215, "num_lines": 57, "path": "/lib/ansible/ruby/modules/generated/source_control/github_deploy_key.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Adds or removes deploy keys for GitHub repositories. Supports authentication using username and password, username and password and 2-factor authentication code (OTP), OAuth2 token, or personal access token.\n class Github_deploy_key < Base\n # @return [String] The name of the individual account or organization that owns the GitHub repository.\n attribute :owner\n validates :owner, presence: true, type: String\n\n # @return [String] The name of the GitHub repository.\n attribute :repo\n validates :repo, presence: true, type: String\n\n # @return [String] The name for the deploy key.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String] The SSH public key to add to the repository as a deploy key.\n attribute :key\n validates :key, presence: true, type: String\n\n # @return [:yes, :no, nil] If C(true), the deploy key will only be able to read repository contents. Otherwise, the deploy key will be able to read and write.\n attribute :read_only\n validates :read_only, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:present, :absent, nil] The state of the deploy key.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(true), forcefully adds the deploy key by deleting any existing deploy key with the same public key or title.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] The username to authenticate with.\n attribute :username\n validates :username, type: String\n\n # @return [String, nil] The password to authenticate with. A personal access token can be used here in place of a password.\n attribute :password\n validates :password, type: String\n\n # @return [String, nil] The OAuth2 token or personal access token to authenticate with. Mutually exclusive with I(password).\n attribute :token\n validates :token, type: String\n\n # @return [Integer, nil] The 6 digit One Time Password for 2-Factor Authentication. Required together with I(username) and I(password).\n attribute :otp\n validates :otp, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7240704298019409, "alphanum_fraction": 0.7243965864181519, "avg_line_length": 75.6500015258789, "blob_id": "2d1e7dc68917cb672f8b63017ab4ffea015c6bf2", "content_id": "3fa05203fb4b0d95c1669e3ee9b8ab9c121bb90b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3066, "license_type": "permissive", "max_line_length": 364, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/network/vyos/vyos_config.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module provides configuration file management of VyOS devices. It provides arguments for managing both the configuration file and state of the active configuration. All configuration statements are based on `set` and `delete` commands in the device configuration.\n class Vyos_config < Base\n # @return [Array<String>, String, nil] The ordered set of configuration lines to be managed and compared with the existing configuration on the remote device.\n attribute :lines\n validates :lines, type: TypeGeneric.new(String)\n\n # @return [String, nil] The C(src) argument specifies the path to the source config file to load. The source config file can either be in bracket format or set format. The source file can include Jinja2 template variables.\n attribute :src\n validates :src, type: String\n\n # @return [:line, :none, nil] The C(match) argument controls the method used to match against the current active configuration. By default, the desired config is matched against the active config and the deltas are loaded. If the C(match) argument is set to C(none) the active configuration is ignored and the configuration is always loaded.\n attribute :match\n validates :match, expression_inclusion: {:in=>[:line, :none], :message=>\"%{value} needs to be :line, :none\"}, allow_nil: true\n\n # @return [:yes, :no, nil] The C(backup) argument will backup the current devices active configuration to the Ansible control host prior to making any changes. The backup file will be located in the backup folder in the playbook root directory or role root directory, if playbook is part of an ansible role. If the directory does not exist, it is created.\n attribute :backup\n validates :backup, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Allows a commit description to be specified to be included when the configuration is committed. If the configuration is not changed or committed, this argument is ignored.\n attribute :comment\n validates :comment, type: String\n\n # @return [Object, nil] The C(config) argument specifies the base configuration to use to compare against the desired configuration. If this value is not specified, the module will automatically retrieve the current active configuration from the remote device.\n attribute :config\n\n # @return [:yes, :no, nil] The C(save) argument controls whether or not changes made to the active configuration are saved to disk. This is independent of committing the config. When set to True, the active configuration is saved.\n attribute :save\n validates :save, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6645483374595642, "alphanum_fraction": 0.6645483374595642, "avg_line_length": 39.796295166015625, "blob_id": "2f4bee3771877d28a966af00c0982e27b3f55cec", "content_id": "fb5434b99f8dce1816bfd385d52f61cb3f221494", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2203, "license_type": "permissive", "max_line_length": 157, "num_lines": 54, "path": "/lib/ansible/ruby/modules/generated/database/vertica/vertica_schema.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Adds or removes Vertica database schema and, optionally, roles with schema access privileges.\n # A schema will not be removed until all the objects have been dropped.\n # In such a situation, if the module tries to remove the schema it will fail and only remove roles created for the schema if they have no dependencies.\n class Vertica_schema < Base\n # @return [String] Name of the schema to add or remove.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Array<String>, String, nil] Comma separated list of roles to create and grant usage access to the schema.\n attribute :usage_roles\n validates :usage_roles, type: TypeGeneric.new(String)\n\n # @return [String, nil] Comma separated list of roles to create and grant usage and create access to the schema.\n attribute :create_roles\n validates :create_roles, type: String\n\n # @return [String, nil] Name of the user to set as owner of the schema.\n attribute :owner\n validates :owner, type: String\n\n # @return [:present, :absent, nil] Whether to create C(present), or drop C(absent) a schema.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [String, nil] Name of the Vertica database.\n attribute :db\n validates :db, type: String\n\n # @return [String, nil] Name of the Vertica cluster.\n attribute :cluster\n validates :cluster, type: String\n\n # @return [Integer, nil] Vertica cluster port to connect to.\n attribute :port\n validates :port, type: Integer\n\n # @return [String, nil] The username used to authenticate with.\n attribute :login_user\n validates :login_user, type: String\n\n # @return [Object, nil] The password used to authenticate with.\n attribute :login_password\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7311334013938904, "alphanum_fraction": 0.7383070588111877, "avg_line_length": 76.44444274902344, "blob_id": "a39dc3db2a0bdd50dba170e6fb37a9768777d594", "content_id": "fefc61256724d74827f5b5ba43d42a5f633e4b59", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3485, "license_type": "permissive", "max_line_length": 495, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_device_connectivity.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages device IP configuration settings for HA on a BIG-IP. Each BIG-IP device has synchronization and failover connectivity information (IP addresses) that you define as part of HA pairing or clustering. This module allows you to configure that information.\n class Bigip_device_connectivity < Base\n # @return [String, nil] Local IP address that the system uses for ConfigSync operations.\n attribute :config_sync_ip\n validates :config_sync_ip, type: String\n\n # @return [String, nil] Specifies the primary IP address for the system to use to mirror connections.\n attribute :mirror_primary_address\n validates :mirror_primary_address, type: String\n\n # @return [Object, nil] Specifies the secondary IP address for the system to use to mirror connections.\n attribute :mirror_secondary_address\n\n # @return [Array<Hash>, Hash, nil] Desired addresses to use for failover operations. Options C(address) and C(port) are supported with dictionary structure where C(address) is the local IP address that the system uses for failover operations. Port specifies the port that the system uses for failover operations. If C(port) is not specified, the default value C(1026) will be used. If you are specifying the (recommended) management IP address, use 'management-ip' in the address field.\n attribute :unicast_failover\n validates :unicast_failover, type: TypeGeneric.new(Hash)\n\n # @return [Symbol, nil] When C(yes), ensures that the Failover Multicast configuration is enabled and if no further multicast configuration is provided, ensures that C(multicast_interface), C(multicast_address) and C(multicast_port) are the defaults specified in each option's description. When C(no), ensures that Failover Multicast configuration is disabled.\n attribute :failover_multicast\n validates :failover_multicast, type: Symbol\n\n # @return [Object, nil] Interface over which the system sends multicast messages associated with failover. When C(failover_multicast) is C(yes) and this option is not provided, a default of C(eth0) will be used.\n attribute :multicast_interface\n\n # @return [Object, nil] IP address for the system to send multicast messages associated with failover. When C(failover_multicast) is C(yes) and this option is not provided, a default of C(224.0.0.245) will be used.\n attribute :multicast_address\n\n # @return [Object, nil] Port for the system to send multicast messages associated with failover. When C(failover_multicast) is C(yes) and this option is not provided, a default of C(62960) will be used. This value must be between 0 and 65535.\n attribute :multicast_port\n\n # @return [:\"between-clusters\", :\"within-cluster\", nil] Specifies whether mirroring occurs within the same cluster or between different clusters on a multi-bladed system.,This parameter is only supported on platforms that have multiple blades, such as Viprion hardware. It is not supported on VE.\n attribute :cluster_mirroring\n validates :cluster_mirroring, expression_inclusion: {:in=>[:\"between-clusters\", :\"within-cluster\"], :message=>\"%{value} needs to be :\\\"between-clusters\\\", :\\\"within-cluster\\\"\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6645129323005676, "alphanum_fraction": 0.6645129323005676, "avg_line_length": 53.378379821777344, "blob_id": "be158d97820bdba9cc0853ac731c054748dac453", "content_id": "b27dcbe3d2ac92b900bd787f92a3fbbfdb66ffc8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2012, "license_type": "permissive", "max_line_length": 652, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/remote_management/ipmi/ipmi_power.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Use this module for power management\n class Ipmi_power < Base\n # @return [String] Hostname or ip address of the BMC.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [Integer, nil] Remote RMCP port.\n attribute :port\n validates :port, type: Integer\n\n # @return [String] Username to use to connect to the BMC.\n attribute :user\n validates :user, presence: true, type: String\n\n # @return [String] Password to connect to the BMC.\n attribute :password\n validates :password, presence: true, type: String\n\n # @return [:\"on -- Request system turn on\", :\"off -- Request system turn off without waiting for OS to shutdown\", :\"shutdown -- Have system request OS proper shutdown\", :\"reset -- Request system reset without waiting for OS\", :\"boot -- If system is off, then 'on', else 'reset'\"] Whether to ensure that the machine in desired state.\n attribute :state\n validates :state, presence: true, expression_inclusion: {:in=>[:\"on -- Request system turn on\", :\"off -- Request system turn off without waiting for OS to shutdown\", :\"shutdown -- Have system request OS proper shutdown\", :\"reset -- Request system reset without waiting for OS\", :\"boot -- If system is off, then 'on', else 'reset'\"], :message=>\"%{value} needs to be :\\\"on -- Request system turn on\\\", :\\\"off -- Request system turn off without waiting for OS to shutdown\\\", :\\\"shutdown -- Have system request OS proper shutdown\\\", :\\\"reset -- Request system reset without waiting for OS\\\", :\\\"boot -- If system is off, then 'on', else 'reset'\\\"\"}\n\n # @return [Integer, nil] Maximum number of seconds before interrupt request.\n attribute :timeout\n validates :timeout, type: Integer\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7384305596351624, "alphanum_fraction": 0.7384305596351624, "avg_line_length": 57.47058868408203, "blob_id": "17f73216d7d736b30cb4a05084740ffb6ef1033f", "content_id": "bdb7b7eef548220f9e61721cf7fdb226ff562d61", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 994, "license_type": "permissive", "max_line_length": 361, "num_lines": 17, "path": "/lib/ansible/ruby/modules/generated/network/slxos/slxos_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Collects a base set of device facts from a remote device that is running SLX-OS. This module prepends all of the base network fact keys with C(ansible_net_<fact>). The facts module will always collect a base set of facts from the device and can enable or disable collection of additional facts.\n class Slxos_facts < Base\n # @return [String, nil] When supplied, this argument will restrict the facts collected to a given subset. Possible values for this argument include all, hardware, config, and interfaces. Can specify a list of values to include a larger subset. Values can also be used with an initial C(M(!)) to specify that a specific subset should not be collected.\n attribute :gather_subset\n validates :gather_subset, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6595091819763184, "alphanum_fraction": 0.6595091819763184, "avg_line_length": 46.70731735229492, "blob_id": "62c568496b3c367b67105e9c2d66501933b3583b", "content_id": "e8ee83d2fcb3ae6854de710b1858f7fcc4d394a6", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1956, "license_type": "permissive", "max_line_length": 290, "num_lines": 41, "path": "/lib/ansible/ruby/modules/generated/cloud/vultr/vr_user.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create, update and remove users.\n class Vultr_user < Base\n # @return [String] Name of the user\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [String, nil] Email of the user.,Required if C(state=present).\n attribute :email\n validates :email, type: String\n\n # @return [String, nil] Password of the user.,Only considered while creating a user or when C(force=yes).\n attribute :password\n validates :password, type: String\n\n # @return [Symbol, nil] Password will only be changed with enforcement.\n attribute :force\n validates :force, type: Symbol\n\n # @return [Boolean, nil] Whether the API is enabled or not.\n attribute :api_enabled\n validates :api_enabled, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [:manage_users, :subscriptions, :provisioning, :billing, :support, :abuse, :dns, :upgrade, nil] List of ACLs this users should have, see U(https://www.vultr.com/api/#user_user_list).,Required if C(state=present).,One or more of the choices list, some depend on each other.\n attribute :acls\n validates :acls, expression_inclusion: {:in=>[:manage_users, :subscriptions, :provisioning, :billing, :support, :abuse, :dns, :upgrade], :message=>\"%{value} needs to be :manage_users, :subscriptions, :provisioning, :billing, :support, :abuse, :dns, :upgrade\"}, allow_nil: true\n\n # @return [:present, :absent, nil] State of the user.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.680768609046936, "alphanum_fraction": 0.6827911734580994, "avg_line_length": 76.05194854736328, "blob_id": "3ca86177146d2f2f4330eeea6955175061d75ab8", "content_id": "4ef580647c05c27c6022794eb5ce4973a991936f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 5933, "license_type": "permissive", "max_line_length": 518, "num_lines": 77, "path": "/lib/ansible/ruby/modules/generated/packaging/os/apt.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages I(apt) packages (such as for Debian/Ubuntu).\n class Apt < Base\n # @return [String, nil] A list of package names, like C(foo), or package specifier with version, like C(foo=1.0). Name wildcards (fnmatch) like C(apt*) and version wildcards like C(foo=1.0*) are also supported.\n attribute :name\n validates :name, type: String\n\n # @return [:absent, :\"build-dep\", :latest, :present, nil] Indicates the desired package state. C(latest) ensures that the latest version is installed. C(build-dep) ensures the package build dependencies are installed.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :\"build-dep\", :latest, :present], :message=>\"%{value} needs to be :absent, :\\\"build-dep\\\", :latest, :present\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Run the equivalent of C(apt-get update) before the operation. Can be run as part of the package installation or as a separate step.\n attribute :update_cache\n validates :update_cache, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Integer, nil] Update the apt cache if its older than the I(cache_valid_time). This option is set in seconds. As of Ansible 2.4, this sets I(update_cache=yes).\n attribute :cache_valid_time\n validates :cache_valid_time, type: Integer\n\n # @return [:yes, :no, nil] Will force purging of configuration files if the module state is set to I(absent).\n attribute :purge\n validates :purge, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] Corresponds to the C(-t) option for I(apt) and sets pin priorities\n attribute :default_release\n validates :default_release, type: String\n\n # @return [Symbol, nil] Corresponds to the C(--no-install-recommends) option for I(apt). C(yes) installs recommended packages. C(no) does not install recommended packages. By default, Ansible will use the same defaults as the operating system. Suggested packages are never installed.\n attribute :install_recommends\n validates :install_recommends, type: Symbol\n\n # @return [:yes, :no, nil] Corresponds to the C(--force-yes) to I(apt-get) and implies C(allow_unauthenticated: yes),This option will disable checking both the packages' signatures and the certificates of the web servers they are downloaded from.,This option *is not* the equivalent of passing the C(-f) flag to I(apt-get) on the command line,**This is a destructive operation with the potential to destroy your system, and it should almost never be used.** Please also see C(man apt-get) for more information.\n attribute :force\n validates :force, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Ignore if packages cannot be authenticated. This is useful for bootstrapping environments that manage their own apt-key setup.,C(allow_unauthenticated) is only supported with state: I(install)/I(present)\n attribute :allow_unauthenticated\n validates :allow_unauthenticated, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:dist, :full, :no, :safe, :yes, nil] If yes or safe, performs an aptitude safe-upgrade.,If full, performs an aptitude full-upgrade.,If dist, performs an apt-get dist-upgrade.,Note: This does not upgrade a specific package, use state=latest for that.,Note: Since 2.4, apt-get is used as a fall-back if aptitude is not present.\n attribute :upgrade\n validates :upgrade, expression_inclusion: {:in=>[:dist, :full, :no, :safe, :yes], :message=>\"%{value} needs to be :dist, :full, :no, :safe, :yes\"}, allow_nil: true\n\n # @return [Array<String>, String, nil] Add dpkg options to apt command. Defaults to '-o \"Dpkg::Options::=--force-confdef\" -o \"Dpkg::Options::=--force-confold\"',Options should be supplied as comma separated list\n attribute :dpkg_options\n validates :dpkg_options, type: TypeGeneric.new(String)\n\n # @return [String, nil] Path to a .deb package on the remote machine.,If :// in the path, ansible will attempt to download deb before installing. (Version added 2.1)\n attribute :deb\n validates :deb, type: String\n\n # @return [:yes, :no, nil] If C(yes), remove unused dependency packages for all module states except I(build-dep). It can also be used as the only option.,Previous to version 2.4, autoclean was also an alias for autoremove, now it is its own separate command. See documentation for further information.\n attribute :autoremove\n validates :autoremove, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(yes), cleans the local repository of retrieved package files that can no longer be downloaded.\n attribute :autoclean\n validates :autoclean, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Only upgrade a package if it is already installed.\n attribute :only_upgrade\n validates :only_upgrade, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Force usage of apt-get instead of aptitude\n attribute :force_apt_get\n validates :force_apt_get, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.683491051197052, "alphanum_fraction": 0.683491051197052, "avg_line_length": 50.4054069519043, "blob_id": "a121d40387ab1597d45a1c2d79d9b8459938be1c", "content_id": "db08fb5933ec1cb1366892225095d70209f86e25", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1902, "license_type": "permissive", "max_line_length": 253, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/cloud/docker/docker_secret.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create and remove Docker secrets in a Swarm environment. Similar to `docker secret create` and `docker secret rm`.\n # Adds to the metadata of new secrets 'ansible_key', an encrypted hash representation of the data, which is then used\n # in future runs to test if a secret has changed.\n # If 'ansible_key is not present, then a secret will not be updated unless the C(force) option is set.\n # Updates to secrets are performed by removing the secret and creating it again.\n class Docker_secret < Base\n # @return [String, nil] String. The value of the secret. Required when state is C(present).\n attribute :data\n validates :data, type: String\n\n # @return [Hash, nil] A map of key:value meta data, where both the I(key) and I(value) are expected to be a string.,If new meta data is provided, or existing meta data is modified, the secret will be updated by removing it and creating it again.\n attribute :labels\n validates :labels, type: Hash\n\n # @return [Symbol, nil] Use with state C(present) to always remove and recreate an existing secret.,If I(true), an existing secret will be replaced, even if it has not changed.\n attribute :force\n validates :force, type: Symbol\n\n # @return [String] The name of the secret.\n attribute :name\n validates :name, presence: true, type: String\n\n # @return [:absent, :present, nil] Set to C(present), if the secret should exist, and C(absent), if it should not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7243747115135193, "alphanum_fraction": 0.7243747115135193, "avg_line_length": 69.31034851074219, "blob_id": "9316e192b72495078060f81d8695dc9888ad52b2", "content_id": "2e4ffc6c82f2a7af7acc4d4862d0f16994114899", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2039, "license_type": "permissive", "max_line_length": 819, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/windows/win_path.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Allows element-based ordering, addition, and removal of Windows path environment variables.\n class Win_path < Base\n # @return [String, nil] Target path environment variable name.\n attribute :name\n validates :name, type: String\n\n # @return [Array<String>, String] A single path element, or a list of path elements (ie, directories) to add or remove.,When multiple elements are included in the list (and C(state) is C(present)), the elements are guaranteed to appear in the same relative order in the resultant path value.,Variable expansions (eg, C(%VARNAME%)) are allowed, and are stored unexpanded in the target path element.,Any existing path elements not mentioned in C(elements) are always preserved in their current order.,New path elements are appended to the path, and existing path elements may be moved closer to the end to satisfy the requested ordering.,Paths are compared in a case-insensitive fashion, and trailing backslashes are ignored for comparison purposes. However, note that trailing backslashes in YAML require quotes.\n attribute :elements\n validates :elements, presence: true, type: TypeGeneric.new(String)\n\n # @return [:absent, :present, nil] Whether the path elements specified in C(elements) should be present or absent.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:machine, :user, nil] The level at which the environment variable specified by C(name) should be managed (either for the current user or global machine scope).\n attribute :scope\n validates :scope, expression_inclusion: {:in=>[:machine, :user], :message=>\"%{value} needs to be :machine, :user\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6501154899597168, "alphanum_fraction": 0.6524249315261841, "avg_line_length": 28.86206817626953, "blob_id": "72b147f1e4270ed2e3ab8bc7414074fbb8bcfbfe", "content_id": "b74970fc9122636371efb6cc9a9436fe5e8d4b8f", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 866, "license_type": "permissive", "max_line_length": 88, "num_lines": 29, "path": "/lib/ansible/ruby/modules/generated/notification/typetalk.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Send a message to typetalk using typetalk API ( http://developers.typetalk.in/ )\n class Typetalk < Base\n # @return [Integer] OAuth2 client ID\n attribute :client_id\n validates :client_id, presence: true, type: Integer\n\n # @return [Integer] OAuth2 client secret\n attribute :client_secret\n validates :client_secret, presence: true, type: Integer\n\n # @return [Integer] topic id to post message\n attribute :topic\n validates :topic, presence: true, type: Integer\n\n # @return [String] message body\n attribute :msg\n validates :msg, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6779323816299438, "alphanum_fraction": 0.6779323816299438, "avg_line_length": 26.94444465637207, "blob_id": "7d7ee934954382bbf8795663e54d4f9152a12088", "content_id": "cf6ee21e0e5f1fc6cb925b6d9be801d02d44cbf9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 503, "license_type": "permissive", "max_line_length": 66, "num_lines": 18, "path": "/lib/ansible/ruby/modules/generated/windows/win_hostname.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manages local Windows computer name.\n # A reboot is required for the computer name to take effect.\n class Win_hostname < Base\n # @return [String] The hostname to set for the computer.\n attribute :name\n validates :name, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6554803848266602, "alphanum_fraction": 0.6554803848266602, "avg_line_length": 38.73118209838867, "blob_id": "7707e322d29e34e3a200e6cefb58e3a397a778af", "content_id": "89bc420022d702f1db975cafdf8483baf5f43146", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3695, "license_type": "permissive", "max_line_length": 224, "num_lines": 93, "path": "/lib/ansible/ruby/modules/generated/network/panos/panos_nat_rule.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # - Create a policy nat rule. Keep in mind that we can either end up configuring source NAT, destination NAT, or both. Instead of splitting it into two we will make a fair attempt to determine which one the user wants.\n\n class Panos_nat_rule < Base\n # @return [String] IP address (or hostname) of PAN-OS device being configured.\n attribute :ip_address\n validates :ip_address, presence: true, type: String\n\n # @return [String, nil] Username credentials to use for auth unless I(api_key) is set.\n attribute :username\n validates :username, type: String\n\n # @return [String] Password credentials to use for auth unless I(api_key) is set.\n attribute :password\n validates :password, presence: true, type: String\n\n # @return [Object, nil] API key that can be used instead of I(username)/I(password) credentials.\n attribute :api_key\n\n # @return [Object, nil] The action to be taken. Supported values are I(add)/I(update)/I(find)/I(delete).\n attribute :operation\n\n # @return [String] name of the SNAT rule\n attribute :rule_name\n validates :rule_name, presence: true, type: String\n\n # @return [Array<String>, String] list of source zones\n attribute :source_zone\n validates :source_zone, presence: true, type: TypeGeneric.new(String)\n\n # @return [String] destination zone\n attribute :destination_zone\n validates :destination_zone, presence: true, type: String\n\n # @return [String, nil] list of source addresses\n attribute :source_ip\n validates :source_ip, type: String\n\n # @return [String, nil] list of destination addresses\n attribute :destination_ip\n validates :destination_ip, type: String\n\n # @return [String, nil] service\n attribute :service\n validates :service, type: String\n\n # @return [String, nil] type of source translation\n attribute :snat_type\n validates :snat_type, type: String\n\n # @return [String, nil] type of source translation. Supported values are I(translated-address)/I(translated-address).\n attribute :snat_address_type\n validates :snat_address_type, type: String\n\n # @return [Object, nil] Source NAT translated address. Used with Static-IP translation.\n attribute :snat_static_address\n\n # @return [Object, nil] Source NAT translated address. Used with Dynamic-IP and Dynamic-IP-and-Port.\n attribute :snat_dynamic_address\n\n # @return [String, nil] snat interface\n attribute :snat_interface\n validates :snat_interface, type: String\n\n # @return [Object, nil] snat interface address\n attribute :snat_interface_address\n\n # @return [:yes, :no, nil] bidirectional flag\n attribute :snat_bidirectional\n validates :snat_bidirectional, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [String, nil] dnat translated address\n attribute :dnat_address\n validates :dnat_address, type: String\n\n # @return [String, nil] dnat translated port\n attribute :dnat_port\n validates :dnat_port, type: String\n\n # @return [:yes, :no, nil] Commit configuration if changed.\n attribute :commit\n validates :commit, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6474389433860779, "alphanum_fraction": 0.6684002876281738, "avg_line_length": 64.41236877441406, "blob_id": "7b6e880da2e7394161402d98d457923736858937", "content_id": "2235b150336d0f5662bd658bcb170929d8cb062b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 6345, "license_type": "permissive", "max_line_length": 293, "num_lines": 97, "path": "/lib/ansible/ruby/modules/generated/network/cloudengine/ce_info_center_global.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module offers the ability to be output to the log buffer, log file, console, terminal, or log host on HUAWEI CloudEngine switches.\n class Ce_info_center_global < Base\n # @return [:true, :false, nil] Whether the info-center function is enabled. The value is of the Boolean type.\n attribute :info_center_enable\n validates :info_center_enable, expression_inclusion: {:in=>[:true, :false], :message=>\"%{value} needs to be :true, :false\"}, allow_nil: true\n\n # @return [Object, nil] Set the priority of the syslog packet.The value is an integer ranging from 0 to 7. The default value is 0.\n attribute :packet_priority\n\n # @return [:false, :true, nil] Whether a device is enabled to suppress duplicate statistics. The value is of the Boolean type.\n attribute :suppress_enable\n validates :suppress_enable, expression_inclusion: {:in=>[:false, :true], :message=>\"%{value} needs to be :false, :true\"}, allow_nil: true\n\n # @return [Object, nil] Maximum number of log files of the same type. The default value is 200.,The value range for log files is[3, 500], for security files is [1, 3],and for operation files is [1, 7].\n attribute :logfile_max_num\n\n # @return [4, 8, 16, 32, nil] Maximum size (in MB) of a log file. The default value is 32.,The value range for log files is [4, 8, 16, 32], for security files is [1, 4],,and for operation files is [1, 4].\n attribute :logfile_max_size\n validates :logfile_max_size, expression_inclusion: {:in=>[4, 8, 16, 32], :message=>\"%{value} needs to be 4, 8, 16, 32\"}, allow_nil: true\n\n # @return [Object, nil] Number for channel. The value is an integer ranging from 0 to 9. The default value is 0.\n attribute :channel_id\n\n # @return [String, nil] Channel name.The value is a string of 1 to 30 case-sensitive characters. The default value is console.\n attribute :channel_cfg_name\n validates :channel_cfg_name, type: String\n\n # @return [:console, :monitor, :trapbuffer, :logbuffer, :snmp, :logfile, nil] Direction of information output.\n attribute :channel_out_direct\n validates :channel_out_direct, expression_inclusion: {:in=>[:console, :monitor, :trapbuffer, :logbuffer, :snmp, :logfile], :message=>\"%{value} needs to be :console, :monitor, :trapbuffer, :logbuffer, :snmp, :logfile\"}, allow_nil: true\n\n # @return [Object, nil] Feature name of the filtered log. The value is a string of 1 to 31 case-insensitive characters.\n attribute :filter_feature_name\n\n # @return [Object, nil] Name of the filtered log. The value is a string of 1 to 63 case-sensitive characters.\n attribute :filter_log_name\n\n # @return [:ipv4, :ipv6, nil] Log server address type, IPv4 or IPv6.\n attribute :ip_type\n validates :ip_type, expression_inclusion: {:in=>[:ipv4, :ipv6], :message=>\"%{value} needs to be :ipv4, :ipv6\"}, allow_nil: true\n\n # @return [Object, nil] Log server address, IPv4 or IPv6 type. The value is a string of 0 to 255 characters. The value can be an valid IPv4 or IPv6 address.\n attribute :server_ip\n\n # @return [Object, nil] Server name. The value is a string of 1 to 255 case-sensitive characters.\n attribute :server_domain\n\n # @return [:yes, :no, nil] Use the default VPN or not.\n attribute :is_default_vpn\n validates :is_default_vpn, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [Object, nil] VPN name on a log server. The value is a string of 1 to 31 case-sensitive characters. The default value is _public_.\n attribute :vrf_name\n\n # @return [:emergencies, :alert, :critical, :error, :warning, :notification, :informational, :debugging, nil] Level of logs saved on a log server.\n attribute :level\n validates :level, expression_inclusion: {:in=>[:emergencies, :alert, :critical, :error, :warning, :notification, :informational, :debugging], :message=>\"%{value} needs to be :emergencies, :alert, :critical, :error, :warning, :notification, :informational, :debugging\"}, allow_nil: true\n\n # @return [Object, nil] Number of a port sending logs.The value is an integer ranging from 1 to 65535. For UDP, the default value is 514. For TCP, the default value is 601. For TSL, the default value is 6514.\n attribute :server_port\n\n # @return [:local0, :local1, :local2, :local3, :local4, :local5, :local6, :local7, nil] Log record tool.\n attribute :facility\n validates :facility, expression_inclusion: {:in=>[:local0, :local1, :local2, :local3, :local4, :local5, :local6, :local7], :message=>\"%{value} needs to be :local0, :local1, :local2, :local3, :local4, :local5, :local6, :local7\"}, allow_nil: true\n\n # @return [Object, nil] Channel name. The value is a string of 1 to 30 case-sensitive characters.\n attribute :channel_name\n\n # @return [:UTC, :localtime, nil] Log server timestamp. The value is of the enumerated type and case-sensitive.\n attribute :timestamp\n validates :timestamp, expression_inclusion: {:in=>[:UTC, :localtime], :message=>\"%{value} needs to be :UTC, :localtime\"}, allow_nil: true\n\n # @return [:tcp, :udp, nil] Transport mode. The value is of the enumerated type and case-sensitive.\n attribute :transport_mode\n validates :transport_mode, expression_inclusion: {:in=>[:tcp, :udp], :message=>\"%{value} needs to be :tcp, :udp\"}, allow_nil: true\n\n # @return [Object, nil] SSL policy name. The value is a string of 1 to 23 case-sensitive characters.\n attribute :ssl_policy_name\n\n # @return [Object, nil] Log source ip address, IPv4 or IPv6 type. The value is a string of 0 to 255. The value can be an valid IPv4 or IPv6 address.\n attribute :source_ip\n\n # @return [:present, :absent, nil] Specify desired state of the resource.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6877509951591492, "alphanum_fraction": 0.6877509951591492, "avg_line_length": 48.79999923706055, "blob_id": "b626ca53bbb1b11df1a02a1efe7a5e48e5174855", "content_id": "44e3851a1258caa5ec89f0c0c9b4935e82efaf39", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1992, "license_type": "permissive", "max_line_length": 299, "num_lines": 40, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_ucs_fetch.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # This module is used for fetching UCS files from remote machines and storing them locally in a file tree, organized by hostname. Note that this module is written to transfer UCS files that might not be present, so a missing remote UCS won't be an error unless fail_on_missing is set to 'yes'.\n class Bigip_ucs_fetch < Base\n # @return [Symbol, nil] Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.\n attribute :backup\n validates :backup, type: Symbol\n\n # @return [Boolean, nil] Creates the UCS based on the value of C(src) if the file does not already exist on the remote system.\n attribute :create_on_missing\n validates :create_on_missing, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String] A directory to save the UCS file into.\n attribute :dest\n validates :dest, presence: true, type: String\n\n # @return [Object, nil] Password to use to encrypt the UCS file if desired\n attribute :encryption_password\n\n # @return [Symbol, nil] Make the module fail if the UCS file on the remote system is missing.\n attribute :fail_on_missing\n validates :fail_on_missing, type: Symbol\n\n # @return [Boolean, nil] If C(no), the file will only be transferred if the destination does not exist.\n attribute :force\n validates :force, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] The name of the UCS file to create on the remote server for downloading\n attribute :src\n validates :src, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.658730149269104, "alphanum_fraction": 0.6626983880996704, "avg_line_length": 49.400001525878906, "blob_id": "130abe3d455464d1fbf1450dd955a5a025658623", "content_id": "9f6d093a504fa03af620df775b21481149e62cea", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2268, "license_type": "permissive", "max_line_length": 198, "num_lines": 45, "path": "/lib/ansible/ruby/modules/generated/network/aci/aci_epg_to_contract.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Bind EPGs to Contracts on Cisco ACI fabrics.\n class Aci_epg_to_contract < Base\n # @return [String, nil] Name of an existing application network profile, that will contain the EPGs.\n attribute :ap\n validates :ap, type: String\n\n # @return [String, nil] The name of the contract.\n attribute :contract\n validates :contract, type: String\n\n # @return [:consumer, :provider] Determines if the EPG should Provide or Consume the Contract.\n attribute :contract_type\n validates :contract_type, presence: true, expression_inclusion: {:in=>[:consumer, :provider], :message=>\"%{value} needs to be :consumer, :provider\"}\n\n # @return [String, nil] The name of the end point group.\n attribute :epg\n validates :epg, type: String\n\n # @return [:level1, :level2, :level3, :unspecified, nil] QoS class.,The APIC defaults to C(unspecified) when unset during creation.\n attribute :priority\n validates :priority, expression_inclusion: {:in=>[:level1, :level2, :level3, :unspecified], :message=>\"%{value} needs to be :level1, :level2, :level3, :unspecified\"}, allow_nil: true\n\n # @return [:all, :at_least_one, :at_most_one, :none, nil] The matching algorithm for Provided Contracts.,The APIC defaults to C(at_least_one) when unset during creation.\n attribute :provider_match\n validates :provider_match, expression_inclusion: {:in=>[:all, :at_least_one, :at_most_one, :none], :message=>\"%{value} needs to be :all, :at_least_one, :at_most_one, :none\"}, allow_nil: true\n\n # @return [:absent, :present, :query, nil] Use C(present) or C(absent) for adding or removing.,Use C(query) for listing an object or multiple objects.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present, :query], :message=>\"%{value} needs to be :absent, :present, :query\"}, allow_nil: true\n\n # @return [String, nil] Name of an existing tenant.\n attribute :tenant\n validates :tenant, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6857970952987671, "alphanum_fraction": 0.694492757320404, "avg_line_length": 52.90625, "blob_id": "c1fcd93f154d942314781efcc4a8c37e5ccb7ada", "content_id": "c0d44ef7dfb024ea185a759828b7bbb08e7bdd81", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1725, "license_type": "permissive", "max_line_length": 560, "num_lines": 32, "path": "/lib/ansible/ruby/modules/generated/cloud/vmware/vmware_guest_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Gather facts about a single VM on a VMware ESX cluster\n class Vmware_guest_facts < Base\n # @return [Object, nil] Name of the VM to work with,This is required if UUID is not supplied.\n attribute :name\n\n # @return [:first, :last, nil] If multiple VMs matching the name, use the first or last found\n attribute :name_match\n validates :name_match, expression_inclusion: {:in=>[:first, :last], :message=>\"%{value} needs to be :first, :last\"}, allow_nil: true\n\n # @return [String, nil] UUID of the instance to manage if known, this is VMware's unique identifier.,This is required if name is not supplied.\n attribute :uuid\n validates :uuid, type: String\n\n # @return [String, nil] Destination folder, absolute or relative path to find an existing guest.,This is required if name is supplied.,The folder should include the datacenter. ESX's datacenter is ha-datacenter,Examples:, folder: /ha-datacenter/vm, folder: ha-datacenter/vm, folder: /datacenter1/vm, folder: datacenter1/vm, folder: /datacenter1/vm/folder1, folder: datacenter1/vm/folder1, folder: /folder1/datacenter1/vm, folder: folder1/datacenter1/vm, folder: /folder1/datacenter1/vm/folder2, folder: vm/folder2, folder: folder2\n attribute :folder\n validates :folder, type: String\n\n # @return [String] Destination datacenter for the deploy operation\n attribute :datacenter\n validates :datacenter, presence: true, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6715570092201233, "alphanum_fraction": 0.7214860320091248, "avg_line_length": 30.53731346130371, "blob_id": "fc59592e9531d5a2565e335b16a0542d00657bde", "content_id": "1ed091d56d2f66e889a925afdc6f4a6f0f16acd5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4226, "license_type": "permissive", "max_line_length": 136, "num_lines": 134, "path": "/CHANGELOG.md", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# 1.0.30\n* Add `listen` support to handlers\n\n# 1.0.29\n* `yum_repository` validation improvements\n* Ensure existing validations are removed first for customized modules\n\n# 1.0.28\n* Add `delegate_facts` support to task DSL\n\n# 1.0.27\n* Support `always` when using `block` within a task\n\n# 1.0.26\n* Fix more issues with jinja expressions and model/module output\n\n# 1.0.25\n* Allow either array or string for `apt` module packages via the `name` attribute\n* Work around list weirdness in the PHP `pear` module\n\n# 1.0.24\n* Make variable counter static to avoid conflicts with importing roles\n\n# 1.0.23\n* Fixed issue with inclusions and jinja expressions. You have to use `expression_inclusion` on any custom Ansible modules you define now\n* Work with `fail` module by using `ansible_fail` in the DSL\n* Support `block` and `rescue` within a task\n\n# 1.0.22\n* Fix issue with jinja expressions/explicit string conversions\n\n# 1.0.21\n* Don't enforce validation with jinja expressions\n\n# 1.0.20\n* Add `tags` capability to playbooks\n* Add `when` support to roles\n\n# 1.0.19\n* Fix issue with `mode` and `copy` module\n\n# 1.0.18\n* `uri` module `status_code` type needed correcting\n\n# 1.0.17\n* Make `replace` a file module\n\n# 1.0.16\n* Add `validate` support to all file modules\n* Make `lineinfile` use file module helpers\n\n# 1.0.15\n* Correct issues with `uri` module\n\n# 1.0.14\n* Handle modules with attribute `method` properly\n\n# 1.0.13\n* Correct typo with role tagging support\n\n# 1.0.12\n* Add role tagging support\n\n# 1.0.11\n* Add `remote_user` support to tasks\n\n# 1.0.10\n* Add `delegated_to` support to tasks\n\n# 1.0.9\n* Add `vars` support to Playbooks\n\n# 1.0.8\n* Use Ansible's `type` metadata attribute to regain some module precision\n\n# 1.0.7\n* Ansible 2.7.1.0 compatibility\n* `ec2` corrections for `count_tag`, `ebs_optimized`, `instance_profile_name`, `exact_count` parameters\n* `ec2_ami`, `ec2_vol`, `iam_policy`, `iam`, `ec2_eip`, `ec2_group` correction for region\n* `ec2_ami` `state` parameter validation correction\n* `get_url`, `unarchive` support for `owner`, `group`, `mode`, `setype`, `selevel`\n* `wait_for` module `port` parameters validation fix - integer\n* `firewalld` permanent type fix\n* `pause` validation fix for `minutes` and `seconds`\n* `user` `groups` correction until Ansible 2.3\n* `gem` module now works and does not conflict with the Ruby keyword\n* `ec2_group` validation fixes for `vpc_id`, `purge_rules`, `purge_rules_egress`\n* `lineinfile` module - added missing `validate` parameter\n* `meta` should now work properly like `command` as a free form module\n* `with_items` supports splat style array parsing\n* `vars` now supported in task and blocks\n* `local_action` support\n\n# 1.0.6 - 14 October 2016\n* Allow sharing variables between tasks (#29)\n* Fix include support in handlers and allow include within task (#32)\n* Add 'connection' support to task DSL/model (#38)\n* Add YARD class comments for generated module classes (#22)\n* Fix `termination policies` in `ec2_asg` (#23)\n* `get_url` takes in a `Hash` for `headers` (#23)\n* `docker_container` `network_mode` is now a String and `volumes` is a `Hash` (#23)\n* `file`, `copy`, `template` support for `owner`, `group`, `mode`, `setype`, `selevel` (#23)\n* `set_fact` is now supported, pass a `Hash` as the parameter \n\n# 1.0.5 - 12 October 2016\n* Added no_log support\n* include_vars support\n* Fix Include Not Tested/Working (#40)\n* Updated modules for Ansible 2.1.2 (see 1d2b99b045d3dc8a3e444e7dc146eb737173cdc2)\n\n# 1.0.4 - 5 September 2016\n* Improve error messages (#7)\n* Add become/become_user/ignore to play DSL\n* Prevent these Ruby methods from interfering with module attributes: `[:system, :test, :warn, :sleep]` \n\n# 1.0.3 - 27 August 2016\n* Fix register count issue (#30)\n* Inclusion support from playbooks\n* Handler support\n* Block support\n* Add jinja variable helper\n* Add with_items support and add block helper for that and with_dict\n\n# 1.0.2 - 25 August 2016\n* Allow free form tasks to be supplied without a block\n* Ensure non-free form tasks are called with a block\n* Add separate clean/compile rake Tasks\n* Rename existing Rake task to execute\n* Try and avoid DSL conflicts\n\n## 1.0.1 - 24 August 2016\n* Bug fix/missing dependency\n\n## 1.0.0 - Initial Release\n" }, { "alpha_fraction": 0.6801292300224304, "alphanum_fraction": 0.6836833357810974, "avg_line_length": 51.45762634277344, "blob_id": "efe44ca66bcf3107624ebd97b7786b2d6d7a8f35", "content_id": "f86f9e971bfc2f1e23f8ca1cafc6ea35fdeffb70", "detected_licenses": [ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 3095, "license_type": "permissive", "max_line_length": 416, "num_lines": 59, "path": "/lib/ansible/ruby/modules/generated/network/f5/bigip_routedomain.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Manage route domains on a BIG-IP.\n class Bigip_routedomain < Base\n # @return [String, nil] The name of the route domain.\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] The bandwidth controller for the route domain.\n attribute :bwc_policy\n\n # @return [Object, nil] The maximum number of concurrent connections allowed for the route domain. Setting this to C(0) turns off connection limits.\n attribute :connection_limit\n\n # @return [Object, nil] Specifies descriptive text that identifies the route domain.\n attribute :description\n\n # @return [Object, nil] The eviction policy to use with this route domain. Apply an eviction policy to provide customized responses to flow overflows and slow flows on the route domain.\n attribute :flow_eviction_policy\n\n # @return [Integer, nil] The unique identifying integer representing the route domain.,This field is required when creating a new route domain.,In version 2.5, this value is no longer used to reference a route domain when making modifications to it (for instance during update and delete operations). Instead, the C(name) parameter is used. In version 2.6, the C(name) value will become a required parameter.\n attribute :id\n validates :id, type: Integer\n\n # @return [Object, nil] Specifies the route domain the system searches when it cannot find a route in the configured domain.\n attribute :parent\n\n # @return [String, nil] Partition to create the route domain on. Partitions cannot be updated once they are created.\n attribute :partition\n validates :partition, type: String\n\n # @return [:none, :BFD, :BGP, :\"IS-IS\", :OSPFv2, :OSPFv3, :PIM, :RIP, :RIPng, nil] Dynamic routing protocols for the system to use in the route domain.\n attribute :routing_protocol\n validates :routing_protocol, expression_inclusion: {:in=>[:none, :BFD, :BGP, :\"IS-IS\", :OSPFv2, :OSPFv3, :PIM, :RIP, :RIPng], :message=>\"%{value} needs to be :none, :BFD, :BGP, :\\\"IS-IS\\\", :OSPFv2, :OSPFv3, :PIM, :RIP, :RIPng\"}, allow_nil: true\n\n # @return [Object, nil] Service policy to associate with the route domain.\n attribute :service_policy\n\n # @return [:present, :absent, nil] Whether the route domain should exist or not.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Symbol, nil] Specifies whether the system enforces cross-routing restrictions or not.\n attribute :strict\n validates :strict, type: Symbol\n\n # @return [Array<String>, String, nil] VLANs for the system to use in the route domain.\n attribute :vlans\n validates :vlans, type: TypeGeneric.new(String)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7273303866386414, "alphanum_fraction": 0.7292327284812927, "avg_line_length": 59.653846740722656, "blob_id": "3a27bae7b4f4bcf58aff0aaa3b438c32896a2543", "content_id": "c4ae5acc42632224a7817f6b68ab7cd1aaaa2018", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1577, "license_type": "permissive", "max_line_length": 361, "num_lines": 26, "path": "/lib/ansible/ruby/modules/generated/identity/onepassword_facts.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # M(onepassword_facts) wraps the C(op) command line utility to fetch data about one or more 1password items and return as Ansible facts.\n # A fatal error occurs if any of the items being searched for can not be found.\n # Recommend using with the C(no_log) option to avoid logging the values of the secrets being retrieved.\n class Onepassword_facts < Base\n # @return [String, Array<Hash>, Hash] A list of one or more search terms.,Each search term can either be a simple string or it can be a dictionary for more control.,When passing a simple string, I(field) is assumed to be C(password).,When passing a dictionary, the following fields are available.\n attribute :search_terms\n validates :search_terms, presence: true, type: TypeGeneric.new(Hash, String)\n\n # @return [Object, nil] A dictionary containing authentication details. If this is set, M(onepassword_facts) will attempt to login to 1password automatically.,The required values can be stored in Ansible Vault, and passed to the module securely that way.,Without this option, you must have already logged in via the 1Password CLI before running Ansible.\n attribute :auto_login\n\n # @return [String, nil] Used to specify the exact path to the C(op) command line interface\n attribute :cli_path\n validates :cli_path, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.7006398439407349, "alphanum_fraction": 0.7015539407730103, "avg_line_length": 58.135135650634766, "blob_id": "64b7de6319a8bd80fe50a157c215572ff1051172", "content_id": "c52ad6ad5c912f19442ff8418b0d9daca4c7d822", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2188, "license_type": "permissive", "max_line_length": 282, "num_lines": 37, "path": "/lib/ansible/ruby/modules/generated/network/cumulus/nclu.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Interface to the Network Command Line Utility, developed to make it easier to configure operating systems running ifupdown2 and Quagga, such as Cumulus Linux. Command documentation is available at U(https://docs.cumulusnetworks.com/display/DOCS/Network+Command+Line+Utility)\n class Nclu < Base\n # @return [Array<String>, String, nil] A list of strings containing the net commands to run. Mutually exclusive with I(template).\n attribute :commands\n validates :commands, type: TypeGeneric.new(String)\n\n # @return [Array<String>, String, nil] A single, multi-line string with jinja2 formatting. This string will be broken by lines, and each line will be run through net. Mutually exclusive with I(commands).\n attribute :template\n validates :template, type: TypeGeneric.new(String)\n\n # @return [Boolean, nil] When true, performs a 'net commit' at the end of the block. Mutually exclusive with I(atomic).\n attribute :commit\n validates :commit, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] Boolean. When true, perform a 'net abort' before the block. This cleans out any uncommitted changes in the buffer. Mutually exclusive with I(atomic).\n attribute :abort\n validates :abort, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [Boolean, nil] When true, equivalent to both I(commit) and I(abort) being true. Mutually exclusive with I(commit) and I(atomic).\n attribute :atomic\n validates :atomic, expression_inclusion: {:in=>[true, false], :message=>\"%{value} needs to be true, false\"}, allow_nil: true\n\n # @return [String, nil] Commit description that will be recorded to the commit log if I(commit) or I(atomic) are true.\n attribute :description\n validates :description, type: String\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6798866987228394, "alphanum_fraction": 0.6798866987228394, "avg_line_length": 26.153846740722656, "blob_id": "99943d1533f417738009b9dc6dee15836fb12557", "content_id": "4add269bd401f691fd38300e59285994df2c7c9b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 706, "license_type": "permissive", "max_line_length": 64, "num_lines": 26, "path": "/lib/ansible/ruby/models/expression_inclusion_validator.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n\n# See LICENSE.txt for license\n\nclass ExpressionInclusionValidator < ActiveModel::EachValidator\n def validate_each(record, attribute, value)\n return if value.is_a? NilClass\n\n # We won't know until runtime what the type is\n return if value.is_a? Ansible::Ruby::Models::JinjaExpression\n\n valid_values = options[:in]\n return if valid_values.include? value\n\n failed = \"#{value} needs to be #{valid_values}\"\n failed = custom_error(value) if options[:message]\n record.errors[attribute] << failed\n end\n\n private\n\n def custom_error(value)\n options[:message].gsub('%{value}', value.to_s)\n .gsub('%{type}', value.class.name)\n end\nend\n" }, { "alpha_fraction": 0.6742090582847595, "alphanum_fraction": 0.6744092702865601, "avg_line_length": 63.85714340209961, "blob_id": "e0322c0275d43c93f4be730ce47ff589e726bd5b", "content_id": "a8985c0e41078f014a93fac3f04efba25198103b", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 4994, "license_type": "permissive", "max_line_length": 388, "num_lines": 77, "path": "/lib/ansible/ruby/modules/generated/files/xml.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # A CRUD-like interface to managing bits of XML files.\n # You might also be interested in a brief tutorial from U(https://www.w3schools.com/xml/xpath_intro.asp) and U(https://developer.mozilla.org/en-US/docs/Web/XPath).\n class Xml < Base\n # @return [String] Path to the file to operate on. File must exist ahead of time.,This parameter is required, unless C(xmlstring) is given.\n attribute :path\n validates :path, presence: true, type: String\n\n # @return [Object] A string containing XML on which to operate.,This parameter is required, unless C(path) is given.\n attribute :xmlstring\n validates :xmlstring, presence: true\n\n # @return [String, nil] A valid XPath expression describing the item(s) you want to manipulate.,Operates on the document root, C(/), by default.\n attribute :xpath\n validates :xpath, type: String\n\n # @return [Hash, nil] The namespace C(prefix:uri) mapping for the XPath expression.,Needs to be a C(dict), not a C(list) of items.\n attribute :namespaces\n validates :namespaces, type: Hash\n\n # @return [:absent, :present, nil] Set or remove an xpath selection (node(s), attribute(s)).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [String, nil] The attribute to select when using parameter C(value).,This is a string, not prepended with C(@).\n attribute :attribute\n validates :attribute, type: String\n\n # @return [Integer, String, Date, nil] Desired state of the selected attribute.,Either a string, or to unset a value, the Python C(None) keyword (YAML Equivalent, C(null)).,Elements default to no value (but present).,Attributes default to an empty string.\n attribute :value\n validates :value, type: MultipleTypes.new(Integer, String, Date)\n\n # @return [Array<Hash>, Hash, nil] Add additional child-element(s) to a selected element for a given C(xpath).,Child elements must be given in a list and each item may be either a string (eg. C(children=ansible) to add an empty C(<ansible/>) child element), or a hash where the key is an element name and the value is the element value.,This parameter requires C(xpath) to be set.\n attribute :add_children\n validates :add_children, type: TypeGeneric.new(Hash)\n\n # @return [Object, nil] Set the child-element(s) of a selected element for a given C(xpath).,Removes any existing children.,Child elements must be specified as in C(add_children).,This parameter requires C(xpath) to be set.\n attribute :set_children\n\n # @return [:yes, :no, nil] Search for a given C(xpath) and provide the count of any matches.,This parameter requires C(xpath) to be set.\n attribute :count\n validates :count, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Search for a given C(xpath) and print out any matches.,This parameter requires C(xpath) to be set.\n attribute :print_match\n validates :print_match, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Pretty print XML output.\n attribute :pretty_print\n validates :pretty_print, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:attribute, :text, nil] Search for a given C(xpath) and get content.,This parameter requires C(xpath) to be set.\n attribute :content\n validates :content, expression_inclusion: {:in=>[:attribute, :text], :message=>\"%{value} needs to be :attribute, :text\"}, allow_nil: true\n\n # @return [:xml, :yaml, nil] Type of input for C(add_children) and C(set_children).\n attribute :input_type\n validates :input_type, expression_inclusion: {:in=>[:xml, :yaml], :message=>\"%{value} needs to be :xml, :yaml\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.\n attribute :backup\n validates :backup, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n\n # @return [:yes, :no, nil] Remove CDATA tags surrounding text values.,Note that this might break your XML file if text values contain characters that could be interpreted as XML.\n attribute :strip_cdata_tags\n validates :strip_cdata_tags, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6697620153427124, "alphanum_fraction": 0.6703424453735352, "avg_line_length": 46.86111068725586, "blob_id": "d51d6f26f1f468138a57bf2335736ac88b64e836", "content_id": "2ba69ebaf7dfe8b9fb226319086190742c070cb9", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1723, "license_type": "permissive", "max_line_length": 229, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/network/aos/aos_asn_pool.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Apstra AOS ASN Pool module let you manage your ASN Pool easily. You can create and delete ASN Pool by Name, ID or by using a JSON File. This module is idempotent and support the I(check) mode. It's using the AOS REST API.\n class Aos_asn_pool < Base\n # @return [String] An existing AOS session as obtained by M(aos_login) module.\n attribute :session\n validates :session, presence: true, type: String\n\n # @return [String, nil] Name of the ASN Pool to manage. Only one of I(name), I(id) or I(content) can be set.\n attribute :name\n validates :name, type: String\n\n # @return [Object, nil] AOS Id of the ASN Pool to manage. Only one of I(name), I(id) or I(content) can be set.\n attribute :id\n\n # @return [String, nil] Datastructure of the ASN Pool to manage. The data can be in YAML / JSON or directly a variable. It's the same datastructure that is returned on success in I(value).\n attribute :content\n validates :content, type: String\n\n # @return [:present, :absent, nil] Indicate what is the expected state of the ASN Pool (present or not).\n attribute :state\n validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>\"%{value} needs to be :present, :absent\"}, allow_nil: true\n\n # @return [Array<Array>, Array, nil] List of ASNs ranges to add to the ASN Pool. Each range must have 2 values.\n attribute :ranges\n validates :ranges, type: TypeGeneric.new(Array)\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6656782627105713, "alphanum_fraction": 0.6656782627105713, "avg_line_length": 36.47222137451172, "blob_id": "d6782c3010353f715b76264d790619e2722e25b8", "content_id": "012351d9906681de09cb3da462eac0bbe1fb012e", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1349, "license_type": "permissive", "max_line_length": 163, "num_lines": 36, "path": "/lib/ansible/ruby/modules/generated/storage/netapp/na_ontap_cg_snapshot.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Create consistency group snapshot for ONTAP volumes.\n class Na_ontap_cg_snapshot < Base\n # @return [String, nil] If you want to create a snapshot.\n attribute :state\n validates :state, type: String\n\n # @return [String] Name of the vserver.\n attribute :vserver\n validates :vserver, presence: true, type: String\n\n # @return [Object] A list of volumes in this filer that is part of this CG operation.\n attribute :volumes\n validates :volumes, presence: true\n\n # @return [String] The provided name of the snapshot that is created in each volume.\n attribute :snapshot\n validates :snapshot, presence: true, type: String\n\n # @return [:urgent, :medium, :relaxed, nil] Timeout selector.\n attribute :timeout\n validates :timeout, expression_inclusion: {:in=>[:urgent, :medium, :relaxed], :message=>\"%{value} needs to be :urgent, :medium, :relaxed\"}, allow_nil: true\n\n # @return [Object, nil] A human readable SnapMirror label to be attached with the consistency group snapshot copies.\n attribute :snapmirror_label\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6697793006896973, "alphanum_fraction": 0.6697793006896973, "avg_line_length": 46.119998931884766, "blob_id": "dacbcb702d21e9d9cbcd61099f8e3119715fbcbd", "content_id": "73e5724c6c3732e54ff40e76ac5cc5539cece4cd", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 1178, "license_type": "permissive", "max_line_length": 216, "num_lines": 25, "path": "/lib/ansible/ruby/modules/generated/packaging/os/rpm_key.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Adds or removes (rpm --import) a gpg key to your rpm database.\n class Rpm_key < Base\n # @return [String] Key that will be modified. Can be a url, a file, or a keyid if the key already exists in the database.\n attribute :key\n validates :key, presence: true, type: String\n\n # @return [:absent, :present, nil] If the key will be imported or removed from the rpm db.\n attribute :state\n validates :state, expression_inclusion: {:in=>[:absent, :present], :message=>\"%{value} needs to be :absent, :present\"}, allow_nil: true\n\n # @return [:yes, :no, nil] If C(no) and the C(key) is a url starting with https, SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.\n attribute :validate_certs\n validates :validate_certs, expression_inclusion: {:in=>[:yes, :no], :message=>\"%{value} needs to be :yes, :no\"}, allow_nil: true\n end\n end\n end\nend\n" }, { "alpha_fraction": 0.6600630283355713, "alphanum_fraction": 0.6600630283355713, "avg_line_length": 44.32653045654297, "blob_id": "263f3c24d5134a18fe40174d39b26c0b6800d496", "content_id": "a0bf79ced058f503a0771c3b1bc63c12f4a0905c", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 2221, "license_type": "permissive", "max_line_length": 199, "num_lines": 49, "path": "/lib/ansible/ruby/modules/generated/network/panos/panos_set.rb", "repo_name": "wied03/ansible-ruby", "src_encoding": "UTF-8", "text": "# frozen_string_literal: true\n# See LICENSE.txt at root of repository\n# GENERATED FILE - DO NOT EDIT!!\nrequire 'ansible/ruby/modules/base'\n\nmodule Ansible\n module Ruby\n module Modules\n # Run an arbitrary 'xapi' command taking an XPath (i.e get) or XPath and element (i.e set).\n # See https://github.com/kevinsteves/pan-python/blob/master/doc/pan.xapi.rst for details\n # Runs a 'set' command by default\n # This should support _all_ commands that your PAN-OS device accepts vi it's cli\n # cli commands are found as\n # Once logged in issue 'debug cli on'\n # Enter configuration mode by issuing 'configure'\n # Enter your set (or other) command, for example 'set deviceconfig system timezone Australia/Melbourne'\n # returns\n # \"<request cmd=\"set\" obj=\"/config/devices/entry[@name='localhost.localdomain']/deviceconfig/system\" cookie=XXXX><timezone>Australia/Melbourne</timezone></request>\n\n # The 'xpath' is \"/config/devices/entry[@name='localhost.localdomain']/deviceconfig/system\"\n # The 'element' is \"<timezone>Australia/Melbourne</timezone>\"\n class Panos_set < Base\n # @return [String] IP address or host FQDN of the target PAN-OS NVA\n attribute :ip_address\n validates :ip_address, presence: true, type: String\n\n # @return [String, nil] User name for a user with admin rights on the PAN-OS NVA\n attribute :username\n validates :username, type: String\n\n # @return [String] Password for the given 'username'\n attribute :password\n validates :password, presence: true, type: String\n\n # @return [:set, :edit, :delete, :get, :show, :override, nil] Xapi method name which supports 'xpath' or 'xpath' and 'element'\n attribute :command\n validates :command, expression_inclusion: {:in=>[:set, :edit, :delete, :get, :show, :override], :message=>\"%{value} needs to be :set, :edit, :delete, :get, :show, :override\"}, allow_nil: true\n\n # @return [String] The 'xpath' for the commands configurable\n attribute :xpath\n validates :xpath, presence: true, type: String\n\n # @return [String, nil] The 'element' for the 'xpath' if required\n attribute :element\n validates :element, type: String\n end\n end\n end\nend\n" } ]
1,776
ushkarev/django-moj-template
https://github.com/ushkarev/django-moj-template
0f941f7a013f1dfcb89b4f36fd91503666b9e07f
ff1bd0e6cd7791593fceee8c731ec152f0d72e5a
75013ae741b538751a8b392c606c1ca68174dbba
refs/heads/master
2021-01-10T02:09:09.423313
2016-02-26T12:33:24
2016-02-29T17:47:07
52,619,306
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5898058414459229, "alphanum_fraction": 0.5898058414459229, "avg_line_length": 33.33333206176758, "blob_id": "e777d250dfd8bc6f032a90309a47c98c3b449edd", "content_id": "cd5319f78badbfd47f4559a1d9bb5094f1ca008c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 413, "license_type": "permissive", "max_line_length": 64, "num_lines": 12, "path": "/builder/template/django_moj_template/context_processors.py", "repo_name": "ushkarev/django-moj-template", "src_encoding": "UTF-8", "text": "from django.utils.translation import get_language, ugettext as _\n\n\ndef moj_context(request):\n return {\n 'html_lang': get_language(),\n 'homepage_url': 'https://www.gov.uk/',\n 'logo_link_title': _('Go to the GOV.UK homepage'),\n 'global_header_text': _('GOV.UK'),\n 'skip_link_message': _('Skip to main content'),\n 'crown_copyright_message': _('© Crown copyright')\n }\n" }, { "alpha_fraction": 0.5408057570457458, "alphanum_fraction": 0.5454545617103577, "avg_line_length": 34.20000076293945, "blob_id": "dcce86f7d555f83c3be4da1bae4f2970951f0c7d", "content_id": "9d77ff6822b8f96dc5c9ad324defb6ecc637cfbe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 3874, "license_type": "permissive", "max_line_length": 151, "num_lines": 110, "path": "/builder/template/django_moj_template/templates/django_moj_template/base.html", "repo_name": "ushkarev/django-moj-template", "src_encoding": "UTF-8", "text": "{% extends 'govuk_template/base.html' %}\n{% load i18n %}\n{% load static %}\n{% load django_moj_template %}\n\n\n{% block page_title %}{{ page_title|default:_('GOV.UK - The best place to find government services and information') }}{% endblock %}\n\n\n{% block head %}\n <!--[if gt IE 8]><!--><link href=\"{% static 'stylesheets/main.css' %}\" media=\"screen\" rel=\"stylesheet\" type=\"text/css\" /><!--<![endif]-->\n <!--[if IE 6]><link href=\"{% static 'stylesheets/main-ie6.css' %}\" media=\"screen\" rel=\"stylesheet\" type=\"text/css\" /><![endif]-->\n <!--[if IE 7]><link href=\"{% static 'stylesheets/main-ie7.css' %}\" media=\"screen\" rel=\"stylesheet\" type=\"text/css\" /><![endif]-->\n <!--[if IE 8]><link href=\"{% static 'stylesheets/main-ie8.css' %}\" media=\"screen\" rel=\"stylesheet\" type=\"text/css\" /><![endif]-->\n{% endblock %}\n\n\n{% block cookie_message %}\n <p>\n {% blocktrans trimmed %}\n GOV.UK uses cookies to make the site simpler. <a href=\"https://www.gov.uk/help/cookies\">Find out more aboutcookies</a>\n {% endblocktrans %}\n </p>\n{% endblock %}\n\n{% block header_class %}{% collapsewhitespace stripped %}\n {{ header_class }}\n {% if proposition %}\n with-proposition\n {% endif %}\n{% endcollapsewhitespace %}{% endblock %}\n\n\n{% block proposition_header %}\n {% if proposition %}\n <div class=\"header-proposition\">\n <div class=\"content\">\n {% if proposition.links|length > 1 %}\n <a href=\"#proposition-links\" class=\"js-header-toggle menu\">{% trans 'Menu' %}</a>\n {% endif %}\n <nav id=\"proposition-menu\">\n <a href=\"/\" id=\"proposition-name\">{{ proposition.name }}</a>\n {% if proposition.links|length == 1 %}\n <p id=\"proposition-link\">\n <a href=\"{{ proposition.links.0.url }}\" {% if proposition.links.0.active %}class=\"active\"{% endif %}>{{ proposition.links.0.name }}</a>\n </p>\n {% elif proposition.links|length > 1 %}\n <ul id=\"proposition-links\">\n {% for proposition_link in proposition.links %}\n <li><a href=\"{{ proposition_link.url }}\" {% if proposition_link.active %}class=\"active\"{% endif %}>{{ proposition_link.name }}</a></li>\n {% endfor %}\n </ul>\n {% endif %}\n </nav>\n </div>\n </div>\n {% endif %}\n{% endblock %}\n\n\n{% block content %}\n <main id=\"content\" role=\"main\">\n\n {% block phase_banner %}\n {% if phase == 'alpha' or phase == 'beta' %}\n <div class=\"phase-banner-{{ phase }}\">\n <p>\n <strong class=\"phase-tag\">\n {% if phase == 'alpha' %}\n {% trans 'ALPHA' %}\n {% else %}\n {% trans 'BETA' %}\n {% endif %}\n </strong>\n <span>\n {% blocktrans trimmed %}\n This is a new service – your <a href=\"{{ feedback_url }}\">feedback</a> will help us to improve it.\n {% endblocktrans %}\n </span>\n </p>\n </div>\n {% endif %}\n {% endblock %}\n\n {% block article_content %}{% endblock %}\n </main>\n{% endblock %}\n\n\n{% block footer_support_links %}\n <ul>\n {% for footer_support_link in footer_support_links %}\n <li><a href=\"{{ footer_support_link.url }}\">{{ footer_support_link.name }}</a></li>\n {% endfor %}\n <li>\n {% blocktrans trimmed with url='https://mojdigital.blog.gov.uk/' %}\n Built by <a href=\"{{ url }}\"><abbr title=\"Ministry of Justice\">MoJ</abbr> Digital</a>\n {% endblocktrans %}\n </li>\n </ul>\n{% endblock %}\n\n\n{% block licence_message %}\n <p>\n {% blocktrans trimmed with url='https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/' %}\n All content is available under the <a href=\"{{ url }}\" rel=\"license\">Open Government Licence v3.0</a>, except where otherwise stated\n {% endblocktrans %}\n </p>\n{% endblock %}\n" }, { "alpha_fraction": 0.6797152757644653, "alphanum_fraction": 0.6797152757644653, "avg_line_length": 27.100000381469727, "blob_id": "58d320d4e7d80238ad42bfdfdf6d1423584bc4e2", "content_id": "de5e75fffe32e70230b781ca494fecdfbc563f55", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 281, "license_type": "permissive", "max_line_length": 83, "num_lines": 10, "path": "/builder/template/django_moj_template/__init__.py", "repo_name": "ushkarev/django-moj-template", "src_encoding": "UTF-8", "text": "default_app_config = 'django_moj_template.app.AppConfig'\n\n\ndef get_assets_src_path():\n \"\"\"\n Returns the path to the assets folder where sass files are stored\n \"\"\"\n from os import path\n\n return path.abspath(path.join(path.dirname(path.join(__file__)), 'assets-src'))\n" }, { "alpha_fraction": 0.6089215874671936, "alphanum_fraction": 0.6128193736076355, "avg_line_length": 25.54022979736328, "blob_id": "60463bf97247fb5dd491a056c256f36d84f11253", "content_id": "356063b883259b59c9000cb86e4e8ffb7509f8c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2309, "license_type": "no_license", "max_line_length": 87, "num_lines": 87, "path": "/builder/utils.py", "repo_name": "ushkarev/django-moj-template", "src_encoding": "UTF-8", "text": "import functools\nimport sys\n\n\ndef announce_calls(announcement=None, after_call=False, bold=True):\n \"\"\"\n Decorator for printing a message when called, defaulting to first line of docstring\n :param announcement: message to print\n :param after_call: announce after calling instead of before\n :param bold: whether the message should be bold\n \"\"\"\n\n def decorator(func):\n message = announcement or one_line_doc(func) or getattr(func, '__name__', '')\n if bold and sys.stdout.isatty():\n message = term_bold(message)\n\n @functools.wraps(func)\n def wrapped_func(*args, **kwargs):\n if message and not after_call:\n print(term_bold(message), file=sys.stdout)\n result = func(*args, **kwargs)\n if message and after_call:\n print(term_bold(message), file=sys.stdout)\n return result\n\n return wrapped_func\n\n return decorator\n\n\ndef requisites(*prerequisites):\n \"\"\"\n A decorator to call pre-requisites before proceeding.\n If any return False, the chain stops.\n \"\"\"\n\n def decorator(func):\n @functools.wraps(func)\n def wrapped_func(*args, **kwargs):\n for requisite in prerequisites:\n result = requisite(*args, **kwargs)\n if result is False:\n return\n return func(*args, **kwargs)\n\n return wrapped_func\n\n return decorator\n\n\ndef _term(message, flag):\n return '\\x1b[%sm%s\\x1b[0m' % (flag, message)\n\n\ndef term_bold(message):\n \"\"\"\n Returns a bold version or message for printing to the terminal\n :param message: the message to wrap\n \"\"\"\n return _term(message, '1')\n\n\ndef term_green(message):\n \"\"\"\n Returns a green version or message for printing to the terminal\n :param message: the message to wrap\n \"\"\"\n return _term(message, '32')\n\n\ndef term_red(message):\n \"\"\"\n Returns a red version or message for printing to the terminal\n :param message: the message to wrap\n \"\"\"\n return _term(message, '31')\n\n\ndef one_line_doc(obj):\n \"\"\"\n Returns the first line of a docstring\n :param obj: an object with a docstring\n \"\"\"\n doc = getattr(obj, '__doc__', None) or ''\n doc = doc.strip().splitlines()\n return doc[0] if doc else ''\n" }, { "alpha_fraction": 0.760869562625885, "alphanum_fraction": 0.760869562625885, "avg_line_length": 48.28571319580078, "blob_id": "a0a7cf76b918aa310c5cc77791173681a683e61b", "content_id": "cb561078326ba176bc74ad6049f7618b7f721632", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 690, "license_type": "permissive", "max_line_length": 134, "num_lines": 14, "path": "/builder/template/README.md", "repo_name": "ushkarev/django-moj-template", "src_encoding": "UTF-8", "text": "Django MoJ Template\n===================\n\nA Django app containing pre-built gov.uk template and elements\nto be used when building Ministry of Justice Django-based services.\n\nUsage\n-----\n\n* Install the package `pip install django_moj_template` or add `django_moj_template` to your requirements.txt\n* Add `django_moj_template` to `INSTALLED_APPS` in settings\n* Add `django_moj_template.context_processors.moj_context` to `context_processors` list in the template settings\n* See `django_moj_template/base.html` and `sample_project` for template context usage\n* Optionally, add result of `django_moj_template.get_assets_src_path()` to sass import paths to include GOV.UK Elements in your builds\n" }, { "alpha_fraction": 0.7564102411270142, "alphanum_fraction": 0.7564102411270142, "avg_line_length": 25, "blob_id": "7b4dff97baf54c73079f3ae6a22427fbcbbce81a", "content_id": "89f5e1c6b43b26b9fde86b17907038bbb4defc0c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 156, "license_type": "permissive", "max_line_length": 52, "num_lines": 6, "path": "/builder/template/django_moj_template/app.py", "repo_name": "ushkarev/django-moj-template", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig as DjangoAppConfig\n\n\nclass AppConfig(DjangoAppConfig):\n name = 'django_moj_template'\n verbose_name = 'MoJ Template'\n" }, { "alpha_fraction": 0.5715234279632568, "alphanum_fraction": 0.5735147595405579, "avg_line_length": 31.053192138671875, "blob_id": "375fbd49c588732efb584319b7294b1c1a8f5328", "content_id": "d953e57e10520fd9bd823ce77a30cc199a50302f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3013, "license_type": "no_license", "max_line_length": 87, "num_lines": 94, "path": "/builder/folders.py", "repo_name": "ushkarev/django-moj-template", "src_encoding": "UTF-8", "text": "import os\nimport re\n\n\nclass FolderStructure:\n name = ''\n\n def __init__(self, path):\n self.path = path\n\n def _get_full_path(self, *paths):\n return os.path.join(self.path, *paths)\n\n\nclass Repository(FolderStructure):\n git_url = ''\n version = None\n\n def __init__(self, path):\n super().__init__(path)\n self.path = self._get_full_path(self.name)\n\n\nclass DjangoAppPackage(FolderStructure):\n name = 'django_moj_template'\n\n def __init__(self, path):\n super().__init__(path)\n self.build_flag_path = self._get_full_path('.build-date')\n self.app_path = self._get_full_path(self.name)\n self.static_path = self._get_full_path(self.name, 'static')\n self.images_path = self._get_full_path(self.name, 'static', 'images')\n self.javascripts_path = self._get_full_path(self.name, 'static', 'javascripts')\n self.stylesheets_path = self._get_full_path(self.name, 'static', 'stylesheets')\n self.templates_path = self._get_full_path(self.name, 'templates')\n self.assets_src_path = self._get_full_path(self.name, 'assets-src')\n\n\nclass GOVUKTemplate(Repository):\n name = 'govuk_template'\n git_url = 'https://github.com/alphagov/govuk_template.git'\n\n def __init__(self, path):\n super().__init__(path)\n self.pkg_root_path = self._get_full_path('pkg')\n self.pkg_path = None\n self.app_path = None\n\n def find_pkg_path(self):\n \"\"\"\n Finds the built python package folder\n e.g. django_govuk_template-0.17.0\n \"\"\"\n if not self.pkg_path:\n def matcher(path):\n if not os.path.isdir(os.path.join(self.pkg_root_path, path)):\n return False\n matches = re.match(r'^django_govuk_template-(?P<version>.*)$', path)\n if not matches:\n return False\n self.version = matches.group('version')\n return True\n\n pkg_path = list(filter(matcher, os.listdir(self.pkg_root_path)))\n if len(pkg_path) != 1:\n return None\n self.pkg_path = os.path.join(self.pkg_root_path, pkg_path[0])\n\n return self.pkg_path\n\n def find_app_path(self):\n \"\"\"\n Finds the path to the Django app inside the package\n \"\"\"\n if not self.app_path:\n if not self.pkg_path:\n return None\n app_path = os.path.join(self.pkg_path, 'govuk_template')\n if not os.path.isdir(app_path):\n return None\n self.app_path = app_path\n\n return self.app_path\n\n\nclass GOVUKElements(Repository):\n name = 'govuk_elements'\n git_url = 'https://github.com/alphagov/govuk_elements.git'\n\n def __init__(self, path):\n super().__init__(path)\n # these do not exist until gulp tasks run:\n self.content_path = self._get_full_path('govuk_modules', 'public')\n self.elements_sass_path = self._get_full_path('public', 'sass')\n" }, { "alpha_fraction": 0.5682998895645142, "alphanum_fraction": 0.570983350276947, "avg_line_length": 37.25165557861328, "blob_id": "84530be650801ba221f23cc8f60f63c546576f11", "content_id": "e35a778bf322e3056aecdd00abeea83587a90ed6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11554, "license_type": "no_license", "max_line_length": 114, "num_lines": 302, "path": "/builder/__init__.py", "repo_name": "ushkarev/django-moj-template", "src_encoding": "UTF-8", "text": "import argparse\nfrom collections import OrderedDict\nimport datetime\nimport filecmp\nimport os\nimport re\nimport subprocess\nimport sys\nimport textwrap\n\nfrom builder.folders import DjangoAppPackage, GOVUKTemplate, GOVUKElements\nfrom builder.utils import announce_calls, one_line_doc, requisites, term_bold\n\ncommands = OrderedDict()\n\n\ndef command(func):\n \"\"\"\n Decorator to make a method available as a command\n :param func: the callable to decorate\n \"\"\"\n name = func.__name__\n commands[name] = {\n 'command': func,\n 'name': name,\n }\n return func\n\n\nclass Builder:\n \"\"\"\n Builds a python package containing a Django app with\n the latest gov.uk template and elements\n \"\"\"\n\n def __init__(self, root_path):\n self.root_path = root_path\n self.template_path = os.path.join(root_path, 'builder', 'template')\n self.src_path = os.path.join(root_path, 'src')\n\n self.source_repositories = [\n GOVUKTemplate(self.src_path),\n GOVUKElements(self.src_path),\n ]\n self.package = DjangoAppPackage(os.path.join(root_path, 'build'))\n\n self.parser = argparse.ArgumentParser(description=textwrap.dedent(self.__doc__).strip())\n self.parser.add_argument('command', choices=[option['name'] for option in commands.values()])\n self.parser.add_argument('--optimise-images', dest='should_optimise_images', action='store_true')\n self.parser.add_argument('-v', '--verbose', action='store_true')\n args = self.parser.parse_args()\n self.command = args.command\n self.verbose = args.verbose\n self.should_optimise_images = args.should_optimise_images\n\n def main(self):\n commands[self.command]['command'](self)\n\n @command\n def help(self):\n \"\"\"\n Prints this help message\n \"\"\"\n print(self.parser.description)\n print('Commands:')\n max_comand_length = max(len(option['name']) for option in commands.values()) + 2\n for option in commands.values():\n name = option['name']\n print(' %s' % name + ' ' * (max_comand_length - len(name)) + one_line_doc(option['command']))\n\n # BUILDING\n\n @announce_calls('Checking build tools are available')\n def check_build_tools(self):\n def check(name, version, cmd, version_re):\n version_tuple = tuple(version.split('.'))\n try:\n output = subprocess.check_output(cmd).decode('utf-8')\n output = re.match(version_re, output, re.I)\n if not output or output.groups([1, len(version_tuple)]) < version_tuple:\n sys.exit('%s on the path must be at least version %s' % (name, output))\n except subprocess.CalledProcessError:\n sys.exit('%s is not on the path' % name)\n\n # check('Ruby', '2.2', ['ruby', '--version'], r'ruby (\\d+)\\.(\\d+)\\.')\n # check('Python', '3.4', ['python', '--version'], r'Python (\\d+)\\.(\\d+)\\.')\n check('bundler', '1.10', ['bundler', '--version'], r'Bundler version (\\d+)\\.(\\d+)\\.')\n check('npm', '3.7', ['npm', '--version'], r'(\\d+)\\.(\\d+)\\.')\n check('sass', '3.4', ['sass', '--version'], r'Sass (\\d+)\\.(\\d+)\\.')\n\n def make_paths(self):\n self.make_paths(self.src_path, self.package.static_path, self.package.templates_path)\n\n @announce_calls('Updating source repositories')\n def update_source_repositories(self):\n for repo in self.source_repositories:\n if os.path.isdir(repo.path):\n subprocess.check_call(['git', 'pull'], cwd=repo.path)\n else:\n subprocess.check_call(['git', 'clone', '--recursive',\n repo.git_url, repo.name], cwd=self.src_path)\n\n @classmethod\n def fix_ruby_version(cls, path):\n path = os.path.join(path, '.ruby-version')\n if not os.path.exists(path):\n sys.exit('No ruby version specified')\n with open(path) as f:\n ruby_version = f.read().strip()\n try:\n ruby_version_tuple = tuple(map(int, ruby_version.split('.')))\n if len(ruby_version_tuple) < 3 or ruby_version_tuple < (2, 2, 0):\n raise ValueError\n except ValueError:\n print(term_bold('Fixing ruby version to 2.2.3 (was %s)') % (ruby_version or '?'))\n with open(path, 'w') as f:\n f.write('2.2.3')\n\n @command\n @requisites(check_build_tools, make_paths, update_source_repositories)\n @announce_calls('Done', after_call=True)\n def build(self):\n \"\"\"\n Builds the complete python package\n \"\"\"\n for repo in self.source_repositories:\n getattr(self, 'build__%s' % repo.name)(repo)\n\n if self.should_optimise_images:\n self.optimise_images()\n self.create_django_app()\n\n @announce_calls('Building gov.uk template')\n def build__govuk_template(self, repo):\n self.fix_ruby_version(repo.path)\n subprocess.check_call(['bundle', 'install'], cwd=repo.path)\n subprocess.check_call(['bundle', 'exec', 'rake', 'build:django'], cwd=repo.path)\n\n if not repo.find_pkg_path():\n sys.exit('Could not find built package')\n if not repo.find_app_path():\n sys.exit('Cannot find built package app content')\n\n # copy built content\n self.rsync_folders(repo.app_path, self.package.app_path)\n\n @announce_calls('Building gov.uk elements')\n def build__govuk_elements(self, repo):\n subprocess.check_call(['npm', 'install'], cwd=repo.path)\n\n # build assets\n grunt_tasks = ['grunt']\n grunt_tasks.extend([\n # grunt tasks are a limited set taken from \"default\" task\n 'copy:govuk_template',\n 'copy:govuk_assets',\n 'copy:govuk_frontend_toolkit_scss',\n 'copy:govuk_frontend_toolkit_js',\n 'copy:govuk_frontend_toolkit_img',\n 'replace',\n 'sass',\n ])\n subprocess.check_call(grunt_tasks, cwd=repo.path)\n\n # copy built content\n self.rsync_folders_and_warn(repo.content_path, self.package.static_path,\n 'GOV.UK Elements overwrites %(count)d asset(s) from GOV.UK Template')\n\n # move sass files to assets folder (originating from govuk_frontend_toolkit?)\n self.rm_paths(self.package.assets_src_path)\n subprocess.check_call([\n 'mv', os.path.join(self.package.static_path, 'sass'), self.package.assets_src_path\n ])\n\n # copy additional elements sass to assets folder\n self.rsync_folders_and_warn(repo.elements_sass_path, self.package.assets_src_path,\n 'GOV.UK Elements build overwrites %(count)d asset(s)')\n\n # build sass files to static folder (originating from govuk_elements?)\n self.fix_sass_images_path(self.package.assets_src_path)\n sass_paths = '.:%s' % self.package.stylesheets_path\n subprocess.check_call(['sass', '--no-cache', '--sourcemap=none', '--update', sass_paths],\n cwd=self.package.assets_src_path)\n\n @classmethod\n def fix_sass_images_path(cls, path):\n path = os.path.join(path, 'elements', '_helpers.scss')\n with open(path) as f:\n helper_sass = f.read()\n helper_sass = re.sub(r'/public/', '../', helper_sass)\n with open(path, 'w') as f:\n f.write(helper_sass)\n\n def optimise_images(self):\n \"\"\"\n Use ImageOptim to optimise images on OS X only\n https://imageoptim.com/\n \"\"\"\n if sys.platform != 'darwin':\n return\n try:\n app_path = subprocess.check_output(['mdfind', 'kMDItemCFBundleIdentifier == \"net.pornel.ImageOptim\"'])\n except subprocess.CalledProcessError:\n return\n app_path = app_path.strip().decode('utf-8').splitlines()\n if not app_path:\n return\n app_path = app_path[0]\n bin_path = '%s/Contents/MacOS/ImageOptim' % app_path\n if not os.path.exists(bin_path):\n return\n\n print(term_bold('Optimising images… this may take a while!'))\n subprocess.check_call([bin_path, self.package.images_path, self.package.stylesheets_path])\n\n @announce_calls('Creating Django app')\n def create_django_app(self):\n # add templated files\n self.rsync_folders(self.template_path, self.package.path)\n\n # tidy up\n subprocess.check_call(['find', '.',\n '-name', '.DS_Store', '-or',\n '-name', '*.mo', '-or',\n '-name', '*.py?', '-or',\n '-path', '\"*/.sass-cache*\"',\n '-delete'],\n cwd=self.package.path)\n\n # mark build as complete\n with open(self.package.build_flag_path, 'w') as f:\n f.write(str(datetime.datetime.now()))\n\n # PUBLISHING\n\n @command\n @announce_calls('Done', after_call=True)\n def publish(self):\n \"\"\"\n Publishes the python package to PyPi\n \"\"\"\n if not os.path.exists(self.package.build_flag_path):\n sys.exit('Run the build command first before trying to publish')\n subprocess.check_call(['python', 'setup.py', 'sdist', 'upload'],\n cwd=self.package.path)\n\n # CLEANING\n\n @command\n def clean(self):\n \"\"\"\n Clean up sources and builds\n \"\"\"\n self.rm_paths(self.src_path, self.package.path)\n\n # UTILS\n\n @classmethod\n def make_paths(cls, *paths):\n for path in paths:\n if os.path.isdir(path):\n continue\n os.makedirs(path, 0o755)\n\n @classmethod\n def rm_paths(cls, *paths):\n for path in paths:\n if not os.path.exists(path):\n continue\n subprocess.check_call(['rm', '-rf', path])\n\n @classmethod\n def rsync_folders(cls, src_path, target_path):\n subprocess.check_call(['rsync', '-r', src_path.rstrip('/') + '/', target_path.rstrip('/')])\n\n @classmethod\n def diff_folders(cls, src_root_path, target_root_path, track_new=True):\n differences = []\n for dir_path, dir_names, file_names in os.walk(src_root_path):\n relative_dir_path = os.path.relpath(dir_path, src_root_path)\n target_dir_path = os.path.abspath(os.path.join(target_root_path, relative_dir_path))\n for file_name in file_names:\n relative_file_path = os.path.join(relative_dir_path, file_name)\n src_file_path = os.path.join(dir_path, file_name)\n target_file_path = os.path.join(target_dir_path, file_name)\n if not os.path.exists(target_file_path):\n if track_new:\n differences.append((relative_file_path, 'new'))\n elif not filecmp.cmp(src_file_path, target_file_path):\n differences.append((relative_file_path, 'modified'))\n return differences\n\n @classmethod\n def rsync_folders_and_warn(cls, src_path, target_path, message):\n differences = cls.diff_folders(src_path, target_path, track_new=False)\n if differences:\n print(term_bold(message % {\n 'count': len(differences)\n }))\n for difference in differences:\n print(' %s' % difference[0])\n cls.rsync_folders(src_path, target_path)\n" }, { "alpha_fraction": 0.5972222089767456, "alphanum_fraction": 0.6145833134651184, "avg_line_length": 23, "blob_id": "b644c40001379e68de90d8ff9cead2d9a7ac870d", "content_id": "71be8e65fc774bb148e48a4853cc36b11a6d1a20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 288, "license_type": "no_license", "max_line_length": 58, "num_lines": 12, "path": "/main.py", "repo_name": "ushkarev/django-moj-template", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport os\nimport sys\n\nif __name__ == '__main__':\n if sys.version_info[:2] < (3, 4):\n sys.exit('Python version must be at least 3.4')\n\n from builder import Builder\n\n root_path = os.path.dirname(os.path.abspath(__file__))\n Builder(root_path).main()\n" }, { "alpha_fraction": 0.6086572408676147, "alphanum_fraction": 0.6121907830238342, "avg_line_length": 28.0256404876709, "blob_id": "dcff114f1b265da00e2407ac51cff314c8a20379", "content_id": "b967c814216f7d16db15424d95e18bd9ab5eea0c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1132, "license_type": "permissive", "max_line_length": 83, "num_lines": 39, "path": "/builder/template/django_moj_template/templatetags/django_moj_template.py", "repo_name": "ushkarev/django-moj-template", "src_encoding": "UTF-8", "text": "import re\n\nfrom django import template\n\nregister = template.Library()\n\n\nclass CollapseWhitespaceNode(template.Node):\n def __init__(self, node_list, stripped):\n self.node_list = node_list\n self.stripped = stripped\n\n def render(self, context):\n output = self.node_list.render(context)\n if isinstance(output, str):\n output = re.sub(r'\\s+', ' ', output)\n if self.stripped:\n output = output.strip()\n return output\n\n\[email protected](name='collapsewhitespace')\ndef do_collapse_whitespace(parser, token):\n args = token.split_contents()[1:]\n arg_count = len(args)\n stripped = False\n try:\n if arg_count == 1:\n if args[0] == 'stripped':\n stripped = True\n else:\n raise ValueError\n elif arg_count > 1:\n raise ValueError\n except ValueError:\n raise template.TemplateSyntaxError('\"stripped\" is the only valid argument')\n node_list = parser.parse(('endcollapsewhitespace',))\n parser.delete_first_token()\n return CollapseWhitespaceNode(node_list, stripped=stripped)\n" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.7144736647605896, "avg_line_length": 29.399999618530273, "blob_id": "d9497d618bec1996fc6620da8013b41a3698f59b", "content_id": "207224ed3b76ee92d12ac9d2bb63a01201acc4ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 764, "license_type": "no_license", "max_line_length": 93, "num_lines": 25, "path": "/README.md", "repo_name": "ushkarev/django-moj-template", "src_encoding": "UTF-8", "text": "Django MoJ Template App Builder\n===============================\n\nUsing the latest gov.uk template and elements, builds a python package\ncontaining a Django app with required static assets and templates.\n\nNB: *Do not* include this repository in your services directly, it is only\ndesigned to create the python package that you then install.\n\nRequirements\n------------\n\n* Ruby 2.2+, bundler 1.10+ and sass 3.4 (probably installed via rbenv)\n* Python 3.4+\n* npm 3.7+\n\nUsage\n-----\n\n`./main.py build` – will download and build the Django app, see build folder\n\n`./main.py publish` – will publish the Django app to PyPi\n\nThe published package is what you use in your services: `pip install django_moj_template` or \nadd `django_moj_template` to your requirements.txt\n" } ]
11
onurcc/youtube-thumbnail-downloader
https://github.com/onurcc/youtube-thumbnail-downloader
9debd1c4cc0615c7eb8daa26f844ce6a90401f00
3e71a27f55edb75ee63d523a95fb7b7a95ec4bb0
b7d56d446058f4960f5eeea67520e772e5a13094
refs/heads/master
2021-01-20T20:48:36.184881
2016-08-08T21:49:29
2016-08-08T21:49:29
65,241,876
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.6496453881263733, "alphanum_fraction": 0.652482271194458, "avg_line_length": 28.375, "blob_id": "d023bd1a00441bf04239c4bcc6d9f400485538d7", "content_id": "b32ef47ac77e54594bb73852461686f80afa9ff0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 705, "license_type": "no_license", "max_line_length": 61, "num_lines": 24, "path": "/main.py", "repo_name": "onurcc/youtube-thumbnail-downloader", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, request\nfrom flask.ext.bootstrap import Bootstrap\nimport urllib.request as ur\nfrom bs4 import BeautifulSoup\nimport webbrowser\n\napp = Flask(__name__)\nbootstrap = Bootstrap(app)\n\n\[email protected]('/', methods=['GET', 'POST'])\ndef index():\n img_page = None\n if request.method == 'POST' and 'link' in request.form:\n video_url = request.form['link']\n page = ur.urlopen(video_url).read()\n soup = BeautifulSoup(page, \"html.parser\")\n img_url = soup.findAll(attrs={\"property\":\"og:image\"})\n img_page = img_url[0]['content']\n return render_template('index.html', img_page=img_page)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n" } ]
1
NamitS27/NZEC-Bot
https://github.com/NamitS27/NZEC-Bot
6188c0f5dd3319b1ce66cf9263c85ac96ec02674
11768f70b29fe02199bd2586954c91be828ed565
0e8518907f1eadfc2725c36038108daec17744e0
refs/heads/master
2023-02-22T14:08:33.831297
2021-01-20T03:13:56
2021-01-20T03:13:56
324,370,393
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6576551795005798, "alphanum_fraction": 0.6631724238395691, "avg_line_length": 32.87850570678711, "blob_id": "cfeb9b1fcb0f4d76dd9a2b8f627d520b6a1e0ad3", "content_id": "b1253fc7f59928bdac33c7b09780702ea961c7fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3625, "license_type": "no_license", "max_line_length": 247, "num_lines": 107, "path": "/lib/cogs/problems.py", "repo_name": "NamitS27/NZEC-Bot", "src_encoding": "UTF-8", "text": "from discord.ext.commands import Cog, BucketType\nfrom discord.ext.commands import command, cooldown\nfrom discord import Embed\nfrom aiohttp import request\nfrom typing import Optional\nimport random\n\nclass Problems(Cog):\n\tdef __init__(self,bot):\n\t\tself.bot = bot\n\n\tasync def get_contest_ids(self):\n\t\turl=\"https://codeforces.com/api/contest.list\"\n\t\tasync with request('GET',url) as response:\n\t\t\tif response.status == 200:\n\t\t\t\tdata = await response.json()\n\t\t\t\tdata = data[\"result\"]\n\t\t\t\tids = []\n\t\t\t\tfor contest in data: \n\t\t\t\t\tids.append(contest[\"id\"])\n\t\t\t\treturn True,ids\n\t\t\telse:\n\t\t\t\tdata = await response.json()\n\t\t\t\tdata = data[\"comment\"]\n\t\t\t\treturn False,data\n\n\tasync def generate_solved_problems_ids(self,username):\n\t\turl=f\"https://codeforces.com/api/user.status?handle={username}\"\n\t\tasync with request('GET',url) as response:\n\t\t\tif response.status == 200:\n\t\t\t\tdata = await response.json()\n\t\t\t\tdata = data[\"result\"]\n\t\t\t\tids = []\n\t\t\t\tfor problem in data: \n\t\t\t\t\tif problem[\"verdict\"]==\"OK\":\n\t\t\t\t\t\tids.append(problem[\"contestId\"])\n\t\t\t\treturn True,ids\n\t\t\telse:\n\t\t\t\tdata = await response.json()\n\t\t\t\tdata = data[\"comment\"]\n\t\t\t\treturn False,data\n\n\tdef create_problem_embed(self,problems):\n\t\tdescription = \"\"\n\t\tfor index,name,link,rating,tags in problems:\n\t\t\ttags = \",\".join(tags)\n\t\t\tdescription += f'[{index}. {name}]({link}) [{rating}]\\nTags : *{tags}*\\n\\n'\n\t\tembed = Embed(description=description,colour=0xffffff)\n\t\treturn embed\n\n\n\t@command(name=\"getproblems\",aliases=[\"getp\"],brief=\"Problem Suggestion on basis of arguments\")\n\t@cooldown(1,60*2,BucketType.user)\n\tasync def fetch_problems(self,ctx,username:str,min_rating:int,max_rating:int,*,tags: Optional[str] = \"\"):\n\t\t\"\"\"\n\t\tGives the list of the problems on the basis of the codeforces username and the problems will be in the range of [minimum rating,maximum rating] as specified by the user. Also the user can specify the tags using \"tag_name\" (between double quotes)\n\t\t\"\"\"\n\t\ttags = \";\".join([tag[1:len(tag)-1] for tag in tags.split(' ')])\n\t\tcontest_flag,contests = await self.get_contest_ids()\n\t\tsolved_flag,solved = await self.generate_solved_problems_ids(username)\n\t\t\n\t\tif contest_flag and solved_flag:\n\t\t\turl=f\"https://codeforces.com/api/problemset.problems?tags={tags}\"\n\t\t\tasync with request('GET',url) as response:\n\t\t\t\tif response.status == 200:\n\t\t\t\t\tdata = await response.json()\n\t\t\t\t\tdata = data[\"result\"][\"problems\"]\n\t\t\t\t\tids = set(contests) - set(solved)\n\t\t\t\t\tproblems = []\n\t\t\t\t\tgive_problem = []\n\t\t\t\t\tcnt = 0\n\t\t\t\t\tfor problem in data:\n\t\t\t\t\t\tif \"*special\" in problem['tags']:\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\trating = problem['rating']\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\trating = None\n\t\t\t\t\t\tif rating is not None:\n\t\t\t\t\t\t\tif problem[\"contestId\"] in ids and (int(rating)>=min_rating and int(rating)<=max_rating):\n\t\t\t\t\t\t\t\tcontest_id = problem[\"contestId\"]\n\t\t\t\t\t\t\t\tproblem_index = problem[\"index\"]\n\t\t\t\t\t\t\t\tlink = f\"https://www.codeforces.com/problemset/problem/{contest_id}/{problem_index}\"\n\t\t\t\t\t\t\t\tproblems.append((problem_index,problem[\"name\"],link,rating,problem[\"tags\"]))\n\t\t\t\t\tindex_list = random.sample(range(0,len(problems)-1), 5)\n\t\t\t\t\tfor i in index_list:\n\t\t\t\t\t\tgive_problem.append(problems[i])\n\t\t\t\t\t\n\t\t\t\t\tembed = self.create_problem_embed(give_problem)\n\t\t\t\t\tawait ctx.send(f'Here are the problems for practice for `{username}`',embed=embed)\t\t\t\t\t\n\t\t\t\telse:\n\t\t\t\t\tdata = await response.json()\n\t\t\t\t\tdata = data[\"comment\"]\n\t\t\t\t\tawait ctx.send(f\"Error : {data}\")\n\t\telse:\n\t\t\tawait ctx.send(\"Some Error Occured!\")\n\n \n\[email protected]()\n\tasync def on_ready(self):\n\t\tif not self.bot.ready:\n\t\t\tself.bot.cogs_ready.ready_up(\"problems\")\n\n \n\ndef setup(bot):\n\tbot.add_cog(Problems(bot))\n" }, { "alpha_fraction": 0.6355599164962769, "alphanum_fraction": 0.6355599164962769, "avg_line_length": 27.27777862548828, "blob_id": "041f224828f3d6830ac77f139abc18c31c92e6bd", "content_id": "9ff45860e2411cdad7073af14a8505d1445fd14e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1018, "license_type": "no_license", "max_line_length": 74, "num_lines": 36, "path": "/lib/cogs/resources.py", "repo_name": "NamitS27/NZEC-Bot", "src_encoding": "UTF-8", "text": "from discord.ext.commands import Cog, BucketType\nfrom discord.ext.commands import command, cooldown\nfrom discord import Embed\nfrom prettytable import PrettyTable\nfrom aiohttp import request\n\nclass Resources(Cog):\n def __init__(self,bot):\n self.bot = bot\n\n @command(name=\"addr\")\n async def add_resources(self,ctx,resource_link,tag):\n \"\"\"\n #TODO: Breif and description is left\n \"\"\"\n user_id = str(ctx.author.id)\n server_id = str(ctx.message.guild.id)\n try:\n self.bot.db.add_resource(server_id,user_id,tag,resource_link)\n await ctx.send(\"Resource submitted successfully!\")\n except:\n await ctx.send(\"Some Error Occurred! Cannot add the resource\")\n\n @command(name=\"findr\")\n async def find_resources(self,ctx,tag):\n pass\n \n\n @Cog.listener()\n async def on_ready(self):\n if not self.bot.ready:\n self.bot.cogs_ready.ready_up(\"resources\")\n\n\ndef setup(bot):\n\tbot.add_cog(Resources(bot))\n" }, { "alpha_fraction": 0.6729559898376465, "alphanum_fraction": 0.7672955989837646, "avg_line_length": 16.77777862548828, "blob_id": "9e0d8e197995a4c1f6bc482f393c4ed27dc2ae54", "content_id": "9267114f9037007c71ff014b0fff378c26b9b788", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 159, "license_type": "no_license", "max_line_length": 47, "num_lines": 9, "path": "/requirements.txt", "repo_name": "NamitS27/NZEC-Bot", "src_encoding": "UTF-8", "text": "git+https://github.com/Rapptz/discord-ext-menus\naiohttp==3.6.3\nAPScheduler==3.6.3\nDateTime==4.3\ndiscord.py==1.5.1\nmatplotlib==3.3.3\ntyping\nprettytable\npsycopg2" }, { "alpha_fraction": 0.6431514620780945, "alphanum_fraction": 0.6799076795578003, "avg_line_length": 34.479530334472656, "blob_id": "26679879e8c7a3d0e769b45c04f9ef04b97823e9", "content_id": "dd1ab42f2b0801f7991dabf6bad9a35a97d1ffe0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6067, "license_type": "no_license", "max_line_length": 182, "num_lines": 171, "path": "/lib/cogs/plot.py", "repo_name": "NamitS27/NZEC-Bot", "src_encoding": "UTF-8", "text": "from discord.ext.commands import Cog, BucketType\nfrom discord.ext.commands import command, cooldown\nfrom discord import Embed,File\nfrom aiohttp import request\nfrom typing import Optional\nimport datetime as dt\nimport matplotlib.pyplot as plt \nimport matplotlib.dates as mdates\nimport os\nfrom collections import namedtuple\n\nRank = namedtuple('Rank', 'low high title title_abbr color_graph color_embed')\n\nRATED_RANKS = (\n Rank(-10 ** 9, 1200, 'Newbie', 'N', '#CCCCCC', 0x808080),\n Rank(1200, 1400, 'Pupil', 'P', '#77FF77', 0x008000),\n Rank(1400, 1600, 'Specialist', 'S', '#77DDBB', 0x03a89e),\n Rank(1600, 1900, 'Expert', 'E', '#AAAAFF', 0x0000ff),\n Rank(1900, 2100, 'Candidate Master', 'CM', '#FF88FF', 0xaa00aa),\n Rank(2100, 2300, 'Master', 'M', '#FFCC88', 0xff8c00),\n Rank(2300, 2400, 'International Master', 'IM', '#FFBB55', 0xf57500),\n Rank(2400, 2600, 'Grandmaster', 'GM', '#FF7777', 0xff3030),\n Rank(2600, 3000, 'International Grandmaster', 'IGM', '#FF3333', 0xff0000),\n Rank(3000, 10 ** 9, 'Legendary Grandmaster', 'LGM', '#AA0000', 0xcc0000)\n)\n\nclass ULegend:\n\tdef __init__(self,s):\n\t\tself.string = s\n\n\tdef __str__(self):\n\t\treturn self.string\n\nclass Plot(Cog):\n\tdef __init__(self,bot):\n\t\tself.bot = bot\n\t\t\n\n\tasync def username_plot(self,username):\n\t\turl = f\"https://codeforces.com/api/user.rating?handle={username}\"\n\t\t\n\t\tasync with request('GET',url,headers={}) as response:\n\t\t\tif response.status == 200:\n\t\t\t\tdata = await response.json()\n\t\t\t\tdata = data['result']\n\t\t\t\trating = []\n\t\t\t\ttime = []\n\t\t\t\tfor submission in data:\n\t\t\t\t\trating.append(submission[\"newRating\"])\n\t\t\t\t\ttime.append(dt.datetime.fromtimestamp(submission[\"ratingUpdateTimeSeconds\"]))\n\t\t\t\treturn True,rating,time\n\t\t\telse:\n\t\t\t\tdata = await response.json()\n\t\t\t\tdata = data[\"comment\"]\n\t\t\t\treturn False,data,None\n\n\tasync def generate_solved_problems_ratings(self,username):\n\t\turl=f\"https://codeforces.com/api/user.status?handle={username}\"\n\t\tasync with request('GET',url) as response:\n\t\t\tif response.status == 200:\n\t\t\t\tdata = await response.json()\n\t\t\t\tdata = data[\"result\"]\n\t\t\t\trating = []\n\t\t\t\tfor problem in data: \n\t\t\t\t\ttry:\n\t\t\t\t\t\tratng = problem[\"problem\"][\"rating\"]\n\t\t\t\t\texcept:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\trating.append(ratng)\n\t\t\t\treturn True,rating\n\t\t\telse:\n\t\t\t\tdata = await response.json()\n\t\t\t\tdata = data[\"comment\"]\n\t\t\t\treturn False,data\n\t\t\n\n\n\t@command(name=\"plotr\",aliases=[\"pr\"],brief=\"Plots the codeforces rating graph\")\n\t@cooldown(1,30,BucketType.user)\n\tasync def plot_rating(self,ctx,username:str,username_2: Optional[str] = None,username_3: Optional[str] = None):\n\t\t\"\"\"\n\t\tRating graph of the username specified will be ploted. Also of more than one user but at most of 3 users, rating graph can be plotted with the help of which one can easily compare.\n\t\t\"\"\"\n\t\tusernames = []\n\t\tusername_1_flag,rating_1,time_1 = await self.username_plot(username)\n\t\tif username_1_flag:\n\t\t\tplt.plot(time_1,rating_1,linestyle='-',marker='o',markersize=3,markeredgewidth=0.5,markerfacecolor='white')\n\t\t\tusernames.append(f'{username} ({rating_1[len(rating_1)-1]})')\n\t\t\tif username_2 is not None:\n\t\t\t\tusername_2_flag,rating_2,time_2 = await self.username_plot(username_2)\n\t\t\t\tif username_2_flag:\n\t\t\t\t\tplt.plot(time_2,rating_2,linestyle='-',marker='o',markersize=3,markeredgewidth=0.5,markerfacecolor='white')\n\t\t\t\t\tusernames.append(f'{username_2} ({rating_2[len(rating_2)-1]})')\n\t\t\t\t\tif username_3 is not None:\n\t\t\t\t\t\tusername_3_flag,rating_3,time_3 = await self.username_plot(username_3)\n\t\t\t\t\t\tif username_3_flag:\n\t\t\t\t\t\t\tplt.plot(time_3,rating_3,linestyle='-',marker='o',markersize=3,markeredgewidth=0.5,markerfacecolor='white')\n\t\t\t\t\t\t\tusernames.append(f'{username_3} ({rating_3[len(rating_3)-1]})')\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tawait ctx.send(embed=Embed(description=f\"Error occured!, **Comment** = {rating_3}\"))\n\t\t\t\t\t\t\treturn\n\t\t\t\telse:\n\t\t\t\t\tawait ctx.send(embed=Embed(description=f\"Error occured!, **Comment** = {rating_2}\"))\n\t\t\t\t\treturn\n\t\telse:\n\t\t\tawait ctx.send(embed=Embed(description=f\"Error occured!, **Comment** = {rating_1}\"))\n\t\t\treturn\n\t\t\n\t\t\"\"\"\n\t\tFollowing are the tweaks done in the graph to make it look pretty\n\t\t\"\"\"\n\t\tymin, ymax = plt.gca().get_ylim()\n\t\tbgcolor = plt.gca().get_facecolor()\n\t\tfor rank in RATED_RANKS:\n\t\t\tplt.axhspan(rank.low, rank.high, facecolor=rank.color_graph, alpha=0.8, edgecolor=bgcolor, linewidth=0.5)\n\n\t\tlocs, labels = plt.xticks()\n\t\tfor loc in locs:\n\t\t\tplt.axvline(loc, color=bgcolor, linewidth=0.5)\n\t\tplt.ylim(ymin, ymax)\n\t\tplt.gcf().autofmt_xdate()\n\t\tplt.gca().fmt_xdata = mdates.DateFormatter('%Y:%m:%d')\n\t\tplt.title('Rating Graph')\n\t\tplt.legend([ULegend(username) for username in usernames])\n\t\tplt.savefig(\"rating_graph.png\")\n\t\tplt.gcf().clear()\n\t\tplt.close()\n\n\t\tawait ctx.send(file=File(\"rating_graph.png\"))\n\t\tos.remove(\"rating_graph.png\")\n\n\t@command(name=\"plots\",aliases=[\"ps\"],brief=\"Histogram plot of solved problems on codeforces\")\n\tasync def plot_solved_graph(self,ctx,username: str,username_2: str,*,other_usernames:Optional[str] = None):\n\t\t\"\"\"\n\t\tHistogram plot of the solved problems of more than one user in order to visualize more clearly how one is performing compared to others.\n\t\t\"\"\"\n\t\tusernames = [username,username_2]\n\t\tif other_usernames is not None:\n\t\t\tusernames += other_usernames.split(\" \")\n\t\thist_ratings = []\n\t\tlabels = []\n\t\tfor username in usernames:\n\t\t\tflag,rating = await self.generate_solved_problems_ratings(username)\n\t\t\tif flag:\n\t\t\t\thist_ratings.append(rating)\n\t\t\t\tlabels.append(f\"{username}: {len(rating)}\")\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tawait ctx.send(embed=Embed(title=\"Error!\",description=rating))\n\t\t\t\treturn\n\t\t\n\t\tplt.grid(color='grey',alpha=0.9,linestyle='-',linewidth=0.3)\n\t\tplt.hist(hist_ratings)\n\t\tplt.legend(labels)\n\t\tplt.xlabel(\"Rating\")\n\t\tplt.ylabel(\"Number of Problems Solved\")\n\t\tplt.title(\"Comparison!\")\n\t\tplt.savefig(\"histograms_solved.png\")\n\t\tplt.gcf().clear()\n\t\tplt.close()\n\t\tawait ctx.send(file=File(\"histograms_solved.png\"))\n\t\tos.remove(\"histograms_solved.png\")\n\n\[email protected]()\n\tasync def on_ready(self):\n\t\tif not self.bot.ready:\n\t\t\tself.bot.cogs_ready.ready_up(\"plot\")\n\n\t\ndef setup(bot):\n\tbot.add_cog(Plot(bot))\n" }, { "alpha_fraction": 0.6916723847389221, "alphanum_fraction": 0.6999312043190002, "avg_line_length": 21.015151977539062, "blob_id": "6a468ffa8e688160e710f15b82751a220b6f8027", "content_id": "43ba44d2696c8a1919a1a9629a722b2137cb44cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1453, "license_type": "no_license", "max_line_length": 165, "num_lines": 66, "path": "/README.md", "repo_name": "NamitS27/NZEC-Bot", "src_encoding": "UTF-8", "text": "<p align=\"center\">\n<img src=\"/images/icon.jpg\" width=100/>\n</p>\n\n<h3 align='center'>NZEC Discord Bot</h3>\n\n<p align='center'>\n This is a discord bot build on the theme of Competitive Programming & CodeForces\n</p>\n\n-------------\n\n<h3>Table of Contents</h3>\n\n* [About The Project](#about-the-project)\n * [Build with](#build-with)\n * [Database Used](#database-used)\n\n* [Usage](#usage)\n* [Contributing](#contributing)\n* [Acknowledgements](#acknowledgements)\n\n\n<br>\n\n### About The Project\n\n#### Build With\n\n* Python\n\n#### Database Used\n\n* [PostgreSQL](https://www.postgresql.org/) (To install postgres click on it)\n\n\n\n<br>\n\n### Usage\n\nClick [here](http://bit.ly/nzec_bot) to add to your discord server!\n\n> **Note**: As I am out of free hours the bot will be offline,so you can mail me on [email protected] to make the bot online and enjoy it!\n\nTo know more about how to use the bot commands, type `~help` after adding bot to your server.\n\n\n<br>\n\n### Contributing\n\nContributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are **greatly appreciated**.\n\n1. Fork the Project\n2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`)\n3. Commit your Changes (`git commit -m 'Added some AmazingFeature'`)\n4. Push to the Branch (`git push origin feature/AmazingFeature`)\n5. Open a Pull Request\n\n\n<br>\n\n### Acknowledgements\n\n* [Codeforces API](https://codeforces.com/apiHelp)\n" }, { "alpha_fraction": 0.6689774990081787, "alphanum_fraction": 0.677209734916687, "avg_line_length": 30.834482192993164, "blob_id": "64b32b619e94a8e8ac458f5e1e60b313b42e359d", "content_id": "b38b0fb9d6e919b30ff435ef6b10c65526e2b982", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4616, "license_type": "no_license", "max_line_length": 137, "num_lines": 145, "path": "/lib/cogs/contest.py", "repo_name": "NamitS27/NZEC-Bot", "src_encoding": "UTF-8", "text": "from discord.ext.commands import Cog, BucketType\nfrom discord.ext.commands import command,BadArgument, cooldown\nfrom discord import Embed\nfrom aiohttp import request\nimport random\nfrom typing import Optional\n\nclass Contest(Cog):\n\tdef __init__(self,bot):\n\t\tself.bot = bot\n\n\tdef parse_args(self,args):\n\t\tusernames = []\n\t\ttags = \"\"\n\t\targs = args.split(' ')\n\t\tfor argument in args:\n\t\t\tif argument[0] != '\"':\n\t\t\t\tusernames.append(argument)\n\t\t\telse:\n\t\t\t\ttags += f'{argument[1:len(argument)-1]};'\n\t\tif len(tags)>1:\n\t\t\tif tags[len(tags)-1]==';':\n\t\t\t\ttags = tags[:len(tags)-1]\n\t\t\n\t\treturn usernames,tags\n\n\tasync def generate_solved_problems_names(self,username):\n\t\turl=f\"https://codeforces.com/api/user.status?handle={username}\"\n\t\tasync with request('GET',url) as response:\n\t\t\tif response.status == 200:\n\t\t\t\tdata = await response.json()\n\t\t\t\tdata = data[\"result\"]\n\t\t\t\tnames = []\n\t\t\t\tfor problem in data: \n\t\t\t\t\tif problem[\"verdict\"]==\"OK\":\n\t\t\t\t\t\tnames.append(problem[\"problem\"][\"name\"])\n\t\t\t\treturn True,names\n\t\t\telse:\n\t\t\t\tdata = await response.json()\n\t\t\t\tdata = data[\"comment\"]\n\t\t\t\treturn False,data\n\n\tasync def get_problems(self,tags):\n\t\turl=f\"https://codeforces.com/api/problemset.problems?tags={tags}\"\n\t\tasync with request('GET',url) as response:\n\t\t\tif response.status == 200:\n\t\t\t\tdata = await response.json()\n\t\t\t\tdata = data[\"result\"][\"problems\"]\n\t\t\t\tproblems = []\n\t\t\t\tfor problem in data:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tcid = problem[\"contestId\"]\n\t\t\t\t\t\trating = problem[\"rating\"]\n\t\t\t\t\texcept:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tproblems.append((problem[\"name\"],problem[\"index\"],cid,rating))\n\t\t\t\treturn True,problems\n\t\t\telse:\n\t\t\t\tdata = await response.json()\n\t\t\t\tdata = data[\"comment\"]\n\t\t\t\treturn False,data\n\n\tasync def get_rating(self,usernames):\n\t\tusername = \";\".join(usernames)\n\t\turl = f\"https://codeforces.com/api/user.info?handles={username}\"\n\t\tasync with request('GET',url) as response:\n\t\t\tif response.status == 200:\n\t\t\t\tratings = []\n\t\t\t\tdata = await response.json()\n\t\t\t\tdata = data[\"result\"]\n\t\t\t\tfor info in data:\n\t\t\t\t\tratings.append(info[\"rating\"])\n\t\t\t\treturn True,ratings\n\t\t\telse:\n\t\t\t\tdata = await response.json()\n\t\t\t\tdata = data[\"comment\"]\n\t\t\t\treturn False,data\n\n\t@command(name=\"mashup\",aliases=[\"cmash\"],usage=\"mashup|cmash <username> [tags]\",brief=\"Creates a smart mashup of problems\")\n\t@cooldown(1,30,BucketType.guild)\n\tasync def create_mashup(self,ctx,*,args: str):\n\t\t\"\"\"\n\t\tCreates the mashup of 4 problems on the basis of the arguments which can be given as follows,\n\t\tusernames : the user can give space seperated codeforces handles of the people for whom they wish to create a mashup.\n\t\ttags : tags are to be given space seperated quoted using double quotes(\"tag\") which are used to find the problems related to this tags.\n\t\t\"\"\"\n\t\tusernames,tags = self.parse_args(args)\n\t\tsolved = []\n\t\tfor username in usernames:\n\t\t\tflag,names= await self.generate_solved_problems_names(username)\n\t\t\tif not flag:\n\t\t\t\tctx.send(embed=Embed(description=f\"Error Occured!\\n**Comment** : {names}\"))\n\t\t\t\treturn\n\t\t\tsolved += names\n\n\t\tproblem_flag,problems = await self.get_problems(tags)\n\t\tif not problem_flag:\n\t\t\tawait ctx.send(embed=Embed(description=f\"Error Occured!\\n**Comment** : {problems}\"))\n\t\t\treturn \n\t\trating_flag,user_rating = await self.get_rating(usernames)\n\t\t\n\t\tif not rating_flag:\n\t\t\tawait ctx.send(embed=Embed(description=f\"Error Occured!\\n**Comment** : {user_rating}\"))\n\t\t\treturn\n\t\tavg_rating = sum(user_rating)//len(usernames)\n\t\t\n\t\tpossible_suggestions = []\n\t\tfor name,index,cid,rating in problems:\n\t\t\tif name not in solved and rating-avg_rating <= 100 and rating-avg_rating >= -150:\n\t\t\t\tlink = f\"https://www.codeforces.com/problemset/problem/{cid}/{index}\"\n\t\t\t\tpossible_suggestions.append((index,name,link,rating))\n\t\t\n\t\tif len(possible_suggestions)<4:\n\t\t\tawait ctx.send(embed=Embed(description=\"Cannot create mashup for the given handles!\"))\n\t\t\treturn\n\t\t\n\t\tmashup_problems = []\n\t\twhile len(mashup_problems)!=4:\n\t\t\tindex = random.randint(0,len(possible_suggestions)-1)\n\t\t\tif possible_suggestions[index] not in mashup_problems:\n\t\t\t\tmashup_problems.append(possible_suggestions[index])\n\t\t\n\t\tdescription = \"\"\n\t\tindexes = ['A','B','C','D']\n\t\ti = 0\n\t\tfor ind,name,link,rating in mashup_problems:\n\t\t\tdescription += f\"[{indexes[i]}. {name}]({link}) [{rating}]\\n\\n\"\n\t\t\ti += 1\n\n\t\tmessage = \"Mashup for\"\n\t\tfor user in usernames:\n\t\t\tmessage += f' `{user}`,'\n\t\tmessage = message[:len(message)-1]\n\t\tembed = Embed(description=description,colour=0xF22324)\t\t \n\t\tawait ctx.send(message,embed=embed)\n\t\t\n\n\[email protected]()\n\tasync def on_ready(self):\n\t\tif not self.bot.ready:\n\t\t\tself.bot.cogs_ready.ready_up(\"contest\")\n\n\t\ndef setup(bot):\n\tbot.add_cog(Contest(bot))\n" }, { "alpha_fraction": 0.7030725479125977, "alphanum_fraction": 0.7082365155220032, "avg_line_length": 28.799999237060547, "blob_id": "edca21883db8513a9340b22b08503e5226d6ea33", "content_id": "2fbf6063d1e99d9a43e4e9286dfc3c993ffef1f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3873, "license_type": "no_license", "max_line_length": 252, "num_lines": 130, "path": "/lib/bot/__init__.py", "repo_name": "NamitS27/NZEC-Bot", "src_encoding": "UTF-8", "text": "from discord import Intents\nfrom glob import glob\nimport datetime\nfrom math import *\nfrom asyncio import sleep\nimport discord\nfrom discord.ext.commands import Bot as BotBase\nfrom discord import Embed,File\nfrom discord.ext.commands import Context\nfrom discord.errors import Forbidden\nfrom db.database import Database\nfrom discord.ext.commands import (CommandNotFound, BadArgument, MissingRequiredArgument,CommandOnCooldown)\nfrom apscheduler.schedulers.asyncio import AsyncIOScheduler\nimport os\n\nPREFIX = \"~\"\nCOGS = [path.split(\"/\")[-1][:-3] for path in glob(\"./lib/cogs/*.py\")]\nIGNORE_EXCEPTIONS = (CommandNotFound, BadArgument)\n\nclass Ready(object):\n\tdef __init__(self):\n\t\tfor cog in COGS:\n\t\t\tsetattr(self, cog, False)\n\n\tdef ready_up(self, cog):\n\t\tsetattr(self, cog, True)\n\t\tprint(f\" {cog} cog is now ready!\")\n\n\tdef all_ready(self):\n\t\treturn all([getattr(self, cog) for cog in COGS])\n\nclass Bot(BotBase):\n\tdef __init__(self):\n\t\tself.PREFIX = PREFIX\n\t\tself.ready = False\n\t\tself.cogs_ready = Ready()\n\t\tself.db = Database()\n\t\tself.scheduler = AsyncIOScheduler()\n\t\tsuper().__init__(command_prefix=PREFIX,intents=Intents.all())\n\n\tdef pretty_print_time(self,seconds: int):\n\t\tdays, seconds = divmod(seconds, 86400)\n\t\thours, seconds = divmod(seconds, 3600)\n\t\tminutes, seconds = divmod(seconds, 60)\n\t\tif days>0:\n\t\t\treturn f\"{days} days, {hours} hours {minutes} mins and {seconds} secs\"\n\t\telif hours>0:\n\t\t\treturn f\"{hours} hours {minutes} mins and {seconds} secs\"\n\t\telif minutes>0:\n\t\t\treturn f\"{minutes} mins and {seconds} secs\"\n\t\telse:\n\t\t\treturn f\"{seconds} secs\"\n\n\tdef setup(self):\n\t\tprint(\"Connecting to database...\")\n\t\tself.db.connect()\n\t\tprint(\"Connected to database successfully!!\")\n\t\tprint(\" COGS =\",COGS)\n\t\tfor cog in COGS:\n\t\t\tself.load_extension(f\"lib.cogs.{cog}\")\n\t\t\tprint(f\" {cog} cog is lock and loaded\")\n\n\t\tprint(\"setup complete\")\n\n\tdef run(self):\n\t\tprint(\"Running setup...\")\n\t\tself.setup()\n\t\tself.TOKEN = os.environ.get('TOKEN')\n\t\tprint(\"Bot is running..!\")\n\t\tsuper().run(self.TOKEN,reconnect=True)\n\n\tasync def process_commands(self, message):\n\t\tctx = await self.get_context(message, cls=Context)\n\n\t\tif ctx.command is not None:\n\t\t\tif not self.ready:\n\t\t\t\tawait ctx.send(\"I'm not ready to receive commands. Please wait a few seconds.\")\n\n\t\t\telse:\n\t\t\t\tawait self.invoke(ctx)\n\n\tasync def on_connect(self):\n\t\tprint(\"Bot is connected..!\")\n\n\tasync def on_disconnect(self):\n\t\tprint(\"Bot is disconnected..!\")\n\n\tasync def on_error(self,err,*args,**kwargs):\n\t\tif err==\"on_command_error\":\n\t\t\tawait args[0].send(embed=Embed(description=\"Wrong usage of the command\\nExplore the help of the respective command for more details\\n\\nOR\\n\\n Note: If you think that you are using the command correctly then contact the developer (Email: [email protected]) \"))\n\t\t\n\t\traise \n\n\tasync def on_command_error(self,ctx,exc):\n\t\tif any([isinstance(exc, error) for error in IGNORE_EXCEPTIONS]):\n\t\t\tawait ctx.send(\"Contact the developer\\nEmail: [email protected]\")\n\n\t\telif isinstance(exc, MissingRequiredArgument):\n\t\t\tawait ctx.send(\"One or more required arguments are missing.\")\n\n\t\telif isinstance(exc, CommandOnCooldown):\n\t\t\tretry_sec = self.pretty_print_time(ceil(exc.retry_after))\n\t\t\tawait ctx.send(f\"That command is on {str(exc.cooldown.type).split('.')[-1]} cooldown. Try again in {retry_sec} :timer:\")\n\n\t\telif hasattr(exc, \"original\"):\n\n\t\t\tif isinstance(exc.original, Forbidden):\n\t\t\t\tawait ctx.send(\"I do not have permission to do that.\")\n\n\t\t\telse:\n\t\t\t\traise exc.original\n\n\t\telse:\n\t\t\traise exc\n\n\tasync def on_ready(self):\n\t\tif not self.ready:\n\t\t\twhile not self.cogs_ready.all_ready():\n\t\t\t\tawait sleep(0.5)\n\t\t\tself.ready = True\n\t\t\tawait self.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=\"~help\"))\n\t\t\tprint(\"Bot is ready\")\n\t\telse:\n\t\t\tprint(\"Bot reconnected!\")\n\n\tasync def on_message(self,message):\n\t\tif not message.author.bot:\n\t\t\tawait self.process_commands(message)\n\nbot = Bot()" }, { "alpha_fraction": 0.6519784331321716, "alphanum_fraction": 0.6780575513839722, "avg_line_length": 24.227272033691406, "blob_id": "8598314af656e77e8f5bafabd0cb1161ff93e7f9", "content_id": "390b9e7d759f7cefabb35de27372f879f503a39e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1112, "license_type": "no_license", "max_line_length": 101, "num_lines": 44, "path": "/test.py", "repo_name": "NamitS27/NZEC-Bot", "src_encoding": "UTF-8", "text": "import psycopg2\nimport os\n\nglobal conn\n\ntry:\n dbname = os.environ.get('DATABASE_NAME')\n user = os.environ.get('DATABASE_USER')\n password = os.environ.get('DATABASE_PASS')\n host = os.environ.get('DATABASE_HOST')\n conn = psycopg2.connect(f\"dbname='{dbname}' user='{user}' host='{host}' password='{password}'\")\nexcept:\n print(\"ERROR :(\")\n\ncur = conn.cursor()\n\n\nquery = \"\"\"\nCREATE TABLE resources(\n rid serial PRIMARY KEY,\n rlink VARCHAR ( 2000 ) UNIQUE NOT NULL,\n tags VARCHAR ( 1000 ) NOT NULL,\n server_id VARCHAR(1000) UNIQUE NOT NULL,\n discord_user_id VARCHAR( 1000 ) NOT NULL,\n submission_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n accepted BOOLEAN DEFAULT FALSE,\n checked BOOLEAN DEFAULT FALSE\n);\n\nCREATE TABLE server_det(\n sd_id serial PRIMARY KEY,\n server_id VARCHAR(1000) NOT NULL,\n user_id VARCHAR(1000) NOT NULL,\n cf_username VARCHAR(500) NOT NULL,\n last_updated_time TIMESTAMP NOT NULL,\n UNIQUE (server_id,user_id)\n);\n\"\"\"\n\ndel_query = \"\"\"DROP TABLE resources;\nDROP TABLE server_det;\"\"\"\n# cur.execute(del_query)\ncur.execute(query)\nconn.commit()\n\n\n" }, { "alpha_fraction": 0.5548269748687744, "alphanum_fraction": 0.5555555820465088, "avg_line_length": 34.19230651855469, "blob_id": "ccbaa1b94886853b84a81d4af6a213572d4ad789", "content_id": "e5e6201ad1e0ae7806795cfcd29951d1f88f4fa8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2745, "license_type": "no_license", "max_line_length": 155, "num_lines": 78, "path": "/db/database.py", "repo_name": "NamitS27/NZEC-Bot", "src_encoding": "UTF-8", "text": "import psycopg2\nimport datetime as dt\nimport os\n\n\nclass Database:\n def __init__(self):\n self.connected = False\n self.connection = None\n\n def connect(self):\n try:\n dbname = os.environ.get('DATABASE_NAME')\n user = os.environ.get('DATABASE_USER')\n password = os.environ.get('DATABASE_PASS')\n host = os.environ.get('DATABASE_HOST')\n conn = psycopg2.connect(f\"dbname='{dbname}' user='{user}' host='{host}' password='{password}'\")\n self.connection = conn\n self.connected = True\n except:\n raise\n\n def insert(self,query):\n try:\n with self.connection as con:\n with self.connection.cursor() as cursor:\n cursor.execute(query)\n con.commit()\n except:\n raise\n\n def insert_server_det(self,server_id,user_id,cf_username):\n NOW = dt.datetime.now()\n query = f\"INSERT INTO server_det(server_id,user_id,cf_username,last_updated_time) VALUES('{server_id}','{user_id}','{cf_username}','{NOW}')\"\n self.insert(query)\n\n def add_resource(self,server_id,user_id,tags,rlink):\n NOW = dt.datetime.now()\n query = f\"INSERT INTO resources(rlink,tags,server_id,discord_user_id,submission_time) VALUES('{rlink}','{tags}','{server_id}','{user_id}','{NOW}')\"\n self.insert(query)\n\n def fetch_all(self,table_name):\n query = f\"SELECT * from {table_name}\"\n try:\n with self.connection.cursor() as cursor:\n cursor.execute(query)\n return cursor.fetchall()\n except:\n raise\n\n def get_server_users(self,server_id):\n query = f\"SELECT * from server_det WHERE server_id='{server_id}'\"\n try:\n with self.connection.cursor() as cursor:\n cursor.execute(query)\n return cursor.fetchall()\n except:\n raise\n\n def get_user_det(self,server_id,user_id):\n query = f\"SELECT * from server_det WHERE server_id='{server_id}' and user_id='{user_id}'\"\n try:\n with self.connection.cursor() as cursor:\n cursor.execute(query)\n return cursor.fetchall()\n except:\n raise\n\n def update_username(self,server_id,user_id,username):\n NOW = dt.datetime.now()\n query = f\"UPDATE server_det SET cf_username='{username}',last_updated_time='{NOW}' WHERE server_id='{server_id}' and user_id='{user_id}'\"\n try:\n with self.connection as con:\n with self.connection.cursor() as cursor:\n cursor.execute(query)\n con.commit()\n except:\n raise\n" }, { "alpha_fraction": 0.6244856119155884, "alphanum_fraction": 0.6586934328079224, "avg_line_length": 32.230770111083984, "blob_id": "38ccad477da075f5a778ec697256b480df64ac10", "content_id": "57fe78b3bd72fc79665d007b403415eec8a7d6c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3888, "license_type": "no_license", "max_line_length": 133, "num_lines": 117, "path": "/lib/cogs/user_stalking.py", "repo_name": "NamitS27/NZEC-Bot", "src_encoding": "UTF-8", "text": "from discord.ext.commands import Cog, BucketType\nfrom discord.ext.commands import command, cooldown\nfrom discord import Embed\nfrom aiohttp import request\n\nclass UserStalking(Cog):\n\tdef __init__(self,bot):\n\t\tself.bot = bot\n\n\tdef rating_to_color(self,rating):\n\t\t\"\"\"\n\t\treturns hex value corresponding to rating\n\t\t\"\"\"\n\t\tcolors = [0xCCCCCC,0x77FF77,0x77DDBB,0xAAAAFF,0xFF88FF,0xFFCC88,0xFFBB55,0xFF7777,0xFF3333,0xAA0000]\n\n\t\tif rating == \"Unrated\" or rating<1200:\n\t\t\treturn colors[0]\n\t\telif rating >= 1200 and rating < 1400:\n\t\t\treturn colors[1]\n\t\telif rating >=1400 and rating < 1600:\n\t\t\treturn colors[2]\n\t\telif rating >=1600 and rating < 1900:\n\t\t\treturn colors[3]\n\t\telif rating >= 1900 and rating < 2100:\n\t\t\treturn colors[4]\n\t\telif rating >=2100 and rating < 2300:\n\t\t\treturn colors[5]\n\t\telif rating >=2400 and rating < 2400:\n\t\t\treturn colors[6]\n\t\telif rating >=2400 and rating < 2600:\n\t\t\treturn colors[7]\n\t\telif rating >=2600 and rating < 2300:\n\t\t\treturn colors[8]\n\t\telse:\n\t\t\treturn colors[9]\n\n\n\t@command(name=\"stalk\",aliases=[\"stk\"],brief='Gives at most 5 latest submission done by the username provided')\n\t@cooldown(1,60,BucketType.user)\n\tasync def stalk(self,ctx,username: str):\n\t\t\"\"\"\n\t\tBy the help of this command one can see the recent submissions made by the codeforces username specified and hence can stalk him :)\n\t\t\"\"\"\n\t\turl = f\"https://codeforces.com/api/user.status?handle={username}&from=1&count=5\"\n\t\tasync with request('GET',url,headers={}) as response:\n\t\t\tif response.status == 200:\n\t\t\t\t\n\t\t\t\tdata = await response.json()\n\t\t\t\tdata = data['result']\n\t\t\t\tdesc = \"\"\n\t\t\t\tfor submission in data:\n\t\t\t\t\tindex = submission[\"problem\"][\"index\"]\n\t\t\t\t\tcontest_id = submission[\"problem\"][\"contestId\"]\n\t\t\t\t\tproblem_name = submission[\"problem\"][\"name\"]\n\t\t\t\t\tflag=0\n\t\t\t\t\ttry:\n\t\t\t\t\t\trating = submission[\"problem\"][\"rating\"]\n\t\t\t\t\texcept:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tflag = 1\n\t\t\t\t\t\t\tpoints = submission[\"problem\"][\"points\"]\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\tflag = 2\n\t\t\t\t\tlink = f'https://www.codeforces.com/problemset/problem/{contest_id}/{index}'\n\t\t\t\t\tif flag==0:\n\t\t\t\t\t\tdesc += f'[{index}. {problem_name}]({link}) [{rating}]\\n\\n'\n\t\t\t\t\telif flag==1:\n\t\t\t\t\t\tdesc += f'[{index}. {problem_name}]({link}) [{int(points)}]\\n\\n'\n\t\t\t\t\telse:\n\t\t\t\t\t\tdesc += f'[{index}. {problem_name}]({link})\\n\\n'\n\t\t\t\t\n\t\t\t\tstalk_embed = Embed(title=f\"Recent Submissions of user {username}\",description=desc)\n\t\t\t\tawait ctx.send(embed=stalk_embed)\n\t\t\telse:\n\t\t\t\tdata = await response.json()\n\t\t\t\tdata = data[\"comment\"]\n\t\t\t\tawait ctx.send(f\"Error! : *{data}*\")\n\n\t@command(name=\"profile\",aliases=[\"prof\"],brief='Displays the profile of the provided username')\n\t# @cooldown(1,15,BucketType.user)\n\tasync def get_profile(self,ctx,username: str):\n\t\t\"\"\"\n\t\tThis command is helpful for viewing the basic profile of the codeforces username specified.\n\t\t\"\"\"\n\t\turl = f\"https://codeforces.com/api/user.info?handles={username}\"\n\t\tasync with request('GET',url,headers={}) as response:\n\t\t\tif response.status == 200:\n\t\t\t\tstalk_embed = Embed(title=f\"Profile of *{username}* !\")\n\t\t\t\tdata = await response.json()\n\t\t\t\tdata = data['result'][0]\n\t\t\t\ttry:\n\t\t\t\t\trating = data[\"rating\"]\n\t\t\t\texcept:\n\t\t\t\t\trating = \"Unrated\"\n\t\t\t\trank = data[\"rank\"]\n\t\t\t\tmax_rating = data[\"maxRating\"]\n\t\t\t\tavatar_url = \"https:\"+data[\"avatar\"]\n\t\t\t\tstalk_embed.colour = self.rating_to_color(rating)\n\t\t\t\tstalk_embed.add_field(name=\"Rating \",value=f\"{rating}\",inline=False)\n\t\t\t\tstalk_embed.add_field(name=\"Max Rating \",value=f\"{max_rating}\",inline=False)\n\t\t\t\tstalk_embed.add_field(name=\"Rank\",value=f\"{rank.upper()}\",inline=False)\n\t\t\t\tstalk_embed.set_thumbnail(url=avatar_url)\n\t\t\t\tawait ctx.send(embed=stalk_embed)\n\t\t\telse:\n\t\t\t\tdata = await response.json()\n\t\t\t\tdata = data[\"comment\"]\n\t\t\t\tawait ctx.send(f\"Error! : *{data}*\")\n\n\n\[email protected]()\n\tasync def on_ready(self):\n\t\tif not self.bot.ready:\n\t\t\tself.bot.cogs_ready.ready_up(\"user_stalking\")\n\n\t\ndef setup(bot):\n\tbot.add_cog(UserStalking(bot))\n" }, { "alpha_fraction": 0.5892819762229919, "alphanum_fraction": 0.5963994264602661, "avg_line_length": 39.48305130004883, "blob_id": "a469b102a6b6848475a2138405ae2a9def1be7d1", "content_id": "1e1acbaeee7753591d74c6e4a34da62e4f528324", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4777, "license_type": "no_license", "max_line_length": 176, "num_lines": 118, "path": "/lib/cogs/user_server.py", "repo_name": "NamitS27/NZEC-Bot", "src_encoding": "UTF-8", "text": "from discord.ext.commands import Cog, BucketType\nfrom discord.ext.commands import command, cooldown\nfrom discord import Embed\nfrom prettytable import PrettyTable\nfrom aiohttp import request\n\nclass UserServer(Cog):\n def __init__(self,bot):\n self.bot = bot\n\n async def check_username(self,handle):\n url=f\"https://codeforces.com/api/user.info?handles={handle}\"\n async with request('GET',url) as response:\n if response.status == 200:\n return True\n else:\n return False\n\n\n @command(name=\"setu\",brief=\"Setting the cf username with own discord user\")\n async def set_user(self,ctx,username):\n \"\"\"\n Sets the codeforces username provided by the user along with the user setting it for that server.\n \"\"\"\n username_test = await self.check_username(username)\n if not username_test:\n await ctx.send(embed=Embed(title=\"Invalid CodeForces username!\"))\n return \n\n user_id = str(ctx.author.id)\n server_id = str(ctx.message.guild.id)\n data = self.bot.db.fetch_all('server_det')\n flag=False\n for pid,sid,uid,cfu,time in data:\n if sid==server_id and user_id==uid:\n flag= True\n break\n if not flag:\n self.bot.db.insert_server_det(server_id,user_id,username)\n await ctx.send(embed=Embed(description=f\"CodeForces username has been set to `{username}` for {ctx.author.mention}\",colour=0x0037fa))\n else:\n await ctx.send(embed=Embed(description=f\"You have already set your CodeForces username\\nYou can update it using command `~updateu <new_username>`\",colour=0x0037fa))\n\n @command(name=\"updateu\",brief=\"Updating the set cf username with own discord user\")\n async def update_user(self,ctx,username):\n \"\"\"\n Updates the cf username which was set by the user with their own self.\n \"\"\"\n username_test = await self.check_username(username)\n if not username_test:\n await ctx.send(embed=Embed(title=\"Invalid CodeForces username!\"))\n return \n\n user_id = str(ctx.author.id)\n server_id = str(ctx.message.guild.id)\n data = self.bot.db.fetch_all('server_det')\n flag=False\n for pid,sid,uid,cfu,time in data:\n if sid==server_id and user_id==uid:\n flag= True\n break\n if flag:\n self.bot.db.update_username(server_id,user_id,username)\n await ctx.send(embed=Embed(description=f\"CodeForces username has been updated to `{username}` for {ctx.author.mention}\",colour=0x0037fa))\n else:\n await ctx.send(embed=Embed(description=f\"You haven't set your CodeForces username\\nYou can set it using command `~setu <cf_username>`\",colour=0x0037fa))\n\n async def get_user_rating(self,username):\n username = \";\".join(username)\n url = f\"https://codeforces.com/api/user.info?handles={username}\"\n async with request('GET',url) as response:\n if response.status == 200:\n rr = []\n data = await response.json()\n data = data[\"result\"]\n for info in data:\n rr.append((info[\"rating\"],info[\"rank\"].upper()))\n return True,rr\n else:\n data = await response.json()\n data = data[\"comment\"]\n return False,data\n\n @command(name=\"list\",brief=\"Listing of server's user list who has set their cf handle\")\n @cooldown(1,60,BucketType.guild)\n async def list_users(self,ctx):\n \"\"\"\n Displays the list of the details of the user who has set their cf username along with their own selves\n \"\"\"\n data = self.bot.db.get_server_users(str(ctx.message.guild.id))\n if len(data)==0:\n await ctx.send(embed=Embed(title=\"There are no cf usernames set to display!\"))\n return\n table = PrettyTable()\n table.field_names = [\"User\",\"CodeForces Handle\",\"Rating\",\"Rank\"]\n usernames = []\n for pid,sid,uid,cfu,time in data:\n usernames.append(cfu)\n flag,rar = await self.get_user_rating(usernames)\n if not flag:\n await ctx.send(f\"ERROR!\\n**Comment** : {rar}\")\n return\n cnt = 0\n for pid,sid,uid,cfu,time in data:\n uname = await self.bot.fetch_user(f\"{uid}\")\n table.add_row([f\"{uname.name}\",cfu,rar[cnt][0],rar[cnt][1]])\n cnt += 1\n await ctx.send(f\"```swift\\n{table}\\n```\")\n\n\n @Cog.listener()\n async def on_ready(self):\n if not self.bot.ready:\n self.bot.cogs_ready.ready_up(\"user_server\")\n\n\ndef setup(bot):\n\tbot.add_cog(UserServer(bot))\n" }, { "alpha_fraction": 0.7043010592460632, "alphanum_fraction": 0.7526881694793701, "avg_line_length": 28.421052932739258, "blob_id": "c99bfaf4526fa5f432e1bb27ea32f515e8763cd2", "content_id": "c6f2394727df04cf017e89613c3a72b207805a64", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 558, "license_type": "no_license", "max_line_length": 56, "num_lines": 19, "path": "/db/database.sql", "repo_name": "NamitS27/NZEC-Bot", "src_encoding": "UTF-8", "text": "CREATE TABLE resources(\n\trid serial PRIMARY KEY,\n\trlink VARCHAR ( 2000 ) UNIQUE NOT NULL,\n\ttags VARCHAR ( 1000 ) NOT NULL,\n\tserver_id VARCHAR(1000) UNIQUE NOT NULL,\n\tdiscord_user_id VARCHAR( 1000 ) NOT NULL,\n submission_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n\taccepted BOOLEAN DEFAULT FALSE,\n\tchecked BOOLEAN DEFAULT FALSE\n);\n\nCREATE TABLE server_det(\n\tsd_id serial PRIMARY KEY,\n\tserver_id VARCHAR(1000) NOT NULL,\n\tuser_id VARCHAR(1000) NOT NULL,\n\tcf_username VARCHAR(500) NOT NULL,\n\tlast_updated_time TIMESTAMP NOT NULL,\n\tUNIQUE (server_id,user_id)\n);" } ]
12
fractaloop/rpg-graph-experiments
https://github.com/fractaloop/rpg-graph-experiments
3f96dd178fe3134d00d7b4b3aa775bc26b8b1d24
0c9552e24d83ba0eeb4de60f4d83d2e8d113bb41
3c8878a927af889062889a7d28b24c091ddbf63e
refs/heads/master
2021-01-23T13:08:08.642501
2017-06-21T07:17:26
2017-06-21T07:17:26
93,221,343
2
2
null
null
null
null
null
[ { "alpha_fraction": 0.6780014038085938, "alphanum_fraction": 0.6884108185768127, "avg_line_length": 18.213333129882812, "blob_id": "f6ed7b3f3c0fe1c57a9a65c074cd5caffad4953a", "content_id": "fc8d8f681838e251df7050e64ba458e14ff2aea7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1443, "license_type": "permissive", "max_line_length": 156, "num_lines": 75, "path": "/README.md", "repo_name": "fractaloop/rpg-graph-experiments", "src_encoding": "UTF-8", "text": "# RolePlayGateway Graphing Experiments\n\nThese are some basic tests for graphing data from [RolePlayGateway.com](https://www.roleplaygateway.com)\n\n## Start\n\n $ npm install\n $ npm start\n\n## Endpoints\n\nAll data for this project is derived from public JSON endpoints. The API is completely ephemeral during this period. Pay\nattention to file modification times. Old files are more likely to be broken.\n\n### Places\n\nPlaces are locations within a Roleplay.\n\n[`https://www.roleplaygateway.com/roleplay/the-multiverse/places?format=json`](https://www.roleplaygateway.com/roleplay/the-multiverse/places\\?format\\=json)\n\nReturns an array of `Place` objects.\n\n```json\n[\n {\n \"id\": \"1\",\n \"name\": \"Mjötviðr; The Realms\",\n \"roleplay_id\": \"1\",\n \"owner\": \"4\",\n \"url\": \"the-realms\"\n }\n]\n```\n\n### Exits\n\nExits connect locations within a Roleplay.\n\n[`https://www.roleplaygateway.com/roleplay/the-multiverse/exits?format=json`](ttps://www.roleplaygateway.com/roleplay/the-multiverse/exits?format=json)\n\n```json\n[\n {\n \"place_id\": \"49222\",\n \"destination_id\": \"16861\",\n \"direction\": \"east\",\n \"mode\": \"normal\"\n }\n]\n```\n\nThere are 4 cardinal directions:\n- `north`\n- `south`\n- `east`\n- `west`\n\nAs well as 2 vertical directions:\n- `up`\n- `down`\n\nPlaces can be contained within another:\n- `in`\n- `out`\n\nAnd a parent-child relationship can be expressed:\n- `ascend`\n- `descend`\n\n## Local testing\n\n```bash\nnpm install\nbeefy index.js\n```\n" }, { "alpha_fraction": 0.5961123108863831, "alphanum_fraction": 0.5982721447944641, "avg_line_length": 24.740739822387695, "blob_id": "1abde90d0f230a155817e0229528c69dcffff749", "content_id": "833bdb29953ed705c462ccc4978cc715ec0fc591", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1389, "license_type": "permissive", "max_line_length": 103, "num_lines": 54, "path": "/map.py", "repo_name": "fractaloop/rpg-graph-experiments", "src_encoding": "UTF-8", "text": "import json\n\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\nG = nx.DiGraph()\n\n\nclass Place(object):\n def __init__(self, id, name, owner, url, roleplay_id):\n self.id = id\n self.name = name\n self.owner = owner\n self.url = url\n self.roleplay_id = roleplay_id\n\n\nclass Exit(object):\n def __init__(self, place_id, destination_id, direction, mode):\n self.place_id = place_id\n self.destination_id = destination_id\n self.direction = direction\n self.mode = mode\n\n\ndef load_places():\n with open(\"places.json\") as places_file:\n def json2place(j):\n return Place(int(j[\"id\"]), j[\"name\"], int(j[\"owner\"]), j[\"url\"], int(j[\"roleplay_id\"]))\n return map(json2place, json.load(places_file))\n\n\ndef load_exits():\n with open(\"exits.json\") as exits_file:\n def json2exit(j):\n return Exit(int(j[\"place_id\"]), int(j[\"destination_id\"]), j[\"direction\"], j[\"mode\"])\n return json.load(exits_file)\n\n\nplaces = load_places()\nfor place in places:\n G.add_node(\n place.id,\n {\"name\": place.name, \"owner\": place.owner, \"url\": place.url, \"roleplay_id\": place.roleplay_id})\n\nexits = load_exits()\nfor exit in exits:\n G.add_edge(\n exit.place_id,\n exit.destination_id,\n {\"direction\": exit.direction, \"mode\": exit.mode})\n\nnx.draw(G)\nnx.write_dot(G,'file.dot')" }, { "alpha_fraction": 0.6032735705375671, "alphanum_fraction": 0.6114575266838074, "avg_line_length": 25.183673858642578, "blob_id": "b5a4622895e61f5259de92bf2b123af0c0265441", "content_id": "a7381bfe0af26d28da4de9f8e541ab3fccefe26a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2566, "license_type": "permissive", "max_line_length": 150, "num_lines": 98, "path": "/index.js", "repo_name": "fractaloop/rpg-graph-experiments", "src_encoding": "UTF-8", "text": "// let's create a simple graph:\nvar nggraph = require('ngraph.graph');\nvar ngpixel = require('ngraph.pixel');\n\nvar idForPlace = function(place) {\n return place.name + \" (\" + place.id + \")\";\n}\n\n// Function generators for chained Promises\nvar addPlacesToGraph = function(graph) {\n return function(places) {\n for (const place of places) {\n graph.addNode(idForPlace(place));\n }\n console.log(\"Added \" + places.length + \" places\")\n return places;\n }\n}\n\nvar addExitsToGraph = function(places, graph) {\n return function(exits) {\n for (const exit of exits) {\n var src = places[exit.place_id];\n var dest = places[exit.destination_id];\n // Lots of missing (hidden) places... Too noisy\n if (!src && !dest) {\n // console.log(\"Error: No places found for link between: \" + exit.place_id + \" \" + exit.direction + \" of \" + exit.destination_id);\n } else if (!src) {\n // console.log(\"Error: No place found for source of link: \" + exit.place_id + \" \" + exit.direction + \" of \" + JSON.stringify(dest));\n } else if (!dest) {\n // console.log(\"Error: No place found for destination of link: \" + JSON.stringify(src) + \" \" + exit.direction + \" of \" + exit.destination_id);\n } else {\n graph.addLink(idForPlace(src), idForPlace(dest));\n }\n }\n console.log(\"Added \" + exits.length + \" exits\")\n return exits;\n }\n}\n\nvar handleException = function(e) {\n console.log(\"Failed to load data!\", e);\n return e;\n};\n\n// Main rendering\nvar rendererForGraph = function(graph) {\n return function(results) {\n // TODO: Graph stats about results?\n var renderer = ngpixel(graph, {\n link: renderLink,\n node: renderNode\n });\n renderer.on('nodehover', function(node) {\n if (node) {\n console.log(JSON.stringify(node));\n }\n });\n return renderer;\n }\n}\n\n// Rendering style\nfunction renderNode(node) {\n return {\n color: Math.random() * 0xFFFFFF | 0,\n size: Math.random() * 21 + 10,\n };\n}\n\nfunction renderLink(link) {\n return {\n fromColor: 0xFF0000,\n toColor: 0x00FF00\n };\n}\n\nfunction createNodeUI(node) {\n return {\n color: 0xFF00FF,\n size: 20\n };\n}\n\n// Entry point\n(function() {\n var g = nggraph()\n console.log(\"Loading places and exits...\")\n\n var places = fetch(\"places.json\").catch(handleException)\n .then(blob => blob.json())\n .then(addPlacesToGraph(g))\n .then(places => fetch(\"exits.json\")\n .then(blob => blob.json())\n .then(addExitsToGraph(places, g)))\n .then(rendererForGraph(g))\n .catch(handleException);\n})();\n" } ]
3
nerdijoe/Phish-Lens
https://github.com/nerdijoe/Phish-Lens
dd7722af0116d4e1a72cdbcbe7db19095313aad9
1a757893ae6d7cc8f2dfb78ccf05d820c2a238a4
bf1ecc6ab6c07ff539979f1b171cb5047e0f5f6e
refs/heads/master
2021-08-28T15:05:31.544886
2017-12-12T14:45:04
2017-12-12T14:45:04
124,609,236
1
0
null
2018-03-10T00:57:11
2017-12-16T19:50:02
2017-12-12T14:45:04
null
[ { "alpha_fraction": 0.39558759331703186, "alphanum_fraction": 0.3997378647327423, "avg_line_length": 27.97468376159668, "blob_id": "709e33c299d7262717b00f3958a573921ab499f9", "content_id": "2db7bfa11bd57745571df6cc93c5785c2996a919", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4578, "license_type": "no_license", "max_line_length": 103, "num_lines": 158, "path": "/phishing-backend/routes/login.js", "repo_name": "nerdijoe/Phish-Lens", "src_encoding": "UTF-8", "text": "var express = require('express');\nvar router = express.Router();\nvar mysql=require(\"./mysql\");\nvar ejs = require(\"ejs\");\n\n\nfunction login(req,res)\n{\n ejs.renderFile('./views/index.ejs',function(err,result){\n // if it is success\n if(!err)\n {\n res.end(result);\n }\n //ERROR\n else\n {\n res.end(\"ERROR OCCURED \");\n console.log(err);\n }\n });\n}\n\nfunction postlogin(req,res){\n var username= req.body.username;\n var password= req.body.password;\n\n var getuser=\"select * from admin where email ='\"+username+\"' AND password='\"+password+\"'\";\n mysql.fetchData(function (err,result) {\n if(err)\n {\n res.end(\"ERROR OCCURED \");\n console.log(err);\n }\n else {\n console.log(\"---------------get user query succesful -----\");\n if (result.length == 1) {\n console.log(\"---------------user found -----\");\n\n var getlogs = \"select * from logs where isPhished =1\";\n var logs = [];\n mysql.fetchData(function (err, result) {\n if (result.length > 0) {\n\n console.log(\"---------------posts found -----\");\n for (var i = 0; i < result.length; i++) {\n var log = {\n clientId: result[i].clientId,\n website: result[i].website,\n isPhished: result[i].isPhished,\n isReportedPhish: result[i].isReportedPhish,\n date: result[i].date\n\n }\n console.log(\"---------------logs found -----\");\n logs.push(log);\n }\n\n }\n console.log(\"---------------posts query dones -----\");\n ejs.renderFile('./views/login.ejs', {logs: logs}, function (err, result) {\n // if it is success\n if (!err) {\n res.end(result);\n }\n //ERROR\n else {\n res.end(\"ERROR OCCURED \");\n console.log(err);\n }\n });\n }, getlogs)\n }\n else {\n res.end(\"No user Found!!\")\n }\n }\n\n },getuser);\n}\n\n\n\n\nexports.login=login;\nexports.postlogin = postlogin;\nexports.login = function(req,res) {\n var reqUsername = req.body.username;\n var reqPassword = req.body.password;\n\n\n var getUser = \"SELECT * FROM admin WHERE email = '[email protected]' and password = 'admin'\";\n console.log(\"query is :\" + getUser);\n\n connection.query(getUser, function (err, rows, fields) {\n\n if (err) {\n throw err;\n }\n else {\n console.log('Valid Login');\n var getLogs = \"SELECT * FROM logs WHERE isPhished=1\";\n console.log(\"query is :\" + getLogs);\n\n connection.query(getLogs, function (err, rows, fields) {\n if (err) {\n throw err;\n }\n else {\n console.log('Success');\n\n }\n\n }, getLogs);\n }\n\n }, getUser);\n\n\n}\nmodule.exports = router;\n\n\n/*exports.login = function(req,res){\n var email= req.body.email;\n var password = req.body.password;\n connection.query('SELECT * FROM admin WHERE email = ?',[email], function (error, results, fields) {\n if (error) {\n // console.log(\"error ocurred\",error);\n res.send({\n \"code\":400,\n \"failed\":\"error ocurred\"\n })\n }else{\n // console.log('The solution is: ', results);\n if(results.length >0){\n if([0].password == password){\n res.send({\n \"code\":200,\n \"success\":\"login sucessfull\"\n });\n }\n else{\n res.send({\n \"code\":204,\n \"success\":\"Email and password does not match\"\n });\n }\n }\n else{\n res.send({\n \"code\":204,\n \"success\":\"Email does not exits\"\n });\n }\n }\n });\n}*/\n" }, { "alpha_fraction": 0.5660653114318848, "alphanum_fraction": 0.5870307087898254, "avg_line_length": 23.41666603088379, "blob_id": "fc0874b9345842669114473b7e38fb99dfb2969a", "content_id": "fb8a3e1970876ab75dda5ef187ed7f6dd6d27075", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2051, "license_type": "no_license", "max_line_length": 110, "num_lines": 84, "path": "/phishing-backend/routes/index.js", "repo_name": "nerdijoe/Phish-Lens", "src_encoding": "UTF-8", "text": "var express = require('express');\nvar router = express.Router();\nvar request = require('request');\nvar app=express();\nvar mysql=require(\"./mysql\");\n\n\n/*\nvar mysql = require('mysql')\nvar connection = mysql.createConnection({\n host : 'localhost',\n user : 'root',\n password : 'root',\n database : 'phishing'\n});\n\nconnection.connect(function(error){\n if(!!error){\n console.log(\"error\");\n }else{\n console.log(\"connected\");\n }\n }\n);\n*/\n\n/*app.get('/',function (req,resp) {\n connection.query(\"select *from admin\", function (error, rows, fields) {\n if (!!error) {\n console.log(\"error in query\");\n } else {\n console.log(\"success\\n\");\n console.log(rows);\n }\n\n })\n});*/\n\n/* GET home page. */\nrouter.get('/', function(req, res, next) {\n res.render('index', { title: 'Express' });\n});\n\n\nrouter.get('/api/check', function(req, res, next) {\n console.log(req.query.id);\n console.log(req.query.url);\n var postData = {\n url: req.query.url\n }\n var options = {\n method: 'post',\n body: postData,\n json: true,\n url: \"http://54.202.123.8/check\"\n }\n request.post(options, function(err,response,body){\n if(err) {\n return res.status(200).json({'status': 500, 'message' : 'some error occoured, please try again later'});\n } else {\n if(body.result) {\n return res.status(200).json({'status': 200, 'message' : 'phishing_detected'});\n } else {\n return res.status(200).json({'status': 200, 'message' : 'website safe'});\n }\n }\n });\n})\n\n\nrouter.post('/api/report', function(req, res, next) {\n console.log(req.body);\n var insert=\"insert into reports (url) values ('\"+req.body.data+\"');\";\n mysql.fetchData(function(err, result) {\n if(err) {\n return res.status(200).json({'status': 500, 'message' : 'some error occoured, please try again later'});\n } else {\n return res.status(200).json({'status': 200, 'message' : 'Thanks for your feedback'});\n }\n },insert);\n})\n\n//app.listen(3001);\nmodule.exports = router;\n" }, { "alpha_fraction": 0.7667310833930969, "alphanum_fraction": 0.795889675617218, "avg_line_length": 71.97435760498047, "blob_id": "3d3b352daff8de56727a69e56646c0389051a69f", "content_id": "a660969b35d0139c64451e8bb4fb648d28287d97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5695, "license_type": "no_license", "max_line_length": 502, "num_lines": 78, "path": "/README.md", "repo_name": "nerdijoe/Phish-Lens", "src_encoding": "UTF-8", "text": "\n<h1> Phish Lens </h1> \nA machine learning enabled chrome extension to smartly identify possible phished pages.\n\nGet the chrome extesnion <a href =\"https://chrome.google.com/webstore/detail/phish-lens/omcddbobcimeodadbojljnnodfmmkhme\">here</a>. \n\n<a href =\"https://chrome.google.com/webstore/detail/phish-lens/omcddbobcimeodadbojljnnodfmmkhme\"> <img src=\"https://lh4.googleusercontent.com/6dccMMMP6I0nyS3G4i3nkOidQHaOVTV16yD0mcKy-xZ--bD-uFmp6UXZswXzBg7ZEHPzKBrVnF383n5qpQzA=w1275-h703\"> </a>\n\n<h1> What is Phishing? </h1>\n\nPhishing is a process to steal user's sensitive information over the internet by tricking a user to enter his information on a disguised or a fake site which is a replica of the authentic site. Leading web portals get trapped because of phishing attacks each day. Thousands of passwords are stolen without either the users or the portals knowing about it, sometimes users also lose money from their bank accounts. Companies end up paying a lot of money in the courts to deal with such attacks.\n\n<h1> Why is phishing dangerous?</h1>\nThere are numerous threats that phishing brings in. Primary threat from phishing is theft of identity of the users. \nUsers emphasise on data security and privacy, they go to great lenghts to protect thier information from the attackers. A single breach can expose the user to multitude of threats, which include credit card fraud, credit score damage, and sometimes precious digital assets. There are also intangible threats, such as damage to credibility, loss of trust,\nor embarrassment; having personal information stolen can cost a great deal more than lost cash.\n\n<h1> Why a chrome extesnsion? </h1> \nWe identify that Google Chrome browser is a popular web browser and a Chrome extension is an easier way for users to use our product and services. For this reason, we built a chrome extension with machine learning capability to detect phishing sites and notify the user in real time.\n\n<h1> Design </h1> \n\nThe architecure diagram is as shown below \n\n<img src=\"https://lh4.googleusercontent.com/lbjQCEB4lDIuq_My4AT4FhfAorPfZ0jtPRoulQaq2zG_-iqKk9skXZoTIgpq6LTX75RzKw0vx6VpR-aLwHVy=w1275-h703\">\n\n<h1> Implementation </h1>\n\nChrome Extension is the client that is interfacing with the user on the Google Chrome browser. Every time user enters a\nnew URL on the address bar, PhishLens will make an API call to the backend server. Backend server will send back a response to PhisLens. Correspondingly, PhishLens will notify a user if the URL is a phishing site. Backend server receives a request from PhishLens Chrome extension to check whether the URL is pointing to a genuine site. Then, backend server will make an API call to the Machine Learning server to check the validity of the URL. Machine Learning server uses a decision tree classifier to\npredict whether a URL is a phishing site or not. The dataset that is used to train this classifier was prepared from the list of URLs (Phishing URLs and legitimate URLs). We converted each of the URLs to a set of parameters that corresponds to the URL rules output. Prior to running through these rules, we will also check with PhishTank API whether the URL is\nalready reported as a phishing site in their database or not. If it is not in the PhishTank database, URL will be converted into parameters and then fed into decision tree classifier.\n\n<h1> Machine Learning rules </h1>\n\n<img src=\"https://lh6.googleusercontent.com/VsrlRTJzQnZpCyxTiW1GS4zt3R-9bo2Kw2or85liHFwVCUGlutDCu6qE6qHFxKJDywykJf5cIGkkFtbHuTvA=w1275-h703\">\n\n<img src=\"https://lh6.googleusercontent.com/3Ox6RSHPbQARt3t8TS2v4aEDENw5UgZv0x_nrwUDl4KrFTcOL0ZIORhex7ihAmvdQ-pjaMeVTtUfmjOP4F_9=w1275-h703\">\n\n<img src=\"https://lh3.googleusercontent.com/I_CZrgxKJzCePE7li9EpuLhRY0wWhulEOtADq1vGT-cjRAXj29J3QbvuUUdL_33jDtm0_y2RaRb0fKJ03oJf=w1275-h703\">\n\nFor example:\nhttps://account-security-system.cf/recovery-chekpoint-login.html\n\nIf we ran through the above site to the Machine Learning Rules, the resultant parameters will look something like below:\n[ -1,0,-1,-1,-1,1,-1,-1,1,-1,1 ]\nThese parameters are then fed to the decision tree. The decision tree internally compares these parameters with the existing set of datasets and returns a boolean valueof True if URL is a phishing site and False otherwise.\n\n\n<h1> Conclusion and future work </h1>\n\nIn this project, we have built a Chrome Extension that has successfully detected phishing URLs. Our implementation is not 100% accurate, however, we can increase detection accuracy by doing the following:\n1. Train the Machine Learning classifier with larger dataset so that it can improve the prediction accuracy of detecting\nphishing sites.\n2. Implement additional machine learning rules to differentiate a common pattern shared among phish site and non-phish site.\n\n<h1> Acknowledgement </h1>\n\nWe would like to thank Professor Rakesh Ranjan, Dept. of Computer Software Engineering, San Jose State University, for immense motivation and guidance throughout the project.\n\n<h1> Special Credits </h1>\n\n* Lichman, M. (2013). UCI Machine Learning Repository http://archive.ics.uci.edu/ml. Irvine, CA: University of California, School of Information and Computer Science.\n\n* Nicolas Papernot (2016) Detecting phishing websites using a decision tree https://github.com/npapernot/phishing-detection\n\n* Sheng S, Magnien B, Kumaraguru P, Acquisti A, Cranor LF, Hong J, Nunge E (2007) Anti-phishing phil: the design and evaluation of a game that teaches people not to fall for phish. In: Proceedings of the SOUPS, Pittsburg, pp 88–99\n\n* Sara Radicati, PhD; Principal Analyst: Justin Levenstein. Statistics Report 2013-2017.The Radicati Group, Inc. A Technology Market Research Firm.\n\n<h1> Contributors </h1>\n\n* Rudy Wahjudi\n\n* Sai Supraja Malla\n\n* Kajal Agarwal \n\n* Prateek Sharma\n" }, { "alpha_fraction": 0.606134831905365, "alphanum_fraction": 0.6241945624351501, "avg_line_length": 29.952247619628906, "blob_id": "810abb865ddd31aaacdc14a780b8cf3e400a0253", "content_id": "c3815c2a231441ac9e5bce70893af68e9bc686a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11019, "license_type": "no_license", "max_line_length": 197, "num_lines": 356, "path": "/server_flask/main.py", "repo_name": "nerdijoe/Phish-Lens", "src_encoding": "UTF-8", "text": "# import sys\nimport os\nimport shutil\nimport time\nimport traceback\nimport urllib\n\nfrom flask import Flask, request, jsonify\nimport pandas as pd\n# from sklearn.externals import joblib\n\n# -----------------------------------------------------------\nfrom sklearn import tree\nfrom sklearn.metrics import accuracy_score\nfrom urlparse import urlparse\nfrom pyfav import get_favicon_url\nimport numpy as np\nimport json\nimport re\nimport requests\n\nfrom rules import rule111_ip, rule112_length, rule113_tinyurl, rule114_atsymbol, rule115_doubleslash, rule116_prefix, rule117_subdomain, rule1110_favicon, rule1111_non_standard_port, rule1112_https\n\n\ndef load_data():\n \"\"\"\n This helper function loads the dataset saved in the CSV file\n and returns 4 numpy arrays containing the training set inputs\n and labels, and the testing set inputs and labels.\n \"\"\"\n\n # Load the training data from the CSV file\n training_data = np.genfromtxt('data/dataset.csv', delimiter=',', dtype=np.int32)\n\n \"\"\"\n Each row of the CSV file contains the features collected on a website\n as well as whether that website was used for phishing or not.\n We now separate the inputs (features collected on each website)\n from the output labels (whether the website is used for phishing).\n \"\"\"\n\n # Extract the inputs from the training data array (all columns but the last one)\n inputs = training_data[:,:-1]\n print \"**** inputs ****\"\n print inputs\n print len(inputs)\n\n # Extract the outputs from the training data array (last column)\n outputs = training_data[:, -1]\n print \"**** outputs ****\"\n print outputs\n print len(outputs)\n\n # Separate the training (first 2,000 websites) and testing data (last 456)\n training_inputs = inputs[:2000]\n training_outputs = outputs[:2000]\n testing_inputs = inputs[2000:]\n testing_outputs = outputs[2000:]\n\n # Return the four arrays\n return training_inputs, training_outputs, testing_inputs, testing_outputs\n\ndef load_custom_data():\n \"\"\"\n This helper function loads the dataset saved in the CSV file\n and returns 4 numpy arrays containing the training set inputs\n and labels, and the testing set inputs and labels.\n \"\"\"\n\n # Load the training data from the CSV file\n training_data = np.genfromtxt('data/custom_dataset.csv', delimiter=',', dtype=np.int32)\n\n \"\"\"\n Each row of the CSV file contains the features collected on a website\n as well as whether that website was used for phishing or not.\n We now separate the inputs (features collected on each website)\n from the output labels (whether the website is used for phishing).\n \"\"\"\n\n # Extract the inputs from the training data array (all columns but the last one)\n inputs = training_data[:,:-1]\n print \"**** inputs ****\"\n print inputs\n print len(inputs)\n\n # Extract the outputs from the training data array (last column)\n outputs = training_data[:, -1]\n print \"**** outputs ****\"\n print outputs\n print len(outputs)\n\n # Separate the training (first 2,000 websites) and testing data (last 456)\n custom_training_inputs = inputs[:900]\n custom_training_outputs = outputs[:900]\n custom_testing_inputs = inputs[900:]\n custom_testing_outputs = outputs[900:]\n\n # Return the four arrays\n return custom_training_inputs, custom_training_outputs, custom_testing_inputs, custom_testing_outputs\n\n\ndef check_phishtank(url):\n myjson = {\n \"url\": url,\n \"format\": \"json\",\n \"app_key\": \"71eb7c67c1f4f2088cf27e3d75216f49edccffc5712c6bde5a4a3fee5e6055f8\"\n }\n print \"--------------myjson\"\n print myjson\n\n url = 'http://checkurl.phishtank.com/checkurl/'\n headers = {\"content-type\":\"application/x-www-form-urlencoded\"}\n res = requests.post(url, headers=headers, data=myjson)\n print 'response from server:',res.text\n\n resjson = res.json()\n print resjson\n print \"-----\"\n print resjson['results']\n\n in_database = False\n if 'in_database' in resjson['results']:\n in_database = resjson['results']['in_database']\n\n valid = False\n if 'valid' in resjson['results']:\n valid = resjson['results']['valid']\n\n verified = False\n if 'verified' in resjson['results']:\n verified = resjson['results']['verified']\n\n print \"-----resjson['results']['in_database']\"\n print in_database\n print \"-----resjson['results']['valid']\"\n print valid\n\n # finalVerdict = (in_database and valid)\n # print 'finalVerdict ='\n # print finalVerdict\n\n # return jsonify({ 'isExisted': finalVerdict })\n return { 'in_database': in_database, 'valid': valid, 'verified': verified }\n\n\ndef strip_url(url):\n old = urlparse(url)\n domain = old.hostname\n splitted = domain.rsplit('.')\n if(len(splitted) == 3):\n domain = splitted[1] + '.' + splitted[2]\n return domain\n\n\n\n# -----------------------------------------------------------\n\napp = Flask(__name__)\n\n# train_inputs, train_outputs, test_inputs, test_outputs = ''\ntrain_inputs = ''\ntrain_outputs = ''\ntest_inputs = ''\ntest_outputs = ''\n\ncustom_train_inputs = ''\ncustom_train_outputs = ''\ncustom_test_inputs = ''\ncustom_test_outputs = ''\n\ntopsites = ''\n\[email protected]('/')\ndef home():\n return \"The server is up\"\n\[email protected]('/test', methods=['POST'])\ndef test():\n myjson = {\n \"url\": \"https://www.facebook.com\",\n \"format\": \"json\",\n \"app_key\": \"71eb7c67c1f4f2088cf27e3d75216f49edccffc5712c6bde5a4a3fee5e6055f8\"\n }\n print \"--------------myjson\"\n print myjson\n\n print \"--------------request\"\n print request.json\n\n url = 'http://checkurl.phishtank.com/checkurl/'\n headers = {\"content-type\":\"application/x-www-form-urlencoded\"}\n res = requests.post(url, headers=headers, data=request.json)\n print 'response from server:',res.text\n\n resjson = res.json()\n print resjson\n print \"-----\"\n print resjson['results']\n\n in_database = False\n if 'in_database' in resjson['results']:\n in_database = resjson['results']['in_database']\n\n valid = False\n if 'valid' in resjson['results']:\n valid = resjson['results']['valid']\n\n print \"-----resjson['results']['in_database']\"\n print in_database\n print \"-----resjson['results']['valid']\"\n print valid\n\n finalVerdict = (in_database and valid)\n print 'finalVerdict ='\n print finalVerdict\n return jsonify({ 'isExisted': finalVerdict })\n # return finalVerdict\n\n\n\[email protected]('/check', methods=['POST'])\ndef check():\n print \"Tutorial: Training a decision tree to detect phishing websites\"\n\n json_ = request.json\n print \"^^^^^^^^^^^^^^^^^ json_ \"\n print json_\n\n\n stripped_url = strip_url(json_['url'])\n res = topsites.loc[topsites['url'] == stripped_url]\n print stripped_url\n if len(res):\n print 'horay'\n else:\n print 'boo'\n\n\n phistank = ''\n\n # Check if url domain is on top sites url\n if len(res):\n return jsonify({'result': False})\n else:\n # if not check with phistank\n phistank = check_phishtank(json_['url'])\n\n print \" ----------- phistank\"\n print phistank\n\n # check if phisthank has it in their database\n if phistank['in_database']==True and phistank['valid']==True:\n return jsonify({'result': True})\n elif phistank['in_database']==False and phistank['valid']==False:\n # phisthank does not have it, we run it through Machine Learning\n # # Load the training data\n # train_inputs, train_outputs, test_inputs, test_outputs = load_data()\n # print \"Training data loaded.\"\n\n # Create a decision tree classifier model using scikit-learn\n # classifier = tree.DecisionTreeClassifier()\n custom_classifier = tree.DecisionTreeClassifier()\n\n print \"Decision tree classifier created.\"\n\n print \"Beginning model training.\"\n # Train the decision tree classifier\n # classifier.fit(train_inputs, train_outputs)\n custom_classifier.fit(custom_train_inputs, custom_train_outputs)\n\n print \"Model training completed.\"\n\n\n attribute = []\n print '###################'\n # url = 'http://88.204.202.98/2/paypal.ca/index.html'\n # url = 'http://0x58.0xCC.0xCA.0x62/2/paypal.ca/index.html'\n # attribute.append(rule01_ip(json_['url']))\n # attribute.append(rule02_length(json_['url']))\n # attribute.append(rule10_favicon(json_['url']))\n # attribute.append(rule11_non_standard_port(json_['url']))\n # attribute.append(rule12_favicon(json_['url']))\n\n url = json_['url']\n attribute.append(rule111_ip(url))\n attribute.append(rule112_length(url))\n attribute.append(rule113_tinyurl(url))\n attribute.append(rule114_atsymbol(url))\n attribute.append(rule115_doubleslash(url))\n attribute.append(rule116_prefix(url))\n attribute.append(rule117_subdomain(url))\n\n # attribute.append(rule1110_favicon(url))\n attribute.append(-1)\n\n attribute.append(rule1111_non_standard_port(url))\n attribute.append(rule1112_https(url))\n\n print 'attribute='\n print attribute\n print '###################'\n\n\n # Use the trained classifier to make predictions on the test data\n # rudy_inputs = [-1,1,1,1,-1,-1,-1,-1,-1,1,1,-1,1,-1,1,-1,-1,-1,0,1,1,1,1,-1,-1,-1,-1,1,1,-1]\n # predictions = classifier.predict([json_['input']])\n predictions = custom_classifier.predict([attribute])\n print \"------ test_inputs ------\"\n # print test_inputs\n # print len(test_inputs)\n print \"Predictions on testing data computed.\"\n print predictions\n print \"----------------- -------\"\n # print len(predictions)\n\n # Print the accuracy (percentage of phishing websites correctly predicted)\n\n rudy_outputs = [-1]\n print \"test_outputs\"\n print len(test_outputs)\n # accuracy = 100.0 * accuracy_score(test_outputs, predictions)\n # accuracy = 100.0 * accuracy_score(rudy_outputs, predictions)\n # print \"The accuracy of your decision tree on testing data is: \" + str(accuracy)\n # return jsonify({'message': \"The accuracy of your decision tree on testing data is: \" + str(accuracy)})\n\n\n if predictions[0] == 1:\n return jsonify({'result': True})\n else:\n return jsonify({'result': False})\n else:\n return jsonify({'result': False})\n\nif __name__ == '__main__':\n try:\n port = int(sys.argv[1])\n except Exception, e:\n port = 80\n\n try:\n # Load the training data\n train_inputs, train_outputs, test_inputs, test_outputs = load_data()\n print \"Training data loaded.\"\n\n custom_train_inputs, custom_train_outputs, custom_test_inputs, custom_test_outputs = load_custom_data()\n print \"Custom training data loaded.\"\n\n topsites = pd.read_table('data/top-sites.csv', sep=',', header=None, names=[\"index\", \"url\"])\n print \"Loaded top sites\"\n\n except Exception, e:\n print 'No model here'\n print 'Train first'\n\n\n app.run(host='0.0.0.0', port=port, debug=True)\n" } ]
4
kalebhill/Lead_Search
https://github.com/kalebhill/Lead_Search
79c2561d2330871db9ac7e15dafd428ed0158ab1
ab4668f4ed39087d9ecba67727a75599704f0b13
7eccaa20759183cbf1cdad2058159040e0b6b36f
refs/heads/master
2021-08-30T17:54:44.467915
2017-12-18T22:28:14
2017-12-18T22:28:14
114,683,295
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6011315584182739, "alphanum_fraction": 0.6071428656578064, "avg_line_length": 37.73972702026367, "blob_id": "73d7a9e4fb9e8a6b049d102928233f8d508420d8", "content_id": "b8189d7458540a1e47b75453ad312ff016870857", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2828, "license_type": "no_license", "max_line_length": 97, "num_lines": 73, "path": "/employee_tech.py", "repo_name": "kalebhill/Lead_Search", "src_encoding": "UTF-8", "text": "import re\nimport operator\nimport csv\n\nemployee_scores = {}\nemployee_profile = {}\nmatches = {}\n\n# compatible_list = ['microsoft sharepoint', 'adobe acrobat', 'adobe creative suite',\n# 'imanage', 'microsoft office', 'citrix', 'dropbox', 'microsoft exchange',\n# 'microsoft office 365', 'microsoft onenote', 'microsoft windows onedrive (formerly skydrive)',\n# 'windows sharepoint services', 'microsoft active directory', 'google drive',\n# 'docusign electronic signature solution', 'microsoft windows 7', 'citrix xenmobile (zenprize)',\n# 'microsoft os', 'microsoft sharepoint server', 'microsoft windows 8', 'microsoft azure',\n# 'microsoft windows servers']\n\nacrobat = 'adobe acrobat'\n\ni_file = \"sf_test.csv\"\n\n# o_file = i_file[:-4] + \".txt\"\n\n# target = open(o_file, 'w')\n\nwith open(i_file) as csvfile:\n reader = csv.DictReader(csvfile, delimiter=',')\n\n for employee in reader:\n # create a blank list for technologies to be placed in\n tech_list2 = []\n\n # how would you use employee id as a unique identifier?\n # define the company parameters to search\n employee_name = employee['Employee Full Name']\n employee_tech = employee['Employee Technologies (excludes HG Data technologies)']\n employee_title = employee['Employee Title']\n employee_seniority_level = employee['Employee Seniority Level']\n reports_to = employee['Employee Reports To']\n email = employee['Employee Email Address']\n phone_number = employee['Employee Direct Phone']\n\n # create the dictionary\n employee_scores[employee_name] = {}\n employee_scores[employee_name][\"Title\"] = employee_title\n employee_scores[employee_name][\"Seniority\"] = employee_seniority_level\n employee_scores[employee_name][\"Reports To\"] = reports_to\n employee_scores[employee_name][\"Email Address\"] = email\n employee_scores[employee_name][\"Phone Number\"] = phone_number\n matches[employee_name] = []\n\n tech_list = employee_tech.split(';')\n for tech in tech_list:\n tech = tech.split(',')\n for program in tech:\n if \":\" in program:\n program = program.split(':')\n tech_list2.append(program[1].strip().lower())\n else:\n tech_list2.append(program.strip().lower())\n\n employee_scores[employee_name][\"Tech\"] = tech_list2\n\nfor entry in employee_scores.items():\n if acrobat in entry[1]['Tech']:\n print(f\"\"\"=============================================================\n{entry[0]}, {entry[1][\"Title\"]}\n - Reports to: {entry[1][\"Reports To\"]}\n - Phone Number: {entry[1][\"Phone Number\"]}\n - Email Address: {entry[1][\"Email Address\"]}\n=============================================================\n\n \"\"\")\n# target.close()\n" }, { "alpha_fraction": 0.5630407929420471, "alphanum_fraction": 0.5741656422615051, "avg_line_length": 34.56044006347656, "blob_id": "085dac996434dbcfcccfddbd2fc5d37d43ee3aa6", "content_id": "14baef629fcdc9ed453f8c2d65acb6096ce22706", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3236, "license_type": "no_license", "max_line_length": 129, "num_lines": 91, "path": "/employee_search.py", "repo_name": "kalebhill/Lead_Search", "src_encoding": "UTF-8", "text": "import re\nimport sys\nimport operator\nimport csv\nfrom os.path import exists\n\nemployee_profiles = {}\nmatches = {}\n\n# text to search for\nsoftware = 'adobe acrobat'\n\n<<<<<<< HEAD\ndef get_file():\n f = input(\"\"\"Enter the .csv you would like to parse (press CTRL-C to exit)\n***This will only work with .csv pulled from DiscoverOrg\n - otherwise you'll have to dig into the code and change the fields ;)***\n=======\n# ask user for the input file\ni_file = input(\"\"\"Enter the .csv you would like to parse (press CTRL-C to exit)\n***This will only work with .csv pulled from DiscoverOrg - otherwise you'll have to dig into the code and change the fields ;)***\n>>>>>>> 4b7ae6a520c67ce78f0f447cd8184059b234bfb7\n> \"\"\")\n return f\n\n# ask user for the input file\ni_file = get_file()\n\nprint(f\"Searching for {i_file}...\")\n\nif exists(i_file) == True:\n print(\"File exists!\\n\")\n\n o_file = input(\"What would you like to name the output file? \")\n o_file = o_file + \".txt\"\n\n target = open(o_file, 'w')\n\n with open(i_file) as csvfile:\n reader = csv.DictReader(csvfile, delimiter=',')\n\n for employee in reader:\n # create a blank list for technologies to be placed in\n tech_list2 = []\n\n # how would you use employee id as a unique identifier?\n employee_name = employee['Employee Full Name']\n employee_tech = employee['Employee Technologies (excludes HG Data technologies)']\n employee_title = employee['Employee Title']\n employee_seniority_level = employee['Employee Seniority Level']\n reports_to = employee['Employee Reports To']\n email = employee['Employee Email Address']\n phone_number = employee['Employee Direct Phone']\n\n # create the dictionary\n employee_profiles[employee_name] = {}\n employee_profiles[employee_name][\"Title\"] = employee_title\n employee_profiles[employee_name][\"Seniority\"] = employee_seniority_level\n employee_profiles[employee_name][\"Reports To\"] = reports_to\n employee_profiles[employee_name][\"Email Address\"] = email\n employee_profiles[employee_name][\"Phone Number\"] = phone_number\n matches[employee_name] = []\n\n tech_list = employee_tech.split(';')\n for tech in tech_list:\n tech = tech.split(',')\n for program in tech:\n if \":\" in program:\n program = program.split(':')\n tech_list2.append(program[1].strip().lower())\n else:\n tech_list2.append(program.strip().lower())\n\n employee_profiles[employee_name][\"Tech\"] = tech_list2\n\n for entry in employee_profiles.items():\n if software in entry[1]['Tech']:\n target.write(f\"\"\"\n=============================================================\n {entry[0]}, {entry[1][\"Title\"]}\n - Reports to: {entry[1][\"Reports To\"]}\n - Phone Number: {entry[1][\"Phone Number\"]}\n - Email Address: {entry[1][\"Email Address\"]}\n=============================================================\n\n \"\"\")\n\n target.close()\n\nelse:\n print(\"Could not find the file...\\n\")\n" } ]
2
miniatureape/templatemaker
https://github.com/miniatureape/templatemaker
e083203c168c4602125a9adb885efc9153aeb74c
c352b7b5f4e7d18abfff0cddf521785ccd4f12aa
77dad3bd60b585673585ff3e1686920e2ca1ece7
refs/heads/master
2021-01-10T06:38:41.164615
2015-12-16T16:33:06
2015-12-16T16:33:06
48,116,669
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5893150568008423, "alphanum_fraction": 0.5950685143470764, "avg_line_length": 37.62434005737305, "blob_id": "6fdf14e92a899c4acff3fb627112c1f66ab7cf73", "content_id": "bb5537cd92f4ffb511923a4f38c4ec247e2a8d9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7300, "license_type": "no_license", "max_line_length": 182, "num_lines": 189, "path": "/templatemaker.c", "repo_name": "miniatureape/templatemaker", "src_encoding": "UTF-8", "text": "#include <Python.h>\n#define MARKER \"\\x1f\"\n\n/*\n longest_match() and longest_match_shifter()\n\n Returns the length of the longest common substring (LCS) in the strings\n a and b.\n\n Sets a_offset to the index of a where the LCS begins.\n Sets b_offset to the index of b where the LCS begins.\n\n If there is NO common substring, it returns 0 and sets both\n a_offset and b_offset to -1.\n\n The strings do not have to be equal length.\n\n The algorithm works by comparing one character at a time and \"shifting\" the\n strings so that different characters are compared. For example, given\n a=\"ABC\" and b=\"DEF\", picture these alignments:\n\n (Shift a to the right)\n -------------------------------------------------------\n a | ABC ABC ABC\n b | DEF DEF DEF\n shift index | 0 1 2\n possible LCS | 3 2 1\n comparisons | AD, BE, CF AE, BF AF\n\n (Shift b to the right)\n -------------------------------------------------------\n | ABC ABC ABC\n | DEF DEF DEF\n shift index | 0 1 2\n possible LCS | 3 2 1\n comparisons | AD, BE, CF BD, CE CD\n\n The algorithm short circuits based on the best_size found so far. For example,\n given a=\"ABC\" and b=\"ABC\", the first cycle of comparisons (AA, BB, CC) would\n result in a best_size=3. Because the algorithm starts with zero shift (i.e.,\n it starts with the highest possible LCS) and adds 1 to the shift index each\n time through, it can safely exit without doing any more comparisons.\n\n This algorithm is O^(m + m-1 + m-2 + ... + 1 + n + n-1 + n-2 + ... + 1), where\n m and n are the length of the two strings. Due to short circuiting, the\n algorithm could potentially finish after the very\n first set of comparisons. The algorithm is slowest when the LCS is smallest,\n and the algorithm is fastest when the LCS is biggest.\n\n longest_match_shifter() performs \"one side\" of the shift -- e.g., \"Shift a to\n the right\" in the above illustration. longest_match() simply calls\n longest_match_shifter() twice, flipping the strings.\n*/\n\nint longest_match_shifter(char* a, char* b, int a_start, int a_end, int b_start, int b_end, int best_size, int* a_offset, int* b_offset) {\n int i, j, k;\n unsigned int current_size;\n\n for (i = b_start, current_size = 0; i < b_end; i++, current_size = 0) { // i is b starting index.\n if (best_size >= b_end - i) break; // Short-circuit. See comment above.\n for (j = i, k = a_start; k < a_end && j < b_end; j++, k++) { // k is index of a, j is index of b.\n if (a[k] == b[j]) {\n if (++current_size > best_size) {\n best_size = current_size;\n *a_offset = k - current_size + 1;\n *b_offset = j - current_size + 1;\n }\n }\n else {\n current_size = 0;\n }\n }\n }\n return best_size;\n}\n\n// a_offset and b_offset are relative to the *whole* string, not the substring\n// (as defined by a_start and a_end).\n// a_end and b_end are (the last index + 1).\nint longest_match(char* a, char* b, int a_start, int a_end, int b_start, int b_end, int* a_offset, int* b_offset) {\n unsigned int best_size;\n *a_offset = -1;\n *b_offset = -1;\n best_size = longest_match_shifter(a, b, a_start, a_end, b_start, b_end, 0, a_offset, b_offset);\n best_size = longest_match_shifter(b, a, b_start, b_end, a_start, a_end, best_size, b_offset, a_offset);\n return best_size;\n}\n\n/*\n make_template()\n\n Creates a template from two strings with a given tolerance.\n*/\n\nvoid make_template(char* template, int tolerance, char* a, char* b, int a_start, int a_end, int b_start, int b_end) {\n int a_offset, b_offset;\n unsigned int best_size;\n\n best_size = longest_match(a, b, a_start, a_end, b_start, b_end, &a_offset, &b_offset);\n if (best_size == 0) {\n strcat(template, MARKER);\n }\n if (a_offset > a_start && b_offset > b_start) {\n // There's leftover stuff on the left side of BOTH strings.\n make_template(template, tolerance, a, b, a_start, a_offset, b_start, b_offset);\n }\n else if (a_offset > a_start || b_offset > b_start) {\n // There's leftover stuff on the left side of ONLY ONE of the strings.\n strcat(template, MARKER);\n }\n\n if (best_size > tolerance) {\n strncat(template, a+a_offset, best_size);\n\n if ((a_offset + best_size < a_end) && (b_offset + best_size < b_end)) {\n // There's leftover stuff on the right side of BOTH strings.\n make_template(template, tolerance, a, b, a_offset + best_size, a_end, b_offset + best_size, b_end);\n }\n else if ((a_offset + best_size < a_end) || (b_offset + best_size < b_end)) {\n // There's leftover stuff on the right side of ONLY ONE of the strings.\n strcat(template, MARKER);\n }\n }\n}\n\n/* \n PYTHON STUFF\n\n These are the hooks between Python and C.\n\n function_longest_match() is commented out, because it's not necessary to\n expose it at the Python level. To expose it, uncomment it, along with the\n appropriate line in the \"ModuleMethods[]\" section toward the bottom of this\n file.\n*/\n\n/*\nstatic PyObject * function_longest_match(PyObject *self, PyObject *args) {\n char* a;\n char* b;\n int a_offset, b_offset, lena, lenb;\n unsigned int best_size;\n\n if (!PyArg_ParseTuple(args, \"s#s#\", &a, &lena, &b, &lenb))\n return NULL;\n\n best_size = longest_match(a, b, 0, lena, 0, lenb, &a_offset, &b_offset);\n return Py_BuildValue(\"(iii)\", best_size, a_offset, b_offset);\n}\n*/\n\nstatic PyObject * function_make_template(PyObject *self, PyObject *args) {\n char* template;\n char* a;\n char* b;\n int tolerance, lena, lenb, maxlen;\n PyObject* result;\n\n if (!PyArg_ParseTuple(args, \"s#s#i\", &a, &lena, &b, &lenb, &tolerance))\n return NULL;\n\n // Allocate enough memory to handle the maximum of len(a) or len(b).\n maxlen = (lena > lenb ? lena : lenb) + 1;\n template = (char *) malloc(maxlen * sizeof(char));\n template[0] = '\\0';\n\n make_template(template, tolerance, a, b, 0, lena, 0, lenb);\n\n result = PyString_FromString(template);\n free(template);\n return result;\n}\n\nstatic PyObject * function_marker(PyObject *self, PyObject *args) {\n return PyString_FromStringAndSize(MARKER, sizeof(MARKER)-1);\n}\n\nstatic PyMethodDef ModuleMethods[] = {\n // longest_match is commented out because it's not necessary to expose it\n // at the Python level. To expose it, uncomment the following line.\n/* {\"longest_match\", function_longest_match, METH_VARARGS, \"Given two strings, determines the longest common substring and returns a tuple of (best_size, a_offset, b_offset).\"},*/\n {\"make_template\", function_make_template, METH_VARARGS, \"Given two strings, returns a template.\"},\n {\"marker\", function_marker, METH_VARARGS, \"Returns a string of the template marker.\"},\n {NULL, NULL, 0, NULL} // sentinel\n};\n\nPyMODINIT_FUNC init_template(void) {\n (void) Py_InitModule(\"_template\", ModuleMethods);\n}\n" }, { "alpha_fraction": 0.6088264584541321, "alphanum_fraction": 0.6118354797363281, "avg_line_length": 28.323530197143555, "blob_id": "05b7dba3c8b748ebca876a3fa5960ad63b41ca6b", "content_id": "759ce8e561f1f207edc57a23df8f841c70403c94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 1994, "license_type": "no_license", "max_line_length": 79, "num_lines": 68, "path": "/TODO.TXT", "repo_name": "miniatureape/templatemaker", "src_encoding": "UTF-8", "text": "========================\ntemplatemaker to-do list\n========================\n\ntemplatemaker.c\n===============\n\n* Is there a more efficient algorithm for the longest_match() C function?\n\n* Provide a Python fallback module.\n\ntemplatemaker.py\n================\n\n* Allow for user definition of symbols that would be treated as \"single\"\n units, instead of always using each character as a separate symbol for\n comparison.\n\n* Create template, then load all known documents into it to get statistics\n on which holes differ more frequently. Can't do this while loading\n documents because a template's holes are not yet defined.\n\n* Keep track of which holes have only 2 to 5 possible values, and mark those\n in a special way -- \"option holes.\"\n\n* Keep track of hole values in known documents, and mark certain holes as\n \"pointless\" if their values are duplicates.\n\n* Don't save \\r\\n\\r\\n\\r\\n\\r\\n.\n\n* Automatically determine which fields are dates/times, and have extract()\n convert to datetime objects.\n\n* If learn() creates more holes, it should provide the PREVIOUS value for\n that hole (before it was a hole) for all previous documents. Thus,\n previous documents will be able to account for the new hole with the\n correct value. For example:\n\n >>> t = Template()\n >>> t.learn('<b>this and that</b><br>')\n >>> t.as_text('!')\n '<b>this and that</b><br>'\n\n >>> t.learn('<b>alex and sue</b><br>')\n True\n >>> t.as_text('!')\n '<b>! and !</b><br>'\n\n >>> t.last_change\n {0: 'this', 1: 'that'}\n\n >>> t.learn('<b>michael and scottie</b>')\n True\n >>> t.as_text('!')\n '<b>! and !</b>!'\n >>> t.last_change\n {2: '<br>'}\n\n >>> t.learn('<b>foo & bar</b><br>')\n True\n >>> t.as_text('!')\n '<b>! ! !</b>!'\n >>> t.last_change\n {1: 'and'}\n\n last_change is an attribute rather than being a return value of learn() to\n keep things clean. The value of last_change is overridden each time learn() is\n called.\n" }, { "alpha_fraction": 0.6513924598693848, "alphanum_fraction": 0.6616742014884949, "avg_line_length": 33.99150085449219, "blob_id": "72712f1211e1c03420f5e4c4fa9503b3624b1a00", "content_id": "1aea4b4ffc97c1e077b49f4e08a39152bb0b0579", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 12352, "license_type": "no_license", "max_line_length": 101, "num_lines": 353, "path": "/README.TXT", "repo_name": "miniatureape/templatemaker", "src_encoding": "UTF-8", "text": "Note: Forked and exported from Adrian Holovaty's google code repo.\n\n=============\ntemplatemaker\n=============\n\nGiven a list of text files in a similar format, templatemaker creates a\ntemplate that can extract data from files in that same format.\n\nThe underlying longest-common-substring algorithm is implemented in C\nfor performance.\n\nInstallation\n============\n\nBecause part of templatemaker is implemented in C, you'll need to compile the\nC portion of it. Fortunately, Python makes this easy.\n\nTo install systemwide:\n\n sudo python setup.py install\n\nTo play around with it without having to install systemwide:\n\n python setup.py build\n cp build/lib*/_templatemaker.so .\n rm -rf build\n\nOverview\n========\n\nThe templatemaker.py module provides a class, Template, that is capable of two\nthings:\n\n * Given an arbitrary number of strings (called \"Sample Strings\"), it\n determines the \"least-common denominator\" template -- that is, a string\n representing all the common substrings, with placeholders (\"holes\") for\n areas in the Sample Strings that differ.\n\n For example, these three Sample Strings...\n \n '<b>this and that</b>'\n '<b>alex and sue</b>'\n '<b>fine and dandy</b>'\n\n ...would produce the following template, where \"!\" represents a \"hole.\"\n\n '<b>! and !</b>'\n\n * Once you have a template, you can give it data that is formatted\n according to that template, and it will \"extract\" a tuple of the \"hole\"\n values for that particular string.\n \n Following the above example, giving the template the following data:\n \n '<b>larry and curly</b>'\n\n ...would produce the following tuple:\n \n ('larry', 'curly')\n\n You can interpret this as \"Hole 0's value is 'larry', and hole 1's value\n is 'curly'.\"\n\nBasic Python API\n================\n\nHere's how to express the above example in Python code:\n\n # Import the Template class.\n >>> from templatemaker import Template\n\n # Create a Template instance.\n >>> t = Template()\n\n # Learn a Sample String.\n >>> t.learn('<b>this and that</b>')\n\n # Output the template so far, using the \"!\" character to mark holes.\n # We've only learned a single string, so the template has no holes.\n >>> t.as_text('!')\n '<b>this and that</b>'\n\n # Learn another string. The True return value means the template gained\n # at least one hole.\n >>> t.learn('<b>alex and sue</b>')\n True\n\n # Sure enough, the template now has some holes.\n >>> t.as_text('!')\n '<b>! and !</b>'\n\n # Learn another string. This time, the return value is False, which means\n # the template didn't gain any holes.\n >>> t.learn('<b>fine and dandy</b>')\n False\n\n # The template is the same as before.\n >>> t.as_text('!')\n '<b>! and !</b>'\n\n # Now that we have a template, let's extract some data.\n >>> t.extract('<b>red and green</b>')\n ('red', 'green')\n >>> t.extract('<b>django and stephane</b>')\n ('django', 'stephane')\n\n # The extract() method is very literal. It doesn't magically trim\n # whitespace, nor does it have any knowledge of markup languages such as\n # HTML.\n >>> t.extract('<b> spacy and <u>underlined</u></b>')\n (' spacy ', '<u>underlined</u>')\n\n # The extract() method will raise the NoMatch exception if the data\n # doesn't match the template. In this example, the data doesn't have the\n # leading and trailing \"<b>\" tags.\n >>> t.extract('this and that')\n Traceback (most recent call last):\n ...\n NoMatch\n\n # Use the extract_dict() method to get a dictionary instead of a tuple.\n # extract_dict() requires that you specify a tuple of field names.\n >>> t.extract_dict('<b>red and green</b>', ('value1', 'value2'))\n {'value1': 'red', 'value2': 'green'}\n\n # You can specify None as one or more of the field-name values in\n # extract_dict(). Any field whose value is None will *not* be included\n # in the resulting dictionary.\n >>> t.extract_dict('<b>red and green</b>', ('value1', None))\n {'value1': 'red'}\n >>> t.extract_dict('<b>red and green</b>', (None, 'value2'))\n {'value2': 'green'}\n\nThe as_text() method\n====================\n\nThe as_text() method displays the template as a string, with holes represented\nby a string of your choosing.\n\n >>> t = Template()\n >>> t.learn('123 and 456')\n >>> t.learn('456 and 789')\n True\n\n Get the template with \"!\" as the hole-representing string.\n >>> t.as_text('!')\n '! and !'\n\n Get the template with \"{{ var }}\" as the hole-representing string.\n >>> t.as_text('{{ var }}')\n '{{ var }} and {{ var }}'\n\nNote that as_text() does *not* perform any escaping if your template contains\nthe hole-representing string:\n\n >>> t = Template()\n >>> t.learn('Yes!')\n >>> t.learn('No!')\n True\n\n Here, we use \"!\" as the hole-representing string, and the template contains\n a literal \"!\" character. The literal character is not escaped, so there is\n no way to tell apart the literal template character from the\n hole-representing string.\n >>> t.as_text('!')\n '!!'\n\n Here, we use an underscore to demonstrate that the template contains a\n literal \"!\" character. This wasn't detectable in the previous statement.\n >>> t.as_text('_')\n '_!'\n\nWith this in mind, you should choose a string in as_text() that is highly\nunlikely to appear in your template. But, in any case, you shouldn't rely on\nthe output of as_text() for use in programs; it's solely intended to be a\nvisual aid for humans to see their templates. (The template-maker code has its\nown internal way of representing holes, and it's guaranteed to be unambiguous.\nSee \"The marker character\" below.)\n\nTolerance\n=========\n\nThis template-making algorithm can often be \"too literal\" for one's liking.\nFor example, given these three Sample Strings...\n\n 'my favorite color is blue'\n 'my favorite color is violet'\n 'my favorite color is purple'\n\nThe color is the only text that changes, so one would assume the template would\nbe the following:\n\n 'my favorite color is !'\n\nLet's see what actually happens:\n\n >>> t = Template()\n >>> t.learn('my favorite color is blue')\n >>> t.learn('my favorite color is violet')\n True\n >>> t.learn('my favorite color is purple')\n False\n >>> t.as_text('!')\n 'my favorite color is !l!e!'\n\nAha, the template-maker was a bit too literal -- it noticed that the strings\n\"blue\", \"violet\" and \"purple\" all contain *something*, then the letter \"l\",\nthen *something*, then the letter \"e\", then *something*. Technically, that's\ncorrect, but for most applications, this approach misses the forest for the\ntrees.\n\nThere are two ways to solve this problem:\n\n * Teach a template many, many Sample Strings. The more diverse your input,\n the less likely this will happen.\n\n * Use a feature called *tolerance*.\n\nThe template-maker algorithm lets you specify a tolerance -- the minimum\nallowed length of text between holes. This gives you control over avoiding the\nproblem.\n\nTo specify tolerance, just pass the ``tolerance`` argument to the Template\nconstructor. Here's the above example with a tolerance=1.\n\n >>> t = Template(tolerance=1)\n >>> t.learn('my favorite color is blue')\n >>> t.learn('my favorite color is violet')\n True\n >>> t.learn('my favorite color is purple')\n False\n >>> t.as_text('!')\n 'my favorite color is !'\n\nAha! Now, that's more like it.\n\nSetting tolerance is useful for small cases like this, but note that there is a\nrisk of throwing the baby out with the bathwater, depending on how high your\ntolerance is set. If the tolerance is set too high, your output template might\nbe \"watered down\" -- less accurate than it possibly could be.\n\nFor example, say we have a list of HTML strings representing significant\nevents:\n\n <p>My birthday is <span style=\"color: blue;\">Dec. 11, 1954</span>.</p>\n <p>My wife's birthday is <span style=\"color: red;\">Jan. 3, 1957</span>.</p>\n <p>Our wedding fell on <span style=\"color: green;\">Sep. 24, 1982</span>.</p>\n\nSay we'd like to extract five pieces of data from each string: the event, the\nHTML color, the month, the day and the year. Here's what we might do in Python:\n\n >>> t = Template(tolerance=5)\n >>> t.learn('<p>My birthday is <span style=\"color: blue;\">Dec. 11, 1954</span>.</p>')\n >>> t.learn('<p>My wife\\'s birthday is <span style=\"color: red;\">Jan. 3, 1957</span>.</p>')\n True\n >>> t.learn('<p>Our wedding fell on <span style=\"color: green;\">Sep. 24, 1982</span>.</p>')\n True\n >>> t.as_text('!')\n '! <span style=\"color: !</span>.</p>'\n\nThis resulting template is correct, but it's watered down.\n\nThis template is, indeed, watered down. You can tell by extracting some data:\n\n >>> t.extract('<p>My sister\\'s birthday is <span style=\"color: pink;\">Jul. 12, 1952</span>.</p>')\n (\"<p>My sister's birthday is\", 'pink;\">Jul. 12, 1952')\n\nThis data is messy. Namely, the color of the <span> is in the same data field\nas the event date. Assuming we're interested in getting as granular as\npossible in our parsing, it would be better to set a lower tolerance.\n\n >>> t = Template(tolerance=1)\n >>> t.learn('<p>My birthday is <span style=\"color: blue;\">Dec. 11, 1954</span>.</p>')\n >>> t.learn('<p>My wife\\'s birthday is <span style=\"color: red;\">Jan. 3, 1957</span>.</p>')\n True\n >>> t.learn('<p>Our wedding fell on <span style=\"color: green;\">Sep. 24, 1982</span>.</p>')\n False\n >>> t.as_text('!')\n '<p>! <span style=\"color: !;\">!. !, 19!</span>.</p>'\n >>> t.extract('<p>My sister\\'s birthday is <span style=\"color: pink;\">Jul. 12, 1952</span>.</p>')\n (\"My sister's birthday is\", 'pink', 'Jul', '12', '52')\n\nMuch better.\n\nUsing tolerance is all about tradeoffs. To use this feature most effectively,\nyou'll need to experiment and consider the nature of the data you're parsing.\n\nVersions\n========\n\nA Template instance keeps tracks of how many Sample Strings it has learned.\nYou can access this via the ``version`` attribute.\n\n >>> t = Template()\n >>> t.version\n 0\n >>> t.learn('My name is Paul.')\n >>> t.version\n 1\n >>> t.learn('My name is Jonas.')\n True\n >>> t.version\n 2\n\nThe marker character\n====================\n\nThe template-maker algorithm, implemented in C, works by comparing two strings\none byte at a time. Each time you call learn(some_string) on a template object,\nthe underlying C algorithm compares some_string to the *current template*.\n\nA template internally represents each hole with a *marker character* -- a\ncharacter that is guaranteed not to appear in either string. This is set to the\ncharacter \"\\x1f\".\n\nIn order to guarantee that the marker character doesn't appear in a string, the\nTemplate's learn() method removes any occurrence of the marker character from\nthe input string before running the comparison algorithm.\n\nThe advantage of this \"dumb\" approach is its simplicity: the C implementation\ndoesn't have to treat markers as a special case. As a result, the C code is\ncleaner and faster. Also, it was easier to write. :)\n\nHowever, there are two disadvantages:\n\n * First, a template effectively cannot contain the literal marker\n character.\n\n In practice, this is *highly* unlikely to be a problem, because the\n marker character is obscure.\n\n * Two, in the slight chance that a template contains a multi-byte character\n (e.g., Unicode) that contains the marker character as one of its bytes,\n the template-maker algorithm will split that Unicode character at that\n byte. This happens because the underlying C implementation compares\n single bytes -- it is *not* Unicode-aware.\n\n In practice, this is *highly* unlikely to be a problem. In order to get\n bitten by this, you'd need an aforementioned multi-byte character to\n appear in your template (not just in a Sample String, but in your\n template -- i.e., in *each* Sample String).\n\n If it turns out there are significant multi-byte characters that contain\n the marker character \"\\x1f\", you can change the MARKER value at the top\n of templatemaker.c and recompile it. Or, suggest a better character to\n the authors.\n\nChange log\n==========\n\n2007-09-20 0.1.1 Created HTMLTemplate\n2007-07-06 0.1 Initial release\n" }, { "alpha_fraction": 0.46834084391593933, "alphanum_fraction": 0.5741575360298157, "avg_line_length": 46.54081726074219, "blob_id": "83038557d0cde65aad7c3e8878901ad189028eaf", "content_id": "1269e862152d1ab3fb2dd37a31fe6a2612b43322", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4659, "license_type": "no_license", "max_line_length": 117, "num_lines": 98, "path": "/tests.py", "repo_name": "miniatureape/templatemaker", "src_encoding": "UTF-8", "text": "import unittest\nfrom templatemaker import Template\n\nclass TemplatemakerTestCase(unittest.TestCase):\n def create(self, tolerance, *inputs):\n \"\"\"\n \"Helper method that returns a Template with the given tolerance and\n inputs.\n \"\"\"\n t = Template(tolerance=tolerance)\n for i in inputs:\n t.learn(i)\n return t\n\n def assertCreated(self, tolerance, expected, *inputs):\n \"\"\"\n Asserts that a Template with the given tolerance and inputs would be\n rendered as_text('!') to the expected string.\n \"\"\"\n t = self.create(tolerance, *inputs)\n self.assertEqual(t.as_text('!'), expected)\n\nclass Creation(TemplatemakerTestCase):\n def test_noop(self):\n self.assertCreated(0, '<title>123</title>', '<title>123</title>')\n self.assertCreated(0, '<title>123</title>', '<title>123</title>', '<title>123</title>')\n self.assertCreated(0, '<title>123</title>', '<title>123</title>', '<title>123</title>', '<title>123</title>')\n\n def test_one_char_start(self):\n self.assertCreated(0, '!2345', '12345', '_2345')\n self.assertCreated(0, '!2345', '12345', '12345', '_2345')\n self.assertCreated(0, '!2345', '12345', '_2345', '^2345')\n\n def test_one_char_end(self):\n self.assertCreated(0, '1234!', '12345', '1234_')\n self.assertCreated(0, '1234!', '12345', '12345', '1234_')\n self.assertCreated(0, '1234!', '12345', '1234_', '1234^')\n\n def test_one_char_middle(self):\n self.assertCreated(0, '12!45', '12345', '12_45')\n self.assertCreated(0, '12!45', '12345', '12345', '12_45')\n self.assertCreated(0, '12!45', '12345', '12_45', '12^45')\n\n def test_multi_char_start(self):\n self.assertCreated(0, '!345', '12345', '_2345', '1_345')\n self.assertCreated(0, '!345', '12345', '1_345', '_2345')\n self.assertCreated(0, '!45', '12345', '_2345', '1_345', '12_45')\n self.assertCreated(0, '!5', '12345', '_2345', '1_345', '12_45', '123_5')\n\n def test_multi_char_end(self):\n self.assertCreated(0, '1234!', '12345', '1234_')\n self.assertCreated(0, '123!', '12345', '1234_', '123_5')\n self.assertCreated(0, '12!', '12345', '1234_', '123_5', '12_45')\n self.assertCreated(0, '1!', '12345', '1234_', '123_5', '12_45', '1_345')\n\n def test_empty(self):\n self.assertCreated(0, '', '', '')\n\n def test_no_similarities(self):\n self.assertCreated(0, '!', 'a', 'b')\n self.assertCreated(0, '!', 'ab', 'ba', 'ac', 'bc')\n self.assertCreated(0, '!', 'abc', 'ab_', 'a_c', '_bc')\n\n def test_left_weight(self):\n self.assertCreated(0, '!a!', 'ab', 'ba') # NOT '!b!'\n self.assertCreated(0, 'a!b!', 'abc', 'acb')\n\n def test_multihole(self):\n self.assertCreated(0, '!2!', '123', '_23', '12_')\n self.assertCreated(0, '!2!4!', '12345', '_2_4_')\n self.assertCreated(0, '!2!4!', '12345', '_2345', '12_45', '1234_')\n self.assertCreated(0, '!2!456!8', '12345678', '_2_456_8')\n self.assertCreated(0, '!2!456!8', '12345678', '_2345678', '12_45678', '123456_8')\n self.assertCreated(0, '!e! there', 'hello there', 'goodbye there')\n\n def test_marker_char(self):\n \"The marker character (\\x1f) is deleted from all input.\"\n self.assertCreated(0, '<title>!</title>', '<title>\\x1f1234</title>', '<title>5678\\x1f</title>')\n\nclass CreationWithTolerance(TemplatemakerTestCase):\n def test_tolerance(self):\n self.assertCreated(1, '<title>!</title>', '<title>123</title>', '<title>a2c</title>')\n self.assertCreated(2, '<title>!</title>', '<title>123</title>', '<title>a2c</title>')\n self.assertCreated(0, '<title>!23!</title>', '<title>1234</title>', '<title>a23c</title>')\n self.assertCreated(1, '<title>!23!</title>', '<title>1234</title>', '<title>a23c</title>')\n self.assertCreated(2, '<title>!</title>', '<title>1234</title>', '<title>a23c</title>')\n self.assertCreated(3, '<title>!</title>', '<title>1234</title>', '<title>a23c</title>')\n self.assertCreated(0, 'http://s!me!.com/', 'http://suntimes.com/', 'http://someing.com/')\n self.assertCreated(1, 'http://s!me!.com/', 'http://suntimes.com/', 'http://someing.com/')\n self.assertCreated(2, 'http://s!.com/', 'http://suntimes.com/', 'http://someing.com/')\n self.assertCreated(3, 'http://s!.com/', 'http://suntimes.com/', 'http://someing.com/')\n self.assertCreated(4, 'http://s!.com/', 'http://suntimes.com/', 'http://someing.com/')\n\nclass TemplateExtractionTests(unittest.TestCase):\n pass\n\nif __name__ == \"__main__\":\n unittest.main()\n" }, { "alpha_fraction": 0.6926605701446533, "alphanum_fraction": 0.6995412707328796, "avg_line_length": 32.53845977783203, "blob_id": "e87e5bf5432270b724b82b6e9a90bf40f2a0e69b", "content_id": "36d7d3a404d2ac4adf6cfd7557cfcf51f1e1f620", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 436, "license_type": "no_license", "max_line_length": 153, "num_lines": 13, "path": "/setup.py", "repo_name": "miniatureape/templatemaker", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nfrom distutils.core import setup, Extension\n\nsetup(\n name='templatemaker',\n version='0.0.1',\n description='Given a list of text files in a similar format, templatemaker creates a template that can extract data from files in that same format.',\n author='Adrian Holovaty',\n author_email='[email protected]',\n packages=['templatemaker'],\n ext_modules=[Extension('templatemaker._template', ['templatemaker.c'])],\n)\n" }, { "alpha_fraction": 0.6000992059707642, "alphanum_fraction": 0.6023319363594055, "avg_line_length": 30.740158081054688, "blob_id": "0b3f9f6b4957d86ae2b43f777db7dd466af543c9", "content_id": "0b12a9fd6c17c263b1c6fe3e2c5ba36a9a9bead3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4031, "license_type": "no_license", "max_line_length": 90, "num_lines": 127, "path": "/templatemaker/template.py", "repo_name": "miniatureape/templatemaker", "src_encoding": "UTF-8", "text": "r\"\"\"\ntemplatemaker.py\n\nCopyright (c) 2007 Adrian Holovaty\nLicense: BSD\n\nSee readme.txt for full documentation.\n\"\"\"\n\nfrom _template import make_template, marker\nimport re\n\n# The marker character lives in _templatemaker.marker() so we don't have\n# to define it in more than one place.\nMARKER = marker()\n\nclass NoMatch(Exception):\n pass\n\nclass Template(object):\n def __init__(self, tolerance=0, brain=None):\n self._brain = brain\n self._tolerance = tolerance\n self.version = 0\n\n def clean(self, text):\n \"\"\"\n Strips any unwanted stuff from the given Sample String, in order to\n make templates more streamlined.\n \"\"\"\n text = re.sub(r'\\r\\n', '\\n', text)\n return text\n\n def learn(self, text):\n \"\"\"\n Learns the given Sample String.\n\n Returns True if this Sample String created more holes in the template.\n Returns None if this is the first Sample String in this template.\n Otherwise, returns False.\n \"\"\"\n text = self.clean(text)\n text = text.replace(MARKER, '')\n self.version += 1\n if self._brain is None:\n self._brain = text\n return None\n old_holes = self.num_holes()\n self._brain = make_template(self._brain, text, self._tolerance)\n return self.num_holes() > old_holes\n\n def as_text(self, custom_marker='{{ HOLE }}'):\n \"\"\"\n Returns a display-friendly version of the template, using the\n given custom_marker to mark template holes.\n \"\"\"\n return self._brain.replace(MARKER, custom_marker)\n\n def num_holes(self):\n \"\"\"\n Returns the number of holes in this template.\n \"\"\"\n return self._brain.count(MARKER)\n\n def extract(self, text):\n \"\"\"\n Given a bunch of text that is marked up using this template, extracts\n the data.\n\n Returns a tuple of the raw data, in the order in which it appears in\n the template. If the text doesn't match the template, raises NoMatch.\n \"\"\"\n text = self.clean(text)\n regex = '^(?s)%s$' % re.escape(self._brain).replace(re.escape(MARKER), '(.*?)')\n m = re.search(regex, text)\n if m:\n return m.groups()\n raise NoMatch\n\n def extract_dict(self, text, field_names):\n \"\"\"\n Extracts the data from `text` and uses the `field_names` tuple to\n return a dictionary of the extracted data.\n\n Returns a dictionary of the raw data according to field_names, which\n should be a tuple of strings representing dictionary keys, in order.\n Use None for one or more values in field_names to specify that a\n certain value shouldn't be included in the dictionary.\n \"\"\"\n data = self.extract(text)\n data_dict = dict(zip(field_names, data))\n try:\n del data_dict[None]\n except:\n pass\n return data_dict\n\n\n def from_directory(cls, dirname, tolerance=0):\n \"\"\"\n Classmethod that learns all of the files in the given directory name.\n Returns the Template object.\n \"\"\"\n import os\n t = cls(tolerance)\n for f in os.listdir(dirname):\n print t.learn(open(os.path.join(dirname, f)).read())\n return t\n from_directory = classmethod(from_directory)\n\nclass HTMLTemplate(Template):\n \"\"\"\n A special version of Template that is a bit smarter about dealing with\n HTML, assuming you care about identifying differences in the *content* of\n an HTML page rather than differences in the markup/script.\n \"\"\"\n def __init__(self, *args, **kwargs):\n Template.__init__(self, *args, **kwargs)\n self.unwanted_tags_re = re.compile(r'(?si)<\\s*?(script|style|noscript)\\b.*?</\\1>')\n\n def clean(self, text):\n \"\"\"\n Strips out <script>, <style> and <noscript> tags and everything within\n them.\n \"\"\"\n text = self.unwanted_tags_re.sub('', text)\n return Template.clean(self, text)\n" }, { "alpha_fraction": 0.6904761791229248, "alphanum_fraction": 0.726190447807312, "avg_line_length": 27, "blob_id": "d87acf3c08a69a2f670e472f715831c11f428419", "content_id": "e9eaf853ec45c27954e376e7685d0dae9da9401a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 84, "license_type": "no_license", "max_line_length": 60, "num_lines": 3, "path": "/templatemaker/__init__.py", "repo_name": "miniatureape/templatemaker", "src_encoding": "UTF-8", "text": "from template import Template, HTMLTemplate, NoMatch, MARKER\n\n__version__ = '0.0.1'\n" } ]
7
py4/twiler
https://github.com/py4/twiler
3067077f744c0a888866dff8a51a44c2d58c01c0
f12c30028e764f143aed3a4fab34e8214a6e8b8f
44fd604d7c501bda45c0df42feaf47ff7f558f32
refs/heads/master
2016-09-05T20:38:28.120891
2014-10-22T14:20:53
2014-10-22T14:20:53
25,371,423
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6165577173233032, "alphanum_fraction": 0.6339869499206543, "avg_line_length": 31.714284896850586, "blob_id": "0b0b61af3241c49ba5432ea8224a9f2e71d56f2f", "content_id": "c472e0e97390bf76909d8566c9646ee1ae6e8be5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 459, "license_type": "no_license", "max_line_length": 61, "num_lines": 14, "path": "/test.rb", "repo_name": "py4/twiler", "src_encoding": "UTF-8", "text": "require 'twitter'\nclient = Twitter::REST::Client.new do |config|\n config.consumer_key = \"6clMQc5LA3irCE7JSgM3AC0jL\"\n config.consumer_secret = \"vDFGq7hrwrUgTfRmvui59dMdABNtGg1lwaN14SMdphvMyBToTv\"\n config.access_token = \"327039781-0mljdsIiAZ0EV6ZqsLJXCOKjuhLrwZ3xFCUx4269\"\n config.access_token_secret = \"r9T1w5ENSGpP9KBnApqTEsaXWe0Ja49TTw20NR4h416GS\"\nend\n\nputs client.search(ARGV[0]).count #take(3).collect do |tweet|\n #puts \"#{tweet.user.methods}\"\n #puts tweet.retweeted_by\n #puts \"#{tweet}\"\n# puts \"#{tweet.user.screen_name}: #{tweet.text}\"\n#end\n\n" }, { "alpha_fraction": 0.5857568383216858, "alphanum_fraction": 0.5951454043388367, "avg_line_length": 44.48958206176758, "blob_id": "a7510306575e5558e51b66256af676d70e8268e2", "content_id": "8a149a6f97639768200658d3c4a7cf5ac7daddfe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4367, "license_type": "no_license", "max_line_length": 461, "num_lines": 96, "path": "/backbone.py", "repo_name": "py4/twiler", "src_encoding": "UTF-8", "text": "#Copyright (C) 2014, Simon Dooms\n\n#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\n#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\n#THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#from twitter import *\nfrom twitter import *\nimport sys\n\nclass Backbone:\n t = None\n\n def __init__(self):\n #Twitter API v1.1 needs oAuth\n token = '327039781-0mljdsIiAZ0EV6ZqsLJXCOKjuhLrwZ3xFCUx4269'\n token_secret = 'r9T1w5ENSGpP9KBnApqTEsaXWe0Ja49TTw20NR4h416GS'\n con_key = '6clMQc5LA3irCE7JSgM3AC0jL'\n con_secret = 'vDFGq7hrwrUgTfRmvui59dMdABNtGg1lwaN14SMdphvMyBToTv'\n try:\n self.t = Twitter(auth=OAuth(token, token_secret, con_key, con_secret))\n except:\n print 'Error connecting to twitter'\n sys.exit()\n\n def search_user_timeline(self,query, since, tl_user_id):\n print \"searching in timeline of user with id: \" + str(tl_user_id)\n tweets = list()\n the_max_id = None\n the_max_id_oneoff = None\n new_since_id = since\n\n res = self.t.statuses.user_timeline(user_id = tl_user_id, count = 1000)\n\t#res = self.t.statuses.home_timeline(user_id=tl_user_id,count = 1000)\n num_results = len(res)\n print 'Found ' + str(num_results) + ' tweets from fucking timeling'\n for d in res:\n\t if not all(x.lower() in d['text'].lower() for x in query.split()):\n\t\tif \"rated\" in d['text']:\n\t\t\tprint query\n\t\t\tprint d['text']\n\t\tcontinue\n tweets.append(d)\n tweetid = d['id']\n\n if new_since_id < tweetid:\n new_since_id = tweetid\n\n print 'Found ' + str(len(tweets)) + ' tweets.'\n return tweets, new_since_id\n\n def searchTweets(self, query, since):\n tweets = list()\n the_max_id = None #start with empty max\n the_max_id_oneoff = None\n new_since_id = since\n\n number_of_iterations = 0\n while (number_of_iterations <= 100):\n number_of_iterations += 1\n count = 200 #maximum number of tweets allowed in one result set\n #try:\n if the_max_id != None:\n the_max_id_oneoff = the_max_id -1\n #798959545 ermirss\n #res = self.t.users.search(q=query, result_type='recent', count=count,since_id=since,max_id=the_max_id_oneoff)\n res = self.t.search.tweets(q=query, result_type='recent', count=count,since_id=since,max_id=the_max_id_oneoff)\n else:\n res = self.t.search.tweets(q=query, result_type='recent', count=count,since_id=since)\n #except:\n # print 'Error searching for tweets'\n # return tweets, new_since_id\n\n try:\n #Extract the tweets from the results\n num_results = len(res['statuses'])\n print ' Found ' + str(num_results) + ' tweets.'\n for d in res['statuses']:\n tweets.append(d)\n tweetid = d['id']\n if the_max_id == None or the_max_id > tweetid:\n the_max_id = tweetid\n\n if new_since_id < tweetid:\n new_since_id = tweetid\n\n #end the while loop if no more tweets were found\n if len(res['statuses']) == 0:\n break\n #break #for debug (quits after 1 iteration of count tweets)\n except ValueError:\n print 'Error ', sys.exc_info()[0]\n traceback.print_exc(file=sys.stdout)\n return tweets, new_since_id\n return tweets, new_since_id\n" }, { "alpha_fraction": 0.6387283205986023, "alphanum_fraction": 0.650288999080658, "avg_line_length": 23.714284896850586, "blob_id": "f15ff8d79a8d99e97173df2cfc0bf9ddb0b9f142", "content_id": "fbde419060f74ef9023143061d678c1a99477386", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 346, "license_type": "no_license", "max_line_length": 64, "num_lines": 14, "path": "/check.rb", "repo_name": "py4/twiler", "src_encoding": "UTF-8", "text": "users = Hash.new { |h,k| h[k] = []}\nsize = 0\nFile.readlines(\"dataset/lastfm/base_listens.dat\").each do |line|\n splitted = line.split(',')\n users[splitted[0]] << splitted[1]\n size += 1\nend\n\nputs users.keys.size\n#puts sum\n#puts users.keys.size\n#puts sum.to_f / users.keys.size\n\n#puts users.map { |user_id, hash| hash.keys.size }.sort.uniq\n" } ]
3
gyom/miscCodeExercisesAndSingleUsage
https://github.com/gyom/miscCodeExercisesAndSingleUsage
3b258dbd4f529753d034c5deb21f34792a33aa69
417a4e287812c4323ac82cb70b007f5e12b8dcbe
82528dcf681f4db953e2d19f279278a38aa373e9
refs/heads/master
2021-01-10T20:11:05.950707
2012-03-13T11:35:11
2012-03-13T11:35:11
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.47989949584007263, "alphanum_fraction": 0.5988274812698364, "avg_line_length": 26.022727966308594, "blob_id": "b17885dbcd2848753a0df8f05cc47109f9e7e91b", "content_id": "6a09edbe9bde4f5930d4ddfd747db6849c8e0786", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1194, "license_type": "no_license", "max_line_length": 73, "num_lines": 44, "path": "/programmingPearls_interviewPreparation/salariesTaxRatesSimplification.py", "repo_name": "gyom/miscCodeExercisesAndSingleUsage", "src_encoding": "UTF-8", "text": "\nimport random\n\ndef method1(income):\n\tif income <= 2200:\n\t\ttax = 0\n\telif income <= 2700:\n\t\ttax = 0.14 * (income-2200)\n\telif income <= 3200:\n\t\ttax = 70 + 0.15 * (income-2700)\n\telif income <= 3700:\n\t\ttax = 145 + 0.16 * (income-3200)\n\telif income <= 4200:\n\t\ttax = 225 + 0.17 * (income-3700)\n\telse:\n\t\t# not the point here, but let's say that the super-rich pay no taxes\n\t\ttax = 0\n\treturn tax\n\ndef method2(income):\n\tcategoryBase = [0, 2200, 2700, 3200, 3700, 4200, 1000000]\n\tcategoryTaxRate = [0, 0.14, 0.15, 0.16, 0.17, 0, 0]\n\tcategoryOffset = [0, 0, 70, 145, 225, 0, 0]\n\t\n\ti = 0\n\twhile( categoryBase[i+1] <= income):\n\t\ti+=1\n\t# terminates when categoryBase[i] <= income < categoryBase[i+1]\n\treturn (income - categoryBase[i])*categoryTaxRate[i] + categoryOffset[i]\n\nif __name__ == \"__main__\":\n\tnreps = 100\n\t(minval, maxval) = (0, 5000)\n\t(okCount, errorCount) = (0, 0)\n\tresults = {}\n\tfor r in range(0, nreps):\n\t\tincome = random.randint(minval, maxval)\n\t\tt1 = method1(income)\n\t\tt2 = method2(income)\n\t\tif (t1 == t2):\n\t\t\tokCount += 1\n\t\telse:\n\t\t\terrorCount += 1\n\t\tresults[(r,income, t1, t2)] = (t1==t2)\n\tprint \"okCount = %d, errorCount = %d\" % (okCount, errorCount)\n\n\n\n\n" }, { "alpha_fraction": 0.4241071343421936, "alphanum_fraction": 0.49968111515045166, "avg_line_length": 23.4453125, "blob_id": "210da0d421c6a2ebf50b22a140943eaef38cc0c9", "content_id": "ef9be355994bf0e8ab14418db18c21ba0d79de88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3136, "license_type": "no_license", "max_line_length": 152, "num_lines": 128, "path": "/programmingPearls_interviewPreparation/sudoku1.py", "repo_name": "gyom/miscCodeExercisesAndSingleUsage", "src_encoding": "UTF-8", "text": "\n# writing again by heart the program from Norvig, 2012-01-15\n\ndef cross(A,B):\n\treturn [a+b for a in A for b in B]\n\ndigits = '123456789'\nrows = 'ABCDEFGHI'\ncols = digits\n\nsquares = cross(rows, cols)\nunitlist = [cross(a,cols) for a in rows] + [cross(rows, [b]) for b in cols] + [cross(A,B) for A in ['ABC', 'DEF', 'GHI'] for B in ['123', '456', '789']]\n\n\nunits = dict( (s, [u for u in unitlist if s in u] ) for s in squares )\n#dict( (s, [u for u in [[1,2], [1,3], [2,3]] if s in u]) for s in [1,2,3])\n#dict( (s, [u for u in [['A1','B2'], ['A1','C3'], ['B2','C3']] if s in u]) for s in ['A1','B2','C3', 'D4'])\n\npeers = dict( (s, set(sum(units[s],[])) - set([s]) ) for s in squares )\n\n\ndef display(values):\n\tstr = \"\"\n\tfor s in squares:\n\t\tif len(values[s]) == 0:\n\t\t\tstr = str + \" X \"\n\t\telif len(values[s]) == 1:\n\t\t\tstr = str + \" \" + values[s] + \" \"\n\t\telse:\n\t\t\tstr = str + \" . \"\n\t\tif s == \"C9\":\n\t\t\tstr = str + \"\\n\"\n\t\t\tstr = str + \"----------------------------\"\n\t\t\tstr = str + \"\\n\"\n\t\telif s == \"F9\":\n\t\t\tstr = str + \"\\n\"\n\t\t\tstr = str + \"----------------------------\"\n\t\t\tstr = str + \"\\n\"\n\t\telif '3' in s or '6' in s:\n\t\t\tstr = str + \" | \"\n\t\telif '9' in s:\n\t\t\tstr = str + \"\\n\"\n\tprint str\n\n\ndef grid_values(grid):\n\tV = [c for c in grid if c in digits or c in '0.']\n\treturn dict(zip(squares, V))\n\ndef parse_grid(grid):\n\tvalues = dict( (s, digits) for s in squares)\n\tfor k,v in grid_values(grid).items():\n\t\t#print \"processing location {} with value {}\".format(k, v)\n\t\tif v in digits and not assign(values, k, v):\n\t\t\tprint \"failed to assign location {} value {} \".format(k, v)\n\t\t\treturn False\n\treturn values\n\n\ndef assign(values, k, v):\n\tif v in values[k]:\n\t\tvalues[k] = v\n\t\tfor p in peers[k]:\n\t\t\t# eliminate the value, but now continue if that means that\n\t\t\t# that square has only one value left\n\t\t\tif eliminate(values, p, v) and len(values[p]) == 1:\n\t\t\t\t# assign that value, but return a general failure if that\n\t\t\t\t# assignment led to a contradiction\n\t\t\t\tif not assign(values, p, values[p]):\n\t\t\t\t\treturn False\n\t\treturn values\n\telse:\n\t\t# tried to assign an illegal value\n\t\treturn False\n\ndef eliminate(values, k, v):\n\tif v in values[k]:\n\t\tvalues[k] = values[k].replace(v, '')\n\t\t# return True if we indeed took out a value\n\t\treturn True\n\telse:\n\t\t# return False if it was already eliminated (like usual)\n\t\treturn False\n\n\n\n\n\n\n\n\n\n\ngrid1 = '003020600900305001001806400008102900700000008006708200002609500800203009005010300'\ndisplay(parse_grid(grid1))\n# 4 8 3 | 9 2 1 | 6 5 7\n# 9 6 7 | 3 4 5 | 8 2 1\n# 2 5 1 | 8 7 6 | 4 9 3\n#----------------------------\n# 5 4 8 | 1 3 2 | 9 7 6\n# 7 2 9 | 5 6 4 | 1 3 8\n# 1 3 6 | 7 9 8 | 2 4 5\n#----------------------------\n# 3 7 2 | 6 8 9 | 5 1 4\n# 8 1 4 | 2 5 3 | 7 6 9\n# 6 9 5 | 4 1 7 | 3 8 2\n\n\n\t\t\t\n\t\t\t\n\ngrid2 = \"\"\"\n4 . . | . . . | 8 . 5\n. 3 . | . . . | . . .\n. . . | 7 . . | . . .\n---------------------\n. 2 . | . . . | . 6 .\n. . . | . 8 . | 4 . . \n. . . | . 1 . | . . . \n---------------------\n. . . | 6 . 3 | . 7 .\n5 . . | 2 . . | . . . \n1 . 4 | . . . | . . . \n\"\"\"\n\nA = parse_grid(grid2)\ndisplay(A)\n\n# won't solve the thing\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.4663461446762085, "alphanum_fraction": 0.5416666865348816, "avg_line_length": 32.55555725097656, "blob_id": "9d274ccb7a1c86ca5946a0ab17875529f6fddc0f", "content_id": "20059fdbf26693e77a0cdc28192c7a66b006c6c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 624, "license_type": "no_license", "max_line_length": 126, "num_lines": 18, "path": "/programmingPearls_interviewPreparation/scheduleConflicts.py", "repo_name": "gyom/miscCodeExercisesAndSingleUsage", "src_encoding": "UTF-8", "text": "\r\n\r\nscheduleData = [[0,1], [2,4], [5,6], [5.5, 5.8], [8,9], [7,8.5], [10,11], [9.5, 11.5], [12,13], [12,12.5], [13,13.5], [14,15]]\r\n\r\nS = set(reduce(lambda acc,E: acc+E, scheduleData, []))\r\nendpoints = [e for e in S]\r\nendpoints.sort()\r\n\r\nconflicts = dict( ((u,v), 0) for (u,v) in zip(endpoints[0:], endpoints[1:]))\r\n\r\n# not very sharp algorithmically, but okay\r\nfor (a,b) in scheduleData:\r\n\tfor ((u,v),n) in conflicts.items():\r\n\t\tif a <= u and v <= b:\r\n\t\t\tconflicts[(u,v)] = n+1\r\n\r\n\r\nfor ((u,v),n) in sorted(conflicts.items(), key = lambda ((u,v),n): u):\r\n\tif n > 1:\r\n\t\tprint \"conflict {} events in ({}, {})\".format(n, u, v)" }, { "alpha_fraction": 0.6434494256973267, "alphanum_fraction": 0.6592040061950684, "avg_line_length": 29.871795654296875, "blob_id": "9e0f9655796aca9ee45317fe941be0d90512bac6", "content_id": "40a9c253fd2b187ec92ff50dc6ae2b0a4f4257c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1206, "license_type": "no_license", "max_line_length": 142, "num_lines": 39, "path": "/programmingPearls_interviewPreparation/burnCpuWrapper.py", "repo_name": "gyom/miscCodeExercisesAndSingleUsage", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport subprocess\nimport math\nimport time\nimport re\n\nnrepsInternal = 100\nnreps = 10\nsizes = [int(math.pow(10,u)) for u in range(6, 9)]\nops = [\"exp\", \"log\", \"sqrt\", \"id\"]\nresults = {}\n\nfor rep in range(0, nreps):\n\tfor size in sizes:\n\t\tfor op in ops:\n\t\t\tstart = time.time()\n\t\t\tresult = subprocess.check_output([\"/Users/gyomalin/Documents/tmp/de_solace/tmp/entrevueGoogle/burnCpu\", str(size), str(nrepsInternal), op])\n\t\t\tend = time.time()\n\t\t\t#if not re.match((\"done with %s\" % op), result):\n\t\t\t#\tprint(\"Got a failure with (rep, size, op) = (%d, %d,%s). Result was %s.\" % (rep, size, op, result))\n\t\t\tresults[(rep, size, op)] = (end-start)\n\n\ndistilledResults = {}\nfor size in sizes:\n\tfor op in ops:\n\t\tmatches = [value for ((rep0, size0, op0), value) in results.items() if size0==size and op0==op]\n\t\tif len(matches) > 0:\n\t\t\taverageTime = sum(matches,0)/len(matches)\n\t\telse:\n\t\t\taverageTime = None\n\t\t# at this point we account for the fact that we ran the thing multiple times in C\n\t\tdistilledResults[(size, op)] = averageTime/nrepsInternal if averageTime else None\n\nfor op in ops:\n\tprint op\n\tfor size in sizes:\n\t\tprint \" %s : %f\" % (str(size).center(15), distilledResults[(size, op)])\n\n\n" }, { "alpha_fraction": 0.6157997250556946, "alphanum_fraction": 0.6404057741165161, "avg_line_length": 26.718563079833984, "blob_id": "720fb1bce1bee6d8d27b00d92a1d6c3baa3626ab", "content_id": "ac12078aa30112e5f36fb7c4f9b69b62a1b5c6e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4633, "license_type": "no_license", "max_line_length": 101, "num_lines": 167, "path": "/programmingPearls_interviewPreparation/consecutiveValuesToT.py", "repo_name": "gyom/miscCodeExercisesAndSingleUsage", "src_encoding": "UTF-8", "text": "\ndef minimalDifference(A,B):\n\t\n\t# catching errors\n\tif len(A)==0 or len(B)==0:\n\t\treturn None\n\t\n\tA = sorted(A)\n\tB = sorted(B)\n\t\n\t# initialization with first case for smoothness\n\t(i,j) = (0,0)\n\t(M,N) = (len(A), len(B))\n\tmindiff = float(\"inf\")\n\tif A[0] <= B[0]:\n\t\tprev = A[0]\n\t\tlastread = 'a'\n\t\ti+=1\n\telse:\n\t\tprev = B[0]\n\t\tlastread = 'b'\n\t\tj+=1\n\t\n\t# run the while loop until both are out\n\twhile ( i < M or j < N):\n\t\t# if they both have elements left, we need to decide from which we want to read\n\t\tif ( i < M and j < N):\n\t\t\tif ( A[i] <= B[j]):\n\t\t\t\tif lastread == 'b':\n\t\t\t\t\tmindiff = min(mindiff, A[i] - prev)\n\t\t\t\t\t#print \"A[%d] = %d, prev = %d\" % (i,A[i],prev)\n\t\t\t\tprev = A[i]\n\t\t\t\tlastread = 'a'\n\t\t\t\t#print \"reading %d\" % A[i] \n\t\t\t\ti+=1\n\t\t\telse:\n\t\t\t\tif lastread == 'a':\n\t\t\t\t\tmindiff = min(mindiff, B[j] - prev)\n\t\t\t\t\t#print \"B[%d] = %d, prev = %d\" % (j,B[j],prev)\n\t\t\t\tprev = B[j]\n\t\t\t\tlastread = 'b'\n\t\t\t\t#print \"reading %d\" % B[j] \n\t\t\t\tj+=1\n\t\telif ( i < M and j >= N):\n\t\t\tif lastread == 'b':\n\t\t\t\tmindiff = min(mindiff, A[i] - prev)\n\t\t\t\t#print \"A[%d] = %d, prev = %d\" % (i,A[i],prev)\n\t\t\tprev = A[i]\n\t\t\tlastread = 'a'\n\t\t\t#print \"reading %d\" % A[i] \n\t\t\ti+=1\n\t\telif ( i >= M and j < N):\n\t\t\tif lastread == 'a':\n\t\t\t\tmindiff = min(mindiff, B[j] - prev)\n\t\t\t\t#print \"B[%d] = %d, prev = %d\" % (j,B[j],prev)\n\t\t\tprev = B[j]\n\t\t\tlastread = 'b'\n\t\t\t#print \"reading %d\" % B[j] \n\t\t\tj+=1\n\treturn mindiff\n\ndef minimalDifferenceValidator(A,B):\n\tif len(A)==0 or len(B)==0:\n\t\treturn None\n\treturn min([abs(a-b) for a in A for b in B])\n\nimport random\ndef test_minimalDifference(m=20,n=20,R=1000):\n\tA = [ random.randint(-R, R) for u in range(0, m)]\n\tB = [ random.randint(-R, R) for u in range(0, n)]\n\tr = minimalDifference(A,B)\n\ttrue_r = minimalDifferenceValidator(A,B)\n\t#print str(sorted(A))\n\t#print str(sorted(B))\n\t#print \"r=%d, true_r=%d\" % (r, true_r)\n\tassert(r == true_r)\n\n#test_minimalDifference()\n#minimalDifference([1,1,2,6,7,15], [4,4,11,20])\n\ndef cumsum(L, skipZero=False):\n\tif skipZero:\n\t\tR = []\n\telse:\n\t\tR = [0]\n\tacc = 0\n\tfor e in L:\n\t\tR.append(acc+e)\n\t\tacc+=e\n\treturn R\n\ndef findClosestSequenceSumToValue(L, targetValue):\n\t\n\tif len(L)==0:\n\t\treturn float(\"inf\")\n\tif len(L)==1:\n\t\treturn abs(L[0]-targetValue)\n\t\n\t# L[h-1] being the last element\n\t(l,m,h) = (0, len(L)/2, len(L))\n\t\n\t# The two recursive calls with short circuits\n\t# because we know we can't get better than 0.\n\t# Just for fun, anticipating datasets where this happens.\n\tbestBefore = findClosestSequenceSumToValue(L[l:m], targetValue)\n\t#print \"recursive call bestBefore on L[%d:%d] found %d\" % (l,m, bestBefore)\n\tif bestBefore == 0:\n\t\treturn bestBefore\n\tbestAfter = findClosestSequenceSumToValue(L[m:h], targetValue)\n\t#print \"recursive call bestAfter on L[%d:%d] found %d\" % (m,h, bestAfter)\n\tif bestAfter == 0:\n\t\treturn bestAfter\n\t\n\tcumsumBefore = cumsum(reversed(L[l:m]), skipZero=True)\n\tcumsumAfter = cumsum(L[m:h], skipZero=True)\n\t\n\t# That could happen, but it should have been covered by the recursive calls\n\t# if that could be the situation. Anyways, adding this just in case.\n\tif targetValue in cumsumBefore:\n\t\treturn 0\n\telif targetValue in cumsumAfter:\n\t\treturn 0\n\t\n\treorganizedCumsumBefore = [u - targetValue for u in cumsumBefore]\n\treorganizedCumsumAfter = [-u for u in cumsumAfter]\n\tminDifferencesBetweenTheCumsums = minimalDifference(reorganizedCumsumBefore, reorganizedCumsumAfter)\n\t#print \"minDifferencesBetweenTheCumsums got us %d\" % (minDifferencesBetweenTheCumsums,)\n\t\n\treturn min([bestBefore, bestAfter, minDifferencesBetweenTheCumsums])\n\n\ndef findClosestSequenceSumToValueValidator(L, targetValue):\n\t\n\tif len(L)==0:\n\t\treturn None\n\tif len(L)==1:\n\t\treturn abs(L[0]-targetValue)\n\t\n\t#mindiff = min([abs(u-targetValue) for u in L])\n\tcs = cumsum(L, skipZero=True)\n\t#print str(cs)\n\tmindiff = float(\"inf\")\n\tfor i in range(0, len(cs)-1):\n\t\tfor j in range(i+1, len(cs)):\n\t\t\t# debug\n\t\t\t#if mindiff > abs(cs[j]-cs[i]-targetValue):\n\t\t\t#\tprint \"found best sequence total between [%d,%d) : %d\" % (i,j,cs[j]-cs[i])\n\t\t\tmindiff = min(mindiff, abs(cs[j]-cs[i]-targetValue))\n\treturn mindiff\n\n\n# findClosestSequenceSumToValueValidator([1,2,-40,23,10,23], 17)\n# findClosestSequenceSumToValue([1,2,-40,23,10,23], 17)\n\nnreps = 100\n(minval, maxval) = (-100000000,100000000)\nsize = 1000\n#for r in range(0, nreps):\nfor size in range(1, 1000):\n\tE = [random.randint(minval, maxval) for u in range(0,size)]\n\ttarget = random.randint(minval, maxval)\n\tresult = findClosestSequenceSumToValue(E, target)\n\texpected = findClosestSequenceSumToValueValidator(E, target)\n\tprint \"result=%d, expected=%d\" % (result, expected)\n\tif result != expected:\n\t\tprint str(E)\n\t\tprint target\n\tassert (result == expected)\n\n\n\n" }, { "alpha_fraction": 0.44121846556663513, "alphanum_fraction": 0.5397430062294006, "avg_line_length": 16.221311569213867, "blob_id": "472e3e262d7cd36b51f8280476c06ce61fb2327f", "content_id": "9fd7c633faa54f69d8a4af76a28f122ef1e72847", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2101, "license_type": "no_license", "max_line_length": 61, "num_lines": 122, "path": "/programmingPearls_interviewPreparation/burnCpu.c", "repo_name": "gyom/miscCodeExercisesAndSingleUsage", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nvoid idOnArray(double * E, long N) {\n\tlong i=0;\n\tfor(i=0; i<N;++i) {\n\t\tE[i] = E[i];\n\t}\n\treturn;\n}\n\nvoid sqrtOnArray(double * E, long N) {\n\tlong i=0;\n\tfor(i=0; i<N;++i) {\n\t\tE[i] = sqrt(E[i]);\n\t}\n\treturn;\n}\n\nvoid logOnArray(double * E, long N) {\n\tlong i=0;\n\tfor(i=0; i<N;++i) {\n\t\tE[i] = log(E[i]);\n\t}\n\treturn;\n}\n\nvoid exponentialOnArray(double * E, long N) {\n\tlong i=0;\n\tfor(i=0; i<N;++i) {\n\t\tE[i] = exp(E[i]);\n\t}\n\treturn;\n}\n\nvoid resetArray(double * E, long N) {\n\tlong i=0;\n\tfor(i=0; i<N;++i) {\n\t\tE[i] = (double)i;\n\t}\n}\n\nint main(int argc, char *argv[]) {\n\t/*\n\t\tburnCpu niter fname\n\t*/\n\n\tif (argc < 4) {\n\t\tprintf(\"We need two arguments : size niter fname \\n\");\n\t\treturn 1;\n\t}\n\n\tlong N = atol(argv[1]);\n\tif (N<=0) {\n\t\tprintf(\"size has to be positive.\");\n\t}\n\n\tlong niter = atol(argv[2]);\n\tif (niter<=0) {\n\t\tprintf(\"niter has to be positive.\");\n\t}\n\n\tdouble * E = (double*)malloc(sizeof(double)*N);\n\tresetArray(E, N);\n\t\n\tchar * fname = argv[3];\n\t\n\tint r=0;\n\tif (strcmp(fname, \"exp\") == 0) {\n\t\tfor(r=0; r<niter;++r) {\n\t\t\tresetArray(E, N);\n\t\t\texponentialOnArray(E, N);\n\t\t}\n\t\tprintf(\"done with exp\\n\");\n\t} else if (strcmp(fname, \"log\") == 0) {\n\t\tfor(r=0; r<niter;++r) {\n\t\t\tresetArray(E, N);\n\t\t\tlogOnArray(E, N);\n\t\t}\n\t\tprintf(\"done with log\\n\");\n\t} else if (strcmp(fname, \"sqrt\") == 0) {\n\t\tfor(r=0; r<niter;++r) {\n\t\t\tresetArray(E, N);\n\t\t\tsqrtOnArray(E, N);\n\t\t}\n\t\tprintf(\"done with sqrt\\n\");\n\t} else if (strcmp(fname, \"id\") == 0) {\n\t\tfor(r=0; r<niter;++r) {\n\t\t\tresetArray(E, N);\n\t\t\tidOnArray(E, N);\n\t\t}\n\t\tprintf(\"done with id\\n\");\n\t} else {\n\t\tprintf(\"nothing done\\n\");\n\t}\n\n\treturn 0;\n}\n\n/*\n\nszkmtk-mba:entrevueGoogle gyomalin$ python burnCpuWrapper.py \n\nexp\n 1000000 : 0.011482\n 10000000 : 0.114639\n 100000000 : 1.176501\nlog\n 1000000 : 0.022984\n 10000000 : 0.230018\n 100000000 : 2.310665\nsqrt\n 1000000 : 0.011671\n 10000000 : 0.115764\n 100000000 : 1.158500\nid\n 1000000 : 0.006451\n 10000000 : 0.063060\n 100000000 : 0.631304\n\n*/\n" }, { "alpha_fraction": 0.36946702003479004, "alphanum_fraction": 0.40198734402656555, "avg_line_length": 25.25, "blob_id": "dc66edbca742ce76e51f3346c4072c51754cb23f", "content_id": "6dfaad0721fdd533e823e04e996e05ea87d019f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1107, "license_type": "no_license", "max_line_length": 96, "num_lines": 40, "path": "/programmingPearls_interviewPreparation/longuestSubsequence.py", "repo_name": "gyom/miscCodeExercisesAndSingleUsage", "src_encoding": "UTF-8", "text": "\r\nC[(i,j)] = \r\n\t0 if i==0 or j==0\r\n\tC[(i-1,j-1)] + 1 if A[i] == B[j]\r\n\tmax(C[i-1,j], C[i, j-1]) otherwise\r\n\t\r\n\r\nA = \"absdsbebnfjdsfdbsnabd\"\r\nB = \"asdjbabsbrbebdssbb\"\r\n\t\r\nC = dict( [((i,-1), 0) for i in range(-1, len(A))] + [((-1,j), 0) for j in range(-1, len(B))] )\r\n\r\nfor i in range(0, len(A)):\r\n\tfor j in range(0, len(B)):\r\n\t\tC[(i,j)] = C[(i-1, j-1)] + 1 if A[i] == B[j] else max( C[(i-1,j)], C[(i,j-1)])\r\n\r\n\r\n################################################\t\t\r\n\t\t\r\n# eurque ! marche tout croche, doit etre revu\r\n\r\nD = \"\"\r\ni=0\r\nj=0\r\n\r\nwhile i < len(A) and j < len(B):\r\n\tif C[(i,j)] == C[(i-1,j-1)] + 1:\r\n\t\tD = D + A[i]\r\n\t\tprint \"appending {} to solution at ({},{})\".format(A[i],i,j)\r\n\t\ti=i+1\r\n\t\tj=j+1\r\n\telif C[(i,j)] == C[(i,j-1)] and j + 1 < len(B):\r\n\t\tprint \"advancing j because C[({},{})] == C[({},{})]\".format(i,j,i,j-1)\r\n\t\tj=j+1\r\n\telif C[(i,j)] == C[(i-1,j)] and i + 1 < len(A):\r\n\t\tprint \"advancing i because C[({},{})] == C[({},{})]\".format(i,j,i-1,j)\r\n\t\ti=i+1\r\n\telse:\r\n\t\tprint \"something is wrong\"\r\n\r\n################################################\t\t\r\n\t\r\n\r\n\t\r\n\r\n\r\n\t" }, { "alpha_fraction": 0.6089109182357788, "alphanum_fraction": 0.6398515105247498, "avg_line_length": 21.38888931274414, "blob_id": "f4df38526c3547b929ade07f2c5a1c81b8539c80", "content_id": "fef872c38397a43f32340a2b81a33830d60dd070", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 808, "license_type": "no_license", "max_line_length": 96, "num_lines": 36, "path": "/asymptoticBehaviorForParticularRecursiveFormula/partialSortCheat.py", "repo_name": "gyom/miscCodeExercisesAndSingleUsage", "src_encoding": "UTF-8", "text": "\nimport math\nimport numpy\nimport pylab\n\ndef averageIndices(s, T):\n\tlow = int(math.floor(s))\n\thigh = int(math.ceil(s))\n\tif (low==high):\n\t\treturn T[low]\n\telse:\n\t\tdlow = abs(s-low)\n\t\tdhigh= abs(s-high)\n\t\treturn dhigh/(dlow+dhigh)*T[low] + dlow/(dlow+dhigh)*T[high]\n\nN = 10000000\nstartOffset = 1\nT = [u for u in range(0,startOffset)] + [0 for u in range(0,N-startOffset)]\n\nfor n in range(startOffset,N):\n\ts = math.sqrt(n)\n\tT[n] = 6*n + 3*s*averageIndices(s, T)\n\n\nx = numpy.arange(0,N)\ny = numpy.array(T)\npylab.plot(x,y)\npylab.show()\n\nnlogn = numpy.array([1 for u in range(0,5)] + [u*math.log(u) for u in range (5,N)])\nnloglogn = numpy.array([1 for u in range(0,5)] + [u*math.log(math.log(u)) for u in range (5,N)])\n\ny_ratio = y / nlogn\ny_ratio2 = y / nloglogn\n\n#pylab.plot(x,y_ratio)\n#pylab.plot(x,y_ratio2)\n\n" }, { "alpha_fraction": 0.6651162505149841, "alphanum_fraction": 0.6801033616065979, "avg_line_length": 42.95454406738281, "blob_id": "38bdf09aa13d92d1053bcabdfa09525799da1dfc", "content_id": "e676e205b9893a9d3676ccec163c1ca3cb33276d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1935, "license_type": "no_license", "max_line_length": 110, "num_lines": 44, "path": "/programmingPearls_interviewPreparation/binarySearchVerifier.py", "repo_name": "gyom/miscCodeExercisesAndSingleUsage", "src_encoding": "UTF-8", "text": "\nimport subprocess\nimport random\n\ndef runTestOnce(minval, maxval, n, wantmatch):\n\tE = list(set([random.randint(minval, maxval) for u in range(0,n)]))\n\tE.sort()\n\t#print (minval, maxval, n, wantmatch)\n\t#print str(E)\n\tif wantmatch:\n\t\tvalue = E[random.randint(0,len(E)-1)]\n\t\texpectedResultForPosition = E.index(value)\n\telse:\n\t\t# purposefully picking an innocent value that's not in the set\n\t\tmissingValues = list(set(range(minval, maxval)).difference(set(E)))\n\t\tif len(missingValues) == 0:\n\t\t\tprint \"You've set up something wrong, because all the values are in the list.\"\n\t\t\tvalue = -abs(minval)*2 - 1;\n\t\telse:\n\t\t\tvalue = missingValues[random.randint(0,len(missingValues)-1)]\n\t\texpectedResultForPosition = -1\n\t#cmdlineExpansionOfArray = str(E).replace('[', '').replace(']', '').replace(',', ' ')\n\tpath = \"/Users/gyomalin/Documents/tmp/de_solace/tmp/entrevueGoogle\"\n\t#result = subprocess.check_output([\"%s/binarySearch\" % (path,), n] + E)\n\t#print str([\"%s/binarySearch\" % (path,), str(n)] + [str(e) for e in E])\n\tresult = subprocess.check_output([\"%s/binarySearch2\" % (path,), str(value)] + [str(e) for e in E])\n\tif int(expectedResultForPosition) != int(result) :\n\t\tprint \"Looking for %d in %s. Got %s instead of %d\" % (value, str(E), result, int(expectedResultForPosition))\n\treturn (expectedResultForPosition, result)\n\nif __name__ == \"__main__\":\n\ttestResults = {}\n\tnreps = 10\n\t(minval, maxval) = (-100, 100)\n\t(okCount, errorCount) = (0, 0)\n\tfor rep in range(0, nreps):\n\t\tfor n in range(1, 100):\n\t\t\twantmatch = True #random.random() > 0.5\n\t\t\t(expectedResultForPosition, result) = runTestOnce(minval, maxval, n, wantmatch)\n\t\t\ttestResults[(rep, minval, maxval, wantmatch, expectedResultForPosition)] = result\n\t\t\tif int(expectedResultForPosition) != int(result):\n\t\t\t\t(okCount, errorCount) = (okCount, errorCount + 1)\n\t\t\telse:\n\t\t\t\t(okCount, errorCount) = (okCount + 1, errorCount)\n\tprint \"okCount = %s, errorCount = %s\" % (okCount, errorCount)\n" }, { "alpha_fraction": 0.5395799875259399, "alphanum_fraction": 0.5961228013038635, "avg_line_length": 24.70833396911621, "blob_id": "62c57625d51d1824b8c052242f95047ae266d341", "content_id": "e084279f4ece2226ef7f4da6df098f8df193b9af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1238, "license_type": "no_license", "max_line_length": 122, "num_lines": 48, "path": "/programmingPearls_interviewPreparation/telephoneKnights.py", "repo_name": "gyom/miscCodeExercisesAndSingleUsage", "src_encoding": "UTF-8", "text": "# 1 2 3\n# 4 5 6\n# 7 8 9\n# . 0 .\n\ndigits = [0,1,2,3,4,5,6,7,8,9]\nneighbours = {0:[4,6], 1:[6,8], 2:[7,9], 3:[4,8], 4:[3,9,0], 5:[], 6:[1,7,0], 7:[2,6], 8:[1,3], 9:[4,2]}\n\n\n#[len([key for (key,S) in neighbours.items() if e in S]) for e in set(digits).difference([5])]\n\n\ndef generateWords(start, n, cache={}):\n\tif n==0:\n\t\treturn []\n\telif n==1:\n\t\treturn [[start]]\n\telif cache.has_key((start, n)):\n\t\treturn cache[(start, n)]\n\telse:\n\t\t# actually compute the thing\n\t\tV = []\n\t\tfor e in neighbours[start]:\n\t\t\tfor rest in generateWords(e, n-1, cache):\n\t\t\t\tV.append([start] + rest)\n\t\tcache[(start, n)] = V\n\t\treturn V\n\ngenerateWords(1, 10)\n\ndef generateWords2(start, n, cache={}):\n\tif n==0:\n\t\treturn []\n\telif n==1:\n\t\treturn [[start]]\n\telif cache.has_key((start, n)):\n\t\treturn cache[(start, n)]\n\telse:\n\t\t# actually compute the thing\n\t\tV = [[start] + rest for rest in reduce( lambda A,B:A+B, [generateWords2(w, n-1, cache) for w in neighbours[start]], [])]\n\t\t# wrong, forgets to flatten\n\t\t#V = [[start] + rest for rest in [generateWords2(w, n-1, cache) for w in neighbours[start]]]\n\t\t# bad syntax\n\t\t#V = [[start] + rest for rest in generateWords2(w, n-1, cache) for w in neighbours[start]]\n\t\tcache[(start, n)] = V\n\t\treturn V\n\ngenerateWords2(1, 10)\n\n\n\n\n" }, { "alpha_fraction": 0.5681234002113342, "alphanum_fraction": 0.5895458459854126, "avg_line_length": 20.849056243896484, "blob_id": "ddb064ae54a2a19ab5cead10f397581f2bcbda4e", "content_id": "1fd14f31fca9c8301434b0e9982dee0c302320ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1167, "license_type": "no_license", "max_line_length": 79, "num_lines": 53, "path": "/programmingPearls_interviewPreparation/mergesort.py", "repo_name": "gyom/miscCodeExercisesAndSingleUsage", "src_encoding": "UTF-8", "text": "\nimport random\n\ndef merge(A,B):\n\tR = []\n\ti=0;\n\tj=0;\n\tN=len(A);\n\tM=len(B);\n\twhile(i+j<N+M):\n\t\tif j==M or (i<N and A[i] <= B[j]):\n\t\t\tR.append(A[i])\n\t\t\t#print \"adding A[{}]={}, setting i={}\".format(i, A[i], i+1)\n\t\t\ti=i+1\n\t\telse:\n\t\t\tR.append(B[j])\n\t\t\t#print \"adding B[{}]={}, setting j={}\".format(j, B[j], j+1)\n\t\t\tj=j+1\n\treturn R\n\ndef partition(E,pivot):\n\treturn ([u for u in E if u <= pivot], [u for u in E if u > pivot])\n\n\ndef mergesort(E):\n\tN = len(E)\n\tif N==0 or N==1:\n\t\treturn E\n\telse:\n\t\t(A,B) = partition(E, E[random.randint(0,N-1)])\n\t\tif len(A) == 0:\n\t\t\t#print \"We hit the special empty array condition with the other array being\"\n\t\t\t#print B\n\t\t\treturn merge([B[0]], mergesort(B[1:]))\n\t\telif len(B) == 0:\n\t\t\t#print \"We hit the special empty array condition with the other array being\"\n\t\t\t#print A\n\t\t\treturn merge([A[0]], mergesort(A[1:]))\n\t\telse:\n\t\t\treturn merge(mergesort(A), mergesort(B))\n\nniter=100\nN=1000\nfor i in range(0, niter):\n\tE = [random.random() for w in range(0,N)]\n\tresult = mergesort(E)\n\treference = sorted(E)\n\tif not (result == reference):\n\t\tprint \"Error.\"\n\t\tprint result\n\t\tprint reference\n\t\tbreak\n\telse:\n\t\tprint \"passed round {}\".format(i)\n\t\t\n\t\t\n\t\t" }, { "alpha_fraction": 0.40748441219329834, "alphanum_fraction": 0.5051975250244141, "avg_line_length": 20.81818199157715, "blob_id": "223cd786e7b4da2af094869dfe672b25d5f5f0e4", "content_id": "cf18608dd74bda0c74d21c9d1b4e4a590b4dfa16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 481, "license_type": "no_license", "max_line_length": 67, "num_lines": 22, "path": "/programmingPearls_interviewPreparation/highestConsecutiveSum.py", "repo_name": "gyom/miscCodeExercisesAndSingleUsage", "src_encoding": "UTF-8", "text": "\ndef highestConsecutiveSum(E):\n\tn = len(E)\n\tif n==0:\n\t\treturn 0\n\tP = [0 for i in range(0, n)]\n\tP[0] = E[0]\n\tfor i in range(1,n):\n\t\tP[i] = E[i] + max(0, P[i-1])\n\t\n\tQ = [0 for i in range(0, n)]\n\tQ[n-1] = E[n-1]\n\tfor i in reversed(range(0,n-1)):\n\t\tQ[i] = E[i] + max(0, Q[i+1])\n\t\n\tS = [0 for i in range(0, n)]\n\tfor i in range(0,n-1):\n\t\tS[i] = max(0, P[i]) + max(0, Q[i+1])\n\tS[n-1] = max(0, P[n-1])\n\t\t\n\treturn max(S)\n\nhighestConsecutiveSum([31, -41, 59, 26, -53, 58, 97, -93, -23, 84])\n" }, { "alpha_fraction": 0.4615384638309479, "alphanum_fraction": 0.5120879411697388, "avg_line_length": 12.21875, "blob_id": "ca2f726c23baa217b79da5d13ef796b47e0b0cb2", "content_id": "86427027025784dd14b581651cb439eda1df68dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 455, "license_type": "no_license", "max_line_length": 56, "num_lines": 32, "path": "/programmingPearls_interviewPreparation/flattenList.py", "repo_name": "gyom/miscCodeExercisesAndSingleUsage", "src_encoding": "UTF-8", "text": "\r\ndef flattenByOne(E):\r\n\tn = len(E)\r\n\tif n==0:\r\n\t\treturn E\r\n\tif n==1:\r\n\t\treturn E[0]\r\n\telse:\r\n\t\treturn reduce(lambda acc,L: acc+L, E, [])\r\n\r\nE = [[1,2,32], [2,2,[23,24]], [4,[[23],2],6,[7],3]]\r\n\r\nflattenByOne(E)\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef flattenAll(E):\r\n\tif type(E) is list:\r\n\t\tn = len(E)\r\n\t\tif n==0:\r\n\t\t\treturn []\r\n\t\tif n==1:\r\n\t\t\treturn flattenAll(E[0])\r\n\t\telse:\r\n\t\t\treturn reduce(lambda acc,L: acc+flattenAll(L), E, [])\r\n\telse:\r\n\t\treturn [E]\r\n\t\t\r\n\r\nflattenAll(E)" }, { "alpha_fraction": 0.4868735074996948, "alphanum_fraction": 0.5274463295936584, "avg_line_length": 15.945945739746094, "blob_id": "c6dc11b2233faf4487e21beb79f38aa8d97264cd", "content_id": "9db17095d8f86856040dd2393474f152c88b91dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1257, "license_type": "no_license", "max_line_length": 55, "num_lines": 74, "path": "/programmingPearls_interviewPreparation/binarySearch2.c", "repo_name": "gyom/miscCodeExercisesAndSingleUsage", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n\nint binarySearch(int * L, int N, int value) {\n\t\n\tif (N==0) {\n\t\treturn -1;\n\t}\n\t\n\t/* with N being the number of elements present in L */\n\tint low = 0, high = N-1;\n\tint mid;\n\n\twhile(low < high) {\n\t\t\n\t\tmid = (high-low)/2 + low;\n\t\t//mid = (low+high)/2;\n\t\t\n\t\tif (L[mid] < value) {\n\t\t\tlow = mid + 1;\n\t\t} else if (L[mid] > value) {\n\t\t\thigh = mid - 1;\n\t\t} else if (L[mid] == value) {\n\t\t\treturn mid;\n\t\t}\n\t}\n\t\n\tif (L[low] == value) {\n\t\treturn low;\n\t} else {\n\t\treturn -1;\n\t}\n}\n\nint main ( int argc, char *argv[]) {\n\n\tif (argc >= 3) {\n\n\t\t// remember that argv[0] is the executable's name.\n\t\tint value = atoi(argv[1]);\n\t\tint N = argc-2;\n\t\tint * L = (int*)malloc(N*sizeof(int));\n\t\t\n\t\tint i;\n\t\tfor (i=0; i<N; i++) {\n\t\t\tL[i] = atoi(argv[2+i]);\n\t\t}\n\t\tprintf(\"%d\", binarySearch(L,N,value));\n\t} else {\n\t\tprintf(\"ERROR. Wrong number of arguments.\\n\");\n\t}\n\n\t/*\n\tint A0[] = {};\n\tint N0 = 0;\n\n\tint A1[] = {0,1,2,3,4};\n\tint N1 = 5;\n\t\n\tif (binarySearch(A0, N0, 42) != -1)\n\t\tprintf(\"Failed on A0.\");\n\n\tif (binarySearch(A1, N1, 2) != 2)\n\t\tprintf(\"Failed on A1 to find 2.\");\n\n\tif (binarySearch(A1, N1, 5) != -1)\n\t\tprintf(\"Failed on A1 to find 5.\");\n\n\tif (binarySearch(A1, N1, -1) != -1)\n\t\tprintf(\"Failed on A1 to find -1.\");\n\t*/\n\n\treturn 0;\n}\n\n\n\n" }, { "alpha_fraction": 0.5717505812644958, "alphanum_fraction": 0.6168294548988342, "avg_line_length": 27.516128540039062, "blob_id": "fb64720cbcbc0dc86928d08fdf7cd1fc67d5e862", "content_id": "aa104cbaeefba03d252228b097919238e738ebdf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2662, "license_type": "no_license", "max_line_length": 105, "num_lines": 93, "path": "/programmingPearls_interviewPreparation/immutableBinomialHeap.py", "repo_name": "gyom/miscCodeExercisesAndSingleUsage", "src_encoding": "UTF-8", "text": "\n\nclass Node():\n\t# value\n\t# children : a list\n\tdef __init__(self, value, children=[]):\n\t\tself.value = value\n\t\tself.children = children\n\nclass BinomialTree():\n\t# root of type Node\n\t# weight of type integer\n\tdef __init__(self, BT1=None, BT2=None):\n\t\tif BT1 and BT2:\n\t\t\t(w1,w2) = (BT1.weight, BT2.weight)\n\t\t\tassert (w1==w2)\n\t\t\tself.weight = w1+w2\n\t\t\t(m1, m2) = (BT1.getMin(), BT2.getMin())\n\t\t\tif m1 > m2:\n\t\t\t\tself.root = Node(m2, BT2.root.children + [BT1])\n\t\t\telse:\n\t\t\t\tself.root = Node(m1, BT1.root.children + [BT2])\n\t\telif BT1:\n\t\t\t# we'll assume here that BT1 is a Node and not a BinomialTree\n\t\t\tself.root = BT1\n\t\t\tself.weight = 1 + (len(BT1.children) if BT1.children else 0)\n\t\telif BT2:\n\t\t\t# we'll assume here that BT2 is a Node and not a BinomialTree\n\t\t\tself.root = BT2\n\t\t\tself.weight = 1 + (len(BT2.children) if BT2.children else 0)\n\tdef getMin(self):\n\t\treturn self.root.value\n\tdef toString(self):\n\t\tstart = \"[\" + str(self.root.value) + \" : \"\n\t\tmiddle = reduce(lambda acc,e: acc + \" \" + e.toString(), self.root.children, \"\")\n\t\tend = \"]\"\n\t\treturn start + middle + end\n\n\na1 = Node(3)\na2 = Node(5)\nb1 = BinomialTree(a1)\nb2 = BinomialTree(a2)\na3 = Node(2)\na4 = Node(19)\nb3 = BinomialTree(a3)\nb4 = BinomialTree(a4)\n\ne = BinomialTree(BinomialTree(b1,b2), BinomialTree(b3,b4))\nprint e.toString()\n\n\ndef packByTwo(L):\n\tR = []\n\tleft = [] if len(L)%2==0 else [L[-1]]\n\ti=0\n\twhile(i+1 < len(L)):\n\t\tR.append( (L[i], L[i+1]) )\n\t\ti += 2\n\treturn (R, left)\n\nassert(packByTwo([]) == ([], []))\nassert(packByTwo([1]) == ([], [1]))\nassert(packByTwo([1,2,3]) == ( [(1,2)], [3] ) )\nassert(packByTwo([1,2,3,4]) == ( [(1,2), (3,4)], [] ) )\nassert(packByTwo([1,2,3,4,5]) == ( [(1,2), (3,4)], [5] ) )\n\n\n\nclass BinomialHeap():\n\tdef __init__(self, *BTS):\n\t\t#self.table = {}\n\t\tself.table = dict( (pow(2,p), []) for p in range(0, 32))\n\t\t#self.promotionThreshold = kwargs.promotionThreshold if kwargs.has_key(\"promotionThreshold\") else 2\n\t\tfor bt in BTS:\n\t\t\tself.table[bt.weight] = [bt] + (self.table[bt.weight] if self.table.has_key(bt.weight) else [])\n\t\tself.__mutableOpReduceTable__()\n\t#\n\tdef __mutableOpReduceTable__(self):\n\t\tfor k in sorted(self.table.keys()):\n\t\t\tif len(self.table[k]) >= 2:\n\t\t\t\t(toPromote, remaining) = packByTwo(self.table[k])\n\t\t\t\tself.table[k] = remaining\n\t\t\t\tnewBinomialTrees = [BinomialTree(BT1, BT2) for (BT1, BT2) in toPromote]\n\t\t\t\tself.table[2*k] = self.table[2*k] + newBinomialTrees if self.table.has_key(2*k) else newBinomialTrees\n\n\nimport random\n\nL = [ random.randint(0,1000) for i in range(0,20) ]\n\nBTS = [ BinomialTree(Node(e)) for e in L]\nBH = BinomialHeap(*BTS)\n\n[ BH.table[pow(2,p)][0].getMin() for p in range(0, 32) if len(BH.table[pow(2,p)])>0]\n\n\n\n\n\n\n\n\t" }, { "alpha_fraction": 0.6550680994987488, "alphanum_fraction": 0.6777609586715698, "avg_line_length": 20.322580337524414, "blob_id": "fe521e1ece994aa948dd4098b54838eb4db1e94f", "content_id": "fe1730fee67181e8faf38fec58fd93bc71411b12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 661, "license_type": "no_license", "max_line_length": 65, "num_lines": 31, "path": "/programmingPearls_interviewPreparation/reverseLinkedList.py", "repo_name": "gyom/miscCodeExercisesAndSingleUsage", "src_encoding": "UTF-8", "text": "\nclass Node:\n\tdef __init__(self, value, next=None):\n\t\tself.value = value\n\t\tself.next = next\n\tdef toList(self):\n\t\treturn [self.value] + (self.next.toList() if self.next else [])\n\ndef reverseLinkedListMutable(head):\n\tif not head:\n\t\treturn head\n\telse:\n\t\tprevious = None\n\t\twhile (head.next):\n\t\t\tcurrent = head\n\t\t\thead = head.next\n\t\t\tcurrent.next = previous\n\t\t\tprevious = current\n\t\thead.next = previous\n\t\treturn head\n\nA = Node(1, Node(2, Node(3)))\nA.toList()\n\nR = reverseLinkedListMutable(A)\nR0 = reverseLinkedListMutable(None)\nR1 = reverseLinkedListMutable(Node(1))\nR2 = reverseLinkedListMutable(Node(1, Node(2)))\n\nR0 == None\nR1.toList() == [1]\nR2.toList() == [2,1]" }, { "alpha_fraction": 0.6041206121444702, "alphanum_fraction": 0.6512511968612671, "avg_line_length": 34.67192459106445, "blob_id": "b827f3020cd481d99e2f00dc3a29a7ca846b0623", "content_id": "c7f1cd249e428bf0032e9b31f32de1965b338293", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11309, "license_type": "no_license", "max_line_length": 148, "num_lines": 317, "path": "/stockScraping/stockMessingAround.py", "repo_name": "gyom/miscCodeExercisesAndSingleUsage", "src_encoding": "UTF-8", "text": "# http://finance.yahoo.com/q/hp?s=GE&a=00&b=2&c=1962&d=01&e=9&f=2012&g=d&z=66&y=66\n# http://finance.yahoo.com/q/hp?s=GE&a=00&b=2&c=1962&d=01&e=9&f=2012&g=d&z=66&y=132\n# http://finance.yahoo.com/q/hp?s=GE&a=00&b=2&c=1962&d=01&e=9&f=2012&g=d&z=66&y=198\n\nimport httplib\nimport re\n\n# http://stackoverflow.com/questions/754593/source-of-historical-stock-data\n# \tsn = TICKER\n# \ta = fromMonth-1\n# \tb = fromDay (two digits)\n# \tc = fromYear\n# \td = toMonth-1\n# \te = toDay (two digits)\n# \tf = toYear\n# \tg = d for day, m for month, y for yearly\n\ndef getHistoricalStockData(quoteName, startYear, endYear, freq='d'):\n\turl = \"/table.csv?s=%s&d=11&e=31&f=%s&g=%s&a=0&b=01&c=%s&ignore=.csv\" % (quoteName, endYear, freq, startYear)\n\tconn = httplib.HTTPConnection(\"ichart.finance.yahoo.com\")\n\tconn.request(\"GET\",url)\n\tres = conn.getresponse()\n\tif res.status != 200:\n\t\tprint res.status, res.reason\n\t\treturn None\n\telse:\n\t\tdata = res.read()\n\t\t# 1996-04-15,35.75,36.00,30.00,32.25,79219200,1.34\\n\n\t\t# 1996-04-12,25.25,43.00,24.50,33.00,408720000,1.38\\n\n\t\tlineRegexp = re.compile(r\"^(.*?),(.*?),(.*?),(.*?),(.*?),(.*?),(.*?)$\")\n\t\tresult = []\n\t\tfor line in data.split(\"\\n\"):\n\t\t\tlineStructure = lineRegexp.match(line)\n\t\t\tif lineStructure:\n\t\t\t\tif lineStructure.group(1) == 'Date':\n\t\t\t\t\t# it's the header, so skip it\n\t\t\t\t\tcontinue\n\t\t\t\tdecomposedDataForLine = {'date': lineStructure.group(1),\n\t\t\t\t\t\t\t\t\t\t 'open': float(lineStructure.group(2)),\n\t\t\t\t\t\t\t\t\t\t 'high': float(lineStructure.group(3)),\n\t\t\t\t\t\t\t\t\t\t 'low': float(lineStructure.group(4)),\n\t\t\t\t\t\t\t\t\t\t 'close': float(lineStructure.group(5)),\n\t\t\t\t\t\t\t\t\t\t 'volume': int(lineStructure.group(6)),\n\t\t\t\t\t\t\t\t\t\t 'adjclose': float(lineStructure.group(7))}\n\t\t\t\tresult.append(decomposedDataForLine)\n\t\treturn result\n\nD = getHistoricalStockData(\"YHOO\", 2005, 2012, 'm')\n\n# conn = httplib.HTTPConnection(\"ichart.finance.yahoo.com\")\n# conn.request(\"GET\",\"/table.csv?s=YHOO&d=0&e=28&f=2010&g=d&a=3&b=12&c=1996&ignore=.csv\")\n# res = conn.getresponse()\n# print res.status, res.reason\n# data = res.read()\n\n\n# This whole thing is just a run-once section to distill the list of stock names from a document.\n\nf = open('/Users/gyomalin/Dropbox/programmation/stockScraping/sp500hst.txt', 'r')\nstockNameRegexp = re.compile(r\"^.*?,(.*?),.*\")\naccum = set([])\nfor line in f.read().split(\"\\n\"):\n\t# 20091113,SAI,18.38,18.49,18.22,18.45,19189\n\tm = stockNameRegexp.match(line)\n\tif m:\n\t\taccum = accum.union([m.group(1)])\nf.close()\n\nf = open('/Users/gyomalin/Dropbox/programmation/stockScraping/allStockNames.txt', 'w')\nfor stockName in sorted(list(accum)):\n\tf.write(stockName + \"\\n\")\n\nf.close()\n\n###################################################\n# read the data back into Python from the file after it's been distilled\n\nf = open('/Users/gyomalin/Dropbox/programmation/stockScraping/allStockNames.txt', 'r')\nallStockNames = [name for name in f.read().split(\"\\n\") if not (name == '')]\nf.close()\n\n######################################################\n\npool = redis.ConnectionPool(host='localhost', port=6379, db=0)\nr = redis.Redis(connection_pool=pool)\n\n# {'volume': 25529100, 'high': 38.19, 'adjclose': 11.9, 'low': 22.87, 'date': '2001-02-01', 'close': 23.81, 'open': 37.5},\n\nstockName = \"YHOO\"\nfor e in getHistoricalStockData(stockName, 1950, 2012, 'd'):\n\tfields = ['volume', 'high', 'adjclose', 'low', 'close', 'open']\n\tfor field in fields:\n\t\tr.set(\"%s:%s:%s\" % (stockName, e['date'], field), e[field])\n\t\nfor stockName in allStockNames:\n\tD = getHistoricalStockData(stockName, 1950, 2012, 'd')\n\tif D:\n\t\tfor e in D:\n\t\t\tfields = ['volume', 'high', 'adjclose', 'low', 'close', 'open']\n\t\t\tfor field in fields:\n\t\t\t\tr.set(\"%s:%s:%s\" % (stockName, e['date'], field), e[field])\n\t\tprint \"got data for %s\" % (stockName, )\n\telse:\n\t\tprint \"no data for %s\" % (stockName, )\n\n# then do 51 to 524\n# total estimate for size : 500 megs\n\n\nstocksPopulated = []\nfor stockName in allStockNames:\n\tkeysPresent = []\n\tfor year in range(1950, 2012+1):\n\t\tfor month in range(1,12+1):\n\t\t\tfor day in range(1,31+1):\n\t\t\t\tkey = \"%s:%d-%0.2d-%0.2d:%s\" % (stockName, year, month, day, \"close\")\n\t\t\t\tif r.get(key):\n\t\t\t\t\tkeysPresent.append(\"%d-%0.2d-%0.2d\" % (year, month, day))\n\tif len(keysPresent) > 0:\n\t\tstocksPopulated.append(stockName)\n\t\tS = sorted(keysPresent)\n\t\tstart = S[0]\n\t\tend = S[-1]\n\t\tr.set(\"delimiters:start:%s\" % (stockName, ), start)\n\t\tr.set(\"delimiters:end:%s\" % (stockName, ), end)\n\t\tprint \"%s goes from %s to %s\" % (stockName, start, end)\n\n#\nfor stockName in stocksPopulated:\n\tr.rpush(\"allStockNames\", stockName)\n\n################################################\n#\ndef generateDatesInAYear(year):\n\tdays = {}\n\tdays['01'] = range(1,31+1)\n\tif (year % 4 == 0):\n\t\tdays['02'] = range(1,29+1)\n\telse:\n\t\tdays['02'] = range(1,28+1)\n\tdays['03'] = range(1,31+1)\n\tdays['04'] = range(1,30+1)\n\tdays['05'] = range(1,31+1)\n\tdays['06'] = range(1,30+1)\n\tdays['07'] = range(1,31+1)\n\tdays['08'] = range(1,31+1)\n\tdays['09'] = range(1,30+1)\n\tdays['10'] = range(1,31+1)\n\tdays['11'] = range(1,30+1)\n\tdays['12'] = range(1,31+1)\n\tmonths = [\"%0.2d\" % m for m in range(1,13)]\n\treturn [ (\"%0.4d-%s-%0.2d\" % (year, month, day)) for month in months for day in days[month] ]\n\n\n# populate the redis server with that so as to never have to compute those values again\nfor year in range(1950,2020):\n\tfor date in generateDatesInAYear(year):\n\t\tr.rpush(\"allDatesInYear:%0.4d\" % year, date)\n#\n# A = r.lrange(\"allDatesInYear:1970\", 0, -1)\n\n\n\n#######################\n#\n# To get back on your feed from nothing, you get the list like this.\nallStockNames = r.lrange(\"allStockNames\", 0, -1)\n\n# from numpy import *\n\ndef timeIntervalOfQuote(stockName):\n\tstart = r.get(\"delimiters:start:%s\" % (stockName, ))\n\tend = r.get(\"delimiters:end:%s\" % (stockName, ))\n\tif (not start) or (not end):\n\t\treturn None\n\t#startYear = int(re.match(r\".*?:(\\d*?)-.*?:\", start).group(1))\n\t#endYear = int(re.match(r\".*?:(\\d*?)-.*?:\", end ).group(1))\n\tstartYear = int(re.match(r\"(\\d*?)-.*?\", start).group(1))\n\tendYear = int(re.match(r\"(\\d*?)-.*?\", end ).group(1))\n\treturn {\"start\": start, \"end\": end, \"startYear\":startYear, \"endYear\":endYear}\n\n#def makeNumpyArrayFromQuote(stockName, fieldName=\"close\"):\n#\tI = timeIntervalOfQuote(stockName)\n#\tstartYear = I['startYear']\n#\tendYear = I['endYear']\n#\tprices = []\n#\tfor year in range(startYear, endYear+1):\n#\t\tfor month in range(1,12+1):\n#\t\t\tfor day in range(1,31+1):\n#\t\t\t\tkey = \"%s:%d-%0.2d-%0.2d:%s\" % (stockName, year, month, day, fieldName)\n#\t\t\t\tv = r.get(key)\n#\t\t\t\tprint v\n#\t\t\t\tif v:\n#\t\t\t\t\tprices.append(float(v))\n#\treturn numpy.array(prices)\n\n# AAPL = makeNumpyArrayFromQuote(\"AAPL\")\n# XRX = makeNumpyArrayFromQuote(\"XRX\")\n\n# Write something to get a number of stocks between start and end as a numpy array / matrix.\n#\n# retrieveStockBlock(stockNameList, start, end, fieldName=\"close\")\n# --> a numpy array of size (M, N)\n# where M = len(stockNameList)\n# and N = however many days there are between start and end\n\ndef retrieveStockBlock(redisConn, stockNameList, start, end, fieldName=\"close\", queryCombinationThreshold=0, useNan=True):\n\t\n\tstartYear = int(re.match(r\"(\\d*?)-.*?\", start).group(1))\n\tendYear = int(re.match(r\"(\\d*?)-.*?\", end ).group(1))\n\t\n\tinterwovenPricesAccumulator = []\n\tqueries = []\n\t\n\tfor year in range(startYear, endYear+1):\n\t\tfor date in r.lrange(\"allDatesInYear:%0.4d\" % year, 0, -1):\n\t\t\tif start <= date and date <= end:\n\t\t\t\tfor stockName in stockNameList:\n\t\t\t\t\tqueries.append(\"%s:%s:%s\" % (stockName, date, fieldName))\n\t\t\t\t\tif len(queries) > queryCombinationThreshold:\n\t\t\t\t\t\tprices = redisConn.mget(queries)\n\t\t\t\t\t\tif useNan:\n\t\t\t\t\t\t\tinterwovenPricesAccumulator.extend( [float(p) if p else numpy.NAN for p in prices ] )\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tinterwovenPricesAccumulator.extend( [float(p) if p else p for p in prices ])\n\t\t\t\t\t\tqueries = []\n\tif len(queries) > 0:\n\t\t# some are left\n\t\tprices = redisConn.mget(queries)\n\t\tif useNan:\n\t\t\tinterwovenPricesAccumulator.extend( [float(p) if p else numpy.NAN for p in prices ] )\n\t\telse:\n\t\t\tinterwovenPricesAccumulator.extend( [float(p) if p else p for p in prices ])\n\t\n\tinterwovenPrices = numpy.array(interwovenPricesAccumulator)\n\t# We have to spin the array just a bit to put it as we want.\n\t# This would have been avoided if we hadn't queried the stock prices\n\t# in that order with all the companies grouped.\n\t(M,N) = (len(stockNameList), interwovenPrices.shape[0]/len(stockNameList))\n\tinterwovenPrices = numpy.reshape(interwovenPrices, (N,M))\n\treturn interwovenPrices.transpose()\n\nL = retrieveStockBlock(r, [\"AAPL\", \"GOOG\", \"YHOO\"], \"2010-01-01\", \"2010-02-10\")\n\ndef shortDiscreteConvolution(dataMatrix, filterCoefficients, filterOffsetRange, wantNormalization=True):\n\t# dataMatrix = matrix of dimensions companies x pricesInTime\n\t# filterCoefficients = [0.1, 0.2, 0.3, 0.2, 0.1]\n\t# filterOffsetRange = [-2,-1,0,1,2]\n\t\n\t(M,N) = dataMatrix.shape\n\t\n\td = max([abs(c) for c in filterOffsetRange])\n\tpaddedDataMatrix = numpy.hstack( (numpy.zeros( (M, d)), dataMatrix, numpy.zeros( (M, d))) )\n\t\n\tconvolutionAccumulator = numpy.zeros( paddedDataMatrix.shape )\n\tnormalizationWeights = numpy.zeros( paddedDataMatrix.shape )\n\t\n\t# the continuous pixel split trick where we account for the weights sent to\n\t# every target pixel when doing the translations\n\tholes = numpy.isnan(paddedDataMatrix)\n\tpatchedPaddedDataMatrix = numpy.where(holes, numpy.zeros( paddedDataMatrix.shape ), paddedDataMatrix)\n\t# patchedPaddedWeights[i,j] = 1 iff the original data was present at (i,j) and was not nan.\n\t# Otherwise, patchedPaddedWeights[i,j] = 0.\n\tpatchedPaddedWeights = numpy.where(holes, numpy.zeros( paddedDataMatrix.shape ),\n\t\t\t\t\t\t\t\t\t\t\t\t numpy.hstack(( numpy.zeros( (M, d)),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumpy.ones( dataMatrix.shape),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnumpy.zeros( (M, d))) ) )\n\t\n\tfor os in filterOffsetRange:\n\t\t#print \"d=%d, N=%d, os=%d\" % (d, N, os)\n\t\tconvolutionAccumulator[:,d:(N+d)] += patchedPaddedDataMatrix[:,(d+os):(N+d+os)] * filterCoefficients[os]\n\t\tnormalizationWeights[ :,d:(N+d)] += patchedPaddedWeights[ :,(d+os):(N+d+os)] * filterCoefficients[os]\n\t\n\tif wantNormalization:\n\t\treturn numpy.where(normalizationWeights[:,d:(N+d)] <= 0, numpy.zeros((M,N)), convolutionAccumulator[:,d:(N+d)] / normalizationWeights[:,d:(N+d)] )\n\telse:\n\t\treturn convolutionAccumulator[:,d:(N+d)]\n\n\n# dataMatrix = numpy.array([[10,20,30], [100,200,300]])\n# filterCoefficients = numpy.array([1, 0.5])\n# filterOffsetRange = numpy.array([0, 1])\n# R = shortDiscreteConvolution(dataMatrix, filterCoefficients, filterOffsetRange)\n\n\nL = retrieveStockBlock(r, [\"AAPL\", \"GOOG\", \"YHOO\"], \"2000-01-01\", \"2009-12-31\")\nosr = numpy.arange(-50,50+1)\nosc = numpy.exp(-numpy.abs(osr))\nS = shortDiscreteConvolution(L, osc, osr)\n\n# x1 = numpy.arange(0,S.shape[1])\n# y1 = numpy.array(S[0,:])\n# pylab.plot(x1,y1)\n# x2 = numpy.arange(0,L.shape[1])\n# y2 = numpy.array(L[0,:])\n# pylab.plot(x2,y2)\n# pylab.show()\n\ndef differentiateFromPreviousInTime(stockDataMatrix):\n\tdelta = stockDataMatrix[:,1:] - stockDataMatrix[:,0:-1]\n\treturn numpy.hstack( (delta[:,0:1], delta) )\n\ndS = differentiateFromPreviousInTime(S)\nddS = differentiateFromPreviousInTime(dS)\n\n\ndef extrapolateWithDerivatives(S, t):\n\tdS = differentiateFromPreviousInTime(S)\n\tddS = differentiateFromPreviousInTime(dS)\n\treturn S + t*dS + 0.5*t*t*ddS\n\nt=1\nstock=2\npred = extrapolateWithDerivatives(S,t)\ndiff = pred[stock,2:-t] - L[stock,2+t:]\npylab.plot(diff)\npylab.show()\n\n" }, { "alpha_fraction": 0.5300395488739014, "alphanum_fraction": 0.5691699385643005, "avg_line_length": 23.08571434020996, "blob_id": "60e8ba1499f8d0534377c22733d5a458849476b8", "content_id": "a5465e91435167498136bcf3ebf488c8b044eda8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2530, "license_type": "no_license", "max_line_length": 111, "num_lines": 105, "path": "/programmingPearls_interviewPreparation/graph1.py", "repo_name": "gyom/miscCodeExercisesAndSingleUsage", "src_encoding": "UTF-8", "text": "\nA = {}\nA[(1,2)] = 1\nA[(2,4)] = 1\nA[(1,4)] = 4\nA[(4,5)] = 1\nA[(2,5)] = 5\n\n\n\n\ndef nextNodes(graph, e):\n\treturn [u for (v,u) in graph.keys() if (e == v)]\n\n# mutates 'best' dict\ndef expand(graph, fringe, best):\n\twhile len(fringe) > 0:\n\t\tnewFringe = []\n\t\tfor e in fringe:\n\t\t\tfor u in nextNodes(graph,e):\n\t\t\t\tif u in best:\n\t\t\t\t\tif best[e] + graph[(e,u)] < best[u]:\n\t\t\t\t\t\tprint \"found shorter road to {} through {}\".format(u, e)\n\t\t\t\t\t\tbest[u] = best[e] + graph[(e,u)]\n\t\t\t\t\t\tnewFringe.append(u)\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint \"found bad road\"\n\t\t\t\telse:\n\t\t\t\t\tbest[u] = best[e] + graph[(e,u)]\n\t\t\t\t\tprint \"found road to {} through {}\".format(u, e)\n\t\t\t\t\tnewFringe.append(u)\n\t\t\tprint \"done with {}\".format(e)\n\t\tfringe = newFringe\n\n\n\t\t\n\t\t\n\t\t\n\t\t\n\nfringe = [1]\nbest = {}\nbest[1] = 0;\n\nexpand(A, fringe, best)\n\n\n\n\n\ngraph2 = {(1,2): 7, (2,3): 10, (2,4):15, (3,4):11, (4,5):6, (1,6):15, (1,3):9, (3,6):2, (5,6):9}\ngraph2.update( dict( ((v,u),c) for ((u,v),c) in graph2.items() ))\nbest2 = {1:0}\nfringe = [1]\n\nexpand2(graph2, fringe, best2)\n\n\n\t\n\t\ndef expand2(graph, fringe, best):\n\tbest = best.copy()\n\tfor ((u,v),c) in graph.items():\n\t\tif not (u in best):\n\t\t\tbest[u] = float(\"inf\");\n\t\tif not (v in best):\n\t\t\tbest[v] = float(\"inf\");\n\twhile len(fringe) > 0:\n\t\tnewFringe = []\n\t\tfor e in fringe:\n\t\t\tfor u in nextNodes(graph,e):\n\t\t\t\tif best[e] + graph[(e,u)] < best[u]:\n\t\t\t\t\tbest[u] = best[e] + graph[(e,u)]\n\t\t\t\t\tnewFringe.append(u)\n\t\tfringe = newFringe\n\treturn best\n\n\n\n#def mergeOnMinimum(best1, best2):\n#\treturn dict( [(e,c) for (e,c) in best1.items() if ((e in best2) and (c < best2[e])) or not e in best2] \\\n#\t\t\t\t+ [(e,c) for (e,c) in best2.items() if ((e in best1) and (c < best1[e])) or not e in best1] )\n\ndef mergeOnMinimum(best1, best2):\n\treturn dict( [(e,c) for (e,c) in best1.items() if (c < best2[e])] \\\n\t\t\t\t+ [(e,c) for (e,c) in best2.items() if (c < best1[e])] )\n\ndef mergeFringeSets(set1, set2):\n\treturn set(set1 + set2)\n\ndef mergePairs((best1, fringe1), (best2, fringe2)):\n\treturn (mergeOnMinimum(best1, best2), mergeFringeSets(fringe1, fringe2))\n\ndef expandOneNode(graph, node, best):\n\tnextNodes = [v for (u,v) in graph.items() if (node == u)]\n\tnextNodesWorthExploring = [v for v in nextNodes if (best[node] + graph[(node, v)]) < best[v]]\n\tif len(nextNodesWorthExploring) > 0:\n\t\treduce(mergePairs, \n\t\t\n\t\t\n\t\t#[(best, [])] + [ ({v: best[node] + graph[(node, v)]}, if best[node] + graph[(node, v)]) for v in nextNodes])\n\telse:\n\t\treturn best\n\n\nbest3 = {1: 0, 2: float(\"-inf\"), 3: float(\"-inf\"), 4: float(\"-inf\"), 5: float(\"-inf\"), 6: float(\"-inf\")}\n" } ]
18
endridani/python-oop
https://github.com/endridani/python-oop
b2a7940a76904cae0713a2751aca10ba998d921e
87d7d85dcdb8f2892a6f52e185885aa473bb51bf
c0b2fc7cb44adefadb5d1a359dd31d0bf8ebe8c6
refs/heads/master
2020-03-30T09:45:10.282172
2018-10-01T13:34:16
2018-10-01T13:34:16
151,090,665
0
3
null
null
null
null
null
[ { "alpha_fraction": 0.5383169651031494, "alphanum_fraction": 0.5481311082839966, "avg_line_length": 29.896774291992188, "blob_id": "57777ab046d326b3539d5d15012a49731e94aabc", "content_id": "95c385e97d2dbdc814ced1431ffc55860e4b707d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4789, "license_type": "no_license", "max_line_length": 114, "num_lines": 155, "path": "/bank_account_manager.py", "repo_name": "endridani/python-oop", "src_encoding": "UTF-8", "text": "__author__ = 'Endri Dani'\n\n################################################################################################\n# Create a class called Account which will be an abstract class for three other classes called #\n# CheckingAccount, SavingsAccount and BusinessAccount. Manage credits and debits from these #\n# accounts through an ATM style program. #\n################################################################################################\n\n\nclass Account:\n def __init__(self, balance, nbr):\n self.balance = balance\n self.nbr = nbr\n\n def withdraw_money(self, amount):\n if amount <= self.balance:\n self.balance -= amount\n else:\n print(\"Not enough funds...\")\n\n def deposit_money(self, amount):\n self.balance += amount\n\n def __str__(self):\n return \"${}\".format(round(self.balance, 2))\n\n\nclass CheckingAccount(Account):\n def __init__(self, balance, nbr):\n super().__init__(balance, nbr)\n\n def __str__(self):\n return \"Checking Account #{} \\n Balance: {}\".format(self.nbr, Account.__str__(self))\n\n\nclass SavingAccount(Account):\n def __init__(self, balance, nbr):\n super().__init__(balance, nbr)\n\n def __str__(self):\n return \"Saving Account #{} \\n Balance: {}\".format(self.nbr, Account.__str__(self))\n\n\nclass BusinessAccount(Account):\n def __init__(self, balance, nbr):\n super().__init__(balance, nbr)\n\n def __str__(self):\n return \"Business Account #{} \\n Balance: {}\".format(self.nbr, Account.__str__(self))\n\n\nclass Costumer:\n def __init__(self, name, pin):\n self.name = name\n self.pin = pin\n self.accounts = {'C': [], 'S': [], 'B': []}\n\n def open_checking(self, balance, nbr):\n self.accounts['C'].append(CheckingAccount(balance, nbr))\n\n def open_saving(self, balance, nbr):\n self.accounts['S'].append(SavingAccount(balance, nbr))\n\n def open_business(self, balance, nbr):\n self.accounts['B'].append(BusinessAccount(balance, nbr))\n\n def total_balance(self):\n total = 0\n for acc in self.accounts['C']:\n print(acc)\n total += acc.balance\n for acc in self.accounts['S']:\n print(acc)\n total += acc.balance\n for acc in self.accounts['B']:\n print(acc)\n total += acc.balance\n print(\"Total balance is ${}\".format(round(total, 2)))\n\n def make_deposit(self, acc_type, amount):\n for acc in self.accounts[acc_type]:\n acc.deposit_money(amount)\n\n def make_withdraw(self, acc_type, amount):\n for acc in self.accounts[acc_type]:\n acc.withdraw_money(amount)\n\n def make_transfer(self, from_acc, to_acc, amount):\n for acc in self.accounts[from_acc]:\n acc.withdraw_money(amount)\n for acc in self.accounts[to_acc]:\n acc.deposit_money(amount)\n\n def __str__(self):\n return self.name\n\n\ndef check_pin(pin, cust):\n if pin == cust.pin:\n return True\n return False\n\n\ndef show_menu():\n print(\"\\n1. Withdraw Money\\n2. Deposit Money\\n3. Transfer Money\\n4. Show Balance\\n5. End Session\")\n\n\ndef choose_account():\n account_choice = int(\n input(\"1. Checking Account\\n2. Saving Account\\n3. Business Account\\nChoose the account to be processed:\"))\n if account_choice == 1:\n return 'C'\n elif account_choice == 2:\n return 'S'\n elif account_choice == 3:\n return 'B'\n\n\ndef money_amount():\n amount = float(input(\"Enter the amount you want to be processed: \"))\n return amount\n\ncostumer_list = []\n\nendri = Costumer('Endri', 1234)\nendri.open_checking(555.55, '001')\nendri.open_saving(250.80, '002')\nendri.open_business(350, '003')\ncostumer_list.append(endri)\n\nprint(\"Welcome\")\nenter_pin = int(input(\"Please Enter PIN: \"))\nfor costumer in costumer_list:\n if check_pin(enter_pin, costumer):\n while True:\n show_menu()\n choose_menu = int(input(\"Please choose your action (1-6): \"))\n if choose_menu == 1:\n costumer.make_withdraw('C', money_amount())\n elif choose_menu == 2:\n account = choose_account()\n costumer.make_deposit(account, money_amount())\n elif choose_menu == 3:\n print(\"From\")\n from_account = choose_account()\n print(\"To\")\n to_account = choose_account()\n costumer.make_transfer(from_account, to_account, money_amount())\n elif choose_menu == 4:\n costumer.total_balance()\n elif choose_menu == 5:\n print(\"Have a nice day!\")\n break\n else:\n print(\"Wrong PIN!\")\n" }, { "alpha_fraction": 0.5337142944335938, "alphanum_fraction": 0.5594285726547241, "avg_line_length": 31.38888931274414, "blob_id": "54fe2399cc0568c9b6552eaa7dcb98cc66f970b8", "content_id": "dbd8e9558614999ceee1fcc6ca039bed7c573c85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1750, "license_type": "no_license", "max_line_length": 119, "num_lines": 54, "path": "/tic_tac_toe.py", "repo_name": "endridani/python-oop", "src_encoding": "UTF-8", "text": "__author__ = 'Endri Dani'\n\nmatrix = [1, 2, 3, 4, 5, 6, 7, 8, 9]\ngame_status = False\n\n\ndef board():\n print \" {} | {} | {}\\n {} | {} | {}\\n {} | {} | {}\".format(*matrix)\n\n\ndef reset_board():\n global matrix, game_status\n matrix = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n game_status = False\n\n\ndef select_position():\n global marker, position, item\n marker = ''\n position = ''\n while not (marker == 'x' or marker == 'o' or position in range(1, 10)):\n marker, position = raw_input(\"\\n Enter the player's marker and the position you want:\").split()\n for number in matrix:\n item = matrix.index(number)\n if int(position) == matrix[item]:\n matrix[item] = marker\n board()\n\n\ndef check_status():\n global game_status\n if matrix[0] == matrix[1] == matrix[2] == marker or matrix[3] == matrix[4] == matrix[5] == marker or matrix[6] == \\\n matrix[7] == matrix[7] == marker or matrix[0] == matrix[3] == matrix[6] == marker or matrix[1] == matrix[\n 4] == matrix[7] == marker or matrix[2] == matrix[5] == matrix[8] == marker or matrix[0] == matrix[4] == matrix[\n 8] == marker or matrix[2] == matrix[4] == matrix[6] == marker:\n print \"\\n {player} Wins! Congratulations!\".format(player=marker)\n game_status = True\n elif all(isinstance(x, str) for x in matrix) and game_status is False:\n print \"\\n The game is draw!\"\n\n\ndef play_game():\n reset_board()\n board()\n while any(not isinstance(x, str) for x in matrix) and game_status is False:\n select_position()\n check_status()\n rematch = raw_input('Would you like to play again? (y/n):')\n if rematch == 'y':\n play_game()\n else:\n print \"Thanks for playing!\"\n\nplay_game()\n\n" }, { "alpha_fraction": 0.5642974376678467, "alphanum_fraction": 0.5723089575767517, "avg_line_length": 35.3283576965332, "blob_id": "739015e184e7695b8625ee0302f389c01273580f", "content_id": "2079e1d3b8542b3546943b0da8341f24a20224db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4868, "license_type": "no_license", "max_line_length": 114, "num_lines": 134, "path": "/company_manager.py", "repo_name": "endridani/python-oop", "src_encoding": "UTF-8", "text": "__author__ = 'Endri Dani'\n\n\n####################################################################################################\n# Abstract class Employee and subclasses HourlyEmployee, SalariedEmployee, Manager and Executive. #\n# Every one's pay is calculated differently. Company class that allows you to manage the employees.#\n# You should be able to hire, fire and raise employees. #\n####################################################################################################\n\n\nclass Employee:\n hourly_pay = 9.62\n\n def __init__(self, name, worked_hours, salary):\n self.name = name\n self.worked_hours = worked_hours\n self.salary = salary + float(self.worked_hours) * Employee.hourly_pay\n\n def __str__(self):\n return \"Full Name: {}\\n Worked hours: {}\\n Weekly Salary: ${}\".format(self.name, self.worked_hours,\n round(self.salary, 2))\n\n\nclass HourlyEmployee(Employee):\n def __init__(self, name, worked_hours):\n super().__init__(name, worked_hours, salary=0)\n\n def __str__(self):\n return \"Hourly Employee\\n {}\".format(Employee.__str__(self))\n\n\nclass SalariedEmployee(Employee):\n def __init__(self, name):\n super().__init__(name, worked_hours=40, salary=0)\n\n def __str__(self):\n return \"Salaried Employee\\n {}\".format(Employee.__str__(self))\n\n\nclass Manager(Employee):\n def __init__(self, name, worked_hours):\n super().__init__(name, worked_hours, salary=550)\n\n def __str__(self):\n return \"Manager\\n {}\".format(Employee.__str__(self))\n\n\nclass Executive(Employee):\n def __init__(self, name, worked_hours):\n super().__init__(name, worked_hours, salary=850)\n\n def __str__(self):\n return \"Executive\\n {}\".format(Employee.__str__(self))\n\n\nclass Company:\n def __init__(self, name):\n self.name = name\n self.employees = {'H': [], 'P': [], 'M': [], 'E': []}\n\n def __str__(self):\n return self.name\n\n def hire_hourly_employee(self, employee_type, name, worked_hours):\n self.employees[employee_type].append(HourlyEmployee(name, worked_hours))\n\n def hire_salaried_employee(self, employee_type, name):\n self.employees[employee_type].append(SalariedEmployee(name))\n\n def hire_manager(self, employee_type, name, worked_hours):\n self.employees[employee_type].append(Manager(name, worked_hours))\n\n def hire_executive(self, employee_type, name, worked_hours):\n self.employees[employee_type].append(Executive(name, worked_hours))\n\n def fire_employee(self, employee_type, name):\n for item in self.employees[employee_type]:\n if item.name == name:\n self.employees[employee_type].remove(item)\n\n def raise_to_manager(self, to_type):\n name = input(\"Enter employee name: \")\n from_type = input(\"Enter employee position: \")\n for item in self.employees[from_type]:\n if item.name == name:\n self.employees[to_type].append(Manager(item.name, item.worked_hours))\n self.employees[from_type].remove(item)\n\n def raise_to_executive(self, to_type):\n name = input(\"Enter employee name: \")\n from_type = input(\"Enter employee position: \")\n for item in self.employees[from_type]:\n if item.name == name:\n self.employees[to_type].append(Executive(item.name, item.worked_hours))\n self.employees[from_type].remove(item)\n\n def show_employees(self, employee_type):\n for item in self.employees[employee_type]:\n print(item)\n\n def search_employee(self):\n name = input(\"Enter the employee name: \")\n for key in self.employees.keys():\n for item in self.employees[key]:\n if item.name == name:\n print(item)\n\n\ncompany = Company(\"Dani Security\")\ncompany.hire_hourly_employee(\"H\", \"Endri Dani\", 100.35)\ncompany.hire_hourly_employee(\"H\", \"Jona Zguri\", 56.98)\ncompany.hire_manager(\"M\", \"Albano Osmani\", 2)\nwhile True:\n print(\"\\nWelcome to Dani Security!\")\n print(\" 1. Show Hourly Employees\\n 2. Show Salaried Employees\\n 3. Show Managers\\n 4. Show Executives\\n \"\n \"5. Search Employee\\n 6. Raise to Manager\\n 7. Raise to Executive\\n 8. Quit\" )\n choice = int(input(\"Enter your choice: \"))\n if choice == 1:\n company.show_employees(\"H\")\n elif choice == 2:\n company.show_employees(\"P\")\n elif choice == 3:\n company.show_employees(\"M\")\n elif choice == 4:\n company.show_employees(\"E\")\n elif choice == 5:\n company.search_employee()\n elif choice == 6:\n company.raise_to_manager(\"M\")\n elif choice == 7:\n company.raise_to_executive(\"E\")\n else:\n print(\"Have a nice day!\")\n break\n" }, { "alpha_fraction": 0.7512864470481873, "alphanum_fraction": 0.7598627805709839, "avg_line_length": 71.875, "blob_id": "b1e25b46499683e25f512e8c710687b7c1944b72", "content_id": "937c388bd7cca10833ee39e2d4b14dccc32d6939", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 583, "license_type": "no_license", "max_line_length": 160, "num_lines": 8, "path": "/README.md", "repo_name": "endridani/python-oop", "src_encoding": "UTF-8", "text": "# Python OOP\n\n4 different exercises making use of the Python OOP principles\n\n* **bank_account_manager.py** - Manage credits and debits through an ATM style program. Written in Python 3 using OOP principles.\n* **black_jack.py** - Simple text-base BlackJack game. Written in Python 2 using the principles of OOP.\n* **company_manager.py** - Writen in Python 3 using OOP principles. A hierarchy of Employee classes and a Company class that allows you to manage the employees.\n* **tic_tac_toe.py** - The classic game of Tic-Tac-Toe written in Python 2. Making use of functions and loops.\n" }, { "alpha_fraction": 0.5272685885429382, "alphanum_fraction": 0.5391842126846313, "avg_line_length": 28.493244171142578, "blob_id": "4882bae4c0d0b5ec7ee874d6a8a7c904b2283413", "content_id": "5e9e594ec5973060fef47439a90c2447bf10f16a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4364, "license_type": "no_license", "max_line_length": 115, "num_lines": 148, "path": "/black_jack.py", "repo_name": "endridani/python-oop", "src_encoding": "UTF-8", "text": "import random\n\n__author__ = 'Endri Dani'\n\ncards = ('A', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K')\ncard_values = {'A': 11, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10,\n 'K': 10}\nglobal bankroll_amount, betting_amount\n\n\nclass Player(object):\n def __init__(self, bankroll=100):\n self.hand = []\n self.bankroll = bankroll\n\n def add_bankroll(self, amount):\n self.bankroll += amount\n\n def subtract_bankroll(self, amount):\n self.bankroll -= amount\n\n def initial_cards(self):\n first_card = random.choice(card_values.keys())\n second_card = random.choice(card_values.keys())\n self.hand.extend([first_card, second_card])\n print\n \"Player: {}\".format(self.hand)\n\n def add_card(self):\n card = random.choice(card_values.keys())\n self.hand.append(card)\n print\n \"Player: {}\".format(self.hand)\n\n def total_points(self):\n total = [card_values[item] for item in self.hand]\n return sum(total)\n\n\nclass Dealer(object):\n def __init__(self):\n self.hand = []\n\n def initial_card(self):\n first_card = random.choice(card_values.keys())\n self.hand.append(first_card)\n print\n \"Dealer: {}\".format(self.hand)\n\n def add_card(self):\n card = random.choice(card_values.keys())\n self.hand.append(card)\n print\n \"Dealer: {}\".format(self.hand)\n\n def total_points(self):\n total = [card_values[item] for item in self.hand]\n return sum(total)\n\n\ndef check_status():\n if player.total_points() > dealer.total_points() or dealer.total_points() > 21:\n print\n \"You WIN!\"\n player.add_bankroll(betting_amount)\n print\n \"Your bankroll is {}\".format(player.bankroll)\n elif player.total_points() < dealer.total_points():\n print\n \"You LOSE!\"\n player.subtract_bankroll(betting_amount)\n print\n \"Your bankroll is {}\".format(player.bankroll)\n elif player.total_points() == dealer.total_points():\n print\n \"DRAW!\"\n print\n \"Your bankroll is {}\".format(player.bankroll)\n\n\ndef check_initial_status():\n player.hand = []\n dealer.hand = []\n global more_cards\n more_cards = ''\n player.initial_cards()\n dealer.initial_card()\n while player.total_points() < 21:\n while not (more_cards == 'h' or more_cards == 's'):\n more_cards = raw_input(\"Do you want another card? (h/s): \")\n if more_cards == 'h':\n player.add_card()\n more_cards = ''\n print\n \"Player Total: {}\".format(player.total_points())\n elif more_cards == 's':\n print\n \"Player: {}\".format(player.hand)\n print\n \"Player Total: {}\".format(player.total_points())\n dealer.add_card()\n while dealer.total_points() <= 16:\n dealer.add_card()\n break\n print\n \"Dealer Total: {}\".format(dealer.total_points())\n check_status()\n break\n if player.total_points() == 21:\n player.add_bankroll(betting_amount)\n print\n \"BlackJack\"\n print\n \"Your bankroll is {}\".format(player.bankroll)\n elif player.total_points() > 21:\n player.subtract_bankroll(betting_amount)\n print\n \"Busted\"\n print\n \"Your bankroll is {}\".format(player.bankroll)\n\n\nwhile True:\n try:\n bankroll_amount = int(raw_input(\"How much do you want to put in? :\"))\n except ValueError:\n print\n \"It looks like you did not enter a valid value!\"\n continue\n else:\n player = Player(bankroll=bankroll_amount)\n dealer = Dealer()\n while player.bankroll > 0:\n try:\n betting_amount = int(raw_input(\"How much do you want to bet? :\"))\n except ValueError:\n print\n \"It looks like you did not enter a valid value!\"\n continue\n if betting_amount > player.bankroll:\n print\n \"Not enough money in the bankroll! Try again!\"\n else:\n check_initial_status()\n else:\n print\n \"No more money in your bankroll!\\nThank You for playing!\"\n break" } ]
5
a2htray/testJenkins
https://github.com/a2htray/testJenkins
6d3056e9839d0081240a52e41f34f8d440bd308a
517934714e581100e00e60010f76a33517e108bf
0187592335e70c75585c4a5840f5196b1f3e2f5d
refs/heads/master
2016-08-23T16:12:18.119236
2016-07-20T06:01:42
2016-07-20T06:01:42
63,677,786
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5504587292671204, "alphanum_fraction": 0.6697247624397278, "avg_line_length": 9.800000190734863, "blob_id": "d1fc0507cb5d3dc91aa2b4dd099727ef4480c67a", "content_id": "0be1ccec237d78a2f4674b3be4a4d8db54b841e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 109, "license_type": "no_license", "max_line_length": 13, "num_lines": 10, "path": "/tool.py", "repo_name": "a2htray/testJenkins", "src_encoding": "UTF-8", "text": "\nnumber = 1\n\ndef bar():\n\tprint 'bar'\n\tprint 'good'\n\tprint number\n\tprint 111\n\tprint 111\n\tprint 222\n\tprint 555\n" } ]
1
vfranca/kt-pivot
https://github.com/vfranca/kt-pivot
0d8ba96d1d246958afb2d3a92d4b5281cb6141d1
59879e20554520fffdf624a153276cae63c133b9
335484740bf3fd77c74930bb827877f5576e7717
refs/heads/master
2022-03-27T04:59:25.295905
2020-01-13T04:21:08
2020-01-13T04:21:08
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6523364782333374, "alphanum_fraction": 0.6822429895401001, "avg_line_length": 21.29166603088379, "blob_id": "85d130ef2984091396b7cb4d7fe66f25692f4543", "content_id": "0fac0949b467c9d7d8141785d372240f3f6c17bc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 535, "license_type": "permissive", "max_line_length": 74, "num_lines": 24, "path": "/pyproject.toml", "repo_name": "vfranca/kt-pivot", "src_encoding": "UTF-8", "text": "[tool.poetry]\nname = \"pivotpoint\"\nversion = \"0.2.1\"\ndescription = \"Utilitario de linha de comando para calcular o pivot point\"\nauthors = [\"Valmir Franca <[email protected]>\"]\nlicense = \"MIT\"\nreadme = \"README.md\"\nrepository = \"https://github.com/vfranca/pp\"\nkeywords = [\"trading\", \"pivot point\"]\n\n[tool.poetry.dependencies]\npython = \"^3.8\"\nclick = \"\\b\"\n\n[tool.poetry.dev-dependencies]\npytest = \"^5.3.2\"\nblack = \"^19.10b0\"\n\n[tool.poetry.scripts]\npp = \"pivotpoint.cli:main\"\n\n[build-system]\nrequires = [\"poetry>=0.12\"]\nbuild-backend = \"poetry.masonry.api\"\n" }, { "alpha_fraction": 0.4166666567325592, "alphanum_fraction": 0.4722222089767456, "avg_line_length": 11, "blob_id": "28d4a88cdd350a72783dcba0e1157027fa622bfa", "content_id": "6edc6e5318c7576d79351a4a7518c0618e2388c3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 36, "license_type": "permissive", "max_line_length": 23, "num_lines": 3, "path": "/pivotpoint/conf.py", "repo_name": "vfranca/kt-pivot", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\ndigits = 2\n" }, { "alpha_fraction": 0.7238805890083313, "alphanum_fraction": 0.7238805890083313, "avg_line_length": 12.199999809265137, "blob_id": "74fc094cad17c0a6020375add849b72babcbf245", "content_id": "45a8766c5fdfdd104b98b2fda270d9010326e2dc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 277, "license_type": "permissive", "max_line_length": 58, "num_lines": 20, "path": "/README.md", "repo_name": "vfranca/kt-pivot", "src_encoding": "UTF-8", "text": "# Pivot Point\n\nUtilitário de linha de comando para calcular o ponto pivô.\n\n## Instalação\n\n```console\npip install pivotpoint\n```\n\n## Uso\n\n```console\npp maxima minima fechamento\n```\n\nonde:\nmaxima = preço máximo\nminima = preço mínimo\nfechamento = preço de fechamento\n\n\n\n\n" }, { "alpha_fraction": 0.7042253613471985, "alphanum_fraction": 0.7183098793029785, "avg_line_length": 22.66666603088379, "blob_id": "51288b29005f51c89cc7ca706625d1243ad87d27", "content_id": "b426fa6c4f5921b53487fcc0f18195939195da21", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 71, "license_type": "permissive", "max_line_length": 30, "num_lines": 3, "path": "/tests/test_helpers.py", "repo_name": "vfranca/kt-pivot", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport unittest\nfrom pivotpoint import helpers\n" }, { "alpha_fraction": 0.5302197933197021, "alphanum_fraction": 0.5521978139877319, "avg_line_length": 15.545454978942871, "blob_id": "67e870965fa482f494af7b37f2e43f24c4a77255", "content_id": "61a22e1c2b989658e01c7a3cb7a17d56b536e717", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 364, "license_type": "permissive", "max_line_length": 46, "num_lines": 22, "path": "/pivotpoint/helpers.py", "repo_name": "vfranca/kt-pivot", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom pivotpoint import conf\n\n\ndef pp(h, l, c):\n return round((h + l + c) / 3, conf.digits)\n\n\ndef r1(pp, l):\n return round(pp * 2 - l, conf.digits)\n\n\ndef s1(pp, h):\n return round(pp * 2 - h, conf.digits)\n\n\ndef r2(pp, h, l):\n return round(pp + (h - l), conf.digits)\n\n\ndef s2(pp, h, l):\n return round(pp - (h - l), conf.digits)\n" }, { "alpha_fraction": 0.5951134562492371, "alphanum_fraction": 0.6055846214294434, "avg_line_length": 21.038461685180664, "blob_id": "b545fdcdda2b6625af17b7059dd2fec35cf471d4", "content_id": "c9c6ad310317864ebd350bacede5a4eb89cb6426", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 573, "license_type": "permissive", "max_line_length": 41, "num_lines": 26, "path": "/pivotpoint/cli.py", "repo_name": "vfranca/kt-pivot", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport sys\nimport click\nfrom pivotpoint import helpers\n\n\[email protected]()\[email protected](\"high\")\[email protected](\"low\")\[email protected](\"close\")\ndef main(high, low, close):\n \"\"\"Console script for pivot_point.\"\"\"\n h = float(high)\n l = float(low)\n c = float(close)\n pp = helpers.pp(h, c, l)\n click.echo(helpers.r2(pp, h, l))\n click.echo(helpers.r1(pp, l))\n click.echo(pp)\n click.echo(helpers.s1(pp, h))\n click.echo(helpers.s2(pp, h, l))\n return 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main()) # pragma: no cover\n" }, { "alpha_fraction": 0.38297873735427856, "alphanum_fraction": 0.42553192377090454, "avg_line_length": 22.5, "blob_id": "0522349c348b081ac04472961287d4138d132d73", "content_id": "26d256dd96c8284939b2f9a2da022611dd1a0b35", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 94, "license_type": "permissive", "max_line_length": 25, "num_lines": 4, "path": "/pivotpoint/__init__.py", "repo_name": "vfranca/kt-pivot", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n__author__ = \"\"\"Valmir França\"\"\"\n__email__ = \"[email protected]\"\n__version__ = \"0.2.0\"\n" }, { "alpha_fraction": 0.5980392098426819, "alphanum_fraction": 0.6627451181411743, "avg_line_length": 27.33333396911621, "blob_id": "40a7b300cf0179cf0ad039395a429f351d3a86b8", "content_id": "6599733b0213579573a907d9fc5ab78c8a716ed8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 510, "license_type": "permissive", "max_line_length": 74, "num_lines": 18, "path": "/tests/test_cli.py", "repo_name": "vfranca/kt-pivot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport unittest\nfrom click.testing import CliRunner\nfrom pivotpoint import pp\nfrom pivotpoint import cli\n\n\nclass TestPivotPoint(unittest.TestCase):\n def setUp(self):\n self.runner = CliRunner()\n\n def tearDown(self):\n \"\"\"Tear down test fixtures, if any.\"\"\"\n\n def test_command_line_interface(self):\n result = self.runner.invoke(cli.main, [\"34.80\", \"32.80\", \"33.40\"])\n assert \"35.67\\n34.54\\n33.67\\n32.54\\n31.67\\n\" in result.output\n" } ]
8
Terrorbear/dumb-clicker
https://github.com/Terrorbear/dumb-clicker
089aaf52a974a3d95ed958e8c39579808dbcc8a6
e48424be07bc78eb8fe2e9d51b2ba0b9cd48620b
c994b2caf2875977a1cd3c032bf93d58b6bb46a4
refs/heads/master
2021-01-19T20:03:49.877845
2015-08-25T04:58:12
2015-08-25T04:58:12
41,342,336
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5653495192527771, "alphanum_fraction": 0.5775076150894165, "avg_line_length": 25.31999969482422, "blob_id": "256a5f0c87021bc1d55525a0d1cf8f5c976c379f", "content_id": "d741ed4693cd25929ee5be1be9d6130c12bac8fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 658, "license_type": "no_license", "max_line_length": 48, "num_lines": 25, "path": "/repclick.py", "repo_name": "Terrorbear/dumb-clicker", "src_encoding": "UTF-8", "text": "#! /usr/bin/python\nfrom pymouse import PyMouse, PyMouseEvent\nfrom time import sleep\n\nCLICKS_PER_SEC = 300\nDURATION_SEC = 30\nREPEATS = DURATION_SEC * CLICKS_PER_SEC\n\nclass RepClick(PyMouseEvent):\n def __init__(self):\n PyMouseEvent.__init__(self)\n self.mouse = PyMouse()\n self.first = True\n\n def click(self, x, y, button, press):\n if self.first and button == 1 and press:\n self.first = False\n x,y = self.mouse.position()\n delay = 1.0/CLICKS_PER_SEC\n for i in xrange(REPEATS):\n self.mouse.click(x, y)\n sleep(delay)\n self.stop()\n\nRepClick().run()\n" }, { "alpha_fraction": 0.7561929821968079, "alphanum_fraction": 0.7561929821968079, "avg_line_length": 24.566667556762695, "blob_id": "54f72132bd313eb5dbe25ce0f6c943e89433b322", "content_id": "6b83e14386a60a3711c86b2e608343191493fe5d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 767, "license_type": "no_license", "max_line_length": 157, "num_lines": 30, "path": "/README.md", "repo_name": "Terrorbear/dumb-clicker", "src_encoding": "UTF-8", "text": "# Autoclicker Readme\n\nSuper simple autoclicker that uses\nthe PyUserInput cloned from:\nhttps://github.com/SavinaRoja/PyUserInput.github\n\n### Setup\n\nFirst run:\n```bash\ngit clone https://github.com/SavinaRoja/PyUserInput.github`\n```\nOnce thats downloaded, go to that directory and run:\n```bash\nsudo python setup.py install\n```\nNow go into my repclick.py and change the CLICKS_PER_SEC and DURATION_SEC numbers to however you want.\n\nYou probably have to give yourself execute permissions as well so\n```bash\nchmod u+x repclick.py\n```\n\n### How to use\n\nOnce you're setup, as soon as you run\n```bash\n./repclick.py\n```\nthe auto clicker will be activated. Once on, the next time you click, the AC will click that same area for the DURATION at the CLICKS_PER_SEC you sepecified.\n" } ]
2
fzhbioinfo/EnsembleSplice
https://github.com/fzhbioinfo/EnsembleSplice
63bcc9f277e2945c331d4c6a2c6b3e5b33414f2e
0d37bec3f18774e77f4b7f6bd995918870fe3610
5803f7ef4f95699011195faa49b3e633fc45747f
refs/heads/master
2023-05-27T06:59:01.041300
2021-03-18T02:03:00
2021-03-18T02:03:00
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6155539155006409, "alphanum_fraction": 0.6236243844032288, "avg_line_length": 30.697673797607422, "blob_id": "bb074725edb98e7c0cc47471f2fb7783e548fe98", "content_id": "fb1a6d28f80e0041ec2322cba059ca79eff40c24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1363, "license_type": "no_license", "max_line_length": 133, "num_lines": 43, "path": "/test/parse_splice_result.py", "repo_name": "fzhbioinfo/EnsembleSplice", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\nfrom io import StringIO\nimport pandas as pd\nimport numpy as np\nimport subprocess\nimport sys\n\n\ndef parse_maxentscan(result):\n try:\n return -float(result.split('|')[-1])\n except:\n return None\n\n\ndef parse_scsnv(result):\n ada_score = result.split('|')[-2]\n rf_score = result.split('|')[-1]\n if '.' not in [ada_score, rf_score]:\n return np.mean([float(ada_score), float(rf_score)])\n elif ada_score == '.' and rf_score != '.':\n return float(rf_score)\n elif ada_score != '.' and rf_score == '.':\n return float(ada_score)\n else:\n return None\n\n\ndef parse_spliceai(result):\n score = max(result.split('|')[2:6])\n if score == '.':\n return None\n return score\n\n\nvcf = pd.read_csv(StringIO(subprocess.getoutput(\"grep -v '##' \" + sys.argv[1])), sep='\\t')\nvcf.rename(columns={'ID': 'Effect'}, inplace=True)\nprediction = vcf['INFO'].str.split(';', expand=True)\nprediction['MaxEntScan'] = prediction.apply(lambda x: parse_maxentscan(x[0]), axis=True)\nprediction['dbscSNV'] = prediction.apply(lambda x: parse_scsnv(x[1]), axis=True)\nprediction['SpliceAI'] = prediction.apply(lambda x: parse_spliceai(x[2]), axis=True)\ndf = vcf.join(prediction)\ndf.to_csv(sys.argv[2], sep='\\t', index=False, columns=['#CHROM', 'POS', 'REF', 'ALT', 'Effect', 'MaxEntScan', 'dbscSNV', 'SpliceAI'])\n" }, { "alpha_fraction": 0.571049153804779, "alphanum_fraction": 0.5768592357635498, "avg_line_length": 41.42253494262695, "blob_id": "7c2673b1aad1ba5a17e56b575c500841135b687b", "content_id": "0fba13ac5bea3c260b1e557907fe6f0c9910f8a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6024, "license_type": "no_license", "max_line_length": 152, "num_lines": 142, "path": "/spliceai_wrapper.py", "repo_name": "fzhbioinfo/EnsembleSplice", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\nfrom vcf.parser import _Info as VcfInfo, field_counts as vcf_field_counts\nfrom multiprocessing import Queue, Process, cpu_count\nfrom argparse import ArgumentParser\nfrom collections import namedtuple\nfrom itertools import count\nimport queue\nimport tabix\nimport vcf\nimport os\n\n\nROOT = os.path.abspath(os.path.dirname(__file__))\nANNOTATION = os.path.join(ROOT, 'annotation')\nVariantRecord = namedtuple('VariantRecord', ['chromosome', 'pos', 'ref', 'alt'])\n\n\nclass SpliceAI:\n def __init__(self, annotation):\n self.annotation_snv = tabix.open(os.path.join(ANNOTATION, 'spliceai_scores.raw.snv.' + annotation + '.vcf.gz'))\n self.annotation_indel = tabix.open(os.path.join(ANNOTATION, 'spliceai_scores.raw.indel.' + annotation + '.vcf.gz'))\n\n def spliceai_score(self, record):\n score = record.alt + '|.|.|.|.|.|.|.|.|.'\n if SpliceAI.mutation_type(record.ref, record.alt) == 'snv':\n records_query = self.annotation_snv.query(record.chromosome, record.pos - 1, record.pos)\n else:\n records_query = self.annotation_indel.query(record.chromosome, record.pos - 1, record.pos)\n if records_query:\n score_list = list()\n for record_query in records_query:\n if [record.chromosome, str(record.pos), record.ref, record.alt] == [record_query[0], record_query[1], record_query[3], record_query[4]]:\n score_list.append(record_query[7].replace('SpliceAI=', ''))\n if score_list:\n score = '/'.join(score_list)\n else:\n score = record.alt + '|.|.|.|.|.|.|.|.|.'\n return score\n\n @staticmethod\n def mutation_type(ref, alt):\n if ref in ['A', 'T', 'C', 'G', 'a', 't', 'c', 'g'] and alt in ['A', 'T', 'C', 'G', 'a', 't', 'c', 'g']:\n return 'snv'\n else:\n return 'indel'\n\n\ndef score_vcf(records, results, annotation):\n spliceai = SpliceAI(annotation)\n while True:\n try:\n record = records.get(False)\n except queue.Empty:\n continue\n if record != 'END':\n record_id, record_infos, record_score_list = record[0], record[1], list()\n for record_info in record_infos:\n record_score_list.append(spliceai.spliceai_score(record_info))\n results.put((record_id, ','.join(record_score_list)))\n else:\n records.put('END')\n break\n\n\ndef annotation_vcf(parsed_args, process_num):\n records, results = Queue(100 * process_num), Queue()\n input_finished = False\n output_finished = False\n wait_records = dict()\n processes = list()\n records_id = count()\n for i in range(process_num):\n p = Process(target=score_vcf, args=(records, results, parsed_args.annotation))\n processes.append(p)\n p.start()\n vcf_reader = vcf.Reader(filename=parsed_args.file_in)\n vcf_reader.infos['SpliceAI'] = VcfInfo('SpliceAI', vcf_field_counts['A'], 'String',\n 'SpliceAIv1.3 variant annotation. These include delta scores (DS) and delta positions (DP) for '\n 'acceptor gain (AG), acceptor loss (AL), donor gain (DG), and donor loss (DL). '\n 'Format: ALLELE|SYMBOL|DS_AG|DS_AL|DS_DG|DS_DL|DP_AG|DP_AL|DP_DG|DP_DL', version=None, source=None)\n vcf_writer = vcf.Writer(open(parsed_args.file_out, 'w'), vcf_reader)\n while True:\n while not records.full() and not input_finished:\n try:\n record = next(vcf_reader)\n record_id = next(records_id)\n wait_records[record_id] = record\n record_infos = list()\n chromosome = str(record.CHROM).replace('chr', '')\n pos = record.POS\n ref = record.REF\n for alt in record.ALT:\n record_infos.append(VariantRecord(chromosome, pos, ref, str(alt)))\n records.put((record_id, record_infos))\n except StopIteration:\n input_finished = True\n records.put('END')\n break\n processes_status = list()\n for p in processes:\n processes_status.append(p.is_alive())\n if True not in processes_status:\n results.put('END')\n while True:\n try:\n result = results.get(False)\n except queue.Empty:\n break\n if result != 'END':\n record_id, record_score = result[0], result[1]\n record_write = wait_records.pop(record_id)\n record_write.add_info('SpliceAI', record_score)\n vcf_writer.write_record(record_write)\n else:\n output_finished = True\n break\n if output_finished:\n break\n vcf_writer.close()\n\n\ndef main():\n parser = ArgumentParser()\n parser.add_argument('-a', help='Genome hg19 or hg38', default='hg19', dest='annotation')\n parser.add_argument('-i', help='Input file', required=True, dest='file_in')\n parser.add_argument('-o', help='Output file', required=True, dest='file_out')\n parser.add_argument('--format_in', help='Input file format: vcf,vcf-4cols,bgianno', default='vcf', dest='format_in')\n parser.add_argument('-p', help='Process number', type=int, default=1, dest='processes')\n parsed_args = parser.parse_args()\n if parsed_args.annotation not in ['hg19', 'hg38']:\n raise Exception('Genome not recognized! Must be hg19 or hg38')\n if parsed_args.format_in not in ['vcf', 'vcf-4cols', 'bgianno']:\n raise Exception('Input file format not recognized! Must be vcf, vcf-4cols or bgianno')\n process_num = min(cpu_count(), parsed_args.processes)\n if parsed_args.format_in != 'vcf':\n raise Exception('Only support vcf Input file format!')\n else:\n annotation_vcf(parsed_args, process_num)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5048093795776367, "alphanum_fraction": 0.5162094831466675, "avg_line_length": 39.68115997314453, "blob_id": "6ac80a25af3bf488efdcf2de6bb5ab9372799d15", "content_id": "c6d84cb3e4a1e0ba10a5f9426afb1ba6e81483c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2807, "license_type": "no_license", "max_line_length": 127, "num_lines": 69, "path": "/test/bgianno2vcf_splice.py", "repo_name": "fzhbioinfo/EnsembleSplice", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\nimport pandas as pd\nimport pyfaidx\nimport sys\n\n\ndef bgi_anno_2_vcf_format(df, fa):\n df.reset_index(drop=True, inplace=True)\n df['#Chr'] = df['#Chr'].astype('str')\n if len(df[df['#Chr'].str.startswith('chr')]):\n df['#CHROM'] = df['#Chr']\n else:\n df['#CHROM'] = 'chr' + df['#Chr']\n df.loc[df['#CHROM'] == 'chrMT', '#CHROM'] = 'chrM_NC_012920.1'\n df['ID'] = df['Splicing_effect']\n df['QUAL'] = '.'\n df['FILTER'] = '.'\n df['INFO'] = '.'\n df['MuType'] = 'delins'\n df.loc[df['Ref'] == '.', 'MuType'] = 'ins'\n df.loc[df['Call'] == '.', 'MuType'] = 'del'\n df.loc[(df['Ref'].map(len) == 1) & (df['Call'].map(len) == 1) & (df['Ref'] != '.') & (df['Call'] != '.'), 'MuType'] = 'snp'\n df['POS'] = df['Stop']\n df.loc[df['MuType'] == 'del', 'POS'] = df.loc[df['MuType'] == 'del', 'Start']\n df.loc[df['MuType'] == 'delins', 'POS'] = df.loc[df['MuType'] == 'delins', 'Start']\n df['REF'] = df['Ref']\n df['ALT'] = df['Call']\n for i in range(df.shape[0]):\n if df.loc[i, 'MuType'] == 'ins':\n base = str(fa.get_seq(df.loc[i, '#CHROM'], df.loc[i, 'POS'], df.loc[i, 'POS'])).upper()\n df.loc[i, 'REF'] = base\n df.loc[i, 'ALT'] = base + df.loc[i, 'ALT']\n elif df.loc[i, 'MuType'] == 'del':\n base = str(fa.get_seq(df.loc[i, '#CHROM'], df.loc[i, 'POS'], df.loc[i, 'POS'])).upper()\n df.loc[i, 'ALT'] = base\n df.loc[i, 'REF'] = base + df.loc[i, 'REF']\n elif df.loc[i, 'MuType'] == 'delins':\n base = str(fa.get_seq(df.loc[i, '#CHROM'], df.loc[i, 'POS'], df.loc[i, 'POS'])).upper()\n df.loc[i, 'REF'] = base + df.loc[i, 'REF']\n df.loc[i, 'ALT'] = base + df.loc[i, 'ALT']\n else:\n pass\n a = df[['#CHROM', 'POS', 'ID', 'REF', 'ALT', 'QUAL', 'FILTER', 'INFO']].copy()\n a.sort_values(by=['#CHROM', 'POS'], ascending=True, inplace=True)\n b = df[['#Chr', 'Start', 'Stop', 'Ref', 'Call', '#CHROM', 'POS', 'REF', 'ALT']].copy()\n df.drop(columns=['ID', 'QUAL', 'FILTER', 'INFO', 'MuType'], inplace=True)\n return a, b, df\n\n\ndef read_vcf_head(header):\n vh = open(header, 'r')\n fp_read = vh.read()\n vh.close()\n return fp_read\n\n\nvcf_header = '/jdfstj1/B2C_RD_P2/USR/fangzhonghai/py_scripts/vcf_head.txt'\nvcf_header_read = read_vcf_head(vcf_header)\nhg19 = '/jdfstj1/B2C_RD_P2/USR/fangzhonghai/project/NBS/hg19/hg19_chM_male_mask.fa'\nreference = pyfaidx.Fasta(hg19)\n\ndf_in = pd.read_excel(sys.argv[1])\n#df_in.rename(columns={'Chr': '#Chr'}, inplace=True)\ndf_in = df_in[df_in['Ref'] != df_in['Call']].copy()\n\nsample_vcf, _1, _2 = bgi_anno_2_vcf_format(df_in, reference)\nwith open(sys.argv[2], 'w') as f:\n f.write(vcf_header_read)\nsample_vcf.to_csv(sys.argv[2], sep='\\t', index=False, mode='a')\n" }, { "alpha_fraction": 0.5901455879211426, "alphanum_fraction": 0.6394177079200745, "avg_line_length": 58.53333282470703, "blob_id": "b9e264bffc020b19dcdd1f54b19e1f27707fd110", "content_id": "449f860b729a943cbbbacba444a4c9fdb4163dd0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1786, "license_type": "no_license", "max_line_length": 177, "num_lines": 30, "path": "/scsnv_parsing.py", "repo_name": "fzhbioinfo/EnsembleSplice", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\nimport pandas as pd\nimport glob\nimport sys\nimport os\nscSNV = glob.glob(sys.argv[1])\nscSNV_df = pd.DataFrame()\nwork_dir = sys.argv[2]\nchromosome = ['chr' + str(i) for i in range(1, 23)] + ['chrX', 'chrY']\nfor snv in scSNV:\n df = pd.read_csv(snv, sep='\\t', dtype={'chr': str, 'hg38_chr': str}, usecols=['chr', 'pos', 'ref', 'alt', 'hg38_chr', 'hg38_pos', 'ada_score', 'rf_score'], low_memory=False)\n df['chr'] = 'chr' + df['chr']\n df['hg38_chr'] = 'chr' + df['hg38_chr']\n scSNV_df = scSNV_df.append(df)\nscSNV_df_hg19 = scSNV_df[['chr', 'pos', 'ref', 'alt', 'ada_score', 'rf_score']].copy()\nscSNV_df_hg38 = scSNV_df[['hg38_chr', 'hg38_pos', 'ref', 'alt', 'ada_score', 'rf_score']].copy()\nscSNV_df_hg19.rename(columns={'chr': '#chr'}, inplace=True)\nscSNV_df_hg38.rename(columns={'hg38_chr': '#chr', 'hg38_pos': 'pos'}, inplace=True)\nscSNV_df_hg19 = scSNV_df_hg19[scSNV_df_hg19['#chr'].isin(chromosome)].copy()\nscSNV_df_hg38 = scSNV_df_hg38[scSNV_df_hg38['#chr'].isin(chromosome)].copy()\nscSNV_df_hg19['pos'] = scSNV_df_hg19['pos'].astype('int64')\nscSNV_df_hg38['pos'] = scSNV_df_hg38['pos'].astype('int64')\nscSNV_df_hg19.sort_values(by=['#chr', 'pos'], ascending=[True, True], inplace=True)\nscSNV_df_hg38.sort_values(by=['#chr', 'pos'], ascending=[True, True], inplace=True)\nscSNV_df_hg19.to_csv(os.path.join(work_dir, 'dbscSNV1.1_hg19.tsv'), sep='\\t', index=False)\nscSNV_df_hg38.to_csv(os.path.join(work_dir, 'dbscSNV1.1_hg38.tsv'), sep='\\t', index=False)\nos.system('bgzip -f ' + os.path.join(work_dir, 'dbscSNV1.1_hg19.tsv'))\nos.system('bgzip -f ' + os.path.join(work_dir, 'dbscSNV1.1_hg38.tsv'))\nos.system('tabix -p vcf ' + os.path.join(work_dir, 'dbscSNV1.1_hg19.tsv.gz'))\nos.system('tabix -p vcf ' + os.path.join(work_dir, 'dbscSNV1.1_hg38.tsv.gz'))\n" }, { "alpha_fraction": 0.5680598616600037, "alphanum_fraction": 0.5740770697593689, "avg_line_length": 39.99333190917969, "blob_id": "58e6196a392530be748529d8d6aad03b66e5e774", "content_id": "ee33f66ef504341be03703b8c89fc4fb3b9ffe6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6149, "license_type": "no_license", "max_line_length": 143, "num_lines": 150, "path": "/scsnv_wrapper.py", "repo_name": "fzhbioinfo/EnsembleSplice", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\nfrom vcf.parser import _Info as VcfInfo, field_counts as vcf_field_counts\nfrom multiprocessing import Queue, Process, cpu_count\nfrom argparse import ArgumentParser\nfrom collections import namedtuple\nfrom itertools import count\nimport pandas as pd\nimport queue\nimport tabix\nimport vcf\nimport os\n\n\nROOT = os.path.abspath(os.path.dirname(__file__))\nANNOTATION = os.path.join(ROOT, 'annotation')\nVariantRecord = namedtuple('VariantRecord', ['chromosome', 'pos', 'ref', 'alt'])\n\n\nclass ScSNV:\n def __init__(self, annotation):\n self.annotation = tabix.open(os.path.join(ANNOTATION, 'dbscSNV1.1_' + annotation + '.tsv.gz'))\n\n def scsnv_score(self, record):\n score = record.alt + '|.|.'\n if not (record.ref in ['A', 'T', 'C', 'G', 'a', 't', 'c', 'g'] and record.alt in ['A', 'T', 'C', 'G', 'a', 't', 'c', 'g']):\n return score\n records_query = self.annotation.query(record.chromosome, record.pos - 1, record.pos)\n if records_query:\n for record_query in records_query:\n if [record.chromosome, str(record.pos), record.ref, record.alt] == record_query[0: 4]:\n score = '|'.join([record.alt, record_query[4], record_query[5]])\n break\n return score\n\n\ndef annotation_pseudo_vcf(parsed_args):\n if parsed_args.format_in == 'vcf-4cols':\n df = pd.read_csv(parsed_args.file_in, sep='\\t', dtype={'#CHROM': str})\n df['#chr'] = df['#CHROM']\n df['pos'] = df['POS']\n df['ref'] = df['REF']\n df['alt'] = df['ALT']\n else:\n df = pd.read_csv(parsed_args.file_in, sep='\\t', dtype={'#Chr': str})\n df['#chr'] = df['#Chr']\n df['pos'] = df['Stop']\n df['ref'] = df['Ref']\n df['alt'] = df['Call']\n db = pd.read_csv(os.path.join(ANNOTATION, 'dbscSNV1.1_' + parsed_args.annotation + '.tsv.gz'),\n sep='\\t', dtype={'#chr': str, 'ada_score': str, 'rf_score': str})\n df_score = pd.merge(df, db, on=['#chr', 'pos', 'ref', 'alt'], how='left')\n df_score.fillna('.', inplace=True)\n df_score['dbscSNV'] = df_score['ada_score'] + '|' + df_score['rf_score']\n df_score.drop(columns=['#chr', 'pos', 'ref', 'alt', 'ada_score', 'rf_score'], inplace=True)\n df_score.to_csv(parsed_args.file_out, sep='\\t', index=False)\n\n\ndef score_vcf(records, results, annotation):\n scsnv = ScSNV(annotation)\n while True:\n try:\n record = records.get(False)\n except queue.Empty:\n continue\n if record != 'END':\n record_id, record_infos, record_score_list = record[0], record[1], list()\n for record_info in record_infos:\n record_score_list.append(scsnv.scsnv_score(record_info))\n results.put((record_id, ','.join(record_score_list)))\n else:\n records.put('END')\n break\n\n\ndef annotation_vcf(parsed_args, process_num):\n records, results = Queue(100 * process_num), Queue()\n input_finished = False\n output_finished = False\n wait_records = dict()\n processes = list()\n records_id = count()\n for i in range(process_num):\n p = Process(target=score_vcf, args=(records, results, parsed_args.annotation))\n processes.append(p)\n p.start()\n vcf_reader = vcf.Reader(filename=parsed_args.file_in)\n vcf_reader.infos['dbscSNV'] = VcfInfo('dbscSNV', vcf_field_counts['A'], 'String',\n 'dbscSNV Score for VCF record alleles, Format: ALLELE|ada_score|rf_score', version=None, source=None)\n vcf_writer = vcf.Writer(open(parsed_args.file_out, 'w'), vcf_reader)\n while True:\n while not records.full() and not input_finished:\n try:\n record = next(vcf_reader)\n record_id = next(records_id)\n wait_records[record_id] = record\n record_infos = list()\n chromosome = str(record.CHROM)\n pos = record.POS\n ref = record.REF\n for alt in record.ALT:\n record_infos.append(VariantRecord(chromosome, pos, ref, str(alt)))\n records.put((record_id, record_infos))\n except StopIteration:\n input_finished = True\n records.put('END')\n break\n processes_status = list()\n for p in processes:\n processes_status.append(p.is_alive())\n if True not in processes_status:\n results.put('END')\n while True:\n try:\n result = results.get(False)\n except queue.Empty:\n break\n if result != 'END':\n record_id, record_score = result[0], result[1]\n record_write = wait_records.pop(record_id)\n record_write.add_info('dbscSNV', record_score)\n vcf_writer.write_record(record_write)\n else:\n output_finished = True\n break\n if output_finished:\n break\n vcf_writer.close()\n\n\ndef main():\n parser = ArgumentParser()\n parser.add_argument('-a', help='Genome hg19 or hg38', default='hg19', dest='annotation')\n parser.add_argument('-i', help='Input file', required=True, dest='file_in')\n parser.add_argument('-o', help='Output file', required=True, dest='file_out')\n parser.add_argument('--format_in', help='Input file format: vcf,vcf-4cols,bgianno', default='vcf-4cols', dest='format_in')\n parser.add_argument('-p', help='Process number', type=int, default=1, dest='processes')\n parsed_args = parser.parse_args()\n if parsed_args.annotation not in ['hg19', 'hg38']:\n raise Exception('Genome not recognized! Must be hg19 or hg38')\n if parsed_args.format_in not in ['vcf', 'vcf-4cols', 'bgianno']:\n raise Exception('Input file format not recognized! Must be vcf, vcf-4cols or bgianno')\n process_num = min(cpu_count(), parsed_args.processes)\n if parsed_args.format_in != 'vcf':\n annotation_pseudo_vcf(parsed_args)\n else:\n annotation_vcf(parsed_args, process_num)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.8141112327575684, "alphanum_fraction": 0.8358209133148193, "avg_line_length": 146.39999389648438, "blob_id": "a76eeb1eab4aef713c968f3a22e4e4bb1d8d534d", "content_id": "6c98d1fe31d42f650a6f6c3780fc2fefec10bfbd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 737, "license_type": "no_license", "max_line_length": 206, "num_lines": 5, "path": "/test/readme.txt", "repo_name": "fzhbioinfo/EnsembleSplice", "src_encoding": "UTF-8", "text": "python3 bgianno2vcf_splice.py ExprValid.uni.xlsx ExperimentValidateSplice.vcf\npython3 ../maxentscan_wrapper.py -r /jdfstj1/B2C_RD_P2/USR/fangzhonghai/project/NBS/hg19/hg19_chM_male_mask.fa -i ExperimentValidateSplice.vcf -p 2 --format_in vcf -o ExperimentValidateSplice.maxentscan.vcf\npython3 ../scsnv_wrapper.py -i ExperimentValidateSplice.maxentscan.vcf --format_in vcf -p 2 -o ExperimentValidateSplice.maxentscan.scsnv.vcf\npython3 ../spliceai_wrapper.py -i ExperimentValidateSplice.maxentscan.scsnv.vcf --format_in vcf -p 2 -o ExperimentValidateSplice.maxentscan.scsnv.spliceai.vcf\npython3 parse_splice_result.py ExperimentValidateSplice.maxentscan.scsnv.spliceai.vcf ExperimentValidateSplice.maxentscan.scsnv.spliceai.vcf.result.tsv\n" }, { "alpha_fraction": 0.6908531188964844, "alphanum_fraction": 0.7062445282936096, "avg_line_length": 50.70454406738281, "blob_id": "4087638b9086f47d864dccd2c178f7dbaf085ab3", "content_id": "17b66ba29c289f181a62085a21b22af18d909930", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2274, "license_type": "no_license", "max_line_length": 161, "num_lines": 44, "path": "/genomic_gff_parsing.py", "repo_name": "fzhbioinfo/EnsembleSplice", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\nfrom bioutils.assemblies import make_ac_name_map\nfrom io import StringIO\nimport pandas as pd\nimport numpy as np\nimport subprocess\nimport sys\n\n\ndef ac_to_name(chromosome_dic, chromosome):\n name = chromosome_dic[chromosome]\n if not name.startswith('chr'):\n name = 'chr' + name\n return name\n\n\ngff = sys.argv[1]\ngenome = sys.argv[2]\nchrome_dic = make_ac_name_map(genome)\nchrome_dic['NC_012920.1'] = 'chrM_NC_012920.1'\n# read and extract info\nannotation = subprocess.getoutput('zcat ' + gff + ' | grep -v \"#\"')\nannotation_df = pd.read_csv(StringIO(annotation), sep='\\t', header=None)\nannotation_df['gene'] = annotation_df[8].str.extract('gene=(.*?);')\nannotation_df['ID'] = annotation_df[8].str.extract('ID=(.*?);')\nannotation_df['tag'] = annotation_df[8].str.extract('tag=(.*?);')\nannotation_df['transcript_id'] = annotation_df[8].str.extract('transcript_id=(.*?)$')\nannotation_df.fillna('.', inplace=True)\n# filter RefSeq Select exon info\nannotation_df = annotation_df[annotation_df[2].isin(['exon']) & annotation_df[1].str.contains('RefSeq') & annotation_df[0].str.contains('NC_')].copy()\nannotation_df_select = annotation_df[annotation_df['tag'] == 'RefSeq Select'].copy()\n# process Not RefSeq Select, choose longest\nselect_genes = annotation_df_select['gene'].unique().tolist()\nannotation_df_notselect = annotation_df[(~annotation_df['gene'].isin(select_genes)) & (annotation_df['transcript_id'] != '.')].copy()\nnotselect = annotation_df_notselect.copy()\nnotselect['size'] = notselect[4] - notselect[3] + 1\nnotselect_stat = notselect.groupby(['gene', 'transcript_id']).agg({'size': np.sum}).reset_index()\nnotselect_stat.sort_values(by='size', ascending=False, inplace=True)\nnotselect_stat.drop_duplicates(subset=['gene'], keep='first', inplace=True)\nannotation_df_notselect_choose = annotation_df_notselect[annotation_df_notselect['transcript_id'].isin(notselect_stat['transcript_id'].unique().tolist())].copy()\n# final annotation info\nannotation_df_final = annotation_df_select.append(annotation_df_notselect_choose)\nannotation_df_final[0] = annotation_df_final.apply(lambda x: ac_to_name(chrome_dic, x[0]), axis=1)\nannotation_df_final.to_csv(sys.argv[3], sep='\\t', columns=[0, 3, 4, 6, 'gene', 'ID', 'tag'], index=False, header=None)" }, { "alpha_fraction": 0.5766777396202087, "alphanum_fraction": 0.5984053015708923, "avg_line_length": 49.8445930480957, "blob_id": "954eb2f3f1a23ec4b7a67c7d451d350260966162", "content_id": "0b67b9ee6ca65ec13b88cfb7e110a0b7fd794120", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15050, "license_type": "no_license", "max_line_length": 195, "num_lines": 296, "path": "/maxentscan_wrapper.py", "repo_name": "fzhbioinfo/EnsembleSplice", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\nfrom vcf.parser import _Info as VcfInfo, field_counts as vcf_field_counts\nfrom multiprocessing import Queue, Process, Pool, cpu_count\nfrom maxentpy.maxent import load_matrix5, load_matrix3\nfrom maxentpy.maxent_fast import score5, score3\nfrom functools import partial, reduce\nfrom argparse import ArgumentParser\nfrom collections import namedtuple\nfrom itertools import count\nimport pandas as pd\nimport pyfaidx\nimport queue\nimport vcf\nimport os\n\n\nROOT = os.path.abspath(os.path.dirname(__file__))\nANNOTATION = os.path.join(ROOT, 'annotation')\nVariantRecord = namedtuple('VariantRecord', ['chromosome', 'pos', 'ref', 'alt'])\nVariantAnnotation = namedtuple('VariantAnnotation', ['location', 'exon_nearby', 'exon_start', 'exon_end', 'strand', 'gene'])\n\n\nclass MaxEntScan:\n def __init__(self, annotation, reference):\n self.annotation = pd.read_csv(os.path.join(ANNOTATION, annotation + '.exon.gff.tsv'), sep='\\t', header=None, dtype={0: str})\n self.matrix5 = load_matrix5()\n self.matrix3 = load_matrix3()\n self.reference = pyfaidx.Fasta(reference)\n\n def mes_score(self, record):\n if not (record.ref in ['A', 'T', 'C', 'G', 'a', 't', 'c', 'g'] and record.alt in ['A', 'T', 'C', 'G', 'a', 't', 'c', 'g']):\n return record.alt + '|.|.|.|.'\n record_anno = MaxEntScan.variant_annotation(self.annotation, record, 0)\n seq_ss, seq_ss_mut, ss = '', '', ''\n if record_anno.location == 'exon':\n if record_anno.strand == '+':\n if record.pos + 2 >= record_anno.exon_end:\n seq_ss, seq_ss_mut, ss = MaxEntScan.forward_exon_ss5(self.reference, record, record_anno.exon_end)\n elif record.pos - 2 <= record_anno.exon_start:\n seq_ss, seq_ss_mut, ss = MaxEntScan.forward_exon_ss3(self.reference, record, record_anno.exon_start)\n else:\n if record.pos - 2 <= record_anno.exon_start:\n seq_ss, seq_ss_mut, ss = MaxEntScan.reverse_exon_ss5(self.reference, record, record_anno.exon_start)\n elif record.pos + 2 >= record_anno.exon_end:\n seq_ss, seq_ss_mut, ss = MaxEntScan.reverse_exon_ss3(self.reference, record, record_anno.exon_end)\n return '|'.join([record.alt, record_anno.gene, *MaxEntScan.score_ss_seq(self.matrix5, self.matrix3, seq_ss, seq_ss_mut, ss)])\n else:\n record_anno = MaxEntScan.variant_annotation(self.annotation, record, -6)\n if record_anno.exon_nearby:\n if record_anno.strand == '+':\n seq_ss, seq_ss_mut, ss = MaxEntScan.forward_intron_ss5(self.reference, record, record_anno.exon_end)\n return '|'.join([record.alt, record_anno.gene, *MaxEntScan.score_ss_seq(self.matrix5, self.matrix3, seq_ss, seq_ss_mut, ss)])\n record_anno = MaxEntScan.variant_annotation(self.annotation, record, 20)\n if record_anno.exon_nearby:\n if record_anno.strand == '+':\n seq_ss, seq_ss_mut, ss = MaxEntScan.forward_intron_ss3(self.reference, record, record_anno.exon_start)\n return '|'.join([record.alt, record_anno.gene, *MaxEntScan.score_ss_seq(self.matrix5, self.matrix3, seq_ss, seq_ss_mut, ss)])\n record_anno = MaxEntScan.variant_annotation(self.annotation, record, 6)\n if record_anno.exon_nearby:\n if record_anno.strand == '-':\n seq_ss, seq_ss_mut, ss = MaxEntScan.reverse_intron_ss5(self.reference, record, record_anno.exon_start)\n return '|'.join([record.alt, record_anno.gene, *MaxEntScan.score_ss_seq(self.matrix5, self.matrix3, seq_ss, seq_ss_mut, ss)])\n record_anno = MaxEntScan.variant_annotation(self.annotation, record, -20)\n if record_anno.exon_nearby:\n if record_anno.strand == '-':\n seq_ss, seq_ss_mut, ss = MaxEntScan.reverse_intron_ss3(self.reference, record, record_anno.exon_end)\n return '|'.join([record.alt, record_anno.gene, *MaxEntScan.score_ss_seq(self.matrix5, self.matrix3, seq_ss, seq_ss_mut, ss)])\n return '|'.join([record.alt, '.', *MaxEntScan.score_ss_seq(self.matrix5, self.matrix3, seq_ss, seq_ss_mut, ss)])\n\n @staticmethod\n def variant_annotation(annotation, record, offset):\n exon = annotation[(annotation[0] == record.chromosome) & (annotation[1] <= record.pos + offset) & (record.pos + offset <= annotation[2])]\n if exon.empty:\n location = 'intron'\n exon_nearby = False\n exon_start = None\n exon_end = None\n strand = None\n gene = None\n else:\n location = 'exon'\n exon_nearby = True\n exon_start = exon[1].values[0]\n exon_end = exon[2].values[0]\n strand = exon[3].values[0]\n gene = exon[4].values[0]\n return VariantAnnotation(location, exon_nearby, exon_start, exon_end, strand, gene)\n\n @staticmethod\n def forward_exon_ss5(reference, record, exon_end):\n seq_ss5 = str(reference.get_seq(record.chromosome, exon_end - 2, exon_end + 6))\n seq_ss5 = seq_ss5[0:3].lower() + seq_ss5[3:5] + seq_ss5[5:].lower()\n seq_ss5_mut = seq_ss5[0:record.pos - exon_end + 2] + record.alt + seq_ss5[record.pos - exon_end + 3:]\n return seq_ss5, seq_ss5_mut, 'ss5'\n\n @staticmethod\n def reverse_exon_ss5(reference, record, exon_start):\n seq_ss5 = str(reference.get_seq(record.chromosome, exon_start - 6, exon_start + 2).reverse.complement)\n seq_ss5 = seq_ss5[0:3].lower() + seq_ss5[3:5] + seq_ss5[5:].lower()\n seq_ss5_mut = seq_ss5[0:exon_start - record.pos + 2] + MaxEntScan.base_complement(record.alt) + seq_ss5[exon_start - record.pos + 3:]\n return seq_ss5, seq_ss5_mut, 'ss5'\n\n @staticmethod\n def forward_exon_ss3(reference, record, exon_start):\n seq_ss3 = str(reference.get_seq(record.chromosome, exon_start - 20, exon_start + 2))\n seq_ss3 = seq_ss3[0:18].lower() + seq_ss3[18:20] + seq_ss3[20:].lower()\n seq_ss3_mut = seq_ss3[0:20] + seq_ss3[20:record.pos - exon_start + 20] + record.alt + seq_ss3[record.pos - exon_start + 21:]\n return seq_ss3, seq_ss3_mut, 'ss3'\n\n @staticmethod\n def reverse_exon_ss3(reference, record, exon_end):\n seq_ss3 = str(reference.get_seq(record.chromosome, exon_end - 2, exon_end + 20).reverse.complement)\n seq_ss3 = seq_ss3[0:18].lower() + seq_ss3[18:20] + seq_ss3[20:].lower()\n seq_ss3_mut = seq_ss3[0:20] + seq_ss3[20:exon_end - record.pos + 20] + MaxEntScan.base_complement(record.alt) + seq_ss3[exon_end - record.pos + 21:]\n return seq_ss3, seq_ss3_mut, 'ss3'\n\n @staticmethod\n def forward_intron_ss5(reference, record, exon_end):\n seq_ss5 = str(reference.get_seq(record.chromosome, exon_end - 2, exon_end + 6))\n seq_ss5 = seq_ss5[0:3].lower() + seq_ss5[3:5] + seq_ss5[5:].lower()\n seq_ss5_mut = seq_ss5[0:3] + seq_ss5[3:record.pos - exon_end + 2] + record.alt + seq_ss5[record.pos - exon_end + 3:]\n return seq_ss5, seq_ss5_mut, 'ss5'\n\n @staticmethod\n def reverse_intron_ss5(reference, record, exon_start):\n seq_ss5 = str(reference.get_seq(record.chromosome, exon_start - 6, exon_start + 2).reverse.complement)\n seq_ss5 = seq_ss5[0:3].lower() + seq_ss5[3:5] + seq_ss5[5:].lower()\n seq_ss5_mut = seq_ss5[0:3] + seq_ss5[3:exon_start - record.pos + 2] + MaxEntScan.base_complement(record.alt) + seq_ss5[exon_start - record.pos + 3:]\n return seq_ss5, seq_ss5_mut, 'ss5'\n\n @staticmethod\n def forward_intron_ss3(reference, record, exon_start):\n seq_ss3 = str(reference.get_seq(record.chromosome, exon_start - 20, exon_start + 2))\n seq_ss3 = seq_ss3[0:18].lower() + seq_ss3[18:20] + seq_ss3[20:].lower()\n seq_ss3_mut = seq_ss3[0:record.pos - exon_start + 20] + record.alt + seq_ss3[record.pos - exon_start + 21:]\n return seq_ss3, seq_ss3_mut, 'ss3'\n\n @staticmethod\n def reverse_intron_ss3(reference, record, exon_end):\n seq_ss3 = str(reference.get_seq(record.chromosome, exon_end - 2, exon_end + 20).reverse.complement)\n seq_ss3 = seq_ss3[0:18].lower() + seq_ss3[18:20] + seq_ss3[20:].lower()\n seq_ss3_mut = seq_ss3[0:exon_end - record.pos + 20] + MaxEntScan.base_complement(record.alt) + seq_ss3[exon_end - record.pos + 21:]\n return seq_ss3, seq_ss3_mut, 'ss3'\n\n @staticmethod\n def score_ss_seq(matrix5, matrix3, seq_ss, seq_ss_mut, ss):\n if 'N' in seq_ss or 'N' in seq_ss_mut or 'n' in seq_ss or 'n' in seq_ss_mut:\n return '.', '.', '.'\n if ss == 'ss5':\n score_wt = score5(seq_ss, matrix=matrix5)\n score_mut = score5(seq_ss_mut, matrix=matrix5)\n return str(round(score_wt, 3)), str(round(score_mut, 3)), str(round((score_mut - score_wt) / score_wt, 3))\n elif ss == 'ss3':\n score_wt = score3(seq_ss, matrix=matrix3)\n score_mut = score3(seq_ss_mut, matrix=matrix3)\n return str(round(score_wt, 3)), str(round(score_mut, 3)), str(round((score_mut - score_wt) / score_wt, 3))\n else:\n return '.', '.', '.'\n\n @staticmethod\n def base_complement(dna_base):\n complement_rule = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C', 'a': 'T', 't': 'A', 'c': 'G', 'g': 'C'}\n return complement_rule[dna_base]\n\n\ndef split_df(df, split_num):\n df.reset_index(drop=True, inplace=True)\n df_list = list()\n step = round(df.shape[0]/split_num)\n for i in range(split_num):\n if i == 0:\n df_list.append(df.loc[0: step-1])\n elif i == split_num-1:\n df_list.append(df.loc[step*i:])\n else:\n df_list.append(df.loc[step*i:step*(i+1)-1])\n return df_list\n\n\ndef score_pseudo_vcf(annotation, reference, format_in, df):\n mes = MaxEntScan(annotation, reference)\n if format_in == 'vcf-4cols':\n df['MaxEntScan'] = df.apply(lambda x: mes.mes_score(VariantRecord(x['#CHROM'], x['POS'], x['REF'], x['ALT'])), axis=1)\n else:\n df['MaxEntScan'] = df.apply(lambda x: mes.mes_score(VariantRecord(x['#Chr'], x['Stop'], x['Ref'], x['Call'])), axis=1)\n return df\n\n\ndef annotation_pseudo_vcf(parsed_args, process_num):\n if parsed_args.format_in == 'vcf-4cols':\n df = pd.read_csv(parsed_args.file_in, sep='\\t', dtype={'#CHROM': str})\n else:\n df = pd.read_csv(parsed_args.file_in, sep='\\t', dtype={'#Chr': str})\n df_list = split_df(df, process_num)\n score_partial = partial(score_pseudo_vcf, parsed_args.annotation, parsed_args.reference, parsed_args.format_in)\n with Pool(process_num) as pool:\n df_list_score = pool.map(score_partial, df_list)\n df_score = reduce(lambda x, y: x.append(y), df_list_score)\n df_score.to_csv(parsed_args.file_out, sep='\\t', index=False)\n\n\ndef score_vcf(records, results, annotation, reference):\n mes = MaxEntScan(annotation, reference)\n while True:\n try:\n record = records.get(False)\n except queue.Empty:\n continue\n if record != 'END':\n record_id, record_infos, record_score_list = record[0], record[1], list()\n for record_info in record_infos:\n record_score_list.append(mes.mes_score(record_info))\n results.put((record_id, ','.join(record_score_list)))\n else:\n records.put('END')\n break\n\n\ndef annotation_vcf(parsed_args, process_num):\n records, results = Queue(100 * process_num), Queue()\n input_finished = False\n output_finished = False\n wait_records = dict()\n processes = list()\n records_id = count()\n for i in range(process_num):\n p = Process(target=score_vcf, args=(records, results, parsed_args.annotation, parsed_args.reference))\n processes.append(p)\n p.start()\n vcf_reader = vcf.Reader(filename=parsed_args.file_in)\n vcf_reader.infos['MaxEntScan'] = VcfInfo('MaxEntScan', vcf_field_counts['A'], 'String',\n 'MaxEntScan Score for VCF record alleles, related_score = (mut_score-wild_score)/wild_score Format: ALLELE|SYMBOL|wild_score|mut_score|related_score',\n version=None, source=None)\n vcf_writer = vcf.Writer(open(parsed_args.file_out, 'w'), vcf_reader)\n while True:\n while not records.full() and not input_finished:\n try:\n record = next(vcf_reader)\n record_id = next(records_id)\n wait_records[record_id] = record\n record_infos = list()\n chromosome = str(record.CHROM)\n pos = record.POS\n ref = record.REF\n for alt in record.ALT:\n record_infos.append(VariantRecord(chromosome, pos, ref, str(alt)))\n records.put((record_id, record_infos))\n except StopIteration:\n input_finished = True\n records.put('END')\n break\n processes_status = list()\n for p in processes:\n processes_status.append(p.is_alive())\n if True not in processes_status:\n results.put('END')\n while True:\n try:\n result = results.get(False)\n except queue.Empty:\n break\n if result != 'END':\n record_id, record_score = result[0], result[1]\n record_write = wait_records.pop(record_id)\n record_write.add_info('MaxEntScan', record_score)\n vcf_writer.write_record(record_write)\n else:\n output_finished = True\n break\n if output_finished:\n break\n vcf_writer.close()\n\n\ndef main():\n parser = ArgumentParser()\n parser.add_argument('-r', help='Reference genome fasta file', required=True, dest='reference')\n parser.add_argument('-a', help='Genome annotation: GRCh37 or GRCh38', default='GRCh37', dest='annotation')\n parser.add_argument('-i', help='Input file', required=True, dest='file_in')\n parser.add_argument('-o', help='Output file', required=True, dest='file_out')\n parser.add_argument('--format_in', help='Input file format: vcf,vcf-4cols,bgianno', default='vcf-4cols', dest='format_in')\n parser.add_argument('-p', help='Process number', type=int, default=1, dest='processes')\n parsed_args = parser.parse_args()\n if parsed_args.annotation not in ['GRCh37', 'GRCh38']:\n raise Exception('Genome not recognized! Must be GRCh37 or GRCh38')\n if parsed_args.format_in not in ['vcf', 'vcf-4cols', 'bgianno']:\n raise Exception('Input file format not recognized! Must be vcf, vcf-4cols or bgianno')\n process_num = min(cpu_count(), parsed_args.processes)\n if parsed_args.format_in != 'vcf':\n annotation_pseudo_vcf(parsed_args, process_num)\n else:\n annotation_vcf(parsed_args, process_num)\n\n\nif __name__ == '__main__':\n main()\n" } ]
8
CokaRoach/aigames
https://github.com/CokaRoach/aigames
f7e9b59f07369e086d409b56f9d5e2fa6214d853
4d66dcfe4f2b20e766ec112fa3ce954463dc78fc
069faf2e04dbf80709f879d0215d235b1a4676d5
refs/heads/master
2022-08-26T23:42:44.300470
2020-05-13T07:46:12
2020-05-13T07:46:12
262,674,078
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.3515748083591461, "alphanum_fraction": 0.3618110120296478, "avg_line_length": 30.87421417236328, "blob_id": "6dfe29eecad5d31b785def5c6694139645e7691b", "content_id": "721cfc641146b368d86991babcc3d18fccce7046", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5080, "license_type": "no_license", "max_line_length": 75, "num_lines": 159, "path": "/play.py", "repo_name": "CokaRoach/aigames", "src_encoding": "UTF-8", "text": "class play:\n \n verbose = True\n \n def __init__(self):\n pass\n \n def initialiseBoard(self):\n board = []\n for x in range(7):\n column = []\n for cell in range(6):\n column.append(None)\n board.append(column)\n return board\n \n def playerBoard(self, board, player_num):\n player_board = []\n for column in board:\n player_column = []\n for cell in column:\n if cell is None:\n player_column.append(None)\n else:\n player_column.append(cell == player_num)\n player_board.append(player_column)\n return player_board\n \n def printBoard(self, board):\n none_code = \" \"\n player_codes = [\"O\",\"#\"]\n header = \"+-------+\"\n print(header)\n for y in range(6)[::-1]:\n row = \"|\"\n for x in range(7):\n cell = board[x][y]\n if cell is None:\n row += none_code\n else:\n row += player_codes[cell]\n row += \"|\"\n print(row)\n print(header)\n \n def checkWin(self, board):\n # check columns\n for column in board:\n token = column[0]\n count = 1\n for x in range(1,6):\n cell = column[x]\n if cell is None:\n break\n if cell == token:\n count += 1\n if count == 4:\n return token\n else:\n token = cell\n count = 1\n\n # check rows\n for y in range(6):\n token = board[0][y]\n count = 1\n for x in range(1,7):\n cell = board[x][y]\n if cell is None:\n token = None\n count = 0\n else:\n if cell == token:\n count += 1\n if count == 4:\n return token\n else:\n token = cell\n count = 1\n \n # check diagonals\n for x in range(6):\n token = None\n count = 0\n for y in range(6):\n column = x+y-2\n row = y\n if column >= 0 and column<7:\n cell = board[column][row]\n if cell is None:\n token = None\n count = 0\n else:\n if cell == token:\n count += 1\n if count == 4:\n return token\n else:\n token = cell\n count = 1\n for x in range(6):\n token = None\n count = 0\n for y in range(6):\n column = x-y+3\n row = y\n if column >= 0 and column<7:\n cell = board[column][row]\n if cell is None:\n token = None\n count = 0\n else:\n if cell == token:\n count += 1\n if count == 4:\n return token\n else:\n token = cell\n count = 1\n \n \n \n return None\n \n \n\n def compete(self, player1, player2):\n board = self.initialiseBoard()\n players = [player1, player2]\n turn_num = 0\n while True:\n player_num = turn_num%2\n if self.verbose:\n print(\"Turn #\"+str(turn_num)+\" - Player #\"+str(player_num))\n current_player = players[player_num]\n player_board = self.playerBoard(board, player_num)\n placement_position = current_player.takeTurn(player_board)\n if self.verbose:\n print(\"Insert token, pos \"+str(placement_position))\n if board[placement_position][5] is None:\n for x in range(6):\n if board[placement_position][x] is None:\n board[placement_position][x] = player_num\n break\n else:\n print(\"Error - invalid move - Player #\"+str(player_num))\n return\n if self.verbose:\n self.printBoard(board)\n print(\"--------------------------------\")\n turn_num += 1\n if turn_num == 42:\n print(\"GAME OVER - DRAW\")\n return\n else:\n winner = self.checkWin(board)\n if winner is not None:\n print(\"GAME OVER - Player #\"+str(winner)+\" wins\")\n return\n " }, { "alpha_fraction": 0.4879032373428345, "alphanum_fraction": 0.524193525314331, "avg_line_length": 21.636363983154297, "blob_id": "a0cd35d33d4bd7d27b80ced04cda60757597fd25", "content_id": "c6ea344b5c4cfbac9459c9b38c1f4bd461094676", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 248, "license_type": "no_license", "max_line_length": 47, "num_lines": 11, "path": "/Doofus1.py", "repo_name": "CokaRoach/aigames", "src_encoding": "UTF-8", "text": "from AiC4 import AiC4\n\nclass Doofus(AiC4):\n def __init__(self):\n self.pos = -1\n \n def takeTurn(self, board):\n self.pos += 1\n while board[self.pos%7][5] is not None:\n self.pos += 1\n return self.pos % 7" }, { "alpha_fraction": 0.32582780718803406, "alphanum_fraction": 0.3523178696632385, "avg_line_length": 26, "blob_id": "0c6fa101b894345206eddf629d283745f29d8f79", "content_id": "a23baa646477e92a1a0c77889ddfcf85cd91e7a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 755, "license_type": "no_license", "max_line_length": 52, "num_lines": 28, "path": "/User.py", "repo_name": "CokaRoach/aigames", "src_encoding": "UTF-8", "text": "from AiC4 import AiC4\n\nclass User(AiC4):\n def __init__(self):\n pass\n\n def takeTurn(self, board):\n header = \"+-------+\"\n print(\"Current board state: (you are $)\")\n print(\"+0123456+\")\n print(\"+-------+\")\n for y in range(6)[::-1]:\n row = \"|\"\n for x in range(7):\n cell = board[x][y]\n if cell is None:\n row += \" \"\n else:\n if cell:\n row += \"$\"\n else:\n row += \"@\"\n row += \"|\"\n print(row)\n print(\"+-------+\")\n print(\"+0123456+\")\n print(\"Which column would you like to try?\")\n return int(input())" }, { "alpha_fraction": 0.5225375890731812, "alphanum_fraction": 0.5409014821052551, "avg_line_length": 26.272727966308594, "blob_id": "151c1c33f8e5156d14ff93129f1a7b39e8c5bf6e", "content_id": "a466d72123ee5fee6032eb85616c05f9fc2eb3e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 599, "license_type": "no_license", "max_line_length": 88, "num_lines": 22, "path": "/Idiot1.py", "repo_name": "CokaRoach/aigames", "src_encoding": "UTF-8", "text": "from AiC4 import AiC4\n\nclass Idiot(AiC4):\n def __init__(self):\n pass\n\n \"\"\"\n board is a 2d array of the connect 4 board\n board[0] is the first column\n board[0][0] is the bottom cell in the first column\n values will be one of:\n - True = your token\n - False = oponents token\n - None = empty\n \n return value should be the index column where you want to insert your next token\n \"\"\" \n def takeTurn(self, board):\n for x in range(7):\n if(board[x][5] is None):\n return x\n return -1" }, { "alpha_fraction": 0.4389570653438568, "alphanum_fraction": 0.45552146434783936, "avg_line_length": 28.64545440673828, "blob_id": "a8781507bfeaa0a22a3625ba917b5682a4349126", "content_id": "7650fb00819f7ffed737c8e85c847d1fcd334a31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3260, "license_type": "no_license", "max_line_length": 96, "num_lines": 110, "path": "/Doofus2.py", "repo_name": "CokaRoach/aigames", "src_encoding": "UTF-8", "text": "from AiC4 import AiC4\n\nclass Doofus(AiC4):\n def __init__(self):\n self.pos = -1\n \n # Check for wins, only need to check ones which include that one position\n def checkWin(self, board, column_num, row_num):\n token = board[column_num][row_num]\n \n # check column\n if row_num >=3:\n for x in range(1,4):\n if board[column_num][row_num-x] == token:\n if x == 3:\n return True\n else:\n break\n \n # check row\n count = 1\n for x in range(column_num-1,-1,-1): # previous columns\n if board[x][row_num] == token:\n count += 1\n else:\n break\n for x in range(column_num+1,7): # next columns\n if board[x][row_num] == token:\n count += 1\n else:\n break\n if count >= 4:\n return True\n \n # check forward slash diagnonal \n count = 1\n for x in range(1,4):\n if column_num-x >= 0 and row_num-x >= 0 and board[column_num-x][row_num-x] == token:\n count += 1\n else:\n break\n for x in range(1,4):\n if column_num+x < 7 and row_num+x < 6 and board[column_num+x][row_num+x] == token:\n count += 1\n else:\n break\n if count >= 4:\n return True\n \n # check back slash diagnonal \n count = 1\n for x in range(1,4):\n if column_num-x >= 0 and row_num+x < 6 and board[column_num-x][row_num+x] == token:\n count += 1\n else:\n break\n for x in range(1,4):\n if column_num+x < 7 and row_num-x >=0 and board[column_num+x][row_num-x] == token:\n count += 1\n else:\n break\n if count >= 4:\n return True\n \n return False\n \n \n \n \n def nextRow(self, column):\n for x in range(0,6):\n if column[x] is None:\n return x\n return None\n \n def takeTurn(self, board):\n \n # Check for winning moves\n for column_num in range(0,7):\n row_num = self.nextRow(board[column_num])\n if row_num is not None:\n board[column_num][row_num] = True\n if self.checkWin(board,column_num,row_num):\n return column_num\n board[column_num][row_num] = None\n \n # Check to stop winning moves\n for column_num in range(0,7):\n row_num = self.nextRow(board[column_num])\n if row_num is not None:\n board[column_num][row_num] = False\n if self.checkWin(board,column_num,row_num):\n return column_num\n board[column_num][row_num] = None\n\n # proceed to play \n self.pos += 1\n while board[self.pos%7][5] is not None:\n self.pos += 1\n return self.pos % 7\n \n \n\"\"\"\npython\nfrom play import play\nfrom Idiot1 import Idiot\nfrom Doofus1 import Doofus\np = play()\np.compete(Idiot(), Doofus())\n\"\"\"" } ]
5
nehasunil/deformable_following
https://github.com/nehasunil/deformable_following
161013489ad6a2fccd843984ca260ea6beb612e5
5bbb56e3136fc2195966f6f2926fe956e2c94311
68fa4dca860bdacdf34bd86e1aed23b61efbadde
refs/heads/master
2023-07-22T01:39:12.576350
2021-08-30T20:54:34
2021-08-30T20:54:34
361,874,431
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6052757501602173, "alphanum_fraction": 0.6124700307846069, "avg_line_length": 27.175676345825195, "blob_id": "28d646b1f23749bcbdac3eb5d687a20b3d9b8020", "content_id": "f0d8385547e701187e5b5f6442a89f0ad77e9178", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2085, "license_type": "no_license", "max_line_length": 133, "num_lines": 74, "path": "/perception/wedge/gelsight/gelsight_driver.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n# -*- coding: utf-8\nimport math\nimport numpy as np\nimport socket\nimport time\nfrom math import pi, sin, cos\nfrom .util.streaming import Streaming\nimport cv2\nimport _thread\nfrom threading import Thread\nfrom .pose import Pose\n# from .tracking import Tracking\ntry:\n from .tracking import Tracking\nexcept:\n print(\"warning: tracking is not installed\")\n\nclass GelSight(Thread):\n def __init__(self, IP, corners, tracking_setting=None, output_sz=(210, 270), id='right', pose_enable=True, tracking_enable=True):\n Thread.__init__(self)\n\n url = \"{}:8080/?action=stream\".format(IP)\n self.stream = Streaming(url)\n _thread.start_new_thread(self.stream.load_stream, ())\n\n self.id = id\n self.corners = corners\n self.output_sz = output_sz\n self.tracking_setting = tracking_setting\n self.pose_enable = pose_enable\n self.tracking_enable = tracking_enable\n\n K_pose = 2\n self.output_sz_pose = (output_sz[0]//K_pose, output_sz[1]//K_pose)\n\n # Wait for video streaming\n self.wait_for_stream()\n\n # Start thread for calculating pose\n self.start_pose()\n\n # Start thread for tracking markers\n self.start_tracking()\n\n\n\n def __del__(self):\n self.pc.running = False\n self.tc.running = False\n self.stream.stop_stream()\n print(\"stop_stream\")\n\n def start_pose(self):\n self.pc = Pose(self.stream, self.corners, self.output_sz_pose, id=self.id) # Pose class\n self.pc.start()\n\n def start_tracking(self):\n if self.tracking_setting is not None:\n self.tc = Tracking(self.stream, self.tracking_setting, self.corners, self.output_sz, id=self.id) # Tracking class\n self.tc.start()\n\n def wait_for_stream(self):\n while True:\n img = self.stream.image\n if img is None: \n continue\n else:\n break\n print(\"GelSight {} image found\".format(self.id))\n\n def run(self):\n print(\"Run GelSight driver\")\n pass\n" }, { "alpha_fraction": 0.49111807346343994, "alphanum_fraction": 0.5987460613250732, "avg_line_length": 32, "blob_id": "abb0e4a4d3647026703689b624fc18a81518907d", "content_id": "dccdf9a4ea79ab1ea92575db92d1aa733391a0e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 957, "license_type": "no_license", "max_line_length": 76, "num_lines": 29, "path": "/perception/fabric/util/segmentation.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\n\n\ndef segmentation(img):\n img = cv2.GaussianBlur(img, (3, 3), 0)\n img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n\n lower_green = np.array([40, 50, 40])\n upper_green = np.array([80, 255, 255])\n lower_red_1 = np.array([0, 100, 80])\n upper_red_1 = np.array([10, 255, 255])\n lower_red_2 = np.array([170, 100, 80])\n upper_red_2 = np.array([180, 255, 255])\n lower_yellow = np.array([20, 150, 80])\n upper_yellow = np.array([40, 255, 255])\n\n mask_green = cv2.inRange(img_hsv, lower_green, upper_green)\n mask_red = cv2.inRange(img_hsv, lower_red_1, upper_red_1) | cv2.inRange(\n img_hsv, lower_red_2, upper_red_2\n )\n mask_yellow = cv2.inRange(img_hsv, lower_yellow, upper_yellow)\n\n mask = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.float32)\n mask[mask_yellow == 255] = [0, 1, 1]\n mask[mask_green == 255] = [0, 1, 0]\n mask[mask_red == 255] = [0, 0, 1]\n\n return mask\n" }, { "alpha_fraction": 0.4538009464740753, "alphanum_fraction": 0.5268826484680176, "avg_line_length": 22.40416717529297, "blob_id": "5aba748ba3c6c48df8052a13004c8106f37aaa4b", "content_id": "921e7a4f073fda2ba21d9940741db7f2c4010e6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11234, "license_type": "no_license", "max_line_length": 80, "num_lines": 480, "path": "/controller/mini_robot_arm/arm_control.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import serial\nimport time\nimport ik\nfrom math import pi, sin, cos, fabs\nimport numpy as np\nimport random\nfrom numpy import abs\nimport copy\nimport math\n\nser = serial.Serial(\"/dev/tty.usbmodem145301\", 1000000) # open serial port\nprint(ser.name) # check which port was really used\n\ntime.sleep(1)\nO = np.array([[0], [0]])\n# ser.write(b'torque 1\\n')\n\n\ndef send(values):\n goal_str = \" \".join([str(_) for _ in values])\n # print(goal_str)\n ser.write(str.encode((\"goal {}\\n\".format(goal_str)))) # write a string\n\n\ndef setxy(values, end_angle, x, y):\n global O\n O = ik.ik(end_angle, x, y, O)\n joint = 2048 - O / pi * 2048\n\n values[1] = int(joint[0, 0])\n values[2] = int(joint[1, 0])\n values[3] = int(joint[2, 0])\n # print(values[3])\n\n\ndef gogo(values, x, y, ang, goal_x, goal_y, goal_ang, goal_rot, timestamp=30.0):\n global O\n\n # timestamp = 30.\n dx = (goal_x - x) / timestamp\n dy = (goal_y - y) / timestamp\n da = (goal_ang - ang) / timestamp\n dr = (goal_rot - values[-2]) / timestamp\n\n for t in range(int(timestamp)):\n x += dx\n y += dy\n ang += da\n values[-2] += dr\n # print(dx, dy, da, dr)\n setxy(values, ang, x, y)\n send(values)\n time.sleep(0.01)\n\n x = goal_x\n y = goal_y\n ang = goal_ang\n values[-2] = goal_rot\n # print(dx, dy, da, dr)\n setxy(values, ang, x, y)\n send(values)\n # time.sleep(0.03)\n\n\ndef robot_grasp(pos, gripper_close):\n global O\n if pos == 1:\n grasp_pos = 305\n down_pos = -75\n else:\n grasp_pos = 300\n down_pos = -77\n # O = np.array([[0], [0]])\n # ser.write(b'torque 1\\n')\n g_close = gripper_close\n g_open = 2000\n values = [2045, 2549, 1110, 1400, 2048, g_open]\n x, y = 310, 120\n end_angle = 0.0\n\n # gogo(values, x, y, end_angle, x, y, end_angle, g_open)\n # print(values, x, y, end_angle)\n # time.sleep(2)\n\n gogo(values, x, y, end_angle, 280, 50, 1.5, 0)\n x = 280\n y = 50\n end_angle = 1.5\n # print(values, x, y, end_angle)\n # time.sleep(2)\n\n # down_pos = down_pos + random.randint(-2, 2)\n down_pos = down_pos\n gogo(values, x, y, end_angle, grasp_pos, down_pos, 1.5, 0)\n x = grasp_pos\n print(x)\n y = down_pos\n end_angle = 1.5\n # print(values, x, y, end_angle)\n # time.sleep(2)\n\n values[-1] = g_close\n setxy(values, end_angle, x, y)\n send(values)\n time.sleep(1)\n\n gogo(values, x, y, end_angle, 280, 120, 1.5, 0)\n x = 280\n y = 120\n end_angle = 1.5\n # print(values, x, y, end_angle)\n # time.sleep(2)\n\n gogo(values, x, y, end_angle, 300, 180, 0, 2050)\n x = 300\n y = 180\n end_angle = 0\n # print(values, x, y, end_angle)\n\n # time.sleep(4)\n\n # ser.close() # close port\n\n # over.put('stop')\n\n\ndef robot_prepare(gripper_close):\n g_close = gripper_close\n g_open = 2000\n values = [2045, 2549, 1110, 2136, 2048, g_close]\n x, y = 300, 180\n end_angle = 0\n gogo(values, x, y, end_angle, 300, 100, 0.2, 2050)\n x, y = 300, 100\n end_angle = 0.2\n # print(values, x, y, end_angle)\n\n\ndef robot_ready(final_angle=0):\n g_close = 1000\n g_open = 2000\n values = [2045, 2549, 1110, 2136, 2048, g_open]\n if final_angle < 150:\n x, y = 310, 120\n end_angle = 0.0\n\n setxy(values, end_angle, x, y)\n send(values)\n else:\n x, y = 330, 120\n end_angle = 0.0\n\n setxy(values, end_angle, x, y)\n send(values)\n\n time.sleep(0.8)\n\n x, y = 310, 120\n end_angle = 0.0\n\n setxy(values, end_angle, x, y)\n send(values)\n\n # gogo(values, x, y, end_angle, x, y, end_angle, g_open)\n\n\ndef robot_sysid60(gripper_close):\n g_close = gripper_close\n g_open = 2000\n values = [2045, 2549, 1110, 2136, 2048, g_close]\n x, y = 300, 180\n end_angle = 0.0\n\n gogo(values, x, y, end_angle, x, y, -0.4, 2050)\n end_angle = -0.4\n\n\ndef robot_sysid90(gripper_close):\n g_close = gripper_close\n g_open = 2000\n values = [2045, 2549, 1110, 2136, 2048, g_close]\n x, y = 300, 180\n end_angle = -0.4\n\n gogo(values, x, y, end_angle, x, y, -0.9, 2050)\n end_angle = -0.9\n\n\ndef robot_sysidback(gripper_close):\n g_close = gripper_close\n g_open = 2000\n values = [2045, 2549, 1110, 2136, 2048, g_close]\n x, y = 300, 180\n end_angle = -0.9\n\n gogo(values, x, y, end_angle, x, y, 0.0, 2050)\n end_angle = 0.0\n\n\ndef robot_shake(gripper_close, theta):\n g_close = gripper_close\n g_open = 2000\n values = [2045, 2549, 1110, 2136, 2048, g_close]\n x, y = 300, 180\n end_angle = 0.0\n setxy(values, end_angle, x, y)\n\n flag = 1\n # shake_range_x = 15\n # shake_range_y = 25\n\n # dx = flag * math.cos(theta/180.0*math.pi) * shake_range_x\n # dy = flag * math.sin(theta/180.0*math.pi) * shake_range_y\n # for k in range(6):\n # gogo(values, x, y, end_angle, x + dx, y + dy, 0.0, 2050, 5.0)\n # x = x + dx\n # y = y + dy\n # flag *= -1\n # dx = flag * math.cos(theta/180.0*math.pi) * shake_range_x\n # dy = flag * math.sin(theta/180.0*math.pi) * shake_range_y\n\n shake_range_angle = int(10 / 360 * 4096)\n mv_range = 30\n\n values[-1] += 150\n goal_str = \" \".join([str(_) for _ in values])\n ser.write(str.encode((\"goal {}\\n\".format(goal_str))))\n\n ser.write(str.encode((\"goal_clear \\n\")))\n\n steps = 10\n for k in range(8):\n # if k % 2 == 0:\n # values[-1] += 15\n # values[-3] += flag*shake_range_angle\n\n for _ in range(steps):\n x = x + (mv_range / steps) * flag\n setxy(values, end_angle, x, y)\n\n goal_str = \" \".join([str(_) for _ in values])\n ser.write(str.encode((\"goal_stack {}\\n\".format(goal_str))))\n time.sleep(0.01)\n\n flag *= -1\n\n ser.write(str.encode((\"goal_run \\n\")))\n\n time.sleep(1.5)\n values[-1] = gripper_close - 20\n goal_str = \" \".join([str(_) for _ in values])\n ser.write(str.encode((\"goal {}\\n\".format(goal_str))))\n\n time.sleep(0.4)\n\n\ndef robot_shake_origin(gripper_close, theta):\n g_close = gripper_close\n g_open = 2000\n values = [2045, 2549, 1110, 2136, 2048, g_close]\n x, y = 300, 180\n end_angle = 0.0\n setxy(values, end_angle, x, y)\n\n flag = 1\n # shake_range_x = 15\n # shake_range_y = 25\n\n # dx = flag * math.cos(theta/180.0*math.pi) * shake_range_x\n # dy = flag * math.sin(theta/180.0*math.pi) * shake_range_y\n # for k in range(6):\n # gogo(values, x, y, end_angle, x + dx, y + dy, 0.0, 2050, 5.0)\n # x = x + dx\n # y = y + dy\n # flag *= -1\n # dx = flag * math.cos(theta/180.0*math.pi) * shake_range_x\n # dy = flag * math.sin(theta/180.0*math.pi) * shake_range_y\n\n shake_range_angle = int(10 / 360 * 4096)\n for k in range(6):\n values[-3] += flag * shake_range_angle\n goal_str = \" \".join([str(_) for _ in values])\n ser.write(str.encode((\"goal {}\\n\".format(goal_str))))\n time.sleep(0.2)\n flag *= -1\n\n\ndef robot_ready2():\n g_open = 2000\n values = [2045, 2549, 1110, 2136, 2048, g_open]\n x, y = 300, 180\n end_angle = -0.9\n setxy(values, end_angle, x, y)\n send(values)\n # gogo(values, x, y, end_angle, x, y, end_angle, g_open)\n\n\ndef robot_sysidback2(gripper_close):\n g_close = gripper_close\n g_open = 2000\n values = [2045, 2549, 1110, 2136, 2048, g_close]\n x, y = 300, 180\n end_angle = -0.9\n\n gogo(values, x, y, end_angle, 310, 120, 0.0, 2050)\n x, y = 310, 120\n end_angle = 0.0\n\n\ndef robot_go(gripper_close, gripper_open, ratio=1.0):\n global O\n # O = np.array([[0], [0]])\n # ser.write(b'torque 1\\n')\n\n values = [2045, 2549, 1110, 2136, 2048, 2000]\n values0 = None\n\n scale = 2.0\n\n ddy = 0.8 * scale\n\n vel = 15 * ratio\n dy = vel\n g_close = gripper_close\n g_open = gripper_open\n distance = 220 * ratio\n end_angle = 0.2\n ang_vel = 0.08 * ratio\n da = ang_vel\n\n x, y = 300, 100\n init_y = 100\n\n # values[-1] = 2000\n # setxy(values, end_angle, x, y)\n # send(values)\n # time.sleep(2)\n\n # values[-1] = g_close\n # setxy(values, end_angle, x, y)\n # send(values)\n # time.sleep(2)\n\n # for t in range(40):\n # end_angle += 0.01\n # setxy(values, end_angle, x, y)\n # send(values)\n # time.sleep(0.008)\n # time.sleep(2)\n cnt = 0\n\n ser.write(str.encode((\"goal_clear \\n\")))\n while True:\n y += dy\n end_angle -= da\n\n # if dy > 0:\n # values[-1] = g_close\n # if dy < 0:\n # values[-1] = g_open\n\n if dy < 0:\n values[-1] = g_open\n else:\n values[-1] = g_close\n\n if y > init_y + distance:\n dy = -vel\n da = -ang_vel\n elif y < init_y:\n # dy = vel\n # da = ang_vel\n\n dy = 0\n da = 0\n values[-1] = g_close\n\n # print(y, end_angle, dy)\n\n O = ik.ik(end_angle, x, y, O)\n joint = 2048 - O / pi * 2048\n\n values[1] = int(joint[0, 0])\n values[2] = int(joint[1, 0])\n values[3] = int(joint[2, 0])\n\n if values0 is None:\n values0 = copy.deepcopy(values)\n\n goal_str = \" \".join([str(_) for _ in values])\n # ser.write(str.encode(('goal {}\\n'.format(goal_str))))\n ser.write(str.encode((\"goal_stack {}\\n\".format(goal_str))))\n\n # print(goal_str)\n if dy == 0:\n break\n # time.sleep(0.008)\n time.sleep(0.001)\n\n cnt += 1\n # print(cnt, \"steps\")\n\n ser.write(str.encode((\"goal_run \\n\")))\n\n time.sleep(1.0)\n gogo(values, x, y, end_angle, 300, 180, 0.0, 2050)\n x, y = 300, 180\n end_angle = 0.0\n\n # goal_str = ' '.join([str(_) for _ in values0])\n # ser.write(str.encode(('goal {}\\n'.format(goal_str))))\n\n # ser.close() # close port\n\n # over.put('stop')\n\n\ndef read_addr(addr, bit):\n ser.write(str.encode(\"readreg {} {}\\n\".format(addr, bit)))\n for i in range(2):\n line = ser.readline()\n print(line)\n data = int(str(line).split(\"Data: \")[-1][:-4])\n return data\n\n\ndef set_servoid(id):\n ser.write(str.encode(\"setcurrentservoid {}\\n\".format(id)))\n for i in range(1):\n line = ser.readline()\n print(line)\n\n\ndef read_goal_current():\n return read_addr(102, 2)\n\n\ndef read_current():\n return read_addr(126, 2)\n\n\ndef read_position():\n return read_addr(132, 4)\n\n\ndef write_goal_current(current):\n ser.write(str.encode(\"writereg 102 2 {}\\n\".format(current)))\n for i in range(2):\n line = ser.readline()\n print(line)\n\n\ndef write_position(position):\n ser.write(str.encode(\"writereg 116 4 {}\\n\".format(position)))\n for i in range(2):\n line = ser.readline()\n print(line)\n\n\ndef readpos():\n ser.write(str.encode(\"readpos \\n\"))\n for i in range(1):\n line = ser.readline()\n print(line)\n\n\ndef torque(enable=1):\n ser.write(str.encode(\"torque {}\\n\".format(enable)))\n for i in range(6):\n line = ser.readline()\n print(line)\n\n\n# robot_go()\n\n# readpos()\ntorque(1)\npos = 0\ngripper_close_min = 900\nrobot_grasp(pos, gripper_close_min)\n" }, { "alpha_fraction": 0.6629412770271301, "alphanum_fraction": 0.6818863153457642, "avg_line_length": 37.41884994506836, "blob_id": "c7366cce230900368ad3da0085f8b1a700b77145", "content_id": "923ad33638b33abbb345ec4ad9ac6f14ccec1070", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7337, "license_type": "no_license", "max_line_length": 209, "num_lines": 191, "path": "/controller/gripper/NewMotorCurrentBasedPositionControl_2020.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 17 14:13:36 2019\n\n@author: yushe\n\"\"\"\n\n\nimport os\nimport sys, tty, termios\nfrom simple_pid import PID\n\nimport cv2\nimport numpy as np\nimport _thread\nimport time\n\nfrom dynamixel_sdk import * \n\n\n################################################################################################################\n#setup for the motor\nADDR_MX_TORQUE_ENABLE = 64 # Control table address is different in Dynamixel model\nADDR_MX_GOAL_POSITION = 116\nADDR_MX_PRESENT_POSITION = 132\n\n# Protocol version\nPROTOCOL_VERSION = 2.0 # See which protocol version is used in the Dynamixel\n\n# Default setting\n\nBAUDRATE = 57600 # Dynamixel default baudrate : 57600\n# DEVICENAME = '/dev/tty.usbserial-FT2N061F' # Check which port is being used on your controller\n # ex) Windows: \"COM1\" Linux: \"/dev/ttyUSB0\" Mac: \"/dev/tty.usbserial-*\"\nDEVICENAME = '/dev/ttyUSB0' # Check which port is being used on your controller\n # ex) \n\n\n\nTORQUE_ENABLE = 1 # Value for enabling the torque\nTORQUE_DISABLE = 0 # Value for disabling the torque\nDXL_MINIMUM_POSITION_VALUE = 938 # Dynamixel will rotate between this value\nDXL_MAXIMUM_POSITION_VALUE = 1738 # and this value (note that the Dynamixel would not move when the position value is out of movable range. Check e-manual about the range of the Dynamixel you use.)\nDXL_MOVING_STATUS_THRESHOLD = 5 \n\n\nDXL_ID =1\n\n\n# Initialize PortHandler instance\n# Set the port path\n# Get methods and members of PortHandlerLinux or PortHandlerWindows\nportHandler = PortHandler(DEVICENAME)\n\n# Initialize PacketHandler instance\n# Set the protocol version\n# Get methods and members of Protocol1PacketHandler or Protocol2PacketHandler\npacketHandler = PacketHandler(PROTOCOL_VERSION)\n\n# Open port\nif portHandler.openPort():\n print(\"Succeeded to open the port\")\nelse:\n print(\"Failed to open the port\")\n\n\n\n# Set port baudrate\nif portHandler.setBaudRate(BAUDRATE):\n print(\"Succeeded to change the baudrate\")\nelse:\n print(\"Failed to change the baudrate\")\n\n# Enable Dynamixel Torque\ndxl_comm_result, dxl_error = packetHandler.write1ByteTxRx(portHandler, DXL_ID, ADDR_MX_TORQUE_ENABLE, TORQUE_DISABLE)\nif dxl_comm_result != COMM_SUCCESS:\n print(\"%s\" % packetHandler.getTxRxResult(dxl_comm_result))\nelif dxl_error != 0:\n print(\"%s\" % packetHandler.getRxPacketError(dxl_error))\nelse:\n print(\"Dynamixel has been successfully connected\")\n\n\n\n# Changing operating mode\nADDR_OPERATING_MODE= 11\nOP_MODE_POSITION= 5\ndxl_comm_result, dxl_error = packetHandler.write2ByteTxRx(portHandler, DXL_ID, ADDR_OPERATING_MODE, OP_MODE_POSITION)\n\n# set the current limit\nADDR_CURRENT_LIMIT = 38\nCURRENT_LIMIT_UPBOUND = 1193\ndxl_comm_result, dxl_error = packetHandler.write2ByteTxRx(portHandler, DXL_ID, ADDR_CURRENT_LIMIT, CURRENT_LIMIT_UPBOUND)\n\n#SET THE VELOCITU LIMIT\nADDR_VELOCITY_LIMIT = 44\nVELOCITY_LIMIT_UPBOUND = 1023\ndxl_comm_result, dxl_error = packetHandler.write2ByteTxRx(portHandler, DXL_ID, ADDR_VELOCITY_LIMIT, VELOCITY_LIMIT_UPBOUND)\n\n#SET THE MAX POSITION LIMIT\nADDR_MAX_POSITION_LIMIT = 48\nMAX_POSITION_LIMIT_UPBOUND = DXL_MAXIMUM_POSITION_VALUE\ndxl_comm_result, dxl_error = packetHandler.write2ByteTxRx(portHandler, DXL_ID, ADDR_MAX_POSITION_LIMIT, MAX_POSITION_LIMIT_UPBOUND)\n\n#SET THE MIN POSITION LIMIT\nADDR_MIN_POSITION_LIMIT = 52\nMIN_POSITION_LIMIT_UPBOUND = DXL_MINIMUM_POSITION_VALUE\ndxl_comm_result, dxl_error = packetHandler.write2ByteTxRx(portHandler, DXL_ID, ADDR_MIN_POSITION_LIMIT, MIN_POSITION_LIMIT_UPBOUND)\n\n\n\nADDR_GOAL_CURRENT = 102\n#GOAL_CURRENT_MINPOSITION = 1\n\n# SET THE GOAL VELOCITY\nADDR_GOAL_VELOCITY = 104\nGOAL_VELOCITY_MAXPOSITION = 1023\ndxl_comm_result, dxl_error = packetHandler.write2ByteTxRx(portHandler, DXL_ID, ADDR_GOAL_VELOCITY, GOAL_VELOCITY_MAXPOSITION)\n\n\nADDR_ACCELERATION_PROFILE = 108\nACCELERATION_ADDRESS_POSITION= 0\ndxl_comm_result, dxl_error = packetHandler.write2ByteTxRx(portHandler, DXL_ID, ADDR_ACCELERATION_PROFILE, ACCELERATION_ADDRESS_POSITION)\n\nADDR_VELOCITY_PROFILE = 112\nVELOCITY_ADDRESS_POSITION= 0\ndxl_comm_result, dxl_error = packetHandler.write2ByteTxRx(portHandler, DXL_ID, ADDR_VELOCITY_PROFILE, VELOCITY_ADDRESS_POSITION)\n \n\n# Enable Dynamixel Torque\ndxl_comm_result, dxl_error = packetHandler.write1ByteTxRx(portHandler, DXL_ID, ADDR_MX_TORQUE_ENABLE, TORQUE_ENABLE)\nif dxl_comm_result != COMM_SUCCESS:\n print(\"%s\" % packetHandler.getTxRxResult(dxl_comm_result))\nelif dxl_error != 0:\n print(\"%s\" % packetHandler.getRxPacketError(dxl_error))\nelse:\n print(\"Dynamixel has been successfully connected\")\n \n\n#dxl_comm_result, dxl_error = packetHandler.write1ByteTxRx(portHandler, DXL_ID, 34, 90)\n################################################################################################################\n\n\n #main code \n################################################################################################################\n\nCurrentPosition = DXL_MINIMUM_POSITION_VALUE\nPositionThreshold_UP = DXL_MAXIMUM_POSITION_VALUE\nPositionThreshold_DOWN = DXL_MINIMUM_POSITION_VALUE\nPositionIncrease =100\n\nCurrentTorque = 200\nTorqueThreshold_UP = 1193\nTorqueThreshold_DOWN = 0\nTorqueIncrease = 100\n\n\ndxl_comm_result, dxl_error = packetHandler.write2ByteTxRx(portHandler, DXL_ID, ADDR_GOAL_CURRENT, CurrentTorque) \ndxl_comm_result, dxl_error = packetHandler.write4ByteTxRx(portHandler, DXL_ID, ADDR_MX_GOAL_POSITION, CurrentPosition)\n\nSign_Moving = 0\nwhile True:\n if Sign_Moving == 0:\n if CurrentPosition >= PositionThreshold_DOWN and CurrentPosition <= PositionThreshold_UP:\n CurrentPosition = CurrentPosition + PositionIncrease \n time.sleep(0.01) \n if CurrentPosition > PositionThreshold_UP:\n CurrentPosition = PositionThreshold_UP\n Sign_Moving = 1 \n if CurrentPosition < PositionThreshold_DOWN:\n CurrentPosition = PositionThreshold_DOWN\n if Sign_Moving == 1:\n if CurrentPosition >= PositionThreshold_DOWN and CurrentPosition <= PositionThreshold_UP:\n CurrentPosition = CurrentPosition - PositionIncrease \n time.sleep(0.01) \n if CurrentPosition > PositionThreshold_UP:\n CurrentPosition = PositionThreshold_UP \n if CurrentPosition < PositionThreshold_DOWN:\n CurrentPosition = PositionThreshold_DOWN \n Sign_Moving = 0 \n # if CurrentTorque > TorqueThreshold_DOWN and CurrentTorque < TorqueThreshold_UP:\n # CurrentTorque = CurrentTorque + TorqueIncrease\n # if CurrentTorque >= TorqueThreshold_UP:\n # CurrentTorque = TorqueThreshold_UP\n # if CurrentTorque <= TorqueThreshold_DOWN:\n # CurrentTorque = TorqueThreshold_DOWN\n print(\"Current Position:\", CurrentPosition)\n print(\"Current_Torque:\", CurrentTorque)\n dxl_comm_result, dxl_error = packetHandler.write2ByteTxRx(portHandler, DXL_ID, ADDR_GOAL_CURRENT, CurrentTorque)\n dxl_comm_result, dxl_error = packetHandler.write4ByteTxRx(portHandler, DXL_ID, ADDR_MX_GOAL_POSITION, CurrentPosition)" }, { "alpha_fraction": 0.5393474102020264, "alphanum_fraction": 0.6235604882240295, "avg_line_length": 36.890907287597656, "blob_id": "da929eb9192e02c3111e715e1180dcd1a9832ef2", "content_id": "36e59bc541db599bc0237710724e6fda667181d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4168, "license_type": "no_license", "max_line_length": 156, "num_lines": 110, "path": "/touch.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport time\nimport cv2\nfrom controller.ur5.ur_controller import UR_Controller\nfrom perception.kinect.kinect_camera import Kinect\nfrom scipy.spatial.transform import Rotation as R\n\ncam_intrinsics_origin = np.array([\n[917.3927285, 0., 957.21294894],\n[ 0., 918.96234057, 555.32910487],\n[ 0., 0., 1. ]])\ncam_intrinsics = np.array([\n[965.24853516, 0., 950.50838964],\n [ 0., 939.67144775, 554.55567298],\n [ 0., 0., 1. ]]) # New Camera Intrinsic Matrix\ndist = np.array([[ 0.0990126, -0.10306044, 0.00024658, -0.00268176, 0.05763196]])\ncamera = Kinect(cam_intrinsics_origin, dist)\n\ncam_pose = np.loadtxt('real/camera_pose.txt', delimiter=' ')\ncam_depth_scale = np.loadtxt('real/camera_depth_scale.txt', delimiter=' ')\n\n# User options (change me)\n# --------------- Setup options ---------------\nurc = UR_Controller()\nurc.start()\na = 0.05\nv = 0.05\n\n# workspace_limits = np.asarray([[0.3, 0.748], [-0.224, 0.224], [-0.255, -0.1]]) # Cols: min max, Rows: x y z (define workspace limits in robot coordinates)\nworkspace_limits = np.asarray([[-0.845, -0.605], [-0.14, 0.2], [0, 0.2]]) # Cols: min max, Rows: x y z (define workspace limits in robot coordinates)\n\n# tool_orientation = [2.22,-2.22,0]\n# tool_orientation = [0., -np.pi/2, 0.] # [0,-2.22,2.22] # [2.22,2.22,0]\nfrom scipy.spatial.transform import Rotation as R\n# tool_orientation_euler = [180, 0, 90]\n# tool_orientation_euler = [180, 0, 0]\ntool_orientation_euler = [180, 0, 180]\ntool_orientation = R.from_euler('xyz', tool_orientation_euler, degrees=True).as_rotvec()\n\n\n# tool_orientation = [0., -np.pi/2, 0.] # [0,-2.22,2.22] # [2.22,2.22,0]\n# tool_orientation = [0., -np.pi/2, 0.] # [0,-2.22,2.22] # [2.22,2.22,0]\n\n# pose0 = np.array([-0.511, 0.294, 0.237, -0.032, -1.666, 0.138])\npose0 = np.hstack([[-0.505, 0.2, 0.2], tool_orientation])\nurc.movel_wait(pose0, a=a, v=v)\n# ---------------------------------------------\n\n\n# Move robot to home pose\n# robot = Robot(False, None, None, workspace_limits,\n# tcp_host_ip, tcp_port, rtc_host_ip, rtc_port,\n# False, None, None)\n# robot.open_gripper()\n\n# Slow down robot\n# robot.joint_acc = 1.4\n# robot.joint_vel = 1.05\n\n# Callback function for clicking on OpenCV window\nclick_point_pix = ()\n# camera_color_img, camera_depth_img = robot.get_camera_data()\ncamera_color_img, camera_depth_img = camera.get_image()\ndef mouseclick_callback(event, x, y, flags, param):\n if event == cv2.EVENT_LBUTTONDOWN:\n global camera, robot, click_point_pix\n click_point_pix = (x,y)\n\n # Get click point in camera coordinates\n click_z = camera_depth_img[y][x] * cam_depth_scale\n click_x = np.multiply(x-cam_intrinsics[0][2],click_z/cam_intrinsics[0][0])\n click_y = np.multiply(y-cam_intrinsics[1][2],click_z/cam_intrinsics[1][1])\n if click_z == 0:\n return\n click_point = np.asarray([click_x,click_y,click_z])\n click_point.shape = (3,1)\n\n # Convert camera to robot coordinates\n # camera2robot = np.linalg.inv(robot.cam_pose)\n camera2robot = cam_pose\n target_position = np.dot(camera2robot[0:3,0:3],click_point) + camera2robot[0:3,3:]\n\n target_position = target_position[0:3,0]\n print(target_position)\n # robot.move_to(target_position, tool_orientation)\n pose = np.hstack([target_position, tool_orientation])\n urc.movel_wait(pose, a=a, v=v)\n\n\n# Show color and depth frames\ncv2.namedWindow('color')\ncv2.setMouseCallback('color', mouseclick_callback)\ncv2.namedWindow('depth')\n\nwhile True:\n # camera_color_img, camera_depth_img = robot.get_camera_data()\n camera_color_img, camera_depth_img = camera.get_image()\n bgr_data = camera_color_img# cv2.cvtColor(camera_color_img, cv2.COLOR_RGB2BGR)\n if len(click_point_pix) != 0:\n bgr_data = cv2.circle(bgr_data, click_point_pix, 7, (0,0,255), 2)\n cv2.imshow('color', bgr_data)\n cv2.imshow('depth', camera_depth_img / 1100.)\n\n if cv2.waitKey(1) == ord('c'):\n break\n\ncv2.destroyAllWindows()\n" }, { "alpha_fraction": 0.4895833432674408, "alphanum_fraction": 0.5477430820465088, "avg_line_length": 23, "blob_id": "ed6ea639daad348dd99f6dfe6d45fcefed5fc48a", "content_id": "965d456dbae39d2ea6d7ad5637552b8bd447669b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1152, "license_type": "no_license", "max_line_length": 78, "num_lines": 48, "path": "/perception/kinect/collect_data.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import cv2\nimport pyk4a\nfrom helpers import colorize\nfrom pyk4a import Config, PyK4A\nimport numpy as np\n\n\ndef main():\n k4a = PyK4A(\n Config(\n color_resolution=pyk4a.ColorResolution.RES_1080P,\n depth_mode=pyk4a.DepthMode.NFOV_UNBINNED,\n )\n )\n k4a.start()\n\n exp_dict = {-11: 500, -10: 1250, -9: 2500, -8: 8330, -7: 16670, -6: 33330}\n exp_val = -7 # to be changed when running\n k4a.exposure = exp_dict[exp_val]\n\n id = 0\n\n while True:\n capture = k4a.get_capture()\n\n if capture.color is not None:\n color = capture.color\n cv2.imshow(\"Color\", color)\n\n if capture.transformed_depth is not None:\n depth_transformed = capture.transformed_depth\n cv2.imshow(\n \"Transformed Depth\", colorize(depth_transformed, (0, 1100))\n )\n\n key = cv2.waitKey(1)\n if key == ord('s'):\n cv2.imwrite(f\"data/intrinsic_1080p/color_{id}.png\", color)\n id += 1\n elif key == ord('q'):\n cv2.destroyAllWindows()\n break\n\n k4a.stop()\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.5140751600265503, "alphanum_fraction": 0.5277818441390991, "avg_line_length": 33.09547805786133, "blob_id": "707ef04dfc22da68d3c9d5fe8e4447248c4901d1", "content_id": "cfb93cf8f41a44d086b53305b27269fba2bb3e24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6785, "license_type": "no_license", "max_line_length": 87, "num_lines": 199, "path": "/perception/fabric/data_loader.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\n\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\nimport numpy as np\nimport random\nimport os\nimport cv2\nimport random\nfrom utils import normalize\n\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import utils\nimport torchvision.transforms.functional as tf\nimport torchvision.transforms as T\n\n\nclass TowelDataset(Dataset):\n def __init__(self, root_dir, phase, use_transform=True, datasize=None):\n self.root_dir = root_dir\n self.phase = phase\n self.use_transform = use_transform\n\n filename = [f for f in os.listdir(self.root_dir) if f.startswith(\"color\")]\n print(datasize)\n self.imgs = (\n filename if (datasize is \"\" or datasize is None) else filename[0:datasize]\n )\n # print(self.imgs)\n\n if self.phase == \"train\":\n self.total_data_num = (\n int(len(self.imgs) / 6 * 4) if len(self.imgs) > 8 else len(self.imgs)\n )\n elif self.phase == \"val\":\n self.total_data_num = int(len(self.imgs) / 6)\n elif self.phase == \"test\":\n self.total_data_num = int(len(self.imgs) / 6)\n\n print(\"Datapoints: %d\" % self.total_data_num)\n\n def __len__(self):\n return self.total_data_num\n\n def __getitem__(self, idx):\n if self.phase == \"val\":\n idx = idx + self.total_data_num * 4\n elif self.phase == \"test\":\n idx = idx + self.total_data_num * 5\n\n # imidx = self.imgs[idx].split(\"_\")[1].replace(\".png\", \"\")\n imidx = self.imgs[idx].split(\"_\")[1].replace(\".jpg\", \"\")\n img_path = os.path.join(self.root_dir, self.imgs[idx])\n depth_path = os.path.join(self.root_dir, \"depth_\" + imidx + \".npy\")\n\n img_rgb = Image.open(img_path)\n\n depth_npy = np.load(depth_path)\n depth_npy[np.isnan(depth_npy)] = max_d = np.nanmax(depth_npy)\n\n depth_min, depth_max = 400.0, 1100.0\n depth_npy = (depth_npy - depth_min) / (depth_max - depth_min)\n depth_npy = depth_npy + np.random.random() * 0.3 - 0.15\n depth_npy = depth_npy.clip(0.0, 1.0)\n\n img_depth = Image.fromarray(depth_npy) # , mode='F')\n\n transform = T.Compose([T.ToTensor()])\n if self.phase == \"test\":\n if self.use_transform:\n img_rgb = transform(img_rgb)\n img_depth = transform(img_depth)\n # mask = transform(mask)\n\n img_depth = normalize(img_depth)\n sample = {\"rgb\": img_rgb, \"X\": img_depth}\n else:\n corners_label = Image.open(\n os.path.join(self.root_dir, \"label_red_\" + imidx + \".png\")\n )\n edges_label = Image.open(\n os.path.join(self.root_dir, \"label_yellow_\" + imidx + \".png\")\n )\n inner_edges_label = Image.open(\n os.path.join(self.root_dir, \"label_green_\" + imidx + \".png\")\n )\n\n if self.use_transform:\n if random.random() > 0.5:\n img_rgb = tf.hflip(img_rgb)\n img_depth = tf.hflip(img_depth)\n corners_label = tf.hflip(corners_label)\n edges_label = tf.hflip(edges_label)\n inner_edges_label = tf.hflip(inner_edges_label)\n if random.random() > 0.5:\n img_rgb = tf.vflip(img_rgb)\n img_depth = tf.vflip(img_depth)\n corners_label = tf.vflip(corners_label)\n edges_label = tf.vflip(edges_label)\n inner_edges_label = tf.vflip(inner_edges_label)\n if random.random() > 0.9:\n angle = T.RandomRotation.get_params([-30, 30])\n img_rgb = tf.rotate(img_rgb, angle, resample=Image.NEAREST)\n img_depth = tf.rotate(img_depth, angle, resample=Image.NEAREST)\n corners_label = tf.rotate(\n corners_label, angle, resample=Image.NEAREST\n )\n edges_label = tf.rotate(edges_label, angle, resample=Image.NEAREST)\n inner_edges_label = tf.rotate(\n inner_edges_label, angle, resample=Image.NEAREST\n )\n img_rgb = transform(np.array(img_rgb))\n img_depth = transform(np.array(img_depth))\n\n corners_label = transform(np.array(corners_label))\n edges_label = transform(np.array(edges_label))\n inner_edges_label = transform(np.array(inner_edges_label))\n\n label = torch.cat((corners_label, edges_label, inner_edges_label), 0)\n img_depth = normalize(img_depth)\n\n sample = {\"rgb\": img_rgb, \"X\": img_depth, \"Y\": label}\n\n return sample\n\n\ndef show_sample(sample):\n\n mask = np.zeros(\n (sample[\"rgb\"].size()[1], sample[\"rgb\"].size()[2], 3), dtype=np.float32\n )\n mask_yellow = sample[\"Y\"][1]\n mask_green = sample[\"Y\"][2]\n mask_red = sample[\"Y\"][0]\n\n mask[mask_yellow == 1] = [1, 1, 0]\n mask[mask_green == 1] = [0, 1, 0]\n mask[mask_red == 1] = [1, 0, 0]\n\n plt.figure(figsize=(12, 36))\n plt.subplot(131)\n plt.imshow(np.moveaxis(np.array(sample[\"rgb\"]), 0, -1))\n\n plt.subplot(132)\n plt.imshow(sample[\"X\"][0])\n\n plt.subplot(133)\n plt.imshow(mask)\n plt.show()\n\n\ndef show_batch(batch):\n for i in range(batch[\"X\"].size()[0]):\n sample = {}\n for key in batch:\n sample[key] = batch[key][i]\n show_sample(sample)\n\n\nif __name__ == \"__main__\":\n train_data = TowelDataset(\n root_dir=\"/home/shawn/Code/kinect_azure/fabric/data/imgs/0506_10k\",\n phase=\"train\",\n use_transform=True,\n )\n\n # show a batch\n batch_size = 1\n for i in range(batch_size):\n sample = train_data[i]\n print(i, sample[\"X\"].size())\n print(sample[\"X\"].max(), sample[\"X\"].min(), sample[\"X\"].type())\n print(sample[\"Y\"].max(), sample[\"Y\"].min(), sample[\"Y\"].type())\n print(sample[\"rgb\"].max(), sample[\"rgb\"].min(), sample[\"rgb\"].type())\n\n a = sample[\"Y\"].numpy()\n for i in range(a.shape[0]):\n for j in range(a.shape[1]):\n for k in range(a.shape[2]):\n if a[i, j, k] != 0 and a[i, j, k] != 1:\n print(a[i, j, k])\n\n dataloader = DataLoader(\n train_data, batch_size=batch_size, shuffle=False, num_workers=1\n )\n\n for i, batch in enumerate(dataloader):\n print(i, batch[\"X\"].size())\n\n # observe 4th batch\n if i == 0:\n plt.figure()\n show_batch(batch)\n plt.axis(\"off\")\n plt.ioff()\n plt.show()\n" }, { "alpha_fraction": 0.5357609987258911, "alphanum_fraction": 0.5973252058029175, "avg_line_length": 32.23188400268555, "blob_id": "63a5617459807c913e404fdba15a3928e5847324", "content_id": "7ce7e021e7afa7eaa5259eb8dc4d0c508dba2f99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13758, "license_type": "no_license", "max_line_length": 198, "num_lines": 414, "path": "/dual_arm.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport time\nimport cv2\nfrom controller.ur5.ur_controller import UR_Controller\nfrom controller.mini_robot_arm.RX150_driver import RX150_Driver\nfrom perception.kinect.kinect_camera import Kinect\nfrom scipy.spatial.transform import Rotation as R\nfrom controller.gripper.gripper_control import Gripper_Controller\nfrom scipy.interpolate import griddata\nfrom perception.fabric.util.segmentation import segmentation\nfrom perception.fabric.run import Run\nfrom PIL import Image\nimport skimage.measure\nimport torchvision.transforms as T\nimport os\n\ncam_intrinsics_origin = np.array([\n[917.3927285, 0., 957.21294894],\n[ 0., 918.96234057, 555.32910487],\n[ 0., 0., 1. ]])\ncam_intrinsics = np.array([\n[965.24853516, 0., 950.50838964],\n [ 0., 939.67144775, 554.55567298],\n [ 0., 0., 1. ]]) # New Camera Intrinsic Matrix\ndist = np.array([[ 0.0990126, -0.10306044, 0.00024658, -0.00268176, 0.05763196]])\ncamera = Kinect(cam_intrinsics_origin, dist)\n\ncam_pose = np.loadtxt('real/camera_pose.txt', delimiter=' ')\ncam_depth_scale = np.loadtxt('real/camera_depth_scale.txt', delimiter=' ')\n\n# User options (change me)\n# --------------- Setup options ---------------\nurc = UR_Controller()\nurc.start()\na = 0.2\nv = 0.2\n\nrx150 = RX150_Driver(port=\"/dev/ttyACM0\", baudrate=1000000)\nrx150.torque(enable=1)\nprint(rx150.readpos())\n\ndef rx_move(g_open, x_pos):\n values = [1024, 2549, 1110, 1400, 0, g_open]\n x = x_pos\n y = 90\n end_angle = 0\n rx150.gogo(values, x, 90, end_angle, 0, timestamp=100)\n\n# workspace_limits = np.asarray([[0.3, 0.748], [-0.224, 0.224], [-0.255, -0.1]]) # Cols: min max, Rows: x y z (define workspace limits in robot coordinates)\nworkspace_limits = np.asarray([[-0.845, -0.605], [-0.14, 0.2], [0, 0.2]]) # Cols: min max, Rows: x y z (define workspace limits in robot coordinates)\n\n# tool_orientation = [2.22,-2.22,0]\n# tool_orientation = [0., -np.pi/2, 0.] # [0,-2.22,2.22] # [2.22,2.22,0]\nfrom scipy.spatial.transform import Rotation as R\ntool_orientation_euler = [180, 0, 90]\n# tool_orientation_euler = [180, 0, 0]\n# tool_orientation_euler = [180, 0, 180]\ntool_orientation = R.from_euler('xyz', tool_orientation_euler, degrees=True).as_rotvec()\n# tool_orientation = [0., -np.pi, 0.] # [0,-2.22,2.22] # [2.22,2.22,0]\n\n# pose0 = np.array([-0.511, 0.294, 0.237, -0.032, -1.666, 0.138])\npose0 = np.hstack([[-0.505, 0.06, 0.2], tool_orientation])\npose_up = pose0.copy()\npose_transfer = np.array([-0.431, -0.032, 0.232, -2.230, -2.194, -0.019])\n\nurc.movel_wait(pose0, a=a, v=v)\n# ---------------------------------------------\n\n# Start gripper\ngrc = Gripper_Controller()\ngrc.gripper_helper.set_gripper_current_limit(0.3)\ngrc.start()\n\ngrc.follow_gripper_pos = 0.\ntime.sleep(0.5)\n\n# Move robot to home pose\n# robot = Robot(False, None, None, workspace_limits,\n# tcp_host_ip, tcp_port, rtc_host_ip, rtc_port,\n# False, None, None)\n# robot.open_gripper()\n\n# Slow down robot\n# robot.joint_acc = 1.4\n# robot.joint_vel = 1.05\n\n# Callback function for clicking on OpenCV window\nclick_point_pix = ()\n# camera_color_img, camera_depth_img = robot.get_camera_data()\ncamera_color_img, camera_depth_img = camera.get_image()\ndef mouseclick_callback(event, x, y, flags, param):\n if event == cv2.EVENT_LBUTTONDOWN:\n global camera, robot, click_point_pix\n click_point_pix = (x,y)\n\n # Get click point in camera coordinates\n click_z = camera_depth_img[y][x] * cam_depth_scale\n click_x = np.multiply(x-cam_intrinsics[0][2],click_z/cam_intrinsics[0][0])\n click_y = np.multiply(y-cam_intrinsics[1][2],click_z/cam_intrinsics[1][1])\n if click_z == 0:\n return\n click_point = np.asarray([click_x,click_y,click_z])\n click_point.shape = (3,1)\n\n # Convert camera to robot coordinates\n # camera2robot = np.linalg.inv(robot.cam_pose)\n camera2robot = cam_pose\n target_position = np.dot(camera2robot[0:3,0:3],click_point) + camera2robot[0:3,3:]\n\n\n\n\n target_position = target_position[0:3,0]\n # print(x, y)\n # # target_position[2] -= 0.03\n # if target_position[2] < -0.118:\n # print(\"WARNNING: Reach Z Limit, set to minimal Z\")\n # target_position[2] = -0.118\n # # robot.move_to(target_position, tool_orientation)\n # pose = np.hstack([target_position, tool_orientation])\n # urc.movel_wait(pose, a=a, v=v)\n\n\n# Show color and depth frames\ncv2.namedWindow('color')\ncv2.setMouseCallback('color', mouseclick_callback)\ncv2.namedWindow('depth')\n\nseq_id = 0\n# sequence = [ord('p'), ord('g'), ord('h'), ord('r'), ord('g')]\nsequence = [ord('p'), ord('g'), ord('h'), ord('g'), ord('d')]\n\n\n\n###################################################\n# Record kinect images\n###################################################\n\n# dir_data = \"data/imgs/0625_10k\"\ndir_data = \"data/imgs/test\"\nos.makedirs(dir_data, exist_ok=True)\ncount = 0\n\nsz = 650\ntopleft = [300, 255]\nbottomright = [topleft[0] + sz, topleft[1] + sz]\n\ndef record_kinect():\n global count\n # get kinect images\n color, depth_transformed = camera.get_image()\n\n # Crop images\n color_small = cv2.resize(color, (0, 0), fx=1, fy=1)\n color_small = color_small[\n topleft[1] : bottomright[1], topleft[0] : bottomright[0]\n ]\n\n depth_transformed_small = cv2.resize(depth_transformed, (0, 0), fx=1, fy=1)\n depth_transformed_small = depth_transformed_small[\n topleft[1] : bottomright[1], topleft[0] : bottomright[0]\n ]\n\n # Normalize depth images\n depth_min = 400.0\n depth_max = 900.0\n depth_transformed_small_img = (\n (depth_transformed_small - depth_min) / (depth_max - depth_min) * 255\n )\n depth_transformed_small_img = depth_transformed_small_img.clip(0, 255)\n\n mask = segmentation(color_small)\n cv2.imshow(\"mask\", mask)\n cv2.imshow(\"color_nn\", color_small)\n cv2.imshow(\"depth_nn\", depth_transformed_small_img / 255.)\n cv2.waitKey(1)\n\n\n cv2.imwrite(f\"{dir_data}/color_{count}.jpg\", color_small)\n cv2.imwrite(\n f\"{dir_data}/depth_{count}.jpg\",\n depth_transformed_small_img.astype(np.uint8),\n )\n np.save(f\"{dir_data}/depth_{count}.npy\", depth_transformed_small)\n\n count += 1\n\n###################################################\n# Demo segmentation\n###################################################\n\nmodel_id = 29\nepoch = 200\npretrained_model = \"/home/gelsight/Code/Fabric/models/%d/chkpnts/%d_epoch%d\" % (\n model_id,\n model_id,\n epoch,\n)\n\ndef seg_output(depth, model=None):\n max_d = np.nanmax(depth)\n depth[np.isnan(depth)] = max_d\n # depth_min, depth_max = 400.0, 1100.0\n # depth = (depth - depth_min) / (depth_max - depth_min)\n # depth = depth.clip(0.0, 1.0)\n\n img_depth = Image.fromarray(depth)\n transform = T.Compose([T.ToTensor()])\n img_depth = transform(img_depth)\n img_depth = np.array(img_depth[0])\n\n out = model.evaluate(img_depth).squeeze()\n seg_pred = out[:, :, :3]\n\n # prob_pred *= mask\n # seg_pred_th = deepcopy(seg_pred)\n # seg_pred_th[seg_pred_th < 0.8] = 0.0\n\n return seg_pred\n\nt1 = Run(model_path=pretrained_model, n_features=3)\n\ndef demo_segmentation():\n # get kinect images\n color, depth_transformed = camera.get_image()\n\n # Crop images\n color_small = cv2.resize(color, (0, 0), fx=1, fy=1)\n color_small = color_small[\n topleft[1] : bottomright[1], topleft[0] : bottomright[0]\n ]\n\n depth_transformed_small = cv2.resize(depth_transformed, (0, 0), fx=1, fy=1)\n depth_transformed_small = depth_transformed_small[\n topleft[1] : bottomright[1], topleft[0] : bottomright[0]\n ]\n\n depth_min = 400.0\n depth_max = 1100.0\n depth_transformed_small_img = (depth_transformed_small - depth_min) / (\n depth_max - depth_min\n )\n depth_transformed_small_img = depth_transformed_small_img.clip(0, 1)\n\n cv2.imshow(\"color_crop\", color_small)\n cv2.imshow(\"depth_crop\", depth_transformed_small_img)\n\n depth_transformed_100x100 = skimage.measure.block_reduce(\n depth_transformed_small_img, (4, 4), np.mean\n )\n seg_pred = seg_output(depth_transformed_100x100, model=t1)\n mask = seg_pred.copy()\n H, W = mask.shape[0], mask.shape[1]\n mask = (\n mask.reshape((H * W, 3))\n @ np.array([[0, 0, 1.0], [0, 1.0, 1.0], [0, 1.0, 0]])\n ).reshape((H, W, 3))\n # mask = 1.0 / (1 + np.exp(-5 * (mask - 0.8)))\n\n mask = cv2.resize(mask, (sz, sz))\n cv2.imshow(\"prediction\", mask)\n cv2.waitKey(1)\n\n\ndef move_record(pose, a, v):\n urc.movel_nowait(pose, a=a, v=v)\n while True:\n # record_kinect()\n demo_segmentation()\n if urc.check_stopped():\n break\n time.sleep(0.05)\n\nwhile True:\n if seq_id % len(sequence) == 0:\n time.sleep(0.5)\n # camera_color_img, camera_depth_img = robot.get_camera_data()\n camera_color_img, camera_depth_img = camera.get_image()\n bgr_data = camera_color_img# cv2.cvtColor(camera_color_img, cv2.COLOR_RGB2BGR)\n if len(click_point_pix) != 0:\n bgr_data = cv2.circle(bgr_data, click_point_pix, 7, (0,0,255), 2)\n cv2.imshow('color', bgr_data)\n cv2.imshow('depth', camera_depth_img / 1100.)\n\n crop_x = [421, 960]\n crop_y = [505, 897]\n camera_depth_img_crop = camera_depth_img[crop_y[0]:crop_y[1], crop_x[0]:crop_x[1]]\n camera_color_img_crop = camera_color_img[crop_y[0]:crop_y[1], crop_x[0]:crop_x[1]]\n x = np.arange(camera_depth_img_crop.shape[0]) + crop_y[0]\n y = np.arange(camera_depth_img_crop.shape[1]) + crop_x[0]\n yy, xx = np.meshgrid(x, y)\n yy = yy.reshape([-1])\n xx = xx.reshape([-1])\n\n # cv2.imshow(\"camera_color_img_crop\", camera_color_img_crop)\n cv2.imshow(\"camera_depth_img_crop\", camera_depth_img_crop/1300.)\n\n zz = (camera_depth_img_crop.T).reshape([-1])\n\n # Validation\n # x = 525\n # y = 424\n # id = x * camera_depth_img.shape[0] + y\n # print(\"Desired\", x,y,camera_depth_img[y][x])\n # print(\"Flattened\", xx[id], yy[id], zz[id])\n\n zz = zz * cam_depth_scale\n zz[zz==0] = -1000\n xx = np.multiply(xx-cam_intrinsics[0][2],zz/cam_intrinsics[0][0])\n yy = np.multiply(yy-cam_intrinsics[1][2],zz/cam_intrinsics[1][1])\n xyz_kinect = np.vstack([xx,yy,zz])\n # shape: (3, W*H)\n\n camera2robot = cam_pose\n xyz_robot = np.dot(camera2robot[0:3,0:3],xyz_kinect) + camera2robot[0:3,3:]\n\n # X, Y\n #[-0.64, 0.2]\n #[-0.36, -0.072]\n\n stepsize=0.01\n xlim = [-0.64, -0.36]\n ylim = [-0.07, 0.20]\n\n scale = 100\n x_ws = np.arange(int(xlim[0] * scale), int(xlim[1] * scale))\n y_ws = np.arange(int(ylim[0] * scale), int(ylim[1] * scale))\n xx_ws, yy_ws = np.meshgrid(x_ws, y_ws)\n points = xyz_robot[:2].T\n # shape: (W*H, 2)\n values = xyz_robot[2]\n # shape: (W*H)\n z_ws = griddata(points*scale, values, (xx_ws, yy_ws), method='nearest')\n\n z_ws_blur = cv2.GaussianBlur(z_ws, (5, 5), 0)\n # ind_highest = np.unravel_index(np.argmax(z_ws_blur, axis=None), z_ws_blur.shape)\n # xyz_robot_highest = [ind_highest[1] / scale + xlim[0], ind_highest[0] / scale + ylim[0], z_ws[ind_highest]]\n\n x_high, y_high = np.where(z_ws_blur >= (z_ws_blur.min() + (z_ws_blur.max() - z_ws_blur.min()) *0.8))\n ind = np.random.randint(len(x_high))\n grasp_point = (x_high[ind], y_high[ind])\n\n\n xyz_robot_highest = [grasp_point[1] / scale + xlim[0], grasp_point[0] / scale + ylim[0], z_ws[grasp_point]]\n print(\"XYZ_HIGHEST\", xyz_robot_highest)\n\n # scale for visualization\n z_min = -0.14\n z_max = 0.0\n z_ws_scaled = (z_ws_blur - z_min) / (z_max - z_min + 1e-6)\n z_ws_scaled = np.dstack([z_ws_scaled, z_ws_scaled, z_ws_scaled])\n z_ws_scaled[grasp_point[0], grasp_point[1], :] = [0, 0, 1]\n z_ws_scaled = np.fliplr(np.rot90(z_ws_scaled, k=1))\n\n cv2.imshow(\"z workspace\", z_ws_scaled)\n\n c = sequence[seq_id % len(sequence)]\n seq_id += 1\n cv2.waitKey(1)\n if c == ord('c'):\n break\n elif c == ord('g'):\n grc.follow_gripper_pos = 1. - grc.follow_gripper_pos\n time.sleep(0.5)\n print(\"GRASP\"*20)\n elif c == ord('h'):\n # tool_orientation_euler = [180, 0, 180]\n # tool_orientation_euler[2] = np.random.randint(180)+90\n # tool_orientation = R.from_euler('xyz', tool_orientation_euler, degrees=True).as_rotvec()\n # random_perturb_rng = 0.05\n # pose_up = np.hstack([[-0.505+np.random.random()*random_perturb_rng - random_perturb_rng / 2, 0.06 + np.random.random()*random_perturb_rng - random_perturb_rng / 2, 0.2], tool_orientation])\n rx_move(1600, 270)\n time.sleep(0.5)\n move_record(pose_transfer, a=a, v=v)\n time.sleep(0.5)\n rx_move(1600, 420)\n time.sleep(0.5)\n rx_move(760, 420)\n elif c == ord('d'):\n time.sleep(0.5)\n rx_move(1600, 420)\n time.sleep(0.5)\n rx_move(1600, 270)\n time.sleep(0.5)\n elif c == ord('p'):\n xyz_robot_highest[2] -= 0.03\n if xyz_robot_highest[2] < -0.118:\n print(\"WARNNING: Reach Z Limit, set to minimal Z\")\n xyz_robot_highest[2] = -0.118\n pose = np.hstack([xyz_robot_highest, tool_orientation])\n move_record(pose, a=a, v=v)\n elif c == ord('r'):\n tool_orientation_euler = [180, 0, 180]\n tool_orientation_euler[2] = np.random.randint(180)+90\n tool_orientation = R.from_euler('xyz', tool_orientation_euler, degrees=True).as_rotvec()\n pose_up = np.hstack([pose_up[:3], tool_orientation])\n move_record(pose_up, a=a, v=v)\n\n record_kinect()\n time.sleep(0.05)\n\n if count > 10000:\n break\n\n\n\n\n\n\n\ncv2.destroyAllWindows()\n" }, { "alpha_fraction": 0.5175131559371948, "alphanum_fraction": 0.5455341339111328, "avg_line_length": 24.977272033691406, "blob_id": "a3aa039c526d9a0e179214b777b454809956aa4c", "content_id": "bfeb17d74c4e48b48ed16749189b52f4f8978e13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1142, "license_type": "no_license", "max_line_length": 63, "num_lines": 44, "path": "/perception/gelsight/util/Vis3D.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "from open3d import *\n\nclass ClassVis3D:\n def __init__(self, n=100, m=200):\n self.n, self.m = n, m\n\n self.init_open3D()\n pass\n\n def init_open3D(self):\n x = np.arange(self.n)\n y = np.arange(self.m)\n self.X, self.Y = np.meshgrid(x,y)\n # Z = (X ** 2 + Y ** 2) / 10\n Z = np.sin(self.X)\n\n self.points = np.zeros([self.n * self.m, 3])\n self.points[:, 0] = np.ndarray.flatten(self.X) / self.m\n self.points[:, 1] = np.ndarray.flatten(self.Y) / self.m\n\n self.depth2points(Z)\n # exit(0)\n\n # points = np.random.rand(1,3)\n\n self.pcd = PointCloud()\n self.pcd.points = Vector3dVector(self.points)\n\n self.vis = Visualizer()\n self.vis.create_window()\n self.vis.add_geometry(self.pcd)\n\n def depth2points(self, Z):\n self.points[:, 2] = np.ndarray.flatten(Z)\n\n\n def update(self, Z):\n # points = np.random.rand(60000,3)\n self.depth2points(Z)\n\n self.pcd.points = Vector3dVector(self.points)\n self.vis.update_geometry()\n self.vis.poll_events()\n self.vis.update_renderer()" }, { "alpha_fraction": 0.5396379232406616, "alphanum_fraction": 0.606784999370575, "avg_line_length": 25.337963104248047, "blob_id": "ad25df498a637fbe9a81d7b6dc0484cbdc00bc57", "content_id": "8a888059630a1413f123741440d4d930f97162dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5689, "license_type": "no_license", "max_line_length": 124, "num_lines": 216, "path": "/record_video_with_width_v2.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import csv\nimport datetime\nimport time\nimport urllib\nimport urllib.request\n\nimport _thread\nimport cv2\nimport numpy as np\nimport util\nfrom util.processing import warp_perspective\nfrom util.reconstruction import Class_3D\nfrom util.streaming import Streaming\nfrom util.Vis3D import ClassVis3D\nfrom controller.mini_robot_arm.RX150_driver import RX150_Driver\n\nimport deepdish as dd\nimport os\n\n#######################################################################################\n\nrx150 = RX150_Driver(port=\"/dev/ttyACM0\", baudrate=1000000)\nprint(rx150.readpos())\n\nrx150.torque(enable=1)\n# g_open = 780\ng_open = 1200\n\ngoal_rot = 3072+4096\n# values = [1024, 2549, 1110, 1400, 0, g_open]\nvalues = [1300, 2549, 1110, 1400, 0, g_open]\n# x = 420\n# x = 380\nx = 280\ny = 120\nend_angle = 0\n# 270 - 420\nrx150.gogo(values, x, y, end_angle, goal_rot, timestamp=100)\ntime.sleep(2)\n\n#######################################################################################\n\nsensor_id = \"fabric_0\"\n\nstream = urllib.request.urlopen(\"http://rpigelsightfabric.local:8080/?action=stream\")\n\nstream = Streaming(stream)\n_thread.start_new_thread(stream.load_stream, ())\n\n# n, m = 300, 400\nn, m = 150, 200\n# Vis3D = ClassVis3D(m, n)\n\nfourcc = cv2.VideoWriter_fourcc(\"M\", \"J\", \"P\", \"G\")\n\ndir_data = \"data/touch/08272021/corner/\"\nos.makedirs(dir_data, exist_ok=True)\n\ndef save_video(frame_list, vid, gripper_width_list):\n fn_video = dir_data + \"F{:03d}.mov\".format(vid)\n fn_gripper = dir_data + \"F{:03d}.npy\".format(vid)\n np.save(fn_gripper, gripper_width_list)\n\n col = 200\n row = 150\n out = cv2.VideoWriter(\n fn_video, fourcc, 20.0, (col * 1, row * 1)\n ) # The fps depends on CPU\n for frame in frame_list:\n out.write(frame)\n out.release()\n\n\n\ndef read_csv(filename=f\"config/config_{sensor_id}.csv\"):\n rows = []\n\n with open(filename, \"r\") as csvfile:\n csvreader = csv.reader(csvfile)\n header = next(csvreader)\n for row in csvreader:\n rows.append((int(row[1]), int(row[2])))\n\n return rows\n\n\nTOPLEFT, TOPRIGHT, BOTTOMLEFT, BOTTOMRIGHT = tuple(read_csv())\n\ncnt = 0\nlast_tm = 0\n# n, m = 48, 48\n# n, m = 300, 300\ndiff_thresh = 5\n\ndiff_max = 0\nimage_peak = None\nflag_recording = False\n\nframes = []\nlast_frame = None\ngripper_width_list = []\ngripper_width_command_list = []\n\ngripper_width = 1000\ngripper_width_inc = -10\n\nst = time.time()\nflag_recording = True\n\nvid = 0\ncnt_close = 0 # compensate for camera latency\n\nwhile True:\n frame = stream.image\n if frame == \"\":\n print(\"waiting for streaming\")\n continue\n\n\n cnt += 1\n\n im = warp_perspective(frame, TOPLEFT, TOPRIGHT, BOTTOMLEFT, BOTTOMRIGHT) # left\n # im[:, :, 0] = 0.0\n\n im_raw = cv2.resize(im, (400, 300))\n # im_raw = cv2.resize(im, (200, 150))\n im = cv2.resize(im, (m, n))\n\n\n\n if cnt == 1:\n frame0 = im.copy()\n frame0 = cv2.GaussianBlur(frame0, (31, 31), 0)\n\n cv2.imshow(\"im_raw\", im_raw)\n\n diff = ((im * 1.0 - frame0)) / 255.0 + 0.5\n cv2.imshow(\"warped\", cv2.resize((diff - 0.5) * 4 + 0.5, (m, n)))\n\n last_tm = time.time()\n\n\n\n\n if flag_recording:\n\n values[-1] = max(gripper_width, 750)\n rx150.gogo(values, x, y, end_angle, goal_rot, timestamp=1)\n\n time.sleep(0.02)\n\n if last_frame is not None and np.sum(last_frame - im_raw) != 0 and flag_recording:\n im_small = cv2.resize(im_raw, (0, 0), fx=0.5, fy=0.5)\n # frames.append(im_raw)\n frames.append(im_small)\n\n # save the command for the gripper width\n gripper_width_command_list.append(gripper_width)\n\n # save the actual reading of the gripper width\n encoder = rx150.readpos_float()\n gripper_width_list.append(encoder[-1])\n print(\"frame\", len(frames), \"command:\", gripper_width_command_list[-1], \"actual:\", gripper_width_list[-1])\n\n\n gripper_width_inc_multiplier = 1\n # gripper_width_inc_multiplier = 1 + (900 - gripper_width) * 0.01\n\n gripper_width += gripper_width_inc\n if gripper_width < 650 and flag_recording:\n # save data\n save_video(frames, vid, gripper_width_list)\n frames, gripper_width_list, gripper_width_command_list = [], [], []\n vid += 1\n\n if vid > 110:\n break\n\n gripper_width = 1050\n values[-1] = gripper_width\n rx150.gogo(values, x, y, end_angle, goal_rot, timestamp=1)\n time.sleep(2)\n\n last_frame = im_raw.copy()\n\n c = cv2.waitKey(1)\n if c == ord(\"q\"):\n break\n if c == ord(\"g\"):\n if flag_recording:\n values[-1] = 1200\n rx150.gogo(values, x, y, end_angle, goal_rot, timestamp=100)\n flag_recording = False\n else:\n values[-1] = 750\n rx150.gogo(values, x, y, end_angle, goal_rot, timestamp=100)\n time.sleep(1)\n values[-1] = 1000\n rx150.gogo(values, x, y, end_angle, goal_rot, timestamp=100)\n time.sleep(1)\n flag_recording = True\n\n\n\nprint(len(frames))\n# data = {\"frames\":frames, \"gripper_width_command_list\":gripper_width_command_list, \"gripper_width_list\":gripper_width_list}\n# dd.io.save(\"data/touch/fabric_test.h5\", frames)\n# dd.io.save(\"data/touch/08192021/fabric_all_fabric.h5\", data)\n# dd.io.save(\"data/touch/08192021/fabric_edge.h5\", data)\n# dd.io.save(\"data/touch/08192021/fabric_edge_skinny.h5\", data)\n# dd.io.save(\"data/touch/08192021/fabric_test.h5\", data)\n# dd.io.save(\"data/touch/08242021/fabric_edge_close.h5\", data)\n# dd.io.save(\"data/touch/08242021/fabric_fold_close.h5\", data)\n# dd.io.save(\"data/touch/08242021/fabric_edge_close_2.h5\", data)\n# dd.io.save(\"data/touch/08192021/fabric_left_edge2.h5\", data)\ncv2.destroyAllWindows()\n" }, { "alpha_fraction": 0.544299304485321, "alphanum_fraction": 0.6639604568481445, "avg_line_length": 31.94186019897461, "blob_id": "7a883b09587123c3d644f60c946bca93bbbb55b1", "content_id": "3f25fd4ea19d55477a0f2640f22f852723b7bec8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2833, "license_type": "no_license", "max_line_length": 156, "num_lines": 86, "path": "/move_together.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport time\nimport cv2\nfrom controller.ur5.ur_controller import UR_Controller\nfrom controller.mini_robot_arm.RX150_driver import RX150_Driver\nfrom perception.kinect.kinect_camera import Kinect\nfrom scipy.spatial.transform import Rotation as R\nfrom controller.gripper.gripper_control import Gripper_Controller\nfrom scipy.interpolate import griddata\nfrom perception.fabric.util.segmentation import segmentation\nfrom perception.fabric.run import Run\nfrom PIL import Image\nimport skimage.measure\nimport torchvision.transforms as T\nimport os\n\nurc = UR_Controller()\nurc.start()\na = 0.2\nv = 0.2\n\nrx150 = RX150_Driver(port=\"/dev/ttyACM0\", baudrate=1000000)\nrx150.torque(enable=1)\nprint(rx150.readpos())\n\ndef rx_move(g_open, x_pos):\n values = [1024, 2549, 1110, 1400, 0, g_open]\n x = x_pos\n y = 90\n end_angle = 0\n rx150.gogo(values, x, 90, end_angle, 0, timestamp=100)\n\n# workspace_limits = np.asarray([[0.3, 0.748], [-0.224, 0.224], [-0.255, -0.1]]) # Cols: min max, Rows: x y z (define workspace limits in robot coordinates)\nworkspace_limits = np.asarray([[-0.845, -0.605], [-0.14, 0.2], [0, 0.2]]) # Cols: min max, Rows: x y z (define workspace limits in robot coordinates)\n\n# tool_orientation = [2.22,-2.22,0]\n# tool_orientation = [0., -np.pi/2, 0.] # [0,-2.22,2.22] # [2.22,2.22,0]\nfrom scipy.spatial.transform import Rotation as R\ntool_orientation_euler = [180, 0, 90]\n# tool_orientation_euler = [180, 0, 0]\n# tool_orientation_euler = [180, 0, 180]\ntool_orientation = R.from_euler('xyz', tool_orientation_euler, degrees=True).as_rotvec()\n# tool_orientation = [0., -np.pi, 0.] # [0,-2.22,2.22] # [2.22,2.22,0]\n\n# pose0 = np.array([-0.511, 0.294, 0.237, -0.032, -1.666, 0.138])\npose0 = np.hstack([[-0.505, 0.06, 0.2], tool_orientation])\npose_up = pose0.copy()\npose_start = np.array([-0.431, 0.05, 0.21, -2.230, -2.194, -0.019])\n\nurc.movel_wait(pose_start, a=a, v=v)\n\ng_open = 1200\nvalues = [1024, 2549, 1110, 1400, 0, g_open]\nx = 420\ny = 120\nend_angle = 0*np.pi/180\nrx150.gogo(values, x, y, end_angle, 0, timestamp=100)\n\n\nurc.movel_wait(pose_start+[0,0,0.12,0,0,0], a=a, v=v)\nrx150.gogo(values, x, y+120, end_angle, 0, timestamp=100)\n\n\nurc.movel_wait(pose_start+[0,0,0,0,0,0], a=a, v=v)\nrx150.gogo(values, x, y, end_angle, 0, timestamp=100)\n\n\nrx150.gogo(values, x-120, y, end_angle, 0, timestamp=100)\nurc.movel_wait(pose_start+[0,-0.12,0,0,0,0], a=a, v=v)\n\nurc.movel_wait(pose_start+[0,0,0,0,0,0], a=a, v=v)\nrx150.gogo(values, x, y, end_angle, 0, timestamp=100)\n\n# inc = 10\n# for i in range(50):\n# y = y + inc\n# if y > 240 or y < 0:\n# inc *= -1\n# time.sleep(0.2)\n# rx150.gogo(values, x, y, end_angle, 0, timestamp=10)\n# pose_start[2] += inc / 1000.\n# urc.movel_nowait(pose_start, a=a, v=v)\n# time.sleep(0.01)\n" }, { "alpha_fraction": 0.4377216696739197, "alphanum_fraction": 0.4642186462879181, "avg_line_length": 30.123376846313477, "blob_id": "96b53b9ada63a7956ca8a95daa62db07c60ae520", "content_id": "4024c303ce12afa80ae4909aa7434ea70decb507", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4793, "license_type": "no_license", "max_line_length": 92, "num_lines": 154, "path": "/perception/wedge_no2/model.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport random\n\n\nclass GradNet2D(nn.Module):\n def __init__(self):\n super(GradNet2D, self).__init__()\n # 5 input image channel, 32 output channels, 1x1 square convolution\n # kernel\n self.conv1 = nn.Conv2d(5, 32, 1)\n self.conv2 = nn.Conv2d(32, 32, 1)\n self.conv3 = nn.Conv2d(32, 32, 1)\n self.conv4 = nn.Conv2d(32, 2, 1)\n\n def forward(self, x):\n x = x.permute(0, 3, 1, 2)\n x = torch.tanh(self.conv1(x))\n x = torch.tanh(self.conv2(x))\n x = torch.tanh(self.conv3(x))\n x = self.conv4(x)\n x = x.permute(0, 2, 3, 1)\n return x\n\n def fit(self, X_train, Y_train):\n batch_size = 2\n N = X_train.shape[0]\n\n idx = list(range(N))\n random.shuffle(idx)\n\n X_train = X_train[idx]\n Y_train = Y_train[idx]\n\n optim = torch.optim.Adam(self.parameters(), lr=0.001)\n sum_loss = 0\n total = 0\n\n for epoch in range(20):\n sum_loss = 0\n total = 0\n for i in range(N // batch_size):\n # clear gradients accumulated on the parameters\n optim.zero_grad()\n\n # get an input (say we only care inputs sampled from N(0, I))\n # x = torch.randn(batch_size, 8, device=cuda0) # this has to be on GPU too\n x = torch.tensor(\n X_train[i * batch_size : (i + 1) * batch_size], dtype=torch.float32\n )\n y = torch.tensor(\n Y_train[i * batch_size : (i + 1) * batch_size], dtype=torch.float32\n )\n\n # forward pass\n result = self.forward(x) # CHANGED: fc => net\n\n # compute loss\n loss = F.mse_loss(result, y)\n\n # compute gradients\n loss.backward()\n\n # let the optimizer do its work; the parameters will be updated in this call\n optim.step()\n\n sum_loss += loss.item()\n total += 1\n # add some printing\n if (i + 1) % 1 == 0:\n print(\n \"epoch {}\\titeration {}\\tloss {:.5f}\".format(\n epoch, i, sum_loss / total\n )\n )\n\n def predict(self, X_test):\n with torch.no_grad():\n return self.forward(torch.tensor(X_test, dtype=torch.float32)).numpy()\n\n\nclass GradNet(nn.Module):\n def __init__(self):\n super(GradNet, self).__init__()\n self.fc1 = nn.Linear(5, 32)\n self.fc2 = nn.Linear(32, 32)\n self.fc3 = nn.Linear(32, 32)\n self.fc4 = nn.Linear(32, 2)\n\n def forward(self, x):\n x = self.fc1(x)\n x = x.tanh()\n x = self.fc2(x)\n x = x.tanh()\n x = self.fc3(x)\n x = x.tanh()\n return self.fc4(x)\n\n def fit(self, X_train, Y_train):\n batch_size = 256\n N = X_train.shape[0]\n\n idx = list(range(N))\n random.shuffle(idx)\n\n X_train = X_train[idx]\n Y_train = Y_train[idx]\n\n optim = torch.optim.Adam(self.parameters(), lr=0.001)\n sum_loss = 0\n total = 0\n\n for epoch in range(10):\n sum_loss = 0\n total = 0\n for i in range(N // batch_size):\n # clear gradients accumulated on the parameters\n optim.zero_grad()\n\n # get an input (say we only care inputs sampled from N(0, I))\n # x = torch.randn(batch_size, 8, device=cuda0) # this has to be on GPU too\n x = torch.tensor(\n X_train[i * batch_size : (i + 1) * batch_size], dtype=torch.float32\n )\n y = torch.tensor(\n Y_train[i * batch_size : (i + 1) * batch_size], dtype=torch.float32\n )\n\n # forward pass\n result = self.forward(x) # CHANGED: fc => net\n\n # compute loss\n loss = F.mse_loss(result, y)\n\n # compute gradients\n loss.backward()\n\n # let the optimizer do its work; the parameters will be updated in this call\n optim.step()\n\n sum_loss += loss.item()\n total += 1\n # add some printing\n if (i + 1) % 200 == 0:\n print(\n \"epoch {}\\titeration {}\\tloss {:.5f}\".format(\n epoch, i, sum_loss / total\n )\n )\n\n def predict(self, X_test):\n with torch.no_grad():\n return self.forward(torch.tensor(X_test, dtype=torch.float32)).numpy()\n" }, { "alpha_fraction": 0.5278276205062866, "alphanum_fraction": 0.5439856648445129, "avg_line_length": 23.19565200805664, "blob_id": "1bf3e09de62ba638215d281539b26bcaf1f67848", "content_id": "4b5ff08feb8df1a03aebcb2a923877e500fcc32b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1114, "license_type": "no_license", "max_line_length": 94, "num_lines": 46, "path": "/perception/wedge_no2/gelsight/util/streaming.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import urllib.request\nimport urllib\nimport cv2\nimport numpy as np\nimport time \n\nclass Streaming(object):\n def __init__(self, url):\n self.image = None\n self.url = url\n\n self.streaming = False\n\n self.start_stream()\n\n def __del__(self):\n self.stop_stream()\n\n def start_stream(self):\n self.streaming = True\n self.stream=urllib.request.urlopen(self.url)\n\n def stop_stream(self):\n if self.streaming == True:\n self.stream.close()\n self.streaming = False\n\n def load_stream(self):\n stream = self.stream\n bytess=b''\n\n while True:\n if self.streaming == False:\n time.sleep(0.01)\n continue\n\n bytess+=stream.read(32767)\n\n a = bytess.find(b'\\xff\\xd8') # JPEG start\n b = bytess.find(b'\\xff\\xd9') # JPEG end\n\n if a!=-1 and b!=-1:\n jpg = bytess[a:b+2] # actual image\n bytess= bytess[b+2:] # other informations\n\n self.image = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.IMREAD_COLOR) \n" }, { "alpha_fraction": 0.47039058804512024, "alphanum_fraction": 0.5850483179092407, "avg_line_length": 29.915584564208984, "blob_id": "857e447300f207147ac6059b20f820a9d6a10568", "content_id": "744a5612f8382dfddad8cc603145603c68791d5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4762, "license_type": "no_license", "max_line_length": 158, "num_lines": 154, "path": "/flip.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport time\nimport cv2\nfrom controller.ur5.ur_controller import UR_Controller\nfrom controller.mini_robot_arm.RX150_driver import RX150_Driver\nfrom perception.kinect.kinect_camera import Kinect\nfrom scipy.spatial.transform import Rotation as R\n# from controller.gripper.gripper_control import Gripper_Controller\nfrom controller.gripper.gripper_control_v2 import Gripper_Controller_V2\nfrom scipy.interpolate import griddata\nfrom perception.fabric.util.segmentation import segmentation\nfrom perception.fabric.run import Run\nfrom PIL import Image\nimport skimage.measure\nimport torchvision.transforms as T\nimport os\nfrom perception.kinect.Vis3D import ClassVis3D\nfrom perception.fabric.grasp_selector import select_grasp\n\n\n# cam_intrinsics_origin = np.array([\n# [917.3927285, 0., 957.21294894],\n# [ 0., 918.96234057, 555.32910487],\n# [ 0., 0., 1. ]])\n# cam_intrinsics = np.array([\n# [965.24853516, 0., 950.50838964],\n# [ 0., 939.67144775, 554.55567298],\n# [ 0., 0., 1. ]]) # New Camera Intrinsic Matrix\n# dist = np.array([[ 0.0990126, -0.10306044, 0.00024658, -0.00268176, 0.05763196]])\n# camera = Kinect(cam_intrinsics_origin, dist)\n#\n# cam_pose = np.loadtxt('real/camera_pose.txt', delimiter=' ')\n# cam_depth_scale = np.loadtxt('real/camera_depth_scale.txt', delimiter=' ')\n#\n# # User options (change me)\n# # --------------- Setup options ---------------\n# urc = UR_Controller()\n# urc.start()\n# a = 0.2\n# v = 0.2\n#\nrx150 = RX150_Driver(port=\"/dev/ttyACM0\", baudrate=1000000)\nrx150.torque(enable=1)\nprint(rx150.readpos())\n\ndef rx_move(g_open, x_pos, end_angle=0, timestamp=100):\n values = [1024, 2549, 1110, 1400, 0, g_open]\n x = x_pos\n y = 120\n end_angle = end_angle\n rx150.gogo(values, x, y, end_angle, 0, timestamp=timestamp)\n\n# ---------------------------------------------\n# initialize rx150\n# rx_move(1600, 270, timestamp=200)\n# rx_move(760, 270, timestamp=200)\nrx_move(760, 370, end_angle=0.8, timestamp=200)\n# rx_move(1600, 370, end_angle=0.8, timestamp=200)\n# for i in range(100):\n# print(rx150.readpos())\n# time.sleep(0.01)\n# time.sleep(0.5)\n# # ---------------------------------------------\n#\n# # workspace_limits = np.asarray([[0.3, 0.748], [-0.224, 0.224], [-0.255, -0.1]]) # Cols: min max, Rows: x y z (define workspace limits in robot coordinates)\n# workspace_limits = np.asarray([[-0.845, -0.605], [-0.14, 0.2], [0, 0.2]]) # Cols: min max, Rows: x y z (define workspace limits in robot coordinates)\n#\n# # tool_orientation = [2.22,-2.22,0]\n# # tool_orientation = [0., -np.pi/2, 0.] # [0,-2.22,2.22] # [2.22,2.22,0]\n# from scipy.spatial.transform import Rotation as R\n# tool_orientation_euler = [180, 0, 90]\n# # tool_orientation_euler = [180, 0, 0]\n# # tool_orientation_euler = [180, 0, 180]\n# tool_orientation = R.from_euler('xyz', tool_orientation_euler, degrees=True).as_rotvec()\n# # tool_orientation = [0., -np.pi, 0.] # [0,-2.22,2.22] # [2.22,2.22,0]\n#\n# # pose0 = np.array([-0.511, 0.294, 0.237, -0.032, -1.666, 0.138])\n# pose0 = np.hstack([[-0.505, 0.06, 0.2], tool_orientation])\n# pose_up = pose0.copy()\n# pose_transfer = np.array([-0.431, 0.092, 0.232, -2.230, -2.194, -0.019])\n#\n# urc.movel_wait(pose0, a=a, v=v)\n# # ---------------------------------------------\n\n# Start gripper\ngrc = Gripper_Controller_V2()\ngrc.follow_gripper_pos = 0\ngrc.follow_dc = [0, 0]\ngrc.gripper_helper.set_gripper_current_limit(0.3)\ngrc.start()\n\ntime.sleep(1)\nk = -1\nsign = 1\n\npos_list = [\n# [-20, 20, 0.4],\n# [-10, 10, 0.7],\n# [0, 30, 0.32],\n# [0, 30, 0.5],\n[0, 30, 0.4],\n# [0, 20, 0.51],\n# [-5, 5, 0.8],\n# [0, 0, 1.4],\n[0, 30, 0.5],\n[0, 0, 0.]\n# [-5, 5, 0.8],\n# [-10, 10, 0.7],\n# [-20, 20, 0.4],\n]\n# grc.follow_gripper_pos = 0.\nfor i in range(10000):\n # grc.follow_dc = [-20, 20]\n # grc.follow_gripper_pos = 0.3\n # grc.follow_dc = [0, 30]\n # grc.follow_gripper_pos = 0.5\n # time.sleep(1)\n # grc.follow_dc = [0, 0]\n # grc.follow_gripper_pos = 0\n # time.sleep(1)\n\n # k = k + 0.1 * sign\n # print(k)\n # if k > 20 or k < -5:\n # sign *= -1\n\n # grc.follow_dc = [-k, k]\n grc.follow_dc = [pos_list[k][0], pos_list[k][1]]\n grc.follow_gripper_pos = pos_list[k][2]\n # k = (k + 1) % len(pos_list)\n c = input()\n print(c)\n if c == \"o\":\n k = -1\n else:\n k = (k+1) % (len(pos_list) - 1)\n\n\n\n\n # grc.follow_dc = [-5, -5]\n # grc.follow_gripper_pos = 1.1\n # time.sleep(1)\n # grc.follow_dc = [0, 0]\n # grc.follow_gripper_pos = 0\n # time.sleep(1)\n\n # grc.follow_dc = [-30, 0]\n # grc.follow_gripper_pos = 0.5\n # time.sleep(1)\n # grc.follow_dc = [0, 0]\n # grc.follow_gripper_pos = 0\n # time.sleep(1)\n" }, { "alpha_fraction": 0.5229936838150024, "alphanum_fraction": 0.5395250916481018, "avg_line_length": 28.70535659790039, "blob_id": "ad34275610d9b7b9c03eb10bee5b54445572f009", "content_id": "280074cd16263c7e6eeab9e5164f7052f6d35b15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3327, "license_type": "no_license", "max_line_length": 99, "num_lines": 112, "path": "/util/ProcessICP.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import threading\nimport time\nfrom scipy.spatial.transform import Rotation as R\nimport copy\nimport open3d as o3d\nfrom open3d import *\nimport numpy as np\nimport multiprocessing\n\nexitFlag = 0\n\nclass myThread (multiprocessing.Process):\n def __init__(self, target):\n multiprocessing.Process.__init__(self)\n self.target = copy.deepcopy(target)\n self.stop = False\n self.id = -1\n self.reg_p2p = None\n \n def icp(self):\n threshold = 2\n trans_init = self.trans_init.copy()\n \n rot_noise = np.eye(4)\n rot_noise[:3,:3] = R.from_euler('xyz', np.random.random(3)*1-0.5, degrees=True).as_matrix()\n \n trans_init = rot_noise.dot(trans_init)\n target = copy.deepcopy(self.target)\n # trans_init[:,:3] += np.random.random(3) * 0.01\n \n reg_p2p = o3d.registration.registration_icp(\n self.source, target, threshold, trans_init,\n o3d.registration.TransformationEstimationPointToPlane(),\n o3d.registration.ICPConvergenceCriteria(max_iteration=500))\n self.reg_p2p = reg_p2p.copy()\n \n def run(self):\n last_id = -1\n while True:\n if self.stop:\n break\n time.sleep(0.001)\n current_id = self.id\n if current_id > last_id:\n self.icp()\n last_id = current_id\n \n \n\nclass ProcessICP():\n def __init__(self, target=None, nb_worker=4, time_limit=0.1):\n self.nb_worker = nb_worker\n self.time_limit = time_limit\n self.thread_list = []\n\n # Create new threads\n for i in range(self.nb_worker):\n t = myThread(target)\n self.thread_list.append(t)\n\n # Start new Threads\n for t in self.thread_list:\n t.start()\n\n self.frame_id = 0\n \n def estimate(self, source, trans_init):\n for t in self.thread_list:\n t.source = source\n t.trans_init = trans_init\n t.id = self.frame_id\n \n\n time.sleep(self.time_limit)\n \n trans_opt = trans_init.copy()\n fitness_max = -1\n inlier_rmse_min = 1e9\n \n \n for t in self.thread_list:\n print(t.id, self.frame_id, t.reg_p2p)\n if t.id == self.frame_id and t.reg_p2p is not None:\n print(f\"fitness {t.reg_p2p.fitness} inlier_rmse {t.reg_p2p.inlier_rmse}\")\n \n if t.reg_p2p.fitness > fitness_max or \\\n (t.reg_p2p.fitness == fitness_max and t.reg_p2p.inlier_rmse < inlier_rmse_min):\n fitness_max = t.reg_p2p.fitness\n inlier_rmse_min = t.reg_p2p.inlier_rmse\n trans_opt = t.reg_p2p.transformation.copy()\n \n self.frame_id += 1\n print(f\"fitness_max {fitness_max} inlier_rmse_min {inlier_rmse_min}\")\n \n return trans_opt\n\n def stop(self):\n for t in self.thread_list:\n t.stop = True\n t.join()\n\n print (\"Exiting Main Thread\")\n \n\nif __name__ == '__main__':\n thread_icp = ThreadICP(target, nb_worker=3, time_limit=0.1)\n\n for i in range(4):\n trans_opt = thread_icp.estimate(source, trans_init)\n print(trans_opt)\n\n thread_icp.stop()\n" }, { "alpha_fraction": 0.4803548753261566, "alphanum_fraction": 0.5969581604003906, "avg_line_length": 27.0118350982666, "blob_id": "d7bfff886e1256e59b92e71a6487816e05774cb2", "content_id": "04c3cb72be0c38733def325c91e92ab9f87e95f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4734, "license_type": "no_license", "max_line_length": 158, "num_lines": 169, "path": "/move_together_thread.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport time\nimport cv2\nfrom controller.ur5.ur_controller import UR_Controller\nfrom controller.mini_robot_arm.RX150_driver import RX150_Driver, RX150_Driver_Thread\nfrom perception.kinect.kinect_camera import Kinect\nfrom scipy.spatial.transform import Rotation as R\nfrom controller.gripper.gripper_control_v2 import Gripper_Controller_V2\nfrom scipy.interpolate import griddata\nfrom perception.fabric.util.segmentation import segmentation\nfrom perception.fabric.run import Run\nfrom PIL import Image\nimport skimage.measure\nimport torchvision.transforms as T\nimport os\n\n\n\n\n################################### initialize ur5\nurc = UR_Controller()\nurc.start()\n\n################################### initialize rx150\nrx150_thread = RX150_Driver_Thread(port=\"/dev/ttyACM0\", baudrate=1000000)\nrx150_thread.rx150.torque(enable=1)\nrx150_thread.start()\n\n\n################################### initialize gripper\n# Start gripper\n# grc = Gripper_Controller_V2()\n# grc.follow_gripper_pos = 1.2\n# grc.follow_dc = [0, 0]\n# grc.gripper_helper.set_gripper_current_limit(0.3)\n# grc.start()\n\n\n################################### 0 degrees\ng_open = 800\nvalues = [1024, 2549, 1110, 1400, 0, g_open]\nx = 300\ny = 90\nend_angle = 0 / 180. * np.pi # in pi\n# rx150_thread.rx150.gogo(values, x, y, end_angle, 0, timestamp=100)\n\n\n\n\n################################### main loop\n\n\n\nrx150_thread.gogo(values, x, y, end_angle, 0, timestamp=100)\npose0 = np.array([-0.431, 0.108, 0.24, -2.23, -2.194, -0.019])\n# urc.movel_wait(pose0)\nurc.pose_following = pose0\n\ntime.sleep(2)\npose = pose0.copy()\nfor i in range(240):\n\t# print(urc.getl_rt())\n\n if i < 60:\n dz = (1 - np.cos(i / 30 * np.pi)) * 0.03\n dx = 0\n elif i < 120:\n dz = 0\n dx = np.sin(i / 30 * np.pi) * 0.03\n elif i < 240:\n dz = (1 - np.cos(i / 30 * np.pi)) * 0.03\n dx = np.sin(i / 30 * np.pi) * 0.03\n\n\n\n # dx = np.sin(i / 60 * np.pi) * 0.02\n\n # rx150 move\n values = [1024, 2549, 1110, 1400, 0, g_open]\n rx150_thread.gogo(values, x + dx * 1000, y + dz * 1000, end_angle, 0, timestamp=20)\n\n # ur5 move\n pose[1] = pose0[1] + dx\n pose[2] = pose0[2] + dz\n urc.pose_following = pose\n\n\n time.sleep(0.05)\nurc.flag_terminate = True\nurc.join()\n\n\n# for i in (list(range(30)) + list(range(30, -1, -1)))*1:\n# values = [1024, 2549, 1110, 1400, 0, g_open]\n# rx150_thread.gogo(values, x, y+i*2, end_angle, 0, timestamp=10)\n# time.sleep(0.05)\n\n\nrx150_thread.running = False\nrx150_thread.join()\n\n\n\n\n#\n#\n#\n#\n#\n# def rx_move(g_open, x_pos):\n# values = [1024, 2549, 1110, 1400, 0, g_open]\n# x = x_pos\n# y = 90\n# end_angle = 0\n# rx150.gogo(values, x, 90, end_angle, 0, timestamp=100)\n#\n# # workspace_limits = np.asarray([[0.3, 0.748], [-0.224, 0.224], [-0.255, -0.1]]) # Cols: min max, Rows: x y z (define workspace limits in robot coordinates)\n# workspace_limits = np.asarray([[-0.845, -0.605], [-0.14, 0.2], [0, 0.2]]) # Cols: min max, Rows: x y z (define workspace limits in robot coordinates)\n#\n# # tool_orientation = [2.22,-2.22,0]\n# # tool_orientation = [0., -np.pi/2, 0.] # [0,-2.22,2.22] # [2.22,2.22,0]\n# from scipy.spatial.transform import Rotation as R\n# tool_orientation_euler = [180, 0, 90]\n# # tool_orientation_euler = [180, 0, 0]\n# # tool_orientation_euler = [180, 0, 180]\n# tool_orientation = R.from_euler('xyz', tool_orientation_euler, degrees=True).as_rotvec()\n# # tool_orientation = [0., -np.pi, 0.] # [0,-2.22,2.22] # [2.22,2.22,0]\n#\n# # pose0 = np.array([-0.511, 0.294, 0.237, -0.032, -1.666, 0.138])\n# pose0 = np.hstack([[-0.505, 0.06, 0.2], tool_orientation])\n# pose_up = pose0.copy()\n# pose_start = np.array([-0.431, 0.05, 0.21, -2.230, -2.194, -0.019])\n#\n# urc.movel_wait(pose_start, a=a, v=v)\n#\n# g_open = 1200\n# values = [1024, 2549, 1110, 1400, 0, g_open]\n# x = 420\n# y = 120\n# end_angle = 0*np.pi/180\n# rx150.gogo(values, x, y, end_angle, 0, timestamp=100)\n#\n#\n# urc.movel_wait(pose_start+[0,0,0.12,0,0,0], a=a, v=v)\n# rx150.gogo(values, x, y+120, end_angle, 0, timestamp=100)\n#\n#\n# urc.movel_wait(pose_start+[0,0,0,0,0,0], a=a, v=v)\n# rx150.gogo(values, x, y, end_angle, 0, timestamp=100)\n#\n# rx150.gogo(values, x-120, y, end_angle, 0, timestamp=100)\n# urc.movel_wait(pose_start+[0,-0.12,0,0,0,0], a=a, v=v)\n#\n# urc.movel_wait(pose_start+[0,0,0,0,0,0], a=a, v=v)\n# rx150.gogo(values, x, y, end_angle, 0, timestamp=100)\n#\n# # inc = 10\n# # for i in range(50):\n# # y = y + inc\n# # if y > 240 or y < 0:\n# # inc *= -1\n# # time.sleep(0.2)\n# # rx150.gogo(values, x, y, end_angle, 0, timestamp=10)\n# # pose_start[2] += inc / 1000.\n# # urc.movel_nowait(pose_start, a=a, v=v)\n# # time.sleep(0.01)\n" }, { "alpha_fraction": 0.4779299795627594, "alphanum_fraction": 0.5920852422714233, "avg_line_length": 20.540983200073242, "blob_id": "4711e75929818f1032109f836be7735c7ab4cc41", "content_id": "0c793f90e078062c91c18468a339139dad8a83e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1314, "license_type": "no_license", "max_line_length": 66, "num_lines": 61, "path": "/main.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "from controller.gripper.gripper_control import Gripper_Controller\nfrom controller.ur5.ur_controller import UR_Controller\nimport time\nimport numpy as np\n\nurc = UR_Controller()\ngrc = Gripper_Controller()\n\nurc.start()\ngrc.start()\n\n# pose0 = np.array([-0.252, -0.138, 0.067, 0.013, -2.121, 2.313])\npose0 = np.array([-0.539, 0.312, 0.321, -1.787, -1.604, -0.691])\npose1 = np.array([-0.481, 0.283, 0.359, -1.6, -1.480, -1.031])\npose2 = np.array([-0.481, 0.283, 0.359, -1.216, -1.480, -.8])\n\n\n# grc.gripper_helper.set_gripper_current_limit(0.4)\n\n\ngrc.follow_gripper_pos = 0\n# c = input()\n# grc.follow_gripper_pos = 1\n\n#\n#\n# a = 0.05\n# v = 0.05\n# urc.movel_wait(pose0, a=a, v=v)\n# #\n# c = input()\n\n# urc.movel_wait(pose1, a=a, v=v)\n# c = input()\n# urc.movel_wait(pose0, a=a, v=v)\n# c = input()\n# urc.movel_wait(pose2, a=a, v=v)\n#\n# grc.follow_gripper_pos = 1\n#\n# c = input()\n\n# time.sleep(0.5)\n# # # pose1 = pose0 - [0.2, 0, 0, 0, 0, 0]\n# # # #\n# a = 0.02\n# v = 0.02\n# dt = 0.05\n# # urc.movel_wait(pose1, a=a, v=v)\n# for t in range(int(5//dt)):\n# urc.speedl( [-0.015, 0, 0, 0, 0, 0], a=a, t=dt)\n# grc.follow_gripper_pos -= .0005\n# time.sleep(dt)\n\nprint(', '.join([str(\"{:.3f}\".format(_)) for _ in urc.getl_rt()]))\ntime.sleep(0.01)\n\nurc.flag_terminate = True\n# grc.flag_terminate = True\nurc.join()\n# grc.join()\n" }, { "alpha_fraction": 0.48288440704345703, "alphanum_fraction": 0.5137485861778259, "avg_line_length": 24.640287399291992, "blob_id": "013b38519dcc444ad30d8ac3f9e4d9425499b69c", "content_id": "72a41713b936dc65cd7be4637079a40426e9e432", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3564, "license_type": "no_license", "max_line_length": 84, "num_lines": 139, "path": "/logger_class.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import time\nfrom datetime import datetime\nimport numpy as np\nimport pickle\nimport os\nimport cv2\nimport matplotlib.pyplot as plt\n\ndef get_timestamp():\n return datetime.now().strftime(\"%Y%m%d%H%M%S%f\")\n\ndef read_logs(filename):\n # data = np.load(filename, allow_pickle=True)\n logs = pickle.load(open(filename, \"rb\"))\n # gelsight_url = logs[0]['gelsight_url']\n return logs\n\nclass Logger():\n def __init__(self):\n # raw data\n self.gelsight = None\n # self.cable_pose = None\n self.ur_velocity = None\n self.ur_pose = None\n\n # states\n self.x = None\n self.y = None\n self.theta = None\n self.dt = None\n\n # action\n self.phi = None\n\n # last_log\n self.last_log = None\n\n self.data_dir = './data/'\n self.id = '20210806_tvlqr'\n self.img_dir = os.path.join(self.data_dir, 'imgs', self.id)\n self.log_dir = os.path.join(self.data_dir, 'logs', self.id)\n self.logs = []\n\n self.prefix = get_timestamp()\n\n def save_img(self):\n dirname = self.img_dir\n timestamp = get_timestamp()\n\n filename = os.path.join(dirname, \"{}_{}.jpg\".format(self.prefix, timestamp))\n # cv2.imwrite(filename, self.gelsight)\n return filename\n\n def update_timestamp(self):\n self.prefix = get_timestamp()\n\n def save_logs(self):\n if len(self.logs) < 10:\n print(\"Logs < 10, not saving\")\n return\n\n print(\"Log length: \", len(self.logs))\n\n filename = os.path.join(self.log_dir, self.prefix) + '.p'\n # np.savez(filename, logs=self.logs)\n\n self.update_timestamp()\n pickle.dump(self.logs, open(filename, \"wb\"))\n self.logs = []\n\n def add(self):\n self.gelsight_url = self.save_img()\n\n log = {\n # 'gelsight_url' : self.gelsight_url,\n # 'cable_pose' : self.cable_pose,\n 'ur_velocity' : self.ur_velocity,\n 'ur_pose' : self.ur_pose,\n 'x' : self.x,\n 'y' : self.y,\n 'theta' : self.theta,\n # 'phi' : self.phi,\n 'dt' : self.dt,\n }\n\n self.logs.append(log)\n\n\ndef update_log(logger):\n logger.gelsight = np.random.random([200,300,3]) * 255\n logger.pose = np.array([1., 1., 1., 2., 2., 2.])\n\ndef draw(logs):\n x = []\n y = []\n thetas = []\n last_xy = [0, 0]\n for i in range(0, len(logs)):\n log = logs[i]\n ur_pose = log['ur_pose']\n theta = log['theta']\n cable_center = log['x']\n\n\n # dist = np.sum((ur_pose[:2] - last_xy)**2)**0.5\n # print(dist)\n # if (i > 1 and (dist > 1e-3 or dist == 0.)):\n # last_xy = [ur_pose[0], ur_pose[1]]\n # continue\n # print(\"XXXXX\")\n\n last_xy = [ur_pose[0], ur_pose[1]]\n thetas.append(theta)\n x.append(ur_pose[0])\n y.append(ur_pose[1])\n\n # x.append(cable_center[0])\n # y.append(cable_center[1])\n # x = x[120:-150]\n # y = y[120:-150]\n # plt.plot(x, y, 'x')\n # plt.plot(thetas)\n plt.figure()\n plt.plot(x, y, 'x')\n plt.figure()\n plt.plot(thetas)\n plt.show()\n\nif __name__ == \"__main__\":\n # logger = Logger()\n # update_log(logger)\n # logger.add()\n # logger.save_logs()\n\n # logs = read_logs('../data/logs/1908290930/20190829144117332498.p')\n # logs = read_logs('~/Code/Fabric/src/data/logs/1908290930/20210427.p')\n\n draw(logs)\n # print(get_timestamp())\n" }, { "alpha_fraction": 0.4922882318496704, "alphanum_fraction": 0.5297092199325562, "avg_line_length": 25.722972869873047, "blob_id": "859b1abee6dc9c4aaf6a8c5932534cd30cdd090a", "content_id": "4ca173ce44cf6d497db33600e3908ffc675205df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3955, "license_type": "no_license", "max_line_length": 70, "num_lines": 148, "path": "/controller/ur5/ur_controller.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "from threading import Thread\nimport numpy as np\nimport socket\nimport time\nimport urx\nfrom scipy.spatial.transform import Rotation as R\n\n\nclass UR_Controller(Thread):\n def __init__(self, HOST=\"10.42.0.121\", PORT=30003):\n Thread.__init__(self)\n\n self.rob = urx.Robot(HOST, use_rt=True)\n\n self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.s.connect((HOST, PORT))\n\n self.flag_terminate = False\n self.pose_following = None\n\n # Check whether the robot has reach the target pose\n self.last_p = []\n self.len_p = 10\n self.total_error = 0\n\n def getl_rt(self):\n # get current pose with urx urrtmon with 125 Hz\n return self.rob.rtmon.getTCF(True)\n\n def send(self, cmd):\n cmd = str.encode(cmd)\n self.s.send(cmd)\n\n def speedl(self, v, a=0.5, t=0.05):\n # send speedl command in socket\n cmd = \"speedl({}, a={}, t={})\\n\".format(str(list(v)), a, t)\n self.send(cmd)\n\n\n def movel_wait(self, pose, a=1, v=0.04):\n # linear move in tool space and wait\n s = self.s\n\n cmd = \"movel(p{}, a={}, v={})\\n\".format(str(list(pose)), a, v)\n cmd = str.encode(cmd)\n s.send(cmd)\n\n last_p = []\n len_p = 20\n quat_goal = R.from_rotvec(pose[3:]).as_quat()\n while True:\n p = self.getl_rt()\n # quat_current = R.from_rotvec(p[3:]).as_quat()\n #\n # error_pos = np.sum((p[:3] - pose[:3])**2)\n # error_ori = np.sum((quat_goal - quat_current)**2)\n #\n # print(\"pos error\", error_pos)\n # print(\"orientation error\", error_ori)\n # diff = error_pos + error_ori\n\n last_p.append(p.copy())\n if len(last_p) > len_p:\n last_p = last_p[-len_p:]\n\n diff = np.sum((p - np.mean(last_p, axis=0))**2)\n\n if len(last_p) == len_p and diff < 1e-12:\n break\n time.sleep(0.02)\n\n def follow(self):\n if self.pose_following is None:\n return\n cur_pose = self.getl_rt()\n error = self.pose_following - cur_pose\n kp = 5\n ki = 0.1\n self.total_error = self.total_error * 0.9 + error\n v = error * kp + self.total_error * ki\n cmd = np.zeros(6)\n cmd[:3] = v[:3]\n print(\"cur\", cur_pose[2], \"goal\", self.pose_following[2])\n self.speedl(cmd, a=1, t=0.05)\n\n def movel_nowait(self, pose, a=1, v=0.04):\n # linear move in tool space and wait\n s = self.s\n\n cmd = \"movel(p{}, a={}, v={})\\n\".format(str(list(pose)), a, v)\n cmd = str.encode(cmd)\n s.send(cmd)\n\n def check_stopped(self):\n p = self.getl_rt()\n\n self.last_p.append(p.copy())\n if len(self.last_p) > self.len_p:\n self.last_p = self.last_p[-self.len_p:]\n\n diff = np.sum((p - np.mean(self.last_p, axis=0))**2)\n\n if len(self.last_p) == self.len_p and diff < 1e-12:\n return True\n\n return False\n\n def run(self):\n while not self.flag_terminate:\n self.follow()\n time.sleep(0.01)\n self.rob.close()\n\n\ndef main():\n\turc = UR_Controller()\n\turc.start()\n\n\tpose0 = np.array([-0.431, 0.05, 0.21, -2.23, -2.194, -0.019])\n\turc.movel_wait(pose0)\n\ttime.sleep(2)\n\tpose = pose0.copy()\n\tfor i in range(120):\n\t\t# print(urc.getl_rt())\n\t\tpose[2] = pose0[2] + np.sin(i / 40 * np.pi) * 0.03\n\t\turc.pose_following = pose\n\t\ttime.sleep(0.05)\n\turc.flag_terminate = True\n\turc.join()\n\ndef test_thread():\n\turc = UR_Controller()\n\turc.start()\n\n\tpose0 = np.array([-0.431, 0.05, 0.21, -2.23, -2.194, -0.019])\n\turc.movel_wait(pose0)\n\ttime.sleep(2)\n\tpose = pose0.copy()\n\tfor i in range(120):\n\t\t# print(urc.getl_rt())\n\t\tpose[2] = pose0[2] + np.sin(i / 40 * np.pi) * 0.03\n\t\turc.pose_following = pose\n\t\ttime.sleep(0.05)\n\turc.flag_terminate = True\n\turc.join()\n\nif __name__ == \"__main__\":\n test_thread()\n" }, { "alpha_fraction": 0.4881656765937805, "alphanum_fraction": 0.557988166809082, "avg_line_length": 24.606060028076172, "blob_id": "30386917c90a3be8057202296ff48aadd03b62f4", "content_id": "3fa16cd78d8a5d2f2e5fa1841531159c17f9824f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3380, "license_type": "no_license", "max_line_length": 115, "num_lines": 132, "path": "/perception/wedge_no2/gelsight/util/processing.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom math import cos, sin, pi\n\nfrom .fast_poisson import poisson_reconstruct\n\nimport pickle\n\nimport cv2\n\n\ndef img2grad(frame0, frame):\n\n diff = frame * 1.0 - frame0\n\n # dx = (diff[:,:,2] * cos(pi/6) - diff[:,:,0] * cos(pi/6)) / 255.\n # dy = (diff[:,:,0] * sin(pi/6) + diff[:,:,2] * sin(pi/6) - diff[:,:,1]) / 255.\n\n dx = (diff[:, :, 1] - (diff[:, :, 0] + diff[:, :, 2]) * 0) / 255.0\n dy = (diff[:, :, 2] - diff[:, :, 0] * 2) / 255.0\n # dy = -(diff[:,:,0] - (diff[:,:,1] + diff[:,:,2]) * 1) / 255.\n\n dx = dx / (1 - dx ** 2) ** 0.5 / 32 * 2\n dy = dy / (1 - dy ** 2) ** 0.5 / 32\n\n # cv2.imshow('dx',dx*32+0.5)\n # cv2.imshow('dy',dy*32+0.5)\n\n return dx, dy\n\n\ndef img2depth(frame0, frame):\n dx, dy = img2grad(frame0, frame)\n\n zeros = np.zeros_like(dx)\n depth = poisson_reconstruct(dy, dx * 0, zeros)\n\n # dx_poisson, dy_poisson = np.gradient(depth)\n # dy[dy_poisson>1] = dy_poisson[dy_poisson>1]\n\n # depth = poisson_reconstruct(dy, dx, zeros)\n\n return depth\n\n # return dx, dy\n\n\n# bias = model.predict([[np.dstack([np.zeros([48, 48], dtype=np.float32), np.zeros([48, 48], dtype=np.float32)])]])\n\n\ndef img2depth_nn_dy(frame0, frame):\n\n frame_small = frame\n frame0_small = frame0\n dx, dy = img2grad(frame0_small, frame_small)\n\n dx = dx / 4 * 0\n dy = dy / 4\n\n pred = model.predict([[np.dstack([dy, dx])]]) - bias\n zeros = np.zeros_like(dx)\n depth = poisson_reconstruct(dy * 2, pred[0, :, :, 1] * 2, zeros)\n\n # dx = dx / 4\n # dy = dy / 4 * 0\n # pred = model.predict([[np.dstack([dx, dy])]]) - bias\n\n # zeros = np.zeros_like(dx)\n # depth = poisson_reconstruct(pred[0,:,:,1] * 2, dx * 2, zeros)\n\n # depth = poisson_reconstruct(pred[0,:,:,0] * 4, pred[0,:,:,1] * 4, zeros)\n # depth = poisson_reconstruct(dy, dx, zeros)\n\n # cv2.imshow('dy', cv2.resize(dy*40+0.5, (300, 300)))\n # cv2.imshow('dx_predict', cv2.resize(pred[0,:,:,1]*40+0.5, (300, 300)))\n\n return depth\n\n\ndef img2depth_nn(frame0, frame):\n LUT = pickle.load(open(\"LUT.pkl\", \"rb\"))\n\n # frame_small = cv2.resize(frame, (48, 48))\n # frame0_small = cv2.resize(frame0, (48, 48))\n frame_small = frame\n frame0_small = frame0\n # dx, dy = img2grad(frame0_small, frame_small)\n\n # dx = dx / 32 * 0\n # dy = dy / 128.\n\n img = frame * 1.0 - frame0 + 127\n\n W, H = img.shape[0], img.shape[1]\n\n X = np.reshape(img, [W * H, 3])\n Y = LUT.predict(X)\n\n dy = np.reshape(Y[:, 0], [W, H])\n dx = np.reshape(Y[:, 1], [W, H])\n\n print(dx.max(), dx.min())\n\n dx = dx / 256.0 / 32 * 0\n dy = dy / 256.0 / 32\n\n pred = model.predict([[np.dstack([dy, dx])]])\n z_reshape = np.reshape(pred[0], [frame_small.shape[0], frame_small.shape[1]])\n\n print(\"MAX\", z_reshape.max())\n\n return z_reshape * 4.0\n\n\n\ndef warp_perspective(img, corners, output_sz=(210, 270)):\n TOPLEFT, TOPRIGHT, BOTTOMLEFT, BOTTOMRIGHT = corners\n\n WARP_W = output_sz[0]\n WARP_H = output_sz[1]\n\n points1=np.float32([TOPLEFT,TOPRIGHT,BOTTOMLEFT,BOTTOMRIGHT])\n points2=np.float32([[0,0],[WARP_W,0],[0,WARP_H],[WARP_W,WARP_H]])\n\n matrix=cv2.getPerspectiveTransform(points1,points2)\n\n result = cv2.warpPerspective(img, matrix, (WARP_W, WARP_H))\n\n return result\n\ndef ini_frame(frame):\n frame_rect = warp_perspective(raw_img, (252, 137), (429, 135), (197, 374), (500, 380))\n return frame\n" }, { "alpha_fraction": 0.4095040261745453, "alphanum_fraction": 0.47520124912261963, "avg_line_length": 24.006492614746094, "blob_id": "635f541978a8b877b8668bc6a343ae00b80b2ba6", "content_id": "e6683b3cfb7977a8f58c8924fff4da867cecb5c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3851, "license_type": "no_license", "max_line_length": 90, "num_lines": 154, "path": "/controller/mini_robot_arm/RX150_driver_0216.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import serial\nimport cv2\nimport numpy as np\nfrom math import sin, cos, pi\nimport time\nimport random\n\nimg = np.zeros([300, 300])\n\n\n\n\nclass RX150_IK:\n def __init__(self):\n self.l2 = 150\n self.lT = 50\n self.l3 = 150\n\n self.O = np.array([[0], [0]])\n pass\n\n def fk(self, t2, t3):\n l2, lT, l3 = self.l2, self.lT, self.l3\n\n x0 = (150, 0)\n x1 = (x0[0] + l2 * sin(t2), x0[1] + l2 * cos(t2))\n x2 = (x1[0] + lT * cos(t2), x1[1] - lT * sin(t2))\n x3 = (x2[0] + l3 * cos(t2 + t3), x2[1] - l3 * sin(t2 + t3))\n return x3\n\n def get_JaccobianTranspose(self, t2, t3):\n l2, lT, l3 = self.l2, self.lT, self.l3\n\n J = np.array(\n [\n [l2 * cos(t2) - lT * sin(t2) - l3 * sin(t2 + t3), -l3 * sin(t2 + t3)],\n [-l2 * sin(t2) - lT * cos(t2) - l3 * cos(t2 + t3), -l3 * cos(t2 + t3)],\n ]\n )\n return J.T\n\n def ik(self, end_angle, x, y):\n l2, lT, l3 = self.l2, self.lT, self.l3\n O_last = self.O.copy()\n\n angle = end_angle\n l_end = 150.0\n fix_end_angle = -0.3\n\n x -= l_end * cos(angle)\n y += l_end * sin(angle)\n\n if len(O_last) == 3:\n O = O_last[:-1]\n else:\n O = O_last\n\n alpha = 0.00001\n\n i = 0\n\n while True:\n i += 1\n\n V = self.fk(O[0, 0], O[1, 0])\n JT = self.get_JaccobianTranspose(O[0, 0], O[1, 0])\n\n dV = np.array([[x - V[0]], [y - V[1]]])\n O = O + alpha * JT.dot(dV)\n\n if (dV ** 2).sum() < 1e-4:\n break\n\n O = np.array(\n [O[0].tolist(), O[1].tolist(), [-O[0, 0] - O[1, 0] + angle - fix_end_angle]]\n )\n\n self.O = O.copy()\n return O\n\nclass RX150_Driver:\n def __init__(self, port=\"/dev/tty.usbmodem145301\", baudrate=1000000):\n self.rx150_ik = RX150_IK()\n self.ser = serial.Serial(port, baudrate) # open serial port\n print(self.ser.name) # check which port was really used\n\n\n def readpos(self):\n self.ser.write(str.encode(\"readpos \\n\"))\n for i in range(1):\n line = self.ser.readline()\n return line\n\n\n def torque(self, enable=1):\n self.ser.write(str.encode(\"torque {}\\n\".format(enable)))\n for i in range(6):\n line = self.ser.readline()\n print(line)\n\n\n def send(self, values):\n goal_str = \" \".join([str(_) for _ in values])\n self.ser.write(str.encode((\"goal {}\\n\".format(goal_str)))) # write a string\n\n\n def setxy(self, values, end_angle, x, y):\n O = self.rx150_ik.ik(end_angle, x, y)\n joint = 2048 - O / pi * 2048\n\n values[1] = int(joint[0, 0])\n values[2] = int(joint[1, 0])\n values[3] = int(joint[2, 0])\n\n\n def gogo(self, values, x, y, ang, goal_x, goal_y, goal_ang, goal_rot, timestamp=30.0):\n # timestamp = 30.\n dx = (goal_x - x) / timestamp\n dy = (goal_y - y) / timestamp\n da = (goal_ang - ang) / timestamp\n dr = (goal_rot - values[-2]) / timestamp\n\n for t in range(int(timestamp)):\n x += dx\n y += dy\n ang += da\n values[-2] += dr\n # print(dx, dy, da, dr)\n self.setxy(values, ang, x, y)\n self.send(values)\n time.sleep(0.01)\n\n x = goal_x\n y = goal_y\n ang = goal_ang\n values[-2] = goal_rot\n # print(dx, dy, da, dr)\n self.setxy(values, ang, x, y)\n self.send(values)\n # time.sleep(0.03)\n\n\n\n\nrx150 = RX150_Driver(port=\"/dev/tty.usbmodem145301\", baudrate=1000000)\nprint(rx150.readpos())\n\ng_open = 2000\n# g_open = 850\nvalues = [1024, 2549, 1110, 1400, 1024, g_open]\nx = 300\ny = 180\nend_angle = 0\nrx150.gogo(values, x, y, end_angle, 300, 180, 0, 1024)\n" }, { "alpha_fraction": 0.4809049367904663, "alphanum_fraction": 0.546492338180542, "avg_line_length": 23.33333396911621, "blob_id": "4ac7a6a9c51fe45af3b6e125cfa386bcb676c973", "content_id": "dcede2e9a6124a9d39be70f592a49d2770b45417", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4818, "license_type": "no_license", "max_line_length": 90, "num_lines": 198, "path": "/main_teleop.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n# -*- coding: utf-8\n\nimport time\nimport cv2\nimport numpy as np\nfrom math import pi, sin, cos, asin, acos\nimport csv\nfrom perception.wedge.gelsight.util.Vis3D import ClassVis3D\n\nfrom perception.wedge.gelsight.gelsight_driver import GelSight\nfrom perception.teleop.apriltag_pose import AprilTagPose\nfrom control.gripper.gripper_control import Gripper_Controller\nfrom control.ur5.ur_controller import UR_Controller\nfrom control.mini_robot_arm.RX150_driver import RX150_Driver\nfrom scipy.spatial.transform import Rotation as R\n\nimport collections\n\nurc = UR_Controller()\ngrc = Gripper_Controller()\n\nurc.start()\ngrc.start()\n\n\n# pose0 = np.array([-0.51, 0.376, 0.409, -1.416, -1.480, -1.031])\n# pose0 = np.array([-0.539, 0.312, 0.29, -1.787, -1.604, -0.691])\npose0 = np.array([-0.520, 0, 0.235, -1.129, -1.226, 1.326])\ngrc.gripper_helper.set_gripper_current_limit(0.6)\n\n\nrx150 = RX150_Driver(port=\"/dev/ttyACM0\", baudrate=1000000)\nrx150.torque(enable=1)\ngrc.follow_gripper_pos = 0.7\nprint(rx150.readpos())\n\ndef rx_move(g_open):\n values = [2048, 2549, 1110, 1400, 3072, g_open]\n x = 320\n y = 90\n end_angle = -30. / 180. * np.pi\n rx150.gogo(values, x, y, end_angle, 320, 90, end_angle, 3072, timestamp=30)\n\nrx_move(820)\n# rx_move(2000)\n\n# sensor_id = \"W03\"\nsensor_id = \"Fabric0\"\n\nIP = \"http://rpigelsightfabric.local\"\n\n# N M fps x0 y0 dx dy\ntracking_setting = (10, 14, 5, 16, 41, 27, 27)\n\n\nn, m = 150, 200\n# Vis3D = ClassVis3D(m, n)\n\n\ndef read_csv(filename=f\"config_{sensor_id}.csv\"):\n rows = []\n\n with open(filename, \"r\") as csvfile:\n csvreader = csv.reader(csvfile)\n header = next(csvreader)\n for row in csvreader:\n rows.append((int(row[1]), int(row[2])))\n\n return rows\n\n\ncorners = tuple(read_csv())\n# corners=((252, 137), (429, 135), (197, 374), (500, 380))\n\n\ngs = GelSight(\n IP=IP,\n corners=corners,\n tracking_setting=tracking_setting,\n output_sz=(400, 300),\n id=\"right\",\n)\ngs.start()\n\n\napril_url = \"http://rpigelsight2.local:8080/?action=stream\"\napril_tag_pose = AprilTagPose(april_url)\napril_tag_pose.start()\n\ndef test_combined():\n\n grc.follow_gripper_pos = 0.5\n a = 0.15\n v = 0.08\n urc.movel_wait(pose0, a=a, v=v)\n\n depth_queue = []\n dt = 0.01\n\n cnt = 0\n flag_start = False\n pose_t0, pose_R0 = None, None\n pose_t_last, pose_R_last = None, None\n\n while True:\n img = gs.stream.image\n\n\n # get pose image\n pose_img = gs.pc.pose_img\n # pose_img = gs.pc.frame_large\n if pose_img is None:\n continue\n\n # waiting for apriltag tracking\n if april_tag_pose.img_undist is None:\n continue\n\n\n depth_current = gs.pc.depth.max()\n depth_queue.append(depth_current)\n\n if len(depth_queue) > 4:\n depth_queue = depth_queue[1:]\n\n if depth_current == np.max(depth_queue):\n pose = gs.pc.pose\n # cv2.imshow(\"pose\", pose_img)\n\n # cv2.imshow(\"apriltag\", april_tag_pose.img_undist)\n cv2.imshow(\"frame\", cv2.resize(april_tag_pose.img_undist, (0, 0), fx=0.5, fy=0.5))\n c = cv2.waitKey(1)\n\n\n # if ur_pose[0] < -0.7:\n # vel[0] = max(vel[0], 0.)\n # if ur_pose[0] > -0.3:\n # vel[0] = min(vel[0], 0.)\n # if ur_pose[2] < .08:\n # vel[2] = 0.\n # if ur_pose[1] > .3:\n # vel[0] = min(vel[0], 0.)\n # vel[1] = 0.\n\n\n if flag_start is True and april_tag_pose.pose is not None:\n pose_t, pose_R = april_tag_pose.pose\n\n if pose_t_last is not None:\n distance = np.sum((pose_t_last - pose_t)**2)**0.5\n else:\n distance = 0\n if distance > 50:\n break\n\n pose_t_last, pose_R_last = pose_t.copy(), pose_R.copy()\n\n if pose_t0 is None:\n pose_t0, pose_R0 = pose_t.copy(), pose_R.copy()\n\n pose_a_t = pose_t - pose_t0\n\n # apriltag to UR5\n alpha = 0.002\n uXa = alpha * np.array([[0, 0, -1], [1, 0, 0], [0, -1, 0]], dtype=np.float32)\n pose_u_t = (uXa @ pose_a_t).T[0] + pose0[:3]\n\n\n # move to goal pose\n vel = np.array([0., 0., 0., 0., 0., 0.])\n ur_pose = urc.getl_rt()\n\n kp = 2\n vel[:3] = kp*(pose_u_t - ur_pose[:3])\n\n urc.speedl(vel, a=a, t=dt*4)\n\n # r = R.from_matrix(pose_R)\n # print(r.as_euler('xyz', degrees=True))\n # print(pose_u_t)\n\n\n time.sleep(dt)\n cnt += 1\n\n c = cv2.waitKey(1) & 0xFF\n if c == ord(\"q\"):\n break\n elif c == ord(\"s\"):\n flag_start = True\n\n\nif __name__ == \"__main__\":\n try:\n test_combined()\n finally:\n del gs\n" }, { "alpha_fraction": 0.48630136251449585, "alphanum_fraction": 0.5534246563911438, "avg_line_length": 24.704225540161133, "blob_id": "5f7b017d9922eda384f27d382d28172def50f111", "content_id": "6e8daf9fde39885eb1ccde5441d0a89336bc19e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3650, "license_type": "no_license", "max_line_length": 115, "num_lines": 142, "path": "/util/processing.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom math import cos, sin, pi\n\nimport util\nfrom util.fast_poisson import poisson_reconstruct\n\nimport pickle\n\nimport cv2\n\n\ndef img2grad(frame0, frame):\n\n diff = frame * 1.0 - frame0\n\n # dx = (diff[:,:,2] * cos(pi/6) - diff[:,:,0] * cos(pi/6)) / 255.\n # dy = (diff[:,:,0] * sin(pi/6) + diff[:,:,2] * sin(pi/6) - diff[:,:,1]) / 255.\n\n dx = (diff[:, :, 1] - (diff[:, :, 0] + diff[:, :, 2]) * 0) / 255.0\n dy = (diff[:, :, 2] - diff[:, :, 0] * 2) / 255.0\n # dy = -(diff[:,:,0] - (diff[:,:,1] + diff[:,:,2]) * 1) / 255.\n\n dx = dx / (1 - dx ** 2) ** 0.5 / 32 * 2\n dy = dy / (1 - dy ** 2) ** 0.5 / 32\n\n # cv2.imshow('dx',dx*32+0.5)\n # cv2.imshow('dy',dy*32+0.5)\n\n return dx, dy\n\n\ndef img2depth(frame0, frame):\n dx, dy = img2grad(frame0, frame)\n\n zeros = np.zeros_like(dx)\n depth = poisson_reconstruct(dy, dx * 0, zeros)\n\n # dx_poisson, dy_poisson = np.gradient(depth)\n # dy[dy_poisson>1] = dy_poisson[dy_poisson>1]\n\n # depth = poisson_reconstruct(dy, dx, zeros)\n\n return depth\n\n # return dx, dy\n\n\n# bias = model.predict([[np.dstack([np.zeros([48, 48], dtype=np.float32), np.zeros([48, 48], dtype=np.float32)])]])\n\n\ndef img2depth_nn_dy(frame0, frame):\n\n frame_small = frame\n frame0_small = frame0\n dx, dy = img2grad(frame0_small, frame_small)\n\n dx = dx / 4 * 0\n dy = dy / 4\n\n pred = model.predict([[np.dstack([dy, dx])]]) - bias\n zeros = np.zeros_like(dx)\n depth = poisson_reconstruct(dy * 2, pred[0, :, :, 1] * 2, zeros)\n\n # dx = dx / 4\n # dy = dy / 4 * 0\n # pred = model.predict([[np.dstack([dx, dy])]]) - bias\n\n # zeros = np.zeros_like(dx)\n # depth = poisson_reconstruct(pred[0,:,:,1] * 2, dx * 2, zeros)\n\n # depth = poisson_reconstruct(pred[0,:,:,0] * 4, pred[0,:,:,1] * 4, zeros)\n # depth = poisson_reconstruct(dy, dx, zeros)\n\n # cv2.imshow('dy', cv2.resize(dy*40+0.5, (300, 300)))\n # cv2.imshow('dx_predict', cv2.resize(pred[0,:,:,1]*40+0.5, (300, 300)))\n\n return depth\n\n\ndef img2depth_nn(frame0, frame):\n LUT = pickle.load(open(\"LUT.pkl\", \"rb\"))\n\n # frame_small = cv2.resize(frame, (48, 48))\n # frame0_small = cv2.resize(frame0, (48, 48))\n frame_small = frame\n frame0_small = frame0\n # dx, dy = img2grad(frame0_small, frame_small)\n\n # dx = dx / 32 * 0\n # dy = dy / 128.\n\n img = frame * 1.0 - frame0 + 127\n\n W, H = img.shape[0], img.shape[1]\n\n X = np.reshape(img, [W * H, 3])\n Y = LUT.predict(X)\n\n dy = np.reshape(Y[:, 0], [W, H])\n dx = np.reshape(Y[:, 1], [W, H])\n\n print(dx.max(), dx.min())\n\n dx = dx / 256.0 / 32 * 0\n dy = dy / 256.0 / 32\n\n pred = model.predict([[np.dstack([dy, dx])]])\n z_reshape = np.reshape(pred[0], [frame_small.shape[0], frame_small.shape[1]])\n\n print(\"MAX\", z_reshape.max())\n\n return z_reshape * 4.0\n\n\ndef warp_perspective(img, TOPLEFT, TOPRIGHT, BOTTOMLEFT, BOTTOMRIGHT):\n\n K = 2\n # TOPLEFT = (217 * K, 120 * K)\n # TOPRIGHT = (400 * K, 117 * K)\n # BOTTOMLEFT = (157 * K, 341 * K)\n # BOTTOMRIGHT = (492 * K, 341 * K)\n\n TOPLEFT = TOPLEFT\n TOPRIGHT = TOPRIGHT\n BOTTOMLEFT = BOTTOMLEFT\n BOTTOMRIGHT = BOTTOMRIGHT\n\n # WARP_W = 300 * K\n WARP_W = 200 * K\n # WARP_H = 270 * K\n WARP_H = 150 * K\n\n points1 = np.float32([TOPLEFT, TOPRIGHT, BOTTOMLEFT, BOTTOMRIGHT])\n points2 = np.float32([[0, 0], [WARP_W, 0], [0, WARP_H], [WARP_W, WARP_H]])\n\n matrix = cv2.getPerspectiveTransform(points1, points2)\n # matrix=cv2.getAffineTransform(points1,points2)\n\n result = cv2.warpPerspective(img, matrix, (WARP_W, WARP_H))\n # result = cv2.warpAffine(img, matrix, (WARP_W,WARP_H))\n\n return result\n" }, { "alpha_fraction": 0.499205082654953, "alphanum_fraction": 0.637519896030426, "avg_line_length": 17, "blob_id": "98787a4ea6ad138834e22cae9f20b04576adc6cf", "content_id": "ef3104bf70400694db34dc7fec05da5a534e99dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 629, "license_type": "no_license", "max_line_length": 94, "num_lines": 35, "path": "/controller/ur5/example_urx.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import urx\nimport time\nimport socket\nimport numpy as np\n\nHOST = \"10.42.0.121\"\nPORT = 30003\n\nrob = urx.Robot(HOST, use_rt=True)\ntime.sleep(0.5)\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((HOST, PORT))\n\n\npose = rob.rtmon.getTCF(True)\nprint(pose)\n\npose0 = np.array([-0.45787275, 0.21882309, 0.42330343, -1.21460518, -1.23206398, -1.04391101])\npose1 = pose0 - [0, 0, 0.03, 0, 0, 0]\na = 0.1\nv = 0.2\ncmd = f\"movel(p{list(pose1)}, a={a}, v={v})\" + \"\\n\"\ncmd = str.encode(cmd)\ns.send(cmd)\n\ntime.sleep(1)\n\ncmd = f\"movel(p{list(pose0)}, a={a}, v={v})\" + \"\\n\"\ncmd = str.encode(cmd)\ns.send(cmd)\n\nprint(pose)\n\nrob.close()" }, { "alpha_fraction": 0.5187623500823975, "alphanum_fraction": 0.5497037768363953, "avg_line_length": 26.369369506835938, "blob_id": "fe5c1fda34bfde8a82856b5cd715711e87cab861", "content_id": "cd945357c9f960f928eaf223df2f8f342fa09789", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3038, "license_type": "no_license", "max_line_length": 85, "num_lines": 111, "path": "/perception/teleop/streaming.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import urllib.request\nimport urllib\nimport cv2\nimport numpy as np\nimport time\nimport _thread\nimport datetime\nimport os\n\n\nclass Streaming(object):\n def __init__(self, url):\n self.image = None\n self.url = url\n\n self.streaming = False\n\n self.start_stream()\n\n def __del__(self):\n self.stop_stream()\n\n def start_stream(self):\n self.streaming = True\n self.stream = urllib.request.urlopen(self.url)\n\n def stop_stream(self):\n if self.streaming == True:\n self.stream.close()\n self.streaming = False\n\n def load_stream(self):\n stream = self.stream\n bytess = b\"\"\n\n while True:\n if self.streaming == False:\n time.sleep(0.01)\n continue\n\n bytess += stream.read(32767)\n\n a = bytess.find(b\"\\xff\\xd8\") # JPEG start\n b = bytess.find(b\"\\xff\\xd9\") # JPEG end\n\n if a != -1 and b != -1:\n jpg = bytess[a : b + 2] # actual image\n bytess = bytess[b + 2 :] # other informations\n\n self.image = cv2.imdecode(\n np.fromstring(jpg, dtype=np.uint8), cv2.IMREAD_COLOR\n )\n\n\n# termination criteria\ncriteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)\n\n# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)\nobjp = np.zeros((6 * 7, 3), np.float32)\nobjp[:, :2] = np.mgrid[0:7, 0:6].T.reshape(-1, 2)\n\n# Arrays to store object points and image points from all the images.\nobjpoints = [] # 3d point in real world space\nimgpoints = [] # 2d points in image plane.\n\n\nif __name__ == \"__main__\":\n url = \"http://rpigelsight2.local:8080/?action=stream\"\n stream = Streaming(url)\n _thread.start_new_thread(stream.load_stream, ())\n\n # dirname = \"data/chessboard_2/\"\n # dirname = \"data/screw/\"\n dirname = \"data/chessboard_3rd/\"\n os.makedirs(dirname, exist_ok=True)\n\n while True:\n img = stream.image\n\n if img is None:\n print(\"Waiting for streaming...\")\n time.sleep(0.1)\n continue\n\n # img = cv2.imread(fname)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n # Find the chess board corners\n ret, corners = cv2.findChessboardCorners(gray, (7, 6), None)\n\n # If found, add object points, image points (after refining them)\n if ret == True:\n objpoints.append(objp)\n\n corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria)\n imgpoints.append(corners2)\n\n # Draw and display the corners\n img = cv2.drawChessboardCorners(img, (7, 6), corners2, ret)\n\n # show the image\n cv2.imshow(\"frame\", cv2.resize(img, (0, 0), fx=0.25, fy=0.25))\n\n c = cv2.waitKey(1)\n if c == ord(\"s\"):\n # Save\n fn = dirname + datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\") + \".jpg\"\n cv2.imwrite(fn, img)\n pass\n elif c == ord(\"q\"):\n break\n" }, { "alpha_fraction": 0.4739699065685272, "alphanum_fraction": 0.5076897740364075, "avg_line_length": 34.14161682128906, "blob_id": "e3b6b490f79f8f4e981067d6d322a31708e5aea9", "content_id": "d0c9b6968f341dbb9f6aee3b356d4317706584b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12159, "license_type": "no_license", "max_line_length": 89, "num_lines": 346, "path": "/controller/gripper/rg_serial.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "from struct import *\nimport time\nfrom .auto_serial import AutoSerial\n\n\nclass SBMotor:\n def __init__(self, serial_port, baud_rate=115200):\n self.serial_port = serial_port\n self.motor_ids = []\n self.baud_rate = baud_rate\n\n self.motor_reg_space = 16\n self.counter = 0\n self.time = time.time()\n\n auto_serial = AutoSerial(\n serial_port=self.serial_port,\n baud_rate=self.baud_rate,\n vendor_id=\"16C0\",\n product_id=\"0483\",\n serial_number=\"8218580\",\n )\n\n self.ser = auto_serial.ser\n\n self.recv_buffer = bytearray(62) # with current\n # self.recv_buffer = bytearray(58) # without current\n self.enable = [False] * 8\n self.stop = [False] * 8\n self.pos = [0.0] * 8\n self.vel = [0.0] * 8\n self.curr = [0.0] * 8\n\n # if motor_params is None:\n # (self.ticks_per_rev, self.kp, self.ki, self.kd) = self.get_default_params()\n # else:\n # (self.ticks_per_rev, self.kp, self.ki, self.kd) = motor_params\n\n # print(self.ticks_per_rev, self.kp, self.ki, self.kd)\n # self.init(self.ticks_per_rev, self.kp, self.ki, self.kd)\n\n # def get_default_params(self):\n # if self.motor_rpm == 26:\n # params = (5462.22, 25.0, 0, 0.16)\n # elif self.motor_rpm == 44:\n # params = (3244.188, 15.0, 0, 0.2)\n # elif self.motor_rpm == 52:\n # params = (2774.64, 16, 0, 0.3)\n # elif self.motor_rpm == 280:\n # params = (514.14, 25.0, 0, 0.16)\n # elif self.motor_rpm == 2737:\n # params = (52.62, 100.0, 0, 0.16)\n # elif self.motor_rpm == 130:\n # params = (3040.7596, 14.0, 0, 0.3)\n # else:\n # params = ()\n # print(\"motor not supported\")\n # return params\n\n def send_cmd_four_double(self, register_name, val1, val2, val3, val4):\n # ser = serial.Serial(self.serial_port, self.baud_rate)\n # print('send_cmd_four_double')\n data = bytearray(\n pack(\n \"<BBBBHddddxx\",\n 0x7E,\n 0,\n 0xFF,\n 0xAA,\n register_name,\n val1,\n val2,\n val3,\n val4,\n )\n )\n # print('unstuffed: ', data)\n data = self.msg_stuff(data)\n # print('stuffed: ', data)\n self.ser.write(data)\n\n def send_cmd_eight_float(self, register_name, data_eight_vals):\n data = bytearray(\n pack(\n \"<BBBBHffffffffxx\", 0x7E, 0, 0xFF, 0xAA, register_name, *data_eight_vals\n )\n )\n data = self.msg_stuff(data)\n self.ser.write(data)\n\n def send_cmd_twelve_float(self, register_name, data_twelve_vals):\n data = bytearray(\n pack(\n \"<BBBBHffffffffffffxx\",\n 0x7E,\n 0,\n 0xFF,\n 0xAA,\n register_name,\n *data_twelve_vals\n )\n )\n data = self.msg_stuff(data)\n self.ser.write(data)\n\n def send_cmd_single_double(self, register_name, val):\n # ser = serial.Serial(self.serial_port, self.baud_rate)\n\n data = bytearray(pack(\"<BBBBHdxx\", 0x7E, 0, 0xFF, 0xAA, register_name, val))\n data = self.msg_stuff(data)\n self.ser.write(data)\n\n def send_cmd_single_int(self, register_name, val):\n # ser = serial.Serial(self.serial_port, self.baud_rate)\n # print('send_cmd_single_int')\n data = bytearray(pack(\"<BBBBHixx\", 0x7E, 0, 0xFF, 0xAA, register_name, val))\n # print('unstuffed: ', data)\n data = self.msg_stuff(data)\n # print('stuffed: ', data)\n self.ser.write(data)\n\n def send_cmd_single_bool(self, register_name, val):\n # ser = serial.Serial(self.serial_port, self.baud_rate)\n data = bytearray(pack(\"<BBBBH?xx\", 0x7E, 0, 0xFF, 0xAA, register_name, val))\n data = self.msg_stuff(data)\n self.ser.write(data)\n\n def init_single_motor(self, motor_id, ticks_per_rev, kp, ki, kd, ctrl_mode):\n if motor_id not in self.motor_ids:\n self.motor_ids.append(motor_id)\n # init pid\n register_name = motor_id * self.motor_reg_space + 16 + 9\n self.send_cmd_four_double(register_name, ticks_per_rev, kp, ki, kd)\n # set control mode, 0 pos, 1 vel\n register_name = motor_id * self.motor_reg_space + 16 + 10\n self.send_cmd_single_int(register_name, ctrl_mode)\n\n def set_enable(self, motor_id, if_enable):\n register_name = motor_id * self.motor_reg_space + 16\n self.enable[motor_id] = if_enable\n self.send_cmd_single_bool(register_name, self.enable[motor_id])\n\n def set_stop(self, motor_id, if_stop):\n register_name = motor_id * self.motor_reg_space + 16 + 7\n self.stop[motor_id] = if_stop\n self.send_cmd_single_bool(register_name, self.stop[motor_id])\n\n def move_to_pos(self, motor_id, degree):\n register_name = motor_id * self.motor_reg_space + 16 + 1\n self.pos[motor_id] = degree\n self.send_cmd_single_double(register_name, self.pos[motor_id])\n\n def set_speed(self, motor_id, rpm):\n register_name = motor_id * self.motor_reg_space + 16 + 2\n self.vel[motor_id] = rpm\n self.send_cmd_single_double(register_name, self.vel[motor_id])\n\n def set_current(self, motor_id, curr):\n register_name = motor_id * self.motor_reg_space + 16 + 10\n self.curr[motor_id] = curr\n self.send_cmd_single_int(register_name, self.curr[motor_id])\n\n def move(self, motor_id, degree):\n register_name = motor_id * self.motor_reg_space + 16 + 1\n self.pos[motor_id] += degree\n self.send_cmd_single_double(register_name, self.pos[motor_id])\n\n def set_kp(self, motor_id, kp):\n register_name = motor_id * self.motor_reg_space + 16 + 3\n self.kp = kp\n self.send_cmd_single_double(register_name, self.kp)\n\n def set_ki(self, motor_id, ki):\n register_name = motor_id * self.motor_reg_space + 16 + 4\n self.ki = ki\n self.send_cmd_single_double(register_name, self.ki)\n\n def set_kd(self, motor_id, kd):\n register_name = motor_id * self.motor_reg_space + 16 + 5\n self.kd = kd\n self.send_cmd_single_double(register_name, self.kd)\n\n def request_vals(self):\n register_name = 0xE0\n self.send_cmd_single_int(register_name, 53)\n\n def move_all_to_pos(self, positions):\n # The positions contain only the positions of the active motors\n for ii in range(len(self.motor_ids)):\n self.pos[self.motor_ids[ii]] = positions[ii]\n register_name = 0xD1\n self.send_cmd_eight_float(register_name, self.pos)\n\n def set_all_velocity(self, velocities):\n # The positions contain only the positions of the active motors\n for ii in range(len(self.motor_ids)):\n self.vel[self.motor_ids[ii]] = velocities[ii]\n register_name = 0xD2\n self.send_cmd_eight_float(register_name, self.vel)\n\n @staticmethod\n def msg_stuff(msg):\n msg_len = len(msg)\n msg[1] = msg_len - 2\n stuffing = 2\n for ii in range(1, msg_len):\n # print(\"%x\"%msg[ii])\n if msg[ii] == 0x7E:\n # print(ii)\n msg[stuffing] = ii\n stuffing = ii\n msg[stuffing] = 0xFF\n return msg\n\n @staticmethod\n def msg_unstuff(msg):\n stuffing = 2\n while msg[stuffing] != 0xFF:\n tmp = msg[stuffing]\n\n msg[stuffing] = 0x7E\n stuffing = tmp\n # print(len(msg))\n # print(stuffing)\n msg[stuffing] = 0x7E\n return msg\n\n def recv_from_serial(self):\n last_state = -1\n cur_state = 0\n rx_len = 0\n idx = 0\n # ready_to_return = False\n return_val = None\n\n while self.ser.in_waiting:\n # rx = self.ser.read(1)\n\n if cur_state == 0:\n # if last_state != cur_state:\n # print(\"read header\")\n rx = self.ser.read(1)\n # print(rx)\n # print(\"%x\" % rx[0])\n if int(rx[0]) == 0x7E:\n cur_state = 1\n idx = 0\n self.recv_buffer[idx] = rx[0]\n last_state = 0\n\n elif cur_state == 1:\n # if last_state != cur_state:\n # print(\"read length\")\n rx = self.ser.read(1)\n rx_len = int(rx[0])\n # print(\"%x\" % rx[0])\n if rx_len <= 0:\n cur_state = 3\n else:\n self.recv_buffer[1] = rx[0]\n cur_state = 2\n last_state = 1\n\n elif cur_state == 2:\n # if last_state != cur_state:\n # print(\"read data\")\n rx = self.ser.read(1)\n # print(\"%x\" % rx[0])\n if int(rx[0]) == 0x7E:\n cur_state = 3\n else:\n self.recv_buffer[idx + 2] = rx[0]\n idx += 1\n # print(idx)\n if idx + 2 == rx_len:\n self.recv_buffer = self.msg_unstuff(bytearray(self.recv_buffer))\n\n # unpacked_data = unpack('<BBBBHlffffffffffff', self.recv_buffer)\n # return_val = unpacked_data[6:]\n unpacked_data = unpack(\n \"<BBBBHffffffffffffhhhh\", self.recv_buffer\n )\n return_val = unpacked_data[5:]\n # print(unpacked_data)\n\n # cur_time = time.time()\n # if (cur_time - self.time) > 0.05:\n # print(unpacked_data)\n # # motor0.counter = 0\n # # print(cur_time - self.time)\n # self.time = cur_time\n cur_state = 0\n self.counter += 1\n\n last_state = 2\n if cur_state == 3:\n # if last_state != cur_state:\n # print(\"read error\")\n last_state = cur_state\n cur_state = 0\n if return_val is not None:\n return [return_val[i] for i in range(8)]\n\n return None\n\n\nif __name__ == \"__main__\":\n import numpy as np\n\n motor_cpr = 3040.7596\n com_baud = 1000000\n print(\"Establishing Serial port...\")\n dc_motors = SBMotor(\"/dev/cu.usbmodem123\", com_baud)\n print(dc_motors.ser)\n dc_motors.init_single_motor(2, motor_cpr, 15.0, 0.2, 100.0, ctrl_mode=1)\n dc_motors.init_single_motor(3, motor_cpr, 15.0, 0.2, 100.0, ctrl_mode=1)\n # dc_motors.init_single_motor(6, motor_cpr, 14.0, 0.0, 0.3, ctrl_mode=0)\n # dc_motors.init_single_motor(7, motor_cpr, 14.0, 0.0, 0.3, ctrl_mode=0)\n # dc_motors.init_single_motor(4, motor_cpr, 15.0, 0.2, 100.0, ctrl_mode=1)\n dc_motors.init_single_motor(4, motor_cpr, 14.0, 0.0, 0.3, ctrl_mode=0)\n # dc_motors.init_single_motor(5, motor_cpr, 15.0, 0.2, 100.0, ctrl_mode=1)\n dc_motors.init_single_motor(5, motor_cpr, 14.0, 0.0, 0.3, ctrl_mode=0)\n\n input(\"finish init\")\n # pos_list = [[0, 0], [-40, 0], [0, 0], [0, 40], [0, 0], [-20, 20]]\n pos_list = [[0, 0], [-15, 15]]\n pos_cnt = 0\n pos = 0\n st_time = time.time()\n while True:\n curr_time = time.time()\n # vel = np.sin(curr_time) * 1\n vel = 10\n pos = np.sin((curr_time - st_time) * 4) * 20\n c = input()\n # pos = 10\n pos_cnt = (pos_cnt + 1) % len(pos_list)\n\n dc_motors.set_all_velocity([0, 0, pos_list[pos_cnt][0], pos_list[pos_cnt][1]])\n print(dc_motors.vel)\n dc_motors.request_vals()\n if dc_motors.ser.in_waiting:\n sensor_val = dc_motors.recv_from_serial()\n print(\"sensor_val: \", sensor_val)\n\n # time.sleep(0.1)\n" }, { "alpha_fraction": 0.32984089851379395, "alphanum_fraction": 0.44082266092300415, "avg_line_length": 22.42727279663086, "blob_id": "f2ee10c992fc7e379cb9bb105845157710f6b375", "content_id": "61a43db492e0dcc222074115c7522182ddafb11d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2577, "license_type": "no_license", "max_line_length": 85, "num_lines": 110, "path": "/controller/mini_robot_arm/ik.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\nfrom math import sin, cos, pi\nimport time\nimport random\n\nimg = np.zeros([300, 300])\n\nl2 = 150\nlT = 50\nl3 = 150\n\n\ndef fk(t2, t3):\n x0 = (150, 0)\n x1 = (x0[0] + l2 * sin(t2), x0[1] + l2 * cos(t2))\n x2 = (x1[0] + lT * cos(t2), x1[1] - lT * sin(t2))\n x3 = (x2[0] + l3 * cos(t2 + t3), x2[1] - l3 * sin(t2 + t3))\n return x3\n\n\ndef draw_fk(t2, t3):\n img = np.zeros([300, 500, 3])\n x0 = (150, 0)\n x1 = (x0[0] + l2 * sin(t2), x0[1] + l2 * cos(t2))\n x2 = (x1[0] + lT * cos(t2), x1[1] - lT * sin(t2))\n x3 = (x2[0] + l3 * cos(t2 + t3), x2[1] - l3 * sin(t2 + t3))\n cv2.line(img, x0, (int(x1[0]), int(x1[1])), (255, 0, 0), 3)\n cv2.line(img, (int(x1[0]), int(x1[1])), (int(x2[0]), int(x2[1])), (255, 0, 0), 3)\n cv2.line(img, (int(x2[0]), int(x2[1])), (int(x3[0]), int(x3[1])), (255, 0, 0), 3)\n return img\n\n\ndef get_JaccobianTranspose(t2, t3):\n J = np.array(\n [\n [l2 * cos(t2) - lT * sin(t2) - l3 * sin(t2 + t3), -l3 * sin(t2 + t3)],\n [-l2 * sin(t2) - lT * cos(t2) - l3 * cos(t2 + t3), -l3 * cos(t2 + t3)],\n ]\n )\n return J.T\n\n\ndef ik(end_angle, x, y, O_):\n angle = end_angle\n l_end = 150.0\n fix_end_angle = -0.3\n\n x -= l_end * cos(angle)\n y += l_end * sin(angle)\n\n if len(O_) == 3:\n O = O_[:-1]\n else:\n O = O_\n alpha = 0.00001\n\n i = 0\n\n while True:\n i += 1\n\n V = fk(O[0, 0], O[1, 0])\n JT = get_JaccobianTranspose(O[0, 0], O[1, 0])\n\n dV = np.array([[x - V[0]], [y - V[1]]])\n O = O + alpha * JT.dot(dV)\n\n if (dV ** 2).sum() < 1e-4:\n break\n\n return np.array(\n [O[0].tolist(), O[1].tolist(), [-O[0, 0] - O[1, 0] + angle - fix_end_angle]]\n )\n\n\ntm = time.time()\nN = 360\nend_angle = 0.2\n\nO = np.array([[0], [0]])\nO0 = np.array([[0], [0]])\n\nfor t in range(360):\n x, y = 300 + sin(t / 180 * pi * 10) * 50, 100 + cos(t / 180 * pi * 10) * 30\n O = ik(end_angle, x, y, O)\n # img = draw_fk(O[0, 0], O[1, 0])\n # cv2.circle(img, (int(x), int(y)), 20, (0, 0, 255), 2)\n # cv2.imshow(\"img\", img[::-1])\n # cv2.waitKey(1)\n\n# for i in range(N):\n# t2, t3 = random.random() * pi, random.random()*pi\n# # x, y = fk(-50/180*pi, -50/180*pi)\n# x, y = fk(t2, t3)\n# O = ik(x, y)\n# # print(t2, t3, O)\n# V = fk(O[0,0], O[1,0])\n# print((t2-O[0,0])**2+(t3-O[1,0])**2,\n# (V[0]-x)**2+(V[1]-y)**2)\n# print((time.time()-tm)/N)\n\n# img = draw_fk(-20/180*pi, -20/180*pi)\n# cv2.imshow(\n# \"img\",\n# img[\n# ::-1,\n# ],\n# )\n# cv2.waitKey(0)\n" }, { "alpha_fraction": 0.4844961166381836, "alphanum_fraction": 0.5109819173812866, "avg_line_length": 27.14545440673828, "blob_id": "2d307efc638db9e360906801785a0a4bc5a0918f", "content_id": "00d7feeb2a6b78951848de9d5957e7b0f56e2a67", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4644, "license_type": "no_license", "max_line_length": 95, "num_lines": 165, "path": "/perception/teleop/apriltag_pose.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import time\n\nimport cv2\nimport numpy as np\nimport _thread\nimport yaml\nfrom dt_apriltags import Detector\nimport urllib\nimport urllib.request\nfrom threading import Thread\nfrom scipy.spatial.transform import Rotation as R\nimport os\n\n\nclass Streaming(object):\n def __init__(self, url):\n self.image = None\n self.url = url\n\n self.streaming = False\n\n self.start_stream()\n\n def __del__(self):\n self.stop_stream()\n\n def start_stream(self):\n self.streaming = True\n self.stream = urllib.request.urlopen(self.url)\n\n def stop_stream(self):\n if self.streaming == True:\n self.stream.close()\n self.streaming = False\n\n def load_stream(self):\n stream = self.stream\n bytess = b\"\"\n\n while True:\n if self.streaming == False:\n time.sleep(0.01)\n continue\n\n bytess += stream.read(32767)\n\n a = bytess.find(b\"\\xff\\xd8\") # JPEG start\n b = bytess.find(b\"\\xff\\xd9\") # JPEG end\n\n if a != -1 and b != -1:\n jpg = bytess[a : b + 2] # actual image\n bytess = bytess[b + 2 :] # other informations\n\n self.image = cv2.imdecode(\n np.fromstring(jpg, dtype=np.uint8), cv2.IMREAD_COLOR\n )\n\nclass AprilTagPose(Thread):\n def __init__(self, url):\n Thread.__init__(self)\n\n self.img_undist = None\n\n self.stream = Streaming(url)\n _thread.start_new_thread(self.stream.load_stream, ())\n\n def run(self):\n at_detector = Detector(\n families=\"tag36h11\",\n nthreads=1,\n quad_decimate=1.0,\n quad_sigma=0.0,\n refine_edges=1,\n decode_sharpening=0.25,\n debug=0,\n )\n\n tag_size = 40 ## unit: mm\n\n # cap = cv2.VideoCapture(0)\n dir_abs = os.path.dirname(os.path.realpath(__file__))\n print(os.path.join(dir_abs, \"camera_parameters.yaml\"))\n with open(os.path.join(dir_abs, \"camera_parameters.yaml\"), \"r\") as stream:\n parameters = yaml.load(stream)\n\n mtx_origin = np.array(parameters[\"K\"]).reshape([3, 3])\n dist = np.array(parameters[\"dist\"])\n\n\n H, W = parameters[\"H\"], parameters[\"W\"]\n camera_matrix, roi = cv2.getOptimalNewCameraMatrix(mtx_origin, dist, (W, H), 1, (W, H))\n\n camera_params = (\n camera_matrix[0, 0],\n camera_matrix[1, 1],\n camera_matrix[0, 2],\n camera_matrix[1, 2],\n )\n\n axis = (\n np.float32([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, -1]]).reshape(-1, 3)\n * tag_size\n / 2\n )\n\n\n def draw(img, imgpts):\n corner = tuple(imgpts[0].ravel())\n img = cv2.line(img, corner, tuple(imgpts[1].ravel()), (255, 0, 0), 5)\n img = cv2.line(img, corner, tuple(imgpts[2].ravel()), (0, 255, 0), 5)\n img = cv2.line(img, corner, tuple(imgpts[3].ravel()), (0, 0, 255), 5)\n return img\n\n\n\n while True:\n img = self.stream.image\n\n if img is None:\n print(\"Waiting for streaming...\")\n time.sleep(0.1)\n continue\n\n # undistort\n img_undist = cv2.undistort(img, mtx_origin, dist, None, camera_matrix)\n\n # crop the image\n x, y, w, h = roi\n img_undist = img_undist[y : y + h, x : x + w]\n\n img_undist_gray = np.mean(img, axis=-1).astype(np.uint8)\n st = time.time()\n # detect apriltag\n tags = at_detector.detect(img_undist_gray, True, camera_params, tag_size)\n\n if len(tags) > 0:\n\n # project 3D points to image plane\n xy, jac = cv2.projectPoints(\n axis, tags[0].pose_R, tags[0].pose_t, camera_matrix, (0, 0, 0, 0, 0)\n )\n draw(img_undist, np.round(xy).astype(np.int))\n self.pose = (tags[0].pose_t, tags[0].pose_R)\n else:\n self.pose = None\n # print(time.time() - st)\n\n self.img_undist = img_undist.copy()\n\n cv2.destroyAllWindows()\n\nif __name__ == \"__main__\":\n url = \"http://rpigelsight2.local:8080/?action=stream\"\n april_tag_pose = AprilTagPose(url)\n april_tag_pose.start()\n while True:\n if april_tag_pose.img_undist is None:\n continue\n\n cv2.imshow(\"frame\", cv2.resize(april_tag_pose.img_undist, (0, 0), fx=0.5, fy=0.5))\n c = cv2.waitKey(1)\n\n if c == ord(\"q\"):\n break\n april_tag_pose.join()\n" }, { "alpha_fraction": 0.587890625, "alphanum_fraction": 0.6334635615348816, "avg_line_length": 27.98113250732422, "blob_id": "4402b4b9b9766b5f65544d23498a04315ad2aa02", "content_id": "416f31f1b256fc665ad820511a7eb9d42f7d555a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1536, "license_type": "no_license", "max_line_length": 80, "num_lines": 53, "path": "/perception/teleop/record.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import datetime\nimport glob\nimport os\n\nimport cv2\nimport numpy as np\n\n# termination criteria\ncriteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)\n\n# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)\nobjp = np.zeros((6 * 7, 3), np.float32)\nobjp[:, :2] = np.mgrid[0:7, 0:6].T.reshape(-1, 2)\n\n# Arrays to store object points and image points from all the images.\nobjpoints = [] # 3d point in real world space\nimgpoints = [] # 2d points in image plane.\n\ncap = cv2.VideoCapture(0)\ndir_output = \"images/03062021/\"\nos.makedirs(dir_output, exist_ok=True)\n# images = glob.glob(\"*.jpg\")\n\n# for fname in images:\nwhile True:\n ret, img = cap.read()\n raw_img = img.copy()\n\n print(img.shape)\n # img = cv2.imread(fname)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n # Find the chess board corners\n ret, corners = cv2.findChessboardCorners(gray, (7, 6), None)\n\n # If found, add object points, image points (after refining them)\n if ret == True:\n objpoints.append(objp)\n\n corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria)\n imgpoints.append(corners2)\n\n # Draw and display the corners\n img = cv2.drawChessboardCorners(img, (7, 6), corners2, ret)\n cv2.imshow(\"img\", img)\n c = cv2.waitKey(1)\n if c == ord(\"q\"):\n break\n elif c == ord(\"l\"):\n fn_output = datetime.datetime.now().strftime(\"%Y%M%d_%H%m%S%f\")\n cv2.imwrite(os.path.join(dir_output, fn_output) + \".png\", raw_img)\n\ncv2.destroyAllWindows()\n" }, { "alpha_fraction": 0.49179157614707947, "alphanum_fraction": 0.5465143918991089, "avg_line_length": 28.1875, "blob_id": "180532a20f1aee1f085ba1b267f6026127963024", "content_id": "8e24f8d61d69b7cc20f3526ea60e96b52a7f0dc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4203, "license_type": "no_license", "max_line_length": 87, "num_lines": 144, "path": "/perception/fabric/demo_segmentation.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import cv2\nimport pyk4a\nfrom helpers import colorize\nfrom pyk4a import Config, PyK4A\nimport deepdish as dd\nimport numpy as np\nfrom util.segmentation import segmentation\nfrom run import Run\nfrom PIL import Image\nimport skimage.measure\nfrom copy import deepcopy\nimport torchvision.transforms as T\n\nmodel_id = 29\nepoch = 200\npretrained_model = \"/home/gelsight/Code/Fabric/models/%d/chkpnts/%d_epoch%d\" % (\n model_id,\n model_id,\n epoch,\n)\n\n\ndef seg_output(depth, model=None):\n max_d = np.nanmax(depth)\n depth[np.isnan(depth)] = max_d\n # depth_min, depth_max = 400.0, 1100.0\n # depth = (depth - depth_min) / (depth_max - depth_min)\n # depth = depth.clip(0.0, 1.0)\n\n img_depth = Image.fromarray(depth)\n transform = T.Compose([T.ToTensor()])\n img_depth = transform(img_depth)\n img_depth = np.array(img_depth[0])\n\n out = model.evaluate(img_depth).squeeze()\n seg_pred = out[:, :, :3]\n\n # prob_pred *= mask\n # seg_pred_th = deepcopy(seg_pred)\n # seg_pred_th[seg_pred_th < 0.8] = 0.0\n\n return seg_pred\n\n\nt1 = Run(model_path=pretrained_model, n_features=3)\n\n\ndef main():\n k4a = PyK4A(\n Config(\n color_resolution=pyk4a.ColorResolution.RES_1080P,\n depth_mode=pyk4a.DepthMode.NFOV_UNBINNED,\n )\n )\n k4a.start()\n\n exp_dict = {-11: 500, -10: 1250, -9: 2500, -8: 8330, -7: 16670, -6: 33330}\n exp_val = -6 # to be changed when running\n k4a.exposure = exp_dict[exp_val]\n\n data = {\"color\": [], \"depth\": []}\n count = 0\n\n sz = 650\n topleft = [300, 255]\n\n # crop_x = [421, 960]\n # crop_y = [505, 897]\n\n bottomright = [topleft[0] + sz, topleft[1] + sz]\n\n while True:\n capture = k4a.get_capture()\n\n if capture.color is not None:\n color = capture.color\n color_small = cv2.resize(color, (0, 0), fx=1, fy=1)\n color_small = color_small[\n topleft[1] : bottomright[1], topleft[0] : bottomright[0]\n ]\n cv2.imshow(\"Color\", color_small)\n\n if capture.transformed_depth is not None:\n depth_transformed = capture.transformed_depth\n depth_transformed_small = cv2.resize(depth_transformed, (0, 0), fx=1, fy=1)\n depth_transformed_small = depth_transformed_small[\n topleft[1] : bottomright[1], topleft[0] : bottomright[0]\n ]\n # cv2.imshow(\n # \"Transformed Depth\", colorize(depth_transformed_small, (600, 1100))\n # )\n\n mask = segmentation(color_small)\n cv2.imshow(\"mask\", mask)\n\n depth_min = 400.0\n depth_max = 1100.0\n depth_transformed_small_img = (depth_transformed_small - depth_min) / (\n depth_max - depth_min\n )\n depth_transformed_small_img = depth_transformed_small_img.clip(0, 1)\n\n cv2.imshow(\"depth\", depth_transformed_small_img)\n\n depth_transformed_100x100 = skimage.measure.block_reduce(\n depth_transformed_small_img, (4, 4), np.mean\n )\n seg_pred = seg_output(depth_transformed_100x100, model=t1)\n # seg_pred_th = deepcopy(seg_pred)\n # seg_pred_th[seg_pred_th < 0.8] = 0.0\n\n mask = seg_pred.copy()\n # mask = np.zeros(\n # (seg_pred_th.shape[0], seg_pred_th.shape[1], 3), dtype=np.float32\n # )\n # mask[seg_pred_th[:, :, 1] > 0.8] = [0, 1, 1]\n # mask[seg_pred_th[:, :, 2] > 0.8] = [0, 1, 0]\n # mask[seg_pred_th[:, :, 0] > 0.8] = [0, 0, 1]\n\n # mask[seg_pred_th[:, :, 1] > 0.8] = [0, 1, 1]\n # mask[seg_pred_th[:, :, 2] > 0.8] = [0, 1, 0]\n # mask[seg_pred_th[:, :, 0] > 0.8] = [0, 0, 1]\n H, W = mask.shape[0], mask.shape[1]\n mask = (\n mask.reshape((H * W, 3))\n @ np.array([[0, 0, 1.0], [0, 1.0, 1.0], [0, 1.0, 0]])\n ).reshape((H, W, 3))\n # mask = 1.0 / (1 + np.exp(-5 * (mask - 0.8)))\n\n mask = cv2.resize(mask, (sz, sz))\n\n cv2.imshow(\"model\", mask)\n\n key = cv2.waitKey(1)\n if key != -1:\n cv2.destroyAllWindows()\n break\n\n k4a.stop()\n # dd.io.save(\"data/videos/data_prelim.h5\", data)\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.42795446515083313, "alphanum_fraction": 0.49221307039260864, "avg_line_length": 25.07849884033203, "blob_id": "69566c8f41338d8304cfe23ecde5b3c004c35d5c", "content_id": "d689746c1b9c67bfcf6778755a2deeb0b9e01ad9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7641, "license_type": "no_license", "max_line_length": 171, "num_lines": 293, "path": "/following_lqr.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n# -*- coding: utf-8\n\nimport time\nimport cv2\nimport numpy as np\nfrom math import pi, sin, cos, asin, acos\nimport csv\nimport random\nfrom perception.wedge.gelsight.util.Vis3D import ClassVis3D\n\nfrom perception.wedge.gelsight.gelsight_driver import GelSight\nfrom controller.gripper.gripper_control import Gripper_Controller\nfrom controller.ur5.ur_controller import UR_Controller\nfrom controller.mini_robot_arm.RX150_driver import RX150_Driver\n\nimport keyboard\nfrom queue import Queue\nfrom logger_class import Logger\n\nimport collections\n\nurc = UR_Controller()\ngrc = Gripper_Controller()\n\nurc.start()\ngrc.start()\n\n# pose0 = np.array([-0.505-.1693, -0.219, 0.235, -1.129, -1.226, 1.326])\npose0 = np.array([-0.667, -0.196, 0.228, 1.146, -1.237, -1.227])\ngrc.gripper_helper.set_gripper_current_limit(0.6)\n\n\nrx150 = RX150_Driver(port=\"/dev/ttyACM0\", baudrate=1000000)\nrx150.torque(enable=1)\nprint(rx150.readpos())\n\nang = 30\n# ang = -90\n\ndef rx_move(g_open):\n values = [2048, 2549, 1110, 1400, 3072, g_open]\n x = 320\n y = 90\n end_angle = -ang / 180. * np.pi\n rx150.gogo(values, x, y, end_angle, 3072, timestamp=30)\n\ndef rx_regrasp():\n rx_move(890)\n time.sleep(0.5)\n values = [2048, 2549, 1110, 1400, 3072, 890]\n x = 335\n y = 95\n end_angle = -ang / 180. * np.pi\n rx150.gogo(values, x, y, end_angle, x, y, end_angle, 3072, timestamp=30)\n time.sleep(0.5)\n values[-1] = 760\n rx150.gogo(values, x, y, end_angle, x, y, end_angle, 3072, timestamp=30)\n time.sleep(0.5)\n x = 320\n y = 90\n rx150.gogo(values, x, y, end_angle, x, y, end_angle, 3072, timestamp=30)\n time.sleep(0.5)\n\n\n# rx_move(2000)\n\n# sensor_id = \"W03\"\nsensor_id = \"fabric_0\"\n\nIP = \"http://rpigelsightfabric.local\"\n\n# N M fps x0 y0 dx dy\ntracking_setting = (10, 14, 5, 16, 41, 27, 27)\n\n\nn, m = 150, 200\n# Vis3D = ClassVis3D(m, n)\n\n\ndef read_csv(filename=f\"config_{sensor_id}.csv\"):\n rows = []\n\n with open(filename, \"r\") as csvfile:\n csvreader = csv.reader(csvfile)\n header = next(csvreader)\n for row in csvreader:\n rows.append((int(row[1]), int(row[2])))\n\n return rows\n\n\ncorners = tuple(read_csv())\n# corners=((252, 137), (429, 135), (197, 374), (500, 380))\n\n\n\n\n\ndef test_combined():\n\n a = 0.15\n v = 0.08\n urc.movel_wait(pose0, a=a, v=v)\n rx_move(1200)\n time.sleep(2)\n\n gs = GelSight(\n IP=IP,\n corners=corners,\n tracking_setting=tracking_setting,\n output_sz=(400, 300),\n id=\"right\",\n )\n gs.start()\n c = input()\n\n rx_move(760)\n grc.follow_gripper_pos = 1\n time.sleep(0.5)\n\n\n\n depth_queue = []\n\n cnt = 0\n dt = 0.05\n pos_x = 0.5\n\n tm_key = time.time()\n logger = Logger()\n noise_acc = 0.\n flag_record = False\n tm = 0\n start_tm = time.time()\n\n vel = [0.00, 0.008, 0, 0, 0, 0]\n\n while True:\n img = gs.stream.image\n\n\n # get pose image\n pose_img = gs.pc.pose_img\n # pose_img = gs.pc.frame_large\n if pose_img is None:\n continue\n\n # depth_current = gs.pc.depth.max()\n # depth_queue.append(depth_current)\n #\n # if len(depth_queue) > 2:\n # depth_queue = depth_queue[1:]\n #\n # if depth_current == np.max(depth_queue):\n pose = gs.pc.pose\n cv2.imshow(\"pose\", pose_img)\n\n if gs.pc.inContact:\n\n # if cnt % 4 < 2:\n # # grc.follow_gripper_pos = 1\n # rx_move(810)\n # else:\n a = 0.02\n v = 0.02\n\n fixpoint_x = pose0[0]\n fixpoint_y = pose0[1] - 0.133\n pixel_size = 0.2e-3\n ur_pose = urc.getl_rt()\n ur_xy = np.array(ur_pose[:2])\n\n x = 0.1 - pose[0] - 0.5 * (1 - 2*pose[1])*np.tan(pose[2])\n alpha = np.arctan(ur_xy[0] - fixpoint_x)/(ur_xy[1] - fixpoint_y) * np.cos(np.pi * ang / 180)\n\n print(\"x: \", x, \"; input: \", x*pixel_size)\n\n # K = np.array([6528.5, 0.79235, 2.18017]) #10 degrees\n # K = np.array([7012, 8.865, 6.435]) #30 degrees\n # K = np.array([1383, 3.682, 3.417])\n K = np.array([862689, 42.704, 37.518])\n\n state = np.array([[x*pixel_size],[pose[2]],[alpha]])\n phi = -K.dot(state)\n\n # noise = random.random() * 0.07 - 0.02\n # a = 0.8\n # noise_acc = a * noise_acc + (1 - a) * noise\n # phi += noise_acc\n\n target_ur_dir = phi + alpha\n limit_phi = np.pi/3\n target_ur_dir = max(-limit_phi, min(target_ur_dir, limit_phi))\n if abs(target_ur_dir) == limit_phi:\n print(\"reached phi limit\")\n v_norm = 0.02\n vel = np.array([v_norm * sin(target_ur_dir)*cos(np.pi * ang / 180), v_norm * cos(target_ur_dir), v_norm * sin(target_ur_dir)*sin(np.pi * -ang / 180), 0, 0, 0])\n\n # if x < -0.2:\n # print(\"regrasp\")\n # rx_regrasp()\n\n if ur_pose[0] < -0.7-.1693:\n vel[0] = max(vel[0], 0.)\n print(\"reached x limit\")\n if ur_pose[0] > -0.4-.1693:\n vel[0] = min(vel[0], 0.)\n print(\"reached x limit\")\n if ur_pose[2] < .15:\n vel[2] = 0.\n print(\"reached z limit\")\n if ur_pose[1] > .34:\n print(\"end of workspace\")\n print(\"log saved: \", logger.save_logs())\n gs.pc.inContact = False\n vel[0] = min(vel[0], 0.)\n vel[1] = 0.\n\n\n # print(\"sliding vel \", vel[0], \"posx \", pos_x)\n\n vel = np.array(vel)\n urc.speedl(vel, a=a, t=dt*2)\n\n time.sleep(dt)\n\n else:\n print(\"no pose estimate\")\n print(\"log saved: \", logger.save_logs())\n break\n\n # # get tracking image\n # tracking_img = gs.tc.tracking_img\n # if tracking_img is None:\n # continue\n\n\n # slip_index_realtime = gs.tc.slip_index_realtime\n # print(\"slip_index_realtime\", slip_index_realtime)\n\n\n # cv2.imshow(\"marker\", tracking_img[:, ::-1])\n # cv2.imshow(\"diff\", gs.tc.diff_raw[:, ::-1] / 255)\n\n # if urc.getl_rt()[0] < -.45:\n # break\n\n\n\n # cnt += 1\n\n c = cv2.waitKey(1) & 0xFF\n if c == ord(\"q\"):\n break\n\n ##################################################################\n # Record data\n # 'gelsight_url' : self.gelsight_url,\n # 'fabric_pose' : self.fabric_pose,\n # 'ur_velocity' : self.ur_velocity,\n # 'ur_pose' : self.ur_pose,\n # 'slip_index' : self.slip_index,\n # 'x' : self.x,\n # 'y' : self.x,\n # 'theta' : self.theta,\n # 'phi' : self.phi,\n # 'dt' : self.dt\n\n if gs.pc.inContact:\n # print(\"LOGGING\")\n # logger.gelsight = gs.pc.diff\n # logger.cable_pose = pose\n logger.ur_velocity = vel\n logger.ur_pose = urc.getl_rt()\n\n v = np.array([logger.ur_velocity[0], logger.ur_velocity[1]])\n alpha = asin(v[1] / np.sum(v ** 2) ** 0.5)\n\n logger.x = pose[0]\n logger.y = pose[1]\n logger.theta = pose[2]\n # logger.phi = alpha - logger.theta\n\n logger.dt = time.time() - tm\n tm = time.time()\n\n logger.add()\n ##################################################################\n\n\nif __name__ == \"__main__\":\n test_combined()\n" }, { "alpha_fraction": 0.5190140604972839, "alphanum_fraction": 0.5571596026420593, "avg_line_length": 32.80952453613281, "blob_id": "2c9083a36e7d907086f1a2a7d28de6ae24790e0f", "content_id": "2e96d1492b4ce2df253dd4e60d93e8789e8607c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8520, "license_type": "no_license", "max_line_length": 110, "num_lines": 252, "path": "/util/Pose3D_thread.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import open3d as o3d\nfrom open3d import *\nimport numpy.matlib\nimport numpy as np\nfrom numpy.linalg import inv\nfrom scipy.spatial.transform import Rotation as R\nimport copy\nfrom util import ThreadICP\n# from util import ProcessICP\n\n\nclass ClassVisPose3D:\n def __init__(self, n=100, m=200):\n self.n, self.m = n, m\n self.pixmm = 20 # pixel per mm\n # self.contact_z_threshold = 0.03\n self.contact_z_threshold = 0.02\n\n self.load_object()\n self.init_open3D()\n\n target = copy.deepcopy(self.obj)\n self.thread_icp = ThreadICP.ThreadICP(target, nb_worker=20, time_limit=0.005)\n \n def load_cube(self): # object unit: mm\n # self.obj = o3d.io.read_point_cloud(\"objects/cube.ply\")\n self.obj = o3d.io.read_point_cloud(\"objects/cube_20k.ply\")\n # self.obj = o3d.io.read_point_cloud(\"objects/cylinder_20k.ply\")\n self.obj.estimate_normals(fast_normal_computation=False)\n self.obj.paint_uniform_color([0.929, 0.651, 0])\n\n scale = np.eye(4)\n scale[3, 3] = self.m / self.pixmm * 2\n\n self.obj.transform(scale)\n\n r = R.from_euler(\"xyz\", [37, 37, 0], degrees=True)\n trans = np.eye(4)\n trans[:3, :3] = r.as_matrix()\n trans[:3, 3] = [-0.0, -0.1, -1.2]\n trans[:3, 3] /= 2\n\n self.obj_id = \"cube\"\n\n self.obj_temp = copy.deepcopy(self.obj)\n self.obj_temp.transform(trans)\n self.trans = inv(trans)\n self.trans0 = self.trans.copy()\n\n def load_cylinder(self): # object unit: mm\n # self.obj = o3d.io.read_point_cloud(\"objects/cube.ply\")\n # self.obj = o3d.io.read_point_cloud(\"objects/cube_20k.ply\")\n self.obj = o3d.io.read_point_cloud(\"objects/cylinder_20k.ply\")\n self.obj.estimate_normals(fast_normal_computation=False)\n self.obj.paint_uniform_color([0.929, 0.651, 0])\n\n scale = np.eye(4)\n scale[3, 3] = self.m / self.pixmm / 1.5\n\n self.obj.transform(scale)\n\n r = R.from_euler(\"xyz\", [0, 0, 0], degrees=True)\n trans = np.eye(4)\n trans[:3, :3] = r.as_matrix()\n trans[:3, 3] = [-0.0, -0.1, -1.2]\n trans[:3, 3] /= 2\n\n self.obj_id = \"cylinder\"\n\n self.obj_temp = copy.deepcopy(self.obj)\n self.obj_temp.transform(trans)\n self.trans = inv(trans)\n self.trans0 = self.trans.copy()\n\n def load_sphere(self): # object unit: mm\n self.obj = o3d.io.read_point_cloud(\"objects/sphere_2k.ply\")\n self.obj.estimate_normals(fast_normal_computation=False)\n self.obj.paint_uniform_color([0.929, 0.651, 0])\n\n scale = np.eye(4)\n # diameter: 12.66 mm\n scale[3, 3] = self.m / self.pixmm / 1.26\n\n self.obj.transform(scale)\n\n r = R.from_euler(\"xyz\", [0, 0, 0], degrees=True)\n trans = np.eye(4)\n trans[:3, :3] = r.as_matrix()\n trans[:3, 3] = [-0.0, -0.1, -1.2]\n trans[:3, 3] /= 2\n\n self.obj_id = \"sphere\"\n\n self.obj_temp = copy.deepcopy(self.obj)\n self.obj_temp.transform(trans)\n self.trans = inv(trans)\n self.trans0 = self.trans.copy()\n\n def load_object(self):\n # self.load_cube()\n self.load_cylinder()\n # self.load_sphere()\n\n def init_open3D(self):\n x = np.arange(self.n) - self.n / 2\n y = np.arange(self.m) - self.m / 2\n self.X, self.Y = np.meshgrid(x, y)\n # Z = (X ** 2 + Y ** 2) / 10\n Z = np.sin(self.X)\n\n self.points = np.zeros([self.n * self.m, 3])\n self.points[:, 0] = np.ndarray.flatten(self.X) / self.m\n self.points[:, 1] = np.ndarray.flatten(self.Y) / self.m\n\n self.depth2points(Z)\n # exit(0)\n\n # points = np.random.rand(1,3)\n\n # self.pcd = PointCloud()\n\n self.pcd = o3d.geometry.PointCloud()\n\n self.pcd.points = o3d.utility.Vector3dVector(self.points)\n # self.pcd.colors = Vector3dVector(np.zeros([self.n, self.m, 3]))\n\n self.vis = o3d.visualization.Visualizer()\n self.vis.create_window()\n self.vis.add_geometry(self.pcd)\n\n self.ctr = self.vis.get_view_control()\n self.ctr.change_field_of_view(-20)\n print(\"fov\", self.ctr.get_field_of_view())\n self.ctr.convert_to_pinhole_camera_parameters()\n self.ctr.set_zoom(1)\n self.ctr.rotate(0, 450) # mouse drag in x-axis, y-axis\n self.ctr.rotate(1050, 0) # mouse drag in x-axis, y-axis\n self.vis.update_renderer()\n\n def depth2points(self, Z):\n self.points[:, 2] = np.ndarray.flatten(Z)\n\n def pose_reset(self):\n self.trans = self.trans0.copy()\n\n def icp(self, points):\n\n # contact map from depth\n mask = points[:, 2] > self.contact_z_threshold\n\n source = o3d.geometry.PointCloud()\n source.points = o3d.utility.Vector3dVector(points[mask])\n source.estimate_normals(\n search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.01, max_nn=30)\n )\n\n # target = copy.deepcopy(self.obj)\n\n trans_init = self.trans\n trans_opt = trans_init.copy()\n\n trans_opt = self.thread_icp.estimate(copy.deepcopy(source), trans_init)\n\n # evaluation = o3d.registration.evaluate_registration(\n # source, target, threshold, trans_init\n # )\n # print(evaluation)\n\n # self.trans = reg_p2l.transformation\n self.trans = trans_opt.copy()\n self.obj_temp = copy.deepcopy(self.obj)\n self.obj_temp.transform(inv(self.trans))\n\n def update(self, Z):\n Z = Z / self.m\n\n # points = np.random.rand(60000,3)\n self.depth2points(Z)\n\n points_sparse = self.points.reshape([self.n, self.m, 3])\n points_sparse = points_sparse[::1, ::1]\n points_sparse = points_sparse.reshape([-1, 3])\n\n print(\"Z.max()\", Z.max())\n if Z.max() > self.contact_z_threshold * 1.5:\n self.icp(points_sparse)\n\n dx, dy = np.gradient(Z)\n dx, dy = dx * 300 / 2, dy * 300 / 2\n\n # I = np.array([-10,-1,-1])\n # I = I / np.sum(I**2)**0.5\n # # np_colors = (dy * I[0] + dx * I[1] - I[2]) / (dy ** 2 + dx ** 2 + 1) ** 0.5 * 3 + 0.5\n # np_colors = (dy * I[0] + dx * I[1] - I[2]) / (dy ** 2 + dx ** 2 + 1) ** 0.5\n # print(\"MIN MAX\", np_colors.min(), np_colors.max())\n # np_colors = (np_colors - 0.5) * 20 + 0.5\n # np_colors[np_colors<0] = 0\n # np_colors[np_colors>1] = 1\n\n np_colors = dx + 0.5\n np_colors[np_colors < 0] = 0\n np_colors[np_colors > 1] = 1\n np_colors = np.ndarray.flatten(np_colors)\n colors = np.zeros([self.points.shape[0], 3])\n\n colors = np.zeros([self.points.shape[0], 3])\n\n for _ in range(3):\n colors[:, _] = np_colors\n # print(\"COLORS\", colors)\n\n mask = self.points[:, 2] > self.contact_z_threshold\n obj_np_points = np.asarray(self.obj_temp.points)\n obj_np_colors = np.zeros([obj_np_points.shape[0], 3], dtype=np.float32)\n\n # print(obj_np_colors.shape)\n # print(self.obj_temp.has_normals())\n obj_normals = np.asarray(self.obj_temp.normals)\n print(obj_normals.shape)\n # light_vector = np.array([0, -1, -0.5])\n # light_vector = np.array([1, -2, -0.5])\n light_vector = np.array([0, -1, -0.5])\n light_vector = light_vector / (np.sum(light_vector ** 2)) ** 0.5\n diffusion = 0.6 + 0.5 * np.sum(obj_normals * light_vector, axis=-1)\n\n base_color = [1, 0.9, 0]\n if self.obj_id == \"sphere\":\n base_color = [0.95, 0.95, 0.95]\n if self.obj_id == \"cylinder\":\n base_color = [0.95, 0.95, 0.95]\n\n for c in range(3):\n obj_np_colors[:, c] = diffusion * base_color[c]\n # obj_np_colors[:, 0] = diffusion\n # obj_np_colors[:, 1] = diffusion * 0.9\n\n # self.pcd.points = o3d.utility.Vector3dVector(self.points)\n # self.pcd.colors = o3d.utility.Vector3dVector(colors)\n self.pcd.points = o3d.utility.Vector3dVector(\n np.vstack([self.points, self.obj_temp.points])\n )\n self.pcd.colors = o3d.utility.Vector3dVector(np.vstack([colors, obj_np_colors]))\n\n # mask = points_sparse[:, 2] > 0.03\n # self.pcd.points = o3d.utility.Vector3dVector(np.vstack([points_sparse[mask], self.obj_temp.points]))\n\n try:\n self.vis.update_geometry()\n except:\n self.vis.update_geometry(self.pcd)\n self.vis.poll_events()\n self.vis.update_renderer()\n" }, { "alpha_fraction": 0.45107096433639526, "alphanum_fraction": 0.5035699009895325, "avg_line_length": 28.036584854125977, "blob_id": "56f0aad80802ec7ddc3b9de1564e24b71b46d9d5", "content_id": "04628aeb46e43b073e97d06ecd1d3521944c6cae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2381, "license_type": "no_license", "max_line_length": 90, "num_lines": 82, "path": "/util/helper.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\n\n\ndef draw_circle(img, cx, cy, r):\n cimg = img.copy()\n # draw circle boundary\n cv2.circle(cimg, (cy, cx), r, (255, 255, 255), -1)\n cimg = img * 1.0 - cimg / 6\n cimg = np.clip(cimg, 0, 255).astype(np.uint8)\n # draw the center of the circle\n cv2.circle(cimg, (cy, cx), 2, (0, 0, 255), 3)\n return cimg\n\n\ndef label_circle(img, cx=200, cy=150, r=10):\n # label the circle info: r (radius), cx (center x), cy (center y)\n dx, dy, dr = 1, 1, 1\n while True:\n cimg = draw_circle(img, cx, cy, r)\n cv2.imshow(\"label_circle\", cimg)\n\n c = cv2.waitKey(1)\n if c == ord(\"q\") or c == 27:\n # save\n return cx, cy, r\n elif c == ord(\"w\"):\n # Up\n cx -= dx\n elif c == ord(\"s\"):\n # Down\n cx += dx\n elif c == ord(\"a\"):\n # Left\n cy -= dy\n elif c == ord(\"d\"):\n # Right\n cy += dy\n elif c == ord(\"=\"):\n # Increase radius\n r += dr\n elif c == ord(\"-\"):\n # Decrese radius\n r -= dr\n\n\ndef find_marker(frame, threshold_list=(40, 40, 40)):\n RESCALE = 400.0 / frame.shape[0]\n frame_small = frame\n\n # Blur image to remove noise\n blur = cv2.GaussianBlur(frame_small, (int(63 / RESCALE), int(63 / RESCALE)), 0)\n\n # Subtract the surrounding pixels to magnify difference between markers and background\n diff = blur - frame_small.astype(np.float32)\n\n diff *= 16.0\n diff[diff < 0.0] = 0.0\n diff[diff > 255.0] = 255.0\n diff = cv2.GaussianBlur(diff, (int(31 / RESCALE), int(31 / RESCALE)), 0)\n # cv2.imshow(\"diff_marker\", diff / 255.0)\n\n mask = (\n (diff[:, :, 0] > threshold_list[0])\n & (diff[:, :, 2] > threshold_list[1])\n & (diff[:, :, 1] > threshold_list[2])\n )\n\n # mask = (diff[:, :, 0] > 0) & (diff[:, :, 2] > 0) & (diff[:, :, 1] > 0)\n\n # def sigmoid(x, rng=1.0):\n # return 1.0 / (1 + np.exp(-x * rng))\n\n # soft_mask = np.mean(sigmoid(diff - 30, rng=0.1), axis=-1)\n # cv2.imshow(\"soft_mask\", soft_mask)\n\n mask = cv2.resize(mask.astype(np.uint8), (frame.shape[1], frame.shape[0]))\n # mask = cv2.resize((mask * 255).astype(np.uint8), (frame.shape[1], frame.shape[0]))\n\n # mask = erode(mask, ksize=5)\n # mask = dilate(mask, ksize=5)\n return mask\n" }, { "alpha_fraction": 0.44735240936279297, "alphanum_fraction": 0.5040576457977295, "avg_line_length": 25.571428298950195, "blob_id": "e8598d1ac63de9bb386f841ca54d48bdfcce7e6c", "content_id": "65661acbbba70341948deea8afc3dc34257cf16c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9858, "license_type": "no_license", "max_line_length": 169, "num_lines": 371, "path": "/following_tvlqr.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n# -*- coding: utf-8\n\nimport time\nimport cv2\nimport numpy as np\nfrom math import pi, sin, cos, asin, acos\nimport csv\nimport random\nfrom perception.wedge.gelsight.util.Vis3D import ClassVis3D\n\nfrom perception.wedge.gelsight.gelsight_driver import GelSight\nfrom controller.gripper.gripper_control import Gripper_Controller\nfrom controller.ur5.ur_controller import UR_Controller\nfrom controller.mini_robot_arm.RX150_driver import RX150_Driver\n\nimport GPy\nfrom load_data import loadall\nimport control as ctrl\nimport slycot\n\nimport keyboard\nfrom queue import Queue\nfrom logger_class import Logger\n\nimport collections\n\n\nX, Y = loadall()\n\nN = X.shape[0]\nprint(N)\nidx = list(range(N))\nrandom.seed(0)\nrandom.shuffle(idx)\n\ntrain_idx = idx[:int(N * 0.8)]\ntest_idx = idx[int(N * 0.8):]\nX_train, Y_train = X[train_idx], Y[train_idx]\n\n# kernel1 = GPy.kern.Linear(input_dim=4,ARD=True,initialize=False)\n# m1 = GPy.models.SparseGPRegression(X_train, Y_train[:, 0].reshape(Y_train.shape[0], 1), kernel1, num_inducing=500, initialize=False)\n# m1.update_model(False)\n# m1.initialize_parameter()\n# m1[:] = np.load('./controller/GP/m1_lin_80_500i.npy')\n# m1.update_model(True)\n\nkernel2 = GPy.kern.Exponential(input_dim=4, ARD=True, initialize=False)\nm2 = GPy.models.SparseGPRegression(X_train, Y_train[:, 1].reshape(Y_train.shape[0], 1), kernel2, num_inducing=500, initialize=False)\nm2.update_model(False)\nm2.initialize_parameter()\nm2[:] = np.load('./controller/GP/m2_exp_80_500i.npy')\nm2.update_model(True)\n\nkernel3 = GPy.kern.Exponential(input_dim=4, ARD=True, initialize=False)\nm3 = GPy.models.SparseGPRegression(X_train, Y_train[:, 2].reshape(Y_train.shape[0], 1), kernel3, num_inducing=500, initialize=False)\nm3.update_model(False)\nm3.initialize_parameter()\nm3[:] = np.load('./controller/GP/m3_exp_80_500i.npy')\nm3.update_model(True)\n\n# def tv_linA(x):\n# m = 3\n# model = [m1, m2, m3]\n# A = np.zeros((m, m))\n# for i in range(m):\n# grad = model[i].predictive_gradients(np.array([x]))\n# for j in range(m):\n# A[i][j] = grad[0][0][j]\n# return A\n#\n# def tv_linB(x):\n# m = 3\n# model = [m1, m2, m3]\n# B = np.zeros((m, 1))\n# for i in range(m):\n# grad = model[i].predictive_gradients(np.array([x]))\n# B[i, 0] = grad[0][0][3]\n# return B\n\ndef tv_linA(x):\n m = 3\n model = [m2, m2, m3]\n A = np.zeros((m, m))\n for i in range(1, m):\n grad = model[i].predictive_gradients(np.array([x]))\n for j in range(m):\n A[i][j] = grad[0][0][j]\n A[0][0] = 9.0954e-02\n A[0][1] = 4.2307e-06\n A[0][2] = 4.77888e-06\n return A\n\ndef tv_linB(x):\n m = 3\n model = [m2, m2, m3]\n B = np.zeros((m, 1))\n for i in range(1, m):\n grad = model[i].predictive_gradients(np.array([x]))\n B[i, 0] = grad[0][0][3]\n B[0][0] = -4.700e-07\n return B\n\n\nurc = UR_Controller()\ngrc = Gripper_Controller()\n\nurc.start()\ngrc.start()\n\n# pose0 = np.array([-0.505-.1693, -0.219, 0.235, -1.129, -1.226, 1.326])\npose0 = np.array([-0.667, -0.196, 0.228, 1.146, -1.237, -1.227])\ngrc.gripper_helper.set_gripper_current_limit(0.6)\n\n\nrx150 = RX150_Driver(port=\"/dev/ttyACM0\", baudrate=1000000)\nrx150.torque(enable=1)\nprint(rx150.readpos())\n\ndef rx_move(g_open):\n values = [2048, 2549, 1110, 1400, 3072, g_open]\n x = 320\n y = 90\n end_angle = -30. / 180. * np.pi\n rx150.gogo(values, x, y, end_angle, 3072, timestamp=30)\n\n# rx_move(2000)\n\n# sensor_id = \"W03\"\nsensor_id = \"fabric_0\"\n\nIP = \"http://rpigelsightfabric.local\"\n\n# N M fps x0 y0 dx dy\ntracking_setting = (10, 14, 5, 16, 41, 27, 27)\n\n\nn, m = 150, 200\n# Vis3D = ClassVis3D(m, n)\n\n\ndef read_csv(filename=f\"config_{sensor_id}.csv\"):\n rows = []\n\n with open(filename, \"r\") as csvfile:\n csvreader = csv.reader(csvfile)\n header = next(csvreader)\n for row in csvreader:\n rows.append((int(row[1]), int(row[2])))\n\n return rows\n\n\ncorners = tuple(read_csv())\n# corners=((252, 137), (429, 135), (197, 374), (500, 380))\n\n\n\n\n\ndef test_combined():\n\n a = 0.15\n v = 0.08\n urc.movel_wait(pose0, a=a, v=v)\n rx_move(1200)\n time.sleep(2)\n\n gs = GelSight(\n IP=IP,\n corners=corners,\n tracking_setting=tracking_setting,\n output_sz=(400, 300),\n id=\"right\",\n )\n gs.start()\n c = input()\n\n rx_move(760)\n grc.follow_gripper_pos = 1\n time.sleep(0.5)\n\n\n\n depth_queue = []\n\n cnt = 0\n dt = 0.05\n pos_x = 0.5\n\n tm_key = time.time()\n logger = Logger()\n noise_acc = 0.\n flag_record = False\n tm = 0\n start_tm = time.time()\n\n vel = [0.00, 0.008, 0, 0, 0, 0]\n\n while True:\n img = gs.stream.image\n\n\n # get pose image\n pose_img = gs.pc.pose_img\n # pose_img = gs.pc.frame_large\n if pose_img is None:\n continue\n\n # depth_current = gs.pc.depth.max()\n # depth_queue.append(depth_current)\n #\n # if len(depth_queue) > 2:\n # depth_queue = depth_queue[1:]\n #\n # if depth_current == np.max(depth_queue):\n pose = gs.pc.pose\n cv2.imshow(\"pose\", pose_img)\n\n if gs.pc.inContact:\n\n # if cnt % 4 < 2:\n # # grc.follow_gripper_pos = 1\n # rx_move(810)\n # else:\n a = 0.02\n v = 0.02\n\n\n fixpoint_x = pose0[0]\n fixpoint_y = pose0[1] - 0.133\n pixel_size = 0.2e-3\n ur_pose = urc.getl_rt()\n ur_xy = np.array(ur_pose[:2])\n\n x = 0.1 - pose[0] - 0.5 * (1 - 2*pose[1])*np.tan(pose[2])\n alpha = np.arctan(ur_xy[0] - fixpoint_x)/(ur_xy[1] - fixpoint_y) * np.cos(np.pi * 30 / 180)\n\n # print(\"x: \", x, \"; input: \", x*pixel_size)\n # print(\"theta: \", pose[2] * 180/np.pi)\n\n\n state = np.array([[x*pixel_size],[pose[2]],[alpha]])\n # phi = -K.dot(state)\n\n Q = np.array([[100000.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.1]])\n R = [[0.1]]\n x0 = np.zeros(4)\n x0[0], x0[1], x0[2] = state[0, 0], state[1, 0], state[2, 0]\n A = tv_linA(x0)\n B = tv_linB(x0)\n try:\n K,S,E = ctrl.lqr(A, B, Q, R)\n print(K)\n except:\n print(\"LQR ERROR!!!!\")\n K = np.array([862689, 42.704, 37.518])\n # K = np.array([862689, 42.704, 37.518])\n phi = -K.dot(state)\n print(phi)\n\n # noise = random.random() * 0.07 - 0.02\n # a = 0.8\n # noise_acc = a * noise_acc + (1 - a) * noise\n # phi += noise_acc\n\n target_ur_dir = phi + alpha\n limit_phi = np.pi/3\n target_ur_dir = max(-limit_phi, min(target_ur_dir, limit_phi))\n if abs(target_ur_dir) == limit_phi:\n print(\"reached phi limit\")\n v_norm = 0.01\n vel = np.array([v_norm * sin(target_ur_dir)*cos(np.pi * 30 / 180), v_norm * cos(target_ur_dir), v_norm * sin(target_ur_dir)*sin(np.pi * -30 / 180), 0, 0, 0])\n\n # if x < -0.2:\n # print(\"regrasp\")\n # rx_regrasp()\n\n if ur_pose[0] < -0.7:\n vel[0] = max(vel[0], 0.)\n print(\"reached x limit\")\n if ur_pose[0] > -0.3:\n vel[0] = min(vel[0], 0.)\n print(\"reached x limit\")\n if ur_pose[2] < .08:\n vel[2] = 0.\n print(\"reached z limit\")\n if ur_pose[1] > .34:\n print(\"end of workspace\")\n print(\"log saved: \", logger.save_logs())\n gs.pc.inContact = False\n vel[0] = min(vel[0], 0.)\n vel[1] = 0.\n\n\n # print(\"sliding vel \", vel[0], \"posx \", pos_x)\n\n vel = np.array(vel)\n urc.speedl(vel, a=a, t=dt*7)\n\n time.sleep(dt)\n\n else:\n print(\"no pose estimate\")\n print(\"log saved: \", logger.save_logs())\n break\n\n # # get tracking image\n # tracking_img = gs.tc.tracking_img\n # if tracking_img is None:\n # continue\n\n\n # slip_index_realtime = gs.tc.slip_index_realtime\n # print(\"slip_index_realtime\", slip_index_realtime)\n\n\n # cv2.imshow(\"marker\", tracking_img[:, ::-1])\n # cv2.imshow(\"diff\", gs.tc.diff_raw[:, ::-1] / 255)\n\n # if urc.getl_rt()[0] < -.45:\n # break\n\n\n\n # cnt += 1\n\n c = cv2.waitKey(1) & 0xFF\n if c == ord(\"q\"):\n break\n\n ##################################################################\n # Record data\n # 'gelsight_url' : self.gelsight_url,\n # 'fabric_pose' : self.fabric_pose,\n # 'ur_velocity' : self.ur_velocity,\n # 'ur_pose' : self.ur_pose,\n # 'slip_index' : self.slip_index,\n # 'x' : self.x,\n # 'y' : self.x,\n # 'theta' : self.theta,\n # 'phi' : self.phi,\n # 'dt' : self.dt\n\n if gs.pc.inContact:\n # print(\"LOGGING\")\n # logger.gelsight = gs.pc.diff\n # logger.cable_pose = pose\n logger.ur_velocity = vel\n logger.ur_pose = urc.getl_rt()\n\n v = np.array([logger.ur_velocity[0], logger.ur_velocity[1]])\n alpha = asin(v[1] / np.sum(v ** 2) ** 0.5)\n\n logger.x = pose[0]\n logger.y = pose[1]\n logger.theta = pose[2]\n # logger.phi = alpha - logger.theta\n\n logger.dt = time.time() - tm\n tm = time.time()\n\n logger.add()\n ##################################################################\n\n\nif __name__ == \"__main__\":\n try:\n test_combined()\n finally:\n del gs\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.6114649772644043, "avg_line_length": 25.25, "blob_id": "63fa09cec7d087953b1d91c9af54566e74e1fd33", "content_id": "a8be31e89fa6332712e2c9589947b5f7ca3ff810", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 314, "license_type": "no_license", "max_line_length": 75, "num_lines": 12, "path": "/controller/ur5/example_movel.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import socket\nimport time\n\nHOST = \"10.42.1.121\" # The remote host\nPORT = 30002 # The same port as used by the server\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((HOST, PORT))\ntime.sleep(0.5)\ns.send(\"movel(p[-0.5, -0., 0.35, 0.1, 4.76, 0.09], a=0.01, v=0.01)\" + \"\\n\")\n\ns.close()" }, { "alpha_fraction": 0.5514523983001709, "alphanum_fraction": 0.558207631111145, "avg_line_length": 33.968502044677734, "blob_id": "345bdaab2b38aae1910c3a58274b6e2998041641", "content_id": "8b453a77060c2f750adb858ee0859400290046eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8882, "license_type": "no_license", "max_line_length": 88, "num_lines": 254, "path": "/perception/fabric/train.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\nimport os\nimport sys\nimport json\nimport time\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\nfrom datetime import datetime\nfrom unet import unet\nfrom data_loader import TowelDataset\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torchvision.transforms as T\nfrom torch.optim import lr_scheduler\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\nfrom utils import weights_init, compute_map, compute_iou, compute_auc, preprocessHeatMap\nfrom tensorboardX import SummaryWriter\nfrom PIL import Image\n\n\nclass BaseTrain:\n def __init__(self, cfgs):\n self.cfgs = cfgs\n self.init_dirs()\n self.init_datasets()\n self.init_tboard()\n\n def init_dirs(self):\n runspath = self.cfgs[\"runspath\"]\n self.run_id = str(\n max([int(run_id) for run_id in os.listdir(runspath) if run_id.isdecimal()])\n + 1\n )\n self.model_path = os.path.join(runspath, self.run_id)\n if not os.path.exists(self.model_path):\n os.makedirs(self.model_path)\n with open(os.path.join(self.model_path, \"cfgs.json\"), \"w\") as f:\n json.dump(self.cfgs, f, sort_keys=True, indent=2)\n self.chkpnts_path = os.path.join(self.model_path, \"chkpnts\")\n if not os.path.exists(self.chkpnts_path):\n os.makedirs(self.chkpnts_path)\n print(self.model_path)\n\n def init_datasets(self):\n self.datasize = self.cfgs[\"datasize\"]\n if self.datasize == \"\":\n self.datasize = None\n print(\"self.datasize\", self.datasize)\n train_data = TowelDataset(\n root_dir=self.cfgs[\"datapath\"],\n phase=\"train\",\n use_transform=self.cfgs[\"transform\"],\n datasize=self.datasize,\n )\n self.train_loader = DataLoader(\n train_data, batch_size=self.cfgs[\"batch_size\"], shuffle=True, num_workers=16\n )\n\n if self.datasize != None and self.datasize <= 8:\n return\n val_data = TowelDataset(\n root_dir=self.cfgs[\"datapath\"],\n phase=\"val\",\n use_transform=False,\n datasize=self.datasize,\n )\n self.val_loader = DataLoader(\n val_data, batch_size=self.cfgs[\"batch_size\"], num_workers=16\n )\n\n def init_model(self):\n self.model = unet(n_classes=self.cfgs[\"n_feature\"], in_channels=1)\n self.use_gpu = torch.cuda.is_available()\n\n def init_tboard(self):\n self.score_dir = os.path.join(self.model_path, \"scores\")\n os.mkdir(self.score_dir)\n self.n_class = self.cfgs[\"n_class\"]\n self.iou_scores = np.zeros((self.cfgs[\"epochs\"], self.n_class))\n self.pixel_scores = np.zeros(self.cfgs[\"epochs\"])\n\n train_sum_path = os.path.join(\n self.model_path, \"summaries\", \"train\", self.run_id\n )\n os.makedirs(train_sum_path)\n self.train_writer = SummaryWriter(train_sum_path)\n\n val_sum_path = os.path.join(self.model_path, \"summaries\", \"val\", self.run_id)\n self.val_writer = SummaryWriter(val_sum_path)\n # if self.datasize != None and self.datasize <= 8: return\n # os.makedirs(val_sum_path)\n\n def loss(self, outputs, labels):\n return self.criterion(outputs[:, : self.n_class, :, :], labels)\n\n def tboard(self, writer, names, vals, epoch):\n for i in range(len(names)):\n writer.add_scalar(names[i], vals[i], epoch)\n\n def metrics(self, outputs, labels):\n output = torch.sigmoid(outputs[:, : self.n_class, :, :])\n output = output.data.cpu().numpy()\n pred = output.transpose(0, 2, 3, 1)\n gt = labels.cpu().numpy().transpose(0, 2, 3, 1)\n\n maps = []\n ious = []\n aucs = []\n for g, p in zip(gt, pred):\n maps.append(compute_map(g, p, self.n_class))\n ious.append(compute_iou(g, p, self.n_class))\n aucs.append(compute_auc(g, p, self.n_class))\n return maps, ious, aucs\n\n\nclass TrainSeg(BaseTrain):\n def __init__(self, cfgs):\n super().__init__(cfgs)\n self.init_model()\n\n def init_model(self):\n super().init_model()\n weights_init(self.model)\n if self.use_gpu:\n torch.cuda.device(0)\n self.model = self.model.cuda()\n\n self.criterion = nn.BCEWithLogitsLoss(pos_weight=torch.tensor(20.0).to(\"cuda\"))\n\n self.optimizer = optim.Adam(\n self.model.parameters(),\n lr=self.cfgs[\"lr\"],\n weight_decay=self.cfgs[\"w_decay\"],\n )\n self.scheduler = lr_scheduler.StepLR(\n self.optimizer, step_size=self.cfgs[\"step_size\"], gamma=self.cfgs[\"gamma\"]\n ) # decay LR by a factor of 0.5 every 30 epochs\n\n def get_batch(self, batch):\n inputs = Variable(batch[\"X\"].cuda()) if self.use_gpu else Variable(batch[\"X\"])\n labels = Variable(batch[\"Y\"].cuda()) if self.use_gpu else Variable(batch[\"Y\"])\n return inputs, labels\n\n def train(self):\n ts = time.time()\n for epoch in range(self.cfgs[\"epochs\"]):\n self.model.train()\n self.scheduler.step()\n\n losses = []\n maps, ious, aucs = ([] for i in range(3))\n for iter, batch in enumerate(self.train_loader):\n self.optimizer.zero_grad()\n inputs, labels = self.get_batch(batch)\n outputs = self.model(inputs)\n\n # Compute losses\n loss = self.loss(outputs, labels)\n losses.append(loss.item())\n loss.backward()\n self.optimizer.step()\n\n if iter % 10 == 0:\n print(\"epoch%d, iter%d, loss: %0.5f\" % (epoch, iter, loss))\n\n batch_maps, batch_ious, batch_aucs = self.metrics(outputs, labels)\n maps += batch_maps\n ious += batch_ious\n aucs += batch_aucs\n\n ious = np.nanmean(ious, axis=1)\n pixel_map = np.nanmean(maps)\n mean_auc = np.nanmean(aucs)\n\n # Write to tensorboard\n names = [\"loss\", \"MAP\", \"meanIOU\", \"meanAUC\"]\n values = [np.nanmean(losses), pixel_map, np.nanmean(ious), mean_auc]\n self.tboard(self.train_writer, names, values, epoch)\n print(\"summary writer add train loss: \" + str(np.nanmean(losses)))\n print(\"Finish epoch {}, time elapsed {}\".format(epoch, time.time() - ts))\n\n if epoch % 1 == 0:\n if self.datasize == None or self.datasize > 8:\n self.val(epoch)\n torch.save(\n self.model.state_dict(),\n os.path.join(\n self.chkpnts_path, \"%s_epoch%d\" % (self.run_id, epoch)\n ),\n )\n self.train_writer.close()\n self.val_writer.close()\n\n def val(self, epoch):\n self.model.eval()\n num_batches = len(self.val_loader)\n losses = []\n maps, ious, aucs = ([] for i in range(3))\n for iter, batch in enumerate(self.val_loader):\n inputs, labels = self.get_batch(batch)\n outputs = self.model(inputs)\n\n with torch.no_grad():\n loss = self.loss(outputs, labels)\n losses.append(loss.item())\n\n batch_maps, batch_ious, batch_aucs = self.metrics(outputs, labels)\n maps += batch_maps\n ious += batch_ious\n aucs += batch_aucs\n\n if epoch % 50 == 0 and iter == 0:\n hm = torch.sigmoid(outputs[0, :, :, :])\n self.val_writer.add_image(\"hm_%d\" % epoch, hm, epoch)\n\n # Calculate average\n ious = np.array(ious).T # n_class * val_len\n ious = np.nanmean(ious, axis=1)\n pixel_map = np.nanmean(maps)\n mean_auc = np.nanmean(aucs)\n print(\n \"epoch{}, pix_map: {}, meanAUC: {}, meanIoU: {}, IoUs: {}\".format(\n epoch, pixel_map, mean_auc, np.nanmean(ious), ious\n )\n )\n self.iou_scores[epoch] = ious\n np.save(os.path.join(self.score_dir, \"meanIOU\"), self.iou_scores)\n self.pixel_scores[epoch] = pixel_map\n np.save(os.path.join(self.score_dir, \"PixelMAP\"), self.pixel_scores)\n\n names = [\"loss\", \"MAP\", \"meanIOU\", \"meanAUC\"]\n values = [np.nanmean(losses), pixel_map, np.nanmean(ious), mean_auc]\n self.tboard(self.val_writer, names, values, epoch)\n\n\nif __name__ == \"__main__\":\n torch.manual_seed(1337)\n torch.cuda.manual_seed(1337)\n np.random.seed(1337)\n random.seed(1337)\n\n with open(\"configs/segmentation.json\", \"r\") as f:\n cfgs = json.loads(f.read())\n print(json.dumps(cfgs, sort_keys=True, indent=1))\n\n t = TrainSeg(cfgs)\n t.train()\n" }, { "alpha_fraction": 0.5761589407920837, "alphanum_fraction": 0.5791022777557373, "avg_line_length": 40.181819915771484, "blob_id": "befda0f3b84af79a26dc3b22ed70ce75574415e3", "content_id": "b1476cc7155c979a5c518d1944dde31c58747be4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1359, "license_type": "no_license", "max_line_length": 109, "num_lines": 33, "path": "/controller/gripper/auto_serial.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import serial\nfrom serial.tools import list_ports\n\nclass AutoSerial:\n\n def __init__(self, vendor_id, product_id, serial_number, serial_port=None, baud_rate=None, connect=True):\n self.ser = None\n self.serial_port = serial_port\n self.baud_rate = baud_rate\n self.vendor_id = vendor_id\n self.product_id = product_id\n self.serial_number = serial_number\n self.target_string = \"USB VID:PID=%s:%s\"%(self.vendor_id, self.product_id)\n self.detected_port = None\n\n if self.ser is None:\n self.detected_port = None\n print(\"target: \", self.target_string)\n for port in list(list_ports.comports()):\n print(port[2], self.target_string in port[2])\n\n if self.target_string in port[2]:\n self.detected_port = port[0]\n\n if self.detected_port is None:\n print(\"Automatic serial port connection failed, using custom serial port...\")\n print(\"custom port: \", self.serial_port, self.baud_rate)\n if connect:\n \tself.ser = serial.Serial(self.serial_port, self.baud_rate)\n else:\n print(\"detected port: \", self.detected_port, self.baud_rate)\n if connect:\n \tself.ser = serial.Serial(self.detected_port, self.baud_rate)\n" }, { "alpha_fraction": 0.5228832960128784, "alphanum_fraction": 0.5589244961738586, "avg_line_length": 28.627119064331055, "blob_id": "b8a84efda944abe11196ed9d9e467fcc8314d056", "content_id": "befcd6b9640c6dce0fa2ad753897e7e0d04d6c95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1748, "license_type": "no_license", "max_line_length": 95, "num_lines": 59, "path": "/perception/kinect/kinect_camera.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import cv2\nimport pyk4a\nfrom pyk4a import Config, PyK4A\nimport numpy as np\n\nclass Kinect():\n def __init__(self, cam_intrinsics, dist):\n k4a = PyK4A(\n Config(\n color_resolution=pyk4a.ColorResolution.RES_1080P,\n depth_mode=pyk4a.DepthMode.NFOV_UNBINNED,\n )\n )\n k4a.start()\n\n self.mtx = cam_intrinsics\n self.dist = dist\n\n exp_dict = {-11: 500, -10: 1250, -9: 2500, -8: 8330, -7: 16670, -6: 33330}\n exp_val = -6 # to be changed when running\n k4a.exposure = exp_dict[exp_val]\n\n self.k4a = k4a\n\n def undistort_kinect(self, img):\n h, w = img.shape[:2]\n newcameramtx, roi = cv2.getOptimalNewCameraMatrix(self.mtx, self.dist, (w,h), 1, (w,h))\n\n # undistort\n dst = cv2.undistort(img, self.mtx, self.dist, None, newcameramtx)\n # crop the image\n x, y, w, h = roi\n dst = dst[y:y+h, x:x+w]\n return dst\n\n def get_image(self):\n capture = self.k4a.get_capture()\n color, depth_transformed = None, None\n if capture.color is not None:\n color = capture.color\n color_undist = self.undistort_kinect(color)\n\n if capture.transformed_depth is not None:\n depth_transformed = capture.transformed_depth\n depth_undist = self.undistort_kinect(depth_transformed)\n\n return color_undist, depth_undist\n\nif __name__ == \"__main__\":\n camera = Kinect()\n while True:\n color, depth = camera.get_image()\n if color is None or depth is None:\n continue\n cv2.imshow(\"color\", color)\n cv2.imshow(\"depth\", depth / 1100)\n c = cv2.waitKey(1)\n if c == ord('q'):\n break\n" }, { "alpha_fraction": 0.5786754488945007, "alphanum_fraction": 0.6124941110610962, "avg_line_length": 32.439788818359375, "blob_id": "b1864c930a807e30234ba08bbfbc14fd8af3a79b", "content_id": "caa4a2b434568532793825d75203c5cb333fffe0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6387, "license_type": "no_license", "max_line_length": 127, "num_lines": 191, "path": "/perception/fabric/grasp_selector.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\nimport torch\nimport torchvision.transforms as T\nimport numpy as np\nfrom copy import deepcopy\nimport cv2\nfrom sklearn.neighbors import KDTree\n\ndef processHeatMap(hm, cmap = plt.get_cmap('jet')):\n resize_transform = T.Compose([T.ToPILImage()])\n hm = torch.Tensor(hm)\n hm = np.uint8(cmap(np.array(hm)) * 255)\n return hm\n\n\ndef postprocess(pred, threshold=100):\n \"\"\"\n Runs the depth image through the model.\n Returns the dense prediction of corners, outer edges, inner edges, and a three-channel image with all three.\n \"\"\"\n # pred = np.load('/media/ExtraDrive1/clothfolding/test_data/pred_62_19_01_2020_12:53:16.npy')\n\n corners = processHeatMap(pred[:, :, 0])\n outer_edges = processHeatMap(pred[:, :, 1])\n inner_edges = processHeatMap(pred[:, :, 2])\n\n corners = corners[:,:,0]\n corners[corners<threshold] = 0\n corners[corners>=threshold] = 255\n\n outer_edges = outer_edges[:,:,0]\n outer_edges[outer_edges<threshold] = 0\n outer_edges[outer_edges>=threshold] = 255\n\n inner_edges = inner_edges[:,:,0]\n inner_edges[inner_edges<threshold] = 0\n inner_edges[inner_edges>=threshold] = 255\n\n return corners, outer_edges, inner_edges\n\ndef select_grasp(pred, surface_normal, num_neighbour=100, grasp_target=\"edges\"):\n corners, outer_edges, inner_edges = postprocess(pred)\n\n impred = np.zeros((corners.shape[0], corners.shape[1], 3), dtype=np.uint8)\n impred[:, :, 0] += corners\n impred[:, :, 1] += outer_edges\n impred[:, :, 2] += inner_edges\n\n idxs = np.where(corners == 255)\n corners[:] = 1\n corners[idxs] = 0\n idxs = np.where(outer_edges == 255)\n outer_edges[:] = 1\n outer_edges[idxs] = 0\n idxs = np.where(inner_edges == 255)\n inner_edges[:] = 1\n inner_edges[idxs] = 0\n\n # Choose pixel in pred to grasp\n channel = 1 if grasp_target == 'edges' else 0\n indices = np.where(impred[:, :, channel] == 255) # outer_edge\n if len(indices[0]) == 0:\n print(\"ERROR: NO FEATURE FOUND\")\n return 0, 0, 0, 0, 0\n\n \"\"\"\n Grasp based on confidence\n \"\"\"\n # Filter out ambiguous points\n # impred:[im_height, im_width, 3] -> corner, outer edge, inner edge predictions\n segmentation = deepcopy(impred)\n im_height, im_width, _ = segmentation.shape\n segmentation[np.logical_and(impred[:,:,1]==255, impred[:,:,2]==255),2] = 0\n segmentation[np.logical_and(impred[:,:,1]==255, impred[:,:,2]==255),1] = 0\n\n inner_edges_filt = np.ones((im_height, im_width))\n\n inner_edges_filt[segmentation[:,:,2]==255] = 0\n\n # Get outer-inner edge correspondence\n xx, yy = np.meshgrid([x for x in range(im_width)],\n [y for y in range(im_height)])\n\n print(\"segmentation shape\", segmentation.shape, \"surface_normal shape\", surface_normal.shape)\n if grasp_target == 'edges':\n xx_o = xx[segmentation[:,:,1]==255]\n yy_o = yy[segmentation[:,:,1]==255]\n surface_normal_o_z = surface_normal[:, :, 2][segmentation[:,:,1]==255]\n else:\n xx_o = xx[segmentation[:,:,0]==255]\n yy_o = yy[segmentation[:,:,0]==255]\n surface_normal_o_z = surface_normal[:, :, 2][segmentation[:,:,0]==255]\n\n xx_i = xx[segmentation[:,:,2]==255]\n yy_i = yy[segmentation[:,:,2]==255]\n\n _, lbl = cv2.distanceTransformWithLabels(inner_edges_filt.astype(np.uint8), cv2.DIST_L2, 5, labelType=cv2.DIST_LABEL_PIXEL)\n\n loc = np.where(inner_edges_filt==0)\n xx_inner = loc[1]\n yy_inner = loc[0]\n label_to_loc = [[0,0]]\n\n for j in range(len(yy_inner)):\n label_to_loc.append([yy_inner[j],xx_inner[j]])\n\n label_to_loc = np.array(label_to_loc)\n direction = label_to_loc[lbl]\n # Calculate distance to the closest inner edge point for every pixel in the image\n distance = np.zeros(direction.shape)\n\n distance[:,:,0] = np.abs(direction[:,:,0]-yy)\n distance[:,:,1] = np.abs(direction[:,:,1]-xx)\n\n # Normalize distance vectors\n mag = np.linalg.norm([distance[:,:,0],distance[:,:,1]],axis = 0)+0.00001\n distance[:,:,0] = distance[:,:,0]/mag\n distance[:,:,1] = distance[:,:,1]/mag\n\n # Get distances of outer edges\n distance_o = distance[segmentation[:,:,1]==255,:]\n\n # Get outer edge neighbors of each outer edge point\n num_neighbour = num_neighbour\n\n # For every outer edge point, find its closest K neighbours\n if len(xx_o) < num_neighbour:\n print(\"ERROR: Not enough points found for KD-Tree\")\n return 0, 0, 0, 0, 0\n\n tree = KDTree(np.vstack([xx_o,yy_o]).T, leaf_size=2)\n dist, ind = tree.query(np.vstack([xx_o,yy_o]).T, k=num_neighbour)\n\n xx_neighbours = distance_o[ind][:,:,1]\n yy_neighbours = distance_o[ind][:,:,0]\n xx_var = np.var(xx_neighbours,axis = 1)\n yy_var = np.var(yy_neighbours,axis = 1)\n var = xx_var+yy_var\n var = (var-np.min(var))/(np.max(var)-np.min(var))\n\n # calculate the center of edges/corners\n mask = inner_edges | outer_edges | corners\n idxs = np.where(mask == 1)\n x_center, y_center = np.mean(idxs[0]), np.mean(idxs[1])\n print(\"x_center, y_center\", x_center, y_center)\n\n\n k_var = 1.0\n k_dist_right = 2.\n k_normal_z = 0.5\n dist_right = -(xx_o - x_center) / pred.shape[0]\n cost = k_var * var + k_dist_right * dist_right + k_normal_z * np.abs(surface_normal_o_z)\n\n # Choose min var point\n cost_min = np.min(cost)\n min_idxs = np.where(cost == cost_min)[0]\n print(\"Number of min cost indices: %d\" % len(min_idxs))\n idx = np.random.choice(min_idxs)\n x = xx_o[idx]\n y = yy_o[idx]\n\n\n # predicting angle\n temp, lbl = cv2.distanceTransformWithLabels(inner_edges.astype(np.uint8), cv2.DIST_L2, 5, labelType=cv2.DIST_LABEL_PIXEL)\n loc = np.where(inner_edges==0)\n xx_inner = loc[1]\n yy_inner = loc[0]\n label_to_loc = list(zip(yy_inner, xx_inner))\n label_to_loc.insert(0, (0, 0)) # 1-indexed\n label_to_loc = np.array(label_to_loc)\n direction = label_to_loc[lbl]\n outer_pt = np.array([y, x])\n inner_pt = direction[y, x]\n\n\n v = inner_pt - outer_pt\n magn = np.linalg.norm(v)\n\n if magn == 0:\n error_msg = \"magnitude is zero for %d samples\" % retries\n print(error_msg)\n magn = 1.0\n\n unitv = v / magn\n originv = [0, 1] # [y, x]\n angle = np.arccos(np.dot(unitv, originv))\n\n if v[0] < 0:\n angle = -angle\n\n return outer_pt[0], outer_pt[1], angle, inner_pt[0], inner_pt[1]\n" }, { "alpha_fraction": 0.6186317205429077, "alphanum_fraction": 0.6870450973510742, "avg_line_length": 25.423076629638672, "blob_id": "193d3921131aa4d89e5968b9ef1eaf3a0fc5daa2", "content_id": "11b8b1b11890fe52d055022a34d87f986bb127f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 687, "license_type": "no_license", "max_line_length": 90, "num_lines": 26, "path": "/perception/gelsight/util/processing.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom math import cos, sin, pi\nfrom .fast_poisson import poisson_reconstruct\n\nimport cv2\n\n\n\ndef warp_perspective(img, corners, output_sz=(210, 270)):\n TOPLEFT, TOPRIGHT, BOTTOMLEFT, BOTTOMRIGHT = corners\n\n WARP_W = output_sz[0]\n WARP_H = output_sz[1]\n\n points1=np.float32([TOPLEFT,TOPRIGHT,BOTTOMLEFT,BOTTOMRIGHT])\n points2=np.float32([[0,0],[WARP_W,0],[0,WARP_H],[WARP_W,WARP_H]])\n\n matrix=cv2.getPerspectiveTransform(points1,points2)\n\n result = cv2.warpPerspective(img, matrix, (WARP_W, WARP_H))\n\n return result\n\ndef ini_frame(frame):\n frame_rect = warp_perspective(raw_img, (252, 137), (429, 135), (197, 374), (500, 380))\n return frame\n" }, { "alpha_fraction": 0.48174622654914856, "alphanum_fraction": 0.5149348974227905, "avg_line_length": 29.48249053955078, "blob_id": "ff880c3324872ae157add3560caf3d2eca793d85", "content_id": "40dfee92e813bc9d35f3881681b8bb906c4d6754", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7834, "license_type": "no_license", "max_line_length": 88, "num_lines": 257, "path": "/util/reconstruction.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import os\nimport pickle\nimport random\n\nimport cv2\nimport numpy as np\nfrom numpy import cos, pi, sin\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.tree import DecisionTreeRegressor\nfrom util.fast_poisson import poisson_reconstruct\n\nfrom scipy.interpolate import griddata\nfrom util import helper\n\n\ndef dilate(img, ksize=5):\n kernel = np.ones((ksize, ksize), np.uint8)\n return cv2.dilate(img, kernel, iterations=1)\n\n\ndef erode(img, ksize=5):\n kernel = np.ones((ksize, ksize), np.uint8)\n return cv2.erode(img, kernel, iterations=1)\n\n\ndef interpolate_grad(img, mask):\n # mask = (soft_mask > 0.5).astype(np.uint8) * 255\n # cv2.imshow(\"mask_hard\", mask)\n # pixel around markers\n mask_around = (dilate(mask, ksize=3) > 0) & (mask != 1)\n # mask_around = mask == 0\n mask_around = mask_around.astype(np.uint8)\n cv2.imshow(\"mask_around\", mask_around * 255)\n\n x, y = np.arange(img.shape[0]), np.arange(img.shape[1])\n yy, xx = np.meshgrid(y, x)\n\n # mask_zero = mask == 0\n mask_zero = mask_around == 1\n mask_x = xx[mask_zero]\n mask_y = yy[mask_zero]\n points = np.vstack([mask_x, mask_y]).T\n values = img[mask_x, mask_y]\n markers_points = np.vstack([xx[mask != 0], yy[mask != 0]]).T\n method = \"nearest\"\n # method = \"linear\"\n # method = \"cubic\"\n x_interp = griddata(points, values, markers_points, method=method)\n x_interp[x_interp != x_interp] = 0.0\n ret = img.copy()\n ret[mask != 0] = x_interp\n return ret\n\n\ndef demark(diff, gx, gy):\n cv2.imshow(\"diff_before\", diff / 255.0)\n\n mask = helper.find_marker(diff)\n cv2.imshow(\"mask\", mask * 255.0)\n\n # gx[mask == 1] = 0\n # gy[mask == 1] = 0\n gx = interpolate_grad(gx, mask)\n gy = interpolate_grad(gy, mask)\n\n return gx, gy\n\n\nclass Class_3D:\n def __init__(self, model_fn=\"LUT.pkl\", features_type=\"RGBXY\"):\n self.features_type = features_type\n self.output_dir = \"output/\"\n self.load_lookup_table(model_fn)\n\n def load_lookup_table(self, model_fn):\n self.model = pickle.load(open(model_fn, \"rb\"))\n\n def infer(\n self,\n img,\n resolution=(0, 0),\n save_id=None,\n refine_gxgy=None,\n demark=None,\n display=True,\n reverse_RB=False,\n ):\n if reverse_RB:\n img = img[:, :, ::-1]\n if resolution != (0, 0):\n img = cv2.resize(img, resolution)\n\n if \"G\" not in self.features_type:\n img[:, :, 1] = 127.5\n if \"R\" not in self.features_type:\n img[:, :, 2] = 127.5\n if \"B\" not in self.features_type:\n img[:, :, 0] = 127.5\n\n W, H = img.shape[0], img.shape[1]\n\n X = np.reshape(img, [W * H, 3]) / 255 - 0.5\n\n x = np.arange(W)\n y = np.arange(H)\n yy, xx = np.meshgrid(y, x)\n xx, yy = np.reshape(xx, [W * H, 1]), np.reshape(yy, [W * H, 1])\n xx, yy = xx / W - 0.5, yy / H - 0.5\n\n X_features = [X, xx, yy]\n X = np.hstack(X_features)\n\n Y = self.model.predict(X)\n\n gx = np.reshape(Y[:, 0], [W, H])\n gy = np.reshape(Y[:, 1], [W, H])\n\n if demark is not None:\n gx, gy = demark(img, gx, gy)\n\n gx_raw, gy_raw = gx.copy(), gy.copy()\n\n if refine_gxgy is not None:\n print(\"before: gx.max() gy.max()\", gx.max(), gy.max())\n gy_raw *= 0.0\n gx, gy = refine_gxgy(gx, gy)\n print(\"gx.max() gy.max()\", gx.max(), gy.max())\n\n gx_img = (np.clip(gx / 2 + 0.5, 0, 1) * 255).astype(np.uint8)\n gy_img = (np.clip(gy / 2 + 0.5, 0, 1) * 255).astype(np.uint8)\n\n zeros = np.zeros_like(gx)\n depth = poisson_reconstruct(gx, gy, zeros)\n depth = cv2.resize(depth, (H, W))\n depth_single = poisson_reconstruct(gx_raw, gy_raw, zeros)\n depth_single = cv2.resize(depth_single, (H, W))\n print(depth.max())\n # depth_img = (np.clip(depth*255/15-80, 0, 255)).astype(np.uint8)\n scale = W / 200\n # depth_img = (np.clip(depth * 255 / 12 / scale - 50, 0, 255)).astype(np.uint8)\n # depth_single_img = (\n # np.clip(depth_single * 255 / 12 / scale - 50, 0, 255)\n # ).astype(np.uint8)\n\n depth_img = (np.clip(depth * 255 / 24 / scale + 63, 0, 255)).astype(np.uint8)\n depth_single_img = (\n np.clip(depth_single * 255 / 24 / scale + 63, 0, 255)\n ).astype(np.uint8)\n\n depth_img_heat = cv2.applyColorMap(depth_img, cv2.COLORMAP_JET)\n\n if display:\n pass\n # cv2.imshow(\n # \"img\", np.clip((img - 127.5) * 2 + 127.5, 0, 255).astype(np.uint8)\n # )\n\n cv2.imshow(\"gx\", gx_img)\n cv2.imshow(\"gy\", gy_img)\n\n # cv2.imshow(\"depth_calibrated_heat\", depth_img_heat)\n # cv2.imshow(\"depth_single_img_gray\", depth_single_img)\n # cv2.imshow(\"depth_calibrated_gray\", depth_img)\n\n # depth = img2depth(img)\n # depth_img = (np.clip(depth*255*2.5, 0, 255)).astype(np.uint8)\n # # depth_img = cv2.applyColorMap(depth_img, cv2.COLORMAP_JET)\n\n # img[:, :, 1] = img[:, :, 0]\n # img[:, :, 2] = img[:, :, 0]\n\n # cv2.imshow('depth_est', depth_img)\n if save_id is not None:\n self.save_img(\n raw=img,\n gx_img=gx_img,\n gy_img=gy_img,\n z_gray=depth_img,\n z_heat=depth_img_heat,\n save_id=save_id,\n )\n return depth, gx, gy\n\n def save_img(\n self,\n raw=None,\n gx_img=None,\n gy_img=None,\n z_gray=None,\n z_heat=None,\n combine=True,\n save_id=None,\n ):\n if raw is not None:\n output_fn = os.path.join(self.output_dir, save_id + \"_depth_calibrated.jpg\")\n cv2.imwrite(output_fn, raw)\n\n if gx_img is not None:\n output_fn = os.path.join(self.output_dir, save_id + \"_gx.jpg\")\n cv2.imwrite(output_fn, gx_img)\n\n if gy_img is not None:\n output_fn = os.path.join(self.output_dir, save_id + \"_gy.jpg\")\n cv2.imwrite(output_fn, gy_img)\n\n if z_gray is not None:\n output_fn = os.path.join(self.output_dir, save_id + \"_depth_gray.jpg\")\n cv2.imwrite(output_fn, z_gray)\n\n if z_heat is not None:\n output_fn = os.path.join(self.output_dir, save_id + \"_depth_heat.jpg\")\n cv2.imwrite(output_fn, z_heat)\n\n if combine is True:\n # image sizes\n W, H = raw.shape[0], raw.shape[1]\n interval = 50\n\n # create canvas\n combine_img = (\n np.ones([W * 2 + interval * 2, H * 3 + interval * 2, 3], dtype=np.uint8)\n * 255\n )\n\n # image placement\n xy_list = [\n (0, 0),\n (W + interval, H + interval),\n (0, H + interval),\n (0, (H + interval) * 2),\n (W + interval, (H + interval) * 2),\n ]\n image_list = [raw, gx_img, gy_img, z_gray, z_heat]\n\n # draw to canvas\n for i in range(len(image_list)):\n image = image_list[i]\n x, y = xy_list[i]\n\n # gray to RGB\n if len(image.shape) == 2:\n image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)\n\n print(\"image.shape\", image.shape)\n combine_img[x : x + W, y : y + H] = image\n\n output_fn = os.path.join(self.output_dir, save_id + \"_combine.jpg\")\n cv2.imwrite(output_fn, combine_img)\n\n\nif __name__ == \"__main__\":\n c3d = Class_3D()\n\n img = cv2.imread(\"cali_data/20200930_164410.jpg\")\n c3d.infer(img)\n cv2.waitKey(0)\n" }, { "alpha_fraction": 0.5356349349021912, "alphanum_fraction": 0.5933084487915039, "avg_line_length": 32.048458099365234, "blob_id": "a20be23a07cc9738fcbe04cd0acf7ecf8dec9428", "content_id": "378d6cba69e05cfc2a9bb40421b8922be5e093a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22506, "license_type": "no_license", "max_line_length": 198, "num_lines": 681, "path": "/dual_arm_edge_grasp.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport time\nimport cv2\nfrom controller.ur5.ur_controller import UR_Controller\nfrom controller.mini_robot_arm.RX150_driver import RX150_Driver\nfrom perception.kinect.kinect_camera import Kinect\nfrom scipy.spatial.transform import Rotation as R\nfrom controller.gripper.gripper_control import Gripper_Controller\nfrom scipy.interpolate import griddata\nfrom perception.fabric.util.segmentation import segmentation\nfrom perception.fabric.run import Run\nfrom PIL import Image\nimport skimage.measure\nimport torchvision.transforms as T\nimport os\nfrom perception.kinect.Vis3D import ClassVis3D\nfrom perception.fabric.grasp_selector import select_grasp\n\n# n, m = 650, 650\n# Vis3D = ClassVis3D(m, n)\n\ncam_intrinsics_origin = np.array([\n[917.3927285, 0., 957.21294894],\n[ 0., 918.96234057, 555.32910487],\n[ 0., 0., 1. ]])\ncam_intrinsics = np.array([\n[965.24853516, 0., 950.50838964],\n [ 0., 939.67144775, 554.55567298],\n [ 0., 0., 1. ]]) # New Camera Intrinsic Matrix\ndist = np.array([[ 0.0990126, -0.10306044, 0.00024658, -0.00268176, 0.05763196]])\ncamera = Kinect(cam_intrinsics_origin, dist)\n\ncam_pose = np.loadtxt('real/camera_pose.txt', delimiter=' ')\ncam_depth_scale = np.loadtxt('real/camera_depth_scale.txt', delimiter=' ')\n\n# User options (change me)\n# --------------- Setup options ---------------\nurc = UR_Controller()\nurc.start()\na = 0.2\nv = 0.2\n\nrx150 = RX150_Driver(port=\"/dev/ttyACM0\", baudrate=1000000)\nrx150.torque(enable=1)\nprint(rx150.readpos())\n\ndef rx_move(g_open, x_pos, end_angle=0, timestamp=100):\n values = [1024, 2549, 1110, 1400, 0, g_open]\n x = x_pos\n y = 90\n end_angle = end_angle\n rx150.gogo(values, x, y, end_angle, 0, timestamp=timestamp)\n\n# ---------------------------------------------\n# initialize rx150\nrx_move(1600, 270, timestamp=200)\n# for i in range(100):\n# print(rx150.readpos())\n# time.sleep(0.01)\n# time.sleep(0.5)\n# ---------------------------------------------\n\n# workspace_limits = np.asarray([[0.3, 0.748], [-0.224, 0.224], [-0.255, -0.1]]) # Cols: min max, Rows: x y z (define workspace limits in robot coordinates)\nworkspace_limits = np.asarray([[-0.845, -0.605], [-0.14, 0.2], [0, 0.2]]) # Cols: min max, Rows: x y z (define workspace limits in robot coordinates)\n\n# tool_orientation = [2.22,-2.22,0]\n# tool_orientation = [0., -np.pi/2, 0.] # [0,-2.22,2.22] # [2.22,2.22,0]\nfrom scipy.spatial.transform import Rotation as R\ntool_orientation_euler = [180, 0, 90]\n# tool_orientation_euler = [180, 0, 0]\n# tool_orientation_euler = [180, 0, 180]\ntool_orientation = R.from_euler('xyz', tool_orientation_euler, degrees=True).as_rotvec()\n# tool_orientation = [0., -np.pi, 0.] # [0,-2.22,2.22] # [2.22,2.22,0]\n\n# pose0 = np.array([-0.511, 0.294, 0.237, -0.032, -1.666, 0.138])\npose0 = np.hstack([[-0.505, 0.06, 0.2], tool_orientation])\npose_up = pose0.copy()\npose_transfer = np.array([-0.431, 0.092, 0.232, -2.230, -2.194, -0.019])\n\nurc.movel_wait(pose0, a=a, v=v)\n# ---------------------------------------------\n\n# Start gripper\ngrc = Gripper_Controller()\ngrc.follow_gripper_pos = 0\ngrc.gripper_helper.set_gripper_current_limit(0.3)\ngrc.start()\n\n# grc.follow_gripper_pos = 0.\ntime.sleep(0.5)\n\n# Move robot to home pose\n# robot = Robot(False, None, None, workspace_limits,\n# tcp_host_ip, tcp_port, rtc_host_ip, rtc_port,\n# False, None, None)\n# robot.open_gripper()\n\n# Slow down robot\n# robot.joint_acc = 1.4\n# robot.joint_vel = 1.05\n\n\n\ncrop_x_normal=[300, 950]\ncrop_y_normal=[255, 905]\nsurface_normal = None\n\ndef get_surface_normal(camera_color_img, camera_depth_img, crop_x_normal=[300, 950], crop_y_normal=[255, 905]):\n\n camera_depth_img_crop = camera_depth_img[crop_y_normal[0]:crop_y_normal[1], crop_x_normal[0]:crop_x_normal[1]]\n camera_color_img_crop = camera_color_img[crop_y_normal[0]:crop_y_normal[1], crop_x_normal[0]:crop_x_normal[1]]\n\n # camera_depth_img_crop = cv2.resize(camera_depth_img_crop, (0, 0), fx=0.2, fy=0.2) * 0.2\n # Vis3D.update(camera_depth_img_crop)\n\n x = np.arange(camera_depth_img_crop.shape[0]) + crop_y_normal[0]\n y = np.arange(camera_depth_img_crop.shape[1]) + crop_x_normal[0]\n yy, xx = np.meshgrid(x, y)\n yy = yy.reshape([-1])\n xx = xx.reshape([-1])\n\n cv2.imshow(\"camera_color_img_crop\", camera_color_img_crop)\n cv2.imshow(\"camera_depth_img_crop\", camera_depth_img_crop/1300.)\n\n # camera_depth_img_crop = cv2.GaussianBlur(camera_depth_img_crop, (11, 11), 0)\n\n # transform to robot frame\n zz = (camera_depth_img_crop.T).reshape([-1])\n\n zz = zz * cam_depth_scale\n zz[zz==0] = -1000\n xx = np.multiply(xx-cam_intrinsics[0][2],zz/cam_intrinsics[0][0])\n yy = np.multiply(yy-cam_intrinsics[1][2],zz/cam_intrinsics[1][1])\n xyz_kinect = np.vstack([xx,yy,zz])\n # shape: (3, W*H)\n\n camera2robot = cam_pose\n xyz_robot = np.dot(camera2robot[0:3,0:3],xyz_kinect) + camera2robot[0:3,3:]\n\n # get gradient\n W, H = camera_depth_img_crop.shape[0], camera_depth_img_crop.shape[1]\n xyz_robot_unflatten = xyz_robot.reshape(3, W, H)\n xx_robot = xyz_robot_unflatten[0]\n yy_robot = xyz_robot_unflatten[1]\n zz_robot = xyz_robot_unflatten[2]\n\n gx_x, gy_x = np.gradient(xx_robot)\n gx_y, gy_y = np.gradient(yy_robot)\n gx_z, gy_z = np.gradient(zz_robot)\n # gx_x shape: (W, H)\n\n gx_x_flatten, gy_x_flatten = gx_x.reshape([-1]), gy_x.reshape([-1])\n gx_y_flatten, gy_y_flatten = gx_y.reshape([-1]), gy_y.reshape([-1])\n gx_z_flatten, gy_z_flatten = gx_z.reshape([-1]), gy_z.reshape([-1])\n # gx_x_flatten shape: (W*H)\n\n gx = np.vstack([gx_x_flatten, gx_y_flatten, gx_z_flatten]).T\n gy = np.vstack([gy_x_flatten, gy_y_flatten, gy_z_flatten]).T\n # gx shape: (W*H, 3)\n\n normal = np.cross(gx, gy)\n # normal shape: (W*H, 3)\n\n normal = normal / (np.sum(normal**2, axis=-1, keepdims=True)**0.5 + 1e-12)\n normal = normal.reshape(W, H, 3)\n\n for c in range(3):\n normal[:,:,c] = np.fliplr(np.rot90(normal[:,:,c], k=3))\n\n normal = cv2.GaussianBlur(normal, (21, 21), 0)\n\n # sign = (normal[:,:,2] > 0) * 2 - 1\n # for c in range(3):\n # normal[:,:,c] *= sign\n\n\n # cv2.imshow(\"normal\", normal / 2 + 0.5)\n return normal\n\n\n\n\n\n\nflag_waiting_for_click = False\n\n# Callback function for clicking on OpenCV window\nclick_point_pix = ()\n# camera_color_img, camera_depth_img = robot.get_camera_data()\ncamera_color_img, camera_depth_img = camera.get_image()\n\ndef grasp_xy(x, y):\n # input: x, y in image frame\n # action: UR5 feed the grasp point to rx150\n global camera, robot, click_point_pix, flag_waiting_for_click\n click_point_pix = (x,y)\n\n # Get click point in camera coordinates\n click_z = camera_depth_img[y][x] * cam_depth_scale\n click_x = np.multiply(x-cam_intrinsics[0][2],click_z/cam_intrinsics[0][0])\n click_y = np.multiply(y-cam_intrinsics[1][2],click_z/cam_intrinsics[1][1])\n if click_z == 0:\n flag_waiting_for_click = False\n return False\n click_point = np.asarray([click_x,click_y,click_z])\n click_point.shape = (3,1)\n\n # Convert camera to robot coordinates\n # camera2robot = np.linalg.inv(robot.cam_pose)\n camera2robot = cam_pose\n target_position = np.dot(camera2robot[0:3,0:3],click_point) + camera2robot[0:3,3:]\n\n pose_curr = urc.getl_rt()\n target_position = target_position[0:3,0]\n print(x, y)\n pose_rx150 = [-0.431, -0.063, 0.212]\n\n pose_move = pose_curr.copy()\n pose_move[:3] += pose_rx150[:3] - target_position[:3]\n if pose_move[0] < pose_rx150[0] - 0.2 or pose_move[0] > pose_rx150[0] + 0.2:\n print(\"WARNING: REACHING X WORKSPACE LIMIT!!!!!\")\n flag_waiting_for_click = False\n return False\n if pose_move[1] < -0.004 and pose_move[2] < 0.245:\n print(\"WARNING: REACHING Y/Z WORKSPACE LIMIT!!!!!\")\n pose_move[1] = -0.004\n pose_move[2] = 0.245\n if pose_move[2] > 0.483:\n print(\"Desired Z\", pose_move[2])\n print(\"WARNING: REACHING Z WORKSPACE LIMIT\")\n return False\n\n\n normal_click = surface_normal[y - crop_y_normal[0], x - crop_x_normal[0]]\n\n theta = np.arctan2(normal_click[1], normal_click[0])\n print(\"ROTATING (before clipping)\", theta / np.pi * 180)\n\n if theta > np.pi/2:\n theta -= np.pi\n if theta < -np.pi/2:\n theta += np.pi\n # theta[theta > np.pi/2] -= np.pi\n # theta[theta < -np.pi/2] += np.pi\n # cv2.imshow(\"surface_normal\", surface_normal / 2 + 0.5)\n print(\"ROTATING\", theta / np.pi * 180)\n\n # tool_orientation_euler = [180, 0, 90]\n tool_orientation_rotvec = R.from_rotvec(pose_curr[3:])\n trans = R.from_euler('xyz', [0, 0, -theta / np.pi * 180], degrees=True)\n tool_orientation_rotvec = trans * tool_orientation_rotvec\n # tool_orientation_euler[2] -= theta / np.pi * 180\n tool_orientation = tool_orientation_rotvec.as_rotvec()\n # tool_orientation = R.from_euler('xyz', tool_orientation_euler, degrees=True).as_rotvec()\n\n rx, ry = target_position[0] - pose_curr[0], target_position[1] - pose_curr[1]\n r = (rx**2 + ry**2) ** 0.5\n # dx, dy = r * np.sin(theta), r * (np.cos(theta) - 1)\n\n nxy = np.array([[np.cos(-theta), -np.sin(-theta)], [np.sin(-theta), np.cos(-theta)]]) @ np.array([[rx], [ry]]) + np.array([[pose_curr[0]], [pose_curr[1]]])\n dx, dy = (nxy[0, 0] - target_position[0]), (nxy[1, 0] - target_position[1])\n\n pose_move[0] -= dx\n pose_move[1] -= dy\n\n\n # pose0 = np.array([-0.511, 0.294, 0.237, -0.032, -1.666, 0.138])\n # Go to target Z, and rotate\n pose_rotate = np.hstack([pose_curr[:3], tool_orientation])\n pose_rotate[2] = pose_move[2]\n pose_rotate[0] = pose_move[0]\n urc.movel_wait(pose_rotate, a=a, v=v)\n\n\n\n # pose_curr[2] = pose_move[2]\n # urc.movel_wait(pose_curr, a=a, v=v)\n\n # Go to target X&Y\n pose_rotate[:2] = pose_move[:2]\n urc.movel_wait(pose_rotate, a=a, v=v)\n\n\n\n flag_waiting_for_click = False\n\n return True\n\n\n\n # goal y: -0.063, z: 0.222\n\n\n # target_position = target_position[0:3,0]\n # print(x, y)\n # # target_position[2] -= 0.03\n # if target_position[2] < -0.118:\n # print(\"WARNNING: Reach Z Limit, set to minimal Z\")\n # target_position[2] = -0.118\n # # robot.move_to(target_position, tool_orientation)\n # pose = np.hstack([target_position, tool_orientation])\n # urc.movel_wait(pose, a=a, v=v)\n\ndef mouseclick_callback(event, x, y, flags, param):\n if event == cv2.EVENT_LBUTTONDOWN:\n grasp_xy(x, y)\n\n\n# Show color and depth frames\ncv2.namedWindow('color')\ncv2.setMouseCallback('color', mouseclick_callback)\ncv2.namedWindow('depth')\n\nseq_id = 0\n# sequence = [ord('p'), ord('g'), ord('h'), ord('r'), ord('g')]\nsequence = [ord('p'), ord('g'), ord('h'), ord('w'), ord('g'), ord('d')]\n\n\n\n###################################################\n# Record kinect images\n###################################################\n\n# dir_data = \"data/imgs/0625_10k\"\ndir_data = \"data/imgs/test\"\nos.makedirs(dir_data, exist_ok=True)\ncount = 0\n\nsz = 650\ntopleft = [300, 255]\nbottomright = [topleft[0] + sz, topleft[1] + sz]\n\ndef record_kinect():\n global count\n # get kinect images\n color, depth_transformed = camera.get_image()\n\n # Crop images\n color_small = cv2.resize(color, (0, 0), fx=1, fy=1)\n color_small = color_small[\n topleft[1] : bottomright[1], topleft[0] : bottomright[0]\n ]\n\n depth_transformed_small = cv2.resize(depth_transformed, (0, 0), fx=1, fy=1)\n depth_transformed_small = depth_transformed_small[\n topleft[1] : bottomright[1], topleft[0] : bottomright[0]\n ]\n\n # Normalize depth images\n depth_min = 400.0\n depth_max = 900.0\n depth_transformed_small_img = (\n (depth_transformed_small - depth_min) / (depth_max - depth_min) * 255\n )\n depth_transformed_small_img = depth_transformed_small_img.clip(0, 255)\n\n mask = segmentation(color_small)\n cv2.imshow(\"mask\", mask)\n cv2.imshow(\"color_nn\", color_small)\n cv2.imshow(\"depth_nn\", depth_transformed_small_img / 255.)\n cv2.waitKey(1)\n\n\n cv2.imwrite(f\"{dir_data}/color_{count}.jpg\", color_small)\n cv2.imwrite(\n f\"{dir_data}/depth_{count}.jpg\",\n depth_transformed_small_img.astype(np.uint8),\n )\n np.save(f\"{dir_data}/depth_{count}.npy\", depth_transformed_small)\n\n count += 1\n\n###################################################\n# Demo segmentation\n###################################################\n\nmodel_id = 29\nepoch = 200\npretrained_model = \"/home/gelsight/Code/Fabric/models/%d/chkpnts/%d_epoch%d\" % (\n model_id,\n model_id,\n epoch,\n)\n\ndef seg_output(depth, model=None):\n max_d = np.nanmax(depth)\n depth[np.isnan(depth)] = max_d\n # depth_min, depth_max = 400.0, 1100.0\n # depth = (depth - depth_min) / (depth_max - depth_min)\n # depth = depth.clip(0.0, 1.0)\n\n img_depth = Image.fromarray(depth)\n transform = T.Compose([T.ToTensor()])\n img_depth = transform(img_depth)\n img_depth = np.array(img_depth[0])\n\n out = model.evaluate(img_depth).squeeze()\n seg_pred = out[:, :, :3]\n\n # prob_pred *= mask\n # seg_pred_th = deepcopy(seg_pred)\n # seg_pred_th[seg_pred_th < 0.8] = 0.0\n\n return seg_pred\n\nt1 = Run(model_path=pretrained_model, n_features=3)\n\ndef demo_segmentation():\n # get kinect images\n color, depth_transformed = camera.get_image()\n\n\n surface_normal = get_surface_normal(color, depth_transformed, crop_x_normal=[topleft[1], bottomright[1]], crop_y_normal=[topleft[0], bottomright[0]])\n cv2.imshow(\"surface_normal\", ((surface_normal / 2 + 0.5) * 255).astype(np.uint8))\n cv2.waitKey(1)\n\n # Crop images\n color_small = cv2.resize(color, (0, 0), fx=1, fy=1)\n color_small = color_small[\n topleft[1] : bottomright[1], topleft[0] : bottomright[0]\n ]\n\n depth_transformed_small = cv2.resize(depth_transformed, (0, 0), fx=1, fy=1)\n depth_transformed_small = depth_transformed_small[\n topleft[1] : bottomright[1], topleft[0] : bottomright[0]\n ]\n\n surface_normal_small = surface_normal.copy()\n\n depth_min = 400.0\n depth_max = 1100.0\n depth_transformed_small_img = (depth_transformed_small - depth_min) / (\n depth_max - depth_min\n )\n depth_transformed_small_img = depth_transformed_small_img.clip(0, 1)\n\n cv2.imshow(\"color_crop\", color_small)\n cv2.imshow(\"depth_crop\", depth_transformed_small_img)\n\n depth_transformed_100x100 = skimage.measure.block_reduce(\n depth_transformed_small_img, (4, 4), np.mean\n )\n seg_pred = seg_output(depth_transformed_100x100, model=t1)\n mask = seg_pred.copy()\n H, W = mask.shape[0], mask.shape[1]\n mask = (\n mask.reshape((H * W, 3))\n @ np.array([[0, 0, 1.0], [0, 1.0, 1.0], [0, 1.0, 0]])\n ).reshape((H, W, 3))\n # mask = 1.0 / (1 + np.exp(-5 * (mask - 0.8)))\n\n mask = cv2.resize(mask, (sz, sz))\n cv2.imshow(\"prediction\", mask)\n cv2.waitKey(1)\n\n return color_small, depth_transformed_small, seg_pred, surface_normal_small\n\n\ndef move_record(pose, a, v):\n urc.movel_nowait(pose, a=a, v=v)\n while True:\n # record_kinect()\n demo_segmentation()\n if urc.check_stopped():\n break\n time.sleep(0.05)\n\ndef grasp_policy():\n retry = 30\n\n for i in range(retry):\n color_small, depth_transformed_small, seg_pred, surface_normal_small = demo_segmentation()\n surface_normal_100x100 = cv2.resize(surface_normal_small, (seg_pred.shape[1], seg_pred.shape[0]))\n outer_pt_x, outer_pt_y, angle, inner_pt_x, inner_pt_y = select_grasp(seg_pred, surface_normal_100x100, num_neighbour=100)\n print(outer_pt_x, outer_pt_y, angle, inner_pt_x, inner_pt_y)\n\n #draw grasp point\n K = 3\n pt1 = (outer_pt_y * 4, outer_pt_x * 4)\n pt2 = ((outer_pt_y + (inner_pt_y - outer_pt_y) * K) * 4, (outer_pt_x + (inner_pt_x - outer_pt_x) * K) * 4)\n color = (0, 0, 255)\n grasp_img = color_small.copy()\n if ((inner_pt_y - outer_pt_y)**2 + (inner_pt_x - outer_pt_x) ** 2) ** 0.5 <= 6:\n cv2.arrowedLine(grasp_img, pt1, pt2, color, 3, tipLength=0.2)\n cv2.imshow(\"grasp\", grasp_img)\n cv2.waitKey(1)\n\n\n img_x, img_y = inner_pt_x * 4 + topleft[1], inner_pt_y * 4 + topleft[0]\n\n if outer_pt_x + outer_pt_y + angle + inner_pt_x + inner_pt_y == 0:\n continue\n\n # flag_grasp = grasp_xy(img_y, img_x)\n\n # if flag_grasp:\n # break\n\n\n# while True:\n# grasp_policy()\n\nwhile True:\n # if seq_id % len(sequence) == 0:\n # time.sleep(0.5)\n # camera_color_img, camera_depth_img = robot.get_camera_data()\n camera_color_img, camera_depth_img = camera.get_image()\n bgr_data = camera_color_img# cv2.cvtColor(camera_color_img, cv2.COLOR_RGB2BGR)\n if len(click_point_pix) != 0:\n bgr_data = cv2.circle(bgr_data, click_point_pix, 7, (0,0,255), 2)\n cv2.imshow('color', bgr_data)\n cv2.imshow('depth', camera_depth_img / 1100.)\n\n\n surface_normal = get_surface_normal(camera_color_img, camera_depth_img)\n cv2.imshow(\"surface_normal\", ((surface_normal / 2 + 0.5) * 255).astype(np.uint8))\n\n c = cv2.waitKey(1)\n if c == ord('c'):\n break\n elif c == ord('g'):\n grc.follow_gripper_pos = 1. - grc.follow_gripper_pos\n time.sleep(0.5)\n print(\"GRASP\"*20)\n\n\n crop_x = [421, 960]\n crop_y = [505, 897]\n camera_depth_img_crop = camera_depth_img[crop_y[0]:crop_y[1], crop_x[0]:crop_x[1]]\n camera_color_img_crop = camera_color_img[crop_y[0]:crop_y[1], crop_x[0]:crop_x[1]]\n x = np.arange(camera_depth_img_crop.shape[0]) + crop_y[0]\n y = np.arange(camera_depth_img_crop.shape[1]) + crop_x[0]\n yy, xx = np.meshgrid(x, y)\n yy = yy.reshape([-1])\n xx = xx.reshape([-1])\n\n # cv2.imshow(\"camera_color_img_crop\", camera_color_img_crop)\n cv2.imshow(\"camera_depth_img_crop\", camera_depth_img_crop/1300.)\n\n zz = (camera_depth_img_crop.T).reshape([-1])\n\n # Validation\n # x = 525\n # y = 424\n # id = x * camera_depth_img.shape[0] + y\n # print(\"Desired\", x,y,camera_depth_img[y][x])\n # print(\"Flattened\", xx[id], yy[id], zz[id])\n\n zz = zz * cam_depth_scale\n zz[zz==0] = -1000\n xx = np.multiply(xx-cam_intrinsics[0][2],zz/cam_intrinsics[0][0])\n yy = np.multiply(yy-cam_intrinsics[1][2],zz/cam_intrinsics[1][1])\n xyz_kinect = np.vstack([xx,yy,zz])\n # shape: (3, W*H)\n\n camera2robot = cam_pose\n xyz_robot = np.dot(camera2robot[0:3,0:3],xyz_kinect) + camera2robot[0:3,3:]\n\n # X, Y\n #[-0.64, 0.2]\n #[-0.36, -0.072]\n\n stepsize=0.01\n xlim = [-0.64, -0.36]\n ylim = [-0.07, 0.20]\n\n scale = 100\n x_ws = np.arange(int(xlim[0] * scale), int(xlim[1] * scale))\n y_ws = np.arange(int(ylim[0] * scale), int(ylim[1] * scale))\n xx_ws, yy_ws = np.meshgrid(x_ws, y_ws)\n points = xyz_robot[:2].T\n # shape: (W*H, 2)\n values = xyz_robot[2]\n # shape: (W*H)\n z_ws = griddata(points*scale, values, (xx_ws, yy_ws), method='nearest')\n\n z_ws_blur = cv2.GaussianBlur(z_ws, (5, 5), 0)\n # ind_highest = np.unravel_index(np.argmax(z_ws_blur, axis=None), z_ws_blur.shape)\n # xyz_robot_highest = [ind_highest[1] / scale + xlim[0], ind_highest[0] / scale + ylim[0], z_ws[ind_highest]]\n\n x_high, y_high = np.where(z_ws_blur >= (z_ws_blur.min() + (z_ws_blur.max() - z_ws_blur.min()) *0.8))\n ind = np.random.randint(len(x_high))\n grasp_point = (x_high[ind], y_high[ind])\n\n\n xyz_robot_highest = [grasp_point[1] / scale + xlim[0], grasp_point[0] / scale + ylim[0], z_ws[grasp_point]]\n\n # scale for visualization\n z_min = -0.14\n z_max = 0.0\n z_ws_scaled = (z_ws_blur - z_min) / (z_max - z_min + 1e-6)\n z_ws_scaled = np.dstack([z_ws_scaled, z_ws_scaled, z_ws_scaled])\n z_ws_scaled[grasp_point[0], grasp_point[1], :] = [0, 0, 1]\n z_ws_scaled = np.fliplr(np.rot90(z_ws_scaled, k=1))\n\n cv2.imshow(\"z workspace\", z_ws_scaled)\n\n c = sequence[seq_id % len(sequence)]\n seq_id += 1\n shortcut = cv2.waitKey(1)\n if shortcut == ord('s'):\n grc.follow_gripper_pos = 0\n rx_move(1600, 270)\n flag_waiting_for_click = False\n seq_id = 0\n continue\n if c == ord('w'):\n ##### Hand-pick grasp point\n # if flag_waiting_for_click is True:\n # seq_id -= 1\n # else:\n # rx_move(1600, 420)\n # time.sleep(0.5)\n # rx_move(760, 420)\n grasp_policy()\n rx_move(1600, 420)\n time.sleep(0.5)\n rx_move(760, 420)\n\n # lower ur5 gripper for less acceleration\n pose_tmp = urc.getl_rt()\n if pose_tmp[2] >= 0.32:\n pose_tmp[2] = 0.32\n urc.movel_wait(pose_tmp)\n\n elif c == ord('c'):\n break\n elif c == ord('g'):\n grc.follow_gripper_pos = 1. - grc.follow_gripper_pos\n time.sleep(0.5)\n print(\"GRASP\"*20)\n elif c == ord('h'):\n # tool_orientation_euler = [180, 0, 180]\n # tool_orientation_euler[2] = np.random.randint(180)+90\n # tool_orientation = R.from_euler('xyz', tool_orientation_euler, degrees=True).as_rotvec()\n # random_perturb_rng = 0.05\n # pose_up = np.hstack([[-0.505+np.random.random()*random_perturb_rng - random_perturb_rng / 2, 0.06 + np.random.random()*random_perturb_rng - random_perturb_rng / 2, 0.2], tool_orientation])\n rx_move(1600, 270)\n time.sleep(0.5)\n move_record(pose_transfer, a=a, v=v)\n flag_waiting_for_click = True\n time.sleep(0.5)\n\n elif c == ord('d'):\n # time.sleep(0.5)\n # rx_move(1600, 420)\n time.sleep(0.5)\n rx_move(1600, 380, end_angle=45/180.*np.pi)\n time.sleep(0.5)\n rx_move(1600, 270)\n time.sleep(0.5)\n elif c == ord('p'):\n xyz_robot_highest[2] -= 0.06\n if xyz_robot_highest[2] < -0.118:\n print(\"WARNNING: Reach Z Limit, set to minimal Z\")\n xyz_robot_highest[2] = -0.118\n pose = np.hstack([xyz_robot_highest, tool_orientation])\n move_record(pose, a=a, v=v)\n elif c == ord('r'):\n tool_orientation_euler = [180, 0, 180]\n tool_orientation_euler[2] = np.random.randint(180)+90\n tool_orientation = R.from_euler('xyz', tool_orientation_euler, degrees=True).as_rotvec()\n pose_up = np.hstack([pose_up[:3], tool_orientation])\n move_record(pose_up, a=a, v=v)\n\n record_kinect()\n time.sleep(0.05)\n\n if count > 10000:\n break\n\n\n\n\n\n\n\ncv2.destroyAllWindows()\n" }, { "alpha_fraction": 0.5138730406761169, "alphanum_fraction": 0.5621436834335327, "avg_line_length": 28.561798095703125, "blob_id": "d3e04957cf0347ffb683bf51b8325c3c90bc4968", "content_id": "d769d59e6cf9b071f7b939f7151e447d689580ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2631, "license_type": "no_license", "max_line_length": 87, "num_lines": 89, "path": "/perception/fabric/collect_data.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import cv2\nimport pyk4a\nfrom helpers import colorize\nfrom pyk4a import Config, PyK4A\nimport deepdish as dd\nimport numpy as np\nfrom util.segmentation import segmentation\nimport os\n\n\ndef main():\n k4a = PyK4A(\n Config(\n color_resolution=pyk4a.ColorResolution.RES_1080P,\n depth_mode=pyk4a.DepthMode.NFOV_UNBINNED,\n )\n )\n k4a.start()\n\n exp_dict = {-11: 500, -10: 1250, -9: 2500, -8: 8330, -7: 16670, -6: 33330}\n exp_val = -6 # to be changed when running\n k4a.exposure = exp_dict[exp_val]\n\n data = {\"color\": [], \"depth\": []}\n count = 0\n\n dir_data = \"data/imgs/0625_10k\"\n os.makedirs(dir_data, exist_ok=True)\n\n sz = 600\n topleft = [350, 305]\n bottomright = [topleft[0] + sz, topleft[1] + sz]\n\n while True:\n capture = k4a.get_capture()\n\n if capture.color is not None:\n color = capture.color\n color_small = cv2.resize(color, (0, 0), fx=1, fy=1)\n color_small = color_small[\n topleft[1] : bottomright[1], topleft[0] : bottomright[0]\n ]\n cv2.imshow(\"Color\", color_small)\n\n if capture.transformed_depth is not None:\n depth_transformed = capture.transformed_depth\n depth_transformed_small = cv2.resize(depth_transformed, (0, 0), fx=1, fy=1)\n depth_transformed_small = depth_transformed_small[\n topleft[1] : bottomright[1], topleft[0] : bottomright[0]\n ]\n cv2.imshow(\n \"Transformed Depth\", colorize(depth_transformed_small, (600, 900))\n )\n data[\"color\"].append(color_small)\n data[\"depth\"].append(depth_transformed_small)\n\n if count > 1000:\n break\n if count % 100 == 0:\n print(count)\n count += 1\n\n key = cv2.waitKey(5)\n if key != -1:\n cv2.destroyAllWindows()\n break\n\n mask = segmentation(color_small)\n cv2.imshow(\"mask\", mask)\n\n cv2.imwrite(f\"{dir_data}/color_{count}.jpg\", color_small)\n depth_min = 600.0\n depth_max = 900.0\n depth_transformed_small_img = (\n (depth_transformed_small - depth_min) / (depth_max - depth_min) * 255\n )\n depth_transformed_small_img = depth_transformed_small_img.clip(0, 255)\n cv2.imwrite(\n f\"{dir_data}/depth_{count}.jpg\",\n depth_transformed_small_img.astype(np.uint8),\n )\n np.save(f\"{dir_data}/depth_{count}.npy\", depth_transformed_small)\n\n k4a.stop()\n # dd.io.save(\"data/videos/data_prelim.h5\", data)\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.5011369585990906, "alphanum_fraction": 0.5455658435821533, "avg_line_length": 31.117977142333984, "blob_id": "ec35dcc97ff74b0cad3ca7ebdcc5c5f2eb31d94e", "content_id": "fc74aa54979ac50399247790e4e07aad301a10e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5717, "license_type": "no_license", "max_line_length": 127, "num_lines": 178, "path": "/load_data.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pickle\nimport glob\nimport matplotlib.pyplot as plt\nfrom scipy.ndimage.filters import gaussian_filter1d\n\ndef read_logs(filename):\n logs = pickle.load(open(filename, \"rb\"))\n # gelsight_url = logs[0]['gelsight_url']\n return logs\n\ndef draw(logs):\n ur_xy = []\n # cable_xy = []\n fabric_xs = []\n fabric_ys = []\n thetas = []\n ur_v = []\n x = []\n y = []\n dt = []\n\n for i in range(8, len(logs)):\n log = logs[i]\n ur_pose = log['ur_pose']\n theta = log['theta']\n fabric_x0 = log['x']\n fabric_y0 = log['y']\n ur_velocity = log['ur_velocity']\n t_diff = log['dt']\n\n thetas.append(theta)\n ur_xy.append([ur_pose[0], ur_pose[1]])\n # cable_xy.append(cable_center)\n ur_v.append([ur_velocity[0], ur_velocity[1]])\n dt.append(t_diff)\n fabric_xs.append(fabric_x0)\n fabric_ys.append(fabric_y0)\n\n x.append(ur_pose[0])\n y.append(ur_pose[1])\n\n # plt.plot(x, y, 'x')\n # plt.plot(thetas)\n # plt.figure()\n # plt.plot(x, y, 'x')\n # plt.figure()\n # plt.plot(thetas)\n # plt.show()\n return ur_xy, fabric_xs, fabric_ys, thetas, ur_v, dt\n\ndef remove_end(x):\n return x[1:-1]\n\ndef parse(logs):\n # pixel_size = 0.2e-3\n # pixel_size = 0.1e-3 # caliper + gelsight examples\n pixel_size = 0.2e-3\n ur_xy, fabric_x0, fabric_y0, thetas, ur_v, dt = draw(logs)\n\n # pose0 = np.array([-0.556, -0.227, 0.092])\n # pose0 = np.array([-0.539, -0.226, 0.092])\n pose0 = np.array([-0.505, -0.219, 0.235])\n fixpoint_x = pose0[0] #+ 0.006 #0.0178 # - 15e-3\n fixpoint_y = pose0[1] - 0.12 #0.039 #0.0382 # 0.2 measure distance between 2 grippers at pose0\n fabric_x = 0.05 - np.array(fabric_x0) + 0.5*(1-2*np.array(fabric_y0))*np.tan(thetas)\n alpha = np.arctan((np.array(ur_xy)[:, 0] - fixpoint_x) / (np.array(ur_xy)[:, 1] - fixpoint_y)) * np.cos(np.pi * 30 / 180)\n\n ur_v = np.asarray(ur_v)\n # beta = np.arcsin((ur_v[:,0])/((ur_v[:,0]**2+ur_v[:,1]**2)**0.5)) # use test case to check signs\n beta = np.arcsin((ur_v[:, 0]) * np.cos(np.pi*30/180) / (((ur_v[:, 0]*np.cos(np.pi*30/180)) ** 2 + ur_v[:, 1] ** 2) ** 0.5))\n\n # print(ur_xy[-1][0])\n # print(\"distance followed: \", (((ur_xy[-1][0] - fixpoint_x)**2 + (ur_xy[-1][1] - fixpoint_y)**2)**0.5)/0.00559)\n\n # print(\"UR_V\", ur_v[:,:2], \"BETA\", beta)\n\n # for i in range(5):\n dt.pop(0)\n dt.append(np.mean(dt))\n dt = np.array(dt)\n\n # print(cable_xy.shape)\n # x = gaussian_filter1d(cable_real_xy[:,1], 2)\n x = gaussian_filter1d(fabric_x*pixel_size, 30)\n\n # phi = gaussian_filter1d(alpha - np.array(thetas),2)\n # phi = gaussian_filter1d(beta - alpha,2)\n phi = gaussian_filter1d(beta - np.array(thetas), 2)\n\n # print(\"UR_xy\", cable_real_xy, \"UR_V\", ur_v, \"X\", x)\n # print(\"BETA\", beta, \"ALPHA\", alpha, \"PHI\", phi)\n\n theta = gaussian_filter1d(np.array(thetas),2)\n theta_ = gaussian_filter1d(np.array(thetas),30)\n x_dot = gaussian_filter1d(np.gradient(x)/np.mean(dt), 30)#dt\n theta_dot = gaussian_filter1d(np.gradient(theta_)/np.mean(dt), 30)#/dt\n alpha_dot = gaussian_filter1d(np.gradient(alpha)/np.mean(dt), 30)#/dt\n\n for i in range(5):\n x = remove_end(x)\n theta = remove_end(theta)\n phi = remove_end(phi)\n x_dot = remove_end(x_dot)\n theta_dot = remove_end(theta_dot)\n alpha = remove_end(alpha)\n alpha_dot = remove_end(alpha_dot)\n for i in range(4):\n dt = remove_end(dt)\n\n\n # plt.figure()\n # plt.plot(alpha)\n\n # plt.figure()\n # plt.plot(beta)\n\n\n # plt.figure()\n # ur_xy = np.array(ur_xy)\n # plt.plot(ur_xy[:, 0], ur_xy[:, 1], 'x')\n\n # plt.show()\n\n # print(alpha.shape, x.shape)\n X = np.hstack([np.array([x]).T, np.array([theta]).T, np.array([alpha]).T, np.array([phi]).T])\n Y = np.hstack([np.array([x_dot]).T, np.array([theta_dot]).T, np.array([alpha_dot]).T])\n # X = np.hstack([np.array([x]).T, np.array([phi]).T])\n # print(X.shape, Y.shape)\n\n return X, Y\n\ndef loadall():\n X, Y = np.empty((0,4), np.float32), np.empty((0,3), np.float32)\n # for filename in glob.glob('logs/1908290930/*.p'):\n # for filename in glob.glob('data/logs/20210503/*.p'):\n # for filename in glob.glob('data/logs/20210806_linear/*.p'):\n # for filename in glob.glob('data/logs/20210629_tvlqr/*.p'):\n for filename in glob.glob('data/logs/20210611_30/*.p'):\n # print(filename)\n logs = read_logs(filename)\n x, y = parse(logs)\n X = np.vstack([X, x])\n Y = np.vstack([Y, y])\n for filename in glob.glob('data/logs/20210624_linear/*.p'):\n logs = read_logs(filename)\n x, y = parse(logs)\n X = np.vstack([X, x])\n Y = np.vstack([Y, y])\n for filename in glob.glob('data/logs/20210624_tvlqr/*.p'):\n logs = read_logs(filename)\n x, y = parse(logs)\n X = np.vstack([X, x])\n Y = np.vstack([Y, y])\n # except:\n # print(\"lost one\")\n # break\n # for filename in glob.glob('data/logs/initialtesting/linearGPLQR/*.p'):\n # logs = read_logs(filename)\n # x, y = parse(logs)\n # X = np.vstack([X, x])\n # Y = np.vstack([Y, y])\n # for filename in glob.glob('data/logs/initialtesting/linearLQR/*.p'):\n # logs = read_logs(filename)\n # x, y = parse(logs)\n # X = np.vstack([X, x])\n # Y = np.vstack([Y, y])\n # for filename in glob.glob('data/logs/initialtesting/tvLQR/*.p'):\n # logs = read_logs(filename)\n # x, y = parse(logs)\n # X = np.vstack([X, x])\n # Y = np.vstack([Y, y])\n\n print(X.shape, Y.shape)\n return X, Y\n\nif __name__ == \"__main__\":\n loadall()\n" }, { "alpha_fraction": 0.42627978324890137, "alphanum_fraction": 0.4978768527507782, "avg_line_length": 26.705883026123047, "blob_id": "9deca5259955c588b1f0fdaf55944f8d1cab6bb8", "content_id": "9f952d30e2acf8ddbb51b92de88695313b431ad8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8478, "license_type": "no_license", "max_line_length": 109, "num_lines": 306, "path": "/controller/mini_robot_arm/RX150_driver.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import serial\nimport cv2\nimport numpy as np\nfrom math import sin, cos, pi\nimport time\nimport random\nfrom threading import Thread\n\nimg = np.zeros([300, 300])\n\n\n\n\nclass RX150_IK:\n def __init__(self):\n self.l2 = 150\n self.lT = 50\n self.l3 = 150\n\n self.O = np.array([[0], [0]])\n\n def fk(self, t2, t3):\n l2, lT, l3 = self.l2, self.lT, self.l3\n\n x0 = (150, 0)\n x1 = (x0[0] + l2 * sin(t2), x0[1] + l2 * cos(t2))\n x2 = (x1[0] + lT * cos(t2), x1[1] - lT * sin(t2))\n x3 = (x2[0] + l3 * cos(t2 + t3), x2[1] - l3 * sin(t2 + t3))\n return x3\n\n def get_JaccobianTranspose(self, t2, t3):\n l2, lT, l3 = self.l2, self.lT, self.l3\n\n J = np.array(\n [\n [l2 * cos(t2) - lT * sin(t2) - l3 * sin(t2 + t3), -l3 * sin(t2 + t3)],\n [-l2 * sin(t2) - lT * cos(t2) - l3 * cos(t2 + t3), -l3 * cos(t2 + t3)],\n ]\n )\n return J.T\n\n def ik(self, end_angle, x, y):\n l2, lT, l3 = self.l2, self.lT, self.l3\n O_last = self.O.copy()\n\n angle = end_angle\n l_end = 150.0\n fix_end_angle = -0.3\n # fix_end_angle = 0\n\n x -= l_end * cos(angle)\n y += l_end * sin(angle)\n\n if len(O_last) == 3:\n O = O_last[:-1]\n else:\n O = O_last\n\n alpha = 0.00001\n\n i = 0\n\n while True:\n i += 1\n\n V = self.fk(O[0, 0], O[1, 0])\n JT = self.get_JaccobianTranspose(O[0, 0], O[1, 0])\n\n dV = np.array([[x - V[0]], [y - V[1]]])\n O = O + alpha * JT.dot(dV)\n\n if (dV ** 2).sum() < 1e-4:\n break\n\n O = np.array(\n [O[0].tolist(), O[1].tolist(), [-O[0, 0] - O[1, 0] + angle - fix_end_angle]]\n )\n\n self.O = O.copy()\n return O\n\nclass RX150_Driver:\n def __init__(self, port=\"/dev/tty.usbmodem145301\", baudrate=1000000):\n self.rx150_ik = RX150_IK()\n\n self.ser = serial.Serial(port, baudrate) # open serial port\n print(self.ser.name) # check which port was really used\n\n # initialize initial joint angle for ik\n time.sleep(0.2)\n joints = self.readpos_float()\n\n t2 = (2048 - joints[1]) / 2048. * pi\n t3 = (2048 - joints[2]) / 2048. * pi\n\n self.rx150_ik.O = np.array([[t2], [t3]])\n\n\n # x, y, angle\n self.last_joint = None\n\n def update_pos(self):\n fix_end_angle = -0.3\n\n time.sleep(0.2)\n joints = self.readpos_float()\n\n t2 = (2048 - joints[1]) / 2048. * pi\n t3 = (2048 - joints[2]) / 2048. * pi\n t4 = (2048 - joints[3]) / 2048. * pi\n end_angle = t2 + t3 + t4 + fix_end_angle\n\n x = np.array(self.rx150_ik.fk(t2, t3))\n\n angle = end_angle\n l_end = 150.0\n\n x[0] += l_end * cos(angle)\n x[1] -= l_end * sin(angle)\n\n self.last_joint = (x[0], x[1], end_angle)\n\n def readpos(self):\n self.ser.write(str.encode(\"readpos \\n\"))\n for i in range(1):\n line = self.ser.readline()\n return line\n\n def readpos_float(self):\n line = self.readpos()\n elems = line.decode('utf-8').split(' ')[:-1]\n elems = [float(_) for _ in elems]\n return elems\n\n def torque(self, enable=1):\n self.ser.write(str.encode(\"torque {}\\n\".format(enable)))\n for i in range(6):\n line = self.ser.readline()\n print(line)\n\n\n def send(self, values):\n goal_str = \" \".join([str(_) for _ in values])\n self.ser.write(str.encode((\"goal {}\\n\".format(goal_str)))) # write a string\n\n\n def setxy(self, values, end_angle, x, y):\n O = self.rx150_ik.ik(end_angle, x, y)\n joint = 2048 - O / pi * 2048\n\n values[1] = int(joint[0, 0])\n values[2] = int(joint[1, 0])\n values[3] = int(joint[2, 0])\n\n\n def gogo(self, values, goal_x, goal_y, goal_ang, goal_rot, timestamp=30.0):\n if self.last_joint is None:\n self.update_pos()\n\n # resolve ambiguity for rotation angle\n joints = self.readpos_float()\n values[-2] = joints[4]\n if np.abs(goal_rot - joints[4] + 4096) < np.abs(goal_rot - joints[4]):\n goal_rot += 4096\n elif np.abs(goal_rot - joints[4] - 4096) < np.abs(goal_rot - joints[4]):\n goal_rot -= 4096\n\n x, y, ang = self.last_joint\n dx = (goal_x - x) / timestamp\n dy = (goal_y - y) / timestamp\n da = (goal_ang - ang) / timestamp\n dr = (goal_rot - values[-2]) / timestamp\n\n self.last_joint = (goal_x, goal_y, goal_ang)\n\n for t in range(int(timestamp)):\n x += dx\n y += dy\n ang += da\n values[-2] += dr\n print(\"Goal rot\", goal_rot, \"Cur rot\", values[-2])\n # print(dx, dy, da, dr)\n self.setxy(values, ang, x, y)\n self.send(values)\n time.sleep(0.01)\n\n x = goal_x\n y = goal_y\n ang = goal_ang\n values[-2] = goal_rot\n # print(dx, dy, da, dr)\n self.setxy(values, ang, x, y)\n self.send(values)\n # time.sleep(0.03)\n\n def move(self, goal_x, goal_y, goal_ang, goal_rot, timestamp=30.0):\n # timestamp = 30.\n dx = (goal_x - x) / timestamp\n dy = (goal_y - y) / timestamp\n da = (goal_ang - ang) / timestamp\n dr = (goal_rot - values[-2]) / timestamp\n\n for t in range(int(timestamp)):\n x += dx\n y += dy\n ang += da\n values[-2] += dr\n # print(dx, dy, da, dr)\n self.setxy(values, ang, x, y)\n self.send(values)\n time.sleep(0.01)\n\n x = goal_x\n y = goal_y\n ang = goal_ang\n values[-2] = goal_rot\n # print(dx, dy, da, dr)\n self.setxy(values, ang, x, y)\n self.send(values)\n # time.sleep(0.03)\n\n\nclass RX150_Driver_Thread(Thread):\n def __init__(self, port=\"/dev/ttyACM0\", baudrate=1000000):\n Thread.__init__(self)\n self.rx150 = RX150_Driver(port=port, baudrate=baudrate)\n self.command = None\n self.last_command = None\n self.running = True\n\n def gogo(self, values, goal_x, goal_y, goal_ang, goal_rot, timestamp=30.0):\n self.command = (values, goal_x, goal_y, goal_ang, goal_rot, timestamp)\n\n def follow(self):\n while self.running:\n if self.command is not None and (self.last_command is None or self.command != self.last_command):\n self.last_command = self.command\n print(self.command)\n self.rx150.gogo(*self.command)\n time.sleep(0.01)\n\n\n def run(self):\n self.follow()\n\n\ndef main():\n rx150 = RX150_Driver(port=\"/dev/ttyACM0\", baudrate=1000000)\n print(rx150.readpos())\n\n rx150.torque(enable=1)\n # g_open = 780\n # g_open = 780\n g_open = 780\n values = [1300, 2549, 1110, 1400, 3072+4096, g_open]\n # x = 420\n # x = 380\n x = 280\n y = 120\n end_angle = 0\n # 270 - 420\n inc = 1\n rx150.gogo(values, x, y, end_angle, 3072+4096, timestamp=100)\n\n print(rx150.readpos_float())\n\ndef main_thread():\n rx150_thread = RX150_Driver_Thread(port=\"/dev/ttyACM0\", baudrate=1000000)\n rx150_thread.rx150.torque(enable=1)\n rx150_thread.start()\n\n ################################### 90 degrees\n # g_open = 1200\n # values = [1024, 2549, 1110, 1400, 0, g_open]\n # x = 320\n # y = 30\n # end_angle = 90 / 180. * np.pi # in pi\n # rx150_thread.rx150.gogo(values, x, y, end_angle, 0, timestamp=100)\n\n ################################### 0 degrees\n g_open = 1200\n values = [1024, 2549, 1110, 1400, 0, g_open]\n x = 320\n y = 90\n end_angle = 0 / 180. * np.pi # in pi\n rx150_thread.rx150.gogo(values, x, y, end_angle, 0, timestamp=100)\n\n\n for i in (list(range(30)) + list(range(30, -1, -1)))*1:\n values = [1024, 2549, 1110, 1400, 100, g_open]\n rx150_thread.gogo(values, x, y+i*2, end_angle, 0, timestamp=10)\n time.sleep(0.05)\n\n\n # for theta in (list(range(10)) + list(range(10, -1, -1)))*1:\n # theta = theta / 180. * np.pi\n # values = [1024+theta/np.pi*2048, 2549, 1110, 1400, 0, g_open]\n # rx150_thread.gogo(values, x / np.cos(theta), y, end_angle, theta/np.pi*2048, timestamp=5)\n # time.sleep(0.05)\n\n rx150_thread.running = False\n rx150_thread.join()\n\nif __name__ == \"__main__\":\n # main_thread()\n main()\n" }, { "alpha_fraction": 0.5802469253540039, "alphanum_fraction": 0.5947396755218506, "avg_line_length": 43.09467315673828, "blob_id": "a3f67c83112cb5793252cfd57876bce5977313f0", "content_id": "cdca85d7550ed904b39e766c34c695c952a164c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7452, "license_type": "no_license", "max_line_length": 234, "num_lines": 169, "path": "/controller/gripper/gripper_control.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import os\nimport sys, tty, termios\nfrom simple_pid import PID\n\nimport cv2\nimport numpy as np\nfrom threading import Thread\nimport time\n\nfrom dynamixel_sdk import *\n\n\nclass Gripper_Controller(Thread):\n def __init__(self):\n Thread.__init__(self)\n self.gripper_helper = GripperHelper(DXL_ID=1, min_position=938, max_position=2700)\n self.follow_gripper_pos = 0.\n self.flag_terminate = False\n\n def follow(self):\n # Set the position to self.follow_gripper_pos\n self.gripper_helper.set_gripper_pos(self.follow_gripper_pos)\n\n def run(self):\n while not self.flag_terminate:\n self.follow()\n time.sleep(0.01)\n\nclass GripperHelper(object):\n def __init__(self, DXL_ID, min_position, max_position, DEVICENAME='/dev/ttyUSB0'):\n self.DXL_ID = DXL_ID\n self.min_position = min_position\n self.max_position = max_position\n self.DEVICENAME = DEVICENAME\n\n self.init()\n\n def set_gripper_pos(self, pos):\n # Set gripper position, 0-1\n ADDR_MX_GOAL_POSITION = 116\n CurrentPosition = int(self.min_position + pos * (self.max_position - self.min_position))\n dxl_comm_result, dxl_error = self.packetHandler.write4ByteTxRx(self.portHandler, self.DXL_ID, ADDR_MX_GOAL_POSITION, CurrentPosition)\n\n def set_gripper_current_limit(self, current_limit):\n # Set gripper current limit, 0-1\n ADDR_GOAL_CURRENT = 102\n CURRENT_LIMIT_UPBOUND = 1193\n CurrentTorque = int(CURRENT_LIMIT_UPBOUND * current_limit)\n dxl_comm_result, dxl_error = self.packetHandler.write2ByteTxRx(self.portHandler, self.DXL_ID, ADDR_GOAL_CURRENT, CurrentTorque)\n\n\n def init(self):\n ################################################################################################################\n #setup for the motor\n ADDR_MX_TORQUE_ENABLE = 64 # Control table address is different in Dynamixel model\n ADDR_MX_PRESENT_POSITION = 132\n\n # Protocol version\n PROTOCOL_VERSION = 2.0 # See which protocol version is used in the Dynamixel\n\n # Default setting\n\n BAUDRATE = 57600 # Dynamixel default baudrate : 57600\n # DEVICENAME = '/dev/tty.usbserial-FT2N061F' # Check which port is being used on your controller\n # ex) Windows: \"COM1\" Linux: \"/dev/ttyUSB0\" Mac: \"/dev/tty.usbserial-*\"\n DEVICENAME = self.DEVICENAME # Check which port is being used on your controller\n # ex)\n\n\n\n TORQUE_ENABLE = 1 # Value for enabling the torque\n TORQUE_DISABLE = 0 # Value for disabling the torque\n DXL_MINIMUM_POSITION_VALUE = self.min_position # Dynamixel will rotate between this value\n DXL_MAXIMUM_POSITION_VALUE = self.max_position # and this value (note that the Dynamixel would not move when the position value is out of movable range. Check e-manual about the range of the Dynamixel you use.)\n DXL_MOVING_STATUS_THRESHOLD = 5\n\n\n DXL_ID = self.DXL_ID\n\n\n # Initialize PortHandler instance\n # Set the port path\n # Get methods and members of PortHandlerLinux or PortHandlerWindows\n portHandler = PortHandler(DEVICENAME)\n self.portHandler = portHandler\n\n # Initialize PacketHandler instance\n # Set the protocol version\n # Get methods and members of Protocol1PacketHandler or Protocol2PacketHandler\n packetHandler = PacketHandler(PROTOCOL_VERSION)\n self.packetHandler = packetHandler\n\n # Open port\n if portHandler.openPort():\n print(\"Succeeded to open the port\")\n else:\n print(\"Failed to open the port\")\n\n\n\n # Set port baudrate\n if portHandler.setBaudRate(BAUDRATE):\n print(\"Succeeded to change the baudrate\")\n else:\n print(\"Failed to change the baudrate\")\n\n # Enable Dynamixel Torque\n dxl_comm_result, dxl_error = packetHandler.write1ByteTxRx(portHandler, DXL_ID, ADDR_MX_TORQUE_ENABLE, TORQUE_DISABLE)\n if dxl_comm_result != COMM_SUCCESS:\n print(\"%s\" % packetHandler.getTxRxResult(dxl_comm_result))\n elif dxl_error != 0:\n print(\"%s\" % packetHandler.getRxPacketError(dxl_error))\n else:\n print(\"Dynamixel has been successfully connected\")\n\n\n # Changing operating mode\n ADDR_OPERATING_MODE= 11\n OP_MODE_POSITION= 5\n dxl_comm_result, dxl_error = packetHandler.write2ByteTxRx(portHandler, DXL_ID, ADDR_OPERATING_MODE, OP_MODE_POSITION)\n\n # set the current limit\n ADDR_CURRENT_LIMIT = 38\n CURRENT_LIMIT_UPBOUND = 1193\n dxl_comm_result, dxl_error = packetHandler.write2ByteTxRx(portHandler, DXL_ID, ADDR_CURRENT_LIMIT, CURRENT_LIMIT_UPBOUND)\n\n #SET THE VELOCITU LIMIT\n ADDR_VELOCITY_LIMIT = 44\n VELOCITY_LIMIT_UPBOUND = 1023\n dxl_comm_result, dxl_error = packetHandler.write2ByteTxRx(portHandler, DXL_ID, ADDR_VELOCITY_LIMIT, VELOCITY_LIMIT_UPBOUND)\n\n #SET THE MAX POSITION LIMIT\n ADDR_MAX_POSITION_LIMIT = 48\n MAX_POSITION_LIMIT_UPBOUND = DXL_MAXIMUM_POSITION_VALUE\n dxl_comm_result, dxl_error = packetHandler.write2ByteTxRx(portHandler, DXL_ID, ADDR_MAX_POSITION_LIMIT, MAX_POSITION_LIMIT_UPBOUND)\n\n #SET THE MIN POSITION LIMIT\n ADDR_MIN_POSITION_LIMIT = 52\n MIN_POSITION_LIMIT_UPBOUND = DXL_MINIMUM_POSITION_VALUE\n dxl_comm_result, dxl_error = packetHandler.write2ByteTxRx(portHandler, DXL_ID, ADDR_MIN_POSITION_LIMIT, MIN_POSITION_LIMIT_UPBOUND)\n\n\n\n ADDR_GOAL_CURRENT = 102\n #GOAL_CURRENT_MINPOSITION = 1\n\n # SET THE GOAL VELOCITY\n ADDR_GOAL_VELOCITY = 104\n GOAL_VELOCITY_MAXPOSITION = 1023\n dxl_comm_result, dxl_error = packetHandler.write2ByteTxRx(portHandler, DXL_ID, ADDR_GOAL_VELOCITY, GOAL_VELOCITY_MAXPOSITION)\n\n\n ADDR_ACCELERATION_PROFILE = 108\n ACCELERATION_ADDRESS_POSITION= 0\n dxl_comm_result, dxl_error = packetHandler.write2ByteTxRx(portHandler, DXL_ID, ADDR_ACCELERATION_PROFILE, ACCELERATION_ADDRESS_POSITION)\n\n ADDR_VELOCITY_PROFILE = 112\n VELOCITY_ADDRESS_POSITION= 0\n dxl_comm_result, dxl_error = packetHandler.write2ByteTxRx(portHandler, DXL_ID, ADDR_VELOCITY_PROFILE, VELOCITY_ADDRESS_POSITION)\n\n\n # Enable Dynamixel Torque\n dxl_comm_result, dxl_error = packetHandler.write1ByteTxRx(portHandler, DXL_ID, ADDR_MX_TORQUE_ENABLE, TORQUE_ENABLE)\n if dxl_comm_result != COMM_SUCCESS:\n print(\"%s\" % packetHandler.getTxRxResult(dxl_comm_result))\n elif dxl_error != 0:\n print(\"%s\" % packetHandler.getRxPacketError(dxl_error))\n else:\n print(\"Dynamixel has been successfully connected\")\n" }, { "alpha_fraction": 0.5509375333786011, "alphanum_fraction": 0.5739416480064392, "avg_line_length": 35.4295768737793, "blob_id": "a45bd4d270f2e698fe4be2a03821781165b717f6", "content_id": "422d9aff48d503db575add1abb3d50be7313c009", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5173, "license_type": "no_license", "max_line_length": 114, "num_lines": 142, "path": "/perception/fabric/utils.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport numpy as np\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport sklearn.metrics\nfrom matplotlib import pyplot as plt\n\ndef normalize(img_depth):\n min_I = img_depth.min()\n max_I = img_depth.max()\n img_depth[img_depth<=min_I] = min_I\n img_depth = (img_depth - min_I) / (max_I - min_I)\n return img_depth\n\ndef compute_map(gt, pred, n_class, average=None):\n \"\"\"\n Compute the multi-label classification accuracy.\n Args:\n gt (np.ndarray): Shape Nxn_class, 0 or 1, 1 if the object i is present in that\n image.\n pred (np.ndarray): Shape Nxn_class, probability of that object in the image\n (output probablitiy).\n Returns:\n MAP (scalar): average precision for all classes\n \"\"\"\n gt = gt.reshape(-1, n_class)\n pred = pred.reshape(-1, n_class)\n AP = []\n for cid in range(n_class):\n gt_cls = gt[:, cid].astype('float32')\n pred_cls = pred[:, cid].astype('float32')\n # As per PhilK. code:\n # https://github.com/philkr/voc-classification/blob/master/src/train_cls.py\n pred_cls -= 1e-5 * gt_cls\n ap = sklearn.metrics.average_precision_score(gt_cls, pred_cls, average=average)\n AP.append(ap)\n return AP\n\ndef compute_iou(gt, pred, n_class):\n '''\n gt, pred -- h * w * n_class\n '''\n thres = 0.6\n ious = []\n for cid in range(n_class):\n pred_inds = pred[:, :, cid].astype('float32') > thres\n target_inds = gt[:, :, cid].astype('bool')\n intersection = pred_inds[target_inds].sum()\n union = pred_inds.sum() + target_inds.sum() - intersection\n if union == 0:\n ious.append(float('nan')) # if there is no ground truth, do not include in evaluation\n else:\n ious.append(float(intersection) / max(union, 1))\n # print(\"cls\", cls, pred_inds.sum(), target_inds.sum(), intersection, float(intersection) / max(union, 1))\n return ious\n\ndef compute_auc(gt, pred, n_class):\n gt = gt.reshape(-1, n_class)\n pred = pred.reshape(-1, n_class)\n AUC = []\n for cid in range(n_class):\n gt_cls = gt[:, cid].astype('float32')\n pred_cls = pred[:, cid].astype('float32')\n\n fpr, tpr, thresholds = sklearn.metrics.roc_curve(gt_cls, pred_cls)\n AUC.append(sklearn.metrics.auc(fpr, tpr))\n # AUC.append(sklearn.metrics.roc_auc_score(gt_cls, pred_cls))\n return AUC\n\ndef preprocessHeatMap(hm, cmap = plt.get_cmap('jet')):\n hm = torch.Tensor(hm)\n hm = np.uint8(cmap(np.array(hm)) * 255).transpose(2, 0, 1)\n return hm\n\ndef print_gradients():\n for m in model.modules():\n if isinstance(m,nn.Conv2d) or isinstance(m,nn.ConvTranspose2d):\n print(m.weight.grad)\n print(m.bias.grad)\n elif isinstance(m,nn.Linear):\n print(m.weight.grad)\n print(m.bias.grad)\n # print(l.weight.grad)\n\ndef weights_init(model):\n for m in model.modules():\n if isinstance(m,nn.Conv2d) or isinstance(m,nn.ConvTranspose2d):\n nn.init.xavier_normal_(m.weight.data)\n # nn.init.kaiming_normal_(m.weight.data)\n m.bias.data.fill_(0)\n elif isinstance(m,nn.Linear):\n m.weight.data.normal_()\n\nclass unetConv2(nn.Module):\n def __init__(self, in_size, out_size, is_batchnorm):\n super(unetConv2, self).__init__()\n\n if is_batchnorm:\n self.conv1 = nn.Sequential(\n nn.Conv2d(in_size, out_size, 3, 1, 1), nn.BatchNorm2d(out_size), nn.ReLU()\n )\n self.conv2 = nn.Sequential(\n nn.Conv2d(out_size, out_size, 3, 1, 1), nn.BatchNorm2d(out_size), nn.ReLU()\n )\n else:\n self.conv1 = nn.Sequential(nn.Conv2d(in_size, out_size, 3, 1, 1), nn.ReLU())\n self.conv2 = nn.Sequential(nn.Conv2d(out_size, out_size, 3, 1, 1), nn.ReLU())\n\n def forward(self, inputs):\n outputs = self.conv1(inputs)\n outputs = self.conv2(outputs)\n return outputs\n\n\nclass unetUp(nn.Module):\n def __init__(self, in_size, out_size, is_deconv):\n super(unetUp, self).__init__()\n self.conv = unetConv2(in_size, out_size, True)\n if is_deconv:\n self.up = nn.ConvTranspose2d(in_size, out_size, kernel_size=2, stride=2)\n else:\n self.up = nn.UpsamplingBilinear2d(scale_factor=2)\n \n def forward(self, inputs1, inputs2):\n outputs2 = self.up(inputs2)\n\n offset = - outputs2.size()[3] + inputs1.size()[3]\n offset2 = - outputs2.size()[2] + inputs1.size()[2]\n if offset % 2:\n if offset2 % 2:\n padding = [offset // 2, offset // 2 + 1, offset2 // 2, offset2 // 2 + 1]\n else:\n padding = [offset // 2, offset // 2 + 1, offset2 // 2, offset2 // 2]\n else:\n if offset2 % 2:\n padding = [offset // 2, offset // 2, offset2 // 2, offset2 // 2 + 1]\n else:\n padding = [offset // 2, offset // 2, offset2 // 2, offset2 // 2 ]\n\n outputs2 = F.pad(outputs2, padding)\n return self.conv(torch.cat([inputs1, outputs2], 1))\n" }, { "alpha_fraction": 0.5241248607635498, "alphanum_fraction": 0.5752128958702087, "avg_line_length": 30.08823585510254, "blob_id": "c067522fa507d5db0718114bb2db19ee49150d23", "content_id": "c687395999f5035ce31b9af5c6917c08c7c09b01", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2114, "license_type": "no_license", "max_line_length": 78, "num_lines": 68, "path": "/realtime_5x5.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import cv2\nimport pyk4a\nfrom helpers import colorize\nfrom pyk4a import Config, PyK4A\nimport numpy as np\n\ncriteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 30, 0.001)\n# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)\nobjp = np.zeros((3*3,3), np.float32)\nobjp[:,:2] = np.mgrid[0:3,0:3].T.reshape(-1,2)\n# Arrays to store object points and image points from all the images.\nobjpoints = [] # 3d point in real world space\nimgpoints = [] # 2d points in image plane.\n\ndef main():\n k4a = PyK4A(\n Config(\n color_resolution=pyk4a.ColorResolution.RES_720P,\n depth_mode=pyk4a.DepthMode.NFOV_UNBINNED,\n )\n )\n k4a.start()\n\n exp_dict = {-11: 500, -10: 1250, -9: 2500, -8: 8330, -7: 16670, -6: 33330}\n exp_val = -7 # to be changed when running\n k4a.exposure = exp_dict[exp_val]\n\n id = 0\n\n while True:\n capture = k4a.get_capture()\n\n if capture.color is not None:\n color = capture.color\n cv2.imshow(\"Color\", color)\n\n if capture.transformed_depth is not None:\n depth_transformed = capture.transformed_depth\n cv2.imshow(\n \"Transformed Depth\", colorize(depth_transformed, (600, 1100))\n )\n\n gray = cv.cvtColor(color, cv.COLOR_BGR2GRAY)\n # Find the chess board corners\n ret, corners = cv.findChessboardCorners(gray, (3,3), None)\n # If found, add object points, image points (after refining them)\n if ret == True:\n objpoints.append(objp)\n corners2 = cv.cornerSubPix(gray,corners, (3,3), (-1,-1), criteria)\n imgpoints.append(corners)\n # Draw and display the corners\n cv.drawChessboardCorners(img, (3,3), corners2, ret)\n cv.imshow('img', img)\n cv.waitKey(1)\n\n key = cv2.waitKey(1)\n if key == ord('s'):\n cv2.imwrite(f\"data/intrinsic_test/color_{id}.png\", color)\n id += 1\n elif key == ord('q'):\n cv2.destroyAllWindows()\n break\n\n k4a.stop()\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.5077639818191528, "alphanum_fraction": 0.5524499416351318, "avg_line_length": 30.329729080200195, "blob_id": "98562d630b68ae991312cf6b9b8133cca1eb896d", "content_id": "64b59c2203dfcd981fb2eb9053afe1ca2a5fd7a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5796, "license_type": "no_license", "max_line_length": 158, "num_lines": 185, "path": "/perception/wedge/gelsight/pose.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n# -*- coding: utf-8\nimport math\nimport numpy as np\nimport socket\nimport time\nfrom math import pi, sin, cos, asin\nfrom .util.streaming import Streaming\nimport cv2\nimport _thread\nfrom threading import Thread\nfrom .util.processing import ini_frame, warp_perspective\nfrom .util.fast_poisson import poisson_reconstruct\nfrom numpy import linalg as LA\nfrom scipy import interpolate\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom .util.reconstruction import Class_3D\nfrom .util.reconstruction import demark\nfrom .util import helper\nimport os\n\ndir_abs = os.path.dirname(os.path.realpath(__file__))\n\nsensor_id = \"Fabric0\"\nmodel_id = \"RGB\"\nmodel_fn = os.path.join(dir_abs, f\"models/LUT_{sensor_id}_{model_id}.pkl\")\nc3d = Class_3D(model_fn=model_fn, features_type=model_id)\n\ndef trim(img):\n img[img<0] = 0\n img[img>255] = 255\n\n\ndef sigmoid(x):\n return (np.exp(x) / (1+np.exp(x)))\n\ndef draw_line(img, theta, x0, y0):\n theta = theta / 180. * np.pi\n img = img.copy()\n rows, cols = img.shape[:2]\n\n center = np.array([x0 * cols, y0 * rows])\n\n d = 1100\n\n start_point = center + (d * np.sin(theta), d * np.cos(theta))\n end_point = center - (d * np.sin(theta), d * np.cos(theta))\n\n start_point = tuple(start_point.astype(np.int))\n end_point = tuple(end_point.astype(np.int))\n\n color = (0, 0, 1)\n thickness = 4\n\n img = cv2.line(img, start_point, end_point, color, thickness)\n return img\n\nclass Pose(Thread):\n def __init__(self, stream, corners, output_sz=(100,130), id='right'):\n Thread.__init__(self)\n self.stream = stream\n\n self.corners = corners\n self.output_sz = output_sz\n self.id = id\n\n self.running = False\n self.pose_img = None\n self.frame_large = None\n\n self.pose = None\n self.mv = None\n self.inContact = True\n\n def __del__(self):\n pass\n\n\n def get_pose(self):\n\n self.running = True\n\n device = torch.device(\"cuda:0\")\n net = Net().to(device)\n fn_nn = os.path.join(dir_abs, \"models/combined_mse_0328.pth\")\n # fn_nn = os.path.join(dir_abs, \"models/combined_0421.pth\")\n # fn_nn = os.path.join(dir_abs, \"models/edge_markers_depth.pth\")\n net.load_state_dict(torch.load(fn_nn, map_location=device))\n\n cnt = 0\n while self.running:\n img = self.stream.image.copy()\n if img is None: continue\n\n # Warp frame\n frame = warp_perspective(img, self.corners, self.output_sz)\n\n # Store first frame\n cnt += 1\n if cnt == 1:\n frame0 = frame.copy()\n # frame0 = cv2.GaussianBlur(frame0,(21,21),0)\n frame0_blur = cv2.GaussianBlur(frame0, (45, 45), 0)\n\n x = np.arange(frame0.shape[1])\n y = np.arange(frame0.shape[0])\n xx, yy = np.meshgrid(x, y)\n\n raw = frame.copy()\n\n diff = (frame * 1.0 - frame0_blur) / 255. + 0.5\n diff_magnified = (frame * 1.0 - frame0_blur) / 255. * 4 + 0.5\n diff_small = cv2.resize(diff, (120, 90))\n depth, gx, gy = c3d.infer(diff_small * 255.0, demark=demark, display=False)\n depth3 = np.dstack([depth] * 3)\n\n self.depth = depth.copy()\n # print(\"max_depth\", depth.max())\n\n Y_pred = net.predict([depth3 * 400/120/10], device)\n y = Y_pred[0]\n theta = np.arctan2(y[2], y[3])\n\n class_probs = torch.softmax(torch.from_numpy(y[5:]), dim=0)\n classification = class_probs.argmax(dim=0)\n\n rendered_img_line = diff_magnified\n\n # diff_small = cv2.resize(diff, (120, 90))\n if classification == 0:\n rendered_img_line = cv2.putText(rendered_img_line, \"No Fabric\", (30,80), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA, False)\n self.pose = (1, 0, 0)\n self.inContact = False\n elif classification == 2:\n rendered_img_line = cv2.putText(rendered_img_line, \"All Fabric\", (30,80), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA, False)\n self.pose = (0, 0.5, 0)\n self.inContact = True\n else:\n rendered_img_line = draw_line(diff_magnified, theta/np.pi*180., y[0], y[1])\n self.pose = (y[0], y[1], theta)\n self.inContact = True\n\n self.pose_img = rendered_img_line\n # self.pose = (y[0], y[1], theta)\n\n def run(self):\n print(\"Run pose estimation\")\n self.get_pose()\n pass\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(3, 6, 5)\n self.conv2 = nn.Conv2d(6, 16, 5)\n self.conv3 = nn.Conv2d(16, 32, 5)\n# self.conv4 = nn.Conv2d(32, 128, 5)\n self.pool = nn.MaxPool2d(2, 2)\n self.fc1 = nn.Linear(32 * 7 * 11, 512)\n# self.fc1 = nn.Linear(128 * 1 * 3, 120)\n self.fc2 = nn.Linear(512, 128)\n self.fc3 = nn.Linear(128, 8)\n\n def forward(self, x):\n x = x.permute(0, 3, 1, 2)\n x = torch.tanh(self.conv1(x))\n x = self.pool(x)\n x = torch.tanh(self.conv2(x))\n x = self.pool(x)\n x = torch.tanh(self.conv3(x))\n x = self.pool(x)\n# x = self.pool(torch.tanh(self.conv4(x)))\n# x = x.permute(0, 2, 3, 1)\n# print(x.size())\n x = x.reshape(-1, 32 * 7 * 11)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n def predict(self, X_test, device):\n with torch.no_grad():\n return self.forward(torch.tensor(X_test, dtype=torch.float32).to(device)).cpu().numpy()\n" }, { "alpha_fraction": 0.6193712949752808, "alphanum_fraction": 0.6261682510375977, "avg_line_length": 30.810810089111328, "blob_id": "727ca484db25ef0c9cd366c60d32479cc00f02ac", "content_id": "8196b661276bd626366ced6eae53151810c25484", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1177, "license_type": "no_license", "max_line_length": 78, "num_lines": 37, "path": "/perception/fabric/run.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import torch\nimport torchvision.transforms as T\nfrom torch.autograd import Variable\nfrom PIL import Image\nfrom .unet import unet\nfrom .utils import normalize\n\nclass Run:\n def __init__(self, model_path, n_features=3):\n self.model_path = model_path\n self.n_features = n_features\n self.load_model()\n\n def load_model(self):\n self.model = unet(n_classes=self.n_features, in_channels=1)\n self.model.load_state_dict(torch.load(self.model_path))\n self.use_gpu = torch.cuda.is_available()\n if self.use_gpu:\n torch.cuda.device(0)\n self.model = self.model.cuda()\n\n def evaluate(self, depth):\n self.model.eval()\n img_depth = Image.fromarray(depth, mode='F')\n\n transform = T.Compose([T.ToTensor()])\n img_depth = transform(img_depth)\n img_depth = normalize(img_depth)\n\n inputs = img_depth.unsqueeze_(0)\n inputs = Variable(inputs.cuda()) if self.use_gpu else Variable(inputs)\n outputs = self.model(inputs)\n\n outputs = torch.sigmoid(outputs)\n output = outputs.data.cpu().numpy()\n pred = output.transpose(0, 2, 3, 1)\n return pred\n" }, { "alpha_fraction": 0.5557077527046204, "alphanum_fraction": 0.6050228476524353, "avg_line_length": 21.121212005615234, "blob_id": "5299d8b6df9ef085c12ba93f62a126c05c0e35de", "content_id": "963da30614c29cd4071c9b1393f8e39243750466", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2190, "license_type": "no_license", "max_line_length": 84, "num_lines": 99, "path": "/perception/fabric-pose/demo_3D_calibrated.py", "repo_name": "nehasunil/deformable_following", "src_encoding": "UTF-8", "text": "import csv\nimport datetime\nimport time\nimport urllib\nimport urllib.request\n\nimport _thread\nimport cv2\nimport numpy as np\nimport util\nfrom util.processing import warp_perspective\nfrom util.reconstruction import Class_3D\nfrom util.streaming import Streaming\nfrom util.Vis3D import ClassVis3D\n\nsensor_id = \"W00\"\n\nstream = urllib.request.urlopen(\"http://rpigelsight.local:8080/?action=stream\")\n\nstream = Streaming(stream)\n_thread.start_new_thread(stream.load_stream, ())\n\n# n, m = 300, 400\nn, m = 150, 200\nVis3D = ClassVis3D(m, n)\n\n\ndef read_csv(filename=f\"config/config_{sensor_id}.csv\"):\n rows = []\n\n with open(filename, \"r\") as csvfile:\n csvreader = csv.reader(csvfile)\n header = next(csvreader)\n for row in csvreader:\n rows.append((int(row[1]), int(row[2])))\n\n return rows\n\n\nTOPLEFT, TOPRIGHT, BOTTOMLEFT, BOTTOMRIGHT = tuple(read_csv())\n\ncnt = 0\nlast_tm = 0\n# n, m = 48, 48\n# n, m = 300, 300\ndiff_thresh = 5\n\ndiff_max = 0\nimage_peak = None\nflag_recording = False\ndirname = \"cali_data_1/\"\n\nmodel_id = \"RGB\"\nmodel_fn = f\"models/LUT_{sensor_id}_{model_id}.pkl\"\nc3d = Class_3D(model_fn=model_fn, features_type=model_id)\n\nwhile True:\n frame = stream.image\n if frame == \"\":\n print(\"waiting for streaming\")\n continue\n\n cnt += 1\n\n im = warp_perspective(frame, TOPLEFT, TOPRIGHT, BOTTOMLEFT, BOTTOMRIGHT) # left\n # im[:, :, 0] = 0.0\n\n im_raw = cv2.resize(im, (400, 300))\n im = cv2.resize(im, (m, n))\n # w = im.shape[0]\n # h = im.shape[1]\n # print(\"W\", w, \"H\", h)\n # im = im[w//2-n:w//2+n, h//2-m:h//2+m]\n # im = im[50:-50:,100:-100]\n # im = cv2.resize(im, (n, m))\n\n if cnt == 1:\n frame0 = im.copy()\n\n diff = ((im * 1.0 - frame0)) / 255.0 + 0.5\n cv2.imshow(\"warped\", cv2.resize((diff - 0.5) * 4 + 0.5, (m, n)))\n\n depth, gx, gy = c3d.infer(diff * 255.0)\n Vis3D.update(depth[::-1])\n\n depth = depth - 0.2\n depth[depth < 0] = 0\n cv2.imshow(\"depth\", depth / 5)\n print(\"total {:.4f} s\".format(time.time() - last_tm))\n last_tm = time.time()\n\n cv2.imshow(\"im_raw\", im_raw)\n\n c = cv2.waitKey(1)\n if c == ord(\"q\"):\n break\n\ncap.release()\ncv2.destroyAllWindows()\n" } ]
51
kyo-kbys/NPG-for-toy-MDP
https://github.com/kyo-kbys/NPG-for-toy-MDP
215163460230f23f8ea87fd99c79486ea9b19962
9bc2288335bb811f5039f9de298d35d473aef6b5
44619a73fa4ea7cced716fab091291df99bb97e2
refs/heads/main
2023-04-15T19:50:52.501032
2021-04-26T13:35:00
2021-04-26T13:35:00
361,760,689
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.49306777119636536, "alphanum_fraction": 0.5258738398551941, "avg_line_length": 23.046947479248047, "blob_id": "c6b601e1682aa2dbc7e962ef6767cd173cc03536", "content_id": "831a294d9ba91204997b2792a0fa08c6193a5a79", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5371, "license_type": "no_license", "max_line_length": 106, "num_lines": 213, "path": "/tests/vanilla_policy_gradient_method.py", "repo_name": "kyo-kbys/NPG-for-toy-MDP", "src_encoding": "UTF-8", "text": "\"\"\"\noverview:\n solve small NOP using natural policy gradint\n\noutput:\n update policy\n\nusage-example:\n python3 natural_polciy_gradient_method.py\n\"\"\"\n\n# import module\nimport numpy as np\nimport copy\nimport matplotlib.pyplot as plt\nimport sys\n\n# parameter of policy\ntheta_choice = np.array([[-5,-5],[-4,-4],[-3,-3],[-2.25,-3.25],[-1.5,-1],[-1.0, -2.5]])\ncolor_list = [\"forestgreen\", \"darkgreen\", \"seagreen\", \"mediumaquamarine\", \"turquoise\", \"darkturquoise\"]\n\n# reward function\nr = np.zeros((2, 2))\nr[0, 0] = 1.0\nr[0, 1] = 0.0\nr[1, 0] = 2.0\nr[1, 1] = 0.0\n\n# policy\npi = np.zeros((2,2))\n\n# anther parameter\nalpha = 0.03\ngamma = 1\nepisode = 20\nepoch = 100000\n\n# 方策パラメータ可視化用のインスタンス\nfig = plt.figure(figsize=(12, 8))\nax = fig.add_subplot(111)\n\n# シグモイド関数\ndef sigmoid(s, theta):\n sigmoid_range = 34.5\n\n if theta[s] <= -sigmoid_range:\n return 1e-15\n if theta[s] >= sigmoid_range:\n return 1.0 - 1e-15\n\n return 1.0 / (1.0 + np.exp(-theta[s]))\n\ndef differential_log_pi(s_t, a_t, theta):\n nabla_theta = np.zeros(2)\n if a_t == 0:\n nabla_theta[s_t] = 1.0 - sigmoid(s_t, theta)\n nabla_theta[(s_t+1)%2] = 0\n else:\n nabla_theta[s_t] = (-1.0) * sigmoid(s_t, theta)\n nabla_theta[(s_t+1)%2] = 0\n\n return nabla_theta\n\ndef act(s, theta):\n pi[s, 0] = sigmoid(s, theta)\n pi[s, 1] = 1 - pi[s, 0]\n\n p = np.random.rand()\n if p <= pi[s, 0]:\n action = 0\n else:\n action = 1\n\n return action\n\ndef vanilla_polciy_gradient(theta, nabla_eta, alpha):\n delta_theta = nabla_eta\n theta_new = list(np.array(theta) + alpha * delta_theta)\n\n return theta_new\n\ndef step(s, a, r):\n if a == 0:\n s_next = s\n elif a == 1:\n s_next = (s + 1)%2\n\n return s_next, r[s, a]\n\n# 等高線の表示\ntheta1 = np.arange(-7.5, 10, 0.05)\ntheta2 = np.arange(-7.5, 10, 0.05)\n\nR_ = np.zeros((len(theta1), len(theta2)))\n# R_ = np.load('./R.npy')\ni = 0\n\nfor x in theta1:\n j = 0\n for y in theta2:\n # 初期状態の観測\n for k in range(10):\n p_s = np.random.rand()\n if p_s <= 0.8:\n s = 0\n else:\n s = 1\n theta = [x,y]\n rewards = []\n scores_deque = []\n scores = []\n\n for t in range(episode):\n a = act(s, theta)\n s, reward = step(s, a, r)\n rewards.append(reward)\n\n scores_deque.append(sum(rewards))\n scores.append(sum(rewards))\n \n discounts = [gamma**i for i in range(len(rewards)+1)]\n R_[j,i] += sum([a*b for a,b in zip(discounts, rewards)]) / 10\n j = j + 1\n i = i + 1\n\nim = ax.pcolormesh(theta1, theta2, R_, cmap='PuOr',alpha=0.3)\nim = ax.contourf(theta1, theta2, R_, cmap=\"inferno\")\nfig.colorbar(im, ax=ax)\n\ni = 0\nfor theta in theta_choice:\n\n print(theta)\n\n print(color_list[i])\n\n ax.scatter(theta[0], theta[1], s=40, marker='o', color = color_list[i])\n\n theta_total = []\n R_total = []\n\n for epoch_ in range(epoch):\n rewards = []\n scores_deque = []\n scores = []\n states = []\n actions = []\n q_values = []\n\n # 初期状態の観測\n p_s = np.random.rand()\n if p_s <= 0.8:\n s = 0\n else:\n s = 1\n\n states.append(s)\n theta_total.append(theta)\n\n # 1 episode分の状態・行動をサンプリング\n for t in range(episode):\n a = act(s, theta)\n next_state, reward = step(s, a, r)\n q = q_table[s, a]\n # 各要素の保存\n s = next_state\n rewards.append(reward)\n actions.append(a)\n states.append(s)\n q_values.append(q)\n\n # 収益の計算\n scores_deque.append(sum(rewards))\n scores.append(sum(rewards))\n\n # 各時間ステップの割引報酬和を計算\n G = []\n for t in range(episode):\n discounts = [gamma**i for i in range(episode-t+1)]\n G.append(sum([a*b for a,b in zip(discounts, rewards[t:])]))\n \n discounts = [gamma**i for i in range(len(rewards)+1)]\n R = sum([a*b for a,b in zip(discounts, rewards)]) / episode\n \n saved_nabla_log_pi = []\n policy_gradient = []\n\n # log(pi)の勾配計算\n for t in range(episode):\n saved_nabla_log_pi.append(list(np.array(differential_log_pi(states[t], actions[t], theta)).T))\n\n # モンテカルロによる勾配近似(REINFOCE)\n for nabla_log_pi_, r_ in zip(saved_nabla_log_pi, G): \n policy_gradient.append(list(np.array(nabla_log_pi_) * r_))\n \n # 方策パラメータの更新\n nabla_eta = np.sum(np.array(policy_gradient).T, axis=1) / episode\n theta = vanilla_polciy_gradient(theta, nabla_eta, alpha)\n\n R_total.append(R)\n\n theta_total_T = list(np.array(theta_total).T)\n ax.plot(theta_total_T[0], theta_total_T[1], linewidth=3, color = color_list[i])\n i = i + 1\n\n# 方策パラメータの可視化\nplt.title('Vannila Policy Gradient (100000 episode)')\nplt.xlabel('theta 1')\nplt.ylabel('theta 2')\nplt.ylim(-7.5, 10)\nplt.xlim(-7.5, 10)\n\nplt.savefig('Vanilla_Policy_Gradient.png')" }, { "alpha_fraction": 0.7868852615356445, "alphanum_fraction": 0.7868852615356445, "avg_line_length": 29.5, "blob_id": "ccd9138d2972a22e02afe41d22074f7a8391321b", "content_id": "b1a6d00fc115542e3a931c78c2d7b4cf55f1248d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 61, "license_type": "no_license", "max_line_length": 42, "num_lines": 2, "path": "/README.md", "repo_name": "kyo-kbys/NPG-for-toy-MDP", "src_encoding": "UTF-8", "text": "# NPG-for-toy-MDP\nnatural policy gradient method for toy MDP\n" } ]
2
junho3174/plotly_test
https://github.com/junho3174/plotly_test
898a71749c07ff66af83d0a0f4d5be0bca81b7a8
b5af49b239901607fc4bad754cea54a9a2c80700
6c1800ee3edfaa0a58bb27696f90387296f2c0a6
refs/heads/main
2023-06-10T14:26:43.652586
2021-07-08T09:07:22
2021-07-08T09:07:22
379,799,112
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4720226526260376, "alphanum_fraction": 0.499237984418869, "avg_line_length": 35.1732292175293, "blob_id": "69b158d06d14dc3591b19af3be895db17e7e182d", "content_id": "fa9e6e167e794236458690432bab8e711a1d78b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4923, "license_type": "no_license", "max_line_length": 97, "num_lines": 127, "path": "/shipTraffic.py", "repo_name": "junho3174/plotly_test", "src_encoding": "UTF-8", "text": "from urllib.request import urlopen\nfrom urllib.parse import urlencode, quote_plus\nimport json\nimport xmltodict\nimport plotly.graph_objects as go\n\ndef cntlvssl() -> list:\n url = 'http://apis.data.go.kr/1192000/CntlVssl2/Info'\n queryParams = '?' + urlencode(\n {\n quote_plus('ServiceKey'): 'Kk6GfZmcpKlmvK0ufG8JnZs8nZhJhSjiEWY6Qs6SoOdLkZLcdNam6Fv8JJBMVKJaXUkCz3+6o3M4O1nW6YMdRw==', # 인증키\n quote_plus('pageNo'): '1', # 페이지 번호\n quote_plus('numOfRows'): '50', # 한 페이지 결과 수(최대 50)\n quote_plus('prtAgCd'): '030', # 항만청코드(인천항 030)\n quote_plus('sde'): '20210708', # 검색 시작일\n quote_plus('ede'): '20210708', # 검색 종료일\n quote_plus('clsgn'): '' # 호출부호\n }\n )\n\n req = urlopen(url + queryParams)\n res = req.read().decode('utf8')\n dict_type = xmltodict.parse(res)\n json_type = json.dumps(dict_type)\n dict2_type = json.loads(json_type)\n\n value = []\n for i in range(5):\n value.append([])\n clsgn = []\n\n i = 1\n for item in dict2_type[\"response\"][\"body\"][\"items\"][\"item\"]:\n try :\n if item[\"details\"][\"detail\"][0][\"cntrlNm\"] == '입항':\n value[0].append(str(i))\n value[1].append(item[\"vsslNm\"])\n value[2].append(item[\"vsslNltyNm\"])\n value[3].append(item[\"clsgn\"])\n clsgn.append(item[\"clsgn\"])\n try:\n value[4].append(item[\"details\"][\"detail\"][0][\"cntrlOpertDt\"])\n except:\n value[4].append(item[\"details\"][\"detail\"][\"cntrlOpertDt\"])\n i += 1\n if i > 10 : break\n except:\n if item[\"details\"][\"detail\"][\"cntrlNm\"] == '입항':\n value[0].append(str(i))\n value[1].append(item[\"vsslNm\"])\n value[2].append(item[\"vsslNltyNm\"])\n value[3].append(item[\"clsgn\"])\n clsgn.append(item[\"clsgn\"])\n try:\n value[4].append(item[\"details\"][\"detail\"][0][\"cntrlOpertDt\"])\n except:\n value[4].append(item[\"details\"][\"detail\"][\"cntrlOpertDt\"])\n i += 1\n if i > 10 : break\n\n fig = go.Figure(\n data=[\n go.Table(\n header=dict(values=['No', 'Vessel', '선박국가', '콜사인', '기항지입항일시']),\n cells=dict(values=value)\n )\n ]\n )\n\n fig.show()\n\n return clsgn\n\ndef cargfrghtout(clsgn):\n url = 'http://apis.data.go.kr/1192000/CargFrghtOut2/Info'\n queryParams = '?' + urlencode(\n {\n quote_plus('ServiceKey'): 'Kk6GfZmcpKlmvK0ufG8JnZs8nZhJhSjiEWY6Qs6SoOdLkZLcdNam6Fv8JJBMVKJaXUkCz3+6o3M4O1nW6YMdRw==', # 인증키\n quote_plus('pageNo'): '1', # 페이지 번호\n quote_plus('numOfRows'): '10', # 한 페이지 결과 수(최대 50)\n quote_plus('prtAgCd'): '030', # 항만청코드(인천항 030)\n quote_plus('etryptYear'): '2021', # 입항연도\n quote_plus('etryptCo'): '001', # 입항횟수\n quote_plus('clsgn'): clsgn # 호출부호\n }\n )\n\n req = urlopen(url + queryParams)\n res = req.read().decode('utf8')\n dict_type = xmltodict.parse(res)\n json_type = json.dumps(dict_type)\n dict2_type = json.loads(json_type)\n\n if dict2_type[\"response\"][\"body\"][\"items\"] == None :\n url = 'http://apis.data.go.kr/1192000/CargFrghtIn2/Info'\n queryParams = '?' + urlencode(\n {\n quote_plus(\n 'ServiceKey'): 'Kk6GfZmcpKlmvK0ufG8JnZs8nZhJhSjiEWY6Qs6SoOdLkZLcdNam6Fv8JJBMVKJaXUkCz3+6o3M4O1nW6YMdRw==',\n # 인증키\n quote_plus('pageNo'): '1', # 페이지 번호\n quote_plus('numOfRows'): '10', # 한 페이지 결과 수(최대 50)\n quote_plus('prtAgCd'): '030', # 항만청코드(인천항 030)\n quote_plus('etryptYear'): '2021', # 입항연도\n quote_plus('etryptCo'): '001', # 입항횟수\n quote_plus('clsgn'): clsgn # 호출부호\n }\n )\n\n req = urlopen(url + queryParams)\n res = req.read().decode('utf8')\n dict_type = xmltodict.parse(res)\n json_type = json.dumps(dict_type)\n dict2_type = json.loads(json_type)\n\n print(\"Vessel : \" + dict2_type[\"response\"][\"body\"][\"items\"][\"item\"][\"vsslNm\"])\n print(\"선박종류명 : \" + dict2_type[\"response\"][\"body\"][\"items\"][\"item\"][\"vsslKndNm\"])\n print(\"화물품목한글명 : \" + dict2_type[\"response\"][\"body\"][\"items\"][\"item\"][\"frghtPrdlstKorNm\"])\n\n else:\n print(\"Vessel : \" + dict2_type[\"response\"][\"body\"][\"items\"][\"item\"][\"vsslNm\"])\n print(\"선박종류명 : \" + dict2_type[\"response\"][\"body\"][\"items\"][\"item\"][\"vsslKndNm\"])\n print(\"화물품목한글명 : \" + dict2_type[\"response\"][\"body\"][\"items\"][\"item\"][\"frghtPrdlstKorNm\"])\n\ncls = cntlvssl()\ni = input(\"검색할 Vessel의 No를 입력하세요. : \")\ncargfrghtout(cls[int(i)-1])" }, { "alpha_fraction": 0.5284923315048218, "alphanum_fraction": 0.5434711575508118, "avg_line_length": 26.41964340209961, "blob_id": "af740cb5e9668693b3aa7b808d2fe500eed34b3b", "content_id": "ea0cce8a43b4c90ee769e7c213f3eb443bb8d85a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3321, "license_type": "no_license", "max_line_length": 117, "num_lines": 112, "path": "/plotly_test.py", "repo_name": "junho3174/plotly_test", "src_encoding": "UTF-8", "text": "# 크롤링 하여 Plotly Table 로 출력\n\n# 크롤링\nimport urllib.request\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\n# plotly\nimport plotly.graph_objects as go\n\ndef get_incheonpilot() -> None:\n # crawled from 인천항 도선사회 - 도선 예보 현황\n print(\"인천 도선사회 도선 예보 현황\")\n date = input(\"날짜를 입력하시오.(YYYY-MM-DD) : \")\n url = 'http://www.incheonpilot.com/pilot/pilot04_01.asp?Datepicker_date='\n req = urllib.request.urlopen(url + date)\n res = req.read()\n\n soup = BeautifulSoup(res, 'html.parser')\n my_titles = soup.select('body > div > div > div > div > div > div > table > tr > td')\n value = []\n i = 0\n\n # 이중 list 선언\n for i in range(12):\n value.append([])\n\n for titles in my_titles:\n if i > 39:\n # 이전까지는 다른 테이블 데이터\n value[(i - 40) % 12].append(str(titles.text).replace(u'\\xa0', u' ').strip())\n i += 1\n\n # plotly table\n fig = go.Figure(\n data=[\n go.Table(\n header=dict(values=['No', '도선사', '시간', '선명', '갑문', '도선구간', '접안', '톤수', '홀수', '대리점', '예선', 'JOB NO']),\n cells=dict(values=value)\n )\n ]\n )\n fig.show()\n\n\ndef get_vesselfinder() -> None:\n # crawled from VesselFinder\n # 셀레니움 사용, 크롬 드라이버 설정\n driver = webdriver.Chrome('chromedriver')\n\n url = 'https://www.vesselfinder.com/ports/KRINC001'\n\n driver.get(url)\n\n sel = driver.page_source\n soup = BeautifulSoup(sel, 'html.parser')\n\n vesselfinder_soup = soup.find('div', id='tab-content')\n\n print('[ 1: expected, 2: arrivals, 3: departures, 4: in-port ]')\n select = 0\n select_id = ''\n\n while select > 5 or select < 1:\n select = int(input(\"메뉴를 선택하시오. : \"))\n if select == 1:\n select_id = 'expected'\n elif select == 2:\n select_id = 'arrivals'\n elif select == 3:\n select_id = 'departures'\n elif select == 4:\n select_id = 'in-port'\n else:\n print(\"다시 입력하시오.\")\n\n selected_soup = vesselfinder_soup.find('section', id=select_id)\n value = []\n\n for i in range(6):\n value.append([])\n\n # VesselFinder 에서는 값을 20개만 보여준다.\n for i in range(20):\n middle_data = selected_soup.select(\"table > tbody > tr\")[i]\n value[0].append(middle_data.select('td')[0].text) # 'ETA'\n value[2].append(middle_data.select('td')[2].text) # 'Built'\n value[3].append(middle_data.select('td')[3].text) # 'GT'\n value[4].append(middle_data.select('td')[4].text) # 'DWT\n value[5].append(middle_data.select('td')[5].text) # 'Size (m)'\n\n vessel = selected_soup.find_all('div', class_='named-title')\n\n for titles in vessel:\n value[1].append(str(titles.text).strip()) # 'Vessel'\n\n driver.quit()\n\n # plotly table\n fig = go.Figure(\n data=[\n go.Table(\n header=dict(values=['ETA', 'Vessel', 'Built', 'GT', 'DWT', 'Size (m)']),\n cells=dict(values=value)\n )\n ]\n )\n fig.show()\n\n\nif __name__ == \"__main__\":\n #get_incheonpilot()\n get_vesselfinder()\n" }, { "alpha_fraction": 0.557851254940033, "alphanum_fraction": 0.589531660079956, "avg_line_length": 32.76744079589844, "blob_id": "20a97a1bfdba7ed6f11a0be342746283f6d1f337", "content_id": "e49cff521dd72e14e1b75304e6564f4675b5a737", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1550, "license_type": "no_license", "max_line_length": 74, "num_lines": 43, "path": "/test.py", "repo_name": "junho3174/plotly_test", "src_encoding": "UTF-8", "text": "from pprint import pprint\nfrom urllib.request import urlopen\nfrom urllib.parse import urlencode, quote_plus\nimport json\nimport xmltodict\n\nurl = 'http://apis.data.go.kr/1192000/VsslEtrynd2/Info'\nqueryParams = '?' + urlencode(\n {\n quote_plus('ServiceKey'): 'Kk6GfZmcpKlmvK0ufG8JnZs8nZhJhSjiEWY6Qs6SoOdLkZLcdNam6Fv8JJBMVKJaXUkCz3+6o3M4O1nW6YMdRw==', # 인증키\n quote_plus('pageNo'): '1', # 페이지 번호\n quote_plus('numOfRows'): '50', # 한 페이지 결과 수(최대 50)\n quote_plus('prtAgCd'): '030', # 항만청코드(인천항 030)\n quote_plus('sde'): '20210629', # 검색 시작일\n quote_plus('ede'): '20210629', # 검색 종료일\n quote_plus('clsgn'): '' # 호출부호\n }\n)\n\nreq = urlopen(url + queryParams)\nres = req.read().decode('utf8')\ndict_type = xmltodict.parse(res)\njson_type = json.dumps(dict_type)\ndict2_type = json.loads(json_type)\n# pprint(dict2_type[\"response\"][\"body\"][\"items\"][\"item\"])\ni = 1\nfor item in dict2_type[\"response\"][\"body\"][\"items\"][\"item\"]:\n print(\"No : \" + str(i))\n print(\"Vessel : \" + item[\"vsslNm\"])\n print(\"선박국가 : \" + item[\"vsslNltyNm\"])\n try:\n print(\"ETA : \" + item[\"details\"][\"detail\"][0][\"etryptDt\"])\n print(\"내외항 : \" + item[\"details\"][\"detail\"][0][\"ibobprtNm\"] + \"\\n\")\n except:\n print(\"ETA : \" + item[\"details\"][\"detail\"][\"etryptDt\"])\n print(\"내외항 : \" + item[\"details\"][\"detail\"][\"ibobprtNm\"] + \"\\n\")\n i += 1\n\n'''\nfile_path = \"./sample.json\"\nwith open(file_path, 'w', encoding='UTF-8') as outfile:\n json.dump(dict2_type, outfile, indent=4, ensure_ascii=False)\n'''\n" }, { "alpha_fraction": 0.651448667049408, "alphanum_fraction": 0.6839332580566406, "avg_line_length": 33.48484802246094, "blob_id": "f36137cce2be8c0d8d0e9caab862b802c4300015", "content_id": "8c6697d1db149a20fee87acb4cc249a8ee1efefe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1251, "license_type": "no_license", "max_line_length": 103, "num_lines": 33, "path": "/getInsightSatlit.py", "repo_name": "junho3174/plotly_test", "src_encoding": "UTF-8", "text": "import urllib.request\nimport json\nfrom urllib.request import urlretrieve\nfrom urllib.error import HTTPError\nfrom urllib.error import URLError\n\nurl = 'http://apis.data.go.kr/1360000/SatlitImgInfoService/getInsightSatlit?' \\\n 'serviceKey=Kk6GfZmcpKlmvK0ufG8JnZs8nZhJhSjiEWY6Qs6SoOdLkZLcdNam6Fv8JJBMVKJaXUkCz3%2B6o3M4O1nW6YMdRw%3D%3D&' \\\n 'pageNo=1&numOfRows=10&dataType=JSON&sat=G2&' \\\n 'data=vi006&area=ko&time=20210708'\n# 조회 기간은 오늘 기준으로 1일 전까지\nreq = urllib.request.urlopen(url)\nres = req.read()\n\njson_object = json.loads(res)\njson_object2 = json_object.get('response').get('body').get('items').get('item')[0].get('satImgC-file')\njson_object3 = json_object2[1:-1].split(',') # 주소값이 담긴 리스트 모양의 하나의 큰 문자열로 되어있음\ni = 0\n\nfor image in json_object3:\n try:\n urlretrieve(image.strip(), \"C:/Users/LeeJunHo/Documents/GitHub/test/image/image\"+str(i)+\".png\")\n i += 1\n #time.sleep(0.5)\n print(\"download :\", i)\n except HTTPError as e:\n print(\"HTTPError :\", e)\n except URLError as e:\n print(\"URLError :\", e)\n\n# 조절 없는 요청으로 서버 측에서 에러 발생\n# urllib.error.HTTPError: HTTP Error 500: Internal Server Error\n# http.client.RemoteDisconnected: Remote end closed connection without response\n\n" } ]
4
MTIzNDU2Nzg5/vortex-based-math
https://github.com/MTIzNDU2Nzg5/vortex-based-math
07cbe1e3fab5f68d4839a98d46c514650f4055fb
3f1db2a4e15dad8bbb5a5a787b826547762966a2
3f4e48ac04f22d4d672b903175324232e5ece91f
refs/heads/master
2020-03-29T01:22:30.173807
2019-07-30T19:23:22
2019-07-30T19:23:22
149,385,697
0
0
null
2018-09-19T03:14:54
2018-10-04T20:59:53
2018-10-04T21:02:46
Python
[ { "alpha_fraction": 0.6470588445663452, "alphanum_fraction": 0.7058823704719543, "avg_line_length": 7.5, "blob_id": "4691f652c654c6e689476ff5ac3caf4e6b4f221e", "content_id": "d4aca56b49bc509dd311e9748a4418fe1c5a6d0e", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 119, "license_type": "permissive", "max_line_length": 24, "num_lines": 14, "path": "/README.md", "repo_name": "MTIzNDU2Nzg5/vortex-based-math", "src_encoding": "UTF-8", "text": "# vortex-math\nUsage:\n\npython vortex-math.py\n\nExample: \n\n>python vortex-math.py \n\n>Enter number to vortex:\n\n>123456\n\n>3\n" }, { "alpha_fraction": 0.561475396156311, "alphanum_fraction": 0.5696721076965332, "avg_line_length": 17.615385055541992, "blob_id": "878148ed94fe82202d4a1697e922ba5bb6d5b59b", "content_id": "2f4e9febdce82de96de8b54f8396829ccae94c73", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 244, "license_type": "permissive", "max_line_length": 46, "num_lines": 13, "path": "/vortex-based-math.py", "repo_name": "MTIzNDU2Nzg5/vortex-based-math", "src_encoding": "UTF-8", "text": "def vortex(n):\n return sum([int(x) for x in list(str(n))])\n\ndef blackhole(n):\n vortex(n) > 9 and blackhole(vortex(n))\n vortex(n) <= 9 and print(\"\\n\",vortex(n))\n \n \n \n \nprint('Enter number to vortex:')\n\nblackhole(input())\n\n\n" } ]
2
Zephery/python_crawler
https://github.com/Zephery/python_crawler
28c734ee8e99a6ec46d8d1280bee60ae9ca0c1ae
b5ee376c90e48743f06acaa2668d952db1a7fa7c
1831d1bcf4a548e5d91634ef75498ff374b9b48a
refs/heads/master
2021-01-20T10:21:20.631684
2017-05-05T07:19:32
2017-05-05T07:19:32
90,348,200
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6470588445663452, "alphanum_fraction": 0.6470588445663452, "avg_line_length": 23.14285659790039, "blob_id": "f6411c43fef8a6a6b1bb832b86d4421beefec232", "content_id": "0d27969927d834b7ae506092ac81446d35f012b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 170, "license_type": "no_license", "max_line_length": 56, "num_lines": 7, "path": "/requests_jd_第五章.py", "repo_name": "Zephery/python_crawler", "src_encoding": "UTF-8", "text": "import requests\nurl = 'https://www.jd.com/'\nresp = requests.get(url)\ns = resp.text\nprint(len(s))\nwith open('requests_jd.html', 'w', encoding='gbk') as f:\n f.write(s)\n\n" }, { "alpha_fraction": 0.5370928049087524, "alphanum_fraction": 0.552142322063446, "avg_line_length": 26.732187271118164, "blob_id": "d1bdcfb29c25c6870e858488c2ab4e646a19255e", "content_id": "01fc079ae1466cf42143761749ac50c6f8d5f78d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11612, "license_type": "no_license", "max_line_length": 159, "num_lines": 407, "path": "/action7_使用队列_没写到书里面.py", "repo_name": "Zephery/python_crawler", "src_encoding": "UTF-8", "text": "__author__ = 'pqh'\n\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\nimport threading\nimport queue\nimport os\nfrom glob import glob\nimport xlwt3\nimport xlrd\n#from threading import Thread, Lock\n\n\ncategories = {\n '计算机基础':('1096',31),\n '图形图像':('1097',80),\n '编程语言':('1098',68),\n '网络与互联网':('1099',33),\n '办公软件':('1100',22),\n '计算机科学':('1101',27),\n '辅助设计':('1102', 13),\n '操作系统':('1103',19),\n '计算机硬件':('1104',6),\n '多媒体技术':('1105',8),\n '信息安全':('1106',9),\n '数据库':('1107',10),\n}\n\n#http://www.phei.com.cn/module/goods/jsjts_list.jsp?Page=2&Page=2&btid=1107&desc=0&desc1=0&desc2=0&sort=&goodtypename=计算机\nurl_part_1 = 'http://www.phei.com.cn/module/goods/jsjts_list.jsp?Page='\nurl_part_2 = '&Page=2&btid='\nurl_part_3 = '&desc=0&desc1=0&desc2=0&sort=&goodtypename=计算机'\n\nbase_url = 'http://www.phei.com.cn/'\n\nmy_lock = threading.Lock()\n\ndef init_webdriver(webdriver):\n firefox_profile = webdriver.FirefoxProfile()\n firefox_profile.set_preference(\"permissions.default.stylesheet\", 2)\n firefox_profile.set_preference(\"permissions.default.image\", 2)\n firefox_profile.set_preference(\"permissions.default.script\", 2)\n firefox_profile.set_preference(\"permissions.default.subdocument\", 2)\n firefox_profile.set_preference(\"javascript.enabled\", False)\n firefox_profile.update_preferences()\n\n with my_lock:\n #init this driver\n #driver = webdriver.Firefox()\n\n #browser = webdriver.Remote(browser_profile=firefox_profile, desired_capabilities=webdriver.DesiredCapabilities.FIREFOX, command_executor=remote)\n webdriver = webdriver.Firefox(firefox_profile=firefox_profile)\n webdriver.set_page_load_timeout(300)\n\n return webdriver\n\n# def get(key_name):\n#\n# tid,pnum = categories[key_name]\n#\n# #生成urls列表\n#\n# urls = []\n#\n# for i in range(1,pnum+1):\n# url = url_part_1+str(i)+url_part_2+tid+url_part_3\n# urls.append(url)\n\ndef get_val_by_name(bs, name):\n\n name_node= bs.find(name)\n\n val_node = name_node.nextSibling\n\n val = ''\n\n if val_node is not None:\n\n val = val_node.get_text()\n\n\n return val\n\ndef get_instruction(html):\n l_tag = '<td align=\"left\" valign=\"top\" class=\"line_h24 f12_grey pad_t20 pad_bot20\"><p>'\n r_tag = '</p>'\n instruction = '----'\n try:\n instruction = html.split(l_tag)[1].split(r_tag)[0]\n except Exception as e:\n print('instruction:', e)\n return instruction\n\ndef get_val_from_dict(d,k):\n try:\n return d[k]\n except Exception as e:\n print(k, e)\n return '----'\n\nclass Crawler(threading.Thread):\n\n # def __init__(self,urls_queue,urls_dir,pages_queue,page_info_dir,webdriver):\n def __init__(self,urls_queue,urls_dir,pages_queue,webdriver):\n threading.Thread.__init__(self)\n self.urls_queue = urls_queue\n self.page_urls_dir = urls_dir\n #self.page_info_dir = page_info_dir\n self.pages_queue = pages_queue\n self.webdriver = init_webdriver(webdriver)\n self.cnt = 0\n\n # def init_webdriver(self,webdriver):\n # firefox_profile = webdriver.FirefoxProfile()\n # firefox_profile.set_preference(\"permissions.default.stylesheet\", 2)\n # firefox_profile.set_preference(\"permissions.default.image\", 2)\n # firefox_profile.set_preference(\"permissions.default.script\", 2)\n # firefox_profile.set_preference(\"permissions.default.subdocument\", 2)\n # firefox_profile.set_preference(\"javascript.enabled\", False)\n # firefox_profile.update_preferences()\n #\n # with my_lock:\n # #init this driver\n # #driver = webdriver.Firefox()\n #\n # #browser = webdriver.Remote(browser_profile=firefox_profile, desired_capabilities=webdriver.DesiredCapabilities.FIREFOX, command_executor=remote)\n # webdriver = webdriver.Firefox(firefox_profile=firefox_profile)\n # webdriver.set_page_load_timeout(60)\n # return webdriver\n\n def run(self):\n\n while True:\n\n url = self.urls_queue.get()\n\n self.webdriver.get(url)\n\n fname = url.split(url_part_1)[1].split(url_part_2)[0]\n\n with open(self.page_urls_dir+'/'+fname+'.html','w') as f:\n f.write(self.webdriver.page_source)\n\n\n\n #grabs urls of hosts and then grabs chunk of webpage\n # url = urllib2.urlopen(host)\n # chunk = url.read()\n\n #place chunk into out queue\n self.pages_queue.put(self.webdriver.page_source)\n\n #signals to queue job is done\n self.urls_queue.task_done()\n\n self.cnt +=1\n\n def quit(self):\n\n self.webdriver.quit()\n\nclass Analyst(threading.Thread):\n\n def __init__(self,pages_queue,page_content_dir,webdriver):\n threading.Thread.__init__(self)\n self.pages_queue = pages_queue\n self.webdriver = init_webdriver(webdriver)\n self.page_content_dir = page_content_dir\n self.cnt = 1\n\n\n\n def get_hrefs(self,html_str):\n\n bs = BeautifulSoup(html_str)\n\n urls_lst = []\n\n divs = bs.find_all('div')\n\n for div in divs:\n\n a_lst = div.find_all('a')\n\n for a in a_lst:\n\n if a['href'] not in urls_lst and 'bookid=' in a['href'] and 'num=1' not in a['href']:\n\n urls_lst.append(a['href'])\n\n\n print(str(len(urls_lst)))\n\n return urls_lst\n\n\n def run(self):\n\n while True:\n\n page_source = self.pages_queue.get()\n\n href_lst = self.get_hrefs(page_source)\n\n for href in href_lst:\n\n url = base_url + href\n\n self.webdriver.get(url)\n\n fname = url.split('bookid=')[1]\n\n with open(self.page_content_dir+'/'+fname+'.html','w') as f:\n f.write(self.webdriver.page_source)\n\n #self.cnt\n\n self.pages_queue.task_done()\n\n\n\n def quit(self):\n\n self.webdriver.quit()\n\n\n\n\nclass ExtractInfo(threading.Thread):\n\n def __init__(self, page_content_dir):\n threading.Thread.__init__(self)\n\n self.page_content_dir = page_content_dir\n\n\n def run(self):\n\n files_list = glob(self.page_content_dir+'/'+'*.html')\n key_names = ['书名','作译者','出版时间','千字数','版次','页数','开本','价格','内容简介']\n all_recs = []\n all_recs.append(key_names)\n\n #4\n for file_name in files_list:\n book_name = file_name.split('.html')[0].replace('./'+self.page_content_dir+'/','')\n\n f = open(file_name, 'r')\n #print(file_name)\n html_str = f.read()\n f.close()\n #5\n # browser.webview.setHtml(html_str)\n # browser.wait(1)\n #6\n try:\n # td_list = browser.webframe.findAllElements('td')\n td_list = BeautifulSoup(html_str).find_all('td')\n #print(td_list)\n d = {}\n d['书名'] = book_name\n #print(file_name)\n for td in td_list:\n if 'height' in td.attrs:\n if td['height'] == '20':\n txt = td.get_text().replace('\\xa0', '').replace(' ','').replace('\\t','')\n if ':' in txt:\n k = txt.split(':')[0]\n v = txt.split(':')[1]\n d[k] = v\n #print(k,v)\n d['价格'] = html_str.split('纸质书定价:¥')[1].split('<span class=\"f12_red\">会员价')[0].replace('&nbsp;&nbsp;&nbsp;','')\n #print(book_name, d['价格'])\n #instruction = get_instruction(html_str)\n instruction = BeautifulSoup(html_str).find('div', attrs = {'id': 'neirong'}).get_text()\n d['内容简介'] = instruction.replace('\\t','').replace('\\n','').replace(' ','')\n #print(d['内容简介'])\n #print([get_val_from_dict(d, kname) for kname in key_names])\n all_recs.append([get_val_from_dict(d, kname) for kname in key_names])\n except Exception as e:\n print(book_name, e)\n continue\n #7\n wb=xlwt3.Workbook()\n sheet=wb.add_sheet(\"图书信息\")\n for i in range(0, len(all_recs)):\n for j in range(0, len(all_recs[i])):\n sheet.write(i, j, all_recs[i][j])\n #print(all_recs[i][j])\n #wb.save(\"图书信息_04_16.xls\")\n print('save:'+self.page_content_dir,' '+str(len(all_recs)))\n wb.save(self.page_content_dir+\".xls\")\n\nclass ThreadSchedule(threading.Thread):\n\n def __init__(self, category_name):\n threading.Thread.__init__(self)\n self.urls_queue = queue.Queue()\n self.pages_queue = queue.Queue()\n self.url_lst = self.get_urls_lst(category_name)\n self.category = category_name\n self.urls_dir = category_name+'_urls'\n self.pages_dir = category_name+'_pages'\n os.makedirs(category_name+'_urls', exist_ok = True)\n os.makedirs(category_name+'_pages', exist_ok = True)\n\n self.crawler = Crawler(self.urls_queue, self.urls_dir, self.pages_queue, webdriver)\n self.analyst = Analyst(self.pages_queue, self.pages_dir, webdriver)\n\n def get_urls_lst(self,name):\n\n tid,pnum = categories[name]\n\n #生成urls列表\n\n urls = []\n\n for i in range(1,pnum+1):\n url = url_part_1+str(i)+url_part_2+tid+url_part_3\n urls.append(url)\n\n return urls\n\n def run(self):\n\n self.crawler.setDaemon(True)\n self.crawler.start()\n\n for url in self.url_lst:\n self.urls_queue.put(url)\n\n self.analyst.setDaemon(True)\n self.analyst.start()\n\n self.urls_queue.join()\n self.pages_queue.join()\n\n self.crawler.quit()\n self.analyst.quit()\n\n print(self.category+':Urls 数量:', self.crawler.cnt)\n print(self.category+':Pages 数量:', self.analyst.cnt)\n\n\n'''\n 抓取\n'''\n\n# threads_lst = []\n#\n# for key in categories.keys():\n# thread = ThreadSchedule(key).start()\n# #threads_lst.append(thread)\n\n\n#\n#\n'''\n 抽取信息\n'''\n\n# threads_lst = []\n#\n# # for key in categories.keys():\n# # thread = ThreadSchedule(key).start()\n# #threads_lst.append(thread)\n#\n# for key in categories.keys():\n# thread = ExtractInfo(key+'_pages').start()\n\n'''\n 合并 _pages.xls\n'''\n\ndef combine_xls():\n\n all_lines = []\n\n xls_files = glob('./'+'*.xls')\n\n for file_name in xls_files:\n if '_pages' in file_name:\n info = xlrd.open_workbook(file_name)\n\n content = info.sheets()[0]\n\n nrows = content.nrows\n ncols = content.ncols\n\n\n\n for i in range(1, nrows):\n row_lst = []\n for j in range(0, ncols-1):\n row_lst.append(str(content.cell(i, j).value))\n\n all_lines.append([row_lst[0].split('_')[0]]+ row_lst[2:])\n\n wb=xlwt3.Workbook()\n sheet=wb.add_sheet(\"计算机类图书信息\")\n for i in range(0,len(all_lines)):\n for j in range(0,len(all_lines[i])):\n sheet.write(i, j, all_lines[i][j])\n #wb.save(\"图书信息_04_16.xls\")\n wb.save(\"计算机类图书信息\"+\".xls\")\n\ncombine_xls()\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.529608964920044, "alphanum_fraction": 0.5469273924827576, "avg_line_length": 21.632911682128906, "blob_id": "d4b224722e09a73ff82ed5610c5c208b135bccac", "content_id": "403354ab0fbb71935d876169d7df8a44f0582f1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1818, "license_type": "no_license", "max_line_length": 91, "num_lines": 79, "path": "/char6_6_3_snipets.py", "repo_name": "Zephery/python_crawler", "src_encoding": "UTF-8", "text": "_author__ = 'pqh'\nimport spynner\n\nbrowser = spynner.Browser()\nbrowser.show()\nbrowser.load('http://www.phei.com.cn/module/goods/wssd_content.jsp?bookid=42345',\n load_timeout=60, tries=3)\ntd_list = browser.webframe.findAllElements('td')\n\nfor td in td_list:\n td_text = td.toPlainText()\n if ':' in td_text:\n print(td_text)\n\nbrowser.close()\n\n\nimport time\n\n#td = browser.search_element_text('著')\n\nbegin_index = 0\n\nbegin_td = None\n\n#td index = 0\n# for td in td_list:\n#\n# # if td.attribute('height') == '20':\n# # txt = td.toPlainText()\n# # print(td.attribute('height'),txt)\n#\n# txt = td.toPlainText()\n# if '著    者:Peter J.Bentley' in txt:\n# print(txt)\n# #print(txt)\n# #print('aaaa')\n# # if '著    者' in txt:\n# # print('bbbb'+txt)\n# # begin_td = td\n# # begin_index = td_list.toList().index(begin_td)\n# # #print(text,begin_index,'OK')\n# # break\n\nd = {}\nfor td in td_list:\n if td.attribute('height') == '20':\n txt = td.toPlainText().replace('\\xa0', '')\n if ':' in txt:\n print(txt)\n k = txt.split(':')[0]\n v = txt.split(':')[1]\n d[k] = v\nprint(d)\n\n\ndef get_instruction(html):\n l_tag = '<td align=\"left\" valign=\"top\" class=\"line_h24 f12_grey pad_t20 pad_bot20\"><p>'\n r_tag = '</p>'\n instruction = ''\n try:\n instruction = html.split(l_tag)[1].split(r_tag)[0]\n except Exception as e:\n print(e)\n return instruction\n\ns = get_instruction(browser.html)\nprint(s)\n#time.sleep(4)\n#\n# if td != []:\n# begin_index = td_list.index(td[0])\n\n#print(begin_index)\n# for i in range(begin_index, begin_index+10):\n# td_text = td_list[i].toPlainText()\n# if ':' in td_text:\n# print(td_text)\nbrowser.close()\n\n\n" }, { "alpha_fraction": 0.5248169302940369, "alphanum_fraction": 0.5728234052658081, "avg_line_length": 21.327272415161133, "blob_id": "22b2efbc59965d0745bb82b230b7ab657d868ebd", "content_id": "6782d51cd2a6af656b87936edf1878b99986da66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1537, "license_type": "no_license", "max_line_length": 62, "num_lines": 55, "path": "/first_get_and_save_file_第一章.py", "repo_name": "Zephery/python_crawler", "src_encoding": "UTF-8", "text": "#引入requests模块\nimport requests\n\n#定义get_content函数\ndef get_content(url):\n resp = requests.get(url)\n return resp.text\n\nif __name__ == '__main__':\n\n #定义url,值为要抓取的目标网站网址\n url = \"http://www.phei.com.cn\"\n\n #调用函数返回值赋值给content\n content = get_content(url)\n\n #打印输出content的前50个字符\n print(\"前50个字符为: \", content[0:50])\n\n #得到content的长度\n content_len = len(content)\n print(\"内容的长度为: \", content_len)\n\n #判断内容长度是否大于40KB\n if content_len >= 40*1024:\n print(\"内容的长度大于等于40KB.\")\n else:\n print(\"内容的长度小于等于40KB.\")\n\n # 方式1\n #文件的写入\n print('-'*20)\n print('方式1:', '文件写入')\n f1 = open('home_page.html', 'w', encoding='utf8')\n f1.write(content)\n f1.close()\n\n #文件的读取\n print('方式1:', '文件读取')\n f2 = open('home_page.html', 'r', encoding='utf8')\n content_read = f2.read()\n print(\"方式1读取的前50个字符为: \", content_read[0:50])\n f2.close()\n\n # 方式2\n # 文件的写入\n print('-' * 20)\n print('方式2:', '文件写入')\n with open('home_page_2.html', 'w', encoding='utf8') as f3:\n f3.write(content)\n # 文件的读取\n print('方式2:', '文件读取')\n with open('home_page_2.html', 'r', encoding='utf8') as f4:\n content_read_2 = f4.read()\n print(\"方式2读取的前50个字符为: \", content_read_2[0:50])\n\n" }, { "alpha_fraction": 0.6158536672592163, "alphanum_fraction": 0.6512194871902466, "avg_line_length": 25.419355392456055, "blob_id": "6792f12cdaa44bf24426ea012b478959578d6e8f", "content_id": "4a8a72d46e6effab41b7027379bb17e76ae6a1e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 832, "license_type": "no_license", "max_line_length": 65, "num_lines": 31, "path": "/tor_change_ip_第六章.py", "repo_name": "Zephery/python_crawler", "src_encoding": "UTF-8", "text": "import socks\nimport socket\nfrom stem.control import Controller\nfrom stem import Signal\nimport requests\nfrom bs4 import BeautifulSoup\nimport time\n\ncontroller = Controller.from_port(port=9151)\ncontroller.authenticate()\nsocks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, \"127.0.0.1\", 9150)\nsocket.socket = socks.socksocket\n\ncounter = 0\nurl_ip = 'http://jsonip.com/'\nwhile counter < 500000:\n try:\n r = requests.get(url_ip)\n soup = BeautifulSoup(r.text)\n ip_val = r.json()['ip']\n print(counter, '当前ip:', ip_val);\n\n time1 = time.time()\n controller.signal(Signal.NEWNYM)\n # time.sleep(controller.get_newnym_wait())\n time.sleep(5)\n time2 = time.time()\n print(counter, '改变ip时间: ', time2-time1)\n counter += 1\n except Exception as e:\n print(e)\n\n" }, { "alpha_fraction": 0.48635977506637573, "alphanum_fraction": 0.5363384485244751, "avg_line_length": 29.966997146606445, "blob_id": "ee15cdcb3907a8d68efa595a0f330c4c39f3a4de", "content_id": "0f2e9593d53bc733e1cfc46a15be52b5c2532587", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9752, "license_type": "no_license", "max_line_length": 410, "num_lines": 303, "path": "/char6_6_3_get_info.py", "repo_name": "Zephery/python_crawler", "src_encoding": "UTF-8", "text": "import spynner\nimport glob\nimport xlwt3\n\n#1\ndef get_instruction(html):\n l_tag = '<td align=\"left\" valign=\"top\" class=\"line_h24 f12_grey pad_t20 pad_bot20\"><p>'\n r_tag = '</p>'\n instruction = '----'\n try:\n instruction = html.split(l_tag)[1].split(r_tag)[0]\n except Exception as e:\n print('instruction:', e)\n return instruction\n\ndef get_val_from_dict(d,k):\n try:\n return d[k]\n except Exception as e:\n print(k,e)\n return '----'\n\n#2\nbrowser = spynner.Browser()\nbrowser.show()\n#3\nfiles_list = glob.glob('./htmls/*.html')\nkey_names = ['书名','作译者','出版时间','千字数','版次','页数','开本','价格','内容简介']\nall_recs = []\nall_recs.append(key_names)\n\n#4\nfor file_name in files_list:\n book_name = file_name.split('.html')[0].replace('./htmls/','')\n f = open(file_name, 'r')\n html_str = f.read()\n f.close()\n #5\n browser.webview.setHtml(html_str)\n browser.wait(1)\n #6\n try:\n td_list = browser.webframe.findAllElements('td')\n d = {}\n d['书名'] = book_name\n print(file_name)\n for td in td_list:\n if td.attribute('height') == '20':\n txt = td.toPlainText().replace('\\xa0', '').replace(' ','').replace('\\t','')\n if ':' in txt:\n k = txt.split(':')[0]\n v = txt.split(':')[1]\n d[k] = v\n d['价格'] = html_str.split('纸质书定价:¥')[1].split('<span class=\"f12_red\">会员价')[0].replace('&nbsp;&nbsp;&nbsp;','')\n instruction = get_instruction(html_str)\n d['内容简介']=instruction\n all_recs.append([get_val_from_dict(d,kname) for kname in key_names])\n except Exception as e:\n print(e)\n continue\n#7\nwb=xlwt3.Workbook()\nsheet=wb.add_sheet(\"图书信息\")\nfor i in range(0,len(all_recs)):\n for j in range(0, len(all_recs[i])):\n sheet.write(i, j, all_recs[i][j])\nwb.save(\"图书信息_04_16.xls\")\nbrowser.close()\n\n\n\n\n\n# import spynner\n# import glob\n# import xlwt3\n#\n# #1\n# def get_instruction(html):\n# l_tag = '<td align=\"left\" valign=\"top\" class=\"line_h24 f12_grey pad_t20 pad_bot20\"><p>'\n# r_tag = '</p>'\n# instruction = '----'\n# try:\n# instruction = html.split(l_tag)[1].split(r_tag)[0]\n# except Exception as e:\n# print('instruction:', e)\n# return instruction\n#\n# def get_val_from_dict(d,k):\n# try:\n# return d[k]\n# except Exception as e:\n# print(k,e)\n# return '----'\n#\n# #2\n# browser = spynner.Browser()\n# browser.show()\n# #3\n# files_list = glob.glob('./htmls/*.html')\n# key_names = ['书名','作译者','出版时间','千字数','版次','页数','开本','价格','内容简介']\n# all_recs = []\n# all_recs.append(key_names)\n#\n# #4\n# for file_name in files_list:\n# book_name = file_name.split('.html')[0].replace('./htmls/','')\n# f = open(file_name, 'r')\n# html_str = f.read()\n# f.close()\n# #5\n# browser.webview.setHtml(html_str)\n# browser.wait(1)\n# #6\n#\n# try:\n#\n# td_list = browser.webframe.findAllElements('td')\n# d = {}\n# d['书名'] = book_name\n# print(file_name)\n# for td in td_list:\n# if td.attribute('height') == '20':\n# txt = td.toPlainText().replace('\\xa0', '').replace(' ','').replace('\\t','')\n# if ':' in txt:\n# k = txt.split(':')[0]\n# v = txt.split(':')[1]\n# d[k] = v\n# # 纸质书定价:¥36.8\n# # <span class=\"f12_red\">会员价:¥29.44\n# d['价格'] = html_str.split('纸质书定价:¥')[1].split('<span class=\"f12_red\">会员价')[0].replace('&nbsp;&nbsp;&nbsp;','')\n# instruction = get_instruction(html_str)\n# d['内容简介']=instruction\n# all_recs.append([get_val_from_dict(d,kname) for kname in key_names])\n# except Exception as e:\n# print(e)\n# continue\n# #7\n# wb=xlwt3.Workbook()\n# sheet=wb.add_sheet(\"图书信息\")\n# for i in range(0,len(all_recs)):\n# for j in range(0,len(all_recs[i])):\n# sheet.write(i,j,all_recs[i][j])\n# wb.save(\"图书信息_04_16.xls\")\n# browser.close()\n\n\n\n# __author__ = 'pqh'\n# import spynner\n# import time\n# import glob\n# import xlwt3\n# def get_instruction(html):\n# l_tag = '<td align=\"left\" valign=\"top\" class=\"line_h24 f12_grey pad_t20 pad_bot20\"><p>'\n# r_tag = '</p>'\n# instruction = '----'\n# try:\n# instruction = html.split(l_tag)[1].split(r_tag)[0]\n# except Exception as e:\n# print('instruction:', e)\n# return instruction\n#\n# def get_val_from_dict(d,k):\n# try:\n# return d[k]\n# except Exception as e:\n# print(k,e)\n# return '----'\n#\n# #作译者,出版时间,千字数,版次,页数,开本,装帧,ISBN\n#\n# files_list = glob.glob('./htmls/*.html')\n# print(len(files_list))\n# browser = spynner.Browser()\n# browser.show()\n# key_names = ['书名', '作译者', '出版时间', '千字数', '版次', '页数', '开本', '内容简介']\n# all_recs = []\n# all_recs.append(key_names)\n# i = 1\n# for file_name in files_list[0:1]:\n# book_name = file_name.split('.html')[0].replace('./htmls/','')\n# f = open(file_name, 'r')\n# html_str = f.read()\n# f.close()\n# #browser.webview.show()\n# browser.webview.setHtml(html_str)\n# browser.wait(1)\n# #\n# td_list = browser.webframe.findAllElements('td')\n# d = {}\n# d['书名'] = book_name\n# print(file_name)\n# for td in td_list:\n# if td.attribute('height') == '20':\n# txt = td.toPlainText().replace('\\xa0', '').replace(' ','').replace('\\t','')\n# print(txt)\n# if ':' in txt:\n# #print(txt)\n# k = txt.split(':')[0]\n# v = txt.split(':')[1]\n# d[k] = v\n#\n# instruction = get_instruction(html_str)\n# d['内容简介']=instruction\n# print(d.keys())\n# all_recs.append([get_val_from_dict(d,kname) for kname in key_names])\n# #print(d)\n# print(all_recs[i])\n# ##print(all_recs)\n# #print(book_name)\n#\n# wb=xlwt3.Workbook()\n# sheet=wb.add_sheet(\"图书信息\")\n# for i in range(0,len(all_recs)):\n# for j in range(0,len(all_recs[i])):\n# sheet.write(i,j,all_recs[i][j])\n# wb.save(\"图书信息.xls\")\n#\n# print(all_recs[1])\n#\n# browser.close()\n\n#browser.load('http://www.phei.com.cn/module/goods/wssd_content.jsp?bookid=42345', load_timeout=60, tries=3)\n# td_list = browser.webframe.findAllElements('td')\n#\n#\n#\n# d = {}\n# for td in td_list:\n# if td.attribute('height') == '20':\n# txt = td.toPlainText().replace('\\xa0', '')\n# if ':' in txt:\n# print(txt)\n# k = txt.split(':')[0]\n# v = txt.split(':')[1]\n# d[k] = v\n\n# __author__ = 'pqh'\n# import spynner\n# import time\n# import glob\n# def get_instruction(html):\n# l_tag = '<td align=\"left\" valign=\"top\" class=\"line_h24 f12_grey pad_t20 pad_bot20\"><p>'\n# r_tag = '</p>'\n# instruction = ''\n# try:\n# instruction = html.split(l_tag)[1].split(r_tag)[0]\n# except Exception as e:\n# print(e)\n# return instruction\n#\n# files_list = glob.glob('./htmls/*.html')\n#\n# browser = spynner.Browser()\n#\n# browser.show()\n# from PyQt4 import QtCore\n# from PyQt4.QtCore import SIGNAL, QUrl, Qt, QEvent\n# for file_name in files_list:\n# f = open(file_name, 'r')\n# html_str = f.read()\n# #browser.load('file:///home/pqh/My_Study_Work/my_Research/book_code/book_code/htmls/3G%E6%99%BA%E8%83%BD%E6%89%8B%E6%9C%BA%E5%88%9B%E6%84%8F%E8%AE%BE%E8%AE%A1%E2%80%94%E2%80%94%E9%A6%96%E5%B1%8A%E5%8C%97%E4%BA%AC%E5%B8%82%E5%A4%A7%E5%AD%A6%E7%94%9F%E8%AE%A1%E7%AE%97%E6%9C%BA%E5%BA%94%E7%94%A8%E5%A4%A7%E8%B5%9B%E8%8E%B7%E5%A5%96%E4%BD%9C%E5%93%81%E7%B2%BE%E9%80%89_22874.html', load_timeout=60, tries=3)\n# #url = 'file:///home/pqh/My_Study_Work/my_Research/book_code/book_code/htmls/3G%E6%99%BA%E8%83%BD%E6%89%8B%E6%9C%BA%E5%88%9B%E6%84%8F%E8%AE%BE%E8%AE%A1%E2%80%94%E2%80%94%E9%A6%96%E5%B1%8A%E5%8C%97%E4%BA%AC%E5%B8%82%E5%A4%A7%E5%AD%A6%E7%94%9F%E8%AE%A1%E7%AE%97%E6%9C%BA%E5%BA%94%E7%94%A8%E5%A4%A7%E8%B5%9B%E8%8E%B7%E5%A5%96%E4%BD%9C%E5%93%81%E7%B2%BE%E9%80%89_22874.html'\n# #url = './htmls/3G%E6%99%BA%E8%83%BD%E6%89%8B%E6%9C%BA%E5%88%9B%E6%84%8F%E8%AE%BE%E8%AE%A1%E2%80%94%E2%80%94%E9%A6%96%E5%B1%8A%E5%8C%97%E4%BA%AC%E5%B8%82%E5%A4%A7%E5%AD%A6%E7%94%9F%E8%AE%A1%E7%AE%97%E6%9C%BA%E5%BA%94%E7%94%A8%E5%A4%A7%E8%B5%9B%E8%8E%B7%E5%A5%96%E4%BD%9C%E5%93%81%E7%B2%BE%E9%80%89_22874.html'\n# #QtCore.QUrl(url)\n#\n# #QtCore.QUrl(\"qrc:///\"+url)\n#\n# # browser.webview.load(QtCore.QUrl(url))\n# browser.webview.setHtml(html_str)\n# browser.webview.show()\n# td_list = browser.webframe.findAllElements('td')\n# d = {}\n# for td in td_list:\n# if td.attribute('height') == '20':\n# txt = td.toPlainText().replace('\\xa0', '')\n# if ':' in txt:\n# print(txt)\n# k = txt.split(':')[0]\n# v = txt.split(':')[1]\n# d[k] = v\n# #print(browser.html)\n# print('ggg')\n# browser.wait(20)\n# f.close()\n#\n# browser.close()\n#\n# #browser.load('http://www.phei.com.cn/module/goods/wssd_content.jsp?bookid=42345', load_timeout=60, tries=3)\n# # td_list = browser.webframe.findAllElements('td')\n# #\n# #\n# #\n# # d = {}\n# # for td in td_list:\n# # if td.attribute('height') == '20':\n# # txt = td.toPlainText().replace('\\xa0', '')\n# # if ':' in txt:\n# # print(txt)\n# # k = txt.split(':')[0]\n# # v = txt.split(':')[1]\n# # d[k] = v\n\n" }, { "alpha_fraction": 0.7273972630500793, "alphanum_fraction": 0.7479451894760132, "avg_line_length": 29.16666603088379, "blob_id": "83ff52f520abe2fdf0cc3737f5ae56687843f426", "content_id": "f41f74809b221d37434da4a402f819ebee9db430", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 730, "license_type": "no_license", "max_line_length": 76, "num_lines": 24, "path": "/tor_selenium_第六章.py", "repo_name": "Zephery/python_crawler", "src_encoding": "UTF-8", "text": "from selenium import webdriver\n\nurl_pub = 'http://www.phei.com.cn/'\n\nprofile = webdriver.FirefoxProfile()\n\nprofile.set_preference(\"permissions.default.stylesheet\", 2)\nprofile.set_preference(\"permissions.default.image\", 2)\nprofile.set_preference(\"dom.ipc.plugins.enabled.libflashplayer.so\", \"false\")\n\nprofile.set_preference('network.proxy.type', 1)\nprofile.set_preference('network.proxy.socks', '127.0.0.1')\nprofile.set_preference('network.proxy.socks_port', 9150)\nprofile.set_preference('network.proxy.socks_version', 5)\nprofile.update_preferences()\n\nbrowser = webdriver.Firefox(profile)\n\nbrowser.get(url_pub)\n\nwith open('tor_selenium' + '.html', 'w', encoding='utf8') as f:\n f.write(browser.page_source)\n\nbrowser.quit()\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.7163865566253662, "alphanum_fraction": 0.743697464466095, "avg_line_length": 25.11111068725586, "blob_id": "49d278da65ea10177e7eafb8279e52e5ed95998f", "content_id": "7beafa7445d2b8bf8515033bd9d7429cfcd6738a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 476, "license_type": "no_license", "max_line_length": 58, "num_lines": 18, "path": "/tor_selenium_for_chang_ip_第六章.py", "repo_name": "Zephery/python_crawler", "src_encoding": "UTF-8", "text": "from selenium import webdriver\nimport time\nurl_ip = 'http://jsonip.com/'\n\nprofile = webdriver.FirefoxProfile()\nprofile.set_preference('network.proxy.type', 1)\nprofile.set_preference('network.proxy.socks', '127.0.0.1')\nprofile.set_preference('network.proxy.socks_port', 9150)\nprofile.set_preference('network.proxy.socks_version', 5)\nprofile.update_preferences()\n\nbrowser = webdriver.Firefox(profile)\n\nwhile True:\n time.sleep(5)\n browser.get(url_ip)\n\nbrowser.quit()\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5631313323974609, "alphanum_fraction": 0.5757575631141663, "avg_line_length": 16.2608699798584, "blob_id": "607a22d3551bd7ce0aabcb0d40d9eca6ebbc0631", "content_id": "462d2f7a0e60dbf4ea041c6fbf8f4779ff0df601", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 412, "license_type": "no_license", "max_line_length": 52, "num_lines": 23, "path": "/char6_6_3_convert_xls_to_txt.py", "repo_name": "Zephery/python_crawler", "src_encoding": "UTF-8", "text": "__author__ = 'pqh'\nimport xlrd\n\ninfo = xlrd.open_workbook('图书信息.xls')\n\ncontent = info.sheets()[0]\n\nnrows = content.nrows\nncols = content.ncols\n2\nf_txt = '图书信息.txt'\n\nf = open(f_txt, 'w')\n\nfor i in range(1, nrows):\n row_str = ''\n for j in range(0, ncols-1):\n row_str += str(content.cell(i, j).value)+','\n\n row_str = (row_str+'\\n').replace(',\\n','\\n')\n f.write(row_str)\n\nf.close()" }, { "alpha_fraction": 0.5795954465866089, "alphanum_fraction": 0.5910290479660034, "avg_line_length": 20.884614944458008, "blob_id": "8728b16769a993ea7baae46c83077722942628d4", "content_id": "dff261d51f4a3730011ef2646498bc41d380dece", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1155, "license_type": "no_license", "max_line_length": 78, "num_lines": 52, "path": "/char6_6_3_copy.py", "repo_name": "Zephery/python_crawler", "src_encoding": "UTF-8", "text": "__author__ = 'pqh'\n\nimport spynner\n#\nbrowser = spynner.Browser()\n\nbrowser.show()\n#http://www.phei.com.cn/module/goods/searchkey.jsp?Page=1&Page=2&searchKey=计算机\n\nurls = []\n\nfor i in range(1, 86):\n urls.append('http://www.phei.com.cn/module/goods/searchkey.jsp?Page='\n +str(i)+\n '&Page=2&searchKey=计算机')\n\nall_href_list = []\nfor url in urls:\n browser.load(url, load_timeout=60)\n a_list = browser.webframe.findAllElements('a')\n needed_list = []\n for a in a_list:\n href_val = a.attribute('href')\n \n if 'bookid' in href_val and 'shopcar0.jsp' not in href_val:\n if href_val not in needed_list:\n needed_list.append(href_val)\n all_href_list += needed_list\n\nall_href_file = open('all_hrefs.txt', 'w')\n\nfor href in all_href_list:\n all_href_file.write(href+'\\n')\n\nall_href_file.close()\n\nfor href_ in all_href_list:\n print(href_)\n\nbrowser.close()\n\n# urls = []\n#\n# for i in range(1, 86):\n# urls.append('http://www.phei.com.cn/module/goods/searchkey.jsp?Page='\n# +str(i)+\n# '&Page=2&searchKey=计算机')\n\n\n\n\n#print(urls)" }, { "alpha_fraction": 0.4748023748397827, "alphanum_fraction": 0.4901185631752014, "avg_line_length": 27.928571701049805, "blob_id": "bdb2d10f09ce0c5e1addabc30d7be82767969414", "content_id": "7377ea86429c47aacdd0b74fb385cdb71a6ef00a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2038, "license_type": "no_license", "max_line_length": 66, "num_lines": 70, "path": "/gevent_第三章.py", "repo_name": "Zephery/python_crawler", "src_encoding": "UTF-8", "text": "import gevent\nfrom gevent import monkey\nmonkey.patch_all()\nimport requests\nfrom bs4 import BeautifulSoup\nimport time\n\n\ndef format_str(s):\n return s.replace(\"\\n\", \"\").replace(\" \", \"\").replace(\"\\t\", \"\")\n\ndef get_urls_in_pages(from_page_num, to_page_num):\n urls = []\n search_word = '计算机'\n url_part_1 = 'http://www.phei.com.cn/module/goods/' \\\n 'searchkey.jsp?Page='\n url_part_2 = '&Page=2&searchKey='\n for i in range(from_page_num, to_page_num + 1):\n urls.append(url_part_1\n + str(i) +\n url_part_2 + search_word)\n all_href_list = []\n for url in urls:\n print(url)\n resp = requests.get(url)\n bs = BeautifulSoup(resp.text)\n a_list = bs.find_all('a')\n needed_list = []\n for a in a_list:\n if 'href' in a.attrs:\n href_val = a['href']\n title = a.text\n if 'bookid' in href_val and 'shopcar0.jsp' \\\n not in href_val and title != '':\n if [title, href_val] not in needed_list:\n needed_list.append([format_str(title),\n format_str(href_val)])\n all_href_list += needed_list\n all_href_file = open(str(from_page_num) + '_' +\n str(to_page_num) + '_' +\n 'all_hrefs.txt', 'w')\n for href in all_href_list:\n all_href_file.write('\\t'.join(href) + '\\n')\n all_href_file.close()\n print(from_page_num, to_page_num, len(all_href_list))\n\n\ndef gevent_test():\n\n t1 = time.time()\n page_ranges_lst = [\n (1, 10),\n (11, 20),\n (21, 30),\n (31, 40),\n ]\n\n jobs = []\n for page_range in page_ranges_lst:\n jobs.append(gevent.spawn(get_urls_in_pages,\n page_range[0], page_range[1]))\n\n gevent.joinall(jobs)\n\n t2 = time.time()\n print('使用时间', t2 - t1)\n return t2 - t1\n\nif __name__ == '__main__':\n gevent_test()" }, { "alpha_fraction": 0.8095238208770752, "alphanum_fraction": 0.8095238208770752, "avg_line_length": 20, "blob_id": "35caa2af1839ac20413425a8d85f96b746c9b85e", "content_id": "82bb44b1827682f2aea30cf90611b998f833aa5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 45, "license_type": "no_license", "max_line_length": 20, "num_lines": 1, "path": "/README.md", "repo_name": "Zephery/python_crawler", "src_encoding": "UTF-8", "text": "# python数据抓取技术与实战》源码\n" }, { "alpha_fraction": 0.5318087339401245, "alphanum_fraction": 0.545945942401886, "avg_line_length": 30.644737243652344, "blob_id": "e7d2be668399a02232baab2a3b616f9875acebb3", "content_id": "665d11cf6b163b2a5e8f43d03a4a5e49b8275ec4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2411, "license_type": "no_license", "max_line_length": 98, "num_lines": 76, "path": "/rpc_crawler.py", "repo_name": "Zephery/python_crawler", "src_encoding": "UTF-8", "text": "from xmlrpc.client import ServerProxy\nfrom bs4 import BeautifulSoup\nimport threading\nimport time\n\n\ndef get_server_ips(sfile):\n server_ips = []\n with open(sfile, 'r', encoding='utf8') as f:\n for ind, line in enumerate(f.readlines()):\n ip = line.strip()\n server_ips.append([ind, ip])\n return server_ips\n\n\ndef format_str(s):\n return s.replace(\"\\n\", \"\").replace(\" \", \"\").replace(\"\\t\", \"\")\n\n\ndef get_urls_in_pages(from_page_num, to_page_num, remote_ip):\n server = ServerProxy(remote_ip[1])\n urls = []\n search_word = '计算机'\n url_part_1 = 'http://www.phei.com.cn/model/goods/searchkey.jsp?Page='\n url_part_2 = '&Page=2&searchkey='\n for i in range(from_page_num, to_page_num + 1):\n urls.append(url_part_1 + str(i) + url_part_2 + search_word)\n all_href_list = []\n for url in urls:\n print(remote_ip[1], url)\n rstr = server.get('username', url, {}, {})\n bs = BeautifulSoup(rstr)\n a_list = bs.find_all('a')\n needed_list = []\n for a in a_list:\n if 'href' in a.attrs:\n href_val = a['href']\n title = a.text\n if 'bookid' in href_val and 'shopcar().jsp' not in href_val and title != '':\n if [title, href_val] not in needed_list:\n needed_list.append([format_str(title), format_str(href_val)])\n all_href_list += needed_list\n all_href_file = open(str(from_page_num) + '_' + str(to_page_num) + '_' + 'all_hrefs.txt', 'w')\n for href in all_href_list:\n all_href_file.writable('\\t'.join(href) + '\\n')\n all_href_file.close()\n print(from_page_num, to_page_num, len(all_href_list))\n\n\ndef multiple_thread_test():\n server_ips = get_server_ips('remotes')\n server_cnt = len(server_ips)\n t1 = time.time()\n page_range_list = [\n (1, 10),\n (11, 20),\n (21, 30),\n (31, 40)\n ]\n th_lst = []\n for ind, page_range in enumerate(page_range_list):\n th = threading.Thread(target=get_urls_in_pages,\n args=(page_range[0], page_range[1], server_ips[ind % server_cnt]))\n th_lst.append(th)\n for th in th_lst:\n th.start()\n for th in th_lst:\n th.join()\n t2 = time.time()\n print('used time1:', t2 - t1)\n return t2 - t1\n\n\nif __name__ == '__main__':\n mt = multiple_thread_test()\n print('mt', mt)\n" } ]
13
alexisjcarr/Sprint-Challenge--Data-Structures-Python
https://github.com/alexisjcarr/Sprint-Challenge--Data-Structures-Python
45b29dc61eeb88c454a54207f9ef99b677fa83a9
fbeca48826e54cc4abcbb999f4a3849064c4f6ef
9ca413194f3a10ff154832d17b5a7ac23b60d951
refs/heads/master
2022-11-15T20:37:17.612465
2020-07-13T01:03:35
2020-07-13T01:03:35
275,682,490
0
0
null
2020-06-28T22:57:06
2020-06-28T22:57:08
2020-07-13T01:03:35
null
[ { "alpha_fraction": 0.6296119093894958, "alphanum_fraction": 0.6559655070304871, "avg_line_length": 29.246376037597656, "blob_id": "1fdff15bdf19b36ddb39fcc4923171ed68edcb45", "content_id": "6c62c23bebcd6852a2a087c3299fd05d2f22ac56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2087, "license_type": "no_license", "max_line_length": 94, "num_lines": 69, "path": "/names/names.py", "repo_name": "alexisjcarr/Sprint-Challenge--Data-Structures-Python", "src_encoding": "UTF-8", "text": "import time\nfrom binary_search_tree import BSTNode\n\nstart_time = time.time()\n\nf = open('names_1.txt', 'r')\nnames_1 = f.read().split(\"\\n\") # List containing 10000 names\nf.close()\n\nf = open('names_2.txt', 'r')\nnames_2 = f.read().split(\"\\n\") # List containing 10000 names\nf.close()\n\nduplicates = [] # Return the list of duplicates in this data structure\n\n# Replace the nested for loops below with your improvements\n# runtime for original code was ~ 6 seconds\n# runtime complexity for original code is O(n^2)\n\n# for name_1 in names_1:\n# for name_2 in names_2:\n# if name_1 == name_2:\n# duplicates.append(name_1)\n\n# runtime for new code was ~ 0.14 seconds\n# runtime complexity was \n# bst = BSTNode('root')\n# [bst.insert(name_1) for name_1 in names_1]\n# # for name_1 in names_1: # n\n# # bst.insert(name_1) # n\n\n# [duplicates.append(name_2) for name_2 in names_2 if bst.contains(name_2)]\n# for name_2 in names_2: # n\n# if bst.contains(name_2): \n# duplicates.append(name_2) # 1\n\n# # O(n^2) + O(n) => n(n+1)\n\n# ---------- Stretch Goal -----------\n# Python has built-in tools that allow for a very efficient approach to this problem\n# What's the best time you can accomplish? Thare are no restrictions on techniques or data\n# structures, but you may not import any additional libraries that you did not write yourself.\n\n# stretch\n# If I had time to write it out, I would:\n# Add names_1 into a list and add names_2 into a list\n# Append the lists\n# sort the lists\n# iterate through with a list comp to and check all the instances\n# where duplicates showed up and append them to duplicates\n\nnames = names_1 + names_2\nnames.sort()\n\nfor idx, name in enumerate(names):\n try:\n if name == names[idx + 1]:\n duplicates.append(name)\n except IndexError:\n break\n\nend_time = time.time()\nprint (f\"{len(duplicates)} duplicates:\\n\\n{', '.join(duplicates)}\\n\\n\")\nprint (f\"runtime: {end_time - start_time} seconds\")\n\n# for name_1 in names_1:\n# for name_2 in names_2:\n# if name_1 == name_2:\n# duplicates.append(name_1)\n" }, { "alpha_fraction": 0.48853209614753723, "alphanum_fraction": 0.49770641326904297, "avg_line_length": 19.809524536132812, "blob_id": "5659c7606036c6aab343c65108828b640b3a13be", "content_id": "e7c44076ddefab2a88f101c5eaefb17a67d02987", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 436, "license_type": "no_license", "max_line_length": 37, "num_lines": 21, "path": "/reverse/stack.py", "repo_name": "alexisjcarr/Sprint-Challenge--Data-Structures-Python", "src_encoding": "UTF-8", "text": "class Stack:\n def __init__(self):\n self.storage = []\n self.size = len(self.storage)\n\n def __len__(self):\n return self.size\n\n def push(self, value):\n self.storage.append(value)\n self.size += 1\n\n def pop(self):\n if self.size == 0:\n return\n val = self.storage.pop(-1)\n self.size -= 1\n return val\n\n def __repr__(self):\n return f'{self.storage}'" }, { "alpha_fraction": 0.5071210861206055, "alphanum_fraction": 0.5091556310653687, "avg_line_length": 20.139785766601562, "blob_id": "c11923aa54ad3f09574c174bd5a45c3db1b163f4", "content_id": "ffbcd92888692625c5de04b2e31c8d24c8eefb7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1966, "license_type": "no_license", "max_line_length": 87, "num_lines": 93, "path": "/reverse/reverse.py", "repo_name": "alexisjcarr/Sprint-Challenge--Data-Structures-Python", "src_encoding": "UTF-8", "text": "from stack import Stack\n\nclass Node:\n def __init__(self, value=None, next_node=None):\n self.value = value\n self.next_node = next_node\n\n def get_value(self):\n return self.value\n\n def get_next(self):\n return self.next_node\n\n def set_next(self, new_next):\n self.next_node = new_next\n\n def __repr__(self):\n return f'value: {self.value}'\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n\n def add_to_head(self, value):\n node = Node(value)\n\n if self.head is not None:\n node.set_next(self.head)\n\n self.head = node\n\n def contains(self, value):\n if not self.head:\n return False\n\n current = self.head\n\n while current:\n if current.get_value() == value:\n return True\n\n current = current.get_next()\n\n return False\n\n def reverse_list(self, node, s_=None):\n \"\"\"\n every node can be added to a stack and then removed one by one and links set up\n \"\"\"\n if self.head is None:\n return\n\n if self.head.next_node is None:\n return\n\n if s_ is None:\n s_ = Stack()\n \n current = node\n\n while current.next_node is not None:\n s_.push(current)\n current = current.next_node\n\n s_.push(current)\n\n self.head = s_.pop()\n node_2 = s_.pop()\n self.head.next_node = node_2\n\n new_current = node_2\n\n while s_.size > 0:\n node = s_.pop()\n new_current.next_node = node\n new_current = node\n\n new_current.next_node = s_.pop()\n\n def __repr__(self):\n ll_rep = list()\n curr = self.head\n\n if self.head is None:\n return '[]'\n\n while curr.next_node:\n ll_rep.append(curr.value)\n curr = curr.next_node\n\n ll_rep.append(curr.value)\n\n return f'{ll_rep}'\n" } ]
3
smwahl/PlLayer
https://github.com/smwahl/PlLayer
86b2c0a34e3cf9a3d205d31ad518bafab6945024
888ebf9d36187fe9686e2994dc791bce49c25270
c8b816cf1dc0ee50c16a8eae7e7745bd6469aae5
refs/heads/master
2021-01-25T08:48:45.189578
2013-10-15T05:35:08
2013-10-15T05:35:08
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.75, "alphanum_fraction": 0.75, "avg_line_length": 28, "blob_id": "40df84f23aa7bdf978255fe202348bc7a46afb94", "content_id": "a9f6153bea4ec3fe0bac1690fce2acba89c8a4b4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 116, "license_type": "permissive", "max_line_length": 98, "num_lines": 4, "path": "/README.md", "repo_name": "smwahl/PlLayer", "src_encoding": "UTF-8", "text": "PlLayer\n=======\n\nModule for to follow the thermal evolution of a model planet made of a number of different layers.\n" }, { "alpha_fraction": 0.6192676424980164, "alphanum_fraction": 0.6211158633232117, "avg_line_length": 32.2961540222168, "blob_id": "6da4a4fdc6e9cd1ad89c71ca75cea36515203653", "content_id": "766e58318c2ba1fb73294086d32f76b950362d56", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8657, "license_type": "permissive", "max_line_length": 104, "num_lines": 260, "path": "/outline.py", "repo_name": "smwahl/PlLayer", "src_encoding": "UTF-8", "text": "import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\nimport matplotlib\n\nfrom copy import deepcopy\n\n\nclass planet\n ''' Represents a snapshot of an evoloving planet, with methods\n for comparing different snapshots and relating thermal evolution to \n time.'''\n\n def __init__(self, params=None, pcopy=None):\n ''' Create planet snapshot, either with new parameters or with \n another planet object.'''\n self.layers = []\n self.boundaries = []\n self.mass = None\n self.radius = None\n # tracks whether structure (radii,T-profiles) have been calculated since modifications were made\n self.structured = False \n if not pcopy is none:\n self.layers = deepcopy(pcopy.layers)\n self.boundaries = deepcopy(pcopy.boundaries)\n self.mass = deepcopy(pcopy.mass)\n self.radius = deepcopy(pcopy.layers)\n\n def setLayers(self,layers):\n ''' Define the layers to be included in the planet snapshot.\n Note: incormation not copied'''\n self.layers = layers\n\n # add layers consistant with the boundaries\n self.boundaries = []\n for layer in layers:\n lbounds = layer.boundaries\n self.boundaries += [ lb for lb in lbounds if lb not in self.boundaries ]\n\n def setBoundaries(self,boundaries):\n ''' Define the layers to be included in the planet snapshot.\n Note: Information not copied'''\n self.boundaries = boundaries\n\n # add layers consistant with the boundaries\n self.layers = []\n for bound in boundaries:\n blayers = bound.layers\n self.layers += [ bl for bl in blayers if bl not in self.layers ]\n\n # Following functions will probably be feature of the more specific model,\n # might want to add placeholder functions, however.\n\n# def stepT(dT,boundary):\n# ''' Simulated timestep in which a boundaries lower temperature is\n# changed by dT'''\n\n# def QtoTime(self,dQ):\n# ''' Placeholder, should be defined by specific model '''\n\n# def diff(comp_snapshot):\n# ''' Compare energy and entropy budgets of various layers. Relates the\n# difference to a heat flow for one snapshot to evolve into the previous one.'''\n\n# def structure(T,boundary):\n# ''' Integrate Strucuture, specifing the temperature at a boundary '''\n\n def budgets():\n ''' Report integrated energy and entropy budgets for layers in the planet'''\n pass\n\nclass xlznCorePlanet(planet):\n ''' Represent particular situation of a crystallizing metallic core with a \n simple model for mantle evoloution'''\n \n def __init__(self,planet_file=None,pcopy=None):\n ''' Initizialize xlznCorePlanet object. Will eventually want to take input\n file names as arguments.'''\n \n if not pcopy is None:\n self.mantle = deepcopy(pcopy.mantle)\n self.core = deepcopy(pcopy.core)\n self.layers = deepcopy(pcopy.layers)\n self.boundaries = deepcopy(pcopy.boundaries)\n self.surface = deepcopy(pcopy.surface)\n self.cmb = deepcopy(pcopy.cmb)\n self.icb = deepcopy(pcopy.icb)\n self.center = deepcopy(pcopy.center)\n self.mass = pcopy.mass\n self.radius = pcopy.radius\n self.mantle_density = pcopy.mantle_density\n self.core_mass = pcopy.core_mass\n self.structured = pcopy.structured\n return None\n\n # Define materials from text files\n rock = material('simpleSilicateMantle.txt')\n liqFeS = material('binaryFeS.txt',mtype='liquid')\n solFe = material('simpleSolidIron.txt')\n \n # Define melting/solidifcation relationships under consideration\n liqFeS.interpLiquidus('FeS',solFe)\n\n self.mantle = layer('mantle',material=rock)\n self.core = xlznLayer('core', material=liqFeS, layernames=['outer_core','inner_core'],\n boundnames=['icb'])\n\n # set list of layers (self.core.layers should initially return a sinlge liquid layer\n self.layers = [self.mantle] + self.core.layers\n \n # set list of boundaries\n self.boundaries = GenerateBoundaries(self.layers,['surface','cmb','center'])\n self.surface = boundaries[0], self.cmb = boundaries[1], self.center = boundaries[-1]\n self.icb = None # indicates icb has yet to form\n\n # read in parameters from file and decide whether this is new planet or a continuation\n # at a different condition\n try:\n params = parseParamFile(open(planet_file,'r'))\n except:\n raise Exception('File not found: {}'.format(planet_file))\n\n try:\n cmb.r = params.Rcore\n self.mass = params.Mplanet\n self.radius = params.Rplanet\n core_radius = params.Rcore\n\n self.cmb.r = core_radius\n self.surface.r = self.radius\n self.mantle_density = None\n self.core_mass = None\n\n self.center.P = P0\n self.cmb.T = params.Tcmb\n smode = 'initial'\n except:\n try:\n self.mass = params.Mplanet\n self.mantle_density = params.rhomantle\n self.core_mass = params.Mcore\n self.core.M = core_mass\n\n self.center.P = P0\n self.cmb.T = params.Tcmb\n\n self.radius = None\n\n smode = 'cont'\n except:\n raise Exception('Invalid input file.')\n\n # Integrate structure (making entire stucture consistant with starting values\n success = self.structure(mode=smode)\n\n # should check to make sure the integration succeeded\n if success:\n\n self.radius = self.surface.r\n #self.mantle_density = \n self.core_mass = pcopy.core.M\n self.structured = pcopy.structured\n\n Mplanet = self.mass\n Mcore = self.core_mass\n rhomantle = self.mantle_density\n PO = self.center.P\n params = [ Mplanet Mcore rhomantle P0]\n\n # write new parameter file to run a planet with consistent mass and mantle density\n writeParamFile(open('./xlzncoreplanet_cont.txt','w'),params)\n return None\n else\n raise Exception\n\n\n\n \n\n \n\n\n \n\n\nclass layer(object):\n ''' A layer is a portion of a planet with an adiabatic temperature profile,\n composed of a single material '''\n\n def __init__(self,name='',mass=None,material=None,comp=None):\n self.name = name\n self.boundaries = None\n self.mass = mass\n self.material = material\n self.comp = comp\n\n def specEnergy():\n pass\n\n\n\n\nclass liquidLayer(layer):\n ''' A liquid layer has a specific entropy which can be related to viscous and/or\n ohmic dissipation.'''\n\n def specEntropy():\n pass\n\n\nclass xlznLayer(object):\n ''' Defines a layer of liquid material that is free to crystalize upon cooling.\n Contains a list of solids with a corresponding liquidus. Upon intersection \n of the liquidus, there are three possible occurances upon intersection with \n a liquidus.\n 1) solid more dense and adiabat remains below liquidus to the bottom of the\n layer, forming a settled region at the bottom.\n 2) Identical case with less dense settling to the top\n 3) 'Snow' regime, where sink/floating crystals would remelt before settling\n for 1) and 2) a separate solid layer is formed. For 3) the liquid adiabat\n is instead constrained to follow the liquidus'''\n self.name\n self.liquid\n self.solids\n self.comp # Mass ratio of different components\n self.mass\n self.liquidi # a liquidi corresponding to each solid phase\n self.adiabat # a modified adiabat, following the liquidus in a 'snow' region.\n\n\nclass boundary(object):\n\n self.T # upper and lower temperature\n self.d\n self.layers\n\n def calcEnergy():\n pass\n\n def calcEntropy():\n pass\n\n\nclass Material(object):\n '''Class for keeping track of various physical properties of a material and how\n these vary as a function of P, T and composition.'''\n\n self.liquidus\n self.components\n\n self.td_params # holds functions for returning thermodynamic parameters\n\n def interp_liquidus(data_file,solid):\n pass\n\n def set_td_params(self,param_file):\n pass\n\ndef shellIntegral(funcs,r0=0.,r1=1.,tols=[],limits=[]):\n ''' Integrate an arbitrary number of function\n" } ]
2
EdithAntunes/mypackage2
https://github.com/EdithAntunes/mypackage2
0f1407d7497f08c348a4254f2a7cf29577249efa
e53fc8732fe89b49910a725ee1a5f804874a30d5
ba20da5c2f75f9a56968e8090ce8f718310ee2a9
refs/heads/master
2023-04-11T14:24:18.156183
2021-04-22T06:38:01
2021-04-22T06:38:01
360,417,556
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.782608687877655, "alphanum_fraction": 0.8260869383811951, "avg_line_length": 23, "blob_id": "76db63f90bccc0f78d984bff05c7cebe0124b8a5", "content_id": "e9748223450f2f08fc078adcf4b8b0dbae326b92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 23, "license_type": "no_license", "max_line_length": 23, "num_lines": 1, "path": "/__init__.py", "repo_name": "EdithAntunes/mypackage2", "src_encoding": "UTF-8", "text": "from . import myModule2" }, { "alpha_fraction": 0.4725050926208496, "alphanum_fraction": 0.490835040807724, "avg_line_length": 17.923076629638672, "blob_id": "6140cf1d9bde39ab8de2491cc39493b8b55ed913", "content_id": "eff94d55f64408bbba3a1ac3bdf31c8e163d914d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 491, "license_type": "no_license", "max_line_length": 60, "num_lines": 26, "path": "/myModule2.py", "repo_name": "EdithAntunes/mypackage2", "src_encoding": "UTF-8", "text": "def fibonacci(n):\n\n \"\"\"\n Calculate nth term in fibonacci sequence\n \n Args:\n n (int): nth term in fibonacci sequence to calculate\n \n Returns:\n int: nth term of fibonacci sequence,\n equal to sum of previous two terms\n \n Examples:\n >>> fibonacci(1)\n 1 \n >> fibonacci(2)\n 1\n >> fibonacci(3)\n 2\n \"\"\"\n\n if n <= 1:\n return n\n\n else:\n return fibonacci(n - 1) + fibonacci(n - 2)" } ]
2
bsipocz/pytest-mpl
https://github.com/bsipocz/pytest-mpl
8344ce4e3954d99470cd8b35bf557ff76338acff
aef6c30ebbf31730816b7a9dfb717e2e93a038b1
0d25c48ed0b4d3314b4e8e857fce1816cedd9256
refs/heads/master
2021-01-21T08:51:29.850298
2015-06-25T21:34:23
2015-06-25T21:34:23
38,079,111
1
0
null
2015-06-25T23:08:07
2015-06-25T19:35:52
2015-06-25T22:35:17
null
[ { "alpha_fraction": 0.7177146077156067, "alphanum_fraction": 0.7250195741653442, "avg_line_length": 32.3304328918457, "blob_id": "7ad376c6e9ecd06eb6748cde84e8b689e890f9ca", "content_id": "638e9c23018ad02d37a2208824b24fa372f4bdf5", "detected_licenses": [ "BSD-3-Clause", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3833, "license_type": "permissive", "max_line_length": 273, "num_lines": 115, "path": "/README.md", "repo_name": "bsipocz/pytest-mpl", "src_encoding": "UTF-8", "text": "[![Travis Build Status](https://travis-ci.org/astrofrog/pytest-mpl.svg?branch=master)](https://travis-ci.org/astrofrog/pytest-mpl) \n[![AppVeyor Build status](https://ci.appveyor.com/api/projects/status/mf7hs44scg5mvcyo?svg=true)](https://ci.appveyor.com/project/astrofrog/pytest-mpl)\n\n\nAbout\n-----\n\nA plugin to faciliate image comparison for [Matplotlib](http://www.matplotlib.org) figures in pytest (which\nuses some of the Matplotlib image comparison functions behind the scenes).\n\nMatplotlib includes a number of test utilities and decorators, but these are geared towards the [nose](http://nose.readthedocs.org/) testing framework. Pytest-mpl makes it easy to compare figures produced by tests to reference images when using [pytest](http://pytest.org).\n\nFor each figure to test, the reference image is substracted from the generated image, and the RMS of the residual is compared to a user-specified tolerance. If the residual is too large, the test will fail (this is implemented in Matplotlib).\n\nFor more information on how to write tests to do this, see the **Using** section below.\n\nInstalling\n----------\n\nThis plugin is compatible with Python 2.6, 2.7, and 3.3 and later, and requires [pytest](http://pytest.org), [matplotlib](http://www.matplotlib.org) and\n[nose](http://nose.readthedocs.org/) to be installed (nose is required by Matplotlib).\n\nTo install, you can do:\n\n pip install pytest-mpl\n\nYou can check that the plugin is registered with pytest by doing:\n\n py.test --version\n \nwhich will show a list of plugins:\n \n This is pytest version 2.7.1, imported from ...\n setuptools registered plugins:\n pytest-mpl-0.1 at ...\n\nUsing\n-----\n\nTo use, you simply need to mark the function where you want to compare images\nusing ``@pytest.mark.mpl_image_compare``, and make sure that the function\nreturns a Matplotlib figure (or any figure object that has a ``savefig``\nmethod):\n\n```python\nimport pytest\nimport matplotlib.pyplot as plt\n\[email protected]_image_compare\ndef test_succeeds():\n fig = plt.figure()\n ax = fig.add_subplot(1,1,1)\n ax.plot([1,2,3])\n return fig\n```\n\nTo generate the baseline images, run the tests with the ``--mpl-generate-path``\noption with the name of the directory where the generated images should be\nplaced:\n\n py.test --mpl-generate-path=baseline\n\nIf the directory does not exist, it will be created. Once you are happy with\nthe generated images, you should move them to a sub-directory called\n``baseline`` (this name is configurable, see below) in the same directory as\nthe tests (or you can generate them there directly). You can then run the tests\nsimply with:\n\n py.test --mpl\n\nand the tests will pass if the images are the same. If you omit the ``--mpl``\noption, the tests will run but will only check that the code runs without\nchecking the output images.\n\nOptions\n-------\n\nThe ``@pytest.mark.mpl_image_compare`` marker can take an argument which is the\nRMS tolerance (which defaults to 10):\n\n```python\[email protected]_image_compare(tolerance=20)\ndef test_image():\n ...\n```\n\nYou can also pass keyword arguments to ``savefig`` by using ``savefig_kwargs``:\n\n```python\[email protected]_image_compare(savefig_kwargs={'dpi':300})\ndef test_image():\n ...\n```\n\nOther options include the name of the baseline directory (which defaults to\n``baseline`` ) and the filename of the plot (which defaults to the name of the\ntest with a ``.png`` suffix):\n\n```python\[email protected]_image_compare(baseline_dir='baseline_images',\n filename='other_name.png')\ndef test_image():\n ...\n```\n\nRunning the tests\n-----------------\n\nTo run the tests, first install the plugin then do:\n\n cd tests\n py.test --mpl\n\nThe reason for having to install the plugin first is to ensure that the plugin\nis correctly loaded as part of the test suite.\n" }, { "alpha_fraction": 0.6058365702629089, "alphanum_fraction": 0.6272373795509338, "avg_line_length": 22.363636016845703, "blob_id": "f66fd0ccbd94492561e89e2e10cb3c77209302b6", "content_id": "6b2c936c771117f7249eb1fe7f207a6b36cee8e9", "detected_licenses": [ "BSD-3-Clause", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2570, "license_type": "permissive", "max_line_length": 104, "num_lines": 110, "path": "/tests/test_pytest_mpl.py", "repo_name": "bsipocz/pytest-mpl", "src_encoding": "UTF-8", "text": "import os\nimport sys\nimport subprocess\nimport tempfile\n\nimport pytest\nimport matplotlib.pyplot as plt\n\nPY26 = sys.version_info[:2] == (2, 6)\n\n\[email protected]_image_compare\ndef test_succeeds():\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n ax.plot([1, 2, 3])\n return fig\n\n\nclass TestClass(object):\n\n @pytest.mark.mpl_image_compare\n def test_succeeds(self):\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n ax.plot([1, 2, 3])\n return fig\n\n\[email protected]_image_compare(savefig_kwargs={'dpi': 30})\ndef test_dpi():\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n ax.plot([1, 2, 3])\n return fig\n\nTEST_FAILING = \"\"\"\nimport pytest\nimport matplotlib.pyplot as plt\[email protected]_image_compare\ndef test_fail():\n fig = plt.figure()\n ax = fig.add_subplot(1,1,1)\n ax.plot([1,2,2])\n return fig\n\"\"\"\n\n\ndef test_fails():\n\n tmpdir = tempfile.mkdtemp()\n\n test_file = os.path.join(tmpdir, 'test.py')\n with open(test_file, 'w') as f:\n f.write(TEST_FAILING)\n\n # If we use --mpl, it should detect that the figure is wrong\n code = subprocess.call('py.test --mpl {0}'.format(test_file), shell=True)\n assert code != 0\n\n # If we don't use --mpl option, the test should succeed\n code = subprocess.call('py.test {0}'.format(test_file), shell=True)\n assert code == 0\n\n\nTEST_GENERATE = \"\"\"\nimport pytest\nimport matplotlib.pyplot as plt\[email protected]_image_compare\ndef test_gen():\n fig = plt.figure()\n ax = fig.add_subplot(1,1,1)\n ax.plot([1,2,3])\n return fig\n\"\"\"\n\n\[email protected](\"PY26\")\ndef test_generate():\n\n tmpdir = tempfile.mkdtemp()\n\n test_file = os.path.join(tmpdir, 'test.py')\n with open(test_file, 'w') as f:\n f.write(TEST_GENERATE)\n\n gen_dir = os.path.join(tmpdir, 'spam', 'egg')\n\n # If we don't generate, the test will fail\n p = subprocess.Popen('py.test --mpl {0}'.format(test_file), shell=True,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n p.wait()\n assert b'Image file not found for comparison test' in p.stdout.read()\n\n # If we do generate, the test should succeed and a new file will appear\n code = subprocess.call('py.test --mpl-generate-path={0} {1}'.format(gen_dir, test_file), shell=True)\n assert code == 0\n assert os.path.exists(os.path.join(gen_dir, 'test_gen.png'))\n\n\[email protected]_image_compare(tolerance=20)\ndef test_tolerance():\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n ax.plot([1, 2, 2])\n return fig\n\n\ndef test_nofigure():\n pass\n" }, { "alpha_fraction": 0.7423580884933472, "alphanum_fraction": 0.7598253488540649, "avg_line_length": 27.5, "blob_id": "d2bf379c30b1a73eff4aa870d08b840b5261299e", "content_id": "18c2efa57f3908fc87743e70fc9bd48373f443f6", "detected_licenses": [ "BSD-3-Clause", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 229, "license_type": "permissive", "max_line_length": 88, "num_lines": 8, "path": "/.continuous-integration/travis/setup_environment_linux.sh", "repo_name": "bsipocz/pytest-mpl", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# Install conda\nwget http://repo.continuum.io/miniconda/Miniconda-latest-Linux-x86_64.sh -O miniconda.sh\nchmod +x miniconda.sh\n./miniconda.sh -b\nexport PATH=/home/travis/miniconda/bin:$PATH\nconda update --yes conda\n\n" }, { "alpha_fraction": 0.34285715222358704, "alphanum_fraction": 0.4571428596973419, "avg_line_length": 10.777777671813965, "blob_id": "51bf7b02c549ba05e9e587d5074d8db65ab886c8", "content_id": "d9d5e8e5da0ac66b96184a1b9317bec088b3ab51", "detected_licenses": [ "BSD-3-Clause", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 105, "license_type": "permissive", "max_line_length": 17, "num_lines": 9, "path": "/CHANGES.md", "repo_name": "bsipocz/pytest-mpl", "src_encoding": "UTF-8", "text": "0.2 (unreleased)\n----------------\n\n- No changes yet\n\n0.1 (2015-06-25)\n----------------\n\n- Initial version" }, { "alpha_fraction": 0.6472148299217224, "alphanum_fraction": 0.6525198817253113, "avg_line_length": 25.928571701049805, "blob_id": "85d2720ea0f74e59d4eacb68891937f4543817e8", "content_id": "e5a5cce1c9b056b674a61bb0514ccd772327baf6", "detected_licenses": [ "BSD-3-Clause", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 377, "license_type": "permissive", "max_line_length": 84, "num_lines": 14, "path": "/setup.py", "repo_name": "bsipocz/pytest-mpl", "src_encoding": "UTF-8", "text": "from setuptools import setup\n\nfrom pytest_mpl import __version__\n\nsetup(\n version=__version__,\n name=\"pytest-mpl\",\n description='pytest plugin to help with testing figures output from Matplotlib',\n packages = ['pytest_mpl'],\n license='BSD',\n author='Thomas Robitaille',\n author_email='[email protected]',\n entry_points = {'pytest11': ['pytest_mpl = pytest_mpl.plugin',]},\n)\n" } ]
5
ShangHaiPTM/node-cgns
https://github.com/ShangHaiPTM/node-cgns
517f415e9fa83515663cb8dd41f6fb35180f2137
e55307e955d1c755d9e06ff4e9db5e976099c81d
5ad6748cf00459d865b3293473d17b3be2f26b5f
refs/heads/master
2021-09-13T02:58:28.323180
2018-04-24T07:01:09
2018-04-24T07:01:09
104,696,735
0
1
null
2017-09-25T02:56:05
2018-04-24T03:44:26
2018-04-24T06:40:42
C++
[ { "alpha_fraction": 0.6600181460380554, "alphanum_fraction": 0.6727107763290405, "avg_line_length": 25.90243911743164, "blob_id": "7ca79100de883692be6b49f41a8463732231847f", "content_id": "e0e2bb6717cdb914b275eb5e2f363b52e0f39186", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2206, "license_type": "no_license", "max_line_length": 115, "num_lines": 82, "path": "/src/Grid.cc", "repo_name": "ShangHaiPTM/node-cgns", "src_encoding": "UTF-8", "text": "//\n// Created by Han Colin on 2017/12/29.\n//\n\n#include \"Grid.h\"\n#include \"helper.h\"\n#include \"v8Helper.h\"\n\nnamespace cgns {\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Maybe;\nusing v8::MaybeLocal;\nusing v8::Context;\nusing v8::Value;\nusing v8::String;\nusing v8::Object;\nusing v8::Number;\nusing v8::Function;\nusing v8::FunctionTemplate;\nusing v8::FunctionCallbackInfo;\nusing v8::Persistent;\n\nPersistent<Function> Grid::constructor;\n\nGrid::Grid() {\n}\n\nGrid::~Grid() {\n}\n\nvoid Grid::Init(Local<Object> exports) {\n Isolate *isolate = exports->GetIsolate();\n\n // Prepare constructor template\n Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);\n tpl->SetClassName(String::NewFromUtf8(isolate, \"CgnsZone\"));\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n constructor.Reset(isolate, tpl->GetFunction());\n exports->Set(String::NewFromUtf8(isolate, \"CgnsZone\"),\n tpl->GetFunction());\n}\n\nvoid Grid::New(const FunctionCallbackInfo<Value> &args) {\n Isolate *isolate = args.GetIsolate();\n\n if (args.IsConstructCall()) {\n Grid *obj = new Grid();\n obj->Wrap(args.This());\n args.GetReturnValue().Set(args.This());\n } else {\n Local<Context> context = isolate->GetCurrentContext();\n Local<Function> cons = Local<Function>::New(isolate, Grid::constructor);\n Local<Object> result = cons->NewInstance(context).ToLocalChecked();\n args.GetReturnValue().Set(result);\n }\n}\n\nLocal<Object> Grid::NewInstance(Local<Context> context, int handler, int baseIndex, int zoneIndex, int gridIndex) {\n Isolate *isolate = context->GetIsolate();\n Local<Function> cons = Local<Function>::New(isolate, Grid::constructor);\n Local<Object> result =\n cons->NewInstance(context).ToLocalChecked();\n\n Grid::Open(result, handler, baseIndex, zoneIndex, gridIndex);\n\n return result;\n}\n\nvoid Grid::Open(Local<Object> _this, int handler, int baseIndex, int zoneIndex, int gridIndex) {\n V_SET_BEGIN(_this);\n\n V_SET_NUMBER(_this, \"index\", gridIndex);\n\n char name[128];\n CGNS_CALL(cg_grid_read(handler, baseIndex, zoneIndex, gridIndex, name));\n V_SET_STRING(_this, \"name\", name);\n\n V_SET_END();\n}\n}\n" }, { "alpha_fraction": 0.5581668615341187, "alphanum_fraction": 0.5593419671058655, "avg_line_length": 28.379310607910156, "blob_id": "00f69a9bae49aedfae9eec0b79518e021a9ae4c5", "content_id": "ebeb761eb7c34ed75b4ca1f27d2328fc0dbdfb22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 851, "license_type": "no_license", "max_line_length": 110, "num_lines": 29, "path": "/src/helper.cc", "repo_name": "ShangHaiPTM/node-cgns", "src_encoding": "UTF-8", "text": "#include \"helper.h\"\n\nnamespace cgns {\n#if defined( _DEBUG )\nbool _cgns_IsError( const int error, const char* file, const int line, const char* func, const char* command )\n{\n if ( error == CG_OK ) { return false; }\n\n // Output message tag.\n std::string message_tag( \"CGNS ERROR\" );\n std::cerr << message_tag;\n\n // Output message with an error string.\n std::string error_string;\n const char* c = cg_get_error();\n while ( *c ) error_string += *c++;\n std::cerr << \": \" << error_string << std::endl;\n std::cerr << \"\\t\" << \"FILE: \" << file << \" (\" << line << \")\" << std::endl;\n std::cerr << \"\\t\" << \"FUNC: \" << func << std::endl;\n std::cerr << \"\\t\" << \"CGNS COMMAND: \" << command << std::endl;\n\n return true;\n}\n#endif // defined(_DEBUG)\n\nconst std::string indents(const int i) {\n return std::string(i * 2, ' ');\n}\n}" }, { "alpha_fraction": 0.5766363143920898, "alphanum_fraction": 0.591549277305603, "avg_line_length": 23.653060913085938, "blob_id": "54a19ab9f91e757a5b8cb32de878f970c443f8d7", "content_id": "d25971396842e5d72ee163761a04df075aca6526", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1207, "license_type": "no_license", "max_line_length": 44, "num_lines": 49, "path": "/src/cgns.cc", "repo_name": "ShangHaiPTM/node-cgns", "src_encoding": "UTF-8", "text": "#include <node/node.h>\n#include \"Doc.h\"\n#include \"Base.h\"\n#include \"Zone.h\"\n#include \"Grid.h\"\n#include \"Coord.h\"\n#include \"Solution.h\"\n#include \"v8Helper.h\"\n\nnamespace cgns {\nusing v8::Local;\nusing v8::Object;\n\nvoid InitAll(Local<Object> exports) {\n Doc::Init(exports);\n Base::Init(exports);\n Zone::Init(exports);\n Grid::Init(exports);\n Coord::Init(exports);\n Solution::Init(exports);\n\n V_ENUM_BEGIN(exports, \"SimulationType\");\n V_ENUM_ITEM(\"nullValue\", 0);\n V_ENUM_ITEM(\"userDefined\", 1);\n V_ENUM_ITEM(\"timeAccurate\", 2);\n V_ENUM_ITEM(\"nonTimeAccurate\", 3);\n V_ENUM_END();\n\n V_ENUM_BEGIN(exports, \"ZoneType\");\n V_ENUM_ITEM(\"nullValue\", 0);\n V_ENUM_ITEM(\"userDefined\", 1);\n V_ENUM_ITEM(\"structured\", 2);\n V_ENUM_ITEM(\"unstructured\", 3);\n V_ENUM_END();\n\n V_ENUM_BEGIN(exports, \"DataType\");\n V_ENUM_ITEM(\"nullValue\", 0);\n V_ENUM_ITEM(\"userDefined\", 1);\n V_ENUM_ITEM(\"integer\", 2);\n V_ENUM_ITEM(\"realSingle\", 3);\n V_ENUM_ITEM(\"realDouble\", 4);\n V_ENUM_ITEM(\"character\", 5);\n V_ENUM_ITEM(\"longInteger\", 6);\n V_ENUM_END();\n\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)\n}" }, { "alpha_fraction": 0.6904069781303406, "alphanum_fraction": 0.707848846912384, "avg_line_length": 23.571428298950195, "blob_id": "89ff552c6ba7c522ffdb0a1f83314ee00ec6db0c", "content_id": "a4daff46aaf18f1283de2102ad013c51ef643139", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 688, "license_type": "no_license", "max_line_length": 139, "num_lines": 28, "path": "/src/Zone.h", "repo_name": "ShangHaiPTM/node-cgns", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include \"cgnslib.h\"\n#include <iostream>\n#include <string>\n#include <node/node.h>\n#include <node/node_object_wrap.h>\n\nnamespace cgns {\nclass Zone : public node::ObjectWrap {\npublic:\n static void Init(v8::Local<v8::Object> exports);\n\n static v8::Local<v8::Object> NewInstance(v8::Local<v8::Context> context, int handler, int baseIndex, int zoneIndex, int cellDimension);\n\nprivate:\n explicit Zone();\n\n ~Zone();\n\n static void New(const v8::FunctionCallbackInfo<v8::Value> &args);\n\n static void Open(v8::Local<v8::Object> _this, int handler, int baseIndex, int zoneIndex, int cellDimension);\n\nprivate:\n static v8::Persistent<v8::Function> constructor;\n};\n}\n" }, { "alpha_fraction": 0.6593886613845825, "alphanum_fraction": 0.6797671318054199, "avg_line_length": 19.205883026123047, "blob_id": "8a5fd0a8e5e7b3baf8b9e029c236c255d23870fc", "content_id": "8b1c563bde99b3db680640554041d7356fd17dd4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 687, "license_type": "no_license", "max_line_length": 71, "num_lines": 34, "path": "/src/Doc.h", "repo_name": "ShangHaiPTM/node-cgns", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include \"cgnslib.h\"\n#include <iostream>\n#include <string>\n#include <node/node.h>\n#include <node/node_object_wrap.h>\n\nnamespace cgns {\nclass Doc : public node::ObjectWrap {\npublic:\n static void Init(v8::Local<v8::Object> exports);\n\nprivate:\n explicit Doc();\n\n ~Doc();\n\n static void New(const v8::FunctionCallbackInfo<v8::Value> &args);\n\n static void Open(const v8::FunctionCallbackInfo<v8::Value> &args);\n\n static void Close(const v8::FunctionCallbackInfo<v8::Value> &args);\n\n void open(v8::Local<v8::Object> _this, v8::Local<v8::String> path);\n\n void close();\n\nprivate:\n int m_handler;\n\n static v8::Persistent<v8::Function> constructor;\n};\n}\n" }, { "alpha_fraction": 0.6543933153152466, "alphanum_fraction": 0.6661087870597839, "avg_line_length": 26.802326202392578, "blob_id": "a78c411354c9caefa58c02b02de7a56205525762", "content_id": "ba758aa6147231661b9093e1f1e31f9ab57dc7bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2390, "license_type": "no_license", "max_line_length": 117, "num_lines": 86, "path": "/src/Coord.cc", "repo_name": "ShangHaiPTM/node-cgns", "src_encoding": "UTF-8", "text": "//\n// Created by Han Colin on 2017/12/29.\n//\n\n#include \"Coord.h\"\n#include \"helper.h\"\n#include \"v8Helper.h\"\n\nnamespace cgns {\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Maybe;\nusing v8::MaybeLocal;\nusing v8::Context;\nusing v8::Value;\nusing v8::String;\nusing v8::Object;\nusing v8::Number;\nusing v8::Function;\nusing v8::FunctionTemplate;\nusing v8::FunctionCallbackInfo;\nusing v8::Persistent;\n\nPersistent<Function> Coord::constructor;\n\nCoord::Coord() {\n}\n\nCoord::~Coord() {\n}\n\nvoid Coord::Init(Local<Object> exports) {\n Isolate *isolate = exports->GetIsolate();\n\n // Prepare constructor template\n Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);\n tpl->SetClassName(String::NewFromUtf8(isolate, \"CgnsZone\"));\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n constructor.Reset(isolate, tpl->GetFunction());\n exports->Set(String::NewFromUtf8(isolate, \"CgnsZone\"),\n tpl->GetFunction());\n}\n\nvoid Coord::New(const FunctionCallbackInfo<Value> &args) {\n Isolate *isolate = args.GetIsolate();\n\n if (args.IsConstructCall()) {\n Coord *obj = new Coord();\n obj->Wrap(args.This());\n args.GetReturnValue().Set(args.This());\n } else {\n Local<Context> context = isolate->GetCurrentContext();\n Local<Function> cons = Local<Function>::New(isolate, Coord::constructor);\n Local<Object> result = cons->NewInstance(context).ToLocalChecked();\n args.GetReturnValue().Set(result);\n }\n}\n\nLocal<Object> Coord::NewInstance(Local<Context> context, int handler, int baseIndex, int zoneIndex, int coordIndex) {\n Isolate *isolate = context->GetIsolate();\n Local<Function> cons = Local<Function>::New(isolate, Coord::constructor);\n Local<Object> result =\n cons->NewInstance(context).ToLocalChecked();\n\n Coord::Open(result, handler, baseIndex, zoneIndex, coordIndex);\n\n return result;\n}\n\nvoid Coord::Open(Local<Object> _this, int handler, int baseIndex, int zoneIndex, int coordIndex) {\n V_SET_BEGIN(_this);\n\n V_SET_NUMBER(_this, \"index\", coordIndex);\n\n char name[128];\n CGNS_ENUMT(DataType_t) dataType;\n CGNS_CALL( cg_coord_info( handler, baseIndex, zoneIndex, coordIndex, &dataType, name ) );\n V_SET_STRING(_this, \"name\", name);\n V_SET_NUMBER(_this, \"dataType\", dataType);\n\n // TODO: Read other properties.\n\n V_SET_END();\n}\n}" }, { "alpha_fraction": 0.6725219488143921, "alphanum_fraction": 0.6976160407066345, "avg_line_length": 20.54054069519043, "blob_id": "1b7e3357a522d5f930fc3850b3b8849c02d57ce0", "content_id": "fb0a30fb812ad02748d60c8fb733ecc0298e0aa1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 797, "license_type": "no_license", "max_line_length": 136, "num_lines": 37, "path": "/src/Coord.h", "repo_name": "ShangHaiPTM/node-cgns", "src_encoding": "UTF-8", "text": "//\n// Created by Han Colin on 2017/12/29.\n//\n\n#ifndef NODE_CGNS_COORD_H\n#define NODE_CGNS_COORD_H\n\n#include \"cgnslib.h\"\n#include <iostream>\n#include <string>\n#include <node/node.h>\n#include <node/node_object_wrap.h>\n\n\nnamespace cgns {\nclass Coord : public node::ObjectWrap {\npublic:\n static void Init(v8::Local<v8::Object> exports);\n\n static v8::Local<v8::Object> NewInstance(v8::Local<v8::Context> context, int handler, int baseIndex, int zoneIndex, int coordIndex);\n\nprivate:\n explicit Coord();\n\n ~Coord();\n\n static void New(const v8::FunctionCallbackInfo<v8::Value> &args);\n\n static void Open(v8::Local<v8::Object> _this, int handler, int baseIndex, int zoneIndex, int coordIndex);\n\nprivate:\n static v8::Persistent<v8::Function> constructor;\n};\n}\n\n\n#endif //NODE_CGNS_COORD_H\n" }, { "alpha_fraction": 0.6303894519805908, "alphanum_fraction": 0.6383866667747498, "avg_line_length": 28.050504684448242, "blob_id": "6e33b5ecca8ebd4823c943d4977882e8e1bdac09", "content_id": "abd5319ada3eb934a4e4805a738d11ccdb8ec4c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2876, "license_type": "no_license", "max_line_length": 92, "num_lines": 99, "path": "/src/Base.cc", "repo_name": "ShangHaiPTM/node-cgns", "src_encoding": "UTF-8", "text": "#include \"Base.h\"\n#include \"helper.h\"\n#include \"v8Helper.h\"\n#include \"Zone.h\"\n\nnamespace cgns {\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Maybe;\nusing v8::MaybeLocal;\nusing v8::Context;\nusing v8::Value;\nusing v8::String;\nusing v8::Object;\nusing v8::Number;\nusing v8::Function;\nusing v8::FunctionTemplate;\nusing v8::FunctionCallbackInfo;\nusing v8::Persistent;\n\nPersistent<Function> Base::constructor;\n\nBase::Base() {\n}\n\nBase::~Base() {\n}\n\nvoid Base::Init(Local<Object> exports) {\n Isolate *isolate = exports->GetIsolate();\n\n // Prepare constructor template\n Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);\n tpl->SetClassName(String::NewFromUtf8(isolate, \"CgnsBase\"));\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n constructor.Reset(isolate, tpl->GetFunction());\n exports->Set(String::NewFromUtf8(isolate, \"CgnsBase\"),\n tpl->GetFunction());\n}\n\nvoid Base::New(const FunctionCallbackInfo<Value> &args) {\n Isolate *isolate = args.GetIsolate();\n\n if (args.IsConstructCall()) {\n Base *obj = new Base();\n obj->Wrap(args.This());\n args.GetReturnValue().Set(args.This());\n } else {\n Local<Context> context = isolate->GetCurrentContext();\n Local<Function> cons = Local<Function>::New(isolate, Base::constructor);\n Local<Object> result = cons->NewInstance(context).ToLocalChecked();\n args.GetReturnValue().Set(result);\n }\n}\n\nLocal<Object> Base::NewInstance(Local<Context> context, int handler, int baseId) {\n Isolate *isolate = context->GetIsolate();\n Local<Function> cons = Local<Function>::New(isolate, Base::constructor);\n Local<Object> result =\n cons->NewInstance(context).ToLocalChecked();\n\n Base::Open(result, handler, baseId);\n\n return result;\n}\n\nvoid Base::Open(Local<Object> _this, int handler, int baseIndex) {\n V_SET_BEGIN(_this);\n\n V_SET_NUMBER(_this, \"index\", baseIndex);\n\n double id;\n CGNS_CALL(cg_base_id(handler, baseIndex, &id));\n V_SET_NUMBER(_this, \"id\", id);\n\n char name[128];\n int cellDim;\n int pyhsDim;\n CGNS_CALL(cg_base_read(handler, baseIndex, name, &cellDim, &pyhsDim));\n V_SET_STRING(_this, \"name\", name);\n V_SET_NUMBER(_this, \"cellDimension\", cellDim);\n V_SET_NUMBER(_this, \"physicalDimension\", pyhsDim);\n\n CGNS_ENUMT(SimulationType_t) simulationType;\n CGNS_CALL(cg_simulation_type_read(handler, baseIndex, &simulationType));\n V_SET_NUMBER(_this, \"simulationType\", simulationType);\n\n int nzones = 0;\n CGNS_CALL(cg_nzones(handler, baseIndex, &nzones));\n V_ARRAY_BEGIN(_this, \"zones\");\n for (int i = 0; i < nzones; i++) {\n V_ARRAY_ADD(Zone::NewInstance(__context, handler, baseIndex, i+1, cellDim));\n }\n V_ARRAY_END();\n\n V_SET_END();\n}\n}\n" }, { "alpha_fraction": 0.5585365891456604, "alphanum_fraction": 0.5707316994667053, "avg_line_length": 18.571428298950195, "blob_id": "65d24141ad37c29a4d450b13802d2b51f82b735d", "content_id": "ac19148f97f31ff48966731a73330a1cb092b0b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 410, "license_type": "no_license", "max_line_length": 41, "num_lines": 21, "path": "/CMakeLists.txt", "repo_name": "ShangHaiPTM/node-cgns", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.8)\nproject(node_cgns)\n\nset(CMAKE_CXX_STANDARD 11)\n\nset(SOURCE_FILES\n src/Base.cc\n src/Base.h\n src/cgns.cc\n src/Doc.cc\n src/Doc.h\n src/helper.cc\n src/helper.h\n src/v8Helper.h\n src/Zone.cc\n src/Zone.h\n src/Grid.cc\n src/Coord.cc\n src/Solution.cc)\n\nadd_executable(node_cgns ${SOURCE_FILES})" }, { "alpha_fraction": 0.4428997039794922, "alphanum_fraction": 0.4428997039794922, "avg_line_length": 28.647058486938477, "blob_id": "aeea333cdeb5429f5cce5f44b56f1e58b3658b6c", "content_id": "11285a24431f64e60add64c570e400d962dbd6b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1007, "license_type": "no_license", "max_line_length": 109, "num_lines": 34, "path": "/src/helper.h", "repo_name": "ShangHaiPTM/node-cgns", "src_encoding": "UTF-8", "text": "/*****************************************************************************/\n/**\n * @file CGNSLib.h\n * @author Naohisa Sakamoto\n */\n/*----------------------------------------------------------------------------\n *\n * Copyright (c) Visualization Laboratory, Kyoto University.\n * All rights reserved.\n * See http://www.viz.media.kyoto-u.ac.jp/kvs/copyright/ for details.\n *\n * $Id$\n */\n/*****************************************************************************/\n#pragma once\n\n#include <cgnslib.h>\n#include <iostream>\n#include <string>\n\nnamespace cgns {\n\n#if defined(_DEBUG)\nbool _cgns_IsError(const int error, const char *file, const int line, const char *func, const char *command);\n#define CGNS_CALL(command) \\\n if (_cgns_IsError(command, __FILE__, __LINE__, __func__, #command)) \\\n { /*KVS_BREAKPOINT;*/ \\\n }\n#else\n#define CGNS_CALL(command) (command)\n#endif // _DEBUG\n\nconst std::string indents(const int i);\n}" }, { "alpha_fraction": 0.5350978374481201, "alphanum_fraction": 0.547468364238739, "avg_line_length": 40.89156723022461, "blob_id": "3b91ed04f76486fa203765e0d6527b3e1874d539", "content_id": "43549ecac426c8a63d085750548dcb3e333f2b06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3476, "license_type": "no_license", "max_line_length": 128, "num_lines": 83, "path": "/src/v8Helper.h", "repo_name": "ShangHaiPTM/node-cgns", "src_encoding": "UTF-8", "text": "#pragma once\n\n#include <iostream>\n#include <node/node.h>\n\nnamespace cgns {\ninline bool isTrue(v8::Maybe<bool> value) {\n return value.IsJust() && value.ToChecked();\n}\n\ninline bool isFalse(v8::Maybe<bool> value) {\n return value.IsJust() && !value.ToChecked();\n}\n\ninline bool isNotTrue(v8::Maybe<bool> value) {\n return value.IsNothing() || !value.ToChecked();\n}\n\ninline bool isNotFalse(v8::Maybe<bool> value) {\n return value.IsNothing() || value.ToChecked();\n}\n\ninline v8::Maybe<bool>\n_v8_IsError(v8::Maybe<bool> r, const char *file, const int line, const char *func, const char *command) {\n if (isTrue(r)) {\n return r;\n }\n\n std::string message_tag(\"V ERROR \\n\");\n std::cerr << message_tag;\n\n // Output message with an error string.\n std::cerr << \"\\t\"\n << \"FILE: \" << file << \" (\" << line << \")\" << std::endl;\n std::cerr << \"\\t\"\n << \"FUNC: \" << func << std::endl;\n std::cerr << \"\\t\"\n << \"COMMAND: \" << command << std::endl;\n return r;\n}\n\n#define V_CALL(command) _v8_IsError((command), __FILE__, __LINE__, __func__, #command)\n\n#define V_SET_BEGIN(_this) \\\n { \\\n v8::Local<v8::Object> __this = _this; \\\n v8::Isolate *__isolate = __this->GetIsolate(); \\\n v8::Local<v8::Context> __context = __isolate->GetCurrentContext()\n\n#define V_SET(_this, name, value) V_CALL(_this->Set(__context, v8::String::NewFromUtf8(__isolate, name), value))\n#define V_SET_NUMBER(_this, name, value) V_SET(_this, name, v8::Number::New(__isolate, value))\n#define V_SET_STRING(_this, name, value) V_SET(_this, name, v8::String::NewFromUtf8(__isolate, value))\n\n#define V_SET_END() }\n\n#define V_ARRAY_BEGIN(_this, name) \\\n{ \\\n v8::Local<v8::Array> __array = v8::Array::New(__isolate); \\\n V_SET(_this, name, __array); \\\n int __arrayIndex = 0\n\n#define V_ARRAY_SET(index, item) V_CALL(__array->Set(__context, v8::Number::New(__isolate, index), item))\n#define V_ARRAY_SET_NUMBER(index, item) V_ARRAY_SET(index, v8::Number::New(__isolate, item))\n#define V_ARRAY_SET_STRING(index, item) V_ARRAY_SET(index, v8::String::NewFromUtf8(__isolate, item))\n#define V_ARRAY_ADD(item) V_ARRAY_SET(__arrayIndex++, item)\n#define V_ARRAY_ADD_NUMBER(item) V_ARRAY_ADD(v8::Number::New(__isolate, item))\n#define V_ARRAY_ADD_STRING(item) V_ARRAY_ADD(v8::String::NewFromUtf8(__isolate, item))\n\n#define V_ARRAY_END() }\n\n#define V_ENUM_BEGIN(exports, enumName) \\\n { \\\n v8::Isolate *__isolate = exports->GetIsolate(); \\\n v8::Local<v8::Context> __context = __isolate->GetCurrentContext(); \\\n v8::Local<v8::Object> __enumObject = v8::Object::New(__isolate); \\\n V_CALL(exports->Set(__context, v8::String::NewFromUtf8(__isolate, enumName), __enumObject))\n\n#define V_ENUM_ITEM(itemName, itemValue) \\\n V_CALL(__enumObject->Set(__context, v8::String::NewFromUtf8(__isolate, itemName), v8::Number::New(__isolate, itemValue))); \\\n V_CALL(__enumObject->Set(__context, v8::Number::New(__isolate, itemValue), v8::String::NewFromUtf8(__isolate, itemName)))\n\n#define V_ENUM_END() }\n}" }, { "alpha_fraction": 0.6482987999916077, "alphanum_fraction": 0.659023642539978, "avg_line_length": 28.40217399597168, "blob_id": "60fd31c62e05833f2941474916399d19adf29ff1", "content_id": "62bb7d0de25516957c1dedb91d4bc65e2e7211f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2704, "license_type": "no_license", "max_line_length": 123, "num_lines": 92, "path": "/src/Solution.cc", "repo_name": "ShangHaiPTM/node-cgns", "src_encoding": "UTF-8", "text": "//\n// Created by Han Colin on 2017/12/30.\n//\n\n#include \"Solution.h\"\n#include \"helper.h\"\n#include \"v8Helper.h\"\n\nnamespace cgns {\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Maybe;\nusing v8::MaybeLocal;\nusing v8::Context;\nusing v8::Value;\nusing v8::String;\nusing v8::Object;\nusing v8::Number;\nusing v8::Function;\nusing v8::FunctionTemplate;\nusing v8::FunctionCallbackInfo;\nusing v8::Persistent;\n\nPersistent<Function> Solution::constructor;\n\nSolution::Solution() {\n}\n\nSolution::~Solution() {\n}\n\nvoid Solution::Init(Local<Object> exports) {\n Isolate *isolate = exports->GetIsolate();\n\n // Prepare constructor template\n Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);\n tpl->SetClassName(String::NewFromUtf8(isolate, \"CgnsZone\"));\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n constructor.Reset(isolate, tpl->GetFunction());\n exports->Set(String::NewFromUtf8(isolate, \"CgnsZone\"),\n tpl->GetFunction());\n}\n\nvoid Solution::New(const FunctionCallbackInfo<Value> &args) {\n Isolate *isolate = args.GetIsolate();\n\n if (args.IsConstructCall()) {\n Solution *obj = new Solution();\n obj->Wrap(args.This());\n args.GetReturnValue().Set(args.This());\n } else {\n Local<Context> context = isolate->GetCurrentContext();\n Local<Function> cons = Local<Function>::New(isolate, Solution::constructor);\n Local<Object> result = cons->NewInstance(context).ToLocalChecked();\n args.GetReturnValue().Set(result);\n }\n}\n\nLocal<Object> Solution::NewInstance(Local<Context> context, int handler, int baseIndex, int zoneIndex, int cellDimension) {\n Isolate *isolate = context->GetIsolate();\n Local<Function> cons = Local<Function>::New(isolate, Solution::constructor);\n Local<Object> result =\n cons->NewInstance(context).ToLocalChecked();\n\n Solution::Open(result, handler, baseIndex, zoneIndex, cellDimension);\n\n return result;\n}\n\nvoid Solution::Open(Local<Object> _this, int handler, int baseIndex, int zoneIndex, int solutionIndex) {\n V_SET_BEGIN(_this);\n\n V_SET_NUMBER(_this, \"index\", solutionIndex);\n\n char name[128];\n CGNS_ENUMT(GridLocation_t) gridLocation;\n CGNS_CALL(cg_sol_info(handler, baseIndex, zoneIndex, solutionIndex, name, &gridLocation));\n V_SET_STRING(_this, \"name\", name);\n V_SET_NUMBER(_this, \"gridLocation\", gridLocation);\n\n int nfields;\n V_ARRAY_BEGIN(_this, \"fields\");\n CGNS_CALL( cg_nfields( handler, baseIndex, zoneIndex, solutionIndex, &nfields ) );\n for (int i = 0; i < nfields; i++) {\n V_ARRAY_ADD_NUMBER(i);\n }\n V_ARRAY_END();\n\n V_SET_END();\n}\n}" }, { "alpha_fraction": 0.6709021329879761, "alphanum_fraction": 0.6963151097297668, "avg_line_length": 21.485713958740234, "blob_id": "5fc29d04e307d9a035093dc18e29e349d8a7b8ac", "content_id": "3771a05f9933f001bb9c54c8d7ed3bd1cb30336e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 787, "license_type": "no_license", "max_line_length": 135, "num_lines": 35, "path": "/src/Grid.h", "repo_name": "ShangHaiPTM/node-cgns", "src_encoding": "UTF-8", "text": "//\n// Created by Han Colin on 2017/12/29.\n//\n\n#ifndef NODE_CGNS_GRID_H\n#define NODE_CGNS_GRID_H\n\n#include \"cgnslib.h\"\n#include <iostream>\n#include <string>\n#include <node/node.h>\n#include <node/node_object_wrap.h>\n\nnamespace cgns {\nclass Grid : public node::ObjectWrap {\npublic:\n static void Init(v8::Local<v8::Object> exports);\n\n static v8::Local<v8::Object> NewInstance(v8::Local<v8::Context> context, int handler, int baseIndex, int zoneIndex, int gridIndex);\n\nprivate:\n explicit Grid();\n\n ~Grid();\n\n static void New(const v8::FunctionCallbackInfo<v8::Value> &args);\n\n static void Open(v8::Local<v8::Object> _this, int handler, int baseIndex, int zoneIndex, int gridIndex);\n\nprivate:\n static v8::Persistent<v8::Function> constructor;\n};\n}\n\n#endif //NODE_CGNS_GRID_H\n" }, { "alpha_fraction": 0.5475481152534485, "alphanum_fraction": 0.5594599843025208, "avg_line_length": 32.13815689086914, "blob_id": "66f0274be03ac667f57df33da3d7d4e4907b9c12", "content_id": "f9cb5cba379583e84dbb2a63ee3b811d7bcebd15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5037, "license_type": "no_license", "max_line_length": 119, "num_lines": 152, "path": "/src/Zone.cc", "repo_name": "ShangHaiPTM/node-cgns", "src_encoding": "UTF-8", "text": "#include \"Zone.h\"\n#include \"helper.h\"\n#include \"v8Helper.h\"\n#include \"Grid.h\"\n#include \"Coord.h\"\n#include \"Solution.h\"\n\nnamespace cgns {\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Maybe;\nusing v8::MaybeLocal;\nusing v8::Context;\nusing v8::Value;\nusing v8::String;\nusing v8::Object;\nusing v8::Number;\nusing v8::Function;\nusing v8::FunctionTemplate;\nusing v8::FunctionCallbackInfo;\nusing v8::Persistent;\n\nPersistent<Function> Zone::constructor;\n\nZone::Zone() {\n}\n\nZone::~Zone() {\n}\n\nvoid Zone::Init(Local<Object> exports) {\n Isolate *isolate = exports->GetIsolate();\n\n // Prepare constructor template\n Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);\n tpl->SetClassName(String::NewFromUtf8(isolate, \"CgnsZone\"));\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n constructor.Reset(isolate, tpl->GetFunction());\n exports->Set(String::NewFromUtf8(isolate, \"CgnsZone\"),\n tpl->GetFunction());\n}\n\nvoid Zone::New(const FunctionCallbackInfo<Value> &args) {\n Isolate *isolate = args.GetIsolate();\n\n if (args.IsConstructCall()) {\n Zone *obj = new Zone();\n obj->Wrap(args.This());\n args.GetReturnValue().Set(args.This());\n } else {\n Local<Context> context = isolate->GetCurrentContext();\n Local<Function> cons = Local<Function>::New(isolate, Zone::constructor);\n Local<Object> result = cons->NewInstance(context).ToLocalChecked();\n args.GetReturnValue().Set(result);\n }\n}\n\nLocal<Object> Zone::NewInstance(Local<Context> context, int handler, int baseIndex, int zoneIndex, int cellDimension) {\n Isolate *isolate = context->GetIsolate();\n Local<Function> cons = Local<Function>::New(isolate, Zone::constructor);\n Local<Object> result =\n cons->NewInstance(context).ToLocalChecked();\n\n Zone::Open(result, handler, baseIndex, zoneIndex, cellDimension);\n\n return result;\n}\n\nvoid Zone::Open(Local<Object> _this, int handler, int baseIndex, int zoneIndex, int cellDimension) {\n V_SET_BEGIN(_this);\n\n V_SET_NUMBER(_this, \"index\", zoneIndex);\n\n double id;\n CGNS_CALL(cg_zone_id(handler, baseIndex, zoneIndex, &id));\n V_SET_NUMBER(_this, \"id\", id);\n\n CGNS_ENUMT(ZoneType_t) type;\n CGNS_CALL(cg_zone_type(handler, baseIndex, zoneIndex, &type));\n V_SET_NUMBER(_this, \"type\", type);\n\n char name[128];\n int sizes[9];\n // cgsize_t rangeMin[3] = {1, 1, 1};\n cgsize_t rangeMax[3] = {1, 1, 1};\n CGNS_CALL(cg_zone_read(handler, baseIndex, zoneIndex, name, (int*)(void*)sizes));\n V_SET_STRING(_this, \"name\", name);\n V_ARRAY_BEGIN(_this, \"sizes\");\n if (type == CGNS_ENUMV(Structured)) {\n if (cellDimension == 2) {\n for (int i = 0; i < 6; i++) {\n V_ARRAY_ADD_NUMBER(sizes[i]);\n }\n } else if (cellDimension == 3) {\n for (int i = 0; i < 9; i++) {\n V_ARRAY_ADD_NUMBER(sizes[i]);\n }\n }\n rangeMax[0] = sizes[0]; // dimi\n rangeMax[1] = sizes[1]; // dimj\n rangeMax[2] = sizes[2]; // dimk\n } else {\n for (int i = 0; i < 3; i++) {\n V_ARRAY_ADD_NUMBER(sizes[i]);\n }\n rangeMax[0] = sizes[0]; // nvertices\n rangeMax[1] = sizes[0]; // nvertices\n rangeMax[2] = sizes[0]; // nvertices\n }\n V_ARRAY_END();\n\n int indexDimension;\n CGNS_CALL(cg_index_dim(handler, baseIndex, zoneIndex, &indexDimension));\n V_SET_NUMBER(_this, \"indexDimension\", indexDimension);\n\n int ngrids = 0;\n CGNS_CALL(cg_ngrids(handler, baseIndex, zoneIndex, &ngrids));\n V_ARRAY_BEGIN(_this, \"grids\");\n for (int i = 0; i < ngrids; i++) {\n V_ARRAY_ADD(Grid::NewInstance(__context, handler, baseIndex, zoneIndex, i + 1));\n // V_ARRAY_ADD_NUMBER(i);\n }\n V_ARRAY_END();\n\n int ncoords = 0;\n CGNS_CALL(cg_ncoords(handler, baseIndex, zoneIndex, &ncoords));\n V_ARRAY_BEGIN(_this, \"coordinates\");\n for (int i = 0; i < ncoords; i++) {\n V_ARRAY_ADD(Coord::NewInstance(__context, handler, baseIndex, zoneIndex, i + 1));\n }\n V_ARRAY_END();\n\n int nsections = 0;\n CGNS_CALL(cg_nsections(handler, baseIndex, zoneIndex, &nsections));\n V_ARRAY_BEGIN(_this, \"sections\");\n for (int i = 0; i < nsections; i++) {\n V_ARRAY_ADD_NUMBER(i);\n }\n V_ARRAY_END();\n\n int nsolutions = 0;\n V_ARRAY_BEGIN(_this, \"solutions\");\n CGNS_CALL(cg_nsols(handler, baseIndex, zoneIndex, &nsolutions));\n for (int i = 0; i < nsolutions; i++) {\n V_ARRAY_ADD(Solution::NewInstance(__context, handler, baseIndex, zoneIndex, i + 1));\n }\n V_ARRAY_END();\n\n V_SET_END();\n}\n}\n" }, { "alpha_fraction": 0.6155914068222046, "alphanum_fraction": 0.6263440847396851, "avg_line_length": 25.64285659790039, "blob_id": "a81bd879e501ff0eb306d4a5f939ad8f32a4ad7c", "content_id": "5954500226009de3532305dfbbc218a665cbf278", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 372, "license_type": "no_license", "max_line_length": 61, "num_lines": 14, "path": "/test/testZone.js", "repo_name": "ShangHaiPTM/node-cgns", "src_encoding": "UTF-8", "text": "let cgns = require('..');\nlet path = require('path');\nlet expect = require('chai').expect;\nlet testFile1 = path.resolve(__dirname, './sqnz_s.hdf.cgns');\n\ndescribe('First zone in sqnz file', function() {\n let doc = new cgns.CgnsDoc(testFile1);\n let bases = doc.bases;\n let zone = bases[0].zones[0];\n\n it('Should have a magic number id', function() {\n\n })\n});" }, { "alpha_fraction": 0.6083799004554749, "alphanum_fraction": 0.6184357404708862, "avg_line_length": 27.648000717163086, "blob_id": "5272f3164d6901e71c3b6d7921733ced6d78b0b5", "content_id": "1f7b4194ae3b86082a5ce04592ec7df84cf28ed8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3580, "license_type": "no_license", "max_line_length": 113, "num_lines": 125, "path": "/src/Doc.cc", "repo_name": "ShangHaiPTM/node-cgns", "src_encoding": "UTF-8", "text": "#include \"Doc.h\"\n#include \"helper.h\"\n#include \"v8Helper.h\"\n#include \"Base.h\"\n\nnamespace cgns {\nusing std::string;\nusing v8::Persistent;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Number;\nusing v8::Object;\nusing v8::Persistent;\nusing v8::String;\nusing v8::Value;\nusing v8::Array;\nusing v8::Context;\nusing v8::MaybeLocal;\nusing v8::Maybe;\nusing v8::Exception;\nusing node::ObjectWrap;\n\nPersistent<Function> Doc::constructor;\n\nDoc::Doc()\n : m_handler(0) {\n}\n\nDoc::~Doc() {\n this->close();\n}\n\nvoid Doc::Init(Local<Object> exports) {\n Isolate *isolate = exports->GetIsolate();\n Local<Context> context = isolate->GetCurrentContext();\n\n // Prepare constructor template\n Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);\n tpl->SetClassName(String::NewFromUtf8(isolate, \"CgnsDoc\"));\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n // Prototype\n NODE_SET_PROTOTYPE_METHOD(tpl, \"open\", Open);\n\n constructor.Reset(isolate, tpl->GetFunction());\n V_CALL(exports->Set(context, String::NewFromUtf8(isolate, \"CgnsDoc\"),\n tpl->GetFunction()));\n}\n\nvoid Doc::New(const FunctionCallbackInfo<Value> &args) {\n Isolate *isolate = args.GetIsolate();\n\n if (args.IsConstructCall()) {\n Doc *obj = new Doc();\n obj->Wrap(args.This());\n if (args.Length() >= 1 && args[0]->IsString()) {\n Local<Context> context = isolate->GetCurrentContext();\n MaybeLocal<String> path = args[0]->ToString(context);\n obj->open(args.This(), path.ToLocalChecked());\n }\n args.GetReturnValue().Set(args.This());\n } else {\n // Invoked as plain function `MyObject(...)`, turn into construct call.\n const int argc = 1;\n Local<Value> argv[argc] = {args[0]};\n Local<Context> context = isolate->GetCurrentContext();\n Local<Function> cons = Local<Function>::New(isolate, constructor);\n Local<Object> result = cons->NewInstance(context, argc, argv).ToLocalChecked();\n args.GetReturnValue().Set(result);\n }\n}\n\nvoid Doc::Open(const FunctionCallbackInfo<Value> &args) {\n Isolate *isolate = args.GetIsolate();\n Local<Context> context = isolate->GetCurrentContext();\n\n if (args.Length() != 1 || !args[0]->IsString()) {\n isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, \"open('path/to/file.cgns')\")));\n return;\n }\n\n Local<Object> _this = args.Holder();\n Doc *_This = ObjectWrap::Unwrap<Doc>(_this);\n Local<String> path = args[0]->ToString(context).ToLocalChecked();\n\n _This->open(_this, path);\n}\n\nvoid Doc::Close(const FunctionCallbackInfo<Value> &args) {\n Doc *_This = ObjectWrap::Unwrap<Doc>(args.Holder());\n _This->close();\n}\n\nvoid Doc::close() {\n if (m_handler != 0) {\n CGNS_CALL(cg_close(m_handler));\n m_handler = 0;\n }\n}\n\nvoid Doc::open(Local<Object> _this, Local<String> path) {\n V_SET_BEGIN(_this);\n String::Utf8Value v(path);\n\n const int mode = CG_MODE_READ;\n CGNS_CALL(cg_open(*v, mode, &m_handler));\n\n float version;\n CGNS_CALL(cg_version(m_handler, &version));\n V_SET_NUMBER(_this, \"version\", version);\n\n int nbases = 0;\n CGNS_CALL(cg_nbases(m_handler, &nbases));\n\n V_ARRAY_BEGIN(_this, \"bases\");\n for (int i = 0; i < nbases; i++) {\n V_ARRAY_ADD(Base::NewInstance(__context, this->m_handler, i + 1));\n }\n V_ARRAY_END();\n V_SET_END();\n}\n}" }, { "alpha_fraction": 0.38410595059394836, "alphanum_fraction": 0.40066224336624146, "avg_line_length": 18.483871459960938, "blob_id": "1027bdfb4e64153e04485aa32f04c06f23cf1261", "content_id": "c566affcf789da552dfd7cec1820a2beca09235f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 604, "license_type": "no_license", "max_line_length": 49, "num_lines": 31, "path": "/binding.gyp", "repo_name": "ShangHaiPTM/node-cgns", "src_encoding": "UTF-8", "text": "{\n 'targets': [\n {\n 'target_name': 'cgns',\n 'sources': [\n 'src/helper.cc',\n 'src/cgns.cc',\n 'src/Doc.cc',\n 'src/Base.cc',\n 'src/Zone.cc',\n 'src/Grid.cc',\n 'src/Coord.cc',\n 'src/Solution.cc'\n ],\n 'dependencies': [\n ],\n 'include_dirs': [\n '/usr/local/include',\n '/usr/include'\n ],\n 'libraries': [\n '-lcgns',\n '-lhdf5',\n '-L/usr/local/lib',\n '-L/usr/lib',\n '-L/usr/lib/x86_64-linux-gnu/'\n '-L/usr/lib/x86_64-linux-gnu/hdf5/serial'\n ]\n }\n ]\n}\n" }, { "alpha_fraction": 0.5911329984664917, "alphanum_fraction": 0.6334975361824036, "avg_line_length": 39.63999938964844, "blob_id": "4fe4385eecef4fc33555c56fe4be151f64bd00a7", "content_id": "140c080339cf58e50e9dd31a2a59960488143e9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1015, "license_type": "no_license", "max_line_length": 104, "num_lines": 25, "path": "/test/testBase.js", "repo_name": "ShangHaiPTM/node-cgns", "src_encoding": "UTF-8", "text": "let cgns = require('..');\nlet path = require('path');\nlet expect = require('chai').expect;\nlet testFile1 = path.resolve(__dirname, './sqnz_s.hdf.cgns');\n\ndescribe('Bases in sqnz file', function() {\n let doc = new cgns.CgnsDoc(testFile1);\n let bases = doc.bases;\n it('id should be a magic number', function() {\n //expect(bases[0].id).to.be.equals(4.778309726736501e-299); // I don't known what this id means.\n expect(bases[0].id).to.be.equals(33554437); // I don't known what this id means.\n });\n it('cellDimension should be 3', function() {\n expect(bases[0].cellDimension).to.be.equals(3);\n });\n it('physicalDimension should be 3', function() {\n expect(bases[0].physicalDimension).to.be.equals(3);\n });\n it('simulationType should be nullValue', function() {\n expect(bases[0].simulationType).to.be.equals(cgns.SimulationType.nullValue);\n });\n it('should have 12 zone', function() {\n expect(bases[0].zones.length).to.be.equals(12);\n });\n})" } ]
18
davidjgmarques/David_Exercises
https://github.com/davidjgmarques/David_Exercises
c3af098ec04840bf7ca20133d20db33e270f8997
11400727cde766d9ceceed5a8c16b920ad3734c3
cff27cdd6677365cf19bec48dfe4ba8384a9ae8f
refs/heads/main
2023-05-02T18:41:23.117577
2021-05-27T17:42:57
2021-05-27T17:42:57
359,547,396
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.4768366813659668, "alphanum_fraction": 0.505849301815033, "avg_line_length": 22.217391967773438, "blob_id": "4b30e7051ba5dcae1f2614daee06f4a5d50e0c67", "content_id": "63397680353dd0de10134e4647bca7294548218f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2137, "license_type": "no_license", "max_line_length": 80, "num_lines": 92, "path": "/RungeKutta/Dav_RKutta.py", "repo_name": "davidjgmarques/David_Exercises", "src_encoding": "UTF-8", "text": "## Runge - Kutta\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nimport sys\n\n#--------------------/ Functions \\--------------------\n\ndef d_theta(omega):\n return omega\n\ndef d_omega(a,s,theta):\n return -(a/s)*math.sin(theta)\n\ndef warp(x):\n if x > 2*math.pi:\n x = x - 2*math.pi\n elif x < (-2*math.pi):\n x = x + 2*math.pi\n return x\n#This can be substituted with the function 'fmod'\n\n\n#--------------------/ Constants \\--------------------\n\ng = 9.8\nL = 0.1\nm = 1\n\n\n#--------------------/ Step \\-------------------------\n\nexp = int(sys.argv[1]) #steps order of magnitude\nperiods = 10 #half periods (1 swing)\nh = (math.pi)*periods/(10**exp)\nt = np.arange(0,periods,h)\nprint('Number of steps:', len(t))\n\n\n#--------------------/ Variables \\--------------------\n\ntheta = []\nomega = []\ninit_theta = math.radians(179)\ninit_omega = 0\ntheta.append(init_theta)\nomega.append(init_omega)\n\n\n#--------------------/ RungeKutta \\--------------------\n\nfor i in range(len(t)-1):\n\n k1_t = h*d_theta(omega[i])\n k1_w = h*d_omega(g,L,theta[i])\n \n k2_t = h*d_theta(omega[i] + 0.5*k1_w)\n k2_w = h*d_omega(g,L,theta[i] + 0.5*k1_t)\n\n loop = warp(theta[i])\n theta[i]=loop\n\n theta.append(theta[i]+k2_t)\n omega.append(omega[i]+k2_w)\n\n\n#--------------------/ System's Energy \\--------------------\n\nEnergy = []\nEnergy0 = []\nfor i in range(len(t)):\n Energy.append(0.5*m*((omega[i]**2)*(L**2)) + m*g*L*(1-math.cos(theta[i]))) \n Energy0.append(0.5*m*((omega[0]**2)*(L**2)) + m*g*L*(1-math.cos(theta[0]))) \n #Line above can be substituted with:' plt.plot(t,np.full(t.size,Energy[0]))\n\n\n#--------------------/ Plots \\--------------------------------\n\nfig, axs = plt.subplots(3)\nfig.tight_layout(pad=3.0)\nfig.set_figheight(5)\nfig.set_figwidth(10)\naxs[0].set_title('Theta (t)')\naxs[0].plot(t,theta,'b')\naxs[1].set_title('Omega (t)')\naxs[1].plot(t,omega, 'r')\naxs[2].set_title('System\\'s energy')\naxs[2].plot(t,Energy,'g', label= 'RK Energy')\naxs[2].plot(t,Energy0,'k', label='Constant Energy')\nplt.legend()\n#plt.show()\nplt.savefig(\"Results.pdf\")\n\n" }, { "alpha_fraction": 0.5319887399673462, "alphanum_fraction": 0.5649533867835999, "avg_line_length": 23.402116775512695, "blob_id": "a55a05cf7365baba920d65a3f4dfc4e8c49b1525", "content_id": "64aa409a30c2aa413967b8322cfc9bfd5b25511b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4611, "license_type": "no_license", "max_line_length": 102, "num_lines": 189, "path": "/Integration/Dav_integrators.py", "repo_name": "davidjgmarques/David_Exercises", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy\nfrom scipy.integrate import simps\n\n# ---------------/ Function to integrate \\------------------------\ndef f1(x):\n return x**4 - 2*x + 1\n\ndef f1_1p(x):\n return 4*x**3 - 2 \n\ndef f1_3p(x):\n return 24*x\n\n\n# ---------------/ Trapezium integrator \\------------------------\ndef Trapezium(func,low_lim,high_lim,steps):\n a=low_lim\n b=high_lim\n N=steps\n h = (b-a)/N\n\n I_trap = (0.5*func(a) + 0.5*func(b))\n\n for k in range(1,N):\n I_trap += func(a+k*h) \n I_trap *= h\n return(I_trap)\n\n# ---------------/ Simpson integrator \\------------------------\ndef Simpson(func,low_lim,high_lim,steps):\n a=low_lim\n b=high_lim\n N=steps\n h = (b-a)/N\n\n I_simp = func(a)+ func(b)\n\n for k in range(1,steps):\n if k % 2 == 0: #even\n I_simp += 2*func(a+k*h) \n else: #odd\n I_simp += 4*func(a+k*h) \n I_simp *= (h/3)\n return(I_simp)\n\n# ---------------/ Simpson with sums (no loops) \\-------------------------\n\n# x = np.linspace(a,b,n_steps+1)\n# func= f1(x)\n# my_A_simp1 = h/3 * (func[0] + func[n_steps] + 4*sum(func[1:n_steps:2]) + 2*sum(func[2:n_steps-1:2]))\n# print('\\nMy simpson integral_1: \\n',my_A_simp1)\n\n\n#----------------/ -------------- \\--------------------------\n\n\n#----------------/ Quick approach \\--------------------------\na=0\nb=2\nexponent = 7\nn_steps = 10**exponent\nIntegral_teo = 4.4\n\nprint('Trapezium method for %2.0e samples: ' % n_steps, Trapezium(f1,a,b,n_steps))\nprint('Simpson method for %2.0e samples: ' % n_steps, Simpson(f1,a,b,n_steps)) \n\nx = np.linspace(a,b,n_steps+1)\npython_A_simp= simps(f1(x),x)\nprint('Python\\'s simpson integral for %2.0e samples: ' % n_steps, python_A_simp)\n\nprint(\n'\\nAnalytic method: \\n'\n' Int(x^4 - 2x + 1) in x{0,2} (=) \\n'\n' (=) x^5/5 - x^2 + x in x{0,2} (=) \\n'\n' (=) 32/5 - 4 + 2 - (0) (=) \\n'\n' (=) 6.4 - 4 + 2 (=) \\n'\n' (=) 4.4')\n\nplot10= plt.figure(7)\nplt.plot(x,f1(x),'-r', label=r'$y = x^4 - 2x + 1$')\nplt.grid()\nplt.axvline(c='k')\nplt.axhline(c='k')\nplt.title('Polynomial Curve')\nplt.legend(loc='upper left')\n\n\n#----------------/ Errors \\--------------------------\n\n\nS_error_approx = []\nS_error_diff = []\nS_error_teo = []\n\nT_error_approx = []\nT_error_diff = []\nT_error_teo = []\n\nN_iterative=[]\n\nfor g in range(1,exponent+1):\n exp=10**g\n h = (b-a)/exp\n\n N_iterative.append(exp)\n\n Simp_1n = Simpson(f1,a,b,exp)\n Simp_2n = Simpson(f1,a,b,exp*2)\n\n S_error_approx.append((1/15)*(abs(Simp_2n-Simp_1n)))\n S_error_diff.append(abs(Integral_teo - Simp_1n))\n S_error_teo.append((1/90)*h**4*(abs(f1_3p(a) - f1_3p(b))))\n\n Trap_1n = Trapezium(f1,a,b,exp)\n Trap_2n = Trapezium(f1,a,b,exp*2)\n\n T_error_approx.append((1/3)*(abs(Trap_2n-Trap_1n)))\n T_error_diff.append(abs(Integral_teo - Trap_1n))\n T_error_teo.append((1/12)*h**2*(abs(f1_1p(a) - f1_1p(b))))\n\nplot1= plt.figure(1)\nplt.xlabel('N')\nplt.grid()\nplt.xscale('log')\nplt.yscale('log')\nplt.ylabel('(1/15) * (I$_{2N}$ - I$_{N}$)')\nplt.title('Simpson - Approximated error')\nplt.plot(N_iterative,S_error_approx,'o')\n\nplt.savefig(\"Simpson - Approximated error.pdf\")\n\nplot2= plt.figure(2)\nplt.xlabel('N')\nplt.grid()\nplt.xscale('log')\nplt.yscale('log')\nplt.ylabel('I$_{teo}$ - I$_{N}$')\nplt.title('Simpson - Difference between theoretical and computed value')\nplt.plot(N_iterative,S_error_diff,'o')\n\nplt.savefig(\"Simpson - Difference between theoretical and computed value.pdf\")\n\nplot3= plt.figure(3)\nplt.xlabel('N')\nplt.grid()\nplt.xscale('log')\nplt.yscale('log')\nplt.ylabel('(1/90) * h$^{4} * (f\\'\\'\\'(a) - f\\'\\'\\'(b))$')\nplt.title('Simpson - Theoretical error')\nplt.plot(N_iterative,S_error_teo,'o')\n\nplt.savefig(\"Simpson - Theoretical error.pdf\")\n\nplot4= plt.figure(4)\nplt.xlabel('N')\nplt.grid()\nplt.xscale('log')\nplt.yscale('log')\nplt.ylabel('(1/3) * (I$_{2N}$ - I$_{N}$)')\nplt.title('Trapezium - Approximated error')\nplt.plot(N_iterative,T_error_approx,'o')\n\nplt.savefig(\"Trapezium - Approximated error.pdf\")\n\nplot5= plt.figure(5)\nplt.xlabel('N')\nplt.grid()\nplt.xscale('log')\nplt.yscale('log')\nplt.ylabel('I$_{teo}$ - I$_{N}$')\nplt.title('Trapezium - Difference between theoretical and computed value')\nplt.plot(N_iterative,T_error_diff,'o')\n\nplt.savefig(\"Trapezium - Difference between theoretical and computed value.pdf\")\n\nplot6= plt.figure(6)\nplt.xlabel('N')\nplt.grid()\nplt.xscale('log')\nplt.yscale('log')\nplt.ylabel('(1/12) * h$^{2} * (f\\'(a) - f\\'(b))$')\nplt.title('Trapezium - Theoretical error')\nplt.plot(N_iterative,T_error_teo,'o')\n\nplt.savefig(\"Trapezium - Theoretical error.pdf\")\n\n#plt.show()" }, { "alpha_fraction": 0.5078027248382568, "alphanum_fraction": 0.5539950132369995, "avg_line_length": 21.570423126220703, "blob_id": "6482179b3be01dc31aa6b9c48ed7d0da8f9f5eb0", "content_id": "ee1d34ef6644b749a2ce84a4a1c2ff37084d8621", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3204, "license_type": "no_license", "max_line_length": 90, "num_lines": 142, "path": "/Crank-Nicolson/Dav-CN.py", "repo_name": "davidjgmarques/David_Exercises", "src_encoding": "UTF-8", "text": "# 1D - Diffusion with source term\n\nimport math\nimport numpy as np\nfrom scipy.linalg import solve_banded\nimport matplotlib.pyplot as plt\nimport time\n\nstart = time.time()\n\ndef analy_sol(x):\n return math.cos(math.pi * 0.5 * x)\n\ndef sourc_term(x,diff):\n return math.cos(math.pi * 0.5 * x) * pow(math.pi,2) * 0.25 * diff\n\nH = 1\nxMin = -H\nxMax = H\nD = 0.1\ndt = pow(10,-3)\n\nexps=[8,9,10]\nN1 = pow(2,exps[0])\nN2 = pow(2,exps[1])\nN3 = pow(2,exps[2])\nN=[N1,N2,N3]\n\nrms= []\n\ntmax= 100\ntime_plot=range(1,tmax+1)\ntime_evolution=[99,98,97,96,95,94]\n\n\nfig, axs = plt.subplots(2,3)\nfig.set_figheight(10)\nfig.set_figwidth(15)\nfig.suptitle('Evolution of $u(x)$ and RMS error for different sampling', fontsize = 16)\nfor k in range(len(N)):\n\n x = np.linspace(xMin,xMax,N[k])\n dx = (xMax-xMin)/(N[k]-1)\n #dx = x[1]-x[0]\n\n Q = [sourc_term(x[i],D) for i in range(N[k])]\n Q[0]=0\n Q[-1]=0\n\n S = [analy_sol(x[i]) for i in range(N[k])]\n S[0]=0\n S[-1]=0\n\n u = np.zeros(N[k])\n rhs = np.zeros(N[k]-2)\n\n alpha = (dt * D) / (2 * pow(dx,2))\n central_diag = (1+2*alpha)\n upper_diag = -alpha\n lower_diag = -alpha\n\n error = 0\n difference = []\n \n evolution_u= np.zeros((len(time_evolution),N[k]))\n\n error_counter=0\n plot_counter=0\n\n t=tmax\n while t > dt:\n for i in range(1,N[k]-1):\n rhs[i-1] = alpha * u[i+1] + (1-2*alpha) * u[i] + alpha * u[i-1] + Q[i] * dt \n\n Ab = np.zeros((3,N[k]-2))\n\n Ab[0,1:] = upper_diag\n Ab[1,0:] = central_diag\n Ab[2,:-1] = lower_diag\n\n sol = solve_banded((1,1),Ab,rhs)\n\n for i in range(1,N[k]-1):\n u[i]=sol[i-1]\n\n t -= dt\n\n if error_counter == 1000-1:\n for i in range(N[k]):\n error += pow(u[i] - S[i],2)\n difference.append(math.sqrt(error/(N[k])))\n error = 0\n error_counter=0\n\n error_counter+=1\n\n point_plot = round(t,3)\n if point_plot in time_evolution:\n for i in range(N[k]-1):\n evolution_u[plot_counter,i]=u[i]\n plot_counter+=1 \n\n\n rms.append(difference)\n\n\n axs[0,k].set_title('N = 2$^{%i}$' %(exps[k]))\n axs[0,k].plot(evolution_u.T)\n axs[0,k].set_xlabel('x')\n axs[0,k].set_ylabel('$u(x)$')\n\n axs[1,k].set_ylabel('$||f(x) - f_{a}(x)||$')\n axs[1,k].set_yscale('log')\n axs[1,k].set_xlabel('t')\n axs[1,k].plot(time_plot,difference,'bo')\n\n\nend = time.time()\n\nprint('Time elapsed:', end - start)\n\nplt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.3, hspace=None)\nplt.savefig(\"Results.pdf\")\n\nplot2= plt.figure(2)\nplot2.set_figheight(5)\nplot2.set_figwidth(10)\nplt.yscale('log')\nplt.ylabel('$||f(x) - f_{a}(x)||$')\nplt.xlabel('t')\nplt.title('RMS comparison for different sampling')\nfor i in range(len(rms)):\n plt.plot(time_plot,[pt for pt in rms[i]],'o',label = '2$^{%i}$' %(exps[i]))\nplt.legend()\nplt.savefig(\"RMS_error_comparison.pdf\")\n#plt.show()\n\ndiff_highN_medN = rms[2][99]/rms[1][99]\ndiff_medN_lowN = rms[1][99]/rms[0][99]\n\nprint('When t goes to infinite, error(N=2^9)/error(N=2^8) = {:.2E}, \\n' \n'and error(N=2^8)/error(N=2^7) = {:.2E}'.format(diff_highN_medN,diff_medN_lowN))" }, { "alpha_fraction": 0.7333333492279053, "alphanum_fraction": 0.7440860271453857, "avg_line_length": 12.70588207244873, "blob_id": "0fa465d2b0087a5c4c4a0a05bb1b2a692f0c09ae", "content_id": "af196a274927c6c0f7b97ab38d92845d3abb6781", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 465, "license_type": "no_license", "max_line_length": 106, "num_lines": 34, "path": "/Integration/README.md", "repo_name": "davidjgmarques/David_Exercises", "src_encoding": "UTF-8", "text": "# Numerical Methods - Exercise 1\n\nIntegration through the Trapezium and Simpson methods.\n\n## Language\n\nPython3\n\n## Libraries necessary\n\nnumpy \nmatplotlib\nscipy\n\n## Usage\n\nWindows 10\n\n```bash\npy ./Dav_integrators.py\n```\n\nUnix/MacOS\n\n```bash\npython ./Dav_integrators.py\n```\n\nNote:\nIf several versions of python are installed, the initialization is made with 'python3' instead of 'python'\n\n## Contributing\n\nPull requests are welcome, as well as verbal comments & tips." }, { "alpha_fraction": 0.7244418263435364, "alphanum_fraction": 0.7356051802635193, "avg_line_length": 28.34482765197754, "blob_id": "1d7929bd813d34e3818c193ca85c1f9217c9e869", "content_id": "e3a04f27ba16daa3947d54ae1d2623ddbd880f39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1710, "license_type": "no_license", "max_line_length": 116, "num_lines": 58, "path": "/RungeKutta/README.md", "repo_name": "davidjgmarques/David_Exercises", "src_encoding": "UTF-8", "text": "# Numerical Methods - Exercise 2\n\nImplementation of Runge Kutta method to solve differential equations.\n\nProblem: Simple Pendullum Oscillation\n\n## Language\n\nPython3\n\n## Libraries necessary\n\nnumpy \nmatplotlib \nmath\n\n## Usage\n\nThe script requires an argument: the exponential(**exp**) in **steps = 10^{exp}**. \nThis number is used to calculate the **step size** used in the Runge Kutta. \nThe *size* and *number* of steps is calculated for a given number of half-periods, here set to 10.\n\nThe user is recommended to use **exp=3** and **exp=4**.\n\nWindows 10\n\n```bash\npy ./Dav_RKutta.py [exp]\n```\n\nUnix/MacOS\n\n```bash\npython ./Dav_RKutta.py [exp]\n```\n\n### Python (conflicting) versions:\n\nIf several versions of python are installed, the initialization is made with 'python3' instead of 'python'.\n\n## Contributing\n\nPull requests are welcome, as well as verbal comments & tips.\n\n# Solutions\n\nWhen using **exp=3**:\n\nThe user will note that the pendullum's theta angle θ will be greater than 2π. \nThis happens due to the low number of steps used to sample θ(t), which generates greater variations in θ(t).\nAt this point, θ is 'warped' back. This results in a θ(t) with several sharp rises. \nThe energy of the system is slowly increasing thus proving the *non energy conservation* of the Runge Kutta method. \n\nWhen using **exp=4**:\nThe sampling is good enough to avoid great variations of θ. \nThis results in a correct behaviour of the pendullum, *i.e.*, a variation of θ between -90 and 90 degrees. \nThe energy system also increases in this case, but much slower, due to the larger number of samples. \nUsing **exp>4** has the same result, with the difference of the energy increase being even smaller.\n" }, { "alpha_fraction": 0.7646648287773132, "alphanum_fraction": 0.7688547372817993, "avg_line_length": 25.462963104248047, "blob_id": "e36c20b44127610d95d183adc06f502043177702", "content_id": "597f0a765088ef7a67f8b29437bdcc80588b8638", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1432, "license_type": "no_license", "max_line_length": 179, "num_lines": 54, "path": "/Crank-Nicolson/README.md", "repo_name": "davidjgmarques/David_Exercises", "src_encoding": "UTF-8", "text": "# Numerical Methods - Exercise 3\n\nProblem: Solve the 1-D diffusion equation with a source term.\n\nMethod: Crank-Nicolson\n\nResult: Difference between function evolution calculated and analytic solution.\n\n## Language\n\nPython3\n\n## Libraries necessary\n\nmath \nmatplotlib \ntime \nnumpy \nscipy.linalg\n\n## Usage\n\nWindows 10\n\n```bash\npy ./Dav-CN.py\n```\n\nUnix/MacOS\n\n```bash\npython ./Dav-CN.py\n```\n\n### Python (conflicting) versions:\n\nIf several versions of python are installed, the initialization is made with 'python3' instead of 'python'.\n\n## Contributing\n\nPull requests are welcome, as well as verbal comments & tips.\n\n# Solutions\n\nOnce the simulation is done, two output files are generated. \nThe first, \"Results\", presents the evolution of the function in the first seconds and the difference between the result obtained and analytical solution, for different sampling. \nThe second, \"RMS_error_comparison\", shows the difference referred above, for different sampling, in the same plot for easier comparison.\n\nIn terminal, the compilation time is shown as well as the limit ratio between the differences referred, between different samplings.\n\n## Solving tridiagonal matrix equations\n\nThe package used to solve these matrixes was *solve_banded* from the *scipy.linalg* library. \nThe reference guide to use this package can be found in [here](https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.solve_banded.html). \n\n" } ]
6
manvirchanna/Voice-to-text-using-python
https://github.com/manvirchanna/Voice-to-text-using-python
7273df46a21d30e809ddb783ff04950d397e35a9
672e2d51338ff42546c6863a1bf4c764dee08e7e
94efc365866e16accdfb2a378d8395048202c11c
refs/heads/master
2022-12-24T08:21:15.037214
2020-10-02T04:44:16
2020-10-02T04:44:16
261,252,333
2
1
null
2020-05-04T17:32:15
2020-06-30T10:54:59
2020-10-02T04:44:16
Python
[ { "alpha_fraction": 0.5964712500572205, "alphanum_fraction": 0.6027319431304932, "avg_line_length": 21.384614944458008, "blob_id": "6d2cf814dbc588c32dd59c0e043062e679e9f7c9", "content_id": "c146ff010d776daa0ff64118f5d3db6d37aad6ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1757, "license_type": "no_license", "max_line_length": 96, "num_lines": 78, "path": "/Voice-to-Text.py", "repo_name": "manvirchanna/Voice-to-text-using-python", "src_encoding": "UTF-8", "text": "import pyttsx3 #pip install pyttsx3\nimport speech_recognition as sr #pip install speechRecognition\nimport datetime\nimport wikipedia #pip install wikipedia\nimport webbrowser \nimport os\nimport smtplib\nimport random\nimport wolframalpha \nimport requests\n\n\nengine = pyttsx3.init('')\nvoices = engine.getProperty('')\n\nengine.setProperty('voice', voices[\"Enter for voice code\"].id)\n\n\ndef speak(audio):\n (engine.say(audio))\n (engine.runAndWait())\n\n\ndef wishMe():\n hour = int(datetime.datetime.now().hour)\n if hour>=0 and hour<12:\n print(\"Good Morning!\")\n speak(\"Good Morning!\")\n\n elif hour>=12 and hour<19:\n print(\"Good Afternoon!\")\n speak(\"Good Afternoon!\") \n\n else:\n print(\"Good Evening!\")\n speak(\"Good Evening!\")\n\n\ndef hello():\n wishMe()\n print(\"This project is made by Manvir Singh. I can convert voice into text\")\n speak(\"This project is made by Manvir Singh. I can convert voice into text\")\n\n\n \n\ndef takeCommand():\n #It takes microphone input as audio from the user and returns its text form in string output\n\n r = sr.Recognizer()\n with sr.Microphone() as source:\n print(\"Listening.....\")\n r.pause_threshold = 1\n audio = r.listen(source)\n\n try:\n print(\"Recognizing.....\") \n query = r.recognize_google(audio, language='en-in')\n print(f\"You said: {query}\\n\")\n\n except Exception as e: \n print(\"Say that again please...\") \n return \"None\"\n return query\n\n\nif __name__ == \"__main__\":\n hello()\n while True:\n query = takeCommand().lower()\n\n if 'stop' in query or 'bye' in query:\n\n speak(\"Bye, Have a nice day\")\n exit()\n \n else:\n speak(query) \n \n" }, { "alpha_fraction": 0.7928571701049805, "alphanum_fraction": 0.7928571701049805, "avg_line_length": 69, "blob_id": "74b73a17d260f347f217cb8c239c1abf603dcd9d", "content_id": "be6adcbfcad658c08100e1f532be57228c61cbc6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 140, "license_type": "no_license", "max_line_length": 110, "num_lines": 2, "path": "/README.md", "repo_name": "manvirchanna/Voice-to-text-using-python", "src_encoding": "UTF-8", "text": "# Voice-to-text-using-python\nThis voice to text module takes the input as user's voice and convert it into text and perform some functions.\n" } ]
2
steve-jang/Advent-of-Code-2020
https://github.com/steve-jang/Advent-of-Code-2020
1bf30ff29baa7628895d1bd8f29fb377875b0ac5
93bb85a74a38a9014890bd535cd3d57664c2b0c2
a649dcefd71c03905d4c0e8a66a96a9a6f7cfdc1
refs/heads/master
2023-02-05T12:21:19.912827
2020-12-25T07:20:28
2020-12-25T07:20:36
320,973,416
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5024015307426453, "alphanum_fraction": 0.519692599773407, "avg_line_length": 26.394737243652344, "blob_id": "9b8d17ac3979f67071d22bbfc0fc7be292570482", "content_id": "27cbb56d8c020bb96f108e2355c8650cc6786ba0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2082, "license_type": "no_license", "max_line_length": 80, "num_lines": 76, "path": "/Day13/day13.py", "repo_name": "steve-jang/Advent-of-Code-2020", "src_encoding": "UTF-8", "text": "def part1():\n f = open(\"input.txt\", \"r\")\n lines = f.readlines()\n f.close()\n time = int(lines[0])\n buses = [int(bus) for bus in lines[1].split(\",\") if bus != \"x\"]\n\n bus_times = {}\n for b in buses:\n bus_times[b] = b - (time % b)\n\n for b in bus_times:\n if bus_times[b] == min(bus_times.values()):\n return b * bus_times[b]\n\n\ndef part2():\n f = open(\"input.txt\", \"r\")\n lines = f.readlines()\n f.close()\n time = int(lines[0])\n\n # bus_offsets is a list of bus-offset pairs.\n bus_offsets = []\n for i, b in enumerate(lines[1].split(\",\")):\n if b != \"x\":\n bus_offsets.append((int(b), i % int(b)))\n\n # need to solve an equation of the form:\n # t = p1a1 - b1 = p2a2 - b2 = p3a3 - b3 = ...\n # Solve the above equation by solving the first two, then solving\n # the solution equation with subsequent equations.\n # let current equation be of the form t = eqn_p*a - eqn_b,\n # keeping track of only p and b.\n for i, bus in enumerate(bus_offsets):\n if i == 0:\n # Initially set variables\n eqn_p = bus[0]\n eqn_b = bus[1]\n else:\n p = bus[0]\n b = bus[1]\n\n # Update current equation being solved\n # Formula for the solution for t after the ith equation\n # (Manually worked out formula)\n eqn_b = -p * (((b - eqn_b) * modinv(p, eqn_p)) % eqn_p) + b\n eqn_p *= p\n\n return -eqn_b\n\n\n# Functions for modinv (modular inverse) obtained from SO:\n# https://stackoverflow.com/questions/16044553/solving-a-modular-equation-python\n# Iterative Algorithm (xgcd)\ndef iterative_egcd(a, b):\n x, y, u, v = 0, 1, 1, 0\n while a != 0:\n q, r = b // a, b % a\n m, n = x - u * q, y - v * q # use x//y for floor \"floor division\"\n b, a, x, y, u, v = a, r, u, v, m, n\n\n return b, x, y\n\n\ndef modinv(a, m):\n g, x, y = iterative_egcd(a, m)\n if g != 1:\n return None\n else:\n return x % m\n\n\nif __name__ == \"__main__\":\n print(part1())\n print(part2())\n" }, { "alpha_fraction": 0.5290462970733643, "alphanum_fraction": 0.5340167880058289, "avg_line_length": 24.75200080871582, "blob_id": "a8e544a1ecf8fb56e5fcbdbdb78833643d18eef9", "content_id": "5b04e0d94ac255f0eb8f0596493e1a9509e5a37e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3219, "license_type": "no_license", "max_line_length": 85, "num_lines": 125, "path": "/Day16/day16.py", "repo_name": "steve-jang/Advent-of-Code-2020", "src_encoding": "UTF-8", "text": "def part1():\n tickets = extract_tickets()\n rules = extract_rules()\n\n error_rate = 0\n for ticket in tickets:\n for n in ticket:\n satisfied = False\n for rule in rules:\n if rule[0] <= n <= rule[1]:\n satisfied = True\n break\n\n if not satisfied:\n error_rate += n\n\n return error_rate\n\n\ndef extract_tickets():\n # Returns a list of (list of numbers representing tickets)\n f = open(\"nearby.txt\", \"r\")\n tickets = [[int(n) for n in line.split(\",\")] for line in f.readlines()]\n f.close()\n return tickets\n\n\ndef extract_rules():\n # Returns a list of (2-item lists representing each range)\n f = open(\"rules.txt\", \"r\")\n rules = []\n for line in f.readlines():\n for word in line.split():\n if \"-\" in word:\n rules.append([int(n) for n in word.split(\"-\")])\n\n f.close()\n return rules\n\n\ndef part2():\n rules = extract_rules()\n tickets = [t for t in extract_tickets() if is_ticket_valid(t, rules)]\n field_count = len(tickets[0])\n specific_rules = extract_specific_rules()\n field_order = {}\n\n # This populates field_order with (field index)-(list of satisfying fields) pairs\n for i in range(field_count):\n field_order[i] = []\n for field in specific_rules:\n values = [ticket[i] for ticket in tickets]\n field_match = True\n for value in values:\n if not is_rule_satisfied(specific_rules[field], value):\n field_match = False\n break\n\n if field_match:\n field_order[i].append(field)\n\n # This converts field_order into field-(matching index) pairs\n filtered_order = {}\n while field_order:\n for k in field_order:\n if len(field_order[k]) == 1:\n field = field_order.pop(k)[0]\n filtered_order[field] = k\n for j in field_order:\n field_order[j].remove(field)\n\n break\n\n # This multiplies values of fields starting with \"departure\"\n my_ticket = [int(n) for n in open(\"my_ticket.txt\", \"r\").readline().split(\",\")]\n result = 1\n for field in filtered_order:\n if \"departure\" in field:\n result *= my_ticket[filtered_order[field]]\n\n return result\n\n\n\ndef is_ticket_valid(ticket, rules):\n for n in ticket:\n valid_field = False\n for rule in rules:\n if rule[0] <= n <= rule[1]:\n valid_field = True\n break\n\n if not valid_field:\n return False\n\n return True\n\n\ndef is_rule_satisfied(rule, value):\n for interval in rule:\n if interval[0] <= value <= interval[1]:\n return True\n\n return False\n\n\ndef extract_specific_rules():\n f = open(\"rules.txt\", \"r\")\n rules = {}\n\n for line in f.readlines():\n field, ranges = line.split(\": \")\n rules[field] = []\n for word in ranges.split():\n if \"-\" in word:\n rules[field].append([int(n) for n in word.split(\"-\")])\n\n f.close()\n return rules\n\n\n\nif __name__ == \"__main__\":\n print(part1())\n print(part2())\n" }, { "alpha_fraction": 0.5919219851493835, "alphanum_fraction": 0.6350975036621094, "avg_line_length": 20.117647171020508, "blob_id": "cc7a5ebd13a1a7e8a3a9fc22f03c13c7af3f1785", "content_id": "04dbf2bd6106a128f1f0f92bbeaefa2a44026a85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 718, "license_type": "no_license", "max_line_length": 64, "num_lines": 34, "path": "/Day25/day25.py", "repo_name": "steve-jang/Advent-of-Code-2020", "src_encoding": "UTF-8", "text": "SUBJECT_NUMBER = 7\nDIVISOR = 20201227\nCARD_PUB_KEY = 16616892\nDOOR_PUB_KEY = 14505727\n\n\ndef part1():\n card_loop_size = get_loop_size(SUBJECT_NUMBER, CARD_PUB_KEY)\n encryption_key = transform(DOOR_PUB_KEY, card_loop_size)\n\n return encryption_key\n\n\ndef get_loop_size(subject_number, transformation_result):\n loops_done = 0\n result = 1\n while True:\n if result == transformation_result:\n return loops_done\n\n result = (result * subject_number) % DIVISOR\n loops_done += 1\n\n\ndef transform(subject_number, loops):\n result = 1\n for _ in range(loops):\n result = (result * subject_number) % DIVISOR\n\n return result\n\n\nif __name__ == \"__main__\":\n print(part1())\n" }, { "alpha_fraction": 0.5432258248329163, "alphanum_fraction": 0.5993548631668091, "avg_line_length": 26.678571701049805, "blob_id": "2b957584c55960746ddcd9b5b4b100b62ae1a3b3", "content_id": "d74bd24619b6de0c41b1233f1dc9b6fe792a7518", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1550, "license_type": "no_license", "max_line_length": 75, "num_lines": 56, "path": "/Day19/day19_part2.py", "repo_name": "steve-jang/Advent-of-Code-2020", "src_encoding": "UTF-8", "text": "from day19 import read_rules, read_messages, satisfy_rule\n\n\ndef part2():\n rules = read_rules()\n messages = read_messages()\n\n rules[8] = [[42], [42, 8]]\n rules[11] = [[42, 31], [42, 11, 31]]\n\n # Rule 0 is 8 11. Messages that satisfy rule 0 are ones which\n # satisfy rule 42 at least once, then satisfy rule 42 X times\n # then rule 31 X times, X >= 1.\n # In other words, messages that satisfy rule 0 are ones which satisfy\n # rule 42 X+Y times then rule 31 Y times, where X and Y >= 1\n\n valid_messages = 0\n for msg in messages:\n if is_rule0_satisfied(msg, rules):\n valid_messages += 1\n\n return valid_messages\n\n\ndef is_rule0_satisfied(msg, rules):\n # Figure out maximum number of times rule 42 can be satisfied\n max_satisfy_42 = 0\n rest_msg = msg\n while True:\n rest_msg = satisfy_rule(rest_msg, rules, 42)\n if rest_msg == False:\n break\n\n max_satisfy_42 += 1\n\n # As an example:\n # If max_satisfy_42 is 3, then try satisfying rule 31 one or two times\n # as this means we check if msg satisfies any of the sequences of rules\n # 42 42 42 31 31, 42 42 42 31, both allowed by rule 0\n for _ in range(max_satisfy_42):\n msg = satisfy_rule(msg, rules, 42)\n\n rest_msg = msg\n for i in range(1, max_satisfy_42):\n rest_msg = satisfy_rule(rest_msg, rules, 31)\n\n if rest_msg == \"\":\n return True\n elif rest_msg == False:\n return False\n\n return False\n\n\nif __name__ == \"__main__\":\n print(part2())\n" }, { "alpha_fraction": 0.53861004114151, "alphanum_fraction": 0.5598455667495728, "avg_line_length": 29.47058868408203, "blob_id": "f7b05f499d83e6a30d15968d8ebe0f581f1e56cd", "content_id": "525177d998be7f0dd89628ef434c4732e2ee0d64", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1554, "license_type": "no_license", "max_line_length": 79, "num_lines": 51, "path": "/Day15/day15.py", "repo_name": "steve-jang/Advent-of-Code-2020", "src_encoding": "UTF-8", "text": "STARTING_NUMBERS = [16, 11, 15, 0, 1, 7]\n\n\ndef solution(n):\n # numbers_spoken contains number-occurence pairs, where occurence\n # is a list containing the turn numbers of up to 2 previous occurences\n # of number, with the last element being the most recent turn of occurence.\n numbers_spoken = {}\n\n for t in range(n):\n if t < 6:\n # Starting numbers\n current_number = STARTING_NUMBERS[t]\n numbers_spoken[current_number] = [t]\n else:\n occurences = numbers_spoken.get(current_number)\n if occurences:\n length = len(occurences)\n if length == 1:\n current_number = 0\n elif length == 2:\n current_number = occurences[1] - occurences[0]\n else:\n raise Exception(\"invalid occurences len\")\n\n store_number(numbers_spoken, current_number, t)\n else:\n raise Exception(\"numbers not stored properly\")\n\n return current_number\n\n\ndef store_number(numbers_spoken, number, turn):\n if numbers_spoken.get(number):\n length = len(numbers_spoken[number])\n if length == 1:\n numbers_spoken[number].append(turn)\n elif length == 2:\n numbers_spoken[number] = [numbers_spoken[number][1], turn]\n else:\n raise Exception\n else:\n numbers_spoken[number] = [turn]\n\n\nif __name__ == \"__main__\":\n # Part 1\n print(solution(2020))\n\n # Part 2\n print(solution(30000000))\n" }, { "alpha_fraction": 0.5398048162460327, "alphanum_fraction": 0.543913722038269, "avg_line_length": 27.423357009887695, "blob_id": "96a21f446d2c5d59be9af3a4ee21b086e15a5a77", "content_id": "be740b4e17ee4c1c6193eda84167a2e358e91e35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3894, "license_type": "no_license", "max_line_length": 77, "num_lines": 137, "path": "/Day20/day20.py", "repo_name": "steve-jang/Advent-of-Code-2020", "src_encoding": "UTF-8", "text": "TOP = \"TOP\"\nBOTTOM = \"BOTTOM\"\nLEFT = \"LEFT\"\nRIGHT = \"RIGHT\"\n\n\nclass Tile:\n def __init__(self, tile_id, pattern):\n self.pattern = pattern\n self.tile_id = tile_id\n\n # Adjacent tiles that match the border\n self.adj_tiles = {TOP: None, BOTTOM: None, LEFT: None, RIGHT: None}\n\n def get_border(self, location):\n if location == TOP:\n return self.pattern[0]\n elif location == BOTTOM:\n return self.pattern[-1]\n elif location == LEFT:\n return \"\".join([row[0] for row in self.pattern])\n elif location == RIGHT:\n return \"\".join([row[-1] for row in self.pattern])\n else:\n raise ValueError(\"Invalid location\")\n\n def get_all_borders(self):\n return {TOP: self.get_border(TOP),\n BOTTOM: self.get_border(BOTTOM),\n LEFT: self.get_border(LEFT),\n RIGHT: self.get_border(RIGHT),}\n\n def rotate_right(self):\n new_pattern = []\n for i in range(len(self.pattern)):\n new_row = []\n for row in self.pattern:\n new_row.append(row[i])\n\n new_pattern.append(\"\".join(reversed(new_row)))\n\n self.pattern = new_pattern\n\n def flip_vertical(self):\n size = len(self.pattern)\n for i in range(size // 2):\n temp_row = self.pattern[i]\n self.pattern[i] = self.pattern[size - i - 1]\n self.pattern[size - i - 1] = temp_row\n\n\ndef get_match_data(static_tile, tiles):\n # Return matches, a dict containing (border position)-(matching tiles)\n # pairs, where matching borders is a list of all tiles which matches\n # the border of static_tile at border position when rotated and/or\n # reflected.\n static_tile_borders = static_tile.get_all_borders()\n matches = {}\n\n # Return True if through only the rotation of the mobile tile,\n # there is a matching pair of borders between both given tiles.\n def check_rotation_match(tile):\n for _ in range(4):\n tile.rotate_right()\n borders = tile.get_all_borders()\n\n found = False\n if borders[TOP] == static_tile_borders[BOTTOM]:\n matches[BOTTOM] = tile\n found = True\n if borders[BOTTOM] == static_tile_borders[TOP]:\n matches[TOP] = tile\n found = True\n if borders[LEFT] == static_tile_borders[RIGHT]:\n matches[RIGHT] = tile\n found = True\n if borders[RIGHT] == static_tile_borders[LEFT]:\n matches[LEFT] = tile\n found = True\n\n if found:\n return True\n\n return False\n\n for tile_n in tiles:\n tile = tiles[tile_n]\n if tile.tile_id == static_tile.tile_id:\n continue\n\n rotation_match = check_rotation_match(tile)\n if not rotation_match:\n # If rotating did not produce a match, reflect tile and try again\n tile.flip_vertical()\n if not check_rotation_match(tile):\n tile.flip_vertical()\n\n return matches\n\n\ndef part1():\n tiles = get_tiles()\n\n # Corner tiles only have 2 borders which match others\n corner_tiles = []\n for t in tiles:\n matches = get_match_data(tiles[t], tiles)\n if len(list(matches.values())) == 2:\n corner_tiles.append(t)\n\n prod = 1\n for n in corner_tiles:\n prod *= n\n\n return prod\n\n\ndef get_tiles():\n f = open(\"input.txt\", \"r\")\n tiles = {}\n\n line = f.readline()\n while line:\n if \"Tile\" in line:\n tile_id = int(line.split()[1][:-1])\n tiles[tile_id] = Tile(tile_id, [])\n elif line != \"\\n\":\n tiles[tile_id].pattern.append(line[:-1])\n\n line = f.readline()\n\n f.close()\n return tiles\n\n\nif __name__ == \"__main__\":\n print(part1())\n" }, { "alpha_fraction": 0.5629168748855591, "alphanum_fraction": 0.5927078723907471, "avg_line_length": 22.9255313873291, "blob_id": "fa4585b564e8f3d7529a4475887c4610309bda61", "content_id": "c18baa04630b759fc5e1410092171ba7e32ee71f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2249, "license_type": "no_license", "max_line_length": 61, "num_lines": 94, "path": "/Day23/day23.py", "repo_name": "steve-jang/Advent-of-Code-2020", "src_encoding": "UTF-8", "text": "CUPS = [7, 8, 9, 4, 6, 5, 1, 2, 3]\n\n\nclass Cup:\n def __init__(self, number, next_cup):\n self.number = number\n self.next = next_cup\n\n\ndef part1():\n # cups is a dict containing (cup number)-Cup pairs\n cups = store_cups(CUPS)\n\n first_cup = cups[CUPS[0]]\n for _ in range(100):\n first_cup = move_cups(first_cup, cups, 9)\n\n # Starting from the cup after cup 1, find next cups\n result = \"\"\n current_cup = cups[1].next\n for _ in range(8):\n result += str(current_cup.number)\n current_cup = current_cup.next\n\n return result\n\n\ndef store_cups(all_cups):\n prev_cup = None\n cups = {}\n for cup in all_cups:\n current_cup = Cup(cup, None)\n cups[cup] = current_cup\n if prev_cup:\n prev_cup.next = current_cup\n\n prev_cup = current_cup\n\n # Make last cup's next be the first cup to complete cycle\n first_cup = cups[all_cups[0]]\n last_cup = cups[all_cups[-1]]\n last_cup.next = first_cup\n\n return cups\n\n\ndef move_cups(first_cup, cups, max_cup):\n # Return the next first cup after doing one move.\n # Get the next three cups\n next1 = first_cup.next\n next2 = next1.next\n next3 = next2.next\n\n new_first_cup = next3.next\n\n invalid_targets = [first_cup.number, next1.number,\n next2.number, next3.number]\n\n # Find destination cup\n target_number = first_cup.number - 1\n if target_number <= 0:\n target_number = max_cup\n\n while target_number in invalid_targets:\n if target_number == 1:\n target_number = max_cup\n else:\n target_number -= 1\n\n # Move the three cups after destination cup\n dest_cup = cups[target_number]\n dest_next = dest_cup.next\n dest_cup.next = next1\n next3.next = dest_next\n\n first_cup.next = new_first_cup\n return new_first_cup\n\n\ndef part2():\n cups_order = CUPS[:] + [i for i in range(10, 1000001)]\n cups = store_cups(cups_order)\n\n first_cup = cups[cups_order[0]]\n for i in range(10000000):\n first_cup = move_cups(first_cup, cups, 1000000)\n\n # Find the 2 cups after cup 1\n return cups[1].next.number * cups[1].next.next.number\n\n\nif __name__ == \"__main__\":\n print(part1())\n print(part2())\n" }, { "alpha_fraction": 0.5320372581481934, "alphanum_fraction": 0.5416210293769836, "avg_line_length": 24.01369857788086, "blob_id": "5ea6e0961486bbbed9db7f61974fce196bd2388c", "content_id": "890f586eb5d5225802d21794905a8ba6db13c72e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3652, "license_type": "no_license", "max_line_length": 78, "num_lines": 146, "path": "/Day24/day24.py", "repo_name": "steve-jang/Advent-of-Code-2020", "src_encoding": "UTF-8", "text": "BLACK = 1\nWHITE = 2\n\n\ndef part1():\n tile_positions = get_tile_positions()\n tiles = setup_tiles(tile_positions)\n\n return black_tile_count(tiles)\n\n\ndef black_tile_count(tiles):\n count = 0\n for pos in tiles:\n if tiles[pos] == BLACK:\n count += 1\n\n return count\n\n\ndef setup_tiles(tile_positions):\n tiles = {(0, 0): WHITE}\n\n for tile_pos in tile_positions:\n if tiles.get(tile_pos):\n if tiles[tile_pos] == WHITE:\n tiles[tile_pos] = BLACK\n else:\n tiles[tile_pos] = WHITE\n else:\n tiles[tile_pos] = BLACK\n\n return tiles\n\n\ndef get_tile_positions():\n f = open(\"input.txt\", \"r\")\n lines = [line[:-1] for line in f.readlines()]\n f.close()\n\n tiles = []\n for line in lines:\n current_tile = []\n i = 0\n while i < len(line):\n c = line[i]\n if c == \"n\" or c == \"s\":\n current_tile.append(c + line[i + 1])\n i += 2\n else:\n current_tile.append(c)\n i += 1\n\n current_tile = simplify_tile(current_tile)\n tiles.append(current_tile)\n\n return tiles\n\n\ndef simplify_tile(tile_pos):\n # Remove redundant directions (e.g. nw then se), and change all\n # directions to be one of e, s, ne, and sw. Use a skewed-axis\n # coordinate system to represent the tile position, where the\n # positive x axis is the e direction, and the positive y axis is\n # the ne direction. Return the coordinate.\n direction_freq = {pos: 0 for pos in [\"nw\", \"ne\", \"sw\", \"se\", \"w\", \"e\"]}\n\n # First change all nw to w ne, and all se to e sw.\n for direction in tile_pos:\n if direction == \"nw\":\n direction_freq[\"w\"] += 1\n direction_freq[\"ne\"] += 1\n elif direction == \"se\":\n direction_freq[\"e\"] += 1\n direction_freq[\"sw\"] += 1\n else:\n direction_freq[direction] += 1\n\n east_dir = direction_freq[\"e\"] - direction_freq[\"w\"]\n ne_dir = direction_freq[\"ne\"] - direction_freq[\"sw\"]\n return east_dir, ne_dir\n\n\ndef part2():\n tile_positions = get_tile_positions()\n tiles = setup_tiles(tile_positions)\n tiles = track_adj_blacks(tiles)\n\n for i in range(100):\n tiles = update_tiles(tiles)\n\n return black_tile_count(tiles)\n\n\ndef track_adj_blacks(tiles):\n new_tiles = {}\n for coords in tiles:\n if tiles[coords] == BLACK:\n neighbours = get_neighbours(coords)\n for pos in neighbours:\n if not tiles.get(pos):\n new_tiles[pos] = WHITE\n else:\n new_tiles[pos] = tiles[pos]\n\n new_tiles[coords] = BLACK\n\n return new_tiles\n\n\ndef get_neighbours(coords):\n result = []\n for i in range(-1, 2):\n for j in range(-1, 2):\n if i != j:\n result.append((coords[0] + i, coords[1] + j))\n\n return result\n\n\ndef update_tiles(tiles):\n new_tiles = {}\n for coords in tiles:\n # Find only the new black tiles\n adj_blacks = adj_black_count(coords, tiles)\n if tiles[coords] == BLACK and not (adj_blacks == 0 or adj_blacks > 2):\n new_tiles[coords] = BLACK\n elif tiles[coords] == WHITE and adj_blacks == 2:\n new_tiles[coords] = BLACK\n\n new_tiles = track_adj_blacks(new_tiles)\n return new_tiles\n\n\ndef adj_black_count(coords, tiles):\n count = 0\n for coords in get_neighbours(coords):\n if tiles.get(coords) and tiles[coords] == BLACK:\n count += 1\n\n return count\n\n\nif __name__ == \"__main__\":\n print(part1())\n print(part2())\n" }, { "alpha_fraction": 0.45661452412605286, "alphanum_fraction": 0.467520147562027, "avg_line_length": 26.038461685180664, "blob_id": "73bca23cb263dbffc4268e3c42b98876993b6a1d", "content_id": "5dd2f0d5e970b08216ca403a70a6eff8d69c4bb0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2109, "license_type": "no_license", "max_line_length": 75, "num_lines": 78, "path": "/Day14/day14.py", "repo_name": "steve-jang/Advent-of-Code-2020", "src_encoding": "UTF-8", "text": "def part1():\n # Get components of each line of input\n f = open(\"input.txt\", \"r\")\n lines = [l[:-1].split() for l in f.readlines()]\n\n # memory contains address-value pairs\n memory = {}\n\n current_mask = \"\"\n for keyword, _, arg in lines:\n # keyword is mask or mem[x], arg is the number after = of the line.\n if keyword == \"mask\":\n current_mask = arg\n else:\n # Convert given value to binary as a string\n bin_str_arg = bin(int(arg))[2:].zfill(36)\n result = \"\"\n for i, c in enumerate(current_mask):\n if c == \"X\":\n result += bin_str_arg[i]\n else:\n result += c\n\n result = int(result, 2)\n address = keyword[4:-1]\n memory[address] = result\n\n return sum(memory.values())\n\n\ndef part2():\n f = open(\"input.txt\", \"r\")\n lines = [l[:-1].split() for l in f.readlines()]\n\n memory = {}\n current_mask = \"\"\n for keyword, _, arg in lines:\n if keyword == \"mask\":\n current_mask = arg\n else:\n address = int(keyword[4:-1])\n bin_str_address = bin(address)[2:].zfill(36)\n new_address = \"\"\n for i, c in enumerate(current_mask):\n if c == \"0\":\n new_address += bin_str_address[i]\n else:\n # If 1, then add 1, if X then add X\n new_address += c\n\n value = int(arg)\n addresses = get_addresses(new_address)\n for a in addresses:\n memory[int(a, 2)] = value\n\n return sum(memory.values())\n\n\ndef get_addresses(float_address):\n result = [\"\"]\n for c in float_address:\n new_result = []\n if c != \"X\":\n for a in result:\n new_result.append(a + c)\n else:\n for a in result:\n new_result.append(a + \"1\")\n new_result.append(a + \"0\")\n\n result = new_result\n\n return result\n\n\nif __name__ == \"__main__\":\n print(part1())\n print(part2())\n" }, { "alpha_fraction": 0.6010291576385498, "alphanum_fraction": 0.6051458120346069, "avg_line_length": 25.990739822387695, "blob_id": "9b57d1d18f6445032de7ec11f296c8acf1ca9c51", "content_id": "f3d7de96b4dcf32775966121282a155611a2ccf5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2915, "license_type": "no_license", "max_line_length": 78, "num_lines": 108, "path": "/Day21/day21.py", "repo_name": "steve-jang/Advent-of-Code-2020", "src_encoding": "UTF-8", "text": "def part1():\n food_clues = read_food_list()\n\n possible_words = set()\n for allergen in food_clues:\n common_words = get_common_words(food_clues[allergen])\n for w in common_words:\n possible_words.add(w)\n\n ingredients = read_only_ingredients()\n impossible_word_freq = 0\n for food in ingredients:\n if food not in possible_words:\n impossible_word_freq += 1\n\n return impossible_word_freq\n\n\ndef get_common_words(sets):\n # Return words that appear in all of the given sets\n common_words = []\n for word in sets[0]:\n if all([word in sets[i] for i in range(1, len(sets))]):\n common_words.append(word)\n\n return common_words\n\n\ndef read_food_list():\n f = open(\"input.txt\", \"r\")\n\n # clues is dictionary containing allergen-(list of sets of possible words)\n # pairs\n clues = {}\n for line in f.readlines():\n words, allergens = line.split(\" (contains \")\n words = set(words.split())\n allergens = allergens[:-2].split(\", \")\n\n for allergen in allergens:\n if not clues.get(allergen):\n clues[allergen] = [words]\n else:\n clues[allergen].append(words)\n\n f.close()\n return clues\n\n\ndef read_only_ingredients():\n f = open(\"input.txt\", \"r\")\n\n ingredients = []\n for line in f.readlines():\n words, _ = line.split(\" (contains \")\n ingredients += words.split()\n\n return ingredients\n\n\ndef part2():\n food_clues = read_food_list()\n\n possible_words = set()\n for allergen in food_clues:\n food_clues[allergen] = get_common_words(food_clues[allergen])\n\n # Match words to allergens until the solution is no longer updated\n matched_words = {}\n while True:\n outcome = match_words_to_allergens(matched_words, food_clues)\n if not outcome:\n break\n\n # Sort by allergen alphabetical order\n sorted_allergens = sorted(list(matched_words.keys()))\n\n # Generate canonical dangerous ingredient list\n result = \"\"\n for allergen in sorted_allergens:\n result += f\"{matched_words[allergen]},\"\n\n # Remove last trailing comma\n return result[:-1]\n\n\ndef match_words_to_allergens(matched_words, food_clues):\n # Populate matched_words with word-allergen pairs where word\n # matches the allergen. If none were matched, return False.\n updated = False\n for allergen in food_clues:\n if len(food_clues[allergen]) == 1:\n # Determine which words must match\n match = food_clues[allergen][0]\n matched_words[allergen] = match\n updated = True\n\n # Remove matched word from all other clues\n for allergen in food_clues:\n if match in food_clues[allergen]:\n food_clues[allergen].remove(match)\n\n return updated\n\n\nif __name__ == \"__main__\":\n print(part1())\n print(part2())\n" }, { "alpha_fraction": 0.5623778700828552, "alphanum_fraction": 0.5707507729530334, "avg_line_length": 25.738805770874023, "blob_id": "280b2d52dd05252b116a25e029c7aa5008526eb2", "content_id": "1949a07eb6b43f8cefbe82842d4e9309c97c777b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3583, "license_type": "no_license", "max_line_length": 81, "num_lines": 134, "path": "/Day18/day18.py", "repo_name": "steve-jang/Advent-of-Code-2020", "src_encoding": "UTF-8", "text": "def part1():\n f = open(\"input.txt\", \"r\")\n lines = [line[:-1] for line in f.readlines()]\n f.close()\n\n result = 0\n for line in lines:\n result += evaluate_line(line)\n\n return result\n\n\ndef evaluate_line(line):\n # Remove spaces and evaluate parentheses first\n expression = \"\".join(line.split())\n simplified_expression = evaluate_parens(expression, evaluate_line)\n\n result = 0\n i = 0\n while i < len(simplified_expression):\n symbol = simplified_expression[i]\n\n if i == 0:\n next_number, digits = find_next_number(-1, simplified_expression)\n result += next_number\n i += digits\n elif symbol == \"+\":\n next_number, digits = find_next_number(i, simplified_expression)\n result += next_number\n i += digits + 1\n else:\n # symbol == \"*\"\n next_number, digits = find_next_number(i, simplified_expression)\n result *= next_number\n i += digits + 1\n\n return result\n\n\ndef find_next_number(index, expression):\n # Return the next number in the expression after the given index.\n # If index = -1, then the first number of the expression is returned.\n result = \"\"\n index += 1\n\n while True:\n if index < len(expression) and expression[index].isnumeric():\n result += expression[index]\n else:\n return int(result), len(result)\n\n index += 1\n\n\ndef evaluate_parens(expression, eval_function):\n # Convert expression into a simplified expression containing no parens.\n new_expression = \"\"\n i = 0\n\n while i < len(expression):\n symbol = expression[i]\n\n if symbol == \"(\":\n close_paren = find_close_paren(i, expression)\n\n # Evaluate parentheses as separate expressions\n new_expression += str(eval_function(expression[i + 1:close_paren]))\n i = close_paren\n elif symbol != \")\":\n new_expression += symbol\n\n i += 1\n\n return new_expression\n\n\ndef find_close_paren(open_paren, expression):\n # Return the index of the closing parenthesis matching the open\n # parenthesis at index open_paren, in expression.\n opened = 0\n for i, symbol in enumerate(expression):\n if i < open_paren:\n continue\n\n if symbol == \"(\":\n opened += 1\n elif symbol == \")\":\n opened -= 1\n\n if opened == 0:\n return i\n\n\ndef part2():\n f = open(\"input.txt\", \"r\")\n lines = [line[:-1] for line in f.readlines()]\n f.close()\n\n result = 0\n for line in lines:\n result += evaluate_line_advanced(line)\n\n return result\n\n\ndef evaluate_line_advanced(line):\n expression = \"\".join(line.split())\n simplified_expression = evaluate_parens(expression, evaluate_line_advanced)\n\n result = 0\n i = 0\n while i < len(simplified_expression):\n symbol = simplified_expression[i]\n\n if i == 0:\n next_number, digits = find_next_number(-1, simplified_expression)\n result += next_number\n i += digits\n elif symbol == \"+\":\n next_number, digits = find_next_number(i, simplified_expression)\n result += next_number\n i += digits + 1\n else:\n # symbol == \"*\"\n # Evaluate rest of expression first, then multiply result, as\n # * has lowest precedence\n return result * evaluate_line_advanced(simplified_expression[i + 1:])\n\n return result\n\n\nif __name__ == \"__main__\":\n print(part1())\n print(part2())\n" }, { "alpha_fraction": 0.5824130773544312, "alphanum_fraction": 0.5865030884742737, "avg_line_length": 27.764705657958984, "blob_id": "90b3b45011a0048e939fec8a4a6ccdc4f324c37e", "content_id": "af93380d9216cf82802c004c0dd1162a5ee33682", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2445, "license_type": "no_license", "max_line_length": 78, "num_lines": 85, "path": "/Day19/day19.py", "repo_name": "steve-jang/Advent-of-Code-2020", "src_encoding": "UTF-8", "text": "def part1():\n rules = read_rules()\n messages = read_messages()\n\n valid_messages = 0\n for msg in messages:\n if is_rule_satisfied(msg, rules, rule_number=0):\n valid_messages += 1\n\n return valid_messages\n\n\ndef read_rules():\n # Returns a dictionary of (rule number)-(list of rules) pairs.\n f = open(\"rules.txt\", \"r\")\n rules = [line[:-1] for line in f.readlines()]\n f.close()\n\n result = {}\n for rule in rules:\n rule_number, sub_rules = rule.split(\": \")\n rule_number = int(rule_number)\n result[rule_number] = []\n\n if \"\\\"\" in sub_rules:\n result[rule_number].append(sub_rules[1:-1])\n else:\n sub_rules = sub_rules.split(\" | \")\n for sub_rule in sub_rules:\n result[rule_number].append([int(n) for n in sub_rule.split()])\n\n return result\n\n\ndef read_messages():\n # Returns a list of messages as strings.\n f = open(\"messages.txt\", \"r\")\n messages = [line[:-1] for line in f.readlines()]\n\n f.close()\n return messages\n\n\ndef is_rule_satisfied(msg, rules, rule_number):\n # Rule is satisfied completely if after satisfying, there are no more\n # letters to check in the message.\n return satisfy_rule(msg, rules, rule_number) == \"\"\n\n\ndef satisfy_rule(msg, rules, rule_number):\n # Return the remaining part of the given message after satisfying\n # the given rule, or False if the rule cannot be satisfied.\n for sub_rule in rules[rule_number]:\n if type(sub_rule) == str:\n # Rules with characters\n if msg[:len(sub_rule)] == sub_rule:\n return msg[len(sub_rule):]\n else:\n return False\n else:\n # Rules with sub rule sequences\n rest_msg = satisfy_rule_sequence(msg, sub_rule, rules)\n if rest_msg != False:\n return rest_msg\n\n return False\n\n\ndef satisfy_rule_sequence(msg, rule_seq, rules):\n # Return the remaining part of the given message after satisfying\n # the given sequence of rules, or False if the rule cannot be satisfied.\n if not rule_seq:\n # Base case\n return msg\n\n for rule_number in rule_seq:\n rest_msg = satisfy_rule(msg, rules, rule_number)\n if rest_msg is False:\n return False\n else:\n return satisfy_rule_sequence(rest_msg, rule_seq[1:], rules)\n\n\nif __name__ == \"__main__\":\n print(part1())\n" }, { "alpha_fraction": 0.5722610950469971, "alphanum_fraction": 0.5776223540306091, "avg_line_length": 29.4255313873291, "blob_id": "fa8da3cc435daa434b65dead0c639fb58e229676", "content_id": "f59122d50e8ebd5bde6e80a42210833aacfec173", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4290, "license_type": "no_license", "max_line_length": 76, "num_lines": 141, "path": "/Day20/day20_part2.py", "repo_name": "steve-jang/Advent-of-Code-2020", "src_encoding": "UTF-8", "text": "from day20 import Tile, get_tiles, get_match_data, TOP, BOTTOM, LEFT, RIGHT\n\n\ndef part2():\n tiles = get_tiles()\n top_left = arrange_tiles(tiles)\n ocean = get_ocean_map(top_left)\n monster = [\" # \",\n \"# ## ## ###\",\n \" # # # # # # \"]\n\n # Rotate ocean map to find sea monsters\n monster_coords = rotate_ocean_for_monsters(ocean, monster)\n if not monster_coords:\n # If no monsters found flip the ocean and try again\n flip_vertical(ocean)\n monster_coords = rotate_ocean_for_monsters(ocean, monster)\n\n # Unoccupied coordinates is the number of \"#\" in ocean minus the\n # occupied coordinates\n return sum([row.count(\"#\") for row in ocean]) - len(monster_coords)\n\n\ndef rotate_ocean_for_monsters(ocean, monster):\n monster_width = len(monster[0])\n monster_height = len(monster)\n\n ocean_height = len(ocean)\n ocean_width = len(ocean[0])\n\n # Rotate the given ocean to find sea monsters, if any monsters are found\n # return the coordinates occupied by the monsters.\n for _ in range(4):\n monster_coords = set()\n for x in range(ocean_height - monster_height + 1):\n for y in range(ocean_width - monster_width + 1):\n occupied_coords = find_monster_coords(ocean, monster, x, y)\n for coord in occupied_coords:\n monster_coords.add(coord)\n\n if monster_coords:\n return monster_coords\n\n ocean = rotate_right(ocean)\n\n\ndef flip_vertical(pattern):\n # Assume pattern is square\n size = len(pattern)\n for i in range(size // 2):\n temp_row = pattern[i]\n pattern[i] = pattern[size - i - 1]\n pattern[size - i - 1] = temp_row\n\n\ndef rotate_right(pattern):\n new_pattern = []\n for i in range(len(pattern)):\n new_row = []\n for row in pattern:\n new_row.append(row[i])\n\n new_pattern.append(\"\".join(reversed(new_row)))\n\n return new_pattern\n\n\ndef find_monster_coords(ocean, monster, x, y):\n # Return a set of all coordinates occupied by any monster found\n # in the given ocean with top left coordinate (x, y).\n occupied = set()\n for i, row in enumerate(monster):\n for j, c in enumerate(row):\n if c == \"#\":\n if ocean[x + i][y + j] != \"#\":\n return set()\n else:\n occupied.add((x + i, y + j))\n\n return occupied\n\n\ndef arrange_tiles(tiles):\n # Set adjacency info for all tiles. Also return the top left tile\n # after arranging, so that the arranged tiles can be traversed.\n todo = [list(tiles.values())[0]]\n tiles_seen = set()\n\n # For each tile set its adjacency data, and get the top left tile\n while todo:\n tile = todo.pop(-1)\n if tile.tile_id in tiles_seen:\n continue\n\n matches = get_match_data(tile, tiles)\n\n # Top left tile has no matching tile on top nor on the left\n if not (matches.get(TOP) or matches.get(LEFT)):\n top_left_tile = tile\n\n opp = {TOP: BOTTOM, BOTTOM: TOP, LEFT: RIGHT, RIGHT: LEFT}\n\n for pos in opp:\n pos_tile = matches.get(pos)\n if pos_tile:\n tile.adj_tiles[pos] = pos_tile\n pos_tile.adj_tiles[opp[pos]] = tile\n todo.append(pos_tile)\n\n tiles_seen.add(tile.tile_id)\n\n return top_left_tile\n\n\ndef get_ocean_map(top_left_tile):\n # Join arranged tiles together, without each tile's boundaries\n n_rows = 8 * 12\n ocean = [\"\" for _ in range(n_rows)]\n current_row_tile = top_left_tile\n current_tile = top_left_tile\n current_row = 0\n while current_row_tile:\n while current_tile:\n current_tile.pattern = current_tile.pattern[1:-1]\n for n, row in enumerate(current_tile.pattern):\n current_tile.pattern[n] = row[1:-1]\n\n for i, row in enumerate(current_tile.pattern):\n ocean[current_row + i] += current_tile.pattern[i]\n\n current_tile = current_tile.adj_tiles[RIGHT]\n\n current_row_tile = current_row_tile.adj_tiles[BOTTOM]\n current_tile = current_row_tile\n current_row += 8\n\n return ocean\n\n\nif __name__ == \"__main__\":\n print(part2())\n" }, { "alpha_fraction": 0.5612068772315979, "alphanum_fraction": 0.5693965554237366, "avg_line_length": 24.217391967773438, "blob_id": "3c8724efb2e0447fc3c0dc7bbc30de6c43436ad3", "content_id": "1a9c9277c90a109dbeed08eb9cda422161be7c5d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2320, "license_type": "no_license", "max_line_length": 69, "num_lines": 92, "path": "/Day17/day17.py", "repo_name": "steve-jang/Advent-of-Code-2020", "src_encoding": "UTF-8", "text": "CYCLES = 6\n\n\nclass Cube:\n def __init__(self, active, adj_active=0):\n self.active = active\n self.adj_active = adj_active\n\n\ndef simulate(dimension):\n # Store only active cubes as coordinates (x, y, z)\n # Assume dimension >= 2\n f = open(\"input.txt\", \"r\")\n lines = [line[:-1] for line in f.readlines()]\n\n active_cubes = {}\n\n # Store all initially active cubes\n for x, row in enumerate(lines):\n for y, cube in enumerate(row):\n if cube == \"#\":\n coord = (x, y)\n for _ in range(dimension - 2):\n coord += (0,)\n\n active_cubes[coord] = Cube(True)\n\n # Also store all inactive cubes adjacent to active cubes, and set\n # all cubes' active neighbour count\n cubes = active_cubes.copy()\n set_adj_cubes(active_cubes, cubes)\n\n for _ in range(CYCLES):\n cubes = update_state(cubes)\n\n result = 0\n for coords in cubes:\n if cubes[coords].active:\n result += 1\n\n return result\n\n\ndef get_neighbours(*coords):\n result = []\n dimensions = len(coords)\n\n def get_neighbours_rec(dim, rsf):\n if dim == dimensions:\n result.append(rsf)\n else:\n for x in range(coords[dim] - 1, coords[dim] + 2):\n get_neighbours_rec(dim + 1, rsf + (x,))\n\n get_neighbours_rec(0, ())\n result.remove(coords)\n return result\n\n\ndef set_adj_cubes(active_cubes, dest_cubes):\n for k in active_cubes:\n adj_cubes_coords = get_neighbours(*k)\n for coords in adj_cubes_coords:\n if not dest_cubes.get(coords):\n dest_cubes[coords] = Cube(False, 1)\n else:\n dest_cubes[coords].adj_active += 1\n\n\n\ndef update_state(cubes):\n new_active_cubes = {}\n\n # Find all next active cubes\n for coord in cubes:\n cube = cubes[coord]\n if (cube.active and cube.adj_active in [2, 3] or\n not cube.active and cube.adj_active == 3):\n new_active_cubes[coord] = Cube(True)\n\n new_state = new_active_cubes.copy()\n\n # Store all inactive cubes adjacent to active cubes,\n # and set adj cube count\n set_adj_cubes(new_active_cubes, new_state)\n\n return new_state\n\n\nif __name__ == \"__main__\":\n print(simulate(dimension=3))\n print(simulate(dimension=4))\n" }, { "alpha_fraction": 0.5358100533485413, "alphanum_fraction": 0.5679816007614136, "avg_line_length": 27.380434036254883, "blob_id": "b51eef96ae36178210d47b51bab5dbf8c3c9195b", "content_id": "c583a34aaf96a564b77418c329bdbc2904ba39ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2611, "license_type": "no_license", "max_line_length": 67, "num_lines": 92, "path": "/Day22/day22.py", "repo_name": "steve-jang/Advent-of-Code-2020", "src_encoding": "UTF-8", "text": "def part1():\n player1_deck, player2_deck = get_decks()\n\n # Play until one player runs out of cards\n while player1_deck and player2_deck:\n player1_top_card = player1_deck.pop(0)\n player2_top_card = player2_deck.pop(0)\n\n if player1_top_card > player2_top_card:\n player1_deck += [player1_top_card, player2_top_card]\n elif player2_top_card > player1_top_card:\n player2_deck += [player2_top_card, player1_top_card]\n\n # Calculate score\n winning_deck = player1_deck if player1_deck else player2_deck\n winning_deck.reverse()\n score = 0\n for i, card in enumerate(winning_deck):\n score += (i + 1) * card\n\n return score\n\n\ndef get_decks():\n f = open(\"input.txt\", \"r\")\n player1_deck = []\n player2_deck = []\n\n current_deck = player1_deck\n while True:\n line = f.readline()\n if not line:\n break\n\n line = line[:-1]\n if line.isnumeric():\n current_deck.append(int(line))\n elif \"Player 2\" in line:\n current_deck = player2_deck\n\n f.close()\n return player1_deck, player2_deck\n\n\ndef part2():\n player1_deck, player2_deck = get_decks()\n _, winning_deck = play_game(player1_deck, player2_deck)\n\n winning_deck.reverse()\n score = 0\n for i, card in enumerate(winning_deck):\n score += (i + 1) * card\n\n return score\n\n\ndef play_game(player1_deck, player2_deck):\n seen_configs = set()\n while True:\n if not player1_deck:\n return \"Player 2\", player2_deck\n if not player2_deck:\n return \"Player 1\", player1_deck\n\n current_config = (tuple(player1_deck), tuple(player2_deck))\n if current_config in seen_configs:\n # Infinite game prevention rule\n return \"Player 1\", player1_deck\n\n seen_configs.add(current_config)\n\n player1_card = player1_deck.pop(0)\n player2_card = player2_deck.pop(0)\n\n if (len(player1_deck) >= player1_card and\n len(player2_deck) >= player2_card):\n winner, _ = play_game(player1_deck[:player1_card],\n player2_deck[:player2_card])\n if winner == \"Player 1\":\n player1_deck += [player1_card, player2_card]\n else:\n player2_deck += [player2_card, player1_card]\n else:\n if player1_card > player2_card:\n player1_deck += [player1_card, player2_card]\n else:\n player2_deck += [player2_card, player1_card]\n\n\nif __name__ == \"__main__\":\n print(part1())\n print(part2())\n" } ]
15
turningpoint1988/streetlearn
https://github.com/turningpoint1988/streetlearn
4b68b281957d4ea1dbe46289e7e1a74066bc558d
dd348cb811064582a77abe855b9ac15799e4a1ef
1a2b97f1d73ede15fa5523c28f80c3e12e2df4ab
refs/heads/master
2020-04-28T20:01:30.771012
2019-03-29T06:08:36
2019-03-29T06:08:36
175,530,059
0
0
Apache-2.0
2019-03-14T01:59:49
2019-03-13T08:18:44
2019-03-04T22:06:35
null
[ { "alpha_fraction": 0.7354804873466492, "alphanum_fraction": 0.7470961213111877, "avg_line_length": 34.73584747314453, "blob_id": "ca9ebf50b1cf31d649261a9e3f1307c21f269b06", "content_id": "44e536de7385dfe833050ae3b4b59cef92259b5f", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1894, "license_type": "permissive", "max_line_length": 80, "num_lines": 53, "path": "/streetlearn/engine/pano_projection.h", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#ifndef THIRD_PARTY_STREETLEARN_ENGINE_PANO_PROJECTION_H_\n#define THIRD_PARTY_STREETLEARN_ENGINE_PANO_PROJECTION_H_\n\n#include <memory>\n\n#include \"streetlearn/engine/image.h\"\n\nnamespace streetlearn {\n\n// Each Street View panorama is an image that provides a full 360-degree view\n// from a single location. Images conform to the equirectangular projection,\n// which contains 360 degrees of horizontal view (a full wrap-around) and\n// 180 degrees of vertical view (from straight up to straight down). The\n// resulting 360-degree panorama defines a projection on a sphere with the image\n// wrapped to the two-dimensional surface of that sphere.\n// Panorama images are projected onto a narrow field of view image at a given\n// pitch and yaw w.r.t. the panorama heading.\nclass PanoProjection {\n public:\n PanoProjection(double fov_deg, int proj_width, int proj_height);\n ~PanoProjection();\n\n // Projects a panorama image input into an output image at specified yaw and\n // pitch angles.\n void Project(const Image3_b& input, double yaw_deg, double pitch_deg,\n Image3_b* output);\n\n // Changes the field of view.\n void ChangeFOV(double fov_deg);\n\n private:\n struct Impl;\n\n std::unique_ptr<Impl> impl_;\n};\n\n} // namespace streetlearn\n\n#endif // THIRD_PARTY_STREETLEARN_ENGINE_PANO_PROJECTION_H_\n" }, { "alpha_fraction": 0.6714837551116943, "alphanum_fraction": 0.6771970987319946, "avg_line_length": 34.4226188659668, "blob_id": "ad5cf9290c428f326f8a16f4a2a3f24372a71453", "content_id": "e036300f6d97aec1efd5551f8fddf827f7862aec", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": true, "language": "C++", "length_bytes": 5951, "license_type": "permissive", "max_line_length": 80, "num_lines": 168, "path": "/third_party/absl/python/numpy/span.h", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 The Abseil Authors.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n// This library provides Clif conversion functions from NumpyArray to\n// template specializations of absl::Span.\n// Note that no data is copied, the `Span`ned memory is owned by the NumpyArray.\n//\n// Only one direction of conversion is provided: a Span argument can be exposed\n// to Python as a Numpy array argument. No conversion is provided for a Span\n// return value.\n//\n// Lifetime management will become complicated if a `Span` returned by a C++\n// object is converted into a Numpy array which outlives the C++ object. Such\n// memory management concerns are normal for C++ but undesirable to introduce to\n// Python.\n//\n// A `Span` argument can be used to expose an output argument to Python so that\n// Python is wholly responsible for memory management of the output object.\n// Using an output argument rather than a return value means that memory can be\n// reused.\n//\n// C++:\n// Simulation::Simulation(int buffer_size);\n// void Simulation::RenderFrame(int frame_index, Span<uint8> buffer);\n//\n// Python:\n// buffer = np.zeroes(1024*768, dtype='uint8')\n// simulation = Simulation(1024*768)\n// simulation.renderFrame(0, buffer)\n// # RGB data can now be read from the buffer.\n\n#ifndef THIRD_PARTY_ABSL_PYTHON_NUMPY_SPAN_H_\n#define THIRD_PARTY_ABSL_PYTHON_NUMPY_SPAN_H_\n\n#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\n\n#include <cstddef>\n\n#include \"absl/types/span.h\"\n#include \"clif/python/postconv.h\"\n#include \"numpy/arrayobject.h\"\n#include \"numpy/ndarrayobject.h\"\n\nnamespace absl {\nnamespace py_span_internal {\n\ntemplate <typename T>\nstruct NumpyType;\n\n// Define NumpyType<const T> in terms of NumpyType<T> to avoid having to use\n// std::remove_const<T>::type\ntemplate <typename T>\nstruct NumpyType<const T> : NumpyType<T> {};\n\n#ifdef ABSL_NUMPY_MAKE_TYPE_TRAIT\n#error \"Redefinition of Numpy type trait partial specialization macro\"\n#endif\n\n#define ABSL_NUMPY_MAKE_TYPE_TRAIT(cxx_type, npy_const, npy_str) \\\n template <> \\\n struct NumpyType<cxx_type> { \\\n static constexpr NPY_TYPES value = npy_const; \\\n static const char* type_error() { \\\n return \"expected numpy.\" #npy_str \" data\"; \\\n } \\\n }\n\nABSL_NUMPY_MAKE_TYPE_TRAIT(bool, NPY_BOOL, bool8);\nABSL_NUMPY_MAKE_TYPE_TRAIT(signed char, NPY_BYTE, byte);\nABSL_NUMPY_MAKE_TYPE_TRAIT(unsigned char, NPY_UBYTE, ubyte);\nABSL_NUMPY_MAKE_TYPE_TRAIT(short, NPY_SHORT, short); // NOLINT(runtime/int)\nABSL_NUMPY_MAKE_TYPE_TRAIT(unsigned short, NPY_USHORT,\n ushort); // NOLINT(runtime/int)\nABSL_NUMPY_MAKE_TYPE_TRAIT(int, NPY_INT, intc);\nABSL_NUMPY_MAKE_TYPE_TRAIT(unsigned int, NPY_UINT, uintc);\nABSL_NUMPY_MAKE_TYPE_TRAIT(long int, NPY_LONG, long); // NOLINT(runtime/int)\nABSL_NUMPY_MAKE_TYPE_TRAIT(unsigned long int, NPY_ULONG,\n ulong); // NOLINT(runtime/int)\nABSL_NUMPY_MAKE_TYPE_TRAIT(long long int, NPY_LONGLONG,\n longlong); // NOLINT(runtime/int)\nABSL_NUMPY_MAKE_TYPE_TRAIT(unsigned long long int, NPY_ULONGLONG,\n ulonglong); // NOLINT(runtime/int)\nABSL_NUMPY_MAKE_TYPE_TRAIT(float, NPY_FLOAT, single);\nABSL_NUMPY_MAKE_TYPE_TRAIT(double, NPY_DOUBLE, double);\nABSL_NUMPY_MAKE_TYPE_TRAIT(long double, NPY_LONGDOUBLE, longfloat);\n\n#undef ABSL_NUMPY_MAKE_TYPE_TRAIT\n\ntemplate <typename T>\nbool SatisfiesWriteableRequirements(PyArrayObject* npy, Span<T>* c) {\n return PyArray_FLAGS(npy) & NPY_ARRAY_WRITEABLE;\n}\n\ntemplate <typename T>\nbool SatisfiesWriteableRequirements(PyArrayObject* npy, Span<const T>* c) {\n return true;\n}\n} // namespace py_span_internal\n\n// Accept a 1-D Numpy array as a Python representation of a Span.\n// Note that the Span will only be valid for the lifetime of the PyObject.\ntemplate <typename T>\nbool Clif_PyObjAs(PyObject* py, Span<T>* c) {\n // CHECK(c != nullptr);\n\n if (PyArray_API == nullptr) {\n import_array1(0);\n }\n\n if (!PyArray_Check(py)) {\n PyErr_SetString(PyExc_TypeError,\n \"The given input is not a NumPy array or matrix.\");\n return false;\n }\n\n auto* npy = reinterpret_cast<PyArrayObject*>(py);\n\n if (!PyArray_ISCONTIGUOUS(npy)) {\n PyErr_SetString(PyExc_ValueError, \"Array must be contiguous.\");\n return false;\n }\n\n if (!py_span_internal::SatisfiesWriteableRequirements(npy, c)) {\n PyErr_SetString(PyExc_TypeError, \"Expected a writeable numpy array\");\n return false;\n }\n\n const int numpy_type = PyArray_TYPE(npy);\n if (py_span_internal::NumpyType<T>::value != numpy_type) {\n PyErr_SetString(PyExc_TypeError,\n py_span_internal::NumpyType<T>::type_error());\n return false;\n }\n\n const int num_dimensions = PyArray_NDIM(npy);\n npy_intp* dimensions = PyArray_DIMS(npy);\n if (num_dimensions != 1) {\n PyErr_SetString(PyExc_TypeError, \"expected a 1-D array\");\n return false;\n }\n\n std::size_t size = *dimensions;\n\n T* numpy_data;\n PyArray_Descr* descr =\n PyArray_DescrFromType(py_span_internal::NumpyType<T>::value);\n PyArray_AsCArray(&py, &numpy_data, dimensions, 1, descr);\n\n *c = Span<T>(numpy_data, size);\n return true;\n}\n\n// CLIF use `::absl::Span` as NumpyArray\n\n} // namespace absl\n\n#endif // THIRD_PARTY_ABSL_PYTHON_NUMPY_SPAN_H_\n" }, { "alpha_fraction": 0.7020535469055176, "alphanum_fraction": 0.7137880325317383, "avg_line_length": 36.1020393371582, "blob_id": "7e79ad0dbd9b1231c478f48269f027b1e59f23a4", "content_id": "d22babc674863cd790eb2eb3c592ac27fae6d24e", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5454, "license_type": "permissive", "max_line_length": 80, "num_lines": 147, "path": "/streetlearn/engine/graph_renderer_test.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/graph_renderer.h\"\n\n#include <string>\n\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n\n#include \"absl/strings/str_cat.h\"\n#include \"absl/types/optional.h\"\n#include \"streetlearn/engine/color.h\"\n#include \"streetlearn/engine/graph_image_cache.h\"\n#include \"streetlearn/engine/math_util.h\"\n#include \"streetlearn/engine/pano_graph.h\"\n#include \"streetlearn/engine/test_dataset.h\"\n#include \"streetlearn/engine/test_utils.h\"\n#include \"streetlearn/engine/vector.h\"\n\nnamespace streetlearn {\nnamespace {\n\nconstexpr int kScreenWidth = 640;\nconstexpr int kScreenHeight = 480;\nconstexpr int kGraphDepth = 10;\nconstexpr double kObserverYawDegrees = 45;\nconstexpr double kObserverFovDegrees = 30;\nconstexpr char kTestPanoID[] = \"5\";\nconstexpr char kTestFilePath[] = \"engine/test_data/\";\nconstexpr Color kConeColor = {0.4, 0.6, 0.9};\nconstexpr Color kNodeColor = {0.1, 0.9, 0.1};\nconstexpr Color kHighlightColor = {0.9, 0.1, 0.1};\n\nstatic const auto* const kColoredPanos = new std::map<std::string, Color>{\n {\"2\", kNodeColor}, {\"4\", kNodeColor}, {\"6\", kNodeColor}};\n\nstatic const auto* const kHighlightedPanos = new std::map<std::string, Color>{\n {\"1\", kHighlightColor}, {\"3\", kHighlightColor}, {\"5\", kHighlightColor}};\n\nclass GraphRendererTest : public testing::Test {\n public:\n static void SetUpTestCase() { ASSERT_TRUE(TestDataset::Generate()); }\n\n void SetUp() override {\n dataset_ = Dataset::Create(TestDataset::GetPath());\n ASSERT_TRUE(dataset_ != nullptr);\n\n pano_graph_ = absl::make_unique<PanoGraph>(\n TestDataset::kMaxGraphDepth, TestDataset::kMaxCacheSize,\n TestDataset::kMinGraphDepth, TestDataset::kMaxGraphDepth,\n dataset_.get());\n graph_image_cache_ = absl::make_unique<GraphImageCache>(\n Vector2_i{kScreenWidth, kScreenHeight}, std::map<std::string, Color>{});\n\n // Build the pano graph.\n pano_graph_->SetRandomSeed(0);\n ASSERT_TRUE(pano_graph_->Init());\n ASSERT_TRUE(pano_graph_->BuildGraphWithRoot(\"1\"));\n\n // Create the graph renderer.\n graph_renderer_ = GraphRenderer::Create(\n *pano_graph_, Vector2_i(kScreenWidth, kScreenHeight), *kColoredPanos);\n }\n\n std::unique_ptr<GraphRenderer> graph_renderer_;\n\n private:\n std::unique_ptr<const Dataset> dataset_;\n std::unique_ptr<PanoGraph> pano_graph_;\n std::unique_ptr<GraphImageCache> graph_image_cache_;\n};\n\nTEST_F(GraphRendererTest, Test) {\n ASSERT_TRUE(graph_renderer_->RenderScene(*kHighlightedPanos, absl::nullopt));\n std::vector<uint8_t> pixel_buffer(3 * kScreenWidth * kScreenHeight);\n graph_renderer_->GetPixels(absl::MakeSpan(pixel_buffer));\n EXPECT_TRUE(test_utils::CompareRGBBufferWithImage(\n pixel_buffer, kScreenWidth, kScreenHeight,\n test_utils::PixelFormat::kPackedRGB,\n absl::StrCat(kTestFilePath, \"graph_test.png\")));\n}\n\nTEST_F(GraphRendererTest, ZoomTest) {\n const std::map<double, std::string> kZoomLevels = {\n {2.0, \"graph_test_zoom2.png\"},\n {4.0, \"graph_test_zoom4.png\"},\n {8.0, \"graph_test_zoom8.png\"}};\n\n std::vector<uint8_t> pixel_buffer(3 * kScreenWidth * kScreenHeight);\n // Zoom in all the way.\n for (const auto& zoom_image_pair : kZoomLevels) {\n ASSERT_TRUE(graph_renderer_->SetZoom(zoom_image_pair.first));\n ASSERT_TRUE(\n graph_renderer_->RenderScene(*kHighlightedPanos, absl::nullopt));\n graph_renderer_->GetPixels(absl::MakeSpan(pixel_buffer));\n EXPECT_TRUE(test_utils::CompareRGBBufferWithImage(\n pixel_buffer, kScreenWidth, kScreenHeight,\n test_utils::PixelFormat::kPackedRGB,\n absl::StrCat(kTestFilePath, zoom_image_pair.second)));\n }\n\n // Zoom out.\n for (auto it = kZoomLevels.rbegin(); it != kZoomLevels.rend(); ++it) {\n ASSERT_TRUE(graph_renderer_->SetZoom(it->first));\n ASSERT_TRUE(\n graph_renderer_->RenderScene(*kHighlightedPanos, absl::nullopt));\n\n graph_renderer_->GetPixels(absl::MakeSpan(pixel_buffer));\n EXPECT_TRUE(test_utils::CompareRGBBufferWithImage(\n pixel_buffer, kScreenWidth, kScreenHeight,\n test_utils::PixelFormat::kPackedRGB,\n absl::StrCat(kTestFilePath, it->second)));\n }\n}\n\nTEST_F(GraphRendererTest, ObserverTest) {\n // Place an observer.\n Observer observer;\n observer.pano_id = kTestPanoID;\n observer.yaw_radians = math::DegreesToRadians(kObserverYawDegrees);\n observer.fov_yaw_radians = math::DegreesToRadians(kObserverFovDegrees);\n observer.color = kConeColor;\n\n ASSERT_TRUE(graph_renderer_->RenderScene(*kHighlightedPanos, observer));\n\n std::vector<uint8_t> pixel_buffer(3 * kScreenWidth * kScreenHeight);\n graph_renderer_->GetPixels(absl::MakeSpan(pixel_buffer));\n EXPECT_TRUE(test_utils::CompareRGBBufferWithImage(\n pixel_buffer, kScreenWidth, kScreenHeight,\n test_utils::PixelFormat::kPackedRGB,\n absl::StrCat(kTestFilePath, \"graph_test_observer.png\")));\n}\n\n} // namespace\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.6587968468666077, "alphanum_fraction": 0.6642451882362366, "avg_line_length": 34.2400016784668, "blob_id": "ed3da19f565c986b5d3f5f639e21a8955a94c21d", "content_id": "00f5d0186e18f85520f57589fabf03b68b2b1a3c", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4405, "license_type": "permissive", "max_line_length": 80, "num_lines": 125, "path": "/streetlearn/engine/dataset_test.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/dataset.h\"\n\n#include <cstdint>\n#include <string>\n#include <utility>\n\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n#include \"absl/memory/memory.h\"\n#include \"leveldb/db.h\"\n#include \"leveldb/iterator.h\"\n#include \"leveldb/options.h\"\n#include \"leveldb/slice.h\"\n#include \"leveldb/status.h\"\n#include \"leveldb/write_batch.h\"\n#include \"streetlearn/proto/streetlearn.pb.h\"\n\nnamespace streetlearn {\nnamespace {\n\nusing ::testing::_;\nusing ::testing::DoAll;\nusing ::testing::Return;\nusing ::testing::SetArgPointee;\nusing ::testing::StrictMock;\n\nclass MockLevelDB : public ::leveldb::DB {\n public:\n MockLevelDB() = default;\n ~MockLevelDB() override = default;\n\n MOCK_METHOD3(Put, ::leveldb::Status(const ::leveldb::WriteOptions& options,\n const ::leveldb::Slice& key,\n const ::leveldb::Slice& value));\n\n MOCK_METHOD2(Delete, ::leveldb::Status(const ::leveldb::WriteOptions& options,\n const ::leveldb::Slice& key));\n\n MOCK_METHOD2(Write, ::leveldb::Status(const ::leveldb::WriteOptions& options,\n ::leveldb::WriteBatch* updates));\n\n MOCK_METHOD3(Get, ::leveldb::Status(const ::leveldb::ReadOptions& options,\n const ::leveldb::Slice& key,\n std::string* value));\n MOCK_METHOD1(NewIterator,\n ::leveldb::Iterator*(const ::leveldb::ReadOptions& options));\n\n MOCK_METHOD0(GetSnapshot, const ::leveldb::Snapshot*());\n\n MOCK_METHOD1(ReleaseSnapshot, void(const ::leveldb::Snapshot*));\n\n MOCK_METHOD2(GetProperty,\n bool(const ::leveldb::Slice& property, std::string* value));\n\n MOCK_METHOD3(GetApproximateSizes,\n void(const ::leveldb::Range* range, int n, uint64_t* sizes));\n\n MOCK_METHOD2(CompactRange, void(const ::leveldb::Slice* begin,\n const ::leveldb::Slice* end));\n};\n\nTEST(DatasetTest, TestAccessWithNonExistingKeys) {\n constexpr char kTestPanoId[] = \"non_existing_pano_id\";\n auto mock_leveldb = absl::make_unique<::testing::StrictMock<MockLevelDB>>();\n\n EXPECT_CALL(*mock_leveldb, Get(_, ::leveldb::Slice(kTestPanoId), _))\n .WillOnce(Return(leveldb::Status::NotFound(\"not found\")));\n EXPECT_CALL(*mock_leveldb, Get(_, ::leveldb::Slice(Dataset::kGraphKey), _))\n .WillOnce(Return(leveldb::Status::NotFound(\"not found\")));\n\n Dataset dataset(std::move(mock_leveldb));\n\n StreetLearnGraph graph;\n EXPECT_FALSE(dataset.GetGraph(&graph));\n\n Pano pano;\n EXPECT_FALSE(dataset.GetPano(kTestPanoId, &pano));\n}\n\nTEST(DatasetTest, TestAccessWithExistingKeys) {\n constexpr char kTestPanoId[] = \"test_pano_id\";\n auto mock_leveldb = absl::make_unique<::testing::StrictMock<MockLevelDB>>();\n\n Pano test_pano;\n test_pano.set_id(kTestPanoId);\n const std::string test_pano_string = test_pano.SerializeAsString();\n\n StreetLearnGraph test_graph;\n test_graph.mutable_min_coords()->set_lat(42);\n const std::string test_graph_string = test_graph.SerializeAsString();\n\n EXPECT_CALL(*mock_leveldb, Get(_, ::leveldb::Slice(kTestPanoId), _))\n .WillOnce(DoAll(SetArgPointee<2>(test_pano_string),\n Return(leveldb::Status::OK())));\n EXPECT_CALL(*mock_leveldb, Get(_, ::leveldb::Slice(Dataset::kGraphKey), _))\n .WillOnce(DoAll(SetArgPointee<2>(test_graph_string),\n Return(leveldb::Status::OK())));\n\n Dataset dataset(std::move(mock_leveldb));\n\n StreetLearnGraph graph;\n EXPECT_TRUE(dataset.GetGraph(&graph));\n EXPECT_EQ(graph.SerializeAsString(), test_graph_string);\n\n Pano pano;\n EXPECT_TRUE(dataset.GetPano(kTestPanoId, &pano));\n EXPECT_EQ(pano.SerializeAsString(), test_pano_string);\n}\n\n} // namespace\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.6500433087348938, "alphanum_fraction": 0.656204879283905, "avg_line_length": 41.74485778808594, "blob_id": "84e429ca5bce6ae2a76eec7934510623814b3b6a", "content_id": "c1b3a97c28b39470a3d31355fbc4a5ee84423c05", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10387, "license_type": "permissive", "max_line_length": 80, "num_lines": 243, "path": "/streetlearn/python/agents/goal_nav_agent.py", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "# Copyright 2018 Google LLC\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# https://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\"\"\"Importance Weighted Actor-Learner Architecture goalless navigation agent.\n\nNote that this is a modification of code previously published by Lasse Espeholt\nunder an Apache license at:\nhttps://github.com/deepmind/scalable_agent\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport functools\n\nfrom six.moves import range\nimport sonnet as snt\nimport tensorflow as tf\n\nimport streetlearn.python.agents.locale_pathway as locale_pathway\n\nnest = tf.contrib.framework.nest\n\nAgentOutput = collections.namedtuple(\n \"AgentOutput\", \"action policy_logits baseline heading xy target_xy\")\n\n\nclass GoalNavAgent(snt.RNNCore):\n \"\"\"Agent with a simple residual convnet and LSTM.\"\"\"\n\n def __init__(self,\n num_actions,\n observation_names,\n goal_type='target_latlng',\n heading_stop_gradient=False,\n heading_num_hiddens=256,\n heading_num_bins=16,\n xy_stop_gradient=True,\n xy_num_hiddens=256,\n xy_num_bins_lat=32,\n xy_num_bins_lng=32,\n target_xy_stop_gradient=True,\n dropout=0.5,\n lstm_num_hiddens=256,\n feed_action_and_reward=True,\n max_reward=1.0,\n name=\"streetlearn_core\"):\n \"\"\"Initializes an agent core designed to be used with A3C/IMPALA.\n\n Supports a single visual observation tensor and goal instruction tensor and\n outputs a single, scalar discrete action with policy logits and a baseline\n value, as well as the agent heading prediction.\n\n Args:\n num_actions: Number of actions available.\n observation_names: String with observation names separated by semi-colon.\n goal_type: String with the name of the target observation field, can be\n `target_latlng` or `target_landmarks`.\n heading_stop_gradient: Boolean for stopping gradient between the LSTM core\n and the heading prediction MLP.\n heading_num_hiddens: Number of hiddens in the heading prediction MLP.\n heading_num_bins: Number of outputs in the heading prediction MLP.\n xy_stop_gradient: Boolean for stopping gradient between the LSTM core\n and the XY position prediction MLP.\n xy_num_hiddens: Number of hiddens in the XY position prediction MLP.\n xy_num_bins_lat: Number of lat outputs in the XY position prediction MLP.\n xy_num_bins_lng: Number of lng outputs in the XY position prediction MLP.\n target_xy_stop_gradient: Boolean for stopping gradient between the LSTM\n core and the target XY position prediction MLP.\n dropout: Dropout probabibility after the locale pathway.\n lstm_num_hiddens: Number of hiddens in the LSTM core.\n feed_action_and_reward: If True, the last action (one hot) and last reward\n (scalar) will be concatenated to the torso.\n max_reward: If `feed_action_and_reward` is True, the last reward will\n be clipped to `[-max_reward, max_reward]`. If `max_reward`\n is None, no clipping will be applied. N.B., this is different from\n reward clipping during gradient descent, or reward clipping by the\n environment.\n name: Optional name for the module.\n \"\"\"\n super(GoalNavAgent, self).__init__(name='agent')\n\n # Policy config\n self._num_actions = num_actions\n tf.logging.info('Agent trained on %d-action policy', self._num_actions)\n # Append last reward (clipped) and last action?\n self._feed_action_and_reward = feed_action_and_reward\n self._max_reward = max_reward\n # Policy LSTM core config\n self._lstm_num_hiddens = lstm_num_hiddens\n # Extract the observation names\n observation_names = observation_names.split(';')\n self._idx_frame = observation_names.index('view_image')\n tf.logging.info('Looking for goal of type %s', goal_type)\n self._idx_goal = observation_names.index(goal_type)\n\n with self._enter_variable_scope():\n # Convnet\n self._convnet = snt.nets.ConvNet2D(\n output_channels=(16, 32),\n kernel_shapes=(8, 4),\n strides=(4, 2),\n paddings=[snt.VALID],\n activation=tf.nn.relu,\n activate_final=True)\n # Recurrent LSTM core of the agent.\n tf.logging.info('Locale pathway LSTM core with %d hiddens',\n self._lstm_num_hiddens)\n self._locale_pathway = locale_pathway.LocalePathway(\n heading_stop_gradient, heading_num_hiddens, heading_num_bins,\n xy_stop_gradient, xy_num_hiddens, xy_num_bins_lat, xy_num_bins_lng,\n target_xy_stop_gradient, lstm_num_hiddens, dropout)\n\n def initial_state(self, batch_size):\n \"\"\"Return initial state with zeros, for a given batch size and data type.\"\"\"\n tf.logging.info(\"Initial state consists of the LSTM core initial state.\")\n return self._locale_pathway.initial_state(batch_size)\n\n def _torso(self, input_):\n \"\"\"Processing of all the visual and language inputs to the LSTM core.\"\"\"\n\n # Extract the inputs\n last_action, env_output = input_\n last_reward, _, _, observation = env_output\n frame = observation[self._idx_frame]\n goal = observation[self._idx_goal]\n goal = tf.to_float(goal)\n\n # Convert to image to floats and normalise.\n frame = tf.to_float(frame)\n frame = snt.FlattenTrailingDimensions(dim_from=3)(frame)\n frame /= 255.0\n\n # Feed image through convnet.\n with tf.variable_scope('convnet'):\n # Convolutional layers.\n conv_out = self._convnet(frame)\n # Fully connected layer.\n conv_out = snt.BatchFlatten()(conv_out)\n conv_out = snt.Linear(256)(conv_out)\n conv_out = tf.nn.relu(conv_out)\n\n # Concatenate outputs of the visual and instruction pathways.\n if self._feed_action_and_reward:\n # Append clipped last reward and one hot last action.\n tf.logging.info('Append last reward clipped to: %f', self._max_reward)\n clipped_last_reward = tf.expand_dims(\n tf.clip_by_value(last_reward, -self._max_reward, self._max_reward),\n -1)\n tf.logging.info('Append last action (one-hot of %d)', self._num_actions)\n one_hot_last_action = tf.one_hot(last_action, self._num_actions)\n tf.logging.info('Append goal:')\n tf.logging.info(goal)\n action_and_reward = tf.concat([clipped_last_reward, one_hot_last_action],\n axis=1)\n else:\n action_and_reward = tf.constant([0], dtype=tf.float32)\n return conv_out, action_and_reward, goal\n\n def _core(self, core_input, core_state):\n \"\"\"Assemble the recurrent core network components.\"\"\"\n (conv_output, action_reward, goal) = core_input\n locale_input = tf.concat([conv_output, action_reward], axis=1)\n core_output, core_state = self._locale_pathway((locale_input, goal),\n core_state)\n return core_output, core_state\n\n def _head(self, policy_input, heading, xy, target_xy):\n \"\"\"Build the head of the agent: linear policy and value function, and pass\n the auxiliary outputs through.\n \"\"\"\n\n # Linear policy and value function.\n policy_logits = snt.Linear(\n self._num_actions, name='policy_logits')(policy_input)\n baseline = tf.squeeze(snt.Linear(1, name='baseline')(policy_input), axis=-1)\n\n # Sample an action from the policy.\n new_action = tf.multinomial(\n policy_logits, num_samples=1, output_dtype=tf.int32)\n new_action = tf.squeeze(new_action, 1, name='new_action')\n\n return AgentOutput(\n new_action, policy_logits, baseline, heading, xy, target_xy)\n\n def _build(self, input_, core_state):\n \"\"\"Assemble the network components.\"\"\"\n action, env_output = input_\n actions, env_outputs = nest.map_structure(lambda t: tf.expand_dims(t, 0),\n (action, env_output))\n outputs, core_state = self.unroll(actions, env_outputs, core_state)\n return nest.map_structure(lambda t: tf.squeeze(t, 0), outputs), core_state\n\n @snt.reuse_variables\n def unroll(self, actions, env_outputs, core_state):\n \"\"\"Manual implementation of the network unroll.\"\"\"\n _, _, done, _ = env_outputs\n\n torso_outputs = snt.BatchApply(self._torso)((actions, env_outputs))\n tf.logging.info(torso_outputs)\n conv_outputs, actions_and_rewards, goals = torso_outputs\n\n # Note, in this implementation we can't use CuDNN RNN to speed things up due\n # to the state reset. This can be XLA-compiled (LSTMBlockCell needs to be\n # changed to implement snt.LSTMCell).\n initial_core_state = self.initial_state(tf.shape(actions)[1])\n policy_input_list = []\n heading_output_list = []\n xy_output_list = []\n target_xy_output_list = []\n for torso_output_, action_and_reward_, goal_, done_ in zip(\n tf.unstack(conv_outputs),\n tf.unstack(actions_and_rewards),\n tf.unstack(goals),\n tf.unstack(done)):\n # If the episode ended, the core state should be reset before the next.\n core_state = nest.map_structure(\n functools.partial(tf.where, done_), initial_core_state, core_state)\n core_output, core_state = self._core(\n (torso_output_, action_and_reward_, goal_), core_state)\n policy_input_list.append(core_output[0])\n heading_output_list.append(core_output[1])\n xy_output_list.append(core_output[2])\n target_xy_output_list.append(core_output[3])\n head_output = snt.BatchApply(self._head)(tf.stack(policy_input_list),\n tf.stack(heading_output_list),\n tf.stack(xy_output_list),\n tf.stack(target_xy_output_list))\n\n return head_output, core_state\n" }, { "alpha_fraction": 0.6422862410545349, "alphanum_fraction": 0.680794358253479, "avg_line_length": 33.40833282470703, "blob_id": "790b3fe7b382c68106931454d75cbda66a0904c7", "content_id": "39c092b712041f297fb9988f714c9d5a5e0612ef", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4129, "license_type": "permissive", "max_line_length": 74, "num_lines": 120, "path": "/streetlearn/python/environment/default_config.py", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "# Copyright 2018 Google LLC.\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\"\"\"Settings for the StreetLearn environment.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport copy\nfrom streetlearn.engine.python import color\nfrom streetlearn.python.environment import coin_game\nfrom streetlearn.python.environment import courier_game\nfrom streetlearn.python.environment import curriculum_courier_game\nfrom streetlearn.python.environment import exploration_game\nfrom streetlearn.python.environment import goal_instruction_game\nfrom streetlearn.python.environment import incremental_instruction_game\nfrom streetlearn.python.environment import step_by_step_instruction_game\n\n\nDEFAULT_CONFIG = {\n 'seed': 1234,\n 'width': 320,\n 'height': 240,\n 'graph_width': 320,\n 'graph_height': 240,\n 'status_height': 10,\n 'field_of_view': 60,\n 'min_graph_depth': 200,\n 'max_graph_depth': 200,\n 'max_cache_size': 1000,\n 'bbox_lat_min': -90.0,\n 'bbox_lat_max': 90.0,\n 'bbox_lng_min': -180.0,\n 'bbox_lng_max': 180.0,\n 'max_reward_per_goal': 10.0,\n 'min_radius_meters': 100.0,\n 'max_radius_meters': 200.0,\n 'timestamp_start_curriculum': 0.0,\n 'annealing_rate_curriculum': 2.0,\n 'hours_curriculum_part_1': 0.0,\n 'hours_curriculum_part_2': 24.0,\n 'min_goal_distance_curriculum': 500.0,\n 'max_goal_distance_curriculum': 3500.0,\n 'instruction_curriculum_type': 0,\n 'curriculum_num_instructions_part_1': 2,\n 'curriculum_bin_distance': 100.0,\n 'curriculum_frame_cap': False,\n 'curriculum_frame_cap_part_1': 100,\n 'max_reward_per_cone': 0.49,\n 'cone_radius_meters': 50.0,\n 'goal_timeout': 1000,\n 'frame_cap': 1000,\n 'full_graph': True,\n 'sample_graph_depth': True,\n 'start_pano': '',\n 'graph_zoom': 32,\n 'show_shortest_path': False,\n 'calculate_ground_truth': False,\n 'neighbor_resolution': 8,\n 'color_for_touched_pano': color.Color(1.0, 0.5, 0.5),\n 'color_for_observer': color.Color(0.5, 0.5, 1.0),\n 'color_for_coin': color.Color(1.0, 1.0, 0.0),\n 'color_for_goal': color.Color(1.0, 0.0, 0.0),\n 'color_for_shortest_path': color.Color(1.0, 0.0, 1.0),\n 'color_for_waypoint': color.Color(0, 0.7, 0.7),\n 'observations': ['view_image', 'graph_image'],\n 'reward_per_coin': 1.0,\n 'reward_at_waypoint': 0.5,\n 'reward_at_goal': 1.0,\n 'instruction_file': None,\n 'num_instructions': 5,\n 'max_instructions': 5,\n 'proportion_of_panos_with_coins': 0.5,\n 'game_name': 'coin_game',\n 'action_spec': 'streetlearn_fast_rotate',\n 'rotation_speed': 22.5,\n 'auto_reset': True,\n}\n\nNAME_TO_GAME = {\n 'coin_game':\n coin_game.CoinGame,\n 'courier_game':\n courier_game.CourierGame,\n 'curriculum_courier_game':\n curriculum_courier_game.CurriculumCourierGame,\n 'exploration_game':\n exploration_game.ExplorationGame,\n 'goal_instruction_game':\n goal_instruction_game.GoalInstructionGame,\n 'incremental_instruction_game':\n incremental_instruction_game.IncrementalInstructionGame,\n 'step_by_step_instruction_game':\n step_by_step_instruction_game.StepByStepInstructionGame,\n}\n\ndef ApplyDefaults(config):\n result = copy.copy(config)\n for default_key, default_value in DEFAULT_CONFIG.items():\n if not default_key in result:\n result[default_key] = default_value\n else:\n assert type(default_value) == type(result[default_key])\n return result\n\ndef CreateGame(name, config):\n assert name in NAME_TO_GAME, \"Unknown game name: %r\" % name\n return NAME_TO_GAME[name](config)\n" }, { "alpha_fraction": 0.7164618968963623, "alphanum_fraction": 0.7267813086509705, "avg_line_length": 33.49152374267578, "blob_id": "820ace8a7d0e98fe8fc49c98744d48f61586001f", "content_id": "00099bcc0de0482c1b74a7d8e3ad3d4193a98235", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2035, "license_type": "permissive", "max_line_length": 76, "num_lines": 59, "path": "/streetlearn/engine/cairo_util_test.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/cairo_util.h\"\n\n#include <vector>\n\n#include \"gtest/gtest.h\"\n#include <cairo/cairo.h>\n\nnamespace streetlearn {\nnamespace {\n\nTEST(CairoUtilTest, TestEmpty) {\n std::vector<unsigned char> buffer;\n CairoRenderHelper helper(buffer.data(), 0, 0);\n\n EXPECT_EQ(helper.width(), 0);\n EXPECT_EQ(helper.height(), 0);\n\n EXPECT_EQ(cairo_status(helper.context()), CAIRO_STATUS_SUCCESS);\n EXPECT_EQ(cairo_image_surface_get_data(helper.surface()), nullptr);\n EXPECT_EQ(cairo_image_surface_get_width(helper.surface()), 0);\n EXPECT_EQ(cairo_image_surface_get_height(helper.surface()), 0);\n EXPECT_EQ(cairo_image_surface_get_stride(helper.surface()), 0);\n}\n\nTEST(CairoUtilTest, TestNonEmpty) {\n constexpr int kWidth = 32;\n constexpr int kHeight = 64;\n constexpr int kChannels = 1;\n\n std::vector<unsigned char> buffer(kWidth * kHeight * kChannels);\n CairoRenderHelper helper(buffer.data(), kWidth, kHeight, CAIRO_FORMAT_A8);\n\n EXPECT_EQ(helper.width(), kWidth);\n EXPECT_EQ(helper.height(), kHeight);\n\n EXPECT_EQ(cairo_status(helper.context()), CAIRO_STATUS_SUCCESS);\n EXPECT_EQ(cairo_image_surface_get_data(helper.surface()), buffer.data());\n EXPECT_EQ(cairo_image_surface_get_width(helper.surface()), kWidth);\n EXPECT_EQ(cairo_image_surface_get_height(helper.surface()), kHeight);\n EXPECT_EQ(cairo_image_surface_get_stride(helper.surface()),\n kWidth * kChannels);\n}\n\n} // namespace\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.6558330655097961, "alphanum_fraction": 0.6630174517631531, "avg_line_length": 31.842697143554688, "blob_id": "ffa8b45959d8871dd473bee8639a83bad46f1057", "content_id": "e75a3e52509971058d447c942646500a52d5ff37", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2923, "license_type": "permissive", "max_line_length": 79, "num_lines": 89, "path": "/streetlearn/engine/rtree_helper.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/rtree_helper.h\"\n\n#include <utility>\n\n#include <boost/function_output_iterator.hpp>\n#include <boost/geometry.hpp>\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/core/tags.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/index/parameters.hpp>\n#include <boost/geometry/index/predicates.hpp>\n#include <boost/geometry/index/rtree.hpp>\n\n#include \"absl/memory/memory.h\"\n#include \"s2/s1angle.h\"\n#include \"s2/s2latlng_rect.h\"\n\nnamespace streetlearn {\nnamespace {\n\nnamespace bg = boost::geometry;\n\nusing point_t = bg::model::point<double, 2, bg::cs::geographic<bg::radian>>;\nusing box_t = bg::model::box<point_t>;\nusing rtree_t =\n boost::geometry::index::rtree<std::pair<box_t, int>,\n boost::geometry::index::quadratic<16>>;\n\nbox_t CreateBox(const S2LatLngRect& rect) {\n return box_t{{rect.lng_lo().radians(), rect.lat_lo().radians()},\n {rect.lng_hi().radians(), rect.lat_hi().radians()}};\n}\n\n} // namespace\n\nstruct RTree::Impl {\n // Helper function to insert S2LatLngRect, insert pairs to the rtree;\n void Insert(const S2LatLngRect& rect, int value) {\n tree_.insert({CreateBox(rect), value});\n }\n\n // Helper function to query intersecting boxes in the RTree and insert values\n // to the result vector.\n std::size_t FindIntersecting(const S2LatLngRect& rect,\n std::vector<int>* out) {\n return tree_.query(boost::geometry::index::intersects(CreateBox(rect)),\n boost::make_function_output_iterator(\n [&](std::pair<box_t, int> const& value) {\n out->push_back(value.second);\n }));\n }\n\n bool empty() const { return tree_.empty(); }\n\n rtree_t tree_;\n};\n\nRTree::RTree() : impl_(absl::make_unique<RTree::Impl>()) {}\n\nRTree::~RTree() {}\n\nvoid RTree::Insert(const S2LatLngRect& rect, int value) {\n impl_->Insert(rect, value);\n}\n\nstd::size_t RTree::FindIntersecting(const S2LatLngRect& rect,\n std::vector<int>* out) const {\n return impl_->FindIntersecting(rect, out);\n}\n\nbool RTree::empty() const { return impl_->empty(); }\n\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.702612578868866, "alphanum_fraction": 0.7153974175453186, "avg_line_length": 30.561403274536133, "blob_id": "05b90de027339832a1b4e7db1b681625f3ecca79", "content_id": "c0f2d930a42eaa43347cdb7247421ed1d9623155", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1799, "license_type": "permissive", "max_line_length": 75, "num_lines": 57, "path": "/streetlearn/engine/math_util.h", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#ifndef THIRD_PARTY_STREETLEARN_ENGINE_MATHUTIL_H_\n#define THIRD_PARTY_STREETLEARN_ENGINE_MATHUTIL_H_\n\n#include <cmath>\n#include <random>\n\n#include \"streetlearn/engine/logging.h\"\n#include \"absl/base/attributes.h\"\n\nnamespace streetlearn {\nnamespace math {\n\n// Returns a random integer in the range [0, max].\ninline int UniformRandomInt(std::mt19937* random, int max) {\n std::uniform_int_distribution<int> uniform_dist(0, max);\n return uniform_dist(*random);\n}\n\n// Clamps value to the range [low, high]. Requires low <= high.\ntemplate <typename T>\nABSL_MUST_USE_RESULT inline const T Clamp(const T& low, const T& high,\n const T& value) {\n // Detects errors in ordering the arguments.\n CHECK(!(high < low));\n if (high < value) return high;\n if (value < low) return low;\n return value;\n}\n\n// Converts the given angle from degrees to radians.\ninline double DegreesToRadians(double degrees) {\n return degrees * M_PI / 180.0;\n}\n\n// Converts the given angle from radians to degrees.\ninline double RadiansToDegrees(double radians) {\n return radians * 180.0 / M_PI;\n}\n\n} // namespace math\n} // namespace streetlearn\n\n#endif // THIRD_PARTY_STREETLEARN_ENGINE_MATHUTIL_H_\n" }, { "alpha_fraction": 0.6441150903701782, "alphanum_fraction": 0.6530078649520874, "avg_line_length": 36.980133056640625, "blob_id": "ecc60689623665b41eec8db13512f8221d35e841", "content_id": "c243223bda9b55443ee8268485f01f52577ead75", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5735, "license_type": "permissive", "max_line_length": 79, "num_lines": 151, "path": "/streetlearn/python/ui/oracle_agent.py", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "# Copyright 2018 Google LLC.\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\"\"\"Basic oracle agent for StreetLearn.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\n\nimport time\nimport numpy as np\nimport pygame\n\nfrom streetlearn.python.environment import courier_game\nfrom streetlearn.python.environment import default_config\nfrom streetlearn.python.environment import streetlearn\n\nFLAGS = flags.FLAGS\nflags.DEFINE_integer('width', 400, 'Observation and map width.')\nflags.DEFINE_integer('height', 400, 'Observation and map height.')\nflags.DEFINE_integer('graph_zoom', 1, 'Zoom level.')\nflags.DEFINE_float('horizontal_rot', 22.5, 'Horizontal rotation step (deg).')\nflags.DEFINE_string('dataset_path', None, 'Dataset path.')\nflags.DEFINE_string('start_pano', '',\n 'Pano at root of partial graph (default: full graph).')\nflags.DEFINE_integer('graph_depth', 200, 'Depth of the pano graph.')\nflags.DEFINE_integer('frame_cap', 1000, 'Number of frames / episode.')\nflags.DEFINE_string('stats_path', None, 'Statistics path.')\nflags.DEFINE_float('proportion_of_panos_with_coins', 0, 'Proportion of coins.')\nflags.mark_flag_as_required('dataset_path')\n\n\nTOL_BEARING = 30\n\n\ndef interleave(array, w, h):\n \"\"\"Turn a planar RGB array into an interleaved one.\n\n Args:\n array: An array of bytes consisting the planar RGB image.\n w: Width of the image.\n h: Height of the image.\n Returns:\n An interleaved array of bytes shape shaped (h, w, 3).\n \"\"\"\n arr = array.reshape(3, w * h)\n return np.ravel((arr[0], arr[1], arr[2]),\n order='F').reshape(h, w, 3).swapaxes(0, 1)\n\ndef loop(env, screen):\n \"\"\"Main loop of the oracle agent.\"\"\"\n action = np.array([0, 0, 0, 0])\n action_spec = env.action_spec()\n sum_rewards = 0\n sum_rewards_at_goal = 0\n previous_goal_id = None\n while True:\n observation = env.observation()\n view_image = interleave(observation['view_image'],\n FLAGS.width, FLAGS.height)\n graph_image = interleave(observation['graph_image'],\n FLAGS.width, FLAGS.height)\n screen_buffer = np.concatenate((view_image, graph_image), axis=1)\n pygame.surfarray.blit_array(screen, screen_buffer)\n pygame.display.update()\n\n for event in pygame.event.get():\n if (event.type == pygame.QUIT or\n (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE)):\n return\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_p:\n filename = time.strftime('oracle_agent_%Y%m%d_%H%M%S.bmp')\n pygame.image.save(screen, filename)\n\n # Take a step given the previous action and record the reward.\n _, reward, done, info = env.step(action)\n sum_rewards += reward\n if (reward > 0) and (info['current_goal_id'] is not previous_goal_id):\n sum_rewards_at_goal += reward\n previous_goal_id = info['current_goal_id']\n if done:\n print('Episode reward: {}'.format(sum_rewards))\n if FLAGS.stats_path:\n with open(FLAGS.stats_path, 'a') as f:\n f.write(str(sum_rewards) + '\\t' + str(sum_rewards_at_goal) + '\\n')\n sum_rewards = 0\n sum_rewards_at_goal = 0\n\n # Determine the next pano and bearing to that pano.\n current_pano_id = info['current_pano_id']\n next_pano_id = info['next_pano_id']\n bearing = info['bearing_to_next_pano']\n logging.info('Current pano: %s, next pano %s at %f',\n current_pano_id, next_pano_id, bearing)\n\n # Bearing-based navigation.\n if bearing > TOL_BEARING:\n if bearing > TOL_BEARING + 2 * FLAGS.horizontal_rot:\n action = 3 * FLAGS.horizontal_rot * action_spec['horizontal_rotation']\n else:\n action = FLAGS.horizontal_rot * action_spec['horizontal_rotation']\n elif bearing < -TOL_BEARING:\n if bearing < -TOL_BEARING - 2 * FLAGS.horizontal_rot:\n action = -3 * FLAGS.horizontal_rot * action_spec['horizontal_rotation']\n else:\n action = -FLAGS.horizontal_rot * action_spec['horizontal_rotation']\n else:\n action = action_spec['move_forward']\n\ndef main(argv):\n config = {'width': FLAGS.width,\n 'height': FLAGS.height,\n 'graph_width': FLAGS.width,\n 'graph_height': FLAGS.height,\n 'graph_zoom': FLAGS.graph_zoom,\n 'goal_timeout': FLAGS.frame_cap,\n 'frame_cap': FLAGS.frame_cap,\n 'full_graph': (FLAGS.start_pano == ''),\n 'start_pano': FLAGS.start_pano,\n 'min_graph_depth': FLAGS.graph_depth,\n 'max_graph_depth': FLAGS.graph_depth,\n 'proportion_of_panos_with_coins':\n FLAGS.proportion_of_panos_with_coins,\n 'action_spec': 'streetlearn_fast_rotate',\n 'observations': ['view_image', 'graph_image', 'yaw', 'pitch']}\n config = default_config.ApplyDefaults(config)\n game = courier_game.CourierGame(config)\n env = streetlearn.StreetLearn(FLAGS.dataset_path, config, game)\n env.reset()\n pygame.init()\n screen = pygame.display.set_mode((FLAGS.width, FLAGS.height * 2))\n loop(env, screen)\n\nif __name__ == '__main__':\n app.run(main)\n" }, { "alpha_fraction": 0.6804420948028564, "alphanum_fraction": 0.6878904104232788, "avg_line_length": 29.602941513061523, "blob_id": "aebc2ee5744354c90afc67753a61e077658b1efe", "content_id": "51caa0424f1b2b8ecfce741efc69b9ba54f5ce94", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4162, "license_type": "permissive", "max_line_length": 80, "num_lines": 136, "path": "/streetlearn/engine/image.h", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#ifndef THIRD_PARTY_STREETLEARN_ENGINE_IMAGE_H_\n#define THIRD_PARTY_STREETLEARN_ENGINE_IMAGE_H_\n\n#include <cstdint>\n#include <cstring>\n#include <vector>\n\n#include \"streetlearn/engine/logging.h\"\n#include \"absl/types/span.h\"\n\nnamespace streetlearn {\n\n// An ImageFrame is a common superclass for Image and ImageView storing\n// dimensions and implements pixel offset calculation.\ntemplate <int kChannels>\nclass ImageFrame {\n static_assert(kChannels > 0, \"Channels must be greater than zero\");\n\n public:\n // Construct an ImageFrame for an image of size width x height. The width_step\n // defines the step in pixels for to the next row which is useful if\n // ImageFrame refers to a sub image.\n ImageFrame(int width, int height, int width_step)\n : width_(width), height_(height), width_step_(width_step) {\n CHECK_GE(width, 0);\n CHECK_GE(height, 0);\n }\n\n virtual ~ImageFrame() = default;\n\n int width() const { return width_; }\n int height() const { return height_; }\n int channels() const { return kChannels; }\n\n int offset(int col, int row) const {\n if (0 <= col && col < width_ && 0 <= row && row < height_) {\n return (width_step_ * row + col) * kChannels;\n }\n\n return 0;\n }\n\n private:\n const int width_;\n const int height_;\n const int width_step_;\n};\n\n// The Image class represents a continous memory buffer of `PixelType` to help\n// storing and accessing images easier.\ntemplate <typename PixelType, int kChannels>\nclass Image : public ImageFrame<kChannels> {\n public:\n Image() : ImageFrame<kChannels>(0, 0, 0) {}\n\n Image(int width, int height)\n : ImageFrame<kChannels>(width, height, width),\n pixels_(width * height * kChannels) {}\n\n Image(const Image& other)\n : ImageFrame<kChannels>(other.width(), other.height(), other.width()),\n pixels_(other.pixels_) {}\n\n ~Image() override = default;\n\n PixelType* pixel(int col, int row) {\n if (pixels_.empty()) return nullptr;\n return &pixels_[ImageFrame<kChannels>::offset(col, row)];\n }\n\n const PixelType* pixel(int col, int row) const {\n if (pixels_.empty()) return nullptr;\n return &pixels_[ImageFrame<kChannels>::offset(col, row)];\n }\n\n absl::Span<const PixelType> data() const { return pixels_; }\n\n private:\n std::vector<PixelType> pixels_;\n};\n\n// ImageView defines a readable and writable view of an Image. As a convenience,\n// ImageView makes it possible to decorate any buffer of type PixelType and use\n// it as if it were an image.\ntemplate <typename PixelType, int kChannels>\nclass ImageView : public ImageFrame<kChannels> {\n public:\n ImageView(Image<PixelType, kChannels>* image, int col, int row, int width,\n int height)\n : ImageFrame<kChannels>(width, height, image->width()),\n pixels_(image->pixel(col, row)) {\n CHECK_LE(0, col);\n CHECK_LE(0, row);\n CHECK_LE(col + width, image->width());\n CHECK_LE(row + height, image->height());\n }\n\n ImageView(PixelType* data, int width, int height)\n : ImageFrame<kChannels>(width, height, width), pixels_(data) {}\n\n ~ImageView() override = default;\n\n PixelType* pixel(int col, int row) {\n return &pixels_[ImageFrame<kChannels>::offset(col, row)];\n }\n\n const PixelType* pixel(int col, int row) const {\n return &pixels_[ImageFrame<kChannels>::offset(col, row)];\n }\n\n private:\n PixelType* const pixels_;\n};\n\nusing Image3_b = Image<uint8_t, 3>;\nusing Image4_b = Image<uint8_t, 4>;\nusing ImageView3_b = ImageView<uint8_t, 3>;\nusing ImageView4_b = ImageView<uint8_t, 4>;\n\n}; // namespace streetlearn\n\n#endif // THIRD_PARTY_STREETLEARN_ENGINE_IMAGE_H_\n" }, { "alpha_fraction": 0.675000011920929, "alphanum_fraction": 0.6784090995788574, "avg_line_length": 26.216495513916016, "blob_id": "18a7c4e01a4c9cc07af73ccdba1cf393a2502b81", "content_id": "7793f8ad4f63c4a6d9fad6ee52054b423f3404cd", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2640, "license_type": "permissive", "max_line_length": 75, "num_lines": 97, "path": "/streetlearn/engine/pano_fetcher.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/pano_fetcher.h\"\n\n#include <fstream>\n#include <memory>\n#include <streambuf>\n\n#include \"absl/memory/memory.h\"\n#include \"absl/strings/str_cat.h\"\n#include \"absl/synchronization/mutex.h\"\n#include \"streetlearn/engine/pano_graph_node.h\"\n\nnamespace streetlearn {\n\nPanoFetcher::PanoFetcher(const Dataset* dataset, int thread_count,\n FetchCallback callback)\n : dataset_(dataset),\n threads_(thread_count),\n callback_(std::move(callback)),\n shutdown_(false) {\n for (int i = 0; i < thread_count; ++i) {\n threads_[i] = std::thread(&PanoFetcher::ThreadExecute, this);\n }\n}\n\nPanoFetcher::~PanoFetcher() {\n {\n absl::MutexLock lock(&queue_mutex_);\n shutdown_ = true;\n }\n for (auto& thread : threads_) {\n thread.join();\n }\n}\n\nstd::shared_ptr<const PanoGraphNode> PanoFetcher::Fetch(\n absl::string_view pano_id) {\n Pano pano;\n if (dataset_->GetPano(pano_id, &pano)) {\n return std::make_shared<PanoGraphNode>(std::move(pano));\n }\n\n return nullptr;\n}\n\nvoid PanoFetcher::FetchAsync(absl::string_view pano_id) {\n absl::MutexLock lock(&queue_mutex_);\n fetch_queue_.emplace_front(pano_id);\n}\n\nbool PanoFetcher::MonitorRequests(std::string* pano_id) {\n auto lock_condition = [](PanoFetcher* fetcher) {\n fetcher->queue_mutex_.AssertHeld();\n return !fetcher->fetch_queue_.empty() || fetcher->shutdown_;\n };\n\n queue_mutex_.LockWhen(absl::Condition(+lock_condition, this));\n if (!shutdown_) {\n *pano_id = fetch_queue_.back();\n fetch_queue_.pop_back();\n queue_mutex_.Unlock();\n return true;\n } else {\n queue_mutex_.Unlock();\n return false;\n }\n}\n\nvoid PanoFetcher::ThreadExecute() {\n std::string pano_id;\n while (MonitorRequests(&pano_id)) {\n callback_(pano_id, Fetch(pano_id));\n }\n}\n\nstd::vector<std::string> PanoFetcher::CancelPendingFetches() {\n absl::MutexLock lock(&queue_mutex_);\n std::vector<std::string> cancelled(\n {fetch_queue_.begin(), fetch_queue_.end()});\n fetch_queue_.clear();\n return cancelled;\n}\n\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.6718611121177673, "alphanum_fraction": 0.6790961623191833, "avg_line_length": 32.52238845825195, "blob_id": "7532e60dbaa445c7d43041cf4f0845cad0bf51ff", "content_id": "d11506d895e0c823f07a16888c7ef6b1df00869c", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8984, "license_type": "permissive", "max_line_length": 80, "num_lines": 268, "path": "/streetlearn/engine/streetlearn_engine.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/streetlearn_engine.h\"\n\n#include <functional>\n\n#include \"streetlearn/engine/logging.h\"\n#include \"absl/hash/hash.h\"\n#include \"absl/memory/memory.h\"\n#include \"streetlearn/engine/bitmap_util.h\"\n#include \"streetlearn/engine/math_util.h\"\n\nnamespace streetlearn {\nnamespace {\n\nconstexpr int kDefaultPrefetchGraphDepth = 20;\nconstexpr int kDefaultMaxNeighborDepth = 3;\nconstexpr bool kShowStopSigns = true;\nconstexpr double kTolerance = 30;\nconstexpr double kMaxYaw = 180;\nconstexpr double kMaxPitch = 90;\n\n// Constrain angle to be in [-constraint, constraint].\nvoid ConstrainAngle(double constraint, double* angle) {\n while (*angle < -constraint) {\n *angle += 2.0 * constraint;\n }\n while (*angle > constraint) {\n *angle -= 2.0 * constraint;\n }\n}\n\n} // namespace\n\nstd::unique_ptr<StreetLearnEngine> StreetLearnEngine::Create(\n const std::string& data_path, int width, int height, int graph_width,\n int graph_height, int status_height, int field_of_view, int min_graph_depth,\n int max_graph_depth, int max_cache_size) {\n auto dataset = Dataset::Create(data_path);\n if (!dataset) {\n return nullptr;\n }\n\n return absl::make_unique<StreetLearnEngine>(\n std::move(dataset), Vector2_i(width, height),\n Vector2_i(graph_width, graph_height), status_height, field_of_view,\n min_graph_depth, max_graph_depth, max_cache_size);\n}\n\nStreetLearnEngine::StreetLearnEngine(std::unique_ptr<Dataset> dataset,\n const Vector2_i& pano_size,\n const Vector2_i& graph_size,\n int status_height, int field_of_view,\n int min_graph_depth, int max_graph_depth,\n int max_cache_size)\n : dataset_(std::move(dataset)),\n pano_size_(pano_size),\n graph_size_(graph_size),\n show_stop_signs_(kShowStopSigns),\n rotation_yaw_(0),\n rotation_pitch_(0),\n field_of_view_(field_of_view),\n pano_buffer_(3 * pano_size.x() * pano_size.y()),\n graph_buffer_(3 * graph_size.x() * graph_size.y()),\n pano_graph_(kDefaultPrefetchGraphDepth, max_cache_size, min_graph_depth,\n max_graph_depth, dataset_.get()),\n pano_renderer_(pano_size.x(), pano_size.y(), status_height,\n field_of_view) {\n // TODO: Init return value unused.\n pano_graph_.Init();\n}\n\nvoid StreetLearnEngine::InitEpisode(int episode_index, int random_seed) {\n absl::Hash<std::tuple<int, int>> hasher;\n int seed = hasher(std::make_tuple(episode_index, random_seed));\n pano_graph_.SetRandomSeed(seed);\n}\n\nstd::string StreetLearnEngine::SetupCurrentGraph() {\n rotation_yaw_ = 0;\n rotation_pitch_ = 0;\n return pano_graph_.Root().id();\n}\n\nabsl::optional<std::string> StreetLearnEngine::BuildRandomGraph() {\n if (!pano_graph_.BuildRandomGraph()) {\n return absl::nullopt;\n }\n return SetupCurrentGraph();\n}\n\nabsl::optional<std::string> StreetLearnEngine::BuildGraphWithRoot(\n const std::string& pano_id) {\n if (!pano_graph_.BuildGraphWithRoot(pano_id)) {\n return absl::nullopt;\n }\n return SetupCurrentGraph();\n}\n\nvoid StreetLearnEngine::SetGraphDepth(const int min_depth,\n const int max_depth) {\n pano_graph_.SetGraphDepth(min_depth, max_depth);\n}\n\nabsl::optional<std::string> StreetLearnEngine::BuildEntireGraph() {\n if (!pano_graph_.BuildEntireGraph()) {\n return absl::nullopt;\n }\n return SetupCurrentGraph();\n}\n\nabsl::optional<std::string> StreetLearnEngine::SetPosition(\n const std::string& pano_id) {\n if (!pano_graph_.SetPosition(pano_id)) {\n return absl::nullopt;\n }\n return SetupCurrentGraph();\n}\n\nabsl::optional<std::string> StreetLearnEngine::MoveToNextPano() {\n if (!pano_graph_.MoveToNeighbor(rotation_yaw_, kTolerance)) {\n return absl::nullopt;\n }\n return pano_graph_.Root().id();\n}\n\nvoid StreetLearnEngine::RotateObserver(double yaw_deg, double pitch_deg) {\n rotation_yaw_ += yaw_deg;\n ConstrainAngle(kMaxYaw, &rotation_yaw_);\n rotation_pitch_ -= pitch_deg;\n ConstrainAngle(kMaxPitch, &rotation_pitch_);\n}\n\nvoid StreetLearnEngine::RenderScene() {\n const auto& neighbor_bearings =\n pano_graph_.GetNeighborBearings(kDefaultMaxNeighborDepth);\n std::map<int, std::vector<TerminalGraphNode>> terminal_bearings;\n if (show_stop_signs_) {\n terminal_bearings = pano_graph_.TerminalBearings(pano_graph_.Root().id());\n }\n pano_renderer_.RenderScene(\n *pano_graph_.RootImage(), pano_graph_.Root().bearing(), rotation_yaw_,\n rotation_pitch_, kTolerance, neighbor_bearings, terminal_bearings);\n}\n\nabsl::Span<const uint8_t> StreetLearnEngine::RenderObservation() {\n RenderScene();\n const auto& pixels = pano_renderer_.Pixels();\n\n // Convert from packed to planar.\n ConvertRGBPackedToPlanar(pixels.data(), pano_size_.x(), pano_size_.y(),\n pano_buffer_.data());\n\n return pano_buffer_;\n}\n\nvoid StreetLearnEngine::RenderObservation(absl::Span<uint8_t> buffer) {\n RenderScene();\n\n const auto& pixels = pano_renderer_.Pixels();\n if (buffer.size() != pixels.size()) {\n LOG(ERROR)\n << \"Input buffer is not the right size for rendering. Buffer size: \"\n << buffer.size() << \" Required size: \" << pixels.size();\n return;\n }\n\n ConvertRGBPackedToPlanar(pixels.data(), pano_size_.x(), pano_size_.y(),\n pano_buffer_.data());\n std::copy(pano_buffer_.begin(), pano_buffer_.end(), buffer.begin());\n}\n\nstd::vector<uint8_t> StreetLearnEngine::GetNeighborOccupancy(\n const int resolution) {\n const auto& neighbor_bearings =\n pano_graph_.GetNeighborBearings(kDefaultMaxNeighborDepth);\n std::vector<uint8_t> neighborOccupancy(resolution, 0);\n\n // For each neighbor in bearings, decide which bin to place it in.\n // Normalize the bearings by subtracting the agent's orientation,\n // then add a fixed offset that is half the size of one bin to make the\n // agent's current orientation be centered in a bin rather than in between.\n double double_offset = 360.0 / static_cast<double>(resolution) / 2.0;\n for (auto bearing : neighbor_bearings) {\n double recentered = bearing.bearing - rotation_yaw_;\n double offset = recentered + double_offset;\n offset -= 360.0 * floor(offset / 360.0);\n\n int bin = static_cast<int>(offset / 360.0 * resolution);\n neighborOccupancy[bin] = 1;\n }\n return neighborOccupancy;\n}\n\nbool StreetLearnEngine::InitGraphRenderer(\n const Color& observer_color,\n const std::map<std::string, streetlearn::Color>& panos_to_highlight) {\n observer_.color = observer_color;\n graph_renderer_ =\n GraphRenderer::Create(pano_graph_, graph_size_, panos_to_highlight);\n return graph_renderer_ != nullptr;\n}\n\nbool StreetLearnEngine::DrawGraph(\n const std::map<std::string, streetlearn::Color>& pano_id_to_color,\n absl::Span<uint8> buffer) {\n if (!graph_renderer_) return false;\n\n observer_.pano_id = pano_graph_.Root().id();\n observer_.yaw_radians = math::DegreesToRadians(rotation_yaw_);\n observer_.fov_yaw_radians = math::DegreesToRadians(field_of_view_);\n\n if (!graph_renderer_->RenderScene(pano_id_to_color, observer_)) {\n return false;\n }\n\n graph_renderer_->GetPixels(absl::MakeSpan(graph_buffer_));\n ConvertRGBPackedToPlanar(graph_buffer_.data(), graph_size_.x(),\n graph_size_.y(), buffer.data());\n return true;\n}\n\nbool StreetLearnEngine::SetZoom(double zoom) {\n if (!graph_renderer_) return false;\n return graph_renderer_->SetZoom(zoom);\n}\n\nstd::shared_ptr<const Pano> StreetLearnEngine::GetPano() const {\n return pano_graph_.Root().GetPano();\n}\n\nabsl::optional<double> StreetLearnEngine::GetPanoDistance(\n const std::string& pano_id1, const std::string& pano_id2) {\n return pano_graph_.GetPanoDistance(pano_id1, pano_id2);\n}\n\nabsl::optional<double> StreetLearnEngine::GetPanoBearing(\n const std::string& pano_id1, const std::string& pano_id2) {\n return pano_graph_.GetPanoBearing(pano_id1, pano_id2);\n}\n\nabsl::optional<PanoMetadata> StreetLearnEngine::GetMetadata(\n const std::string& pano_id) const {\n PanoMetadata metadata;\n if (!pano_graph_.Metadata(pano_id, &metadata)) {\n return absl::nullopt;\n }\n return metadata;\n}\n\nstd::map<std::string, std::vector<std::string>> StreetLearnEngine::GetGraph()\n const {\n return pano_graph_.GetGraph();\n}\n\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.7397290468215942, "alphanum_fraction": 0.7455201148986816, "avg_line_length": 42.58095169067383, "blob_id": "af8edbf842942749f4d40d02c884e388db4862de", "content_id": "d5e6c98fdf427c7dc6ece73e82f2246cea485928", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 18304, "license_type": "permissive", "max_line_length": 212, "num_lines": 420, "path": "/README.md", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "# StreetLearn\n\n## Overview\n\nThis repository contains an implementation of the\n[**StreetLearn**](http://streetlearn.cc) environment for training navigation\nagents as well as code for implementing the agents used in the NeurIPS 2018\npaper on\n[\"Learning to Navigate in Cities Without a Map\"](http://papers.nips.cc/paper/7509-learning-to-navigate-in-cities-without-a-map).\nThe StreetLearn environment relies on panorama images from\n[Google Street View](https://maps.google.com) and provides an interface for\nmoving a first-person view agent inside the Street View graph. This is not an\nofficially supported Google product.\n\nFor a detailed description of the architecture please read our paper. Please\ncite the paper if you use the code from this repository in your work.\n\nOur paper also provides a detailed description of how to train and implement\nnavigation agents in the StreetLearn environment by using a TensorFlow\nimplementation of \"Importance Weighted Actor-Learner Architectures\", published\nin Espeholt, Soyer, Munos et al. (2018) \"IMPALA: Scalable Distributed Deep-RL\nwith Importance Weighted Actor-Learner\nArchitectures\"(https://arxiv.org/abs/1802.01561). The generic agent and trainer\ncode have been published by Lasse Espeholt under an Apache license at:\n[https://github.com/deepmind/scalable_agent](https://github.com/deepmind/scalable_agent).\n\n### Bibtex\n\n```\n@inproceedings{mirowski2018learning,\n title={Learning to Navigate in Cities Without a Map},\n author={Mirowski, Piotr and Grimes, Matthew Koichi and Malinowski, Mateusz and Hermann, Karl Moritz and Anderson, Keith and Teplyashin, Denis and Simonyan, Karen and Kavukcuoglu, Koray and Zisserman, Andrew and Hadsell, Raia},\n booktitle={Neural Information Processing Systems (NeurIPS)},\n year={2018}\n}\n```\n\n### Code structure\n\nThis environment code contains:\n\n* **streetlearn/engine** Our C++ StreetLearn engine for loading, caching and\n serving Google Street View panoramas by projecting them from a\n equirectangular representation to first-person projected view at a given\n yaw, pitch and field of view, and for handling navigation (moving from one\n panorama to another) depending on the city street graph and the current\n orientation.\n* **streetlearn/proto** The message\n [protocol buffer](https://developers.google.com/protocol-buffers/) used to\n store panoramas and street graph.\n* **streetlearn/python/environment** A Python-based interface for calling the\n StreetLearn environment with custom action spaces. Within the Python\n StreetLearn interface, several games are defined in individual files whose\n names end with **_game.py**.\n* **streetlearn/python/ui** A simple interactive **human_agent** and an\n **oracle_agent** and **instruction_following_oracle_agent** for courier and\n instruction-following tasks respectively; all agents are implemented in\n Python using pygame and instantiate the StreetLearn environment on the\n requested map, along with a simple user interface. The interactive\n **human_agent** enables a user to play various games. The **oracle_agent**\n and **instruction_following_oracle_agent** are similar to the human agent\n and automatically navigate towards the goal (courier game) or towards the\n goal via waypoints, following instructions (instruction-following game) and\n they report oracle performance on these tasks.\n\n## Compilation from source\n\n[Bazel](http://bazel.build) is the official build system for StreetLearn. The\nbuild has only been tested running on Ubuntu 18.04.\n\n### Install build prerequisites\n\n```shell\nsudo apt-get install autoconf automake libtool curl make g++ unzip virtualenv python-virtualenv cmake subversion pkg-config libpython-dev libcairo2-dev libboost-all-dev python-pip libssl-dev\npip install setuptools\npip install pyparsing\n```\n\n### Install Protocol Buffers\n\nFor detailed information see:\nhttps://github.com/protocolbuffers/protobuf/blob/master/src/README.md\n\n```shell\ngit clone https://github.com/protocolbuffers/protobuf.git\ncd protobuf\ngit submodule update --init --recursive\n./autogen.sh\n./configure\nmake -j7\nsudo make install\nsudo ldconfig\ncd python\npython setup.py build\nsudo python setup.py install\ncd ../..\n```\n\n### Install CLIF\n\n```shell\ngit clone https://github.com/google/clif.git\ncd clif\n./INSTALL.sh\ncd ..\n```\n\n### Install OpenCV 2.4.13\n\n```shell\nwget https://github.com/opencv/opencv/archive/2.4.13.6.zip\nunzip 2.4.13.6.zip\ncd opencv-2.4.13.6\nmkdir build\ncd build\ncmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local ..\nmake -j7\nsudo make install\nsudo ldconfig\ncd ../..\n```\n\n### Install Python dependencies\n\n```shell\npip install six\npip install absl-py\npip install inflection\npip install wrapt\npip install numpy\npip install dm-sonnet\npip install tensorflow-gpu\npip install tensorflow-probability-gpu\npip install pygame\n```\n\n### Install Bazel\n\n[This page](https://bazel.build/) describes how to install the Bazel build and\ntest tool on your machine.\n\n### Building StreetLearn\n\nClone this repository and install\n[Scalable Agent](https://github.com/deepmind/scalable_agent):\n\n```shell\ngit clone https://github.com/deepmind/streetlearn.git\ncd streetlearn\nsh get_scalable_agent.sh\n```\n\nTo build the StreetLearn engine only:\n\n```shell\nexport CLIF_PATH=$HOME/opt\nbazel build streetlearn:streetlearn_engine_py\n```\n\nTo build the human agent and the oracle agent in the StreetLearn environment,\nwith all the dependencies:\n\n```shell\nexport CLIF_PATH=$HOME/opt\nbazel build streetlearn/python/ui:all\n```\n\n## Running the StreetLearn human agent\n\nTo run the human agent using one of the StreetLearn datasets downloaded and\nstored at **dataset_path**:\n\n```shell\nbazel run streetlearn/python/ui:human_agent -- --dataset_path=<dataset path>\n```\n\nFor help with the options of the human_agent:\n\n```shell\nbazel run streetlearn/python/ui:human_agent -- --help\n```\n\nSimilarly, to run the oracle agent on the courier game:\n\n```shell\nbazel run streetlearn/python/ui:oracle_agent -- --dataset_path=<dataset path>\n```\n## Building the scalable agent in the Streetlearn environment, and training it using StreetLearn datasets\n\n```shell\nexport CLIF_PATH=$HOME/opt\nbazel build streetlearn/python:experiment\nbazel run streetlearn/python:experiment -- --dataset_paths=<dataset path> --level_names=<dataset name>\n```\n\n* **dataset path** denotes the path of streetlearn datasets.\n* **dataset name** denotes the streetlearn dataset name stored in the **dataset path**.\n\nFor more information, using:\n```shell\nbazel run streetlearn/python:experiment -- --help\n```\n\nThe human agent and the oracle agent show a **view_image** (on top) and a\n**graph_image** (on bottom).\n\n### Actions available to an agent:\n\n* Rotate left or right in the panorama, by a specified angle (change the yaw\n of the agent). In the human_agent, press **a** or **d**.\n* Rotate up or down in the panorama, by a specified angle (change the pitch of\n the agent). In the human_agent, press **w** or **s**.\n* Move from current panorama A forward to another panorama B if the current\n bearing of the agent from A to B is within a tolerance angle of 30 degrees.\n In the human_agent, press **space**.\n* Zoom in and out in the panorama. In the human_agent, press **i** or **o**.\n\nAdditional keys for the human_agent are **escape** and **p** (to print the\ncurrent view as a bitmap image).\n\nFor training RL agents, action spaces are discretized using integers. For\ninstance, in our paper, we used 5 actions: (move forward, turn left by 22.5 deg,\nturn left by 67.5 deg, turn right by 22.5 deg, turn right by 67.5 deg).\n\n### Navigation Bar\n\nAlong the bottom of the **view_image** is the navigation bar which displays a\nsmall circle in any direction in which travel is possible:\n\n* When within the centre range, they will turn green meaning the user can move\n in this direction.\n* When they are out of this range, they will turn red meaning this is\n inaccessible.\n* When more than one dots are within the centre range, all except the most\n central will turn orange, meaning that there are multiple (forward)\n directions available.\n\n### Stop signs\n\nThe graph is constructed by breadth first search to the depth specified by the\ngraph depth flags. At the maximum depth the graph will suddenly stop, generally\nin the middle of a street. Because we are trying to train agents to recognize\nstreets as navigable, and in order not to confuse the agents, red stop signs are\nshown from two panoramas away from any terminal node in the graph.\n\n### Obtaining the StreetLearn dataset\n\nYou can request the StreetLearn dataset on the\n[StreetLearn project website](https://sites.google.com/view/streetlearn/).\n\n## Using the StreetLearn environment code\n\nThe Python StreetLearn environment follows the specifications from\n[OpenAI Gym](https://gym.openai.com/docs/). The call to function\n**step(action)** returns: * **observation** (tuple of observations requested at\nconstruction), * **reward** (a float with the current reward of the agent), *\n**done** (boolean indicating whether the episode has ended) * and **info** (a\ndictionary of environment state variables). After creating the environment, it\nis initialised by calling function **reset()**. If the flag auto_reset is set to\nTrue at construction, **reset()** will be called automatically every time that\nan episode ends.\n\n### Environment Settings\n\nDefault environment settings are stored in streetlearn/python/default_config.py.\n\n* **seed**: Random seed.\n* **width**: Width of the streetview image.\n* **height**: Height of the streetview image.\n* **graph_width**: Width of the map graph image.\n* **graph_height**: Height of the map graph image.\n* **status_height**: Status bar height in pixels.\n* **field_of_view**: Horizontal field of view, in degrees.\n* **min_graph_depth**: Min bound on BFS depth for panos.\n* **max_graph_depth**: Max bound on BFS depth for panos.\n* **max_cache_size**: Pano cache size.\n* **bbox_lat_min**: Minimum value for normalizing the target latitude.\n* **bbox_lat_max**: Maximum value for normalizing the target latitude.\n* **bbox_lng_min**: Minimum value for normalizing the target longitude.\n* **bbox_lng_max**: Maximum value for normalizing the target longitude.\n* **min_radius_meters**: Minimum distance from goal at which reward shaping\n starts in the courier game.\n* **max_radius_meters**: Maximum distance from goal at which reward shaping\n starts in the courier game.\n* **timestamp_start_curriculum**: Integer timestamp (UNIX time) when\n curriculum learning starts, used in the curriculum courier game.\n* **hours_curriculum_part_1**: Number of hours for the first part of\n curriculum training (goal location within minimum distance), used in the\n curriculum courier game.\n* **hours_curriculum_part_2**: Number of hours for the second part of\n curriculum training (goal location annealed further away), used in the\n curriculum courier game.\n* **min_goal_distance_curriculum**: Distance in meters of the goal location at\n the beginning of curriculum learning, used in the curriculum courier game.\n* **max_goal_distance_curriculum**: Distance in meters of the goal location at\n the beginning of curriculum learning, used in the curriculum courier game.\n* **instruction_curriculum_type**: Type of curriculum learning, used in the\n instruction following games.\n* **frame_cap**: Episode frame cap.\n* **full_graph**: Boolean indicating whether to build the entire graph upon\n episode start.\n* **sample_graph_depth**: Boolean indicating whether to sample graph depth\n between min_graph_depth and max_graph_depth.\n* **start_pano**: The pano ID string to start from. The graph will be build\n out from this point.\n* **graph_zoom**: Initial graph zoom. Valid between 1 and 32.\n* **show_shortest_path**: Boolean indicator asking whether the shortest path\n to the goal shall be shown on the graph.\n* **calculate_ground_truth**: Boolean indicator asking whether the ground\n truth direction to the goal should be calculated during the game (useful for\n oracle agents, visualisation and for imitation learning).\n* **neighbor_resolution**: Used to calculate a binary occupancy vector of\n neighbors to the current pano.\n* **color_for_touched_pano**: RGB color for the panos touched by the agent.\n* **color_for_observer**: RGB color for the observer.\n* **color_for_coin**: RGB color for the panos containing coins.\n* **color_for_goal**: RGB color for the goal pano.\n* **color_for_shortest_path**: RGB color for panos on the shortest path to the\n goal.\n* **color_for_waypoint**: RGB color for a waypoint pano.\n* **observations**: Array containing one or more names of the observations\n requested from the environment: ['view_image', 'graph_image', 'yaw',\n 'pitch', 'metadata', 'target_metadata', 'latlng', 'target_latlng',\n 'latlng_label', 'target_latlng_label', 'yaw_label', 'neighbors',\n 'thumbnails', 'instructions', 'ground_truth_direction']\n* **reward_per_coin**: Coin reward for coin game.\n* **reward_at_waypoint**: Waypoint reward for the instruction-following games.\n* **reward_at_goal**: Goal reward for the instruction-following games.\n* **proportion_of_panos_with_coins**: The proportion of panos with coins.\n* **game_name**: Game name, can be: 'coin_game', 'exploration_game',\n 'courier_game', 'curriculum_courier_game', 'goal_instruction_game',\n 'incremental_instruction_game' and 'step_by_step_instruction_game'.\n* **action_spec**: Either of 'streetlearn_default', 'streetlearn_fast_rotate',\n 'streetlearn_tilt'\n* **rotation_speed**: Rotation speed in degrees. Used to create the action\n spec.\n* **auto_reset**: Boolean indicator whether games are reset automatically when\n the max number of frames is achieved.\n\n### Observations\n\nThe following observations can be returned by the agent:\n\n* **view_image**: RGB image for the first-person view image returned from the\n environment and seen by the agent,\n* **graph_image**: RGB image for the top-down street graph image, usually not\n seen by the agent,\n* **yaw**: Scalar value of the yaw angle of the agent, in degrees (zero\n corresponds to North),\n* **pitch**: Scalar value of the pitch angle of the agent, in degrees (zero\n corresponds to horizontal),\n* **metadata**: Message protocol buffer of type Pano with the metadata of the\n current panorama,\n* **target_metadata**: Message protocol buffer of type Pano with the metadata\n of the target/goal panorama,\n* **latlng**: Tuple of lat/lng scalar values for the current position of the\n agent,\n* **target_latlng**: Tuple of lat/lng scalar values for the target/goal\n position,\n* **latlng_label**: Integer discretized value of the current agent position\n using 1024 bins (32 bins for latitude and 32 bins for longitude),\n* **target_latlng_label**: Integer discretized value of the target position\n using 1024 bins (32 bins for latitude and 32 bins for longitude),\n* **yaw_label**: Integer discretized value of the agent yaw using 16 bins,\n* **neighbors**: Vector of immediate neighbor egocentric traversability grid\n around the agent, with 16 bins for the directions around the agent and bin 0\n corresponding to the traversability straight ahead of the agent.\n* **thumbnails**: Array of n+1 RGB images for the first-person view image\n returned from the environment, that should be seen by the agent at specific\n waypoints and goal locations when playing the instruction-following game\n with n instructions,\n* **instructions**: List of n string instructions for the agent at specific\n waypoints and goal locations when playing the instruction-following game\n with n instructions,\n* **ground_truth_direction**: Scalar value of the relative ground truth\n direction to be taken by the agent in order to follow a shortest path to the\n next goal or waypoint. This observation should be requested only for agents\n trained using imitation learning.\n\n### Games\n\nThe following games are available in the StreetLearn environment:\n\n* **coin_game**: invisible coins scattered throughout the map, yielding a\n reward of 1 for each. Once picked up, these rewards do not reappear until\n the end of the episode.\n* **courier_game**: the agent is given a goal destination, specified as\n lat/long pairs. Once the goal is reached (with 100m tolerance), a new goal\n is sampled, until the end of the episode. Rewards at a goal are proportional\n to the number of panoramas on the shortest path from the agent's position\n when it gets the new goal assignment to that goal position. Additional\n reward shaping consists in early rewards when the agent gets within a range\n of 200m of the goal. Additional coins can also be scattered throughout the\n environment. The proportion of coins, the goal radius and the early reward\n radius are parametrizable.\n* **curriculum_courier_game**: same as the courier game, but with a curriculum\n on the difficulty of the task (maximum straight-line distance from the\n agent's position to the goal when it is assigned).\n* **goal_instruction_game** and its variations\n **incremental_instruction_game** and **step_by_step_instruction_game** use\n navigation instructions to direct agents to a goal. Agents are provided with\n a list of instructions as well as thumbnails that guide the agent from its\n starting position to the goal location. In\n **step_by_step_instruction_game**, agents are provided one instruction and\n two thumbnails at a time, in the other game variants the whole list is\n available throughout the whole game. Reward is granted upon reaching the\n goal location (all variants), as well as when hitting individual waypoints\n (**incremental_instruction_game** and **step_by_step_instruction_game**\n only). During training various curriculum strategies are available to the\n agents, and reward shaping can be employed to provide fractional rewards\n when the agent gets within a range of 50m of a waypoint or goal.\n\n## License\n\nThe Abseil C++ library is licensed under the terms of the Apache license. See\n[LICENSE](LICENSE) for more information.\n\n## Disclaimer\n\nThis is not an official Google product.\n" }, { "alpha_fraction": 0.6624400019645691, "alphanum_fraction": 0.6675805449485779, "avg_line_length": 32.54022979736328, "blob_id": "25980849a4dc389f1f6ed72e540a6c39fd6c4ea8", "content_id": "4fbcb70fa631ace4976d85a21cef1443cea930f6", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2918, "license_type": "permissive", "max_line_length": 84, "num_lines": 87, "path": "/streetlearn/pip_package/setup.py", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "# Copyright 2018 Google LLC.\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\"\"\"\nSetup module for turning StreetLearn into a pip package.\nBased on: https://github.com/google/nucleus/blob/master/nucleus/pip_package/setup.py\nThis should be invoked through build_pip_package.sh, rather than run directly.\n\"\"\"\nimport fnmatch\nimport os\n\nfrom setuptools import find_packages\nfrom setuptools import setup\n\ndef find_files(pattern, root):\n \"\"\"Return all the files matching pattern below root dir.\"\"\"\n for dirpath, _, files in os.walk(root):\n for filename in fnmatch.filter(files, pattern):\n yield os.path.join(dirpath, filename)\n\n\ndef is_python_file(fn):\n return fn.endswith('.py') or fn.endswith('.pyc')\n\nheaders = list(find_files('*.h', 'streetlearn'))\n\nmatches = ['../' + x for x in find_files('*', 'external')\n if not is_python_file(x)]\n\nso_lib_paths = [\n i for i in os.listdir('.')\n if os.path.isdir(i) and fnmatch.fnmatch(i, '_solib_*')\n]\n\nfor path in so_lib_paths:\n matches.extend(['../' + x for x in find_files('*', path)\n if not is_python_file(x)])\n\nsetup(\n name='streetlearn',\n version='0.1.0',\n description='A library to aid navigation research.',\n long_description=\n \"\"\"\n TODO\n \"\"\",\n url='https://github.com/deepmind/streetlearn',\n author='The StreetLearn Team at DeepMind',\n author_email='[email protected]',\n license='Apache 2.0',\n\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'Intended Audience :: Science/Research',\n 'License :: OSI Approved :: Apache Software License',\n 'Operating System :: POSIX :: Linux',\n 'Programming Language :: Python',\n 'Topic :: Scientific/Engineering :: Artificial Intelligence',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n ],\n keywords='navigation tensorflow machine learning',\n packages=find_packages(exclude=['g3doc', 'testdata']),\n install_requires=['six', 'absl-py', 'inflection', 'wrapt', 'numpy',\n 'dm-sonnet', 'tensorflow', 'tensorflow-probability'],\n headers=headers,\n include_package_data=True,\n package_data={'streetlearn': matches},\n data_files=[],\n entry_points={},\n project_urls={\n 'Source': 'https://github.com/deepmind/streetlearn',\n 'Bug Reports': 'https://github.com/deepmind/streetlearn/issues',\n },\n zip_safe=False,\n)\n" }, { "alpha_fraction": 0.7250232100486755, "alphanum_fraction": 0.7278069853782654, "avg_line_length": 36.160919189453125, "blob_id": "268e0e605afc6e998ad02f7398347e41f862fd97", "content_id": "d182116fc601b0cda8ecc833ed2f39498ec6115a", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6466, "license_type": "permissive", "max_line_length": 80, "num_lines": 174, "path": "/streetlearn/engine/pano_graph.h", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#ifndef THIRD_PARTY_STREETLEARN_ENGINE_PANO_GRAPH_H_\n#define THIRD_PARTY_STREETLEARN_ENGINE_PANO_GRAPH_H_\n\n#include <map>\n#include <memory>\n#include <random>\n#include <string>\n#include <vector>\n\n#include \"absl/synchronization/blocking_counter.h\"\n#include \"absl/types/optional.h\"\n#include \"absl/types/span.h\"\n#include \"streetlearn/engine/dataset.h\"\n#include \"streetlearn/engine/metadata_cache.h\"\n#include \"streetlearn/engine/node_cache.h\"\n#include \"streetlearn/engine/pano_graph_node.h\"\n#include \"streetlearn/proto/streetlearn.pb.h\"\n\nnamespace streetlearn {\n\n// Class that represents a graph of PanoGraphNodes. It provides methods for\n// creating random graphs and those containing given panos, as well as\n// methods for navigating and querying the graph.\n// The graph is stored as a lookup from pano ID to metadata which includes\n// neighbor information. The PanoGraphNodes are loaded asyncronously on demand,\n// as loading and decompressing the imagery is a costly operation.\nclass PanoGraph {\n public:\n // prefetch_depth: the depth of the node prefetch neighborhood.\n // max_cache_size: the maximum size of the node cache.\n // min_graph_depth: the minimum depth of graphs required.\n // max_graph_depth: the maximum depth of graphs required.\n // dataset: StreetLearn dataset wrapper.\n PanoGraph(int prefetch_depth, int max_cache_size, int min_graph_depth,\n int max_graph_depth, const Dataset* dataset);\n ~PanoGraph();\n\n // Loads metadata for the region. Returns false if metadata is not available.\n bool Init();\n\n // Initialises the random number generator.\n void SetRandomSeed(int random_seed);\n\n // Builds a graph with the given pano as root. Returns false if the pano\n // supplied is not in the graph.\n bool BuildGraphWithRoot(const std::string& pano_id);\n\n // Builds a graph between min_graph_depth_ and max_graph_depth_, chosen\n // randomly from those available. Returns false if none are available.\n bool BuildRandomGraph();\n\n // Builds the largest connected graph in the region. Returns false if no\n // graphs are available.\n bool BuildEntireGraph();\n\n // Sets the min and max graph depth\n void SetGraphDepth(int min_depth, int max_depth);\n\n // Teleports to the given pano, if it's in the current graph. Returns false\n // if the teleport is not possible.\n bool SetPosition(const std::string& pano_id);\n\n // Gets the image from the root node.\n std::shared_ptr<Image3_b> RootImage() const;\n\n // Moves to neighbor if there is one within tolerance of our bearing. Returns\n // false if the move is not possible.\n bool MoveToNeighbor(double current_bearing, double tolerance);\n\n // Returns the bearings of all neighbors of the root node in the graph.\n std::vector<PanoNeighborBearing> GetNeighborBearings(\n int max_neighbor_depth) const;\n\n // Returns all terminal neighbors of the node with their distance in numbers\n // of nodes, up to two hops from the current node.\n std::map<int, std::vector<TerminalGraphNode>> TerminalBearings(\n const std::string& node_id) const;\n\n // Returns the distance in meters between two panos.\n absl::optional<double> GetPanoDistance(const std::string& pano_id1,\n const std::string& pano_id2);\n\n // Returns the bearing in degrees between two panos.\n absl::optional<double> GetPanoBearing(const std::string& pano_id1,\n const std::string& pano_id2);\n\n // Returns the current root node.\n const PanoGraphNode Root() const { return root_node_; }\n\n // Returns metadata for the node identified by pano_id. Returns false if the\n // node is not in the graph.\n bool Metadata(const std::string& pano_id, PanoMetadata* metadata) const;\n\n // Returns a map of pano_ids to their neighbors in the current graph.\n std::map<std::string, std::vector<std::string>> GetGraph() const;\n\n private:\n // Returns metadata for a pano in the node tree. Returns nullptr if not found.\n const PanoMetadata* GetNodeMetadata(const std::string& pano_id) const;\n\n // Returns terminal bearings for nodes inside the graph.\n std::map<int, std::vector<TerminalGraphNode>> InteriorTerminalBearings(\n const PanoMetadata& node) const;\n\n // Prefetches a section of graph up to prefetch_depth_ from the new root.\n void PrefetchGraph(const std::string& new_root);\n\n // Builds the node_tree_ of the entire graph or to the required depth.\n enum class GraphRegion { kDepthBounded, kEntire };\n bool BuildGraph(const std::string& root_node_id, GraphRegion graph_region);\n\n // Gets the node with the given id synchronously.\n PanoGraphNode FetchNode(const std::string& node_id);\n\n // Gets the node with the given id asynchronously.\n void PrefetchNode(const std::string& node_id);\n\n // Cancels any ongoing fetch requests.\n void CancelPendingFetches();\n\n const Dataset* dataset_;\n\n // Limits to the depth of graphs built.\n int min_graph_depth_;\n int max_graph_depth_;\n\n // The depth of asynchronous prefetch.\n const int prefetch_depth_;\n\n // The ID of the root node.\n std::string root_id_;\n\n // The root node of the graph.\n PanoGraphNode root_node_;\n\n // Metadata reader and cache.\n std::unique_ptr<MetadataCache> metadata_cache_;\n\n // Counts unfinished prefetch requests.\n std::unique_ptr<absl::BlockingCounter> blockingCounter_;\n\n // Node cache - owns the nodes.\n NodeCache node_cache_;\n\n // Node tree - gets built once when a graph is constructed.\n std::map<std::string, PanoMetadata> node_tree_;\n\n // Neighbors of lead nodes that lie outside the graph.\n std::map<std::string, PanoMetadata> terminal_nodes_;\n\n // Nodes currently being requested - changes every time the root node changes.\n std::vector<std::string> current_subtree_;\n\n // Used for choosing random panos when no root ID is supplied.\n std::mt19937 random_;\n};\n\n} // namespace streetlearn\n\n#endif // THIRD_PARTY_STREETLEARN_ENGINE_PANO_GRAPH_H_\n" }, { "alpha_fraction": 0.6406852602958679, "alphanum_fraction": 0.6493855714797974, "avg_line_length": 33.51702880859375, "blob_id": "f084a59fe0ed27c91c723d7b0c03cf75d01fcc98", "content_id": "a5f2fd3bd43cf353fcb3439c986dc909f5bf200e", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11149, "license_type": "permissive", "max_line_length": 80, "num_lines": 323, "path": "/streetlearn/engine/graph_renderer.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/graph_renderer.h\"\n\n#include <algorithm>\n#include <cmath>\n#include <iterator>\n#include <limits>\n#include <string>\n#include <utility>\n\n#include \"streetlearn/engine/logging.h\"\n#include \"absl/container/node_hash_set.h\"\n#include \"absl/memory/memory.h\"\n#include \"streetlearn/engine/metadata_cache.h\"\n#include \"streetlearn/engine/pano_graph.h\"\n#include \"streetlearn/proto/streetlearn.pb.h\"\n#include \"s2/s1angle.h\"\n\nnamespace streetlearn {\nnamespace {\n\nconstexpr double kMaxLat = 90.0;\nconstexpr double kMaxLon = 180.0;\nconstexpr double kShowNodesLimit = 0.004;\nconstexpr double kViewConeLength = 0.05;\nconstexpr int kNodeRadius = 2;\nconstexpr int kMaxNodes = 5000;\n\n// Extends the bounds to encompass the node.\nvoid AddNodeToBounds(const PanoMetadata& node, double* min_lat, double* max_lat,\n double* min_lng, double* max_lng) {\n double latitude = node.pano.coords().lat();\n *min_lat = std::min(latitude, *min_lat);\n *max_lat = std::max(latitude, *max_lat);\n\n double longitude = node.pano.coords().lng();\n *min_lng = std::min(longitude, *min_lng);\n *max_lng = std::max(longitude, *max_lng);\n}\n\n// Calculates the bounding box around the panos in the graph.\nbool CalculateBounds(const PanoGraph& graph, double* min_lat, double* max_lat,\n double* min_lng, double* max_lng) {\n std::map<std::string, std::vector<std::string>> graph_nodes =\n graph.GetGraph();\n absl::node_hash_set<std::string> already_done;\n for (const auto& node : graph_nodes) {\n PanoMetadata node_data;\n if (!graph.Metadata(node.first, &node_data)) {\n return false;\n }\n AddNodeToBounds(node_data, min_lat, max_lat, min_lng, max_lng);\n already_done.insert(node.first);\n\n for (const auto& neighbor_id : node.second) {\n if (already_done.find(neighbor_id) != already_done.end()) {\n continue;\n }\n PanoMetadata neighbor_data;\n if (!graph.Metadata(neighbor_id, &neighbor_data)) {\n return false;\n }\n AddNodeToBounds(neighbor_data, min_lat, max_lat, min_lng, max_lng);\n already_done.insert(node.first);\n }\n }\n return true;\n}\n\n} // namespace\n\nstd::unique_ptr<GraphRenderer> GraphRenderer::Create(\n const PanoGraph& graph, const Vector2_i& screen_size,\n const std::map<std::string, Color>& highlight) {\n auto graph_renderer =\n absl::WrapUnique(new GraphRenderer(graph, screen_size, highlight));\n if (!graph_renderer->InitRenderer()) {\n LOG(ERROR) << \"Failed to initialize GraphRenderer\";\n return nullptr;\n }\n return graph_renderer;\n}\n\nGraphRenderer::GraphRenderer(const PanoGraph& graph,\n const Vector2_i& screen_size,\n const std::map<std::string, Color>& highlight)\n : screen_size_(screen_size),\n pixel_buffer_(screen_size.x(), screen_size.y()),\n cairo_(pixel_buffer_.pixel(0, 0), screen_size.x(), screen_size.y()),\n pano_graph_(graph),\n image_cache_(screen_size, highlight) {}\n\nbool GraphRenderer::InitRenderer() {\n // Initialise to the extents and calculate bounds.\n double min_lat = kMaxLat;\n double max_lat = -kMaxLat;\n double min_lng = kMaxLon;\n double max_lng = -kMaxLon;\n if (!CalculateBounds(pano_graph_, &min_lat, &max_lat, &min_lng, &max_lng)) {\n return false;\n }\n S2LatLng graph_min = S2LatLng::FromDegrees(min_lat, min_lng);\n S2LatLng graph_max = S2LatLng::FromDegrees(max_lat, max_lng);\n graph_bounds_ = S2LatLngRect(graph_min, graph_max);\n\n if (!image_cache_.InitCache(pano_graph_, graph_bounds_)) {\n return false;\n }\n\n if (!BuildRTree()) {\n return false;\n }\n\n return SetSceneBounds(\"\");\n}\n\nbool GraphRenderer::BuildRTree() {\n std::map<std::string, std::vector<std::string>> graph_nodes =\n pano_graph_.GetGraph();\n if (graph_nodes.empty()) {\n return false;\n }\n nodes_.clear();\n nodes_.reserve(graph_nodes.size());\n\n for (const auto& node : graph_nodes) {\n PanoMetadata node_data;\n if (!pano_graph_.Metadata(node.first, &node_data)) {\n return false;\n }\n\n nodes_.emplace_back(node.first);\n auto node_coords = S2LatLng::FromDegrees(node_data.pano.coords().lat(),\n node_data.pano.coords().lng());\n rtree_.Insert(S2LatLngRect(node_coords, node_coords), nodes_.size() - 1);\n }\n\n return true;\n}\n\nbool GraphRenderer::SetSceneBounds(absl::string_view pano_id) {\n // Center the graph and choose a range in degrees to encompass both bounds.\n double current_zoom = image_cache_.current_zoom();\n double lat_range =\n (graph_bounds_.lat_hi() - graph_bounds_.lat_lo()).degrees() /\n current_zoom;\n double lng_range =\n (graph_bounds_.lng_hi() - graph_bounds_.lng_lo()).degrees() /\n current_zoom;\n double max_range = std::numeric_limits<double>::max();\n if (current_zoom > 1) {\n // If we're zoomed in use a square region on the max dimension.\n max_range = std::max(lat_range, lng_range);\n lat_range = lng_range = max_range * 2;\n }\n\n double lat_centre, lng_centre;\n if (current_zoom > 1 && !pano_id.empty()) {\n PanoMetadata node_data;\n if (!pano_graph_.Metadata(string(pano_id), &node_data)) {\n return false;\n }\n lat_centre = node_data.pano.coords().lat();\n lng_centre = node_data.pano.coords().lng();\n } else {\n lat_centre =\n (graph_bounds_.lat_hi() + graph_bounds_.lat_lo()).degrees() / 2;\n lng_centre =\n (graph_bounds_.lng_hi() + graph_bounds_.lng_lo()).degrees() / 2;\n }\n graph_centre_ = S2LatLng::FromDegrees(lat_centre, lng_centre);\n\n S2LatLng new_min = S2LatLng::FromDegrees(lat_centre - lat_range / 2,\n lng_centre - lng_range / 2);\n S2LatLng new_max = S2LatLng::FromDegrees(lat_centre + lat_range / 2,\n lng_centre + lng_range / 2);\n\n std::vector<int> nodes;\n if (!rtree_.FindIntersecting(S2LatLngRect(new_min, new_max), &nodes)) {\n return false;\n }\n\n current_nodes_.clear();\n if (nodes.size() < kMaxNodes || max_range < kShowNodesLimit) {\n std::transform(nodes.begin(), nodes.end(),\n std::back_inserter(current_nodes_),\n [this](int pos) { return this->nodes_[pos]; });\n }\n\n return true;\n}\n\nbool GraphRenderer::SetZoom(double zoom) {\n image_cache_.SetZoom(zoom);\n return SetSceneBounds(current_pano_);\n}\n\nvoid GraphRenderer::GetPixels(absl::Span<uint8_t> rgb_buffer) const {\n constexpr int kRGBPixelSize = 3;\n constexpr int kBGRAPixelSize = 4;\n CHECK_EQ(rgb_buffer.size(),\n pixel_buffer_.width() * pixel_buffer_.height() * kRGBPixelSize);\n\n absl::Span<const uint8_t> pixel_data = pixel_buffer_.data();\n\n int total_size =\n pixel_buffer_.width() * pixel_buffer_.height() * kRGBPixelSize;\n int pixel_offset = 0;\n int out_offset = 0;\n while (out_offset < total_size) {\n rgb_buffer[out_offset++] = pixel_data[pixel_offset + 2];\n rgb_buffer[out_offset++] = pixel_data[pixel_offset + 1];\n rgb_buffer[out_offset++] = pixel_data[pixel_offset];\n pixel_offset += kBGRAPixelSize;\n }\n}\n\nbool GraphRenderer::RenderScene(\n const std::map<std::string, Color>& pano_id_to_color,\n const absl::optional<Observer>& observer) {\n if (observer && observer->pano_id != current_pano_) {\n current_pano_ = observer->pano_id;\n if (!SetSceneBounds(observer->pano_id)) {\n return false;\n }\n }\n\n // Draw the background of graph edges.\n DrawGraphEdges();\n\n // Draw highlighted nodes.\n for (const auto& node : pano_id_to_color) {\n PanoMetadata metadata;\n if (!pano_graph_.Metadata(node.first, &metadata)) {\n return false;\n }\n Vector2_d coords = MapCoordinates(metadata);\n DrawPosition(coords, node.second);\n }\n\n // Draw the observer cone.\n if (observer) {\n PanoMetadata metadata;\n if (!pano_graph_.Metadata(observer->pano_id, &metadata)) {\n return false;\n }\n DrawObserver(metadata, *observer);\n }\n\n return true;\n}\n\nvoid GraphRenderer::DrawObserver(const PanoMetadata& metadata,\n const Observer& observer) {\n Vector2_d coords = MapCoordinates(metadata);\n double min_bearing = observer.yaw_radians - observer.fov_yaw_radians / 2;\n double max_bearing = observer.yaw_radians + observer.fov_yaw_radians / 2;\n int cone_size = kViewConeLength * screen_size_.x();\n Vector2_d coord1 = {coords.x() + cone_size * sin(min_bearing),\n coords.y() - cone_size * cos(min_bearing)};\n Vector2_d coord2 = {coords.x() + cone_size * sin(max_bearing),\n coords.y() - cone_size * cos(max_bearing)};\n cairo_move_to(cairo_.context(), coord1.x(), coord1.y());\n cairo_line_to(cairo_.context(), coords.x(), coords.y());\n cairo_line_to(cairo_.context(), coord2.x(), coord2.y());\n cairo_close_path(cairo_.context());\n cairo_set_source_rgba(cairo_.context(), observer.color.red,\n observer.color.green, observer.color.blue, 0.5);\n cairo_fill(cairo_.context());\n DrawEdge(coords, coord1, observer.color);\n DrawEdge(coords, coord2, observer.color);\n DrawPosition(coords, observer.color);\n}\n\nvoid GraphRenderer::DrawPosition(const Vector2_d& coords, const Color& color) {\n cairo_set_source_rgb(cairo_.context(), color.red, color.green, color.blue);\n cairo_arc(cairo_.context(), coords.x(), coords.y(), kNodeRadius, 0, 2 * M_PI);\n cairo_fill(cairo_.context());\n}\n\nvoid GraphRenderer::DrawGraphEdges() {\n double current_zoom = image_cache_.current_zoom();\n auto pixels = image_cache_.Pixels(graph_centre_);\n int stride = cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32,\n screen_size_.x() * current_zoom);\n cairo_surface_t* surf = cairo_image_surface_create_for_data(\n pixels.pixel(0, 0), CAIRO_FORMAT_ARGB32, screen_size_.x(),\n screen_size_.y(), stride);\n\n cairo_set_source_surface(cairo_.context(), surf, 0, 0);\n cairo_surface_flush(surf);\n cairo_paint(cairo_.context());\n cairo_surface_destroy(surf);\n}\n\nvoid GraphRenderer::DrawEdge(const Vector2_d& start, const Vector2_d& end,\n const Color& color) {\n cairo_set_source_rgb(cairo_.context(), color.red, color.green, color.blue);\n cairo_set_line_width(cairo_.context(), 0.5);\n cairo_move_to(cairo_.context(), start.x(), start.y());\n cairo_line_to(cairo_.context(), end.x(), end.y());\n cairo_stroke(cairo_.context());\n}\n\nVector2_d GraphRenderer::MapCoordinates(const PanoMetadata& node) {\n return image_cache_.MapToScreen(S2LatLng::FromDegrees(\n node.pano.coords().lat(), node.pano.coords().lng()));\n}\n\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.6482245922088623, "alphanum_fraction": 0.6630883812904358, "avg_line_length": 34.617645263671875, "blob_id": "5e1a4db07316260ecde42b21d3091d167eaae243", "content_id": "cf7780ea61bf5bc6f16f5a66fe26ddd410a16f30", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1211, "license_type": "permissive", "max_line_length": 79, "num_lines": 34, "path": "/streetlearn/engine/bitmap_util.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/bitmap_util.h\"\n\nnamespace streetlearn {\n\nvoid ConvertRGBPackedToPlanar(const uint8_t* rgb_buffer, int width, int height,\n uint8_t* out_buffer) {\n int g_offset = width * height;\n int b_offset = 2 * g_offset;\n for (int y = 0; y < height; ++y) {\n int row_offset = y * width;\n for (int x = 0; x < width; ++x) {\n int index = row_offset + x;\n out_buffer[index] = rgb_buffer[3 * index];\n out_buffer[index + g_offset] = rgb_buffer[3 * index + 1];\n out_buffer[index + b_offset] = rgb_buffer[3 * index + 2];\n }\n }\n}\n\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.7763253450393677, "alphanum_fraction": 0.7886710166931152, "avg_line_length": 36.216217041015625, "blob_id": "dc3c3b688ce215b49a7f055377f8210f2e78d441", "content_id": "6950f7b3f8dc34d0cb0d0b804e31c46146ed832e", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1377, "license_type": "permissive", "max_line_length": 74, "num_lines": 37, "path": "/streetlearn/python/agents/__init__.py", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "# Copyright 2018 Google LLC\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# https://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\"\"\"Helper functions for Importance Weighted Actor-Learner Architectures.\n\nFor details and theory see:\n\n\"IMPALA: Scalable Distributed Deep-RL with\nImportance Weighted Actor-Learner Architectures\"\nby Espeholt, Soyer, Munos et al.\n\nSee https://arxiv.org/abs/1802.01561 for the full paper.\n\nNote that this is a copy of the code previously published by Lasse Espeholt\nunder an Apache license at:\nhttps://github.com/deepmind/scalable_agent\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom streetlearn.python.agents.city_nav_agent import CityNavAgent\nfrom streetlearn.python.agents.goal_nav_agent import GoalNavAgent\nfrom streetlearn.python.agents.locale_pathway import LocalePathway\nfrom streetlearn.python.agents.plain_agent import PlainAgent\n" }, { "alpha_fraction": 0.6595861315727234, "alphanum_fraction": 0.6650678515434265, "avg_line_length": 42.43452453613281, "blob_id": "11d17334b68d15d1355a9c0d9b41b59801b88cf8", "content_id": "7db54e2640bac8104c126e030f3bd70812c1d11f", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7297, "license_type": "permissive", "max_line_length": 80, "num_lines": 168, "path": "/streetlearn/python/agents/city_nav_agent.py", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "# Copyright 2019 Google LLC\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# https://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\"\"\"Implements the goal-driven StreetLearn CityNavAgent with auxiliary losses.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\n\n\nimport tensorflow as tf\nimport sonnet as snt\n\nimport streetlearn.python.agents.goal_nav_agent as goal_nav_agent\nimport streetlearn.python.agents.locale_pathway as locale_pathway\n\n\nclass CityNavAgent(goal_nav_agent.GoalNavAgent):\n \"\"\"Core with A2C/A3C-compatible outputs for simple visual observations.\"\"\"\n\n def __init__(self,\n num_actions,\n observation_names,\n goal_type='target_latlng',\n heading_stop_gradient=False,\n heading_num_hiddens=256,\n heading_num_bins=16,\n xy_stop_gradient=True,\n xy_num_hiddens=256,\n xy_num_bins_lat=32,\n xy_num_bins_lng=32,\n target_xy_stop_gradient=True,\n locale_lstm_num_hiddens=256,\n dropout=0.5,\n locale_bottleneck_num_hiddens=64,\n skip_connection=True,\n policy_lstm_num_hiddens=256,\n feed_action_and_reward=True,\n max_reward=1.0,\n name=\"streetlearn_core\"):\n \"\"\"Initializes an agent core designed to be used with A3C/IMPALA.\n\n Supports a single visual observation tensor and goal instruction tensor and\n outputs a single, scalar discrete action with policy logits and a baseline\n value, as well as the agent heading, XY position and target XY predictions.\n\n Args:\n num_actions: Number of actions available.\n observation_names: String with observation names separated by semi-colon.\n goal_type: String with the name of the target observation field, can be\n `target_latlng` or `target_landmarks`.\n heading_stop_gradient: Boolean for stopping gradient between the LSTM core\n and the heading prediction MLP.\n heading_num_hiddens: Number of hiddens in the heading prediction MLP.\n heading_num_bins: Number of outputs in the heading prediction MLP.\n xy_stop_gradient: Boolean for stopping gradient between the LSTM core\n and the XY position prediction MLP.\n xy_num_hiddens: Number of hiddens in the XY position prediction MLP.\n xy_num_bins_lat: Number of lat outputs in the XY position prediction MLP.\n xy_num_bins_lng: Number of lng outputs in the XY position prediction MLP.\n target_xy_stop_gradient: Boolean for stopping gradient between the LSTM\n core and the target XY position prediction MLP.\n locale_lstm_num_hiddens: Number of hiddens in the locale pathway core.\n dropout: Dropout probabibility after the locale pathway.\n locale_bottleneck_num_hiddens: Number of hiddens in the bottleneck after\n the locale pathway.\n skip_connection: Is there a direct connection from convnet to policy LSTM?\n policy_lstm_num_hiddens: Number of hiddens in the policy LSTM core.\n feed_action_and_reward: If True, the last action (one hot) and last reward\n (scalar) will be concatenated to the torso.\n max_reward: If `feed_action_and_reward` is True, the last reward will\n be clipped to `[-max_reward, max_reward]`. If `max_reward`\n is None, no clipping will be applied. N.B., this is different from\n reward clipping during gradient descent, or reward clipping by the\n environment.\n name: Optional name for the module.\n \"\"\"\n super(CityNavAgent, self).__init__(\n num_actions,\n observation_names,\n goal_type,\n heading_stop_gradient,\n heading_num_hiddens,\n heading_num_bins,\n xy_stop_gradient,\n xy_num_hiddens,\n xy_num_bins_lat,\n xy_num_bins_lng,\n target_xy_stop_gradient,\n dropout,\n lstm_num_hiddens=locale_lstm_num_hiddens,\n feed_action_and_reward=feed_action_and_reward,\n max_reward=max_reward,\n name=name)\n\n # Skip connection for convnet, short-circuiting the global pathway?\n self._skip_connection = skip_connection\n tf.logging.info(\"Convnet skip connection? \" + str(self._skip_connection))\n\n with self._enter_variable_scope():\n # Recurrent policy LSTM core of the agent.\n tf.logging.info('LSTM core with %d hiddens', policy_lstm_num_hiddens)\n self._policy_lstm = tf.contrib.rnn.LSTMBlockCell(policy_lstm_num_hiddens,\n name=\"policy_lstm\")\n # Add an optional bottleneck after the global LSTM\n if locale_bottleneck_num_hiddens > 0:\n self._locale_bottleneck = snt.nets.MLP(\n output_sizes=(locale_bottleneck_num_hiddens,),\n activation=tf.nn.tanh,\n activate_final=True,\n name=\"locale_bottleneck\")\n tf.logging.info(\"Auxiliary global pathway bottleneck with %d hiddens\",\n locale_bottleneck_num_hiddens)\n else:\n self._locale_bottleneck = tf.identity\n\n def initial_state(self, batch_size):\n \"\"\"Returns an initial state with zeros, for a batch size and data type.\"\"\"\n tf.logging.info(\"Initial state consists of the locale pathway and policy \"\n \"LSTM core initial states.\")\n initial_state_list = []\n initial_state_list.append(self._policy_lstm.zero_state(\n batch_size, tf.float32))\n initial_state_list.append(self._locale_pathway.initial_state(batch_size))\n return tuple(initial_state_list)\n\n def _core(self, core_input, core_state):\n \"\"\"Assemble the recurrent core network components.\"\"\"\n (conv_output, action_reward, goal) = core_input\n\n # Get the states\n policy_state, locale_state = core_state\n\n # Locale-specific pathway\n locale_input = conv_output\n locale_output, locale_state = self._locale_pathway((locale_input, goal),\n locale_state)\n (lstm_output, heading_output, xy_output, target_xy_output) = locale_output\n\n # Policy LSTM\n policy_input = self._locale_bottleneck(lstm_output)\n if self._skip_connection:\n policy_input = tf.concat([policy_input, conv_output], axis=1)\n if self._feed_action_and_reward:\n policy_input = tf.concat([policy_input, action_reward], axis=1)\n policy_input = tf.identity(policy_input, name=\"policy_input\")\n\n policy_output, policy_state = self._policy_lstm(policy_input, policy_state)\n\n core_output = (policy_output, heading_output, xy_output, target_xy_output)\n core_state_list = []\n core_state_list.append(policy_state)\n core_state_list.append(locale_state)\n core_state = tuple(core_state_list)\n return core_output, core_state\n" }, { "alpha_fraction": 0.7239551544189453, "alphanum_fraction": 0.7294597625732422, "avg_line_length": 33.0625, "blob_id": "29d8ea80d85d790c9345892061f2d24125f6e75a", "content_id": "d92a4f9be08a6be507eff16d38e5f9ced1091d3a", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4905, "license_type": "permissive", "max_line_length": 80, "num_lines": 144, "path": "/streetlearn/engine/graph_renderer.h", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#ifndef THIRD_PARTY_STREETLEARN_ENGINE_GRAPH_RENDERER_H_\n#define THIRD_PARTY_STREETLEARN_ENGINE_GRAPH_RENDERER_H_\n\n#include <cstdint>\n#include <map>\n#include <memory>\n#include <string>\n#include <vector>\n\n#include \"absl/strings/string_view.h\"\n#include \"absl/types/optional.h\"\n#include \"absl/types/span.h\"\n#include <cairo/cairo.h>\n#include \"streetlearn/engine/cairo_util.h\"\n#include \"streetlearn/engine/color.h\"\n#include \"streetlearn/engine/graph_image_cache.h\"\n#include \"streetlearn/engine/image.h\"\n#include \"streetlearn/engine/metadata_cache.h\"\n#include \"streetlearn/engine/pano_graph.h\"\n#include \"streetlearn/engine/rtree_helper.h\"\n#include \"streetlearn/engine/vector.h\"\n#include \"s2/s2latlng.h\"\n#include \"s2/s2latlng_rect.h\"\n\nnamespace streetlearn {\n\n// Information for drawing an observer view cone. The cone is drawn at a bearing\n// of yaw_radians for an angle fov_yaw_radians in the color indicated.\nstruct Observer {\n std::string pano_id;\n Color color;\n double yaw_radians = 0.0;\n double fov_yaw_radians = 0.0;\n};\n\n// Draws a graphical representation of a pano graph. Nodes are marked as filled\n// circles and connected with edges drawn in grey. The Observer allows the\n// current position and field of view to be shown.\nclass GraphRenderer {\n public:\n static std::unique_ptr<GraphRenderer> Create(\n const PanoGraph& graph, const Vector2_i& screen_size,\n const std::map<std::string, Color>& highlight);\n\n GraphRenderer(const GraphRenderer&) = delete;\n GraphRenderer& operator=(const GraphRenderer&) = delete;\n\n // Sets up the graph bounds and observer cone size.\n bool InitRenderer();\n\n // Renders the scene into an internal screen buffer. Nodes are draw using the\n // default color unless in pano_id_to_color in which case the associated color\n // is used. The graph is drawn to the depth indicated.\n bool RenderScene(const std::map<std::string, Color>& pano_id_to_color,\n const absl::optional<Observer>& observer);\n\n // Sets the current zoom.\n bool SetZoom(double zoom);\n\n // Draws the pixel buffer int `rgb_buffer`. The color order is RGB. Caller of\n // this function has to make sure that the size of `rgb_buffer` exactly\n // matches the size of the image.\n void GetPixels(absl::Span<uint8_t> rgb_buffer) const;\n\n private:\n GraphRenderer(const PanoGraph& graph, const Vector2_i& screen_size,\n const std::map<std::string, Color>& highlight);\n\n // Builds an RTree of graph nodes.\n bool BuildRTree();\n\n // Calculates lat/lon bounds for the scene and the mapping factors to screen\n // coordinates centered on the pano provided.\n bool SetSceneBounds(absl::string_view pano_id);\n\n // Marks the current observer position and orientation using a cone that\n // extends to three neighboring panos.\n void DrawObserver(const PanoMetadata& metadata, const Observer& observer);\n\n // Draws the background of graph edges.\n void DrawGraphEdges();\n\n // Draw an edge between two points. Used for the observer cone.\n void DrawEdge(const Vector2_d& start, const Vector2_d& end,\n const Color& color);\n\n // Draws a filled circle of the given radius in the color provided.\n void DrawPosition(const Vector2_d& coords, const Color& color);\n\n // Transform the node coordinates from lat/lon to screen.\n Vector2_d MapCoordinates(const PanoMetadata& node);\n\n // The output screen size.\n const Vector2_i screen_size_;\n\n // The graph bounds in degrees.\n S2LatLngRect graph_bounds_;\n\n // The user's current location in the graph.\n S2LatLng graph_centre_;\n\n // The pano currently being displayed.\n std::string current_pano_;\n\n // The pixel buffer is used to hold the current render.\n Image4_b pixel_buffer_;\n\n // Wrapper around Cairo surface creation.\n CairoRenderHelper cairo_;\n\n // The graph this object renders.\n const PanoGraph& pano_graph_;\n\n // RTree of point rects for all nodes in the graph, associated to indices in\n // the nodes_ collection below. Keys in the RTree need to be POD types.\n RTree rtree_;\n\n // Pano IDs of the nodes in the RTree.\n std::vector<std::string> nodes_;\n\n // Nodes in the current view.\n std::vector<std::string> current_nodes_;\n\n // Cache of images of the graph edges.\n GraphImageCache image_cache_;\n};\n\n} // namespace streetlearn\n\n#endif // THIRD_PARTY_STREETLEARN_ENGINE_GRAPH_RENDERER_H_\n" }, { "alpha_fraction": 0.6964129209518433, "alphanum_fraction": 0.715660572052002, "avg_line_length": 28.30769157409668, "blob_id": "a18328e88e51e1f19a5d040b87739cfdc38bfcaa", "content_id": "f0c00c1f9f9a3ebb288cf57b81d45a7cef14b552", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1143, "license_type": "permissive", "max_line_length": 75, "num_lines": 39, "path": "/streetlearn/engine/vector.h", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#ifndef THIRD_PARTY_STREETLEARN_ENGINE_VECTOR_H_\n#define THIRD_PARTY_STREETLEARN_ENGINE_VECTOR_H_\n\nnamespace streetlearn {\n\n// Trivially simple 2d vector class with no support for any operations.\ntemplate <class T>\nclass Vector2 {\n public:\n Vector2() : Vector2(0, 0) {}\n Vector2(T x, T y) : data_{x, y} {}\n\n T x() const { return data_[0]; }\n T y() const { return data_[1]; }\n\n private:\n T data_[2];\n};\n\nusing Vector2_d = Vector2<double>;\nusing Vector2_i = Vector2<int>;\n\n}; // namespace streetlearn\n\n#endif // THIRD_PARTY_STREETLEARN_ENGINE_VECTOR_H_\n" }, { "alpha_fraction": 0.6833030581474304, "alphanum_fraction": 0.6851179599761963, "avg_line_length": 35.733333587646484, "blob_id": "eb932a498ad96c5d6b3b4615e9f0124ccb9d1927", "content_id": "43e3a8940829724dc4beb0d2eaf5c5fbb6a65e62", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4408, "license_type": "permissive", "max_line_length": 80, "num_lines": 120, "path": "/streetlearn/engine/node_cache.h", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#ifndef STREETLEARN_NODE_CACHE_H_\n#define STREETLEARN_NODE_CACHE_H_\n\n#include <cstddef>\n#include <functional>\n#include <list>\n#include <memory>\n#include <unordered_map>\n\n#include \"absl/base/thread_annotations.h\"\n#include \"absl/container/flat_hash_map.h\"\n#include \"absl/strings/string_view.h\"\n#include \"absl/synchronization/mutex.h\"\n#include \"streetlearn/engine/pano_fetcher.h\"\n#include \"streetlearn/engine/pano_graph_node.h\"\n\nnamespace streetlearn {\n\n// A Least Recently Used (LRU) cache for PanoGraphNodes. It uses a PanoFetcher\n// to fetch nodes from disk and uses a callback mechanism to inform the callee\n// when nodes are available. It works like this:\n//\n// +-------+ +---------+\n// Lookup | | Fetch | |\n// ---------> | LRU | ---------> | Fetch |\n// <--------- | Cache | <--------- | Routine |\n// Callback | | Callback | |\n// +-------+ +---------+\n//\n// The cache reads panos from a single directory passed to the constructor. All\n// lookups and insertions are thread safe, but the copies of the callbacks\n// passed to Lookup are called concurrently, the most recently added first.\nclass NodeCache {\n public:\n // Type of the client callback.\n using LoadCallback = std::function<void(const PanoGraphNode*)>;\n\n // The Cache will use thread_count threads for fetching panos from the dataset\n // and store up to max_size pano nodes.\n NodeCache(const Dataset* dataset, int thread_count, std::size_t max_size);\n\n ~NodeCache() { CancelPendingFetches(); }\n\n // Looks up a pano node and runs the callback when it is available. Returns\n // true if the pano is already in the cache and available immediately and\n // false if the fetcher has been used.\n bool Lookup(const std::string& pano_id, LoadCallback callback)\n LOCKS_EXCLUDED(mutex_);\n\n // Called by the fetcher when panos are loaded.\n void Insert(const std::string& pano_id,\n std::shared_ptr<const PanoGraphNode> node) LOCKS_EXCLUDED(mutex_);\n\n // Cancel any outstanding fetches.\n void CancelPendingFetches() LOCKS_EXCLUDED(mutex_);\n\n private:\n // Updates the cache with the give node and returns any callbacks required.\n ABSL_MUST_USE_RESULT\n std::list<LoadCallback> InsertImpl(const std::string& pano_id,\n std::shared_ptr<const PanoGraphNode> node)\n LOCKS_EXCLUDED(mutex_);\n\n // Remove and return any callbacks that are required for the given pano.\n ABSL_MUST_USE_RESULT\n std::list<LoadCallback> GetAndClearCallbacks(const std::string& pano_id);\n\n // Run the callbacks provided.\n void RunCallbacks(const std::list<LoadCallback>& callbacks,\n const std::shared_ptr<const PanoGraphNode>& node)\n LOCKS_EXCLUDED(mutex_);\n\n // An entry in the LRU list the cache maintains.\n struct CacheEntry {\n std::string pano_id;\n std::shared_ptr<const PanoGraphNode> pano_node;\n\n CacheEntry(const std::string& id, std::shared_ptr<const PanoGraphNode> node)\n : pano_id(id), pano_node(std::move(node)) {}\n };\n\n // Insertions/lookups will happen from multiple fetch threads, so require\n // this mutex.\n absl::Mutex mutex_;\n\n // Store cache entries. The list is sorted by recency of entry lookups, with\n // the most recent entry at the front.\n std::list<CacheEntry> cache_list_ GUARDED_BY(mutex_);\n\n // Store lookup from key to entry in the cache list.\n absl::flat_hash_map<std::string, std::list<CacheEntry>::iterator>\n cache_lookup_ GUARDED_BY(mutex_);\n\n // Client callbacks when nodes become available.\n absl::flat_hash_map<std::string, std::list<LoadCallback>> callbacks_;\n\n // Maximum size of the cache.\n const std::size_t max_size_;\n\n // The pano fetcher\n PanoFetcher pano_fetcher_;\n};\n\n} // namespace streetlearn\n\n#endif // STREETLEARN_NODE_CACHE_H_\n" }, { "alpha_fraction": 0.7109136581420898, "alphanum_fraction": 0.7492363452911377, "avg_line_length": 35.37373733520508, "blob_id": "18697aaab8e3310fd8bd202084e1a5d68fe4090b", "content_id": "e7c63fbb54a2c69f5d01caa11586311853bc4e03", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3601, "license_type": "permissive", "max_line_length": 80, "num_lines": 99, "path": "/streetlearn/engine/test_dataset.h", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#ifndef THIRD_PARTY_STREETLEARN_ENGINE_TEST_DATASET_H_\n#define THIRD_PARTY_STREETLEARN_ENGINE_TEST_DATASET_H_\n\n#include <cstdint>\n#include <string>\n#include <vector>\n\n#include \"streetlearn/engine/image.h\"\n#include \"streetlearn/proto/streetlearn.pb.h\"\n\nnamespace streetlearn {\n\n// This class is used in tests to generate a test dataset existing of kPanoCount\n// panos that are connected and are on a line.\nclass TestDataset {\n public:\n static constexpr char kStreetName[] = \"Pancras Square\";\n static constexpr char kRegion[] = \"London, England\";\n static constexpr char kFullAddress[] = \"Pancras Square, London, England\";\n static constexpr char kDescription[] = \"Sample Pano\";\n static constexpr char kCountryCode[] = \"GB\";\n static constexpr char kPanoDate[] = \"12/12/2012\";\n static constexpr float kAltitude = 70.10226140993;\n static constexpr float kLatitude = 51.530589522519;\n static constexpr float kLongitude = -0.12275015773299;\n\n static constexpr float kIncrement = 0.001;\n static constexpr float kRollDegrees = 3.335879;\n static constexpr float kPitchDegrees = 12.23486;\n static constexpr float kHeadingDegrees = -9.98770;\n static constexpr float kMinLatitude = 51.5315895;\n static constexpr float kMinLongitude = -0.1217502;\n static constexpr float kMaxLatitude = 51.5405884;\n static constexpr float kMaxLongitude = -0.1127502;\n\n static constexpr int kImageWidth = 64;\n static constexpr int kImageHeight = 48;\n static constexpr int kImageDepth = 3;\n\n static constexpr int kPanoCount = 10;\n\n static constexpr int kNeighborCount = 2;\n static constexpr int kMinGraphDepth = 5;\n static constexpr int kMaxGraphDepth = 10;\n static constexpr int kMaxNeighborDepth = 1;\n\n static constexpr int kMaxCacheSize = 8;\n\n // Create a test dataset of kPanoCount panos on a line with IDs 1..kPanoCount.\n static bool Generate();\n\n // Return the path where the generated test dataset is.\n static std::string GetPath();\n\n // Create an invalid dataset.\n static bool GenerateInvalid();\n\n // Return the path where the invalid dataset is.\n static std::string GetInvalidDatasetPath();\n\n // Generate a test pano filled with the data defined in the constants.\n static Pano GeneratePano(int pano_id);\n\n // Generate a test pano image of size (kImageWidth, kImageHeight). The pixels\n // of the test image are set to RGB values of 16, 32, 64 respectively.\n static Image3_b GenerateTestImage();\n\n // Generate a test pano image but return a compressed (PNG) buffer.\n static std::vector<uint8_t> GenerateCompressedTestImage();\n\n // Returns the pano IDs in the test data.\n static std::vector<std::string> GetPanoIDs();\n\n private:\n // Add neighbors to the pano. Neighbors are the previous and next panos on the\n // line if they exist.\n static void AddNeighbors(int pano_id, Pano* pano);\n\n // Add neigbor metadata to the connection.\n static void AddNeighborMetadata(int pano_id, PanoConnection* connection);\n};\n\n} // namespace streetlearn\n\n#endif // THIRD_PARTY_STREETLEARN_ENGINE_TEST_DATASET_H_\n" }, { "alpha_fraction": 0.6957598924636841, "alphanum_fraction": 0.7022301554679871, "avg_line_length": 31.868778228759766, "blob_id": "9bdab57daea4902c8fb5e2d134ce311090a38f0c", "content_id": "f7429df8fa6cf6d5b1938feaf7b018266e204ada", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7264, "license_type": "permissive", "max_line_length": 80, "num_lines": 221, "path": "/streetlearn/engine/test_dataset.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/test_dataset.h\"\n#include \"gtest/gtest.h\"\n#include <opencv/cv.h>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include \"absl/memory/memory.h\"\n#include \"absl/strings/str_cat.h\"\n#include \"leveldb/db.h\"\n#include \"leveldb/options.h\"\n#include \"streetlearn/engine/dataset.h\"\n\nnamespace streetlearn {\n\nconstexpr char TestDataset::kStreetName[];\nconstexpr char TestDataset::kRegion[];\nconstexpr char TestDataset::kFullAddress[];\nconstexpr char TestDataset::kDescription[];\nconstexpr char TestDataset::kCountryCode[];\nconstexpr char TestDataset::kPanoDate[];\nconstexpr float TestDataset::kAltitude;\nconstexpr float TestDataset::kLatitude;\nconstexpr float TestDataset::kLongitude;\nconstexpr float TestDataset::kIncrement;\nconstexpr float TestDataset::kRollDegrees;\nconstexpr float TestDataset::kPitchDegrees;\nconstexpr float TestDataset::kHeadingDegrees;\nconstexpr float TestDataset::kMinLatitude;\nconstexpr float TestDataset::kMinLongitude;\nconstexpr float TestDataset::kMaxLatitude;\nconstexpr float TestDataset::kMaxLongitude;\nconstexpr int TestDataset::kImageWidth;\nconstexpr int TestDataset::kImageHeight;\nconstexpr int TestDataset::kImageDepth;\nconstexpr int TestDataset::kPanoCount;\nconstexpr int TestDataset::kNeighborCount;\nconstexpr int TestDataset::kMinGraphDepth;\nconstexpr int TestDataset::kMaxGraphDepth;\nconstexpr int TestDataset::kMaxNeighborDepth;\nconstexpr int TestDataset::kMaxCacheSize;\n\nPano TestDataset::GeneratePano(int pano_id) {\n Pano pano;\n pano.set_id(absl::StrCat(pano_id));\n pano.set_street_name(kStreetName);\n pano.set_full_address(kFullAddress);\n pano.set_region(kRegion);\n pano.set_country_code(kCountryCode);\n pano.set_pano_date(kPanoDate);\n pano.set_alt(kAltitude);\n pano.set_roll_deg(kRollDegrees);\n pano.set_pitch_deg(kPitchDegrees);\n pano.set_heading_deg(kHeadingDegrees);\n pano.set_pano_date(kPanoDate);\n LatLng* coords = pano.mutable_coords();\n // Place the panos in a line.\n coords->set_lat(kLatitude + kIncrement * pano_id);\n coords->set_lng(kLongitude + kIncrement * pano_id);\n return pano;\n}\n\nstd::vector<uint8_t> TestDataset::GenerateCompressedTestImage() {\n auto image = GenerateTestImage();\n cv::Mat mat(image.height(), image.width(), CV_8UC3,\n const_cast<uint8_t*>(image.pixel(0, 0)));\n // Convert to BGR as the defaul OpenCV format is BGR.\n cv::Mat bgr_mat;\n cvtColor(mat, bgr_mat, CV_RGB2BGR);\n\n std::vector<uint8_t> compressed_image;\n cv::imencode(\".png\", bgr_mat, compressed_image);\n return compressed_image;\n}\n\n// The panos are numbered 1-10 and arranged in a line, each connecting to both\n// its immediate neighbors, except the ends.\nvoid TestDataset::AddNeighbors(int pano_id, Pano* pano) {\n if (pano_id < kPanoCount) {\n int next = pano_id + 1;\n PanoNeighbor* neighbor = pano->add_neighbor();\n neighbor->set_id(absl::StrCat(next));\n neighbor->set_pano_date(kPanoDate);\n LatLng* coords = neighbor->mutable_coords();\n coords->set_lat(kLatitude + kIncrement * next);\n coords->set_lng(kLongitude + kIncrement * next);\n }\n\n if (pano_id > 1) {\n int previous = pano_id - 1;\n PanoNeighbor* neighbor = pano->add_neighbor();\n neighbor->set_id(absl::StrCat(previous));\n neighbor->set_pano_date(kPanoDate);\n LatLng* coords = neighbor->mutable_coords();\n coords->set_lat(kLatitude + kIncrement * previous);\n coords->set_lng(kLongitude + kIncrement * previous);\n }\n}\n\n// The panos are numbered 1-10 and arranged in a line, each connecting to both\n// its immediate neighbors except the ends.\nvoid TestDataset::AddNeighborMetadata(int pano_id, PanoConnection* connection) {\n connection->set_subgraph_size(kPanoCount);\n connection->set_id(absl::StrCat(pano_id));\n\n if (pano_id < kPanoCount) {\n auto* neighbor = connection->add_neighbor();\n *neighbor = absl::StrCat(pano_id + 1);\n }\n\n if (pano_id > 1) {\n auto* neighbor = connection->add_neighbor();\n *neighbor = absl::StrCat(pano_id - 1);\n }\n}\n\nbool TestDataset::Generate() {\n leveldb::DB* db_ptr;\n leveldb::Options options;\n options.create_if_missing = true;\n\n leveldb::Status leveldb_status =\n leveldb::DB::Open(options, GetPath(), &db_ptr);\n if (!leveldb_status.ok()) {\n LOG(ERROR) << \"Cannot initialize dataset: \" << leveldb_status.ToString();\n return false;\n }\n\n auto db = absl::WrapUnique<leveldb::DB>(db_ptr);\n const auto compressed_pano_image = GenerateCompressedTestImage();\n\n // Create panos.\n for (int i = 1; i <= kPanoCount; ++i) {\n Pano pano = GeneratePano(i);\n AddNeighbors(i, &pano);\n pano.mutable_compressed_image()->assign(compressed_pano_image.begin(),\n compressed_pano_image.end());\n\n leveldb_status =\n db->Put(leveldb::WriteOptions(), pano.id(), pano.SerializeAsString());\n if (!leveldb_status.ok()) {\n return false;\n }\n }\n\n // Create connectivity graph.\n StreetLearnGraph metadata;\n metadata.mutable_min_coords()->set_lat(kMinLatitude);\n metadata.mutable_min_coords()->set_lng(kMinLongitude);\n metadata.mutable_max_coords()->set_lat(kMaxLatitude);\n metadata.mutable_max_coords()->set_lng(kMaxLongitude);\n\n for (int i = 1; i <= kPanoCount; ++i) {\n PanoConnection* connection = metadata.add_connection();\n *metadata.add_pano() = GeneratePano(i);\n AddNeighborMetadata(i, connection);\n }\n\n leveldb_status = db->Put(leveldb::WriteOptions(), Dataset::kGraphKey,\n metadata.SerializeAsString());\n return leveldb_status.ok();\n}\n\nstd::string TestDataset::GetPath() {\n return ::testing::TempDir() + \"/streetlearn_test_dataset\";\n}\n\nbool TestDataset::GenerateInvalid() {\n leveldb::DB* db_ptr;\n leveldb::Options options;\n options.create_if_missing = true;\n\n auto status = leveldb::DB::Open(options, GetInvalidDatasetPath(), &db_ptr);\n if (!status.ok()) {\n LOG(ERROR) << \"Cannot initialize dataset: \" << status.ToString();\n return false;\n }\n\n auto db = absl::WrapUnique<leveldb::DB>(db_ptr);\n return true;\n}\n\nstd::string TestDataset::GetInvalidDatasetPath() {\n return ::testing::TempDir() + \"/streetlearn_invalid_dataset\";\n}\n\nImage3_b TestDataset::GenerateTestImage() {\n Image3_b test_image(kImageWidth, kImageHeight);\n for (int x = 0; x < kImageWidth; ++x) {\n for (int y = 0; y < kImageHeight; ++y) {\n auto pixel = test_image.pixel(x, y);\n pixel[0] = 16;\n pixel[1] = 32;\n pixel[2] = 64;\n }\n }\n\n return test_image;\n}\n\nstd::vector<std::string> TestDataset::GetPanoIDs() {\n std::vector<std::string> pano_ids(kPanoCount);\n for (int i = 0; i < kPanoCount; ++i) {\n pano_ids[i] = absl::StrCat(i + 1);\n }\n return pano_ids;\n}\n\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.6529792547225952, "alphanum_fraction": 0.65667325258255, "avg_line_length": 35.55381774902344, "blob_id": "e584e02d5b419736ee0ba21c781a1e97ff006bc2", "content_id": "945dae35bc8df3ced0dee3b072d93bf8176dec5d", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18679, "license_type": "permissive", "max_line_length": 80, "num_lines": 511, "path": "/streetlearn/python/environment/instructions_base.py", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "# Copyright 2019 Google LLC.\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\"\"\"StreetLearn basic level for the instruction-following task.\n\nIn this environment, the agent receives a reward for every waypoint it hits\nas well as a larger reward for reaching the final goal.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nfrom absl import logging\nimport numpy as np\n\nfrom streetlearn.python.environment import coin_game\nfrom streetlearn.python.environment import thumbnail_helper\n\nTrajectoryStep = collections.namedtuple(\n 'TrajectoryStep',\n 'waypoint_index pano lat lng heading_deg length instruction')\nTrajectory = collections.namedtuple('Trajectory', 'steps goal')\n\n\nclass InstructionsBase(coin_game.CoinGame):\n \"\"\"Instruction following game.\"\"\"\n\n def __init__(self, config):\n \"\"\"Creates an instance of the StreetLearn level.\n\n Args:\n config: config dict of various settings.\n \"\"\"\n super(InstructionsBase, self).__init__(config)\n\n self._colors.update({\n 'goal': config['color_for_goal'],\n 'waypoint': config['color_for_waypoint'],\n 'shortest_path': config['color_for_shortest_path'],\n })\n self._reward_at_waypoint = config['reward_at_waypoint']\n self._reward_at_goal = config['reward_at_goal']\n self._instruction_file = config['instruction_file']\n self._num_instructions = config['num_instructions']\n self._max_instructions = config['max_instructions']\n self._thumbnail_helper = thumbnail_helper.ThumbnailHelper()\n self._thumbnails = np.zeros(\n [self._max_instructions + 1, 3, config['width'], config['height']],\n dtype=np.uint8)\n logging.info('Using %d instructions', self._num_instructions)\n logging.info('Padding to %d instructions', self._max_instructions)\n self._instructions = []\n self._step_counter = 1\n self._reward_pano_id_list = {}\n self._reward_pano_id_to_family = {}\n self._reward_family = {}\n self._pano_id_to_color = {}\n self._goal_pano_id = None\n self._trajectory = None\n self._show_shortest_path = config['show_shortest_path']\n self._calculate_ground_truth = config['calculate_ground_truth']\n\n # Ground truth direction (for imitation learning agents).\n self._gt_direction = 0\n\n # Trajectories\n self._num_trajectories = 0\n self._trajectory_data = []\n self._loaded_trajectories = False\n\n def _load_trajectories(self):\n \"\"\"Load the trajectories into memory.\"\"\"\n logging.info('Loading trajectories from %s', self._instruction_file)\n steps = []\n current_trajectory_index = 0\n with open(self._instruction_file, 'r') as f:\n for line in f:\n tokens = line.strip().split('\\t')\n trajectory_index = int(tokens[0])\n waypoint_index = int(tokens[1])\n lat = float(tokens[2])\n lng = float(tokens[3])\n heading_deg = float(tokens[4])\n length = float(tokens[5])\n pano_id = tokens[6]\n instruction = tokens[7]\n step = TrajectoryStep(\n waypoint_index=waypoint_index,\n pano=pano_id,\n lat=lat,\n lng=lng,\n heading_deg=heading_deg,\n length=length,\n instruction=instruction)\n if trajectory_index != current_trajectory_index:\n self._add_trajectory(steps)\n steps = []\n current_trajectory_index = trajectory_index\n steps.append(step)\n self._add_trajectory(steps)\n\n logging.info('Loaded %d trajectories', self._num_trajectories)\n self._loaded_trajectories = True\n\n def _add_trajectory(self, steps):\n \"\"\"Store a trajectory.\"\"\"\n num_steps = len(steps)\n if num_steps > 0:\n\n # Separate goal from waypoints.\n goal = steps[num_steps-1]\n steps = steps[:(num_steps-1)]\n\n # Store the trajectory in a hashtable.\n trajectory = Trajectory(steps=steps, goal=goal)\n self._trajectory_data.append(trajectory)\n self._num_trajectories += 1\n if self._num_trajectories % 1000 == 0:\n logging.info('Stored %d trajectories', self._num_trajectories)\n\n def on_reset(self, streetlearn):\n \"\"\"Gets called after StreetLearn:reset().\n\n Selects a random trajectory, extracts the instructions and panos at goal and\n waypoints, computes the shortest paths between each start, each waypoint and\n the goal.\n\n Args:\n streetlearn: a streetlearn instance.\n Returns:\n A newly populated pano_id_to_color dictionary.\n \"\"\"\n # Initialise graph of rewards and colors with coins\n super(InstructionsBase, self).on_reset(streetlearn)\n\n self._current_step = 0\n self._step_counter = 1\n self._step_by_pano = {}\n self._pano_by_step = {}\n\n self._reward_pano_id_list = {}\n self._reward_pano_id_to_family = {}\n self._reward_family = {}\n self._pano_id_to_color = {}\n self._num_steps_this_goal = 0\n\n # Randomly sample a trajectory.\n if self._loaded_trajectories == False:\n self._load_trajectories()\n trajectory = self._sample_trajectory(streetlearn)\n\n start = max(len(trajectory.steps) - self._num_instructions, 0)\n logging.info('Trajectory of length %d (max %d), starting at %d',\n len(trajectory.steps), self._num_instructions, start)\n num_steps = 0\n start_pano_id = None\n self._instructions = []\n self._thumbnails[:] = 0\n pano_list = []\n\n for step in trajectory.steps[start:]:\n pano_id = step.pano\n pano_list.append(pano_id)\n\n # Even if we do not take rewards for waypoints, we store them to keep\n # track of the agent's position along the trajectory.\n if num_steps == 0:\n start_pano_id = pano_id\n if num_steps > 0:\n self._add_reward_to_pano(pano_id, self._reward_at_waypoint,\n self._colors['waypoint'], streetlearn)\n self._instructions.append(step.instruction)\n\n # Fetch the thumbnail for the current step of the trajectory.\n step_thumbnail = self._thumbnail_helper.get_thumbnail(\n streetlearn, pano_id, step.heading_deg)\n if step_thumbnail is not None:\n self._thumbnails[num_steps] = step_thumbnail\n\n if self._reward_at_waypoint:\n logging.info('Waypoint %d at pano %s, yields reward of %f',\n num_steps, pano_id, self._reward_at_waypoint)\n else:\n logging.info('Waypoint %d at pano %s', num_steps, pano_id)\n num_steps += 1\n\n # Set the goal.\n self._goal_pano_id = trajectory.goal.pano\n self._add_reward_to_pano(self._goal_pano_id, self._reward_at_goal,\n self._colors['goal'], streetlearn)\n pano_list.append(self._goal_pano_id)\n\n # Store the previously defined coin rewards and colours\n for pano_id in self._coin_pano_id_set:\n self._add_coin_reward_to_pano(pano_id)\n\n # Add goal pano thumbnail at the end.\n goal_thumbnail = self._thumbnail_helper.get_thumbnail(\n streetlearn, self._goal_pano_id, trajectory.goal.heading_deg)\n if goal_thumbnail is not None:\n self._thumbnails[num_steps] = goal_thumbnail\n\n # Move and rotate player into start position.\n streetlearn.engine.SetPosition(start_pano_id)\n streetlearn.currentpano_id = start_pano_id\n streetlearn.engine.RotateObserver(trajectory.steps[start].heading_deg, 0)\n\n logging.info('From: %s (%f, %f), To: %s', start_pano_id,\n trajectory.steps[start].lat,\n trajectory.steps[start].lng, self._goal_pano_id)\n logging.info('Trajectory with %d waypoints (goal included)', num_steps)\n\n if self._calculate_ground_truth or self._show_shortest_path:\n # Update the shortest path to the goal or first waypoint.\n self._update_shortest_path(streetlearn, start_pano_id)\n if self._show_shortest_path:\n # Use the computed shortest path to color the panos.\n self._color_shortest_path(streetlearn)\n # By default, direction is forward.\n self._gt_direction = 0\n\n return self._pano_id_to_color\n\n def _update_shortest_path(self, streetlearn, start_pano_id):\n \"\"\"Update the target of the shortest paths and color panos along that path.\n\n Args:\n streetlearn: the streetlearn environment.\n start_pano_id: a string for the current pano ID, for computing the optimal\n path.\n \"\"\"\n step = self._current_step + 1\n logging.info(self._pano_by_step)\n logging.info('Reached step %d', step)\n if step in self._pano_by_step:\n target_pano_id = self._pano_by_step[step]\n self._shortest_path, num_panos = self._shortest_paths(\n streetlearn, target_pano_id, start_pano_id)\n logging.info('Shortest path from %s to waypoint/goal %s covers %d panos',\n start_pano_id, target_pano_id, num_panos)\n\n def _color_shortest_path(self, streetlearn):\n \"\"\"Color panos along the current shortest path to the current target.\n\n Args:\n streetlearn: the streetlearn environment.\n \"\"\"\n for pano_id in self._shortest_path:\n self._pano_id_to_color.setdefault(pano_id, self._colors['shortest_path'])\n\n @property\n def trajectory(self):\n return self._trajectory\n\n def _sample_trajectory(self, streetlearn):\n \"\"\"Sample a trajectory.\n\n Args:\n streetlearn: Streetlearn instance.\n Returns:\n trajectory object.\n \"\"\"\n trajectory_index = np.random.randint(len(self._trajectory_data))\n self._trajectory = self._trajectory_data[trajectory_index]\n return self.trajectory\n\n def _add_reward_to_pano(self, pano_id, reward, color, streetlearn):\n \"\"\"Add reward to a pano and all its neighbours.\n\n Args:\n pano_id: centroid pano id.\n reward: Amount of reward to attach to this and neighbouring panos.\n color: Color for the goal in the minimap.\n streetlearn: Streetlearn instance\n \"\"\"\n # If this already has a reward indirectly through a neighbour, undo that.\n if pano_id in self._reward_pano_id_list:\n if self._reward_pano_id_to_family[pano_id] == pano_id:\n # This was already made a reward field; update reward only.\n for neighbor in self._reward_family[pano_id]:\n # Replace reward and colour.\n self._reward_pano_id_list[neighbor] = reward\n self._pano_id_to_color[neighbor] = color\n return\n else:\n # This was previously an indirect reward field.\n # Remove from other family,: continue with default operation.\n self._reward_family[self._reward_pano_id_to_family[pano_id]].remove(\n pano_id)\n self._reward_pano_id_to_family[pano_id] = None\n\n # Define family around this id.\n self._add_family(pano_id, streetlearn)\n\n # Add reward and colour to family and links into family.\n for neighbor in self._reward_family[pano_id]:\n self._reward_pano_id_list[neighbor] = reward\n self._reward_pano_id_to_family[neighbor] = pano_id\n self._pano_id_to_color[neighbor] = color\n\n def _add_coin_reward_to_pano(self, pano_id):\n \"\"\"Add coin reward to a pano, but only if that pano has no reward yet.\n\n Args:\n pano_id: centroid pano id.\n \"\"\"\n if pano_id not in self._reward_pano_id_list:\n self._reward_pano_id_list[pano_id] = self._reward_per_coin\n self._reward_pano_id_to_family[pano_id] = pano_id\n self._reward_family[pano_id] = {pano_id}\n self._pano_id_to_color[pano_id] = self._colors['coin']\n\n def _add_family(self, pano_id, streetlearn):\n \"\"\"Add all neighbours of a pano to a list (family) of pano IDs.\n\n Args:\n pano_id: centroid pano id.\n streetlearn: streetlearn graph for establishing neighbours.\n \"\"\"\n # If the pano is already part of a reward, do not mess with it.\n if pano_id in self._reward_family:\n return\n\n # Assign each waypoint with a pano group counter. Used when adding waypoints\n # one by one, in the order of the trajectory.\n if pano_id not in self._step_by_pano:\n logging.info('Added waypoint %d at pano %s', self._step_counter, pano_id)\n self._step_by_pano[pano_id] = self._step_counter\n self._pano_by_step[self._step_counter] = pano_id\n self._step_counter += 1\n\n # Add the same logic to the immediate neighbours of the pano.\n self._reward_family[pano_id] = set({pano_id})\n pano_metadata = streetlearn.engine.GetMetadata(pano_id)\n for neighbor in pano_metadata.neighbors:\n if neighbor.id not in self._reward_pano_id_to_family:\n self._reward_pano_id_to_family[neighbor.id] = pano_id\n self._reward_family[pano_id].add(neighbor.id)\n\n def _check_reward(self, pano_id, streetlearn):\n \"\"\"Check what reward the current pano yields, based on instructions.\n\n Args:\n pano_id: centroid pano id.\n streetlearn: streetlearn graph for establishing neighbours.\n Returns:\n The reward for the current step.\n \"\"\"\n reward = 0\n self._reached_goal = False\n\n # Check if pano ID is in the list of pano IDs that yield rewards.\n if pano_id in self._reward_pano_id_list:\n reward = self._reward_pano_id_list[pano_id]\n family_id = self._reward_pano_id_to_family[pano_id]\n\n # If the family_id matches the goal, we have finished the trajectory.\n previous_step = self._current_step\n self._current_step = self._step_by_pano[family_id]\n if family_id == self._goal_pano_id:\n self._reached_goal = True\n logging.info('%d: Completed level', streetlearn.frame_count)\n # It appears the level does not end immediately, so we need to reset the\n # step counter manually at this stage to prevent overflow.\n self._current_step = 0\n else:\n logging.info('%d: Moved from %d to %d', streetlearn.frame_count,\n previous_step, self._current_step)\n if self._calculate_ground_truth or self._show_shortest_path:\n # Update the shortest path to the goal or next waypoint.\n self._update_shortest_path(streetlearn, pano_id)\n if self._show_shortest_path:\n # Use the computed shortest path to color the panos.\n self._color_shortest_path(streetlearn)\n\n for i in self._reward_family[family_id]:\n del self._reward_pano_id_list[i]\n del self._reward_pano_id_to_family[i]\n del self._pano_id_to_color[i]\n del self._reward_family[family_id]\n\n # The value of the reward determines if the goal was reached and the\n # episode can now end.\n logging.info('%d: Picked up reward of %f at pano %s.',\n streetlearn.frame_count, reward, pano_id)\n\n # Add optional coin rewards.\n if pano_id in self._coin_pano_id_set:\n reward += self._reward_per_coin\n self._coin_pano_id_set.remove(pano_id)\n\n return reward\n\n def get_reward(self, streetlearn):\n \"\"\"Looks at current_pano_id and collects any reward found there.\n\n Args:\n streetlearn: the streetlearn environment.\n Returns:\n reward: the reward from the last step.\n \"\"\"\n # Calculate coin, waypoint and goal rewards, determine if end of episode.\n current_pano_id = streetlearn.current_pano_id\n reward = self._check_reward(current_pano_id, streetlearn)\n self._num_steps_this_goal += 1\n return reward\n\n def get_info(self, streetlearn):\n \"\"\"\"Returns current information about the state of the environment.\n\n Args:\n streetlearn: a StreetLearn instance.\n Returns:\n info: information from the environment at the last step.\n \"\"\"\n info = super(InstructionsBase, self).get_info(streetlearn)\n info['num_steps_this_goal'] = self._num_steps_this_goal\n info['current_step'] = self._current_step\n info['current_goal_id'] = self._goal_pano_id\n info['distance_to_goal'] = streetlearn.engine.GetPanoDistance(\n streetlearn.current_pano_id, self._goal_pano_id)\n info['reward_current_goal'] = self._reward_at_goal\n if self._calculate_ground_truth:\n current_pano_id = streetlearn.current_pano_id\n next_pano_id = self._panos_to_goal[current_pano_id]\n info['next_pano_id'] = next_pano_id\n if next_pano_id:\n bearing_to_next_pano = streetlearn.engine.GetPanoBearing(\n current_pano_id, next_pano_id) - streetlearn.engine.GetYaw()\n else:\n bearing_to_next_pano = 0\n info['bearing_to_next_pano'] = (bearing_to_next_pano + 180) % 360 - 180\n return info\n\n def done(self):\n \"\"\"Returns a flag indicating the end of the current episode.\n\n This game ends only at the end of the episode or if the goal is reached.\n \"\"\"\n if self._reached_goal:\n self._reached_goal = False\n return True\n else:\n return False\n\n def thumbnails(self):\n \"\"\"Returns extra observation thumbnails.\n\n Args:\n include_goal_thumb: Bool (default: False) of whether we add the goal.\n Returns:\n thumbnails: Thumbnails array of shape (batch_size, 3, h, w)\n \"\"\"\n return self._thumbnails\n\n def instructions(self):\n \"\"\"Returns instructions.\n\n Args:\n None\n Returns:\n instructions: string containing game specific instructions.\n \"\"\"\n return self._instructions\n\n @property\n def goal_id(self):\n \"\"\"Returns the id of the goal Pano.\"\"\"\n return self._goal_pano_id\n\n def on_step(self, streetlearn):\n \"\"\"Update the ground truth direction to take and the set of touched panos.\n\n Args:\n streetlearn: the streetlearn environment.\n \"\"\"\n super(InstructionsBase, self).on_step(streetlearn)\n\n if self._calculate_ground_truth:\n # streetlearn.current_pano_id is not always updated.\n current_pano_id = streetlearn.engine.GetPano().id\n # What is the next pano and what is the direction to the pano?\n next_pano_id = self._panos_to_goal[current_pano_id]\n if next_pano_id:\n yaw = streetlearn.engine.GetYaw()\n bearing = streetlearn.engine.GetPanoBearing(\n current_pano_id, next_pano_id) - yaw\n self._gt_direction = (bearing + 180) % 360 - 180\n else:\n self._gt_direction = 0\n\n def ground_truth_direction(self):\n \"\"\"Returns the ground truth direction to take.\n\n Returns:\n ground_truth_direction: Float angle with the ground truth direction\n to be taken for the agent to go towards the goal.\n \"\"\"\n return self._gt_direction\n" }, { "alpha_fraction": 0.7141109108924866, "alphanum_fraction": 0.7181892395019531, "avg_line_length": 28.90243911743164, "blob_id": "04df2c90592bb36664451dd5937c72ccf2e2ea0a", "content_id": "707736c4e97dd28f7d0c5e856b2752e3dc9b2add", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2452, "license_type": "permissive", "max_line_length": 79, "num_lines": 82, "path": "/streetlearn/engine/pano_graph_node.h", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#ifndef THIRD_PARTY_STREETLEARN_ENGINE_PANO_GRAPH_NODE_H_\n#define THIRD_PARTY_STREETLEARN_ENGINE_PANO_GRAPH_NODE_H_\n\n#include <map>\n#include <string>\n#include <vector>\n\n#include \"absl/types/span.h\"\n#include \"streetlearn/engine/image.h\"\n#include \"streetlearn/proto/streetlearn.pb.h\"\n\nnamespace streetlearn {\n\n// Holds metadata and de-compressed image for a pano.\nclass PanoGraphNode {\n public:\n PanoGraphNode() = default;\n explicit PanoGraphNode(const Pano& pano);\n\n // The ID of the pano.\n std::string id() const { return pano_->id(); }\n\n // The date on which the pano was recorded.\n std::string date() const { return pano_->pano_date(); }\n\n // The latitude at which the pano was recorded.\n double latitude() const { return pano_->coords().lat(); }\n\n // The longitude at which the pano was recorded.\n double longitude() const { return pano_->coords().lng(); }\n\n // The camera bearing at which the pano was recorded.\n double bearing() const { return pano_->heading_deg(); }\n\n // Returns the node's image.\n const std::shared_ptr<Image3_b> image() const { return image_; }\n\n // Returns the metadata.\n std::shared_ptr<Pano> GetPano() const { return pano_; }\n\n private:\n // The protocol buffer containing the pano's data.\n std::shared_ptr<Pano> pano_;\n\n // The de-compressed image for the pano.\n std::shared_ptr<Image3_b> image_;\n};\n\n// A struct representing a neighbor bearing.\nstruct PanoNeighborBearing {\n std::string pano_id;\n double bearing;\n double distance;\n};\n\n// Struct that holds the distance in meters and the bearing in degrees from the\n// current position to a terminal pano.\nstruct TerminalGraphNode {\n TerminalGraphNode(double distance, double bearing)\n : distance(distance), bearing(bearing) {}\n\n double distance;\n double bearing;\n};\n\n} // namespace streetlearn\n\n#endif // THIRD_PARTY_STREETLEARN_ENGINE_PANO_GRAPH_NODE_H_\n" }, { "alpha_fraction": 0.7003890872001648, "alphanum_fraction": 0.7034463882446289, "avg_line_length": 37.27659606933594, "blob_id": "dbc816bc5a0c19aaef690677a17ed457c8698675", "content_id": "003d884b1c572ab99014c9fdd6eb7f3a91292ac4", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3598, "license_type": "permissive", "max_line_length": 80, "num_lines": 94, "path": "/streetlearn/python/environment/instructions_densification.py", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "# Copyright 2019 Google LLC.\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\"\"\"StreetLearn level with reward circles around each waypoint.\n\nThis file extends the instruction-following game by adding reward densification,\ngiving fractional reward to agents as they approach a waypoint. At any point in\ntime, the level will project a reward cone around the next waypoint given the\nmost recently passed waypoint.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl import logging\n\nfrom streetlearn.python.environment import instructions_curriculum\n\n\nclass InstructionsDensification(\n instructions_curriculum.InstructionsCurriculum):\n \"\"\"StreetLang game with a cone around each waypoint reward.\"\"\"\n\n def __init__(self, config):\n \"\"\"Creates an instance of the StreetLang level.\n\n Args:\n config: config dict of various settings.\n \"\"\"\n super(InstructionsDensification, self).__init__(config)\n self._max_reward_per_cone = config['max_reward_per_cone']\n self._cone_radius_meters = config['cone_radius_meters']\n self._min_distance_reached = float('inf')\n self._distance_to_next_waypoint = float('inf')\n # We cannot have coins in this game.\n assert config['proportion_of_panos_with_coins'] == 0\n\n def on_reset(self, streetlearn):\n \"\"\"Gets called after StreetLearn:reset().\n\n Args:\n streetlearn: a streetlearn instance.\n Returns:\n A newly populated pano_id_to_color dictionary.\n \"\"\"\n self._min_distance_reached = float('inf')\n self._distance_to_next_waypoint = float('inf')\n return super(InstructionsDensification, self).on_reset(streetlearn)\n\n def get_reward(self, streetlearn):\n \"\"\"Returns the reward from the last step.\n\n Args:\n streetlearn: a StreetLearn instance.\n Returns:\n reward: the reward from the last step.\n \"\"\"\n # Calculate distance to next waypoint for _check_reward to use.\n next_waypoint_pano = self._pano_by_step[self._current_step + 1]\n self._distance_to_next_waypoint = streetlearn.engine.GetPanoDistance(\n streetlearn.current_pano_id, next_waypoint_pano)\n\n # Check if pano ID is within a cone from the next waypoint.\n dense_reward = 0\n if self._distance_to_next_waypoint < min(self._cone_radius_meters,\n self._min_distance_reached):\n dense_reward = (\n self._max_reward_per_cone *\n (self._cone_radius_meters - self._distance_to_next_waypoint) /\n self._cone_radius_meters)\n self._min_distance_reached = self._distance_to_next_waypoint\n logging.info('distance_to_next_waypoint=%f, extra reward=%f',\n self._distance_to_next_waypoint, dense_reward)\n\n # Compute the regular reward using the logic from the base class.\n prev_step = self._current_step\n reward = super(InstructionsDensification, self).get_reward(streetlearn)\n\n # Reset the minimum distance threshold?\n if prev_step != self._current_step:\n self._min_distance_reached = float('inf')\n\n return reward + dense_reward\n" }, { "alpha_fraction": 0.6629019379615784, "alphanum_fraction": 0.7128620743751526, "avg_line_length": 41.519775390625, "blob_id": "bbadc2605484d6666969eb87507e5132b25af701", "content_id": "d224f8d8cd7e51efcaff63231aa3ed7f02cca84d", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7526, "license_type": "permissive", "max_line_length": 78, "num_lines": 177, "path": "/streetlearn/engine/pano_projection_test.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/pano_projection.h\"\n\n#include <cmath>\n\n#include \"gtest/gtest.h\"\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include \"streetlearn/engine/test_dataset.h\"\n\nnamespace streetlearn {\nnamespace {\n\n// Panorama and projection image specs.\nconstexpr int kPanoramaLargeWidth = 6656;\nconstexpr int kPanoramaLargeHeight = 3328;\nconstexpr int kPanoramaSmallWidth = 416;\nconstexpr int kPanoramaSmallHeight = 208;\nconstexpr int kProjectionLargeWidth = 640;\nconstexpr int kProjectionLargeHeight = 480;\nconstexpr int kProjectionSmallWidth = 84;\nconstexpr int kProjectionSmallHeight = 84;\nconstexpr int kXCenterLarge = kProjectionLargeWidth / 2;\nconstexpr int kXCenterSmall = kProjectionSmallWidth / 2;\nconstexpr int kXRightLarge = kProjectionLargeWidth - 1;\nconstexpr int kXRightSmall = kProjectionSmallWidth - 1;\nconstexpr int kYCenterLarge = kProjectionLargeHeight / 2;\nconstexpr int kYCenterSmall = kProjectionSmallHeight / 2;\nconstexpr int kYBottomLarge = kProjectionLargeHeight - 1;\nconstexpr int kYBottomSmall = kProjectionSmallHeight - 1;\nconstexpr double kHorizontalFieldOfView = 60.0;\nconstexpr double kLongitudeStep = 30.0;\nconstexpr double kLongitudeTolerance = 5.0;\nconstexpr double kLatitudeStep = 30.0;\nconstexpr double kLatitudeTolerance = 5.0;\nconstexpr int kImageWidth = 64;\nconstexpr int kImageHeight = 48;\nconstexpr int kImageDepth = 3;\n\n// Generate a panorama image.\nImage3_b GeneratePanorama(int width, int height) {\n // Create grayscale image of the same size as the panorama.\n Image3_b panorama(width, height);\n // Draw white rectangles on the black panoramic image at regular intervals.\n for (int y = 0; y < height; y++) {\n double latitude = y * 180.0 / height;\n latitude = std::fmod(latitude, kLatitudeStep);\n if ((latitude < kLatitudeTolerance) ||\n ((kLatitudeStep - latitude) < kLatitudeTolerance)) {\n for (int x = 0; x < width; x++) {\n double longitude = x * 360.0 / width;\n longitude = std::fmod(longitude, kLongitudeStep);\n if ((longitude < kLongitudeTolerance) ||\n ((kLongitudeStep - longitude) < kLongitudeTolerance)) {\n auto pixel = panorama.pixel(x, y);\n pixel[0] = 255;\n pixel[1] = 255;\n pixel[2] = 255;\n }\n }\n }\n }\n\n return panorama;\n}\n\n// Return grayscale color of pixel.\ndouble GrayScaleColorAt(const Image3_b& image, int x, int y) {\n EXPECT_GE(x, 0);\n EXPECT_GE(y, 0);\n EXPECT_LT(x, image.width());\n EXPECT_LT(y, image.height());\n auto pixel = image.pixel(x, y);\n return (pixel[0] + pixel[1] + pixel[2]) / 3;\n}\n\n// Helper function for testing values at 9 points on the projected image.\nvoid TestProjection(const Image3_b& image, int topLeft, int topMiddle,\n int topRight, int centerLeft, int center, int centerRight,\n int bottomLeft, int bottom, int bottomRight) {\n int width = image.width();\n int height = image.height();\n int halfWidth = width / 2;\n int halfHeight = height / 2;\n EXPECT_EQ(GrayScaleColorAt(image, 0, 0), topLeft);\n EXPECT_EQ(GrayScaleColorAt(image, 0, halfHeight), topMiddle);\n EXPECT_EQ(GrayScaleColorAt(image, 0, height - 1), topRight);\n EXPECT_EQ(GrayScaleColorAt(image, halfWidth, 0), centerLeft);\n EXPECT_EQ(GrayScaleColorAt(image, halfWidth, halfHeight), center);\n EXPECT_EQ(GrayScaleColorAt(image, halfWidth, height - 1), centerRight);\n EXPECT_EQ(GrayScaleColorAt(image, width - 1, 0), bottomLeft);\n EXPECT_EQ(GrayScaleColorAt(image, width - 1, halfHeight), bottom);\n EXPECT_EQ(GrayScaleColorAt(image, width - 1, height - 1), bottomRight);\n}\n\nTEST(StreetLearn, PanoProjectionOpenCVLargeTest) {\n Image3_b panorama =\n GeneratePanorama(kPanoramaLargeWidth, kPanoramaLargeHeight);\n Image3_b image(kProjectionLargeWidth, kProjectionLargeHeight);\n\n // Creates the pano projection object.\n PanoProjection projector(kHorizontalFieldOfView, kProjectionLargeWidth,\n kProjectionLargeHeight);\n // Projects the panorama at zero pitch and yaw.\n projector.Project(panorama, 0.0, 0.0, &image);\n TestProjection(image, 0, 255, 0, 0, 255, 0, 0, 255, 0);\n // Projects the panorama at zero pitch and 30 yaw.\n projector.Project(panorama, kLongitudeStep, 0.0, &image);\n TestProjection(image, 0, 255, 0, 0, 255, 0, 0, 255, 0);\n // Projects the panorama at zero pitch and -30 yaw.\n projector.Project(panorama, kLongitudeStep, 0.0, &image);\n TestProjection(image, 0, 255, 0, 0, 255, 0, 0, 255, 0);\n // Projects the panorama at zero pitch and 15 yaw.\n projector.Project(panorama, kLongitudeStep / 2, 0.0, &image);\n TestProjection(image, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n // Projects the panorama at 15 pitch and zero yaw.\n projector.Project(panorama, 0.0, kLatitudeStep / 2, &image);\n TestProjection(image, 255, 0, 0, 0, 0, 0, 255, 0, 0);\n // Projects the panorama at 30 pitch and zero yaw.\n projector.Project(panorama, 0.0, kLatitudeStep, &image);\n TestProjection(image, 0, 255, 0, 0, 255, 0, 0, 255, 0);\n // Projects the panorama at 60 pitch and zero yaw.\n projector.Project(panorama, 0.0, kLatitudeStep * 2, &image);\n TestProjection(image, 0, 0, 255, 0, 255, 0, 0, 0, 255);\n}\n\nTEST(StreetLearn, PanoProjectionOpenCVSmallTest) {\n Image3_b panorama =\n GeneratePanorama(kPanoramaSmallWidth, kPanoramaSmallHeight);\n Image3_b image(kProjectionSmallWidth, kProjectionSmallHeight);\n\n // Creates the pano projection object.\n PanoProjection projector(kHorizontalFieldOfView, kProjectionSmallWidth,\n kProjectionSmallHeight);\n // Projects the panorama at zero pitch and yaw.\n projector.Project(panorama, 0.0, 0.0, &image);\n TestProjection(image, 255, 255, 255, 255, 255, 255, 255, 255, 255);\n // Projects the panorama at zero pitch and 15 yaw.\n projector.Project(panorama, kLongitudeStep / 2, 0.0, &image);\n TestProjection(image, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n // Projects the panorama at 15 pitch and zero yaw.\n projector.Project(panorama, 0.0, kLatitudeStep / 2, &image);\n TestProjection(image, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n // Projects the panorama at 30 pitch and zero yaw.\n projector.Project(panorama, 0.0, kLatitudeStep, &image);\n TestProjection(image, 0, 255, 255, 255, 255, 255, 0, 255, 255);\n // Projects the panorama at 60 pitch and zero yaw.\n projector.Project(panorama, 0.0, kLatitudeStep * 2, &image);\n TestProjection(image, 255, 0, 255, 255, 255, 255, 255, 0, 255);\n}\n\nTEST(StreetLearn, PanoProjectionPanoImageTest) {\n // Creates the panorama\n const auto test_image = TestDataset::GenerateTestImage();\n // Creates the pano projection object.\n PanoProjection projector(kHorizontalFieldOfView, kImageWidth, kImageHeight);\n // Projects the panorama at zero pitch and yaw.\n Image3_b proj_image(kImageWidth, kImageHeight);\n projector.Project(test_image, 0.0, 0.0, &proj_image);\n TestProjection(proj_image, 37, 37, 37, 37, 37, 37, 37, 37, 37);\n}\n\n} // namespace\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.7410972118377686, "alphanum_fraction": 0.7468720078468323, "avg_line_length": 38.20754623413086, "blob_id": "b295c46dc26c742023d13281fc76cdfd935905e3", "content_id": "34da58df4d7ef4ddfe845481a9d9f15035f4712c", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2078, "license_type": "permissive", "max_line_length": 80, "num_lines": 53, "path": "/streetlearn/engine/test_utils.h", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#ifndef THIRD_PARTY_STREETLEARN_ENGINE_TESTING_TEST_UTILS_H_\n#define THIRD_PARTY_STREETLEARN_ENGINE_TESTING_TEST_UTILS_H_\n\n#include <string>\n#include <vector>\n\n#include \"gtest/gtest.h\"\n#include \"absl/strings/string_view.h\"\n#include \"streetlearn/engine/image.h\"\n\nnamespace streetlearn {\n\nnamespace test_utils {\n\n// Returns the name of the directory in which the test binary is located.\nstd::string TestSrcDir();\n\n// Custom assertion to compare to compare two images pixel by pixel. The\n// expected image is loaded from `expected_image_path` which is a sub path\n// inside TEST_SRCDIR.\n::testing::AssertionResult CompareImages(const ImageView4_b& image,\n absl::string_view expected_image_path);\n\n// Supported pixel formats for comparison.\nenum PixelFormat { kPackedRGB, kPlanarRGB };\n\n// Custom assertion to compare to compare two images pixel by pixel. The source\n// image is provided as a continous buffer where each pixel is represented\n// as as 24 bit R, G, B value. PixelFormat determines whether channels are\n// are stored in packed or planar format. The expected image is loaded from\n// `expected_image_path` which is a sub path inside TEST_SRCDIR.\n::testing::AssertionResult CompareRGBBufferWithImage(\n absl::Span<const uint8_t> buffer, int width, int height, PixelFormat format,\n absl::string_view expected_image_path);\n\n} // namespace test_utils\n} // namespace streetlearn\n\n#endif // THIRD_PARTY_STREETLEARN_ENGINE_TESTING_TEST_UTILS_H_\n" }, { "alpha_fraction": 0.7020795941352844, "alphanum_fraction": 0.7066003680229187, "avg_line_length": 34.11111068725586, "blob_id": "44e2322f8003a981723616025db69cfe692595c4", "content_id": "587c472e2e9f04b8475522d533243f3cc340c2ca", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2212, "license_type": "permissive", "max_line_length": 78, "num_lines": 63, "path": "/streetlearn/engine/cairo_util.h", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#ifndef THIRD_PARTY_STREETLEARN_ENGINE_CAIRO_UTIL_H_\n#define THIRD_PARTY_STREETLEARN_ENGINE_CAIRO_UTIL_H_\n\n#include <cairo/cairo.h>\n\nnamespace streetlearn {\n\n// A helper class to aid rendering with Cairo.\nclass CairoRenderHelper {\n public:\n // Create a CairoRenderHelper for the image pointed to by `pixels`. The data\n // pointed to by `pixels` must have a longer life time than the created\n // CairoRenderHelper object.\n CairoRenderHelper(unsigned char* pixels, int width, int height,\n cairo_format_t format = CAIRO_FORMAT_ARGB32) {\n int stride = cairo_format_stride_for_width(format, width);\n surface_ = cairo_image_surface_create_for_data(pixels, format, width,\n height, stride);\n context_ = cairo_create(surface_);\n }\n\n ~CairoRenderHelper() {\n cairo_surface_flush(surface_);\n cairo_destroy(context_);\n cairo_surface_destroy(surface_);\n }\n\n CairoRenderHelper(const CairoRenderHelper&) = delete;\n CairoRenderHelper& operator=(const CairoRenderHelper&) = delete;\n\n int width() const { return cairo_image_surface_get_width(surface_); }\n int height() const { return cairo_image_surface_get_height(surface_); }\n\n // Returns the current cairo context.\n cairo_t* context() { return context_; }\n\n // Returns the surface of the current cairo context.\n cairo_surface_t* surface() { return surface_; }\n\n private:\n // Offscreen buffer used to render game state.\n cairo_surface_t* surface_;\n // Current rendering context.\n cairo_t* context_;\n};\n\n} // namespace streetlearn\n\n#endif // THIRD_PARTY_STREETLEARN_ENGINE_CAIRO_UTIL_H_\n" }, { "alpha_fraction": 0.704599142074585, "alphanum_fraction": 0.7112686038017273, "avg_line_length": 36.290157318115234, "blob_id": "b8b926f35c5002002426aca8da2994bfce809a63", "content_id": "ca5a0cb8f93cc39112517bb4b91451bd4d3ef32b", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7197, "license_type": "permissive", "max_line_length": 80, "num_lines": 193, "path": "/streetlearn/engine/streetlearn_engine.h", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#ifndef STREETLEARN_STREETLEARN_ENGINE_H_\n#define STREETLEARN_STREETLEARN_ENGINE_H_\n\n#include <array>\n#include <cmath>\n#include <cstdint>\n#include <map>\n#include <memory>\n#include <string>\n#include <vector>\n\n#include \"absl/types/optional.h\"\n#include \"absl/types/span.h\"\n#include \"streetlearn/engine/dataset.h\"\n#include \"streetlearn/engine/graph_renderer.h\"\n#include \"streetlearn/engine/math_util.h\"\n#include \"streetlearn/engine/metadata_cache.h\"\n#include \"streetlearn/engine/pano_graph.h\"\n#include \"streetlearn/engine/pano_graph_node.h\"\n#include \"streetlearn/engine/pano_renderer.h\"\n#include \"streetlearn/proto/streetlearn.pb.h\"\n\nnamespace streetlearn {\n\n// The controller for building and navigating around StreetLearn graphs.\n// Streetlearn pano and metadata should be in the same directory. Each pano\n// file needs to use the ID of the pano it contains as its name.\nclass StreetLearnEngine {\n public:\n // Creates an instance of the StreetLearnEngine.\n // Arguments:\n // data_path: full path to the directory containing the dataset.\n // width: width of the street image.\n // height: height of the street image.\n // graph_width: width of the map graph image.\n // graph_height: height of the map graph image.\n // status_height: height of the status bar at the bottom of the screen.\n // field_of_view: field of view covered by the screen.\n // min_graph_depth: minimum depth of graphs created.\n // max_graph_depth: maximum depth of graphs created.\n // max_cache_size: maximum capacity of the node cache.\n static std::unique_ptr<StreetLearnEngine> Create(\n const std::string& data_path, int width = 320, int height = 240,\n int graph_width = 320, int graph_height = 240, int status_height = 10,\n int field_of_view = 60, int min_graph_depth = 10,\n int max_graph_depth = 15, int max_cache_size = 1000);\n\n StreetLearnEngine(std::unique_ptr<Dataset> dataset,\n const Vector2_i& pano_size, const Vector2_i& graph_size,\n int status_height, int field_of_view, int min_graph_depth,\n int max_graph_depth, int max_cache_size);\n\n // Initialises the random number generator.\n void InitEpisode(int episode_index, int random_seed);\n\n // Builds a random graph of the required depth bounds, if possible. Returns\n // the root node of the graph if successful.\n absl::optional<std::string> BuildRandomGraph();\n\n // Builds a graph around the given root. Returns the root node of the graph\n // if successful.\n absl::optional<std::string> BuildGraphWithRoot(const std::string& pano_id);\n\n // Builds an entire graph for a region.\n absl::optional<std::string> BuildEntireGraph();\n\n // Sets the current Pano or chooses a random one if no ID is specified.\n absl::optional<std::string> SetPosition(const std::string& pano_id);\n\n // Moves to the neighbor ahead and if possible returns the new panoID.\n absl::optional<std::string> MoveToNextPano();\n\n // Sets the min and max graph depth.\n void SetGraphDepth(int min_depth, int max_depth);\n\n // Rotates the observer by the given amounts.\n void RotateObserver(double yaw_deg, double pitch_deg);\n\n // Renders and returns the observation of the game at the current timestep.\n absl::Span<const uint8_t> RenderObservation();\n\n // Renders and returns the observation of the game at the current timestep.\n // The user is responsible for providing a buffer of the correct size.\n void RenderObservation(absl::Span<uint8_t> buffer);\n\n // Calculates a binary occupancy vector of neighbors to the current pano.\n std::vector<uint8_t> GetNeighborOccupancy(int resolution);\n\n // Returns the pano for the root of the current graph.\n std::shared_ptr<const Pano> GetPano() const;\n\n // Returns metadata for the given pano if it's in the current graph.\n absl::optional<PanoMetadata> GetMetadata(const std::string& pano_id) const;\n\n // Returns a list of panoIDs and their neighbors in the current graph.\n std::map<std::string, std::vector<std::string>> GetGraph() const;\n\n // Returns the agent's current yaw rotation.\n double GetYaw() const { return rotation_yaw_; }\n\n // Returns the agent's current pitch rotation.\n double GetPitch() const { return -rotation_pitch_; }\n\n // Calculates the distance in meters between the two panos.\n absl::optional<double> GetPanoDistance(const std::string& pano_id1,\n const std::string& pano_id2);\n\n // Returns the bearing in degrees between two panos.\n absl::optional<double> GetPanoBearing(const std::string& pano_id1,\n const std::string& pano_id2);\n\n // The shape of the observation tensor.\n std::array<int, 3> ObservationDims() const {\n return {{3, pano_size_.y(), pano_size_.x()}};\n }\n\n // Creates a new graph renderer with the given panos highlighted. Returns true\n // if graph renderer is initialised correctly.\n bool InitGraphRenderer(\n const Color& observer_color,\n const std::map<std::string, Color>& panos_to_highlight);\n\n // Renders the current graph into the buffer provided. The user is\n // responsible for providing a buffer of the correct size. Returns true is\n // rendering is successful.\n bool DrawGraph(const std::map<std::string, Color>& pano_id_to_color,\n absl::Span<uint8_t> buffer);\n\n // Sets the current zoom factor. Returns true if zoom is successfully set.\n bool SetZoom(double zoom);\n\n private:\n // Sets internal state once a graph is loaded.\n std::string SetupCurrentGraph();\n\n // Renders the current pano view.\n void RenderScene();\n\n // StreetLearn dataset.\n std::unique_ptr<Dataset> dataset_;\n\n // The width/height of the output pano images.\n Vector2_i pano_size_;\n\n // The width/height of the output graph images.\n Vector2_i graph_size_;\n\n // Indicate where the graph has been cutoff.\n bool show_stop_signs_;\n\n // The agent's current orientation.\n double rotation_yaw_;\n double rotation_pitch_;\n\n // The agent's field of view.\n double field_of_view_;\n\n // Buffer in which to do pixel transforms when drawing panos.\n std::vector<uint8_t> pano_buffer_;\n\n // Buffer in which to do pixel transforms when drawing the graph.\n std::vector<uint8_t> graph_buffer_;\n\n // The observer used for the view cone when rendering the graph.\n Observer observer_;\n\n // The graph of panos.\n PanoGraph pano_graph_;\n\n // Rotates, projects and draws subsections of panos.\n PanoRenderer pano_renderer_;\n\n // Draws a pictorial representation of graphs.\n std::unique_ptr<GraphRenderer> graph_renderer_;\n};\n\n} // namespace streetlearn\n\n#endif // STREETLEARN_STREETLEARN_ENGINE_H_\n" }, { "alpha_fraction": 0.7192904949188232, "alphanum_fraction": 0.7232816219329834, "avg_line_length": 35.96721267700195, "blob_id": "051c157375a9372d79018d26c93eb00924c70333", "content_id": "21c7d0255ddbea3a2004d1667e4eb5ce45aa5156", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2255, "license_type": "permissive", "max_line_length": 80, "num_lines": 61, "path": "/streetlearn/engine/pano_graph_node_test.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/pano_graph_node.h\"\n\n#include <string>\n\n#include \"gtest/gtest.h\"\n#include \"absl/strings/str_cat.h\"\n#include \"streetlearn/engine/test_dataset.h\"\n\nnamespace streetlearn {\nnamespace {\n\nTEST(StreetLearn, PanoGraphNodeTest) {\n constexpr int kTestPanoId = 1;\n Pano pano = TestDataset::GeneratePano(kTestPanoId);\n const auto compressed_pano_image = TestDataset::GenerateCompressedTestImage();\n pano.mutable_compressed_image()->assign(compressed_pano_image.begin(),\n compressed_pano_image.end());\n const PanoGraphNode graph_node(pano);\n\n EXPECT_EQ(graph_node.id(), absl::StrCat(kTestPanoId));\n EXPECT_EQ(graph_node.date(), TestDataset::kPanoDate);\n EXPECT_EQ(graph_node.latitude(),\n TestDataset::kLatitude + TestDataset::kIncrement);\n EXPECT_EQ(graph_node.longitude(),\n TestDataset::kLongitude + TestDataset::kIncrement);\n EXPECT_EQ(graph_node.bearing(), TestDataset::kHeadingDegrees);\n\n auto image = graph_node.image();\n EXPECT_EQ(image->width(), TestDataset::kImageWidth);\n EXPECT_EQ(image->height(), TestDataset::kImageHeight);\n EXPECT_EQ(image->data(), TestDataset::GenerateTestImage().data());\n\n auto metadata = graph_node.GetPano();\n EXPECT_EQ(metadata->street_name(), TestDataset::kStreetName);\n EXPECT_EQ(metadata->full_address(), TestDataset::kFullAddress);\n EXPECT_EQ(metadata->region(), TestDataset::kRegion);\n EXPECT_EQ(metadata->country_code(), TestDataset::kCountryCode);\n}\n\nTEST(StreetLearn, InvalidPanoTest) {\n Pano pano;\n PanoGraphNode graph_node(pano);\n EXPECT_EQ(graph_node.image().get(), nullptr);\n}\n\n} // namespace\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.7040613293647766, "alphanum_fraction": 0.709457516670227, "avg_line_length": 34.56565475463867, "blob_id": "b4cd1cfc4ad1de7312d4247bfaffe4dd89d291b3", "content_id": "bc40d5756e2674ae6fa067e37cab9e40858a36c6", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3521, "license_type": "permissive", "max_line_length": 79, "num_lines": 99, "path": "/streetlearn/python/environment/step_by_step_instruction_game.py", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "# Copyright 2019 Google LLC.\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\"\"\"StreetLearn level for the single instruction-following game with curriculum.\n\nIn this environment, the agent receives a reward for every waypoint it hits\nas well as a larger reward for reaching the final goal. At any point in time\nthe agent will receive exactly one instruction, matching the next waypoint.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl import logging\n\nfrom streetlearn.python.environment import instructions_densification\n\n\nclass StepByStepInstructionGame(\n instructions_densification.InstructionsDensification):\n \"\"\"StreetLang game for following a single instructions at a time.\"\"\"\n\n def on_reset(self, streetlearn):\n \"\"\"Gets called after StreetLearn:reset().\n\n Args:\n streetlearn: a streetlearn instance.\n Returns:\n A newly populated pano_id_to_color dictionary.\n \"\"\"\n super(StepByStepInstructionGame, self).on_reset(streetlearn)\n\n # Save instruction and thumbnail vectors into a separate holder.\n # It is sufficient to use _with_goal as this is a superset of the other.\n self._all_thumbs = self._thumbnails.copy()\n self._all_instrs = self._instructions\n\n # Initialise everything to the first entry\n self._thumbnails[2:, :] = 0 # Zero all but the first and second one.\n self._instructions = [self._all_instrs[0]]\n\n logging.info(self._all_instrs)\n logging.info(self._instructions)\n\n return self._pano_id_to_color\n\n def _check_reward(self, pano_id, streetlearn):\n \"\"\"Check what reward the current pano yields, based on instructions.\n\n Args:\n pano_id: centroid pano id.\n streetlearn: streetlearn graph for establishing neighbours.\n Returns:\n The reward for the current step.\n \"\"\"\n reward = 0\n\n previous_step = self._current_step\n reward = super(StepByStepInstructionGame, self)._check_reward(\n pano_id, streetlearn)\n\n if previous_step != self._current_step and not self._reached_goal:\n # If we changed the step, but haven't terminated the game, update instrs.\n self._thumbnails[0, :] = self._all_thumbs[self._current_step]\n self._thumbnails[1, :] = (\n self._all_thumbs[self._current_step + 1])\n self._instructions = [self._all_instrs[self._current_step]]\n\n # Remove epsilon from reward to avoid triggering the waypoint switchers.\n epsilon = 0.01\n reward -= epsilon\n logging.info('Switched from step %d to step %d.',\n previous_step, self._current_step)\n logging.info(self._instructions)\n\n return reward\n\n def get_info(self, streetlearn):\n \"\"\"\"Returns current information about the state of the environment.\n\n Args:\n streetlearn: a StreetLearn instance.\n Returns:\n info: information from the environment at the last step.\n \"\"\"\n info = super(StepByStepInstructionGame, self).get_info(streetlearn)\n info['current_step'] = 0\n return info\n" }, { "alpha_fraction": 0.700237512588501, "alphanum_fraction": 0.7040380239486694, "avg_line_length": 28.23611068725586, "blob_id": "a0b31020c19921702faf661dfb20b3e10c481713", "content_id": "c7588118818f71d6baa63d63a5b7afe2f8b9f757", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2105, "license_type": "permissive", "max_line_length": 75, "num_lines": 72, "path": "/streetlearn/engine/dataset.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/dataset.h\"\n\n#include <string>\n#include <utility>\n\n#include \"streetlearn/engine/logging.h\"\n#include \"absl/memory/memory.h\"\n#include \"absl/strings/string_view.h\"\n#include \"leveldb/options.h\"\n#include \"leveldb/status.h\"\n\nnamespace streetlearn {\n\nconstexpr char Dataset::kGraphKey[];\n\nstd::unique_ptr<Dataset> Dataset::Create(const std::string& dataset_path) {\n leveldb::DB* db;\n leveldb::Status status =\n leveldb::DB::Open(leveldb::Options(), dataset_path, &db);\n if (!status.ok()) {\n LOG(ERROR) << \"Unable initialize dataset: \" << status.ToString();\n return nullptr;\n }\n\n return absl::make_unique<Dataset>(absl::WrapUnique(db));\n}\n\nDataset::Dataset(std::unique_ptr<leveldb::DB> db) { db_ = std::move(db); }\n\nbool Dataset::GetGraph(StreetLearnGraph* graph) const {\n std::string graph_proto_string;\n if (GetValue(kGraphKey, &graph_proto_string)) {\n return graph->ParseFromString(graph_proto_string);\n }\n return false;\n}\n\nbool Dataset::GetPano(absl::string_view pano_id, Pano* pano) const {\n std::string pano_proto_string;\n if (GetValue(pano_id, &pano_proto_string)) {\n return pano->ParseFromString(pano_proto_string);\n }\n\n return false;\n}\n\nbool Dataset::GetValue(absl::string_view key, std::string* value) const {\n leveldb::Status status =\n db_->Get(leveldb::ReadOptions(), std::string(key), value);\n if (!status.ok()) {\n LOG(ERROR) << \"Unable to get key/value: \" << status.ToString();\n return false;\n }\n\n return true;\n}\n\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.7506738305091858, "alphanum_fraction": 0.756738543510437, "avg_line_length": 34.33333206176758, "blob_id": "c6cd40397d48eb3eb62066bffcebe8cebebe9cb2", "content_id": "2af3513021a6821ae18973c135938579f1154f5e", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1484, "license_type": "permissive", "max_line_length": 79, "num_lines": 42, "path": "/streetlearn/python/environment/incremental_instruction_game.py", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "# Copyright 2019 Google LLC.\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\"\"\"StreetLearn level for the single instruction-following game with curriculum.\n\nIn this environment, the agent receives a reward for every waypoint it hits\nas well as a larger reward for reaching the final goal.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl import logging\n\nfrom streetlearn.python.environment import instructions_densification\n\n\nclass IncrementalInstructionGame(\n instructions_densification.InstructionsDensification):\n \"\"\"StreetLang game with goal and waypoint rewards.\"\"\"\n\n def __init__(self, config):\n \"\"\"Creates an instance of the StreetLearn level.\n\n Args:\n config: config dict of various settings.\n \"\"\"\n super(IncrementalInstructionGame, self).__init__(config)\n\n # Verify that waypoints receive reward.\n assert self._reward_at_waypoint > 0, \"Waypoint reward should be nonzero.\"\n" }, { "alpha_fraction": 0.6990185379981995, "alphanum_fraction": 0.7041594982147217, "avg_line_length": 42.96575164794922, "blob_id": "d371b2b455711865b9cb8f0e37b28902c1bc43e9", "content_id": "ae205f287650891ce42591eca5262b5b1796c610", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6419, "license_type": "permissive", "max_line_length": 80, "num_lines": 146, "path": "/streetlearn/python/environment/curriculum_courier_game.py", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "# Copyright 2018 Google LLC.\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\"\"\"StreetLearn level for the curriculum-based courier task.\n\nThis is a version of the courier task that increases the distance to the\ngoal with each episode using the given annealing rate.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl import logging\nimport numpy as np\nimport time\n\nfrom streetlearn.python.environment import courier_game\n\n_SECONDS_IN_HOUR = 3600\n\n\nclass CurriculumCourierGame(courier_game.CourierGame):\n \"\"\"Coin game that gives extra reward for finding the goal pano. A courier goal\n is randomly selected from panos in the graph according to a curriculum that\n starts with panos within a maximum distance from the current agent position,\n then anneals it with time. On success or timeout, a new goal is chosen. The\n episode ends after a fixed episode length.\n \"\"\"\n\n def __init__(self, config):\n \"\"\"Creates an instance of the RandomTaxiCurriculum level.\n\n This coin game gives extra reward for finding the goal pano, and resets the\n goal once the goal has been found (or on timeout). Panos can be assigned\n rewards (coins) randomly and the agent will receive the reward the first\n time they visit these panos. Goal panos are assigned within a circle whose\n radius grows in time from min_goal_distance to max_goal_distance.\n\n Args:\n config: config dict of various settings.\n \"\"\"\n super(CurriculumCourierGame, self).__init__(config)\n self._timestamp_start = config['timestamp_start_curriculum']\n self._annealing_rate = config['annealing_rate_curriculum']\n self._hours_curriculum_part_1 = config['hours_curriculum_part_1']\n self._hours_curriculum_part_2 = config['hours_curriculum_part_2']\n self._min_goal_distance = config['min_goal_distance_curriculum']\n self._max_goal_distance = config['max_goal_distance_curriculum']\n self._allowed_goal_distance = self._min_goal_distance\n assert self._timestamp_start <= time.time()\n assert self._annealing_rate > 0\n assert self._hours_curriculum_part_1 >= 0\n assert self._hours_curriculum_part_2 > 0\n assert self._min_goal_distance < self._max_goal_distance\n\n logging.info('CurriculumCourierGame: starts at t=%d', self._timestamp_start)\n logging.info('CurriculumCourierGame: #hours for part 1 of curriculum: %f',\n self._hours_curriculum_part_1)\n logging.info('CurriculumCourierGame: #hours for part 2 of curriculum: %f',\n self._hours_curriculum_part_2)\n logging.info('CurriculumCourierGame: min goal distance: %f',\n self._min_goal_distance)\n logging.info('CurriculumCourierGame: max goal distance: %f',\n self._max_goal_distance)\n logging.info('CurriculumCourierGame: annealing rate of the curriculum: %f',\n self._annealing_rate)\n\n def _update_curriculum_goal_distance(self):\n \"\"\"Updates the allowed distance to the goal according to the curriculum.\"\"\"\n hours_train = max(0,\n (time.time() - self._timestamp_start) / _SECONDS_IN_HOUR)\n if hours_train <= self._hours_curriculum_part_1:\n # During part 1 of the curriculum, sample goals within a minimal distance.\n self._allowed_goal_distance = self._min_goal_distance\n else:\n # During part 2 of the curriculum, sample goals within a distance\n # that grows from a minimum value to a maximum value.\n numerator = hours_train - self._hours_curriculum_part_1\n denom = self._hours_curriculum_part_2\n time_factor = pow(min(1, max(0, numerator / denom)), self._annealing_rate)\n self._allowed_goal_distance = (\n (self._max_goal_distance - self._min_goal_distance\n ) * time_factor + self._min_goal_distance)\n\n def on_reset(self, streetlearn):\n \"\"\"Gets called after StreetLearn:reset().\n\n Selects a random pano as goal destination.\n\n If there are any coins, clears the set of touched panos and randomly\n generates reward-yielding coins and populates pano_id_to_color.\n\n Args:\n streetlearn: a streetlearn instance.\n Returns:\n A newly populated pano_id_to_color dictionary.\n \"\"\"\n # Update the allowed distance to the goal according to the curriculum.\n self._update_curriculum_goal_distance()\n # Populate the list of panos and assign optional coins to panos.\n # Assign the goal location to one of the panos.\n return super(CurriculumCourierGame, self).on_reset(streetlearn)\n\n def get_info(self, streetlearn):\n \"\"\"\"Returns current information about the state of the environment.\n\n Args:\n streetlearn: a StreetLearn instance.\n Returns:\n info: information from the environment at the last step.\n \"\"\"\n info = super(CurriculumCourierGame, self).get_info(streetlearn)\n info['allowed_goal_distance'] = self._allowed_goal_distance\n return info\n\n def _sample_random_goal(self, streetlearn):\n \"\"\"Randomly sets a new pano for the current goal according to a curriculum.\n\n Args:\n streetlearn: The StreetLearn environment.\n \"\"\"\n # Sample a goal among the pano ids that is within that distance.\n goals = [goal for goal in streetlearn.graph\n if ((goal != self._current_goal_id) and\n (goal != streetlearn.current_pano_id))]\n self._initial_distance_to_goal = float('inf')\n while self._initial_distance_to_goal > self._allowed_goal_distance:\n self._current_goal_id = np.random.choice(goals)\n self._min_distance_reached = streetlearn.engine.GetPanoDistance(\n streetlearn.current_pano_id, self._current_goal_id)\n self._initial_distance_to_goal = self._min_distance_reached\n logging.info(\n '%d CurriculumCourierGame: distance to goal: %f (max allowed: %f)',\n streetlearn.frame_count, self._initial_distance_to_goal,\n self._allowed_goal_distance)\n" }, { "alpha_fraction": 0.6905057430267334, "alphanum_fraction": 0.7068322896957397, "avg_line_length": 34.440250396728516, "blob_id": "8bfd2cb35e276b5c40eeefcb49b97a0bd6388042", "content_id": "614bb0784d4425a39bc633f5d9127e83d2dea8d8", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5635, "license_type": "permissive", "max_line_length": 80, "num_lines": 159, "path": "/streetlearn/engine/streetlearn_engine_test.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/streetlearn_engine.h\"\n\n#include <array>\n#include <map>\n#include <string>\n#include <vector>\n\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n#include \"absl/memory/memory.h\"\n#include \"absl/strings/numbers.h\"\n#include \"absl/strings/str_cat.h\"\n#include \"streetlearn/engine/math_util.h\"\n#include \"streetlearn/engine/pano_calculations.h\"\n#include \"streetlearn/engine/test_dataset.h\"\n#include \"streetlearn/engine/test_utils.h\"\n\nnamespace streetlearn {\nnamespace {\n\nconstexpr int kScreenWidth = 640;\nconstexpr int kScreenHeight = 480;\nconstexpr int kStatusHeight = 10;\nconstexpr int kFieldOfView = 30;\nconstexpr double kPanoOffset = 32.0;\nconstexpr int kMinGraphDepth = 10;\nconstexpr int kMaxGraphDepth = 50;\nconstexpr int kImageDepth = 3;\nconstexpr int kBufferSize =\n kImageDepth * TestDataset::kImageWidth * TestDataset::kImageHeight;\n\nconstexpr Color kObserverColor = {0.4, 0.6, 0.9};\nconstexpr Color kNodeColor = {0.1, 0.9, 0.1};\n\nusing ::testing::DoubleEq;\nusing ::testing::Eq;\nusing ::testing::Optional;\n\nclass StreetLearnEngineTest : public testing::Test {\n public:\n static void SetUpTestCase() { ASSERT_TRUE(TestDataset::Generate()); }\n\n void SetUp() override {\n std::unique_ptr<Dataset> dataset = Dataset::Create(TestDataset::GetPath());\n ASSERT_TRUE(dataset != nullptr);\n\n engine_ = absl::make_unique<StreetLearnEngine>(\n std::move(dataset),\n Vector2_i(TestDataset::kImageWidth, TestDataset::kImageHeight),\n Vector2_i(kScreenWidth, kScreenHeight), kStatusHeight, kFieldOfView,\n kMinGraphDepth, kMaxGraphDepth, TestDataset::kMaxCacheSize);\n\n engine_->InitEpisode(0 /*episode_index*/, 0 /*random_seed*/);\n ASSERT_THAT(engine_->BuildGraphWithRoot(\"1\"), Optional(Eq(\"1\")));\n\n ASSERT_TRUE(engine_->InitGraphRenderer(\n kObserverColor,\n {{\"2\", kNodeColor}, {\"4\", kNodeColor}, {\"6\", kNodeColor}}));\n }\n\n std::unique_ptr<StreetLearnEngine> engine_;\n};\n\nTEST_F(StreetLearnEngineTest, TestEngine) {\n std::array<int, 3> dims = {\n {kImageDepth, TestDataset::kImageHeight, TestDataset::kImageWidth}};\n EXPECT_EQ(engine_->ObservationDims(), dims);\n\n // Set position a couple of times and check the result.\n EXPECT_THAT(engine_->SetPosition(\"1\"), Optional(Eq(\"1\")));\n EXPECT_THAT(engine_->GetPano()->id(), Eq(\"1\"));\n EXPECT_THAT(engine_->SetPosition(\"2\"), Optional(Eq(\"2\")));\n EXPECT_THAT(engine_->GetPano()->id(), Eq(\"2\"));\n\n // Currently facing north so cannot move to the next pano.\n EXPECT_THAT(engine_->MoveToNextPano(), Optional(Eq(\"2\")));\n EXPECT_EQ(engine_->GetPitch(), 0);\n EXPECT_DOUBLE_EQ(engine_->GetYaw(), 0);\n const auto pano2 = engine_->GetPano();\n\n // Rotate to face the next pano and move should succeed.\n engine_->RotateObserver(kPanoOffset, 0.0);\n EXPECT_THAT(engine_->MoveToNextPano(), Optional(Eq(\"3\")));\n EXPECT_EQ(engine_->GetPano()->id(), \"3\");\n const auto pano3 = engine_->GetPano();\n\n EXPECT_THAT(engine_->GetPanoDistance(\"2\", \"3\"),\n Optional(DoubleEq(DistanceBetweenPanos(*pano2, *pano3))));\n\n // Check that obervations are the right size.\n auto obs = engine_->RenderObservation();\n EXPECT_EQ(obs.size(), kBufferSize);\n\n // Should have two neighbors.\n auto occupancy = engine_->GetNeighborOccupancy(4);\n EXPECT_THAT(occupancy, ::testing::ElementsAre(1, 0, 1, 0));\n\n // Check that the right metadata is returned.\n auto metadata = engine_->GetMetadata(\"1\");\n EXPECT_EQ(metadata->pano.id(), \"1\");\n}\n\nTEST_F(StreetLearnEngineTest, TestGraphRendering) {\n constexpr char kTestPanoID[] = \"5\";\n constexpr double kYawDegrees = 45.0;\n\n engine_->SetPosition(kTestPanoID);\n engine_->RotateObserver(kYawDegrees, 0.0);\n constexpr Color kHighlightColor = {0.9, 0.1, 0.1};\n const std::map<std::string, Color> kHighlightedPanos = {\n {\"1\", kHighlightColor}, {\"3\", kHighlightColor}, {\"5\", kHighlightColor}};\n\n std::vector<uint8_t> image_buffer(kImageDepth * kScreenWidth * kScreenHeight);\n ASSERT_TRUE(\n engine_->DrawGraph(kHighlightedPanos, absl::MakeSpan(image_buffer)));\n EXPECT_TRUE(test_utils::CompareRGBBufferWithImage(\n absl::MakeSpan(image_buffer), kScreenWidth, kScreenHeight,\n test_utils::PixelFormat::kPlanarRGB,\n \"engine/test_data/graph_test_observer.png\"));\n}\n\nTEST(StreetLearn, StreetLearnEngineCreateTest) {\n TestDataset::Generate();\n\n auto engine = StreetLearnEngine::Create(\n TestDataset::GetPath(), TestDataset::kImageWidth,\n TestDataset::kImageHeight, TestDataset::kImageWidth,\n TestDataset::kImageHeight, kStatusHeight, kFieldOfView);\n engine->InitEpisode(0 /*episode_index*/, 0 /*random_seed*/);\n\n // Do some basic checks on the graph.\n auto opt_id = engine->BuildRandomGraph();\n ASSERT_TRUE(opt_id);\n EXPECT_EQ(engine->SetPosition(opt_id.value()), opt_id.value());\n EXPECT_EQ(engine->GetPano()->id(), opt_id.value());\n\n auto obs = engine->RenderObservation();\n EXPECT_EQ(obs.size(), kBufferSize);\n\n auto graph = engine->GetGraph();\n EXPECT_EQ(graph.size(), TestDataset::kPanoCount);\n}\n\n} // namespace\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.6657994389533997, "alphanum_fraction": 0.6714226007461548, "avg_line_length": 32.94301986694336, "blob_id": "f9615a557d5eb0d04c693ca13fca05a81a70a1c0", "content_id": "7b851c4d2b93d7c23626d8472c47d582b6d6c7cf", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11915, "license_type": "permissive", "max_line_length": 79, "num_lines": 351, "path": "/streetlearn/python/environment/streetlearn.py", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "# Copyright 2018 Google LLC.\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\"\"\"The StreetLearn RL environment.\n\nEpisodes take place either in a mini-map created by performing a breadth-first\ntraversal of the StreetView graph starting from a starting location, or in\nthe entire fully-connected graph.\n\nObservations:\n{\n view_image: numpy array of dimension [3, height, width] containing the\n street imagery.\n graph_image: numpy array of dimension [3, graph_height, graph_width]\n containing the map graph image.\n metadata: learning_deepmind.datasets.street_learn.Pano proto\n without compressed_image.\n target_metadata: learning_deepmind.datasets.street_learn.Pano proto\n without compressed_image.\n}\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl import logging\nimport inflection\nimport numpy as np\nimport six\n\nfrom streetlearn.python.environment import observations\nfrom streetlearn.python.environment import default_config\nfrom streetlearn.engine.python import streetlearn_engine\n\n_MIN_ZOOM = 1\n_MAX_ZOOM = 32\n\ndef _action(*entries):\n return np.array(entries, dtype=np.float)\n\nACTIONS = {\n 'move_forward': _action(1, 0.0, 0.0, 0.0),\n 'horizontal_rotation': _action(0, 1.0, 0.0, 0.0),\n 'vertical_rotation': _action(0, 0.0, 1.0, 0.0),\n 'map_zoom': _action(0, 0.0, 0.0, 1.0),\n}\n\nNUM_ACTIONS = 4\n\nACTION_SETS = {\n \"streetlearn_default\": lambda rotation_speed: (\n ACTIONS[\"move_forward\"],\n ACTIONS[\"horizontal_rotation\"] * (-rotation_speed),\n ACTIONS[\"horizontal_rotation\"] * rotation_speed),\n \"streetlearn_fast_rotate\": lambda rotation_speed: (\n ACTIONS[\"move_forward\"],\n ACTIONS[\"horizontal_rotation\"] * (-rotation_speed),\n ACTIONS[\"horizontal_rotation\"] * (-rotation_speed * 3),\n ACTIONS[\"horizontal_rotation\"] * rotation_speed,\n ACTIONS[\"horizontal_rotation\"] * rotation_speed * 3),\n \"streetlearn_tilt\": lambda rotation_speed: (\n ACTIONS[\"move_forward\"],\n ACTIONS[\"horizontal_rotation\"] * (-rotation_speed),\n ACTIONS[\"horizontal_rotation\"] * rotation_speed,\n ACTIONS[\"vertical_rotation\"] * rotation_speed,\n ACTIONS[\"vertical_rotation\"] * (-rotation_speed)),\n}\n\ndef get_action_set(action_spec, rotation_speed):\n \"\"\"Returns the set of StreetLearn actions for the given action_spec.\"\"\"\n\n # If action_spec is a string, it should be the name of a standard action set.\n if isinstance(action_spec, basestring):\n if action_spec not in ACTION_SETS:\n raise ValueError(\"Unrecognized action specification %s.\" % action_spec)\n else:\n return np.array(ACTION_SETS[action_spec](rotation_speed), dtype=np.float)\n raise ValueError(\"Action specification %s not a string.\" % action_spec)\n\nclass StreetLearn(object):\n \"\"\"The Streetlearn environment.\"\"\"\n\n def __init__(self, dataset_path, config, game):\n \"\"\"Construct the StreetLearn environment.\n\n Args:\n dataset_path: filesystem path where the dataset resides.\n config: dictionary containing various config settings. Will be extended\n with defaults from default_config.DEFAULT_CONFIG.\n game: an instance of Game.\n \"\"\"\n assert game, \"Did not provide game.\"\n logging.info('dataset_path:')\n logging.info(dataset_path)\n logging.info('config:')\n logging.info(config)\n logging.info('game:')\n logging.info(game)\n self._config = default_config.ApplyDefaults(config)\n self._seed = self._config[\"seed\"]\n self._start_pano_id = self._config[\"start_pano\"]\n self._zoom = self._config[\"graph_zoom\"]\n self._frame_cap = self._config[\"frame_cap\"]\n self._field_of_view = self._config[\"field_of_view\"]\n self._neighbor_resolution = self._config[\"neighbor_resolution\"]\n self._sample_graph_depth = self._config[\"sample_graph_depth\"]\n self._min_graph_depth = self._config[\"min_graph_depth\"]\n self._max_graph_depth = self._config[\"max_graph_depth\"]\n self._full_graph = self._config[\"full_graph\"]\n self._color_for_observer = self._config[\"color_for_observer\"]\n self._action_spec = self._config[\"action_spec\"]\n self._rotation_speed = self._config[\"rotation_speed\"]\n self._auto_reset = self._config[\"auto_reset\"]\n self._action_set = get_action_set(self._action_spec, self._rotation_speed)\n logging.info('Action set:')\n logging.info(self._action_set)\n self._bbox_lat_min = self._config[\"bbox_lat_min\"]\n self._bbox_lat_max = self._config[\"bbox_lat_max\"]\n self._bbox_lng_min = self._config[\"bbox_lng_min\"]\n self._bbox_lng_max = self._config[\"bbox_lng_max\"]\n\n self._game = game\n self._current_pano_id = None\n self._episode_id = -1\n self._frame_count = 0\n\n self._engine = streetlearn_engine.StreetLearnEngine.Create(\n dataset_path,\n width=self._config[\"width\"],\n height=self._config[\"height\"],\n graph_width=self._config[\"graph_width\"],\n graph_height=self._config[\"graph_height\"],\n status_height=self._config[\"status_height\"],\n field_of_view=self._field_of_view,\n min_graph_depth=self._min_graph_depth,\n max_graph_depth=self._max_graph_depth,\n max_cache_size=self._config[\"max_cache_size\"])\n assert self._engine, \"Could not initialise engine from %r.\" % dataset_path\n self._observations = []\n for name in self._config[\"observations\"]:\n try:\n self._observations.append(observations.Observation.create(name, self))\n except ValueError as e:\n logging.warning(str(e))\n\n self._reward = 0\n self._done = False\n self._info = {}\n\n @property\n def config(self):\n return self._config\n\n @property\n def game(self):\n return self._game\n\n @property\n def field_of_view(self):\n return self._field_of_view\n\n @property\n def current_pano_id(self):\n return self._current_pano_id\n\n @property\n def frame_cap(self):\n return self._frame_cap\n\n @frame_cap.setter\n def frame_cap(self, value):\n self._frame_cap = value\n\n @property\n def frame_count(self):\n return self._frame_count\n\n @property\n def graph(self):\n return self._graph\n\n @property\n def engine(self):\n return self._engine\n\n @property\n def neighbor_resolution(self):\n return self._neighbor_resolution\n\n @property\n def bbox_lat_min(self):\n return self._bbox_lat_min\n\n @property\n def bbox_lat_max(self):\n return self._bbox_lat_max\n\n @property\n def bbox_lng_min(self):\n return self._bbox_lng_min\n\n @property\n def bbox_lng_max(self):\n return self._bbox_lng_max\n\n def observation_spec(self):\n \"\"\"Returns the observation spec, dependent on the observation format.\"\"\"\n return {observation.name: observation.observation_spec\n for observation in self._observations}\n\n def action_spec(self):\n \"\"\"Returns the action spec.\"\"\"\n return ACTIONS\n\n def reset(self):\n \"\"\"Start a new episode.\"\"\"\n self._frame_count = 0\n self._episode_id += 1\n if self._sample_graph_depth:\n max_depth = np.random.randint(self._min_graph_depth,\n self._max_graph_depth + 1)\n self._engine.SetGraphDepth(self._min_graph_depth, max_depth)\n\n self._engine.InitEpisode(self._episode_id, self._seed)\n\n # Build a new graph if we don't have one yet.\n if not self._current_pano_id:\n if self._full_graph:\n self._current_pano_id = self._engine.BuildEntireGraph()\n elif self._start_pano_id:\n self._current_pano_id = self._engine.BuildGraphWithRoot(\n self._start_pano_id)\n else:\n self._current_pano_id = self._engine.BuildRandomGraph()\n logging.info('Built new graph with root %s', self._current_pano_id)\n # else respawn in current graph.\n elif not self._start_pano_id:\n self._current_pano_id = np.random.choice(self._engine.GetGraph().keys())\n self._engine.SetPosition(self._current_pano_id)\n logging.info('Reusing existing graph and respawning %s',\n self._current_pano_id)\n\n self._graph = self._engine.GetGraph()\n highlighted_panos = self._game.on_reset(self)\n self._engine.InitGraphRenderer(self._color_for_observer, highlighted_panos)\n self._engine.SetZoom(_MAX_ZOOM)\n\n def goto(self, pano_id, yaw):\n \"\"\"Go to a specific pano and yaw in the environment.\n\n Args:\n pano_id: a string containing the ID of a pano.\n yaw: a float with relative yaw w.r.t. north.\n Returns:\n observation: tuple with observations.\n \"\"\"\n current_pano_id = self._engine.SetPosition(pano_id)\n assert pano_id == current_pano_id\n yaw = (yaw + 180) % 360 - 180\n self._engine.RotateObserver(yaw, 0.0)\n assert yaw == self._engine.GetYaw()\n return self.observation()\n\n def step(self, action):\n \"\"\"Takes a step in the environment.\n\n Args:\n action: a 1d array containing a combination of actions.\n Returns:\n observation: tuple with observations for the last time step.\n reward: scalar reward at the last time step.\n done: boolean indicating the end of an episode.\n info: dictionary with additional debug information.\n \"\"\"\n self._frame_count += 1\n if type(action) != np.ndarray:\n action = np.array(action, dtype=np.float)\n assert action.size == NUM_ACTIONS, \"Wrong number of actions.\"\n move_forward = np.dot(action, ACTIONS['move_forward'])\n horizontal_rotation = np.dot(action, ACTIONS['horizontal_rotation'])\n vertical_rotation = np.dot(action, ACTIONS['vertical_rotation'])\n map_zoom = np.dot(action, ACTIONS['map_zoom'])\n\n if move_forward:\n self._current_pano_id = self._engine.MoveToNextPano()\n if map_zoom > 0:\n self._zoom = min(self._zoom * 2, _MAX_ZOOM)\n elif map_zoom < 0:\n self._zoom = max(self._zoom / 2, _MIN_ZOOM)\n\n if horizontal_rotation or vertical_rotation:\n self._engine.RotateObserver(horizontal_rotation, vertical_rotation)\n\n self._engine.SetZoom(self._zoom)\n self._game.on_step(self)\n\n # Update the reward and done flag. Because we do not know the code logic\n # inside each game, it is safer to obtain these immediately after step(),\n # and store them for subsequent calls to reward(), done() and info().\n self._reward = self._game.get_reward(self)\n self._done = (self._frame_count > self._frame_cap) or self._game.done()\n self._info = self._game.get_info(self)\n if self._auto_reset and self._done:\n self.reset()\n\n # Return\n return self.observation(), self.reward(), self.done(), self.info()\n\n def observation(self):\n \"\"\"Returns the observations for the last time step.\"\"\"\n return {item.name: item.observation for item in self._observations}\n\n def reward(self):\n \"\"\"Returns the reward for the last time step.\"\"\"\n return self._reward\n\n def done(self):\n \"\"\"Return a flag indicating the end of the current episode.\"\"\"\n return self._done\n\n def info(self):\n \"\"\"Return a dictionary with environment information at the current step.\"\"\"\n return self._info\n\n def get_metadata(self, pano_id):\n \"\"\"Return the metadata corresponding to the selected pano.\n\n Args:\n pano_id: a string containing the ID of a pano.\n Returns:\n metadata: a protocol buffer with the pano metadata.\n \"\"\"\n if hasattr(self, '_graph') and pano_id in self.graph:\n return self._engine.GetMetadata(pano_id)\n else:\n return None\n\n def render(self):\n \"\"\"Empty function, for compatibility with OpenAI Gym.\"\"\"\n pass\n\n" }, { "alpha_fraction": 0.6892496943473816, "alphanum_fraction": 0.6998879909515381, "avg_line_length": 34.366336822509766, "blob_id": "1c83039a73ee56ff0ee15b5b3eb0aac5c1066b14", "content_id": "671f7d10375b824731d034d0a2316b777c427e1a", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3572, "license_type": "permissive", "max_line_length": 80, "num_lines": 101, "path": "/streetlearn/engine/graph_image_cache_test.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/graph_image_cache.h\"\n\n#include <string>\n\n#include \"gtest/gtest.h\"\n#include \"absl/memory/memory.h\"\n#include \"absl/strings/str_cat.h\"\n#include \"streetlearn/engine/cairo_util.h\"\n#include \"streetlearn/engine/pano_graph.h\"\n#include \"streetlearn/engine/test_dataset.h\"\n#include \"streetlearn/engine/test_utils.h\"\n#include \"streetlearn/engine/vector.h\"\n#include \"s2/s2latlng.h\"\n#include \"s2/s2latlng_rect.h\"\n\nnamespace streetlearn {\nnamespace {\n\nconstexpr int kScreenWidth = 640;\nconstexpr int kScreenHeight = 480;\nconstexpr int kGraphDepth = 10;\nconstexpr char kTestFilePath[] = \"engine/test_data/\";\n\nclass GraphImageCacheTest : public testing::Test {\n public:\n static void SetUpTestCase() { ASSERT_TRUE(TestDataset::Generate()); }\n\n void SetUp() {\n dataset_ = Dataset::Create(TestDataset::GetPath());\n ASSERT_TRUE(dataset_ != nullptr);\n\n pano_graph_ = absl::make_unique<PanoGraph>(\n TestDataset::kMaxGraphDepth, TestDataset::kMaxCacheSize,\n TestDataset::kMinGraphDepth, TestDataset::kMaxGraphDepth,\n dataset_.get());\n\n // Build the pano graph.\n pano_graph_->SetRandomSeed(1);\n ASSERT_TRUE(pano_graph_->Init());\n ASSERT_TRUE(pano_graph_->BuildGraphWithRoot(\"1\"));\n\n // Initialise the graph renderer.\n auto bounds_min = S2LatLng::FromDegrees(TestDataset::kMinLatitude,\n TestDataset::kMinLongitude);\n auto bounds_max = S2LatLng::FromDegrees(TestDataset::kMaxLatitude,\n TestDataset::kMaxLongitude);\n S2LatLngRect graph_bounds(bounds_min, bounds_max);\n graph_image_cache_ = absl::make_unique<GraphImageCache>(\n Vector2_i{kScreenWidth, kScreenHeight}, std::map<std::string, Color>{});\n\n ASSERT_TRUE(\n graph_image_cache_->InitCache(*pano_graph_.get(), graph_bounds));\n }\n\n std::unique_ptr<GraphImageCache> graph_image_cache_;\n\n private:\n std::unique_ptr<const Dataset> dataset_;\n std::unique_ptr<PanoGraph> pano_graph_;\n};\n\nTEST_F(GraphImageCacheTest, GraphImageCacheTest) {\n const S2LatLng image_centre = S2LatLng::FromDegrees(\n (TestDataset::kMaxLatitude + TestDataset::kMinLatitude) / 2,\n (TestDataset::kMaxLongitude + TestDataset::kMinLongitude) / 2);\n\n // Test rendering.\n EXPECT_TRUE(test_utils::CompareImages(\n graph_image_cache_->Pixels(image_centre),\n absl::StrCat(kTestFilePath, \"image_cache_test.png\")));\n\n // Test zoom.\n graph_image_cache_->SetZoom(2.0);\n EXPECT_DOUBLE_EQ(graph_image_cache_->current_zoom(), 2.0);\n EXPECT_TRUE(test_utils::CompareImages(\n graph_image_cache_->Pixels(image_centre),\n absl::StrCat(kTestFilePath, \"image_cache_test_zoomed.png\")));\n\n graph_image_cache_->SetZoom(1.0);\n EXPECT_DOUBLE_EQ(graph_image_cache_->current_zoom(), 1.0);\n EXPECT_TRUE(test_utils::CompareImages(\n graph_image_cache_->Pixels(image_centre),\n absl::StrCat(kTestFilePath, \"image_cache_test.png\")));\n}\n\n} // namespace\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.6293693780899048, "alphanum_fraction": 0.6395911574363708, "avg_line_length": 39.88432693481445, "blob_id": "c397dd829121b3879bd2778a9a70882ca813393c", "content_id": "f1191b24210a98bf12992f5f7fa6a8b7b4ec2294", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10957, "license_type": "permissive", "max_line_length": 81, "num_lines": 268, "path": "/streetlearn/python/ui/human_agent.py", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "# Copyright 2018 Google LLC.\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\"\"\"Basic human agent for StreetLearn.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\n\nimport time\nimport numpy as np\nimport pygame\n\nfrom streetlearn.engine.python import color\nfrom streetlearn.python.environment import coin_game\nfrom streetlearn.python.environment import courier_game\nfrom streetlearn.python.environment import default_config\nfrom streetlearn.python.environment import goal_instruction_game\nfrom streetlearn.python.environment import incremental_instruction_game\nfrom streetlearn.python.environment import step_by_step_instruction_game\nfrom streetlearn.python.environment import streetlearn\n\nFLAGS = flags.FLAGS\nflags.DEFINE_integer('width', 400, 'Observation and map width.')\nflags.DEFINE_integer('height', 400, 'Observation and map height.')\nflags.DEFINE_integer('graph_zoom', 1, 'Zoom level.')\nflags.DEFINE_integer('width_text', 300, 'Text width.')\nflags.DEFINE_integer('font_size', 30, 'Font size.')\nflags.DEFINE_float('horizontal_rot', 10, 'Horizontal rotation step (deg).')\nflags.DEFINE_float('vertical_rot', 10, 'Vertical rotation step (deg).')\nflags.DEFINE_string('dataset_path', None, 'Dataset path.')\nflags.DEFINE_string('instruction_file', None, 'Instruction path.')\nflags.DEFINE_string(\n 'game',\n 'incremental_instruction_game',\n 'Game name [courier_game|goal_instruction_game|'\n 'incremental_instruction_game|step_by_step_instruction_game]')\nflags.DEFINE_float('reward_at_waypoint', 0.5, 'Reward at waypoint.')\nflags.DEFINE_float('reward_at_goal', 1.0, 'Reward at waypoint.')\nflags.DEFINE_integer('num_instructions', 5, 'Number of instructions.')\nflags.DEFINE_integer('max_instructions', 5, 'Maximum number of instructions.')\nflags.DEFINE_string('start_pano', '',\n 'Pano at root of partial graph (default: full graph).')\nflags.DEFINE_integer('graph_depth', 200, 'Depth of the pano graph.')\nflags.DEFINE_boolean('hide_goal', False,\n 'Whether to hide the goal location on the graph.')\nflags.DEFINE_boolean('show_shortest_path', True,\n 'Whether to highlight the shortest path in the UI.')\nflags.DEFINE_integer('frame_cap', 1000, 'Number of frames / episode.')\nflags.DEFINE_float('proportion_of_panos_with_coins', 0.0, 'Proportion of coins.')\nflags.mark_flag_as_required('dataset_path')\n\nCOLOR_WAYPOINT = (0, 178, 178)\nCOLOR_GOAL = (255, 0, 0)\nCOLOR_INSTRUCTION = (255, 255, 255)\n\n\ndef interleave(array, w, h):\n \"\"\"Turn a planar RGB array into an interleaved one.\n\n Args:\n array: An array of bytes consisting the planar RGB image.\n w: Width of the image.\n h: Height of the image.\n Returns:\n An interleaved array of bytes shape shaped (h, w, 3).\n \"\"\"\n arr = array.reshape(3, w * h)\n return np.ravel((arr[0], arr[1], arr[2]),\n order='F').reshape(h, w, 3).swapaxes(0, 1)\n\ndef blit_instruction(screen, instruction, font, color, x_min, y, x_max):\n \"\"\"Render and blit a multiline instruction onto the PyGame screen.\"\"\"\n words = instruction.split()\n space_width = font.size(' ')[0]\n x = x_min\n for word in words:\n word_surface = font.render(word, True, color)\n word_width, word_height = word_surface.get_size()\n if x + word_width >= x_max:\n x = x_min\n y += word_height\n screen.blit(word_surface, (x, y))\n x += word_width + space_width\n\ndef loop(env, screen, x_max, y_max, subsampling=None, font=None):\n \"\"\"Main loop of the human agent.\"\"\"\n screen_buffer = np.zeros((x_max, y_max, 3), np.uint8)\n action = np.array([0, 0, 0, 0])\n action_spec = env.action_spec()\n sum_rewards = 0\n sum_rewards_at_goal = 0\n previous_goal_id = None\n while True:\n\n # Take a step through the environment and record the reward.\n observation, reward, done, info = env.step(action)\n sum_rewards += reward\n pano_id = env.current_pano_id\n if reward > 0:\n print('Collected reward of {} at {}'.format(reward, pano_id))\n if done:\n print('Episode reward: {}'.format(sum_rewards))\n sum_rewards = 0\n sum_rewards_at_goal = 0\n\n # Draw the observations (view, graph).\n observation = env.observation()\n view_image = interleave(observation['view_image'],\n FLAGS.width, FLAGS.height)\n graph_image = interleave(observation['graph_image'],\n FLAGS.width, FLAGS.height)\n\n if FLAGS.game == 'coin_game' or FLAGS.game == 'courier_game':\n screen_buffer = np.concatenate((view_image, graph_image), axis=1)\n pygame.surfarray.blit_array(screen, screen_buffer)\n else:\n # Draw extra observations (thumbnails, instructions).\n screen_buffer[:FLAGS.width, :FLAGS.height, :] = view_image\n screen_buffer[:FLAGS.width, FLAGS.height:(FLAGS.height*2), :] = graph_image\n thumb_image = np.copy(observation['thumbnails'])\n current_step = info.get('current_step', -1)\n for k in range(FLAGS.max_instructions+1):\n if k != current_step:\n thumb_image[k, :, :, :] = thumb_image[k, :, :, :] / 2\n thumb_image = np.swapaxes(thumb_image, 0, 1)\n thumb_image = interleave(thumb_image,\n FLAGS.width,\n FLAGS.height * (FLAGS.max_instructions + 1))\n thumb_image = thumb_image[::subsampling, ::subsampling, :]\n screen_buffer[FLAGS.width:(FLAGS.width+thumb_image.shape[0]),\n 0:thumb_image.shape[1],\n :] = thumb_image\n pygame.surfarray.blit_array(screen, screen_buffer)\n instructions = observation['instructions'].split('|')\n instructions.append('[goal]')\n x_min = x_max - FLAGS.width_text + 10\n y = 10\n for k in range(len(instructions)):\n instruction = instructions[k]\n if k == current_step:\n color = COLOR_WAYPOINT\n elif k == len(instructions) - 1:\n color = COLOR_GOAL\n else:\n color = COLOR_INSTRUCTION\n blit_instruction(screen, instruction, font, color, x_min, y, x_max)\n y += int(FLAGS.height / subsampling)\n\n pygame.display.update()\n\n action_spec = env.action_spec()\n action = np.array([0, 0, 0, 0])\n\n while True:\n event = pygame.event.wait()\n if event.type == pygame.QUIT:\n return\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n print(pano_id + ': exit')\n return\n if event.key == pygame.K_SPACE:\n action = action_spec['move_forward']\n print(pano_id + ': move')\n elif event.key == pygame.K_p:\n filename = time.strftime('human_agent_%Y%m%d_%H%M%S.bmp')\n pygame.image.save(screen, filename)\n elif event.key == pygame.K_i:\n action = action_spec['map_zoom']\n print(pano_id + ': zoom in')\n elif event.key == pygame.K_o:\n action = -1 * action_spec['map_zoom']\n print(pano_id + ': zoom out')\n elif event.key == pygame.K_a:\n action = -FLAGS.horizontal_rot * action_spec['horizontal_rotation']\n print(pano_id + ': rotate left')\n elif event.key == pygame.K_d:\n action = FLAGS.horizontal_rot * action_spec['horizontal_rotation']\n print(pano_id + ': rotate right')\n elif event.key == pygame.K_w:\n action = -FLAGS.vertical_rot * action_spec['vertical_rotation']\n print(pano_id + ': look up')\n elif event.key == pygame.K_s:\n action = FLAGS.vertical_rot * action_spec['vertical_rotation']\n print(pano_id + ': look down')\n elif event.type == pygame.KEYUP:\n break\n\ndef main(argv):\n config = {'width': FLAGS.width,\n 'height': FLAGS.height,\n 'graph_width': FLAGS.width,\n 'graph_height': FLAGS.height,\n 'graph_zoom': FLAGS.graph_zoom,\n 'show_shortest_path': FLAGS.show_shortest_path,\n 'goal_timeout': FLAGS.frame_cap,\n 'frame_cap': FLAGS.frame_cap,\n 'full_graph': (FLAGS.start_pano == ''),\n 'start_pano': FLAGS.start_pano,\n 'min_graph_depth': FLAGS.graph_depth,\n 'max_graph_depth': FLAGS.graph_depth,\n 'reward_at_waypoint': FLAGS.reward_at_waypoint,\n 'reward_at_goal': FLAGS.reward_at_goal,\n 'instruction_file': FLAGS.instruction_file,\n 'num_instructions': FLAGS.num_instructions,\n 'max_instructions': FLAGS.max_instructions,\n 'proportion_of_panos_with_coins':\n FLAGS.proportion_of_panos_with_coins,\n 'observations': ['view_image', 'graph_image', 'yaw', 'thumbnails',\n 'pitch', 'instructions', 'latlng',\n 'target_latlng']}\n if FLAGS.hide_goal:\n config['color_for_goal'] = color.Color(1.0, 1.0, 1.0)\n config = default_config.ApplyDefaults(config)\n if FLAGS.game == 'coin_game':\n game = coin_game.CoinGame(config)\n if FLAGS.game == 'courier_game':\n game = courier_game.CourierGame(config)\n elif FLAGS.game == 'goal_instruction_game':\n game = goal_instruction_game.GoalInstructionGame(config)\n elif FLAGS.game == 'incremental_instruction_game':\n game = incremental_instruction_game.IncrementalInstructionGame(config)\n elif FLAGS.game == 'step_by_step_instruction_game':\n game = step_by_step_instruction_game.StepByStepInstructionGame(config)\n else:\n print('Unknown game: [{}]'.format(FLAGS.game))\n print('Run instruction_following_oracle_agent --help.')\n return\n env = streetlearn.StreetLearn(FLAGS.dataset_path, config, game)\n env.reset()\n\n # Configure pygame.\n pygame.init()\n pygame.font.init()\n if FLAGS.game == 'coin_game' or FLAGS.game == 'courier_game':\n subsampling = 1\n x_max = FLAGS.width\n y_max = FLAGS.height * 2\n logging.info('Rendering images at %dx%d', x_max, y_max)\n else:\n subsampling = int(np.ceil((FLAGS.max_instructions + 1) / 2))\n x_max = FLAGS.width + int(FLAGS.width / subsampling) + FLAGS.width_text\n y_max = FLAGS.height * 2\n logging.info('Rendering images at %dx%d, thumbnails subsampled by %d',\n x_max, y_max, subsampling)\n screen = pygame.display.set_mode((x_max, y_max))\n font = pygame.font.SysFont('arial', FLAGS.font_size)\n\n loop(env, screen, x_max, y_max, subsampling, font)\n\nif __name__ == '__main__':\n app.run(main)\n" }, { "alpha_fraction": 0.6949295997619629, "alphanum_fraction": 0.7100220322608948, "avg_line_length": 35.85625076293945, "blob_id": "6435d1c4d2abff0ca3e6ad258ebaecbd1bdda9f4", "content_id": "65c1fd0741bdb122ef60aa69987a3138c1dda5cf", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5897, "license_type": "permissive", "max_line_length": 80, "num_lines": 160, "path": "/streetlearn/engine/graph_region_mapper_test.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/graph_region_mapper.h\"\n\n#include <cmath>\n\n#include \"gtest/gtest.h\"\n#include \"streetlearn/engine/test_dataset.h\"\n#include \"streetlearn/engine/vector.h\"\n#include \"s2/s1angle.h\"\n#include \"s2/s2latlng.h\"\n#include \"s2/s2latlng_rect.h\"\n\nnamespace streetlearn {\nnamespace {\n\nconstexpr int kScreenWidth = 640;\nconstexpr int kScreenHeight = 480;\nconstexpr int kMarginX = 38;\nconstexpr int kMarginY = 22;\nconstexpr double kMinLatitude = TestDataset::kMinLatitude;\nconstexpr double kMinLongitude = TestDataset::kMinLongitude;\nconstexpr double kMaxLatitude = TestDataset::kMaxLatitude;\nconstexpr double kMaxLongitude = TestDataset::kMaxLongitude;\nconstexpr double kLatCentre = (kMaxLatitude + kMinLatitude) / 2;\nconstexpr double kLngCentre = (kMaxLongitude + kMinLongitude) / 2;\nconstexpr double kLatRange = kMaxLatitude - kMinLatitude;\nconstexpr double kLngRange = kMaxLongitude - kMinLongitude;\n\nS2LatLng image_centre() {\n return S2LatLng::FromDegrees(kLatCentre, kLngCentre);\n}\n\nclass RegionMapperTest : public testing::Test {\n public:\n RegionMapperTest() : region_mapper_({kScreenWidth, kScreenHeight}) {\n S2LatLng bounds_min(S1Angle::Degrees(kMinLatitude),\n S1Angle::Degrees(kMinLongitude));\n S2LatLng bounds_max(S1Angle::Degrees(kMaxLatitude),\n S1Angle::Degrees(kMaxLongitude));\n S2LatLngRect graph_bounds(bounds_min, bounds_max);\n region_mapper_.SetGraphBounds(graph_bounds);\n }\n\n void SetCurrentBounds(double zoom, const S2LatLng& image_centre) {\n region_mapper_.SetCurrentBounds(zoom, image_centre);\n }\n\n Vector2_d MapToScreen(double lat, double lng) const {\n return region_mapper_.MapToScreen(lat, lng);\n }\n\n Vector2_d MapToBuffer(double lat, double lng, int width, int height) const {\n return region_mapper_.MapToBuffer(lat, lng, width, height);\n }\n\n void ResetCurrentBounds(int zoom) { region_mapper_.ResetCurrentBounds(zoom); }\n\n private:\n streetlearn::GraphRegionMapper region_mapper_;\n};\n\nTEST_F(RegionMapperTest, MapToScreenTest) {\n // Test at full zoom.\n S2LatLng centre = image_centre();\n SetCurrentBounds(1.0 /* zoom_factor */, centre);\n\n Vector2_d mid = MapToScreen(centre.lat().degrees(), centre.lng().degrees());\n EXPECT_EQ(kScreenWidth / 2, std::lround(mid.x()));\n EXPECT_EQ(kScreenHeight / 2, std::lround(mid.y()));\n\n Vector2_d min = MapToScreen(kMinLatitude, kMinLongitude);\n EXPECT_EQ(kMarginX, std::lround(min.x()));\n EXPECT_EQ(kScreenHeight - kMarginY, std::lround(min.y()));\n\n Vector2_d max = MapToScreen(kMaxLatitude, kMaxLongitude);\n EXPECT_EQ(kScreenWidth - kMarginX, std::lround(max.x()));\n EXPECT_EQ(kMarginY, std::lround(max.y()));\n\n // Test at zoom factor 2.\n SetCurrentBounds(2.0 /* zoom_factor */, centre);\n\n Vector2_d new_centre =\n MapToScreen(centre.lat().degrees(), centre.lng().degrees());\n EXPECT_EQ(kScreenWidth / 2, std::lround(new_centre.x()));\n EXPECT_EQ(kScreenHeight / 2, std::lround(new_centre.y()));\n\n Vector2_d new_min =\n MapToScreen(kMinLatitude + kLatRange / 4, kMinLongitude + kLngRange / 4);\n EXPECT_EQ(kMarginX, std::lround(new_min.x()));\n EXPECT_EQ(kScreenHeight - kMarginY, std::lround(new_min.y()));\n\n Vector2_d new_max =\n MapToScreen(kMaxLatitude - kLatRange / 4, kMaxLongitude - kLngRange / 4);\n EXPECT_EQ(kScreenWidth - kMarginX, std::lround(new_max.x()));\n EXPECT_EQ(kMarginY, std::lround(new_max.y()));\n}\n\nTEST_F(RegionMapperTest, OffsetCentreTest) {\n // Test with centre offset.\n S2LatLng offset_centre(S1Angle::Degrees(kLatCentre - kLatRange / 2),\n S1Angle::Degrees(kLngCentre - kLngRange / 2));\n SetCurrentBounds(2.0 /* zoom_factor */, offset_centre);\n\n S2LatLng centre = image_centre();\n Vector2_d offset_test =\n MapToScreen(centre.lat().degrees(), centre.lng().degrees());\n EXPECT_EQ(kScreenWidth, std::lround(offset_test.x()));\n EXPECT_EQ(0, std::lround(offset_test.y()));\n}\n\nTEST_F(RegionMapperTest, ResetCurrentBoundsTest) {\n // Offset the centre firstly.\n S2LatLng offset_centre(S1Angle::Degrees(kLatCentre - kLatRange / 2),\n S1Angle::Degrees(kLngCentre - kLngRange / 2));\n SetCurrentBounds(2.0 /* zoom_factor */, offset_centre);\n\n // Then test ResetCurrentBounds.\n ResetCurrentBounds(2.0 /* zoom_factor */);\n S2LatLng centre = image_centre();\n Vector2_d reset_test =\n MapToScreen(centre.lat().degrees(), centre.lng().degrees());\n EXPECT_EQ(kScreenWidth / 2, std::lround(reset_test.x()));\n EXPECT_EQ(kScreenHeight / 2, std::lround(reset_test.y()));\n}\n\nTEST_F(RegionMapperTest, MapToBufferTest) {\n S2LatLng centre = image_centre();\n SetCurrentBounds(1.0 /* zoom_factor */, centre);\n\n Vector2_d mid =\n MapToBuffer(kLatCentre, kLngCentre, kScreenWidth, kScreenHeight);\n EXPECT_EQ(kScreenWidth / 2, std::lround(mid.x()));\n EXPECT_EQ(kScreenHeight / 2, std::lround(mid.y()));\n\n Vector2_d min =\n MapToBuffer(kMinLatitude, kMinLongitude, kScreenWidth, kScreenHeight);\n EXPECT_EQ(kMarginX, std::lround(min.x()));\n EXPECT_EQ(kScreenHeight - kMarginY, std::lround(min.y()));\n\n Vector2_d max =\n MapToBuffer(kMaxLatitude, kMaxLongitude, kScreenWidth, kScreenHeight);\n EXPECT_EQ(kScreenWidth - kMarginX, std::lround(max.x()));\n EXPECT_EQ(kMarginY, std::lround(max.y()));\n}\n\n} // namespace\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.6481921076774597, "alphanum_fraction": 0.6557139158248901, "avg_line_length": 39.095237731933594, "blob_id": "4f575182c4272a6845d91a6c0a90c6493a3afe3b", "content_id": "39a4ec3a72caab4c3d4c3a6a348576f8eddac146", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7578, "license_type": "permissive", "max_line_length": 80, "num_lines": 189, "path": "/streetlearn/python/agents/plain_agent.py", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "# Copyright 2018 Google LLC\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# https://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\"\"\"Importance Weighted Actor-Learner Architecture goalless navigation agent.\n\nNote that this is a modification of code previously published by Lasse Espeholt\nunder an Apache license at:\nhttps://github.com/deepmind/scalable_agent\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport functools\n\nfrom six.moves import range\nimport sonnet as snt\nimport tensorflow as tf\n\nnest = tf.contrib.framework.nest\n\nAgentOutput = collections.namedtuple('AgentOutput',\n 'action policy_logits baseline')\n\n\nclass PlainAgent(snt.RNNCore):\n \"\"\"Agent with a simple residual convnet and LSTM.\"\"\"\n\n def __init__(self,\n num_actions,\n observation_names,\n lstm_num_hiddens=256,\n feed_action_and_reward=True,\n max_reward=1.0,\n name=\"streetlearn_core\"):\n \"\"\"Initializes an agent core designed to be used with A3C/IMPALA.\n\n Supports a single visual observation tensor and outputs a single, scalar\n discrete action with policy logits and a baseline value.\n\n Args:\n num_actions: Number of actions available.\n observation_names: String with observation types separated by semi-colon.\n lstm_num_hiddens: Number of hiddens in the LSTM core.\n feed_action_and_reward: If True, the last action (one hot) and last reward\n (scalar) will be concatenated to the torso.\n max_reward: If `feed_action_and_reward` is True, the last reward will\n be clipped to `[-max_reward, max_reward]`. If `max_reward`\n is None, no clipping will be applied. N.B., this is different from\n reward clipping during gradient descent, or reward clipping by the\n environment.\n name: Optional name for the module.\n \"\"\"\n super(PlainAgent, self).__init__(name='agent')\n\n # Policy config\n self._num_actions = num_actions\n tf.logging.info('Agent trained on %d-action policy', self._num_actions)\n # Append last reward (clipped) and last action?\n self._feed_action_and_reward = feed_action_and_reward\n self._max_reward = max_reward\n # Policy LSTM core config\n self._lstm_num_hiddens = lstm_num_hiddens\n # Extract the observation names\n observation_names = observation_names.split(';')\n self._idx_frame = observation_names.index('view_image')\n\n with self._enter_variable_scope():\n tf.logging.info('LSTM core with %d hiddens', self._lstm_num_hiddens)\n self._core = tf.contrib.rnn.LSTMBlockCell(self._lstm_num_hiddens)\n\n def initial_state(self, batch_size):\n \"\"\"Return initial state with zeros, for a given batch size and data type.\"\"\"\n tf.logging.info(\"Initial state consists of the LSTM core initial state.\")\n return self._core.zero_state(batch_size, tf.float32)\n\n def _torso(self, input_):\n \"\"\"Processing of all the visual and language inputs to the LSTM core.\"\"\"\n\n # Extract the inputs\n last_action, env_output = input_\n last_reward, _, _, observation = env_output\n if type(observation) == list:\n frame = observation[self._idx_frame]\n else:\n frame = observation\n\n # Convert to image to floats and normalise.\n frame = tf.to_float(frame)\n frame /= 255\n\n # Feed image through convnet.\n with tf.variable_scope('convnet'):\n conv_out = frame\n for i, (num_ch, num_blocks) in enumerate([(16, 2), (32, 2), (32, 2)]):\n # Downscale.\n conv_out = snt.Conv2D(num_ch, 3, stride=1, padding='SAME')(conv_out)\n conv_out = tf.nn.pool(\n conv_out,\n window_shape=[3, 3],\n pooling_type='MAX',\n padding='SAME',\n strides=[2, 2])\n # Residual block(s).\n for j in range(num_blocks):\n with tf.variable_scope('residual_%d_%d' % (i, j)):\n block_input = conv_out\n conv_out = tf.nn.relu(conv_out)\n conv_out = snt.Conv2D(num_ch, 3, stride=1, padding='SAME')(conv_out)\n conv_out = tf.nn.relu(conv_out)\n conv_out = snt.Conv2D(num_ch, 3, stride=1, padding='SAME')(conv_out)\n conv_out += block_input\n # Fully connected layer.\n conv_out = tf.nn.relu(conv_out)\n conv_out = snt.BatchFlatten()(conv_out)\n conv_out = snt.Linear(256)(conv_out)\n conv_out = tf.nn.relu(conv_out)\n\n # Concatenate outputs of the visual and instruction pathways.\n if self._feed_action_and_reward:\n # Append clipped last reward and one hot last action.\n tf.logging.info('Append last reward clipped to: %f', self._max_reward)\n clipped_last_reward = tf.expand_dims(\n tf.clip_by_value(last_reward, -self._max_reward, self._max_reward),\n -1)\n tf.logging.info('Append last action (one-hot of %d)', self._num_actions)\n one_hot_last_action = tf.one_hot(last_action, self._num_actions)\n core_input = tf.concat(\n [conv_out, clipped_last_reward, one_hot_last_action],\n axis=1)\n else:\n core_input = conv_out\n return core_input\n\n def _head(self, core_output):\n \"\"\"Build the head of the agent: linear policy and value function.\"\"\"\n policy_logits = snt.Linear(\n self._num_actions, name='policy_logits')(\n core_output)\n baseline = tf.squeeze(snt.Linear(1, name='baseline')(core_output), axis=-1)\n\n # Sample an action from the policy.\n new_action = tf.multinomial(\n policy_logits, num_samples=1, output_dtype=tf.int32)\n new_action = tf.squeeze(new_action, 1, name='new_action')\n\n return AgentOutput(new_action, policy_logits, baseline)\n\n def _build(self, input_, core_state):\n \"\"\"Assemble the network components.\"\"\"\n action, env_output = input_\n actions, env_outputs = nest.map_structure(lambda t: tf.expand_dims(t, 0),\n (action, env_output))\n outputs, core_state = self.unroll(actions, env_outputs, core_state)\n return nest.map_structure(lambda t: tf.squeeze(t, 0), outputs), core_state\n\n @snt.reuse_variables\n def unroll(self, actions, env_outputs, core_state):\n \"\"\"Manual implementation of the network unroll.\"\"\"\n _, _, done, _ = env_outputs\n\n torso_outputs = snt.BatchApply(self._torso)((actions, env_outputs))\n\n # Note, in this implementation we can't use CuDNN RNN to speed things up due\n # to the state reset. This can be XLA-compiled (LSTMBlockCell needs to be\n # changed to implement snt.LSTMCell).\n initial_core_state = self._core.zero_state(tf.shape(actions)[1], tf.float32)\n core_output_list = []\n for input_, d in zip(tf.unstack(torso_outputs), tf.unstack(done)):\n # If the episode ended, the core state should be reset before the next.\n core_state = nest.map_structure(\n functools.partial(tf.where, d), initial_core_state, core_state)\n core_output, core_state = self._core(input_, core_state)\n core_output_list.append(core_output)\n\n return snt.BatchApply(self._head)(tf.stack(core_output_list)), core_state\n" }, { "alpha_fraction": 0.6753754615783691, "alphanum_fraction": 0.6784611940383911, "avg_line_length": 30.16025733947754, "blob_id": "bce4f6c163a3704f10b1c251e846bb68243b6148", "content_id": "28577b24b78add7a065b464aebc35a4f024e2b57", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4861, "license_type": "permissive", "max_line_length": 79, "num_lines": 156, "path": "/streetlearn/engine/pano_fetcher_test.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/pano_fetcher.h\"\n\n#include <algorithm>\n#include <memory>\n#include <string>\n#include <vector>\n\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n#include \"absl/base/thread_annotations.h\"\n#include \"absl/strings/str_cat.h\"\n#include \"absl/synchronization/blocking_counter.h\"\n#include \"absl/synchronization/mutex.h\"\n#include \"streetlearn/engine/pano_graph_node.h\"\n#include \"streetlearn/engine/test_dataset.h\"\n\nnamespace streetlearn {\nnamespace {\n\nconstexpr int kThreadCount = 8;\n\nclass PanoFetcherTest : public ::testing::Test {\n public:\n static void SetUpTestCase() { ASSERT_TRUE(TestDataset::Generate()); }\n\n void SetUp() {\n dataset_ = Dataset::Create(TestDataset::GetPath());\n ASSERT_TRUE(dataset_ != nullptr);\n }\n\n std::unique_ptr<const Dataset> dataset_;\n};\n\n// Class to fetch a single batch of panos of the required size. Provides a wait\n// method for asynchronous loads.\nclass FetchTest {\n public:\n explicit FetchTest(int panos_required) : counter_(panos_required) {}\n\n // Callback for the PanoFetcher when a new pano arrives. Optionally block on\n // the last fetch to test cancellation.\n void PanoLoaded(absl::string_view pano_file,\n std::shared_ptr<const PanoGraphNode> pano)\n LOCKS_EXCLUDED(mutex_) {\n absl::MutexLock scope_lock(&mutex_);\n if (pano != nullptr) {\n loaded_.push_back(std::move(pano));\n }\n counter_.DecrementCount();\n }\n\n int LoadedCount() LOCKS_EXCLUDED(mutex_) {\n absl::MutexLock scope_lock(&mutex_);\n return loaded_.size();\n }\n\n bool PanoWithID(const std::string& pano_id, const PanoGraphNode* pano_node)\n LOCKS_EXCLUDED(mutex_) {\n absl::MutexLock scope_lock(&mutex_);\n auto it = std::find_if(\n loaded_.begin(), loaded_.end(),\n [&pano_id](const std::shared_ptr<const PanoGraphNode>& arg) {\n return arg->id() == pano_id;\n });\n if (it == loaded_.end()) {\n return false;\n }\n pano_node = it->get();\n return true;\n }\n\n // Wait for all remaining panos to be downloaded.\n void WaitForAsyncLoad(int cancelled) {\n for (int i = 0; i < cancelled; ++i) {\n counter_.DecrementCount();\n }\n counter_.Wait();\n }\n\n PanoFetcher::FetchCallback MakeCallback() {\n return [this](absl::string_view pano_file,\n std::shared_ptr<const PanoGraphNode> node) {\n this->PanoLoaded(pano_file, std::move(node));\n };\n }\n\n private:\n std::vector<std::shared_ptr<const PanoGraphNode>> loaded_ GUARDED_BY(mutex_);\n absl::BlockingCounter counter_;\n absl::Mutex mutex_;\n};\n\nTEST_F(PanoFetcherTest, TestPanoFetcher) {\n FetchTest fetch_test(TestDataset::kPanoCount);\n PanoFetcher pano_fetcher(dataset_.get(), kThreadCount,\n fetch_test.MakeCallback());\n\n for (int i = 1; i <= TestDataset::kPanoCount; ++i) {\n pano_fetcher.FetchAsync(absl::StrCat(i));\n }\n\n fetch_test.WaitForAsyncLoad(0);\n\n EXPECT_EQ(fetch_test.LoadedCount(), TestDataset::kPanoCount);\n\n for (int i = 1; i <= TestDataset::kPanoCount; ++i) {\n PanoGraphNode* pano = nullptr;\n EXPECT_TRUE(fetch_test.PanoWithID(absl::StrCat(i), pano));\n }\n}\n\nTEST_F(PanoFetcherTest, CancelFetchTest) {\n FetchTest fetch_test(TestDataset::kPanoCount);\n PanoFetcher pano_fetcher(dataset_.get(), kThreadCount,\n fetch_test.MakeCallback());\n\n std::vector<std::string> pano_ids(TestDataset::kPanoCount);\n for (int i = 1; i <= TestDataset::kPanoCount; ++i) {\n auto pano_id = absl::StrCat(i);\n pano_ids.emplace_back(pano_id);\n pano_fetcher.FetchAsync(pano_id);\n }\n\n // Since the fetching is asynchronous there is no way of knowing which panos\n // have been cancelled - can only check the right number have taken place.\n std::vector<std::string> cancelled = pano_fetcher.CancelPendingFetches();\n fetch_test.WaitForAsyncLoad(cancelled.size());\n EXPECT_EQ(fetch_test.LoadedCount(),\n TestDataset::kPanoCount - cancelled.size());\n}\n\nTEST_F(PanoFetcherTest, InvalidPanoTests) {\n FetchTest fetch_test(TestDataset::kPanoCount);\n PanoFetcher pano_fetcher(dataset_.get(), kThreadCount,\n fetch_test.MakeCallback());\n\n auto pano_node = pano_fetcher.Fetch(\"Pano1\");\n EXPECT_EQ(pano_node, nullptr);\n}\n\n} // namespace\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.677859365940094, "alphanum_fraction": 0.7256033420562744, "avg_line_length": 28.323076248168945, "blob_id": "a5374ee569d1e8d0a8fc470a2f4af27761c51a4e", "content_id": "563d32665c923192ed2bbee40950d81c8ffc2bf3", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1906, "license_type": "permissive", "max_line_length": 75, "num_lines": 65, "path": "/streetlearn/engine/pano_calculations_test.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/pano_calculations.h\"\n\n#include <random>\n\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n\nnamespace streetlearn {\nnamespace {\n\nconstexpr double kLatitude1 = 51.5335010;\nconstexpr double kLatitude2 = 51.5380236;\nconstexpr double kLongitude1 = -0.1256744;\nconstexpr double kLongitude2 = -0.1268474;\nconstexpr double kTolerance = 0.001;\n\nclass PanoCalculationsTest : public ::testing::Test {\n public:\n PanoCalculationsTest() {\n LatLng* coords1 = pano1_.mutable_coords();\n coords1->set_lat(kLatitude1);\n coords1->set_lng(kLongitude1);\n\n LatLng* coords2 = pano2_.mutable_coords();\n coords2->set_lat(kLatitude2);\n coords2->set_lng(kLongitude2);\n }\n\n Pano pano1_;\n Pano pano2_;\n};\n\nTEST(StreetLearn, AngleConversionsTest) {\n EXPECT_EQ(DegreesToRadians(0), 0);\n EXPECT_EQ(DegreesToRadians(90), M_PI / 2);\n EXPECT_EQ(DegreesToRadians(-90), -M_PI / 2);\n EXPECT_EQ(DegreesToRadians(180), M_PI);\n}\n\nTEST_F(PanoCalculationsTest, BearingBetweenPanosTest) {\n EXPECT_THAT(BearingBetweenPanos(pano1_, pano2_),\n testing::DoubleNear(-9.16417, kTolerance));\n}\n\nTEST_F(PanoCalculationsTest, DistanceBetweenPanos) {\n EXPECT_THAT(DistanceBetweenPanos(pano1_, pano2_),\n testing::DoubleNear(509.393, kTolerance));\n}\n\n} // namespace\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.7195828557014465, "alphanum_fraction": 0.7276940941810608, "avg_line_length": 29.280702590942383, "blob_id": "c55e43f28f630246ee8510d31bc81811d47575f4", "content_id": "a71469de27aaeed1a900bfa6cdc990da748c5c62", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1726, "license_type": "permissive", "max_line_length": 80, "num_lines": 57, "path": "/streetlearn/engine/rtree_helper.h", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#ifndef THIRD_PARTY_STREETLEARN_ENGINE_RTREE_HELPER_H_\n#define THIRD_PARTY_STREETLEARN_ENGINE_RTREE_HELPER_H_\n\n#include <cstddef>\n#include <memory>\n#include <vector>\n\n#include \"s2/s2latlng_rect.h\"\n\nnamespace streetlearn {\n\n// Helper class that encapsulates a generic RTree implementation for the purpose\n// of executing intersection queries against S2LatLngRects. This RTree is only\n// capable of storing int values and only supports insertion and intersection\n// query.\nclass RTree {\n public:\n RTree();\n ~RTree();\n\n RTree(const RTree&) = delete;\n RTree& operator=(const RTree&) = delete;\n\n // Inserts S2LatLngRect, int pairs.\n void Insert(const S2LatLngRect& rect, int value);\n\n // Query boxes that intersect `rect` and insert values to the result vector.\n // Returns the number of intersecting boxes.\n std::size_t FindIntersecting(const S2LatLngRect& rect,\n std::vector<int>* out) const;\n\n // Returns whether the tree is empty.\n bool empty() const;\n\n private:\n struct Impl;\n\n std::unique_ptr<Impl> impl_;\n};\n\n} // namespace streetlearn\n\n#endif // THIRD_PARTY_STREETLEARN_ENGINE_RTREE_HELPER_H_\n" }, { "alpha_fraction": 0.6932972073554993, "alphanum_fraction": 0.7014217972755432, "avg_line_length": 27.403846740722656, "blob_id": "1bf596953fa691a7539dcdcd060d858ddb053611", "content_id": "8c354dbc43bce4e52b11e76e76e0292b99a37280", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1477, "license_type": "permissive", "max_line_length": 94, "num_lines": 52, "path": "/streetlearn/pip_package/build_pip_package.sh", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# Copyright 2018 Google LLC.\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\nset -e\nTMPDIR=$(mktemp -d -t tmp.XXXXXXXXXXX)\nRUNFILES=bazel-bin/streetlearn/pip_package/build_pip_package.runfiles/org_deepmind_streetlearn\n\n# Build.\nbazel build -c opt $COPT_FLAGS streetlearn/pip_package:build_pip_package\n\n# 1: Copy /streetlearn to top level.\ncp -R \"${RUNFILES}/streetlearn\" \"${TMPDIR}\"\n\n# 2: Copy /*solib* dir to top level.\nso_lib_dir=$(ls \"$RUNFILES\" | grep solib)\nif [ -n \"${so_lib_dir}\" ]; then\n cp -R \"${RUNFILES}/${so_lib_dir}\" \"${TMPDIR}\"\nfi\n\ncp LICENSE \"${TMPDIR}\"\ncp README.md \"${TMPDIR}\"\ncp streetlearn/pip_package/MANIFEST.in \"${TMPDIR}\"\ncp streetlearn/pip_package/setup.py \"${TMPDIR}\"\n\npushd \"${TMPDIR}\"\nrm -f MANIFEST\necho $(date) : \"=== Building wheel in ${TMPDIR}\"\npython setup.py bdist_wheel\npopd\n\nif [ $# -gt 0 ]; then\n DEST=$1\n mkdir -p \"${DEST}\"\n cp \"${TMPDIR}/dist\"/* \"${DEST}\"\nelse\n DEST=\"${TMPDIR}/dist\"\nfi\n\necho \"Output wheel is in ${DEST}\"\n" }, { "alpha_fraction": 0.6719177961349487, "alphanum_fraction": 0.6842465996742249, "avg_line_length": 32.953487396240234, "blob_id": "77a295b757c800eea7c78f4f4f8164c59049ce33", "content_id": "438a3a0e40aa32a4cf2c47e80cf2767c11263d75", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1460, "license_type": "permissive", "max_line_length": 75, "num_lines": 43, "path": "/streetlearn/engine/pano_graph_node.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/pano_graph_node.h\"\n\n#include <memory>\n\n#include <opencv/cv.h>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n\nnamespace streetlearn {\n\nPanoGraphNode::PanoGraphNode(const Pano& pano) {\n pano_ = std::make_shared<Pano>(pano);\n\n const std::string& compressed_image = pano.compressed_image();\n if (!compressed_image.empty()) {\n cv::Mat mat =\n cv::imdecode(cv::Mat(1, compressed_image.size(), CV_8UC1,\n const_cast<char*>(compressed_image.data())),\n CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR);\n CHECK_EQ(mat.channels(), 3);\n cv::Mat rgb_mat;\n cv::cvtColor(mat, rgb_mat, CV_BGR2RGB);\n\n image_ = std::make_shared<Image3_b>(mat.cols, mat.rows);\n std::copy(rgb_mat.datastart, rgb_mat.dataend, image_->pixel(0, 0));\n }\n}\n\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.6430432796478271, "alphanum_fraction": 0.6531676054000854, "avg_line_length": 40.39419174194336, "blob_id": "ba04620ddc5d1da562327f3fadca16482d680374", "content_id": "8c965c4d230c4d869bf581380bffbff67971a6d6", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9976, "license_type": "permissive", "max_line_length": 79, "num_lines": 241, "path": "/streetlearn/python/ui/instruction_following_oracle_agent.py", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "# Copyright 2018 Google LLC.\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\"\"\"Basic oracle agent for StreetLearn.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\n\nimport time\nimport numpy as np\nimport pygame\n\nfrom streetlearn.python.environment import default_config\nfrom streetlearn.python.environment import goal_instruction_game\nfrom streetlearn.python.environment import incremental_instruction_game\nfrom streetlearn.python.environment import step_by_step_instruction_game\nfrom streetlearn.python.environment import streetlearn\n\nFLAGS = flags.FLAGS\nflags.DEFINE_integer('width', 400, 'Observation and map width.')\nflags.DEFINE_integer('height', 400, 'Observation and map height.')\nflags.DEFINE_integer('graph_zoom', 1, 'Zoom level.')\nflags.DEFINE_integer('width_text', 300, 'Text width.')\nflags.DEFINE_integer('font_size', 30, 'Font size.')\nflags.DEFINE_float('horizontal_rot', 10, 'Horizontal rotation step (deg).')\nflags.DEFINE_string('dataset_path', None, 'Dataset path.')\nflags.DEFINE_string('instruction_file', None, 'Instruction path.')\nflags.DEFINE_string(\n 'game',\n 'incremental_instruction_game',\n 'Game name [goal_instruction_game|'\n 'incremental_instruction_game|step_by_step_instruction_game]')\nflags.DEFINE_float('reward_at_waypoint', 0.5, 'Reward at waypoint.')\nflags.DEFINE_float('reward_at_goal', 1.0, 'Reward at waypoint.')\nflags.DEFINE_integer('num_instructions', 5, 'Number of instructions.')\nflags.DEFINE_integer('max_instructions', 5, 'Maximum number of instructions.')\nflags.DEFINE_string('start_pano', '',\n 'Pano at root of partial graph (default: full graph).')\nflags.DEFINE_integer('graph_depth', 200, 'Depth of the pano graph.')\nflags.DEFINE_boolean('show_shortest_path', True,\n 'Whether to highlight the shortest path in the UI.')\nflags.DEFINE_integer('frame_cap', 1000, 'Number of frames / episode.')\nflags.DEFINE_string('stats_path', None, 'Statistics path.')\nflags.mark_flag_as_required('dataset_path')\nflags.mark_flag_as_required('instruction_file')\n\nCOLOR_WAYPOINT = (0, 178, 178)\nCOLOR_GOAL = (255, 0, 0)\nCOLOR_INSTRUCTION = (255, 255, 255)\n\n\ndef interleave(array, w, h):\n \"\"\"Turn a planar RGB array into an interleaved one.\n\n Args:\n array: An array of bytes consisting the planar RGB image.\n w: Width of the image.\n h: Height of the image.\n Returns:\n An interleaved array of bytes shape shaped (h, w, 3).\n \"\"\"\n arr = array.reshape(3, w * h)\n return np.ravel((arr[0], arr[1], arr[2]),\n order='F').reshape(h, w, 3).swapaxes(0, 1)\n\ndef blit_instruction(screen, instruction, font, color, x_min, y, x_max):\n \"\"\"Render and blit a multiline instruction onto the PyGame screen.\"\"\"\n words = instruction.split()\n space_width = font.size(' ')[0]\n x = x_min\n for word in words:\n word_surface = font.render(word, True, color)\n word_width, word_height = word_surface.get_size()\n if x + word_width >= x_max:\n x = x_min\n y += word_height\n screen.blit(word_surface, (x, y))\n x += word_width + space_width\n\ndef loop(env, screen, x_max, y_max, subsampling, font):\n \"\"\"Main loop of the oracle agent.\"\"\"\n screen_buffer = np.zeros((x_max, y_max, 3), np.uint8)\n action = np.array([0, 0, 0, 0])\n action_spec = env.action_spec()\n sum_rewards = 0\n sum_rewards_at_goal = 0\n previous_goal_id = None\n while True:\n\n # Take a step given the previous action and record the reward.\n observation, reward, done, info = env.step(action)\n sum_rewards += reward\n if (reward > 0) and (info['current_goal_id'] is not previous_goal_id):\n sum_rewards_at_goal += reward\n previous_goal_id = info['current_goal_id']\n if done:\n print('Episode reward: {}'.format(sum_rewards))\n if FLAGS.stats_path:\n with open(FLAGS.stats_path, 'a') as f:\n f.write(str(sum_rewards) + '\\t' + str(sum_rewards_at_goal) + '\\n')\n sum_rewards = 0\n sum_rewards_at_goal = 0\n\n # Determine the next pano and bearing to that pano.\n current_pano_id = info['current_pano_id']\n next_pano_id = info['next_pano_id']\n bearing_info = info['bearing_to_next_pano']\n bearing = observation['ground_truth_direction']\n logging.info('Current pano: %s, next pano %s at %f (%f)',\n current_pano_id, next_pano_id, bearing, bearing_info)\n current_step = info.get('current_step', -1)\n\n # Bearing-based navigation.\n if bearing > FLAGS.horizontal_rot:\n if bearing > FLAGS.horizontal_rot + 2 * FLAGS.horizontal_rot:\n action = 3 * FLAGS.horizontal_rot * action_spec['horizontal_rotation']\n else:\n action = FLAGS.horizontal_rot * action_spec['horizontal_rotation']\n elif bearing < -FLAGS.horizontal_rot:\n if bearing < -FLAGS.horizontal_rot - 2 * FLAGS.horizontal_rot:\n action = -3 * FLAGS.horizontal_rot * action_spec['horizontal_rotation']\n else:\n action = -FLAGS.horizontal_rot * action_spec['horizontal_rotation']\n else:\n action = action_spec['move_forward']\n\n # Draw the observations (view, graph, thumbnails, instructions).\n view_image = interleave(observation['view_image'],\n FLAGS.width, FLAGS.height)\n graph_image = interleave(observation['graph_image'],\n FLAGS.width, FLAGS.height)\n screen_buffer[:FLAGS.width, :FLAGS.height, :] = view_image\n screen_buffer[:FLAGS.width, FLAGS.height:(FLAGS.height*2), :] = graph_image\n thumb_image = np.copy(observation['thumbnails'])\n for k in range(FLAGS.max_instructions+1):\n if k != current_step:\n thumb_image[k, :, :, :] = thumb_image[k, :, :, :] / 2\n thumb_image = np.swapaxes(thumb_image, 0, 1)\n thumb_image = interleave(thumb_image,\n FLAGS.width,\n FLAGS.height * (FLAGS.max_instructions + 1))\n thumb_image = thumb_image[::subsampling, ::subsampling, :]\n screen_buffer[FLAGS.width:(FLAGS.width+thumb_image.shape[0]),\n 0:thumb_image.shape[1],\n :] = thumb_image\n pygame.surfarray.blit_array(screen, screen_buffer)\n instructions = observation['instructions'].split('|')\n instructions.append('[goal]')\n x_min = x_max - FLAGS.width_text + 10\n y = 10\n for k in range(len(instructions)):\n instruction = instructions[k]\n if k == current_step:\n color = COLOR_WAYPOINT\n elif k == len(instructions) - 1:\n color = COLOR_GOAL\n else:\n color = COLOR_INSTRUCTION\n blit_instruction(screen, instruction, font, color, x_min, y, x_max)\n y += int(FLAGS.height / subsampling)\n pygame.display.update()\n\n for event in pygame.event.get():\n if (event.type == pygame.QUIT or\n (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE)):\n return\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_p:\n filename = time.strftime('oracle_agent_%Y%m%d_%H%M%S.bmp')\n pygame.image.save(screen, filename)\n\ndef main(argv):\n config = {'width': FLAGS.width,\n 'height': FLAGS.height,\n 'status_height': 0,\n 'graph_width': FLAGS.width,\n 'graph_height': FLAGS.height,\n 'graph_zoom': FLAGS.graph_zoom,\n 'show_shortest_path': FLAGS.show_shortest_path,\n 'calculate_ground_truth': True,\n 'goal_timeout': FLAGS.frame_cap,\n 'frame_cap': FLAGS.frame_cap,\n 'full_graph': (FLAGS.start_pano == ''),\n 'start_pano': FLAGS.start_pano,\n 'min_graph_depth': FLAGS.graph_depth,\n 'max_graph_depth': FLAGS.graph_depth,\n 'reward_at_waypoint': FLAGS.reward_at_waypoint,\n 'reward_at_goal': FLAGS.reward_at_goal,\n 'instruction_file': FLAGS.instruction_file,\n 'num_instructions': FLAGS.num_instructions,\n 'max_instructions': FLAGS.max_instructions,\n 'proportion_of_panos_with_coins': 0.0,\n 'action_spec': 'streetlearn_fast_rotate',\n 'observations': ['view_image', 'graph_image', 'yaw', 'thumbnails',\n 'instructions', 'ground_truth_direction']}\n # Configure game and environment.\n config = default_config.ApplyDefaults(config)\n if FLAGS.game == 'goal_instruction_game':\n game = goal_instruction_game.GoalInstructionGame(config)\n elif FLAGS.game == 'incremental_instruction_game':\n game = incremental_instruction_game.IncrementalInstructionGame(config)\n elif FLAGS.game == 'step_by_step_instruction_game':\n game = step_by_step_instruction_game.StepByStepInstructionGame(config)\n else:\n print('Unknown game: [{}]'.format(FLAGS.game))\n print('Run instruction_following_oracle_agent --help.')\n return\n env = streetlearn.StreetLearn(FLAGS.dataset_path, config, game)\n env.reset()\n\n # Configure pygame.\n pygame.init()\n pygame.font.init()\n subsampling = int(np.ceil((FLAGS.max_instructions + 1) / 2))\n x_max = FLAGS.width + int(FLAGS.width / subsampling) + FLAGS.width_text\n y_max = FLAGS.height * 2\n logging.info('Rendering images at %dx%d, thumbnails subsampled by %d',\n x_max, y_max, subsampling)\n screen = pygame.display.set_mode((x_max, y_max))\n font = pygame.font.SysFont('arial', FLAGS.font_size)\n\n loop(env, screen, x_max, y_max, subsampling, font)\n\nif __name__ == '__main__':\n app.run(main)\n" }, { "alpha_fraction": 0.6594892740249634, "alphanum_fraction": 0.6678763628005981, "avg_line_length": 40.564247131347656, "blob_id": "a0d6772b37d431ae6b3a6900a46fe2df9ac1d692", "content_id": "683e7aa77fe877b11bcdb26830e44c9fdd51947e", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 37200, "license_type": "permissive", "max_line_length": 80, "num_lines": 895, "path": "/streetlearn/python/experiment.py", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "# Copyright 2018 Google LLC\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# https://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\"\"\"Main experiment file for the StreetLearn agent, based on an implementation of\nImportance Weighted Actor-Learner Architectures.\n\nFor details and theory see:\n\n\"IMPALA: Scalable Distributed Deep-RL with\nImportance Weighted Actor-Learner Architectures\"\nby Espeholt, Soyer, Munos et al.\n\nSee https://arxiv.org/abs/1802.01561 for the full paper.\n\nNote that this derives from code previously published by Lasse Espeholt\nunder an Apache license at:\nhttps://github.com/deepmind/scalable_agent\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport contextlib\nimport functools\nimport os\nimport sys\nimport time\n\nimport numpy as np\nfrom six.moves import range\nimport sonnet as snt\nimport tensorflow as tf\n\nfrom streetlearn.python.agents import goal_nav_agent\nfrom streetlearn.python.agents import city_nav_agent\nfrom streetlearn.python.scalable_agent import py_process\nfrom streetlearn.python.scalable_agent import vtrace\nfrom streetlearn.python.environment import default_config\nfrom streetlearn.python.environment import streetlearn\n\nnest = tf.contrib.framework.nest\n\nflags = tf.app.flags\nFLAGS = tf.app.flags.FLAGS\n\nflags.DEFINE_string('logdir', '/tmp/agent', 'TensorFlow log directory.')\nflags.DEFINE_enum('mode', 'train', ['train', 'test'], 'Training or test mode.')\n\n# Flags used for testing.\nflags.DEFINE_integer('test_num_episodes', 10, 'Number of episodes per level.')\n\n# Flags used for distributed training.\nflags.DEFINE_integer('task', -1, 'Task id. Use -1 for local training.')\nflags.DEFINE_enum('job_name', 'learner', ['learner', 'actor'],\n 'Job name. Ignored when task is set to -1.')\nflags.DEFINE_string('master', '', 'Session master.')\n\n# Training.\nflags.DEFINE_integer('total_environment_frames', int(1e9),\n 'Total environment frames to train for.')\nflags.DEFINE_integer('num_actors', 1, 'Number of actors.')\nflags.DEFINE_integer('batch_size', 1, 'Batch size for training.')\nflags.DEFINE_integer('unroll_length', 50, 'Unroll length in agent steps.')\nflags.DEFINE_integer('seed', 1, 'Random seed.')\n\n# Loss settings.\nflags.DEFINE_float('entropy_cost', 0.00025, 'Entropy cost/multiplier.')\nflags.DEFINE_float('baseline_cost', .5, 'Baseline cost/multiplier.')\nflags.DEFINE_float('discounting', .99, 'Discounting factor.')\nflags.DEFINE_enum('reward_clipping', 'abs_one', ['abs_one', 'soft_asymmetric'],\n 'Reward clipping.')\nflags.DEFINE_float('heading_prediction_cost', 1.0,\n 'Auxiliary cost/multiplier for heading prediction.')\nflags.DEFINE_float('xy_prediction_cost', 1.0,\n 'Auxiliary cost/multiplier for XY position prediction.')\nflags.DEFINE_float('target_xy_prediction_cost', 1.0,\n 'Auxiliary cost/multiplier for XY target prediction.')\n\n# Environment settings.\nflags.DEFINE_string('game_name', 'curriculum_courier_game',\n 'Game name for the StreetLearn agent.')\nflags.DEFINE_string('level_names', 'manhattan_lowres',\n 'Lavel name for the StreetLearn agent.')\nflags.DEFINE_string('dataset_paths', None, 'Path were the levels are stored.')\nflags.DEFINE_integer('width', 84, 'Width of observation.')\nflags.DEFINE_integer('height', 84, 'Height of observation.')\nflags.DEFINE_integer('graph_width', 84, 'Width of graph visualisation.')\nflags.DEFINE_integer('graph_height', 84, 'Height of graph visualisation.')\nflags.DEFINE_integer('graph_zoom', 1, 'Zoom in graph visualisation.')\nflags.DEFINE_string('start_pano', '',\n 'Pano at root of partial graph (default: full graph).')\nflags.DEFINE_integer('graph_depth', 200, 'Depth of the pano graph.')\nflags.DEFINE_integer('frame_cap', 1000, 'Number of frames / episode.')\nflags.DEFINE_string('action_set', 'streetlearn_fast_rotate',\n 'Set of actions used by the agent.')\nflags.DEFINE_float('rotation_speed', 22.5,\n 'Rotation speed of the actor.')\nflags.DEFINE_string('observations',\n 'view_image;graph_image;latlng;target_latlng;yaw;yaw_label;'\n 'latlng_label;target_latlng_label',\n 'Observations used by the agent.')\nflags.DEFINE_float('timestamp_start_curriculum', time.time(),\n 'Timestamp at the start of the curriculum.')\nflags.DEFINE_float('hours_curriculum_part_1', 0.0,\n 'Number of hours for 1st part of curriculum.')\nflags.DEFINE_float('hours_curriculum_part_2', 24.0,\n 'Number of hours for 2nd part of curriculum.')\nflags.DEFINE_float('min_goal_distance_curriculum', 500.0,\n 'Maximum distance to goal at beginning of curriculum.')\nflags.DEFINE_float('max_goal_distance_curriculum', 3500.0,\n 'Maximum distance to goal at end of curriculum.')\nflags.DEFINE_float('bbox_lat_min', 0, 'Minimum latitude.')\nflags.DEFINE_float('bbox_lat_max', 100, 'Maximum latitude.')\nflags.DEFINE_float('bbox_lng_min', 0, 'Minimum longitude.')\nflags.DEFINE_float('bbox_lng_max', 100, 'Maximum longitude.')\nflags.DEFINE_float('min_radius_meters', 100.0, 'Radius of goal area.')\nflags.DEFINE_float('max_radius_meters', 200.0, 'Radius of early rewards.')\nflags.DEFINE_float('proportion_of_panos_with_coins', 0, 'Proportion of coins.')\n\n# Agent settings.\nflags.DEFINE_string('agent', 'city_nav_agent', 'Agent name.')\n\n# Optimizer settings.\nflags.DEFINE_float('learning_rate', 0.001, 'Learning rate.')\nflags.DEFINE_float('decay', .99, 'RMSProp optimizer decay.')\nflags.DEFINE_float('momentum', 0., 'RMSProp momentum.')\nflags.DEFINE_float('epsilon', .1, 'RMSProp epsilon.')\n\n# Structure to be sent from actors to learner.\nActorOutput = collections.namedtuple(\n 'ActorOutput', 'level_name agent_state env_outputs agent_outputs')\nAgentOutput = collections.namedtuple('AgentOutput',\n 'action policy_logits baseline heading')\n\n\ndef is_single_machine():\n return FLAGS.task == -1\n\n\nStepOutputInfo = collections.namedtuple('StepOutputInfo',\n 'episode_return episode_step')\nStepOutput = collections.namedtuple('StepOutput',\n 'reward info done observation')\n\n\nclass FlowEnvironment(object):\n \"\"\"An environment that returns a new state for every modifying method.\n\n The environment returns a new environment state for every modifying action and\n forces previous actions to be completed first. Similar to `flow` for\n `TensorArray`.\n\n Note that this is a copy of the code previously published by Lasse Espeholt\n under an Apache license at:\n https://github.com/deepmind/scalable_agent\n \"\"\"\n def __init__(self, env):\n \"\"\"Initializes the environment.\n\n Args:\n env: An environment with `initial()` and `step(action)` methods where\n `initial` returns the initial observations and `step` takes an action\n and returns a tuple of (reward, done, observation). `observation`\n should be the observation after the step is taken. If `done` is\n True, the observation should be the first observation in the next\n episode.\n \"\"\"\n self._env = env\n\n def initial(self):\n \"\"\"Returns the initial output and initial state.\n\n Returns:\n A tuple of (`StepOutput`, environment state). The environment state should\n be passed in to the next invocation of `step` and should not be used in\n any other way. The reward and transition type in the `StepOutput` is the\n reward/transition type that lead to the observation in `StepOutput`.\n \"\"\"\n with tf.name_scope('flow_environment_initial'):\n initial_reward = tf.constant(0.)\n initial_info = StepOutputInfo(tf.constant(0.), tf.constant(0))\n initial_done = tf.constant(True)\n initial_observation = self._env.initial()\n\n initial_output = StepOutput(initial_reward, initial_info, initial_done,\n initial_observation)\n\n # Control dependency to make sure the next step can't be taken before the\n # initial output has been read from the environment.\n with tf.control_dependencies(nest.flatten(initial_output)):\n initial_flow = tf.constant(0, dtype=tf.int64)\n initial_state = (initial_flow, initial_info)\n return initial_output, initial_state\n\n def step(self, action, state):\n \"\"\"Takes a step in the environment.\n\n Args:\n action: An action tensor suitable for the underlying environment.\n state: The environment state from the last step or initial state.\n\n Returns:\n A tuple of (`StepOutput`, environment state). The environment state should\n be passed in to the next invocation of `step` and should not be used in\n any other way. On episode end (i.e. `done` is True), the returned reward\n should be included in the sum of rewards for the ending episode and not\n part of the next episode.\n \"\"\"\n with tf.name_scope('flow_environment_step'):\n flow, info = nest.map_structure(tf.convert_to_tensor, state)\n\n # Make sure the previous step has been executed before running the next\n # step.\n with tf.control_dependencies([flow]):\n reward, done, observation = self._env.step(action)\n\n with tf.control_dependencies(nest.flatten(observation)):\n new_flow = tf.add(flow, 1)\n\n # When done, include the reward in the output info but not in the\n # state for the next step.\n new_info = StepOutputInfo(info.episode_return + reward,\n info.episode_step + 1)\n new_state = new_flow, nest.map_structure(\n lambda a, b: tf.where(done, a, b),\n StepOutputInfo(tf.constant(0.), tf.constant(0)), new_info)\n\n output = StepOutput(reward, new_info, done, observation)\n return output, new_state\n\n\nclass StreetLearnImpalaAdapter(streetlearn.StreetLearn):\n def __init__(self, dataset_path, config, game):\n super(StreetLearnImpalaAdapter, self).__init__(dataset_path, config, game)\n self.reset()\n\n def initial(self):\n \"\"\"Returns the original observation.\"\"\"\n super(StreetLearnImpalaAdapter, self).step([0.0, 0.0, 0.0, 0.0])\n observation = self._reshape_observation(self.observation())\n return observation\n\n def step(self, action):\n \"\"\"Takes a step in the environment.\n\n Args:\n action: a 1d array containing a combination of actions.\n Returns:\n reward: float value.\n done: boolean indicator.\n observation: observation at the last step.\n \"\"\"\n (observation, reward, done, _) = super(\n StreetLearnImpalaAdapter, self).step(action)\n reward = np.array(reward, dtype=np.float32)\n observation = self._reshape_observation(observation)\n return reward, done, observation\n\n def _reshape_observation(self, observation):\n return [\n np.transpose(np.reshape(observation['view_image'],\n [3, FLAGS.height, FLAGS.width]),\n axes=(1, 2, 0)),\n np.transpose(np.reshape(observation['graph_image'],\n [3, FLAGS.graph_height, FLAGS.graph_width]),\n axes=(1, 2, 0)),\n observation['latlng'],\n observation['target_latlng'],\n observation['yaw'],\n observation['yaw_label'],\n observation['latlng_label'],\n observation['target_latlng_label'],\n ]\n\n @staticmethod\n def _tensor_specs(method_name, unused_kwargs, constructor_kwargs):\n \"\"\"Returns a nest of `TensorSpec` with the method's output specification.\"\"\"\n observation_spec = [\n tf.contrib.framework.TensorSpec(\n [FLAGS.height, FLAGS.width, 3], tf.uint8),\n tf.contrib.framework.TensorSpec(\n [FLAGS.graph_height, FLAGS.graph_width, 3], tf.uint8),\n tf.contrib.framework.TensorSpec(\n [2,], tf.float64),\n tf.contrib.framework.TensorSpec(\n [2,], tf.float64),\n tf.contrib.framework.TensorSpec(\n [], tf.float64),\n tf.contrib.framework.TensorSpec(\n [], tf.uint8),\n tf.contrib.framework.TensorSpec(\n [], tf.int32),\n tf.contrib.framework.TensorSpec(\n [], tf.int32),\n ]\n\n if method_name == 'initial':\n return observation_spec\n elif method_name == 'step':\n return (\n tf.contrib.framework.TensorSpec([], tf.float32),\n tf.contrib.framework.TensorSpec([], tf.bool),\n observation_spec,\n )\n\n\ndef build_actor(agent, env, level_name, action_set):\n \"\"\"Builds the actor loop.\"\"\"\n # Initial values.\n initial_env_output, initial_env_state = env.initial()\n initial_agent_state = agent.initial_state(1)\n initial_action = tf.zeros([1], dtype=tf.int32)\n dummy_agent_output, _ = agent(\n (initial_action,\n nest.map_structure(lambda t: tf.expand_dims(t, 0), initial_env_output)),\n initial_agent_state)\n initial_agent_output = nest.map_structure(\n lambda t: tf.zeros(t.shape, t.dtype), dummy_agent_output)\n\n # All state that needs to persist across training iterations. This includes\n # the last environment output, agent state and last agent output. These\n # variables should never go on the parameter servers.\n def create_state(t):\n # Creates a unique variable scope to ensure the variable name is unique.\n with tf.variable_scope(None, default_name='state'):\n return tf.get_local_variable(t.op.name, initializer=t, use_resource=True)\n\n persistent_state = nest.map_structure(\n create_state, (initial_env_state, initial_env_output, initial_agent_state,\n initial_agent_output))\n\n def step(input_, unused_i):\n \"\"\"Steps through the agent and the environment.\"\"\"\n env_state, env_output, agent_state, agent_output = input_\n\n # Run agent.\n action = agent_output[0]\n batched_env_output = nest.map_structure(lambda t: tf.expand_dims(t, 0),\n env_output)\n agent_output, agent_state = agent((action, batched_env_output), agent_state)\n\n # Convert action index to the native action.\n action = agent_output[0][0]\n raw_action = tf.gather(action_set, action)\n\n env_output, env_state = env.step(raw_action, env_state)\n\n return env_state, env_output, agent_state, agent_output\n\n # Run the unroll. `read_value()` is needed to make sure later usage will\n # return the first values and not a new snapshot of the variables.\n first_values = nest.map_structure(lambda v: v.read_value(), persistent_state)\n _, first_env_output, first_agent_state, first_agent_output = first_values\n\n # Use scan to apply `step` multiple times, therefore unrolling the agent\n # and environment interaction for `FLAGS.unroll_length`. `tf.scan` forwards\n # the output of each call of `step` as input of the subsequent call of `step`.\n # The unroll sequence is initialized with the agent and environment states\n # and outputs as stored at the end of the previous unroll.\n # `output` stores lists of all states and outputs stacked along the entire\n # unroll. Note that the initial states and outputs (fed through `initializer`)\n # are not in `output` and will need to be added manually later.\n output = tf.scan(step, tf.range(FLAGS.unroll_length), first_values)\n _, env_outputs, _, agent_outputs = output\n\n # Update persistent state with the last output from the loop.\n assign_ops = nest.map_structure(lambda v, t: v.assign(t[-1]),\n persistent_state, output)\n\n # The control dependency ensures that the final agent and environment states\n # and outputs are stored in `persistent_state` (to initialize next unroll).\n with tf.control_dependencies(nest.flatten(assign_ops)):\n # Remove the batch dimension from the agent state/output.\n first_agent_state = nest.map_structure(lambda t: t[0], first_agent_state)\n first_agent_output = nest.map_structure(lambda t: t[0], first_agent_output)\n agent_outputs = nest.map_structure(lambda t: t[:, 0], agent_outputs)\n\n # Concatenate first output and the unroll along the time dimension.\n full_agent_outputs, full_env_outputs = nest.map_structure(\n lambda first, rest: tf.concat([[first], rest], 0),\n (first_agent_output, first_env_output), (agent_outputs, env_outputs))\n\n output = ActorOutput(\n level_name=level_name, agent_state=first_agent_state,\n env_outputs=full_env_outputs, agent_outputs=full_agent_outputs)\n\n # No backpropagation should be done here.\n return nest.map_structure(tf.stop_gradient, output)\n\n\ndef compute_baseline_loss(advantages):\n # Loss for the baseline, summed over the time dimension.\n # Multiply by 0.5 to match the standard update rule:\n # d(loss) / d(baseline) = advantage\n return .5 * tf.reduce_sum(tf.square(advantages))\n\n\ndef compute_entropy_loss(logits):\n policy = tf.nn.softmax(logits)\n log_policy = tf.nn.log_softmax(logits)\n entropy_per_timestep = tf.reduce_sum(-policy * log_policy, axis=-1)\n return -tf.reduce_sum(entropy_per_timestep)\n\n\ndef compute_classification_loss(logits, labels):\n classification_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(\n logits=logits, labels=labels)\n return tf.reduce_sum(classification_loss)\n\n\ndef compute_policy_gradient_loss(logits, actions, advantages):\n cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(\n labels=actions, logits=logits)\n advantages = tf.stop_gradient(advantages)\n policy_gradient_loss_per_timestep = cross_entropy * advantages\n return tf.reduce_sum(policy_gradient_loss_per_timestep)\n\n\ndef plot_logits_2d(logits, num_x, num_y):\n \"\"\"Plot logits as 2D images.\"\"\"\n logits_2d = tf.reshape(logits, shape=[-1, num_y, num_x])\n logits_2d = tf.expand_dims(tf.expand_dims(logits_2d[:, ::-1, :], 1), -1)\n return logits_2d\n\n\ndef build_learner(agent, agent_state, env_outputs, agent_outputs):\n \"\"\"Builds the learner loop.\n\n Args:\n agent: A snt.RNNCore module outputting `AgentOutput` named tuples, with an\n `unroll` call for computing the outputs for a whole trajectory.\n agent_state: The initial agent state for each sequence in the batch.\n env_outputs: A `StepOutput` namedtuple where each field is of shape\n [T+1, ...].\n agent_outputs: An `AgentOutput` namedtuple where each field is of shape\n [T+1, ...].\n\n Returns:\n A tuple of (done, infos, and environment frames) where\n the environment frames tensor causes an update.\n \"\"\"\n learner_outputs, _ = agent.unroll(agent_outputs.action, env_outputs,\n agent_state)\n\n # Use last baseline value (from the value function) to bootstrap.\n bootstrap_value = learner_outputs.baseline[-1]\n\n # At this point, the environment outputs at time step `t` are the inputs that\n # lead to the learner_outputs at time step `t`. After the following shifting,\n # the actions in agent_outputs and learner_outputs at time step `t` is what\n # leads to the environment outputs at time step `t`.\n agent_outputs = nest.map_structure(lambda t: t[1:], agent_outputs)\n rewards, infos, done, observations = nest.map_structure(\n lambda t: t[1:], env_outputs)\n learner_outputs = nest.map_structure(lambda t: t[:-1], learner_outputs)\n observation_names = FLAGS.observations.split(';')\n\n if FLAGS.reward_clipping == 'abs_one':\n clipped_rewards = tf.clip_by_value(rewards, -1, 1)\n elif FLAGS.reward_clipping == 'soft_asymmetric':\n squeezed = tf.tanh(rewards / 5.0)\n # Negative rewards are given less weight than positive rewards.\n clipped_rewards = tf.where(rewards < 0, .3 * squeezed, squeezed) * 5.\n\n discounts = tf.to_float(~done) * FLAGS.discounting\n\n # Compute V-trace returns and weights.\n # Note, this is put on the CPU because it's faster than on GPU. It can be\n # improved further with XLA-compilation or with a custom TensorFlow operation.\n with tf.device('/cpu'):\n vtrace_returns = vtrace.from_logits(\n behaviour_policy_logits=agent_outputs.policy_logits,\n target_policy_logits=learner_outputs.policy_logits,\n actions=agent_outputs.action,\n discounts=discounts,\n rewards=clipped_rewards,\n values=learner_outputs.baseline,\n bootstrap_value=bootstrap_value)\n\n # Compute loss as a weighted sum of the baseline loss, the policy gradient\n # loss and an entropy regularization term.\n rl_loss_policy_gradient = compute_policy_gradient_loss(\n learner_outputs.policy_logits, agent_outputs.action,\n vtrace_returns.pg_advantages)\n rl_loss_baseline = FLAGS.baseline_cost * compute_baseline_loss(\n vtrace_returns.vs - learner_outputs.baseline)\n rl_loss_entropy = FLAGS.entropy_cost * compute_entropy_loss(\n learner_outputs.policy_logits)\n total_loss = rl_loss_policy_gradient + rl_loss_baseline + rl_loss_entropy\n\n # Add auxiliary loss for heading prediction.\n if 'yaw_label' in observation_names:\n idx_yaw_label = observation_names.index('yaw_label')\n yaw_logits = learner_outputs.heading\n yaw_labels = tf.cast(observations[idx_yaw_label], dtype=tf.int32)\n heading_loss = FLAGS.heading_prediction_cost * compute_classification_loss(\n yaw_logits, yaw_labels)\n total_loss += heading_loss\n\n # Add auxiliary loss for XY position and XY target position prediction.\n if 'latlng_label' in observation_names:\n idx_latlng_label = observation_names.index('latlng_label')\n xy_logits = learner_outputs.xy\n xy_labels = tf.cast(observations[idx_latlng_label], dtype=tf.int32)\n xy_loss = FLAGS.xy_prediction_cost * compute_classification_loss(\n xy_logits, xy_labels)\n total_loss += xy_loss\n if 'target_latlng_label' in observation_names:\n idx_target_latlng_label = observation_names.index('target_latlng_label')\n target_xy_logits = learner_outputs.target_xy\n target_xy_labels = tf.cast(observations[idx_target_latlng_label],\n dtype=tf.int32)\n target_xy_loss = (\n FLAGS.target_xy_prediction_cost * compute_classification_loss(\n target_xy_logits, target_xy_labels))\n total_loss += target_xy_loss\n\n # Optimization\n num_env_frames = tf.train.get_global_step()\n learning_rate = tf.train.polynomial_decay(FLAGS.learning_rate, num_env_frames,\n FLAGS.total_environment_frames, 0)\n optimizer = tf.train.RMSPropOptimizer(learning_rate, FLAGS.decay,\n FLAGS.momentum, FLAGS.epsilon)\n train_op = optimizer.minimize(total_loss)\n\n # Merge updating the network and environment frames into a single tensor.\n with tf.control_dependencies([train_op]):\n num_env_frames_and_train = num_env_frames.assign_add(\n FLAGS.batch_size * FLAGS.unroll_length)\n\n # Adding a few summaries: RL losses and actions.\n tf.summary.scalar('learning_rate', learning_rate)\n tf.summary.scalar('rl_loss_policy_gradient',\n rl_loss_policy_gradient)\n tf.summary.scalar('rl_loss_baseline', rl_loss_baseline)\n tf.summary.scalar('rl_loss_entropy', rl_loss_entropy)\n if 'yaw_label' in observation_names:\n tf.summary.scalar('heading_loss', heading_loss)\n if 'latlng_label' in observation_names:\n tf.summary.scalar('xy_loss', xy_loss)\n if 'target_latlng_label' in observation_names:\n tf.summary.scalar('target_xy_loss', target_xy_loss)\n tf.summary.scalar('total_loss', total_loss)\n tf.summary.histogram('action', agent_outputs.action)\n\n # Adding a few summaries: agent's view and graph.\n idx_frame = observation_names.index('view_image')\n frame = observations[idx_frame]\n tf.summary.image('frame', frame[:3, 0, :, :, :])\n idx_graph = observation_names.index('graph_image')\n street_graph = observations[idx_graph]\n tf.summary.image('street_graph', street_graph[:3, 0, :, :, :])\n\n # Adding a few summaries: current and target lat/lng.\n idx_latlng = observation_names.index('latlng')\n latlng = observations[idx_latlng]\n tf.summary.histogram('current_lat', latlng[:, 0, 0])\n tf.summary.histogram('current_lng', latlng[:, 0, 1])\n idx_target_latlng = observation_names.index('target_latlng')\n target_latlng = observations[idx_target_latlng]\n target_latlng = tf.Print(target_latlng, [target_latlng])\n tf.summary.histogram('target_lat', target_latlng[:, 0, 0])\n tf.summary.histogram('target_lng', target_latlng[:, 0, 1])\n\n # Adding a few summaries: yaw.\n if 'yaw' in observation_names:\n idx_yaw = observation_names.index('yaw')\n yaw = observations[idx_yaw]\n tf.summary.histogram('yaw', yaw[:, 0])\n\n # Adding a few summaries: heading prediction.\n if 'yaw_label' in observation_names:\n img_yaw_labels = tf.expand_dims(\n tf.expand_dims(tf.one_hot(tf.cast(yaw_labels, tf.int32), 16), 1), -1)\n img_yaw_logits = tf.expand_dims(\n tf.expand_dims(tf.nn.softmax(tf.cast(yaw_logits, tf.float32)), 1), -1)\n tf.summary.image(\"yaw_labels\", img_yaw_labels[:, :, 0, :, :])\n tf.summary.image(\"yaw_logits\", img_yaw_logits[:, :, 0, :, :])\n\n # Adding a few summaries: XY position prediction.\n if 'latlng_label' in observation_names:\n img_xy_labels = plot_logits_2d(\n tf.one_hot(tf.cast(xy_labels[:, 0], tf.int32), 32*32), 32, 32)\n img_xy_logits = plot_logits_2d(\n tf.nn.softmax(tf.cast(xy_logits[:, 0, :], tf.float32)), 32, 32)\n tf.summary.image(\"xy_labels\", img_xy_labels[:, 0, :, :, :])\n tf.summary.image(\"xy_logits\", img_xy_logits[:, 0, :, :, :])\n\n # Adding a few summaries: XY position prediction.\n if 'target_latlng_label' in observation_names:\n img_target_xy_labels = plot_logits_2d(\n tf.one_hot(tf.cast(target_xy_labels[:, 0], tf.int32), 32*32), 32, 32)\n img_target_xy_logits = plot_logits_2d(\n tf.nn.softmax(tf.cast(target_xy_logits, tf.float32)), 32, 32)\n tf.summary.image(\"target_xy_labels\", img_target_xy_labels[:, 0, :, :, :])\n tf.summary.image(\"target_xy_logits\", img_target_xy_logits[:, 0, :, :, :])\n\n return done, infos, num_env_frames_and_train\n\n\ndef create_environment(level_name, seed, is_test=False):\n \"\"\"Creates an environment wrapped in a `FlowEnvironment`.\"\"\"\n observations = FLAGS.observations.split(';')\n tf.logging.info('Observations requested:')\n tf.logging.info(observations)\n config = {\n 'status_height': 0,\n 'width': FLAGS.width,\n 'height': FLAGS.height,\n 'graph_width': FLAGS.graph_width,\n 'graph_height': FLAGS.graph_height,\n 'graph_zoom': FLAGS.graph_zoom,\n 'game_name': FLAGS.game_name,\n 'goal_timeout': FLAGS.frame_cap,\n 'frame_cap': FLAGS.frame_cap,\n 'full_graph': (FLAGS.start_pano == ''),\n 'start_pano': FLAGS.start_pano,\n 'min_graph_depth': FLAGS.graph_depth,\n 'max_graph_depth': FLAGS.graph_depth,\n 'proportion_of_panos_with_coins':\n FLAGS.proportion_of_panos_with_coins,\n 'timestamp_start_curriculum': FLAGS.timestamp_start_curriculum,\n 'hours_curriculum_part_1': FLAGS.hours_curriculum_part_1,\n 'hours_curriculum_part_2': FLAGS.hours_curriculum_part_2,\n 'min_goal_distance_curriculum': FLAGS.min_goal_distance_curriculum,\n 'max_goal_distance_curriculum': FLAGS.max_goal_distance_curriculum,\n 'observations': observations,\n 'bbox_lat_min': FLAGS.bbox_lat_min,\n 'bbox_lat_max': FLAGS.bbox_lat_max,\n 'bbox_lng_min': FLAGS.bbox_lng_min,\n 'bbox_lng_max': FLAGS.bbox_lng_max,\n 'min_radius_meters': FLAGS.min_radius_meters,\n 'max_radius_meters': FLAGS.max_radius_meters,\n }\n\n config = default_config.ApplyDefaults(config)\n tf.logging.info(config)\n game = default_config.CreateGame(config['game_name'], config)\n dataset_path = FLAGS.dataset_paths + '/' + level_name\n tf.logging.info(dataset_path)\n p = py_process.PyProcess(\n StreetLearnImpalaAdapter, dataset_path, config, game)\n return FlowEnvironment(p.proxy)\n\n\[email protected]\ndef pin_global_variables(device):\n \"\"\"Pins global variables to the specified device.\"\"\"\n\n def getter(getter, *args, **kwargs):\n var_collections = kwargs.get('collections', None)\n if var_collections is None:\n var_collections = [tf.GraphKeys.GLOBAL_VARIABLES]\n if tf.GraphKeys.GLOBAL_VARIABLES in var_collections:\n with tf.device(device):\n return getter(*args, **kwargs)\n else:\n return getter(*args, **kwargs)\n\n with tf.variable_scope('', custom_getter=getter) as vs:\n yield vs\n\n\ndef create_agent(num_actions):\n \"\"\"Create the agent.\"\"\"\n assert FLAGS.agent in ['goal_nav_agent', 'city_nav_agent']\n if FLAGS.agent == 'city_nav_agent':\n agent = city_nav_agent.CityNavAgent(\n num_actions, observation_names=FLAGS.observations)\n else:\n agent = goal_nav_agent.GoalNavAgent(\n num_actions, observation_names=FLAGS.observations)\n return agent\n\n\ndef train(action_set, level_names):\n \"\"\"Train.\"\"\"\n\n if is_single_machine():\n local_job_device = ''\n shared_job_device = ''\n is_actor_fn = lambda i: True\n is_learner = True\n global_variable_device = '/gpu'\n server = tf.train.Server.create_local_server()\n server_target = FLAGS.master\n filters = []\n else:\n local_job_device = '/job:%s/task:%d' % (FLAGS.job_name, FLAGS.task)\n shared_job_device = '/job:learner/task:0'\n is_actor_fn = lambda i: FLAGS.job_name == 'actor' and i == FLAGS.task\n is_learner = FLAGS.job_name == 'learner'\n\n # Placing the variable on CPU, makes it cheaper to send it to all the\n # actors. Continual copying the variables from the GPU is slow.\n global_variable_device = shared_job_device + '/cpu'\n cluster = tf.train.ClusterSpec({\n 'actor': ['localhost:%d' % (8001 + i) for i in range(FLAGS.num_actors)],\n 'learner': ['localhost:8000']\n })\n server = tf.train.Server(cluster, job_name=FLAGS.job_name,\n task_index=FLAGS.task)\n server_target = server.target\n filters = [shared_job_device, local_job_device]\n\n # Only used to find the actor output structure.\n with tf.Graph().as_default():\n agent = create_agent(len(action_set))\n env = create_environment(level_names[0], seed=1)\n structure = build_actor(agent, env, level_names[0], action_set)\n flattened_structure = nest.flatten(structure)\n dtypes = [t.dtype for t in flattened_structure]\n shapes = [t.shape.as_list() for t in flattened_structure]\n\n with tf.Graph().as_default(), \\\n tf.device(local_job_device + '/cpu'), \\\n pin_global_variables(global_variable_device):\n tf.set_random_seed(FLAGS.seed) # Makes initialization deterministic.\n\n # Create Queue and Agent on the learner.\n with tf.device(shared_job_device):\n queue = tf.FIFOQueue(1, dtypes, shapes, shared_name='buffer')\n agent = create_agent(len(action_set))\n\n # Build actors and ops to enqueue their output.\n enqueue_ops = []\n for i in range(FLAGS.num_actors):\n if is_actor_fn(i):\n level_name = level_names[i % len(level_names)]\n tf.logging.info('Creating actor %d with level %s', i, level_name)\n env = create_environment(level_name, seed=i + 1)\n actor_output = build_actor(agent, env, level_name, action_set)\n with tf.device(shared_job_device):\n enqueue_ops.append(queue.enqueue(nest.flatten(actor_output)))\n\n # If running in a single machine setup, run actors with QueueRunners\n # (separate threads).\n if is_learner and enqueue_ops:\n tf.train.add_queue_runner(tf.train.QueueRunner(queue, enqueue_ops))\n\n # Build learner.\n if is_learner:\n # Create global step, which is the number of environment frames processed.\n tf.get_variable(\n 'num_environment_frames',\n initializer=tf.zeros_initializer(),\n shape=[],\n dtype=tf.int64,\n trainable=False,\n collections=[tf.GraphKeys.GLOBAL_STEP, tf.GraphKeys.GLOBAL_VARIABLES])\n\n # Create batch (time major) and recreate structure.\n dequeued = queue.dequeue_many(FLAGS.batch_size)\n dequeued = nest.pack_sequence_as(structure, dequeued)\n\n def make_time_major(s):\n return nest.map_structure(\n lambda t: tf.transpose(t, [1, 0] + list(range(t.shape.ndims))[2:]),\n s)\n\n dequeued = dequeued._replace(\n env_outputs=make_time_major(dequeued.env_outputs),\n agent_outputs=make_time_major(dequeued.agent_outputs))\n\n with tf.device('/gpu'):\n # Using StagingArea allows us to prepare the next batch and send it to\n # the GPU while we're performing a training step. This adds up to 1 step\n # policy lag.\n flattened_output = nest.flatten(dequeued)\n area = tf.contrib.staging.StagingArea(\n [t.dtype for t in flattened_output],\n [t.shape for t in flattened_output])\n stage_op = area.put(flattened_output)\n\n data_from_actors = nest.pack_sequence_as(structure, area.get())\n\n # Unroll agent on sequence, create losses and update ops.\n output = build_learner(agent, data_from_actors.agent_state,\n data_from_actors.env_outputs,\n data_from_actors.agent_outputs)\n\n # Create MonitoredSession (to run the graph, checkpoint and log).\n tf.logging.info('Creating MonitoredSession, is_chief %s', is_learner)\n # config = tf.ConfigProto(allow_soft_placement=True)\n config = tf.ConfigProto(allow_soft_placement=True, device_filters=filters)\n with tf.train.MonitoredTrainingSession(\n server_target,\n is_chief=is_learner,\n checkpoint_dir=FLAGS.logdir,\n save_checkpoint_secs=600,\n save_summaries_secs=30,\n log_step_count_steps=50000,\n config=config,\n hooks=[py_process.PyProcessHook()]) as session:\n\n if is_learner:\n tf.logging.info('is_learner')\n # Logging.\n level_returns = {level_name: [] for level_name in level_names}\n summary_writer = tf.summary.FileWriterCache.get(FLAGS.logdir)\n\n # Prepare data for first run.\n session.run_step_fn(\n lambda step_context: step_context.session.run(stage_op))\n\n # Execute learning and track performance.\n num_env_frames_v = 0\n while num_env_frames_v < FLAGS.total_environment_frames:\n tf.logging.info(num_env_frames_v)\n level_names_v, done_v, infos_v, num_env_frames_v, _ = session.run(\n (data_from_actors.level_name,) + output + (stage_op,))\n level_names_v = np.repeat([level_names_v], done_v.shape[0], 0)\n\n for level_name, episode_return, episode_step in zip(\n level_names_v[done_v],\n infos_v.episode_return[done_v],\n infos_v.episode_step[done_v]):\n episode_frames = episode_step\n\n tf.logging.info('Level: %s Episode return: %f',\n level_name, episode_return)\n\n summary = tf.summary.Summary()\n summary.value.add(tag=level_name + '/episode_return',\n simple_value=episode_return)\n summary.value.add(tag=level_name + '/episode_frames',\n simple_value=episode_frames)\n summary_writer.add_summary(summary, num_env_frames_v)\n\n else:\n tf.logging.info('actor')\n # Execute actors (they just need to enqueue their output).\n while True:\n session.run(enqueue_ops)\n\n\ndef test(action_set, level_names):\n \"\"\"Test.\"\"\"\n\n level_returns = {level_name: [] for level_name in level_names}\n with tf.Graph().as_default():\n agent = create_agent(len(action_set))\n outputs = {}\n for level_name in level_names:\n env = create_environment(level_name, seed=1, is_test=True)\n outputs[level_name] = build_actor(agent, env, level_name, action_set)\n\n with tf.train.SingularMonitoredSession(\n checkpoint_dir=FLAGS.logdir,\n hooks=[py_process.PyProcessHook()]) as session:\n for level_name in level_names:\n tf.logging.info('Testing level: %s', level_name)\n while True:\n done_v, infos_v = session.run((\n outputs[level_name].env_outputs.done,\n outputs[level_name].env_outputs.info\n ))\n returns = level_returns[level_name]\n returns.extend(infos_v.episode_return[1:][done_v[1:]])\n\n if len(returns) >= FLAGS.test_num_episodes:\n tf.logging.info('Mean episode return: %f', np.mean(returns))\n break\n\n\ndef main(_):\n tf.logging.set_verbosity(tf.logging.INFO)\n\n action_set = streetlearn.get_action_set(FLAGS.action_set,\n FLAGS.rotation_speed)\n tf.logging.info(action_set)\n level_names = FLAGS.level_names.split(',')\n tf.logging.info(level_names)\n\n if FLAGS.mode == 'train':\n train(action_set, level_names)\n else:\n test(action_set, level_names)\n\n\nif __name__ == '__main__':\n tf.app.run()\n" }, { "alpha_fraction": 0.7101593613624573, "alphanum_fraction": 0.724103569984436, "avg_line_length": 32.46666717529297, "blob_id": "4d22b1716f19eeac4ac1847d4f8a7d1a371e16e6", "content_id": "3aec0b0e58f9bed5252a21b9d477e47f7b352b34", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2008, "license_type": "permissive", "max_line_length": 75, "num_lines": 60, "path": "/streetlearn/engine/math_util_test.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/math_util.h\"\n\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n\nnamespace streetlearn {\nnamespace math {\nnamespace {\n\nusing ::testing::Eq;\n\ntemplate <typename T>\nclass MathUtilTest : public ::testing::Test {};\nTYPED_TEST_SUITE_P(MathUtilTest);\n\nTYPED_TEST_P(MathUtilTest, ClampTest) {\n constexpr TypeParam kLow = static_cast<TypeParam>(7);\n constexpr TypeParam kHigh = static_cast<TypeParam>(42);\n constexpr TypeParam kTestValue = static_cast<TypeParam>(33);\n\n EXPECT_THAT(Clamp(kLow, kHigh, kTestValue), Eq(kTestValue));\n EXPECT_THAT(Clamp(kLow, kHigh, kLow), Eq(kLow));\n EXPECT_THAT(Clamp(kLow, kHigh, kHigh), Eq(kHigh));\n EXPECT_THAT(Clamp(kLow, kHigh, kLow - 1), Eq(kLow));\n EXPECT_THAT(Clamp(kLow, kHigh, kHigh + 1), Eq(kHigh));\n\n EXPECT_THAT(Clamp(kLow, kLow, kLow - 1), Eq(kLow));\n EXPECT_THAT(Clamp(kLow, kLow, kLow), Eq(kLow));\n EXPECT_THAT(Clamp(kLow, kLow, kLow + 1), Eq(kLow));\n}\n\nTEST(StreetLearn, AngleConversionsTest) {\n EXPECT_DOUBLE_EQ(DegreesToRadians(0), 0);\n EXPECT_DOUBLE_EQ(DegreesToRadians(90), M_PI / 2);\n EXPECT_DOUBLE_EQ(DegreesToRadians(-90), -M_PI / 2);\n EXPECT_DOUBLE_EQ(DegreesToRadians(180), M_PI);\n}\n\nREGISTER_TYPED_TEST_SUITE_P(MathUtilTest, ClampTest);\n\nusing Types = ::testing::Types<int, float, double>;\nINSTANTIATE_TYPED_TEST_SUITE_P(TpedMathUtilTests, MathUtilTest, Types);\n\n} // namespace\n} // namespace math\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.6787620186805725, "alphanum_fraction": 0.6798292398452759, "avg_line_length": 26.558822631835938, "blob_id": "7fc85720677b7c10709a222e4b8299483e24f865", "content_id": "99dd44fcf3cafdca1d569aea1c0bd2a5743c1158", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 937, "license_type": "permissive", "max_line_length": 65, "num_lines": 34, "path": "/streetlearn/python/environment/thumbnail_helper.py", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "\"\"\"Thumbnail helper class used in Taxi and Streetlang levels.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\n\nclass ThumbnailHelper(object):\n \"\"\"Thumbnail helper class.\"\"\"\n\n def __init__(self):\n self._width = None\n self._height = None\n\n def get_thumbnail(self, streetlearn, pano_id, heading):\n \"\"\"Fetch the thumbnail from the environment.\n\n Args:\n streetlearn: a streetlearn instance.\n pano_id: Pano id of the thumbnail.\n heading: Heading in degrees for the thumbnail.\n\n Returns:\n Thumbnail ndarray.\n \"\"\"\n observation = streetlearn.goto(pano_id, heading)\n thumbnail = observation['view_image']\n if not self._width:\n self._width = streetlearn.config['width']\n self._height = streetlearn.config['height']\n thumbnail = thumbnail.reshape([3, self._width, self._height])\n return thumbnail\n" }, { "alpha_fraction": 0.7365813255310059, "alphanum_fraction": 0.7452518343925476, "avg_line_length": 33.599998474121094, "blob_id": "4a2b4d788f50d476f4e3b0181574881c719ca56c", "content_id": "06d029f904f74d08d005c999a2fd0c41b50c536a", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2422, "license_type": "permissive", "max_line_length": 78, "num_lines": 70, "path": "/streetlearn/engine/graph_region_mapper.h", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#ifndef THIRD_PARTY_STREETLEARN_ENGINE_GRAPH_REGION_MAPPER_H_\n#define THIRD_PARTY_STREETLEARN_ENGINE_GRAPH_REGION_MAPPER_H_\n\n#include \"streetlearn/engine/vector.h\"\n#include \"s2/s2latlng.h\"\n#include \"s2/s2latlng_rect.h\"\n\nnamespace streetlearn {\n\n// Helper class for calculating mappings from graph to screen regions and\n// between lat/lng and screen co-ordinates.\nclass GraphRegionMapper {\n public:\n explicit GraphRegionMapper(const Vector2_i& screen_size)\n : screen_size_(screen_size) {}\n\n // GraphRegionManager is neither copyable nor movable.\n GraphRegionMapper(const GraphRegionMapper&) = delete;\n GraphRegionMapper& operator=(const GraphRegionMapper&) = delete;\n\n // Sets graph region and the display margin required.\n void SetGraphBounds(const S2LatLngRect& graph_bounds);\n\n // Sets the bounds of the current view around the centre point.\n void SetCurrentBounds(double zoom, const S2LatLng& image_centre);\n\n // Re-centers the current view.\n void ResetCurrentBounds(double zoom);\n\n // Maps the lat/lng provided to screen coordinates.\n Vector2_d MapToScreen(double lat, double lng) const;\n\n // Maps the lat/lng to coordinates in the buffer of the given dimensions.\n Vector2_d MapToBuffer(double lat, double lng, int image_width,\n int image_height) const;\n\n private:\n // Calculates the margin around the graph region to fit the screen shape.\n void CalculateSceneMargin();\n\n // The size of the screen into which to render.\n Vector2_i screen_size_;\n\n // The bounding lat/lng of the graph.\n S2LatLngRect graph_bounds_;\n\n // The bounds of the current display.\n S2LatLngRect current_bounds_;\n\n // The margin to leave around the map to fit the aspect ratio of the screen.\n S2LatLng margin_;\n};\n\n} // namespace streetlearn\n\n#endif // THIRD_PARTY_STREETLEARN_ENGINE_GRAPH_REGION_MAPPER_H_\n" }, { "alpha_fraction": 0.674647867679596, "alphanum_fraction": 0.6777898073196411, "avg_line_length": 38.27659606933594, "blob_id": "69cb87dbc4f757d668a280bfa0ada8bb9636e408", "content_id": "48469908d6a0d5b45101823a5d606f31e45abf83", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9230, "license_type": "permissive", "max_line_length": 80, "num_lines": 235, "path": "/streetlearn/python/environment/courier_game.py", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "# Copyright 2018 Google LLC.\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\"\"\"StreetLearn level for the courier task with random goals/targets.\n\nIn this environment, the agent receives a reward for every coin it collects and\nan extra reward for locating the goal pano.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl import logging\nimport numpy as np\nimport six\n\nfrom streetlearn.python.environment import coin_game\n\n\nclass CourierGame(coin_game.CoinGame):\n \"\"\"Coin game that gives extra reward for finding the goal pano. A courier goal\n is randomly selected from panos in the graph. On success or timeout, a new\n goal is chosen. The episode ends after a fixed episode length.\n \"\"\"\n\n def __init__(self, config):\n \"\"\"Constructor.\n\n This coin game gives extra reward for finding the goal pano, and resets the\n goal once the goal has been found (or on timeout). Panos can be assigned\n rewards (coins) randomly and the agent will receive the reward the first\n time they visit these panos.\n\n Args:\n config: config dict of various settings.\n \"\"\"\n super(CourierGame, self).__init__(config)\n self._reward_current_goal = config['max_reward_per_goal']\n self._min_radius_meters = config['min_radius_meters']\n self._max_radius_meters = config['max_radius_meters']\n self._goal_timeout = config['goal_timeout']\n self._colors['goal'] = config['color_for_goal']\n self._colors['shortest_path'] = config['color_for_shortest_path']\n\n self._num_steps_this_goal = 0\n self._min_distance_reached = np.finfo(np.float32).max\n self._initial_distance_to_goal = np.finfo(np.float32).max\n self._current_goal_id = None\n self._visited_panos = set()\n self._shortest_path = {}\n self._timed_out = False\n\n def on_reset(self, streetlearn):\n \"\"\"Gets called after StreetLearn:reset().\n\n Selects a random pano as goal destination.\n\n If there are any coins, clears the set of touched panos and randomly\n generates reward-yielding coins and populates pano_id_to_color.\n\n Args:\n streetlearn: a streetlearn instance.\n Returns:\n A newly populated pano_id_to_color dictionary.\n \"\"\"\n # Populate the list of panos and assign optional coins to panos.\n pano_id_to_color = super(CourierGame, self).on_reset(streetlearn)\n\n # Assign the goal location to one of the panos.\n self._pick_random_goal(streetlearn)\n self._num_steps_this_goal = 0\n return pano_id_to_color\n\n @property\n def goal_id(self):\n \"\"\"Returns the ID of the goal Pano.\"\"\"\n return self._current_goal_id\n\n def get_reward(self, streetlearn):\n \"\"\"Looks at current_pano_id and collects any reward found there.\n\n Args:\n streetlearn: A streetlearn instance.\n Returns:\n reward: the reward from the last step.\n \"\"\"\n # If we have exceeded the maximum steps to look for a goal, reset the goal.\n if self._num_steps_this_goal > self._goal_timeout:\n logging.info('%d Courier target TIMEOUT (%d steps)',\n streetlearn.frame_count, self._num_steps_this_goal)\n #self._timed_out = True\n self._num_steps_this_goal = 0\n self._pick_random_goal(streetlearn)\n\n reward = self._compute_reward(streetlearn)\n\n # If we have found the goal, set a new one.\n if reward >= self._reward_current_goal:\n logging.info('%d Courier target FOUND (%d steps)',\n streetlearn.frame_count, self._num_steps_this_goal)\n self._num_steps_this_goal = 0\n self._pick_random_goal(streetlearn)\n\n # Give additional reward if current pano has a coin.\n if streetlearn.current_pano_id in self._coin_pano_id_set:\n reward += self._reward_per_coin\n self._coin_pano_id_set.remove(streetlearn.current_pano_id)\n\n self._num_steps_this_goal += 1\n return reward\n\n def get_info(self, streetlearn):\n \"\"\"\"Returns current information about the state of the environment.\n\n Args:\n streetlearn: a StreetLearn instance.\n Returns:\n info: information from the environment at the last step.\n \"\"\"\n info = super(CourierGame, self).get_info(streetlearn)\n info['num_steps_this_goal'] = self._num_steps_this_goal\n info['current_goal_id'] = self._current_goal_id\n info['min_distance_reached'] = self._min_distance_reached\n info['initial_distance_to_goal'] = self._initial_distance_to_goal\n info['reward_current_goal'] = self._reward_current_goal\n next_pano_id = self._panos_to_goal[streetlearn.current_pano_id]\n info['next_pano_id'] = next_pano_id\n bearing_to_next_pano = streetlearn.engine.GetPanoBearing(\n streetlearn.current_pano_id, next_pano_id) - streetlearn.engine.GetYaw()\n info['bearing_to_next_pano'] = (bearing_to_next_pano + 180) % 360 - 180\n return info\n\n def done(self):\n \"\"\"Returns a flag indicating the end of the current episode.\n\n This game ends only at the end of the episode or if the goal times out.\n During a single episode, every time a goal is found, a new one is chosen,\n until the time runs out.\n \"\"\"\n if self._timed_out:\n self._timed_out = False\n return True\n else:\n return False\n\n def _sample_random_goal(self, streetlearn):\n \"\"\"Randomly sets a new pano for the current goal.\n\n Args:\n streetlearn: The StreetLearn environment.\n \"\"\"\n goals = [goal for goal in streetlearn.graph\n if ((goal != self._current_goal_id) and\n (goal != streetlearn.current_pano_id))]\n self._current_goal_id = np.random.choice(goals)\n self._min_distance_reached = streetlearn.engine.GetPanoDistance(\n streetlearn.current_pano_id, self._current_goal_id)\n self._initial_distance_to_goal = self._min_distance_reached\n\n def _pick_random_goal(self, streetlearn):\n \"\"\"Randomly sets a new pano for the current goal.\n\n Args:\n streetlearn: The StreetLearn environment.\n \"\"\"\n self._visited_panos.clear()\n self._sample_random_goal(streetlearn)\n logging.info('%d CourierGame: New goal chosen', streetlearn.frame_count)\n logging.info('%d New goal id: %s ', streetlearn.frame_count, self.goal_id)\n logging.info('%d Distance to goal: %f', streetlearn.frame_count,\n self._min_distance_reached)\n # Compute the extended graph and shortest path to goal to estimate\n # the reward to give to the agent.\n shortest_path, num_panos = self._shortest_paths(\n streetlearn, self._current_goal_id, streetlearn.current_pano_id)\n self._reward_current_goal = num_panos\n logging.info('%d Reward for the current goal depends on #panos to goal: %d',\n streetlearn.frame_count, self._reward_current_goal)\n # Decorate the graph.\n self._pano_id_to_color = {coin_pano_id: self._colors['coin']\n for coin_pano_id in self._coin_pano_id_set}\n self._update_pano_id_to_color()\n for pano_id in six.iterkeys(shortest_path):\n self._pano_id_to_color[pano_id] = self._colors['shortest_path']\n self._pano_id_to_color[self.goal_id] = self._colors['goal']\n\n def _compute_reward(self, streetlearn):\n \"\"\"Reward is a piecewise linear function of distance to the goal.\n\n If agent is greater than max_radius_meters from the goal, reward is 0. If\n agent is less than min_radius_reters, reward is max_reward_per_goal. Between\n min and max radius the reward is linear between 0 and max_reward_per_goal.\n\n Args:\n streetlearn: The StreetLearn environment.\n Returns:\n The reward for the current step.\n \"\"\"\n # Do not give rewards for already visited panos.\n reward = 0\n if streetlearn.current_pano_id in self._visited_panos:\n return reward\n\n # Mark the pano as visited and compute distance to goal.\n self._visited_panos.add(streetlearn.current_pano_id)\n distance_to_goal = streetlearn.engine.GetPanoDistance(\n streetlearn.current_pano_id, self.goal_id)\n if distance_to_goal < self._min_radius_meters:\n # Have we reached the goal?\n reward = self._reward_current_goal\n logging.info('%d Reached goal, distance_to_goal=%s, reward=%s',\n streetlearn.frame_count, distance_to_goal, reward)\n else:\n if distance_to_goal < self._max_radius_meters:\n # Early reward shaping.\n if distance_to_goal < self._min_distance_reached:\n reward = (self._reward_current_goal *\n (self._max_radius_meters - distance_to_goal) /\n (self._max_radius_meters - self._min_radius_meters))\n self._min_distance_reached = distance_to_goal\n logging.info('%d Distance_to_goal=%f, reward=%d',\n streetlearn.frame_count, distance_to_goal, reward)\n\n return reward\n" }, { "alpha_fraction": 0.6203879117965698, "alphanum_fraction": 0.6276797652244568, "avg_line_length": 34.71354293823242, "blob_id": "782a2fb4451ec5a57ccd64b5cc32dcf780908d53", "content_id": "eae6d5d1957c2d08d7b1dd1bc0173ceddad012f2", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6857, "license_type": "permissive", "max_line_length": 80, "num_lines": 192, "path": "/streetlearn/engine/graph_image_cache.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/graph_image_cache.h\"\n\n#include <cmath>\n#include <string>\n\n#include \"streetlearn/engine/logging.h\"\n#include \"absl/container/node_hash_set.h\"\n#include <cairo/cairo.h>\n#include \"streetlearn/engine/cairo_util.h\"\n#include \"streetlearn/engine/color.h\"\n#include \"streetlearn/engine/math_util.h\"\n#include \"streetlearn/engine/pano_graph.h\"\n#include \"streetlearn/engine/vector.h\"\n\nnamespace streetlearn {\nnamespace {\n\nconstexpr int kMinZoom = 1;\nconstexpr int kMaxZoom = 32;\nconstexpr int kNodeZoomCutoff = 1;\nconstexpr int kNodeRadius = 2;\nconstexpr double kLineWidth = 0.5;\n\n// All color vectors interpreted as {r, g, b}\nColor BackColor() { return {0, 0, 0}; }\nColor NodeColor() { return {1, 1, 1}; }\nColor EdgeColor() { return {0.4, 0.4, 0.4}; }\n\n} // namespace\n\nbool GraphImageCache::InitCache(const PanoGraph& pano_graph,\n const S2LatLngRect& graph_bounds) {\n image_cache_.clear();\n region_manager_.SetGraphBounds(graph_bounds);\n if (!SetGraph(pano_graph)) {\n return false;\n }\n\n // Create and cache the top-level image.\n region_manager_.ResetCurrentBounds(1.0 /* zoom factor */);\n RenderLevel();\n return true;\n}\n\nvoid GraphImageCache::SetZoom(double zoom) {\n CHECK_GE(zoom, kMinZoom);\n CHECK_LE(zoom, kMaxZoom);\n current_zoom_ = zoom;\n\n // Create the image for the level if it's not in the cache.\n if (image_cache_.find(current_zoom_) == image_cache_.end()) {\n region_manager_.ResetCurrentBounds(current_zoom_);\n RenderLevel();\n }\n}\n\n// ImageView4_b GraphImageCache::Pixels(const S2LatLng& image_centre) {\nImageView4_b GraphImageCache::Pixels(const S2LatLng& image_centre) {\n auto it = image_cache_.find(current_zoom_);\n CHECK(it != image_cache_.end());\n auto& current_image = it->second;\n\n int image_width = screen_size_.x() * current_zoom_;\n int image_height = screen_size_.y() * current_zoom_;\n region_manager_.SetCurrentBounds(current_zoom_, image_centre);\n\n Vector2_d centre = region_manager_.MapToBuffer(image_centre.lat().degrees(),\n image_centre.lng().degrees(),\n image_width, image_height);\n\n // Constrain the limits to be within the image.\n int left = static_cast<int>(centre.x() - screen_size_.x() / 2);\n left = math::Clamp(0, image_width - screen_size_.x(), left);\n int top = static_cast<int>(centre.y() - screen_size_.y() / 2);\n top = math::Clamp(0, image_height - screen_size_.y(), top);\n\n return ImageView4_b(&current_image, left, top, screen_size_.x(),\n screen_size_.y());\n}\n\nvoid GraphImageCache::RenderLevel() {\n int image_width = screen_size_.x() * current_zoom_;\n int image_height = screen_size_.y() * current_zoom_;\n auto it =\n image_cache_.emplace(current_zoom_, Image4_b(image_width, image_height))\n .first;\n CairoRenderHelper cairo(it->second.pixel(0, 0), it->second.width(),\n it->second.height());\n\n // Draw the background.\n auto back_color = BackColor();\n cairo_set_source_rgb(cairo.context(), back_color.red, back_color.green,\n back_color.blue);\n cairo_paint(cairo.context());\n\n auto edge_color = EdgeColor();\n cairo_set_source_rgb(cairo.context(), edge_color.red, edge_color.green,\n edge_color.blue);\n cairo_set_line_width(cairo.context(), kLineWidth);\n\n // Draw all the edges.\n DrawEdges(image_width, image_height, cairo.context());\n\n // Draw highlighted nodes if sufficiently zoomed in.\n if (current_zoom_ >= kNodeZoomCutoff) {\n DrawNodes(image_width, image_height, cairo.context());\n }\n}\n\nvoid GraphImageCache::DrawEdges(int image_width, int image_height,\n cairo_t* context) {\n for (const auto& edge : graph_edges_) {\n Vector2_d start = region_manager_.MapToBuffer(edge.start.lat().degrees(),\n edge.start.lng().degrees(),\n image_width, image_height);\n Vector2_d end = region_manager_.MapToBuffer(edge.end.lat().degrees(),\n edge.end.lng().degrees(),\n image_width, image_height);\n\n cairo_move_to(context, start.x(), start.y());\n cairo_line_to(context, end.x(), end.y());\n cairo_stroke(context);\n }\n}\n\nvoid GraphImageCache::DrawNodes(int image_width, int image_height,\n cairo_t* context) {\n // Draw the nodes\n for (const auto& node : nodes_) {\n Vector2_d coords = region_manager_.MapToBuffer(node.second.lat().degrees(),\n node.second.lng().degrees(),\n image_width, image_height);\n auto iter = highlighted_nodes_.find(node.first);\n const Color& color =\n iter != highlighted_nodes_.end() ? iter->second : NodeColor();\n cairo_set_source_rgb(context, color.red, color.green, color.blue);\n cairo_arc(context, coords.x(), coords.y(), kNodeRadius, 0, 2 * M_PI);\n cairo_fill(context);\n }\n}\n\nbool GraphImageCache::SetGraph(const PanoGraph& pano_graph) {\n std::map<std::string, std::vector<std::string>> graph_nodes =\n pano_graph.GetGraph();\n\n // Populate the edge cache.\n absl::node_hash_set<std::string> already_done;\n for (const auto& node : graph_nodes) {\n PanoMetadata node_data;\n if (!pano_graph.Metadata(node.first, &node_data)) {\n return false;\n }\n double start_lat = node_data.pano.coords().lat();\n double start_lng = node_data.pano.coords().lng();\n already_done.insert(node.first);\n\n auto start = S2LatLng::FromDegrees(start_lat, start_lng);\n nodes_[node.first] = start;\n\n for (const auto& neighbor_id : node.second) {\n if (already_done.find(neighbor_id) != already_done.end()) {\n continue;\n }\n PanoMetadata neighbor_data;\n if (!pano_graph.Metadata(neighbor_id, &neighbor_data)) {\n return false;\n }\n\n double end_lat = neighbor_data.pano.coords().lat();\n double end_lng = neighbor_data.pano.coords().lng();\n graph_edges_.emplace_back(start, S2LatLng::FromDegrees(end_lat, end_lng));\n }\n }\n\n return true;\n}\n\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.673855721950531, "alphanum_fraction": 0.6772106289863586, "avg_line_length": 29.91111183166504, "blob_id": "ffa39ac0f4ed6643daf79c2208e5640063c7d3d8", "content_id": "075e35009179af220010c2f5fffe83f330158ff5", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4173, "license_type": "permissive", "max_line_length": 80, "num_lines": 135, "path": "/streetlearn/engine/node_cache_test.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/node_cache.h\"\n\n#include <map>\n#include <memory>\n#include <string>\n\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n#include \"absl/base/thread_annotations.h\"\n#include \"absl/container/flat_hash_map.h\"\n#include \"absl/strings/str_cat.h\"\n#include \"absl/strings/string_view.h\"\n#include \"absl/synchronization/blocking_counter.h\"\n#include \"absl/synchronization/mutex.h\"\n#include \"absl/synchronization/notification.h\"\n#include \"streetlearn/engine/test_dataset.h\"\n\nnamespace streetlearn {\nnamespace {\n\nconstexpr int kThreadCount = 8;\n\nclass CacheTest : public ::testing::Test {\n public:\n static void SetUpTestCase() { ASSERT_TRUE(TestDataset::Generate()); }\n\n CacheTest()\n : dataset_(Dataset::Create(TestDataset::GetPath())),\n node_cache_(dataset_.get(), kThreadCount, TestDataset::kMaxCacheSize) {}\n\n void LoadPano(const std::string& pano_id) {\n notification_ = absl::make_unique<absl::Notification>();\n node_cache_.Lookup(pano_id,\n [this](const PanoGraphNode* node) { PanoLoaded(node); });\n notification_->WaitForNotification();\n }\n\n void LoadPanoAsync(const std::string& pano_id) {\n node_cache_.Lookup(pano_id,\n [this](const PanoGraphNode* node) { PanoLoaded(node); });\n }\n\n const PanoGraphNode* GetNode(const std::string& pano_id)\n LOCKS_EXCLUDED(mutex_) {\n absl::ReaderMutexLock lock(&mutex_);\n return loaded_panos_.find(pano_id) != loaded_panos_.end()\n ? loaded_panos_[pano_id]\n : nullptr;\n }\n\n bool CacheContains(const std::string& pano_id) {\n return node_cache_.Lookup(pano_id, [](const PanoGraphNode* node) {});\n }\n\n void InitBlockingCounter(int size) {\n blockingCounter_ = absl::make_unique<absl::BlockingCounter>(size);\n }\n\n void WaitForAll() { blockingCounter_->Wait(); }\n\n private:\n void PanoLoaded(const PanoGraphNode* node) LOCKS_EXCLUDED(mutex_) {\n if (node != nullptr) {\n absl::WriterMutexLock lock(&mutex_);\n loaded_panos_[node->id()] = node;\n }\n if (notification_) {\n notification_->Notify();\n }\n if (blockingCounter_) {\n blockingCounter_->DecrementCount();\n }\n }\n\n std::unique_ptr<const Dataset> dataset_;\n absl::Mutex mutex_;\n NodeCache node_cache_;\n absl::flat_hash_map<std::string, const PanoGraphNode*> loaded_panos_\n GUARDED_BY(mutex_);\n std::unique_ptr<absl::Notification> notification_;\n std::unique_ptr<absl::BlockingCounter> blockingCounter_;\n};\n\nTEST_F(CacheTest, NodeCacheTest) {\n // Fill the cache.\n for (int i = 1; i <= TestDataset::kMaxCacheSize; ++i) {\n auto node_id = absl::StrCat(i);\n LoadPano(node_id);\n const PanoGraphNode* node = GetNode(node_id);\n EXPECT_NE(node, nullptr);\n EXPECT_EQ(node->id(), node_id);\n }\n\n // Test an eviction. The first element should now have been removed.\n auto node_id = absl::StrCat(TestDataset::kMaxCacheSize + 1);\n LoadPano(node_id);\n const PanoGraphNode* node = GetNode(node_id);\n EXPECT_NE(node, nullptr);\n EXPECT_EQ(node->id(), node_id);\n EXPECT_FALSE(CacheContains(absl::StrCat(1)));\n}\n\nTEST_F(CacheTest, NodeCacheTestAsync) {\n // Load the panos asynchronously.\n InitBlockingCounter(TestDataset::kMaxCacheSize);\n for (int i = 1; i <= TestDataset::kMaxCacheSize; ++i) {\n LoadPanoAsync(absl::StrCat(i));\n }\n\n WaitForAll();\n\n for (int i = 1; i <= TestDataset::kMaxCacheSize; ++i) {\n auto node_id = absl::StrCat(i);\n const PanoGraphNode* node = GetNode(node_id);\n EXPECT_NE(node, nullptr);\n EXPECT_EQ(node->id(), node_id);\n }\n}\n\n} // namespace\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.7128864526748657, "alphanum_fraction": 0.7153351902961731, "avg_line_length": 31.670000076293945, "blob_id": "eae55f452430fe6171fdada54091e80f07daa1f2", "content_id": "23cc35822160d4d4f2a10b7128b543cce8866e00", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3267, "license_type": "permissive", "max_line_length": 78, "num_lines": 100, "path": "/streetlearn/engine/metadata_cache.h", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#ifndef THIRD_PARTY_STREETLEARN_METADATA_CACHE_H_\n#define THIRD_PARTY_STREETLEARN_METADATA_CACHE_H_\n\n#include <cstddef>\n#include <map>\n#include <memory>\n#include <string>\n#include <vector>\n\n#include \"streetlearn/engine/dataset.h\"\n#include \"streetlearn/proto/streetlearn.pb.h\"\n\nnamespace streetlearn {\n\n// Metadata for an individual pano.\nstruct PanoMetadata {\n // The neighbors of the pano.\n std::vector<PanoIdAndGpsCoords> neighbors;\n\n // Metadata for the pano.\n Pano pano;\n\n // Depth of the connected graph.\n int graph_depth;\n};\n\n// Reads and caches metadata and pano connectivity information for a region.\n// This data is provided by a panos_connectivity file generated by the pano\n// download process.\nclass MetadataCache {\n public:\n // Create an instance of the cache using the dataset provided. Graphs below\n // the minimum depth will be excluded. Returns null if the metadata file is\n // invalid.\n static std::unique_ptr<MetadataCache> Create(const Dataset* dataset,\n int min_graph_depth);\n\n // Limits of the region.\n double min_lat() const { return min_lat_; }\n double max_lat() const { return max_lat_; }\n double min_lng() const { return min_lng_; }\n double max_lng() const { return max_lng_; }\n\n // Total number of panos in the region.\n std::size_t size() const { return pano_metadata_.size(); }\n\n // Returns the metadata for the given pano or null if it doesn't exist. The\n // object returned is only valid for the lifetime of the cache.\n const PanoMetadata* GetPanoMetadata(const std::string& pano_id) const;\n\n // Returns all panos in graphs of at least min_size.\n std::vector<std::string> PanosInGraphsOfSize(int min_size) const;\n\n // Returns a pano in the largest connected graph in the region.\n std::string PanoInLargestGraph() const;\n\n private:\n explicit MetadataCache(int min_graph_depth);\n\n // Reads metadata from the dataset provided, which must contain a\n // StreetLearnGraph proto and populates self. Returns false for non-existent\n // or invalid files.\n bool ReadData(const Dataset* dataset);\n\n // Add neighbor information to the metadata cache.\n void ProcessNeighbors(const StreetLearnGraph& streetLearnGraph,\n const std::map<std::string, Pano>& panos);\n\n // Minimum lat/long of the region's bounds.\n double min_lat_;\n double min_lng_;\n\n // Maximum lat/long of the region's bounds.\n double max_lat_;\n double max_lng_;\n\n // Lookup of metadata indexed on pano ID.\n std::map<std::string, PanoMetadata> pano_metadata_;\n\n // The minimum graph depth loaded.\n int min_graph_depth_;\n};\n\n} // namespace streetlearn\n\n#endif // STREETLEARN_METADATA_CACHE_H_\n" }, { "alpha_fraction": 0.6749863028526306, "alphanum_fraction": 0.6866428852081299, "avg_line_length": 36.015228271484375, "blob_id": "4aa76f741590d47245b7cd6dffcb04c7fb205cd1", "content_id": "31155e89459e6a7f25f3b11834399cd302059ecf", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7292, "license_type": "permissive", "max_line_length": 80, "num_lines": 197, "path": "/streetlearn/engine/pano_graph_test.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/pano_graph.h\"\n\n#include <cmath>\n#include <string>\n#include <vector>\n\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n#include \"absl/strings/str_cat.h\"\n#include \"streetlearn/engine/test_dataset.h\"\n\nnamespace streetlearn {\nnamespace {\n\nusing ::testing::DoubleNear;\nusing ::testing::Optional;\n\nclass PanoGraphTest : public ::testing::Test {\n public:\n static void SetUpTestCase() { ASSERT_TRUE(TestDataset::Generate()); }\n\n void SetUp() {\n dataset_ = Dataset::Create(TestDataset::GetPath());\n ASSERT_TRUE(dataset_ != nullptr);\n }\n\n std::unique_ptr<const Dataset> dataset_;\n};\n\nvoid TestGraph(PanoGraph* pano_graph, const std::string& root) {\n auto root_node = pano_graph->Root();\n if (!root.empty()) {\n EXPECT_EQ(root_node.id(), root);\n }\n auto root_image = pano_graph->RootImage();\n int graph_size = pano_graph->GetGraph().size();\n EXPECT_NE(root_image.get(), nullptr);\n\n PanoMetadata metadata;\n EXPECT_FALSE(pano_graph->Metadata(\"bogus\", &metadata));\n ASSERT_TRUE(pano_graph->Metadata(root_node.id(), &metadata));\n EXPECT_LE(metadata.neighbors.size(), TestDataset::kNeighborCount);\n\n for (const auto& neighbor : metadata.neighbors) {\n EXPECT_TRUE(pano_graph->BuildGraphWithRoot(neighbor.id()));\n auto root_node = pano_graph->Root();\n EXPECT_EQ(root_node.id(), neighbor.id());\n EXPECT_EQ(pano_graph->GetGraph().size(), graph_size);\n auto neighbor_bearings = pano_graph->GetNeighborBearings(1);\n EXPECT_GE(neighbor_bearings.size(), 1);\n }\n\n auto old_graph = pano_graph->GetGraph();\n EXPECT_TRUE(pano_graph->MoveToNeighbor(30 /* bearing */, 5 /* tol */));\n EXPECT_TRUE(pano_graph->MoveToNeighbor(-150 /* bearing */, 5 /* tol */));\n auto new_graph = pano_graph->GetGraph();\n EXPECT_EQ(old_graph.size(), new_graph.size());\n\n // The panos are in a straight line at 32 degrees to each other.\n auto bearings =\n pano_graph->GetNeighborBearings(TestDataset::kMaxNeighborDepth);\n for (const auto& neighbor : bearings) {\n EXPECT_TRUE(round(fabs(neighbor.bearing)) == 32 ||\n round(fabs(neighbor.bearing)) == 148);\n }\n}\n\nTEST(StreetLearn, PanoGraphInitFailureTest) {\n ASSERT_TRUE(TestDataset::GenerateInvalid());\n std::unique_ptr<Dataset> invalid_dataset =\n Dataset::Create(TestDataset::GetInvalidDatasetPath());\n ASSERT_TRUE(invalid_dataset != nullptr);\n\n PanoGraph pano_graph(TestDataset::kMaxGraphDepth, TestDataset::kMaxCacheSize,\n TestDataset::kMinGraphDepth, TestDataset::kMaxGraphDepth,\n invalid_dataset.get());\n // Invalid dataset.\n EXPECT_FALSE(pano_graph.Init());\n}\n\nTEST_F(PanoGraphTest, TestPanoGraph) {\n PanoGraph pano_graph(TestDataset::kMaxGraphDepth, TestDataset::kMaxCacheSize,\n TestDataset::kMinGraphDepth, TestDataset::kMaxGraphDepth,\n dataset_.get());\n pano_graph.SetRandomSeed(0);\n // Valid metadata filename.\n ASSERT_TRUE(pano_graph.Init());\n EXPECT_FALSE(pano_graph.MoveToNeighbor(0, 0));\n\n // BuildRandomGraph test. The root is chosen randomly so we don't\n // test what it's set to.\n EXPECT_TRUE(pano_graph.BuildRandomGraph());\n TestGraph(&pano_graph, \"\" /* Don't check root */);\n EXPECT_FALSE(pano_graph.SetPosition(\"-1\"));\n EXPECT_FALSE(pano_graph.MoveToNeighbor(270, 0));\n EXPECT_TRUE(pano_graph.SetPosition(\"2\"));\n\n // BuildGraphWithRoot tests.\n EXPECT_TRUE(pano_graph.BuildGraphWithRoot(\"1\"));\n TestGraph(&pano_graph, \"1\");\n\n for (int root_index = 1; root_index <= TestDataset::kPanoCount;\n ++root_index) {\n const std::string root_id = absl::StrCat(root_index);\n\n EXPECT_TRUE(pano_graph.BuildGraphWithRoot(root_id));\n TestGraph(&pano_graph, root_id);\n }\n\n // BuildEntireGraph test.\n EXPECT_TRUE(pano_graph.BuildEntireGraph());\n const auto graph = pano_graph.GetGraph();\n EXPECT_EQ(graph.size(), TestDataset::GetPanoIDs().size());\n TestGraph(&pano_graph, \"\" /* Don't check root */);\n}\n\nTEST_F(PanoGraphTest, InvalidGraphSizeTest) {\n PanoGraph pano_graph(TestDataset::kMaxGraphDepth, TestDataset::kMaxCacheSize,\n 2 * TestDataset::kMaxGraphDepth,\n 2 * TestDataset::kMaxGraphDepth, dataset_.get());\n ASSERT_TRUE(pano_graph.Init());\n EXPECT_FALSE(pano_graph.BuildRandomGraph());\n}\n\nTEST_F(PanoGraphTest, InvalidPanosTest) {\n PanoGraph pano_graph(TestDataset::kMaxGraphDepth, TestDataset::kMaxCacheSize,\n TestDataset::kMinGraphDepth, TestDataset::kMaxGraphDepth,\n dataset_.get());\n ASSERT_TRUE(pano_graph.Init());\n\n EXPECT_FALSE(pano_graph.BuildGraphWithRoot(\"\"));\n\n std::string bogus_id = \"-1\";\n EXPECT_FALSE(pano_graph.BuildGraphWithRoot(bogus_id));\n}\n\nTEST_F(PanoGraphTest, TerminalBearingTest) {\n PanoGraph pano_graph(TestDataset::kMaxGraphDepth, TestDataset::kMaxCacheSize,\n TestDataset::kMinGraphDepth / 2,\n TestDataset::kMaxGraphDepth / 2, dataset_.get());\n ASSERT_TRUE(pano_graph.Init());\n EXPECT_TRUE(pano_graph.BuildGraphWithRoot(\"5\"));\n\n const auto& terminalBearings = pano_graph.TerminalBearings(\"9\");\n ASSERT_EQ(terminalBearings.size(), 1);\n const auto& bearings = *terminalBearings.begin();\n EXPECT_EQ(bearings.first, 1);\n ASSERT_EQ(bearings.second.size(), 1);\n const auto& terminal = *bearings.second.begin();\n EXPECT_EQ(std::round(terminal.distance), 131);\n EXPECT_EQ(std::round(terminal.bearing), 32);\n}\n\nTEST_F(PanoGraphTest, PanoCalculationTest) {\n PanoGraph pano_graph(TestDataset::kMaxGraphDepth, 42 /* large cache */,\n TestDataset::kMinGraphDepth / 2,\n TestDataset::kMaxGraphDepth / 2, dataset_.get());\n ASSERT_TRUE(pano_graph.Init());\n EXPECT_TRUE(pano_graph.BuildGraphWithRoot(\"1\"));\n\n auto pano_ids = TestDataset::GetPanoIDs();\n PanoMetadata metadata1;\n ASSERT_TRUE(pano_graph.Metadata(pano_ids[0], &metadata1));\n const auto& pano1 = metadata1.pano;\n PanoMetadata metadata2;\n ASSERT_TRUE(pano_graph.Metadata(pano_ids[1], &metadata2));\n const auto& pano2 = metadata2.pano;\n\n // TODO: elminitate all magic numbers\n EXPECT_THAT(pano_graph.GetPanoDistance(pano1.id(), pano2.id()),\n Optional(DoubleNear(131, 0.1)));\n EXPECT_THAT(pano_graph.GetPanoBearing(pano1.id(), pano2.id()),\n Optional(DoubleNear(31.9, 0.1)));\n\n std::string bogus_id = \"-1\";\n EXPECT_FALSE(pano_graph.GetPanoDistance(pano1.id(), bogus_id).has_value());\n EXPECT_FALSE(pano_graph.GetPanoDistance(bogus_id, pano1.id()).has_value());\n EXPECT_FALSE(pano_graph.GetPanoBearing(pano1.id(), bogus_id).has_value());\n EXPECT_FALSE(pano_graph.GetPanoBearing(bogus_id, pano1.id()).has_value());\n}\n\n} // namespace\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.6900763511657715, "alphanum_fraction": 0.694656491279602, "avg_line_length": 29.703125, "blob_id": "04b9d88dad4e31ebc9cb36548afb82145b285c3c", "content_id": "df43011931e1f56027473def587c8b5ec520e132", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": true, "language": "C++", "length_bytes": 1965, "license_type": "permissive", "max_line_length": 78, "num_lines": 64, "path": "/third_party/absl/python/optional.h", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 The Abseil Authors.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n// This library provides Clif conversion functions for specializations of\n// absl::optional. Clif refers to absl::optional<T> as NoneOr<T>.\n\n#ifndef THIRD_PARTY_ABSL_PYTHON_OPTIONAL_H_\n#define THIRD_PARTY_ABSL_PYTHON_OPTIONAL_H_\n\n#include \"absl/types/optional.h\"\n#include \"clif/python/postconv.h\"\n#include \"clif/python/types.h\"\n\n// If Abseil claims std::optional does not exist then it provides an\n// absl::optional<T> of its own. In that case, wrap that type. Otherwise, rely\n// on third_party/clif/python/types.h to wrap std::optional<T>.\n#if !defined(ABSL_HAVE_STD_OPTIONAL)\n\nnamespace absl {\n\n// CLIF use `::absl::optional` as NoneOr\n\n// C++ object to python\ntemplate <typename T>\nPyObject* Clif_PyObjFrom(const optional<T>& opt,\n const ::clif::py::PostConv& pc) {\n if (!opt) Py_RETURN_NONE;\n using ::clif::Clif_PyObjFrom;\n return Clif_PyObjFrom(*opt, pc.Get(0));\n}\n\n// Python to C++ object\ntemplate <typename T>\nbool Clif_PyObjAs(PyObject* py, optional<T>* c) {\n DCHECK(c != nullptr);\n if (Py_None == py) { // Uninitialized case.\n c->reset();\n return true;\n }\n // Initialized case.\n using ::clif::Clif_PyObjAs;\n if (!Clif_PyObjAs(py, &c->emplace())) {\n c->reset();\n return false;\n }\n return true;\n}\n\n} // namespace absl\n\n#endif // !defined(ABSL_HAVE_STD_OPTIONAL)\n\n#endif // THIRD_PARTY_ABSL_PYTHON_OPTIONAL_H_\n" }, { "alpha_fraction": 0.7377049326896667, "alphanum_fraction": 0.7436661720275879, "avg_line_length": 32.54999923706055, "blob_id": "c40294cff391a6568350c516a3e21ca25a3e5dfe", "content_id": "f19b50853953e7509ae220b4d79768de071be8dd", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1342, "license_type": "permissive", "max_line_length": 76, "num_lines": 40, "path": "/streetlearn/python/environment/exploration_game.py", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "# Copyright 2018 Google LLC.\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\"\"\"Coin game level with early termination.\n\nIn this environment, the agent receives a reward for every coin it collects,\nand the episode ends when all the coins are collected.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom streetlearn.python.environment import coin_game\n\n\nclass ExplorationGame(coin_game.CoinGame):\n\n def done(self, streetlearn):\n \"\"\"Returns a flag indicating the end of the current episode.\n\n This game ends when all the coins are collected.\n\n Args:\n streetlearn: the streetlearn environment.\n Returns:\n reward: the reward from the last step.\n pcontinue: a flag indicating the end of an episode.\n \"\"\"\n return not bool(self._coin_pano_id_set)\n" }, { "alpha_fraction": 0.7475447654724121, "alphanum_fraction": 0.7498555779457092, "avg_line_length": 35.44210433959961, "blob_id": "bc014572d77a32695e153ed682545a628d4afb3c", "content_id": "9169f211a21aaff7a38f48948f8c7df360af0606", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3462, "license_type": "permissive", "max_line_length": 80, "num_lines": 95, "path": "/streetlearn/engine/pano_fetcher.h", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#ifndef STREETLEARN_PANO_FETCHER_H_\n#define STREETLEARN_PANO_FETCHER_H_\n\n#include <deque>\n#include <functional>\n#include <memory>\n#include <string>\n#include <thread>\n#include <vector>\n\n#include \"absl/base/thread_annotations.h\"\n#include \"absl/strings/string_view.h\"\n#include \"absl/synchronization/mutex.h\"\n#include \"streetlearn/engine/dataset.h\"\n#include \"streetlearn/engine/pano_graph_node.h\"\n#include \"streetlearn/proto/streetlearn.pb.h\"\n\nnamespace streetlearn {\n\n// Class to fetch panos from disk for the LRU Cache maintained by the\n// PanoGraph. Conceptually, it consists of a synchronized queue of items to\n// be fetched and a pool of worker threads that pop items from the queue and\n// process them. Non-binding attempts to remove items from the queue are\n// supported. All queue operations are serialized.\n//\n// The fetcher owns a callback to handle notifications when asynchronous fetches\n// have completed. This callback is called concurrently by the worker threads\n// and must therefore be thread-safe. Any state referenced by the callback must\n// outlive the fetcher.\nclass PanoFetcher {\n public:\n using FetchCallback = std::function<void(\n absl::string_view pano_file, std::shared_ptr<const PanoGraphNode>)>;\n\n // Constructs a PanoFetcher using data from the dataset provided using the\n // given callback. The fetcher uses thread_count threads for fetching.\n PanoFetcher(const Dataset* dataset, int thread_count, FetchCallback callback);\n\n // Cancels and joins all of the fetching threads.\n ~PanoFetcher() LOCKS_EXCLUDED(queue_mutex_);\n\n // Fetch a pano synchronously by ID. Returns null if the current graph does\n // not contain a pano with the given ID.\n std::shared_ptr<const PanoGraphNode> Fetch(absl::string_view pano_id);\n\n // Fetch a pano asynchronously by ID and calls the callback when complete.\n void FetchAsync(absl::string_view pano_id) LOCKS_EXCLUDED(queue_mutex_);\n\n // Clears the fetch queue and returns the IDs of panos cancelled.\n std::vector<std::string> CancelPendingFetches() LOCKS_EXCLUDED(queue_mutex_);\n\n private:\n // Thread routine for loading panos.\n void ThreadExecute();\n\n // Waits until a pano request is pending on the queue or shutdown has been\n // requested. Returns true when a request is pending and false on shutdown.\n bool MonitorRequests(std::string* filename) LOCKS_EXCLUDED(queue_mutex_);\n\n // Dataset to read the panos.\n const Dataset* dataset_;\n\n // The threads used for fetching.\n std::vector<std::thread> threads_;\n\n // Queue for fetch requests.\n std::deque<std::string> fetch_queue_ GUARDED_BY(queue_mutex_);\n\n // Fetch queue mutex.\n absl::Mutex queue_mutex_;\n\n // Callback for asynchronous requests.\n FetchCallback callback_;\n\n // Shutdown flag to terminate fetch threads.\n bool shutdown_ GUARDED_BY(queue_mutex_);\n};\n\n} // namespace streetlearn\n\n#endif // STREETLEARN_PANO_FETCHER_H_\n" }, { "alpha_fraction": 0.6775177121162415, "alphanum_fraction": 0.686663031578064, "avg_line_length": 27.610591888427734, "blob_id": "e327146c57adfa933bce2bdc47994b68437318b9", "content_id": "d088993f8f94d71733332913a369a75453d93fb2", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9185, "license_type": "permissive", "max_line_length": 80, "num_lines": 321, "path": "/streetlearn/python/environment/observations.py", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "# Copyright 2018 Google LLC.\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\"\"\"Classes to handle the various StreetLearn observation types.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport abc\nimport numpy as np\n\n_METADATA_COUNT = 14\n_NUM_HEADING_BINS = 16\n_NUM_LAT_BINS = 32\n_NUM_LNG_BINS = 32\n\n\nclass Observation(object):\n \"\"\"Base class for all observations.\"\"\"\n __metaclass__ = abc.ABCMeta\n\n def __init__(self, streetlearn):\n self._streetlearn = streetlearn\n\n @abc.abstractproperty\n def observation_spec(self):\n \"\"\"The observation_spec for this observation.\"\"\"\n pass\n\n @abc.abstractproperty\n def observation(self):\n \"\"\"The observation data.\"\"\"\n pass\n\n @classmethod\n def create(cls, name, streetlearn):\n \"\"\"Dispatches an Observation based on `name`.\"\"\"\n observations = [ViewImage, GraphImage, Yaw, Pitch, Metadata, TargetMetadata,\n LatLng, TargetLatLng, YawLabel, Neighbors, LatLngLabel,\n TargetLatLngLabel, Thumbnails, Instructions,\n GroundTruthDirection]\n dispatch = {o.name: o for o in observations}\n try:\n return dispatch[name](streetlearn)\n except KeyError:\n raise ValueError('No Observation named %s found' % name)\n\n\nclass ViewImage(Observation):\n \"\"\"RGB pixel data of the view.\"\"\"\n name = 'view_image'\n observation_spec_dtypes = np.uint8\n\n def __init__(self, streetlearn):\n super(ViewImage, self).__init__(streetlearn)\n self._width = streetlearn.config[\"width\"]\n self._height = streetlearn.config[\"height\"]\n self._depth = 3\n self._buffer = np.empty(self._depth * self._width * self._height,\n dtype=np.uint8)\n\n @property\n def observation_spec(self):\n return [self._depth, self._height, self._width]\n\n @property\n def observation(self):\n self._streetlearn.engine.RenderObservation(self._buffer)\n return self._buffer\n\n\nclass GraphImage(Observation):\n \"\"\"RGB pixel data of the graph.\"\"\"\n name = 'graph_image'\n observation_spec_dtypes = np.uint8\n\n def __init__(self, streetlearn):\n super(GraphImage, self).__init__(streetlearn)\n self._width = streetlearn.config[\"graph_width\"]\n self._height = streetlearn.config[\"graph_height\"]\n self._depth = 3\n self._buffer = np.empty(self._depth * self._width * self._height,\n dtype=np.uint8)\n\n @property\n def observation_spec(self):\n return [self._depth, self._height, self._width]\n\n @property\n def observation(self):\n highlighted_panos = self._streetlearn.game.highlighted_panos()\n self._streetlearn.engine.DrawGraph(highlighted_panos, self._buffer)\n return self._buffer\n\n\nclass Yaw(Observation):\n \"\"\"The agent's current yaw (different from the current pano heading).\"\"\"\n name = 'yaw'\n observation_spec_dtypes = np.float64\n\n @property\n def observation_spec(self):\n return [0]\n\n @property\n def observation(self):\n return np.array(self._streetlearn.engine.GetYaw(), dtype=np.float64)\n\n\nclass Pitch(Observation):\n \"\"\"The agent's current pitch.\"\"\"\n name = 'pitch'\n observation_spec_dtypes = np.float64\n\n @property\n def observation_spec(self):\n return [0]\n\n @property\n def observation(self):\n return np.array(self._streetlearn.engine.GetPitch(), dtype=np.float64)\n\n\nclass YawLabel(Observation):\n \"\"\"The agent's current yaw (different from the current pano heading).\"\"\"\n name = 'yaw_label'\n observation_spec_dtypes = np.uint8\n\n @property\n def observation_spec(self):\n return [0]\n\n @property\n def observation(self):\n yaw = self._streetlearn.engine.GetYaw() % 360.0\n return np.array(yaw * _NUM_HEADING_BINS / 360.0, dtype=np.uint8)\n\n\nclass Metadata(Observation):\n \"\"\"Metadata about the current pano.\"\"\"\n name = 'metadata'\n observation_spec_dtypes = bytearray\n\n @property\n def observation_spec(self):\n return [_METADATA_COUNT]\n\n @property\n def observation(self):\n pano_id = self._streetlearn.current_pano_id\n return bytearray(self._streetlearn.engine.GetMetadata(\n pano_id).pano.SerializeToString())\n\n\nclass TargetMetadata(Observation):\n \"\"\"Metadata about the target pano.\"\"\"\n name = 'target_metadata'\n observation_spec_dtypes = bytearray\n\n @property\n def observation_spec(self):\n return [_METADATA_COUNT]\n\n @property\n def observation(self):\n goal_id = self._streetlearn.game.goal_id\n if goal_id:\n return bytearray(self._streetlearn.engine.GetMetadata(\n goal_id).pano.SerializeToString())\n return bytearray()\n\n\nclass LatLng(Observation):\n \"\"\"The agent's current lat/lng coordinates, scaled according to config params\n using bbox_lat_min and bbox_lat_max, as well as bbox_lng_min and bbox_lng_max,\n so that scaled lat/lng take values between 0 and 1 within the bounding box.\n \"\"\"\n name = 'latlng'\n observation_spec_dtypes = np.float64\n\n def _scale_lat(self, lat):\n den = self._streetlearn.bbox_lat_max - self._streetlearn.bbox_lat_min\n return ((lat - self._streetlearn.bbox_lat_min) / den if (den > 0) else 0)\n\n def _scale_lng(self, lng):\n den = self._streetlearn.bbox_lng_max - self._streetlearn.bbox_lng_min\n return ((lng - self._streetlearn.bbox_lng_min) / den if (den > 0) else 0)\n\n @property\n def observation_spec(self):\n return [2]\n\n @property\n def observation(self):\n pano_id = self._streetlearn.current_pano_id\n pano_data = self._streetlearn.engine.GetMetadata(pano_id).pano\n lat_scaled = self._scale_lat(pano_data.coords.lat)\n lng_scaled = self._scale_lng(pano_data.coords.lng)\n return np.array([lat_scaled, lng_scaled], dtype=np.float64)\n\n\nclass LatLngLabel(LatLng):\n \"\"\"The agent's current yaw (different from the current pano heading).\"\"\"\n name = 'latlng_label'\n observation_spec_dtypes = np.int32\n\n def _latlng_bin(self, pano_id):\n pano_data = self._streetlearn.engine.GetMetadata(pano_id).pano\n lat_bin = np.floor(self._scale_lat(pano_data.coords.lat) * _NUM_LAT_BINS)\n lat_bin = np.max([np.min([lat_bin, _NUM_LAT_BINS-1]), 0])\n lng_bin = np.floor(self._scale_lng(pano_data.coords.lng) * _NUM_LNG_BINS)\n lng_bin = np.max([np.min([lng_bin, _NUM_LNG_BINS-1]), 0])\n latlng_bin = lat_bin * _NUM_LNG_BINS + lng_bin\n return latlng_bin\n\n @property\n def observation_spec(self):\n return [0]\n\n @property\n def observation(self):\n pano_id = self._streetlearn.current_pano_id\n return np.array(self._latlng_bin(pano_id), dtype=np.int32)\n\n\nclass TargetLatLng(LatLng):\n \"\"\"The agent's target lat/lng coordinates.\"\"\"\n name = 'target_latlng'\n\n @property\n def observation(self):\n goal_id = self._streetlearn.game.goal_id\n if goal_id:\n pano_data = self._streetlearn.engine.GetMetadata(goal_id).pano\n lat_scaled = self._scale_lat(pano_data.coords.lat)\n lng_scaled = self._scale_lng(pano_data.coords.lng)\n return np.array([lat_scaled, lng_scaled], dtype=np.float64)\n return np.array([0, 0], dtype=np.float64)\n\n\nclass TargetLatLngLabel(LatLngLabel):\n \"\"\"The agent's current yaw (different from the current pano heading).\"\"\"\n name = 'target_latlng_label'\n\n @property\n def observation(self):\n goal_id = self._streetlearn.game.goal_id\n if goal_id:\n return np.array(self._latlng_bin(goal_id), dtype=np.int32)\n return np.array(0, dtype=np.int32)\n\n\nclass Thumbnails(Observation):\n \"\"\"Thumbnails' pixel data.\"\"\"\n name = 'thumbnails'\n observation_spec_dtypes = np.uint8\n\n @property\n def observation_spec(self):\n return self._streetlearn.game.thumbnails().shape\n\n @property\n def observation(self):\n return self._streetlearn.game.thumbnails()\n\n\nclass Instructions(Observation):\n \"\"\"StreetLang instructions.\"\"\"\n name = 'instructions'\n observation_spec_dtypes = str\n\n @property\n def observation_spec(self):\n return [1]\n\n @property\n def observation(self):\n return ('|'.join(self._streetlearn.game.instructions())).encode('utf-8')\n\n\nclass GroundTruthDirection(Observation):\n \"\"\"Direction in degrees that the agent needs to take now.\"\"\"\n name = 'ground_truth_direction'\n observation_spec_dtypes = np.float32\n\n @property\n def observation_spec(self):\n return [0]\n\n @property\n def observation(self):\n return np.array(self._streetlearn.game.ground_truth_direction(),\n dtype=np.float32)\n\n\nclass Neighbors(Observation):\n \"\"\"IDs of neighboring panos.\"\"\"\n name = 'neighbors'\n observation_spec_dtypes = np.uint8\n\n @property\n def observation_spec(self):\n return [self._streetlearn.neighbor_resolution]\n\n @property\n def observation(self):\n return np.asarray(\n self._streetlearn.engine.GetNeighborOccupancy(\n self._streetlearn.neighbor_resolution),\n dtype=np.uint8)\n\n" }, { "alpha_fraction": 0.6813752055168152, "alphanum_fraction": 0.6859772801399231, "avg_line_length": 34.519229888916016, "blob_id": "ad229b388450f08b216a59244cf45ce4ac880dce", "content_id": "bf60703728f0ef9b129a22c96da7d30461c17e4e", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3694, "license_type": "permissive", "max_line_length": 80, "num_lines": 104, "path": "/streetlearn/engine/metadata_cache_test.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/metadata_cache.h\"\n\n#include <string>\n\n#include \"gtest/gtest.h\"\n#include \"absl/strings/numbers.h\"\n#include \"absl/strings/str_cat.h\"\n#include \"streetlearn/engine/test_dataset.h\"\n\nnamespace streetlearn {\nnamespace {\n\nTEST(StreetLearn, MetadataCacheTest) {\n ASSERT_TRUE(TestDataset::Generate());\n std::unique_ptr<const Dataset> dataset =\n Dataset::Create(TestDataset::GetPath());\n ASSERT_TRUE(dataset != nullptr);\n\n auto metadata_cache =\n MetadataCache::Create(dataset.get(), TestDataset::kMinGraphDepth);\n ASSERT_TRUE(metadata_cache);\n\n EXPECT_EQ(metadata_cache->min_lat(), TestDataset::kMinLatitude);\n EXPECT_EQ(metadata_cache->max_lat(), TestDataset::kMaxLatitude);\n EXPECT_EQ(metadata_cache->min_lng(), TestDataset::kMinLongitude);\n EXPECT_EQ(metadata_cache->max_lng(), TestDataset::kMaxLongitude);\n EXPECT_EQ(metadata_cache->size(), TestDataset::kPanoCount);\n\n // Invalis Pano ID\n auto* invalid_pano = metadata_cache->GetPanoMetadata(\n absl::StrCat(2 * TestDataset::kPanoCount));\n EXPECT_EQ(invalid_pano, nullptr);\n\n // Valid indices.\n for (int pano_id = 1; pano_id <= TestDataset::kPanoCount; ++pano_id) {\n auto metadata = metadata_cache->GetPanoMetadata(absl::StrCat(pano_id));\n ASSERT_NE(metadata, nullptr);\n\n // Pano Coords\n LatLng lat_lng = metadata->pano.coords();\n EXPECT_EQ(lat_lng.lat(),\n TestDataset::kLatitude + TestDataset::kIncrement * pano_id);\n EXPECT_EQ(lat_lng.lng(),\n TestDataset::kLongitude + TestDataset::kIncrement * pano_id);\n\n // Graph Depth - zero for the isolated temporal neighbor.\n if (pano_id < TestDataset::kPanoCount + 1) {\n EXPECT_EQ(metadata->graph_depth, TestDataset::kPanoCount);\n } else {\n EXPECT_EQ(metadata->graph_depth, 0);\n }\n\n // Neighbors\n auto neighbors = metadata->neighbors;\n if (pano_id == 1 || pano_id == TestDataset::kPanoCount) {\n EXPECT_EQ(neighbors.size(), 1);\n } else if (pano_id < TestDataset::kPanoCount + 1) {\n EXPECT_EQ(neighbors.size(), TestDataset::kNeighborCount);\n } else {\n EXPECT_EQ(neighbors.size(), 0);\n }\n for (const auto& neighbor : neighbors) {\n int id;\n EXPECT_TRUE(absl::SimpleAtoi(neighbor.id(), &id));\n const auto& coords = neighbor.coords();\n EXPECT_EQ(coords.lat(),\n TestDataset::kLatitude + TestDataset::kIncrement * id);\n EXPECT_EQ(coords.lng(),\n TestDataset::kLongitude + TestDataset::kIncrement * id);\n int neighbor_id;\n ASSERT_TRUE(absl::SimpleAtoi(neighbor.id(), &neighbor_id));\n EXPECT_GE(neighbor_id, 1);\n EXPECT_LE(neighbor_id, TestDataset::kPanoCount);\n }\n }\n}\n\nTEST(StreetLearn, InvalidDataTest) {\n ASSERT_TRUE(TestDataset::GenerateInvalid());\n std::unique_ptr<const Dataset> invalid_dataset =\n Dataset::Create(TestDataset::GetInvalidDatasetPath());\n ASSERT_TRUE(invalid_dataset != nullptr);\n\n auto metadata_cache =\n MetadataCache::Create(invalid_dataset.get(), TestDataset::kMinGraphDepth);\n EXPECT_FALSE(metadata_cache);\n}\n\n} // namespace\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.7226890921592712, "alphanum_fraction": 0.7329598665237427, "avg_line_length": 35.931034088134766, "blob_id": "d2a7d8db9e1814127fb05bf7fca386cba9f9834a", "content_id": "1b06874c96bad793ec36926af10dddd09a2c073a", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1071, "license_type": "permissive", "max_line_length": 79, "num_lines": 29, "path": "/streetlearn/engine/bitmap_util.h", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#ifndef THIRD_PARTY_STREETLEARN_ENGINE_IMAGE_UTIL_H_\n#define THIRD_PARTY_STREETLEARN_ENGINE_IMAGE_UTIL_H_\n\n#include <cstdint>\n\nnamespace streetlearn {\n\n// Converts the input packed RGB pixels to planar. The buffers must both be\n// at least 3 * width * height in size.\nvoid ConvertRGBPackedToPlanar(const uint8_t* rgb_buffer, int width, int height,\n uint8_t* out_buffer);\n\n} // namespace streetlearn\n\n#endif // THIRD_PARTY_STREETLEARN_ENGINE_IMAGE_UTIL_H_\n" }, { "alpha_fraction": 0.6293534636497498, "alphanum_fraction": 0.6456950306892395, "avg_line_length": 37.85317611694336, "blob_id": "3dfb496740f82d0af08f74604a3c86d2ca43adf7", "content_id": "f6a48b9679b58170c8eb3c9b26a035e248880df6", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9791, "license_type": "permissive", "max_line_length": 80, "num_lines": 252, "path": "/streetlearn/engine/pano_renderer.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/pano_renderer.h\"\n\n#include <cmath>\n#include <cstdint>\n#include <iostream>\n\n#include \"streetlearn/engine/logging.h\"\n#include \"streetlearn/engine/math_util.h\"\n#include \"streetlearn/engine/pano_graph_node.h\"\n\nnamespace streetlearn {\nnamespace {\n\n// Cairo uses [0, 1] range for colors.\nconstexpr Color kBackColor = {0.0, 0.0, 0.0};\nconstexpr Color kBarColor = {0.5, 0.5, 0.5};\nconstexpr Color kRedColor = {0.9, 0.0, 0.0};\nconstexpr Color kAmberColor = {1.0, 0.49, 0.0};\nconstexpr Color kGreenColor = {0.0, 0.9, 0.0};\n\nconstexpr Color kNoEntryColor = {230, 0, 0};\nconstexpr double kNoEntryProportion = 0.1; // proportion of screen\nconstexpr double kNoEntrySignWidthMeters = 3;\nconstexpr int kConstraintMultiplier = 2;\n\n// Scale the rgb vector from [0, 1] to [0, 255] and set at the point provided.\nvoid PutPixel(int screen_width, int screen_height, int x, int y,\n const Color& color, uint8_t* pixels) {\n if (0 <= x && x < screen_width && 0 <= y && y < screen_height) {\n int index = 3 * (y * screen_width + x);\n pixels[index] = color.red;\n pixels[index + 1] = color.green;\n pixels[index + 2] = color.blue;\n }\n}\n\n// Draw a filled circle at the centre point provided in the given color.\nvoid DrawCircle(int screen_width, int screen_height, int center_x, int center_y,\n int radius, const Color& color, uint8_t* pixels) {\n const float sin_45_degrees = std::sin(math::DegreesToRadians(45.0));\n // This is the distance on the axis from sin(90) to sin(45).\n int range = radius / (2 * sin_45_degrees);\n for (int i = radius; i >= range; --i) {\n int j = sqrt(radius * radius - i * i);\n for (int k = -j; k <= j; k++) {\n // We draw all the 4 sides at the same time.\n PutPixel(screen_width, screen_height, center_x - k, center_y + i, color,\n pixels);\n PutPixel(screen_width, screen_height, center_x - k, center_y - i, color,\n pixels);\n PutPixel(screen_width, screen_height, center_x + i, center_y + k, color,\n pixels);\n PutPixel(screen_width, screen_height, center_x - i, center_y - k, color,\n pixels);\n }\n }\n // To fill the circle we draw the circumscribed square.\n range = radius * sin_45_degrees;\n for (int i = center_x - range + 1; i < center_x + range; i++) {\n for (int j = center_y - range + 1; j < center_y + range; j++) {\n PutPixel(screen_width, screen_height, i, j, color, pixels);\n }\n }\n}\n} // namespace\n\nPanoRenderer::PanoRenderer(int screen_width, int screen_height,\n int status_height, double fov_deg)\n : width_(screen_width),\n height_(screen_height),\n fov_deg_(fov_deg),\n status_height_(status_height),\n no_entry_width_(width_ * kNoEntryProportion),\n degrees_pp_(360.0 / width_),\n context_(nullptr),\n pano_buffer_(screen_width, screen_height - status_height),\n pano_projection_(fov_deg, screen_width, screen_height - status_height) {\n pixels_.resize(width_ * height_ * 3);\n if (status_height_ > 0 && status_height_ < height_) {\n int stride = cairo_format_stride_for_width(CAIRO_FORMAT_RGB24, width_);\n status_pixels_.resize(stride * status_height_);\n surface_ = cairo_image_surface_create_for_data(status_pixels_.data(),\n CAIRO_FORMAT_RGB24, width_,\n status_height_, stride);\n context_ = cairo_create(surface_);\n\n } else if (status_height_ != 0) {\n LOG(ERROR) << \"Invalid status bar height: \" << status_height_;\n status_height_ = 0;\n }\n}\n\nPanoRenderer::~PanoRenderer() {\n if (context_ != nullptr) {\n cairo_destroy(context_);\n cairo_surface_destroy(surface_);\n }\n}\n\nvoid PanoRenderer::RenderScene(\n const Image3_b& input, double global_yaw, double yaw, double pitch,\n double tolerance, const std::vector<PanoNeighborBearing>& bearings,\n const std::map<int, std::vector<TerminalGraphNode>>& inaccessible) {\n if (status_height_ > 0) {\n DrawStatusBar(tolerance, yaw, bearings);\n }\n\n ProjectPano(input, yaw - global_yaw, pitch);\n DrawNoEntrySigns(global_yaw, yaw, pitch, inaccessible);\n}\n\nvoid PanoRenderer::ProjectPano(const Image3_b& input, double yaw,\n double pitch) {\n yaw = ConstrainAngle(360, yaw);\n pitch = ConstrainAngle(90, pitch);\n pano_projection_.Project(input, yaw, pitch, &pano_buffer_);\n std::copy(pano_buffer_.data().begin(), pano_buffer_.data().end(),\n pixels_.begin());\n}\n\nvoid PanoRenderer::DrawBearing(double current_bearing, double bearing,\n const Color& color) {\n double pos = ConstrainAngle(180, bearing - current_bearing);\n double x_pos = width_ / 2.0 + pos / degrees_pp_;\n cairo_arc(context_, x_pos, status_height_ / 2, status_height_ / 2 - 1, 0,\n 2 * M_PI);\n cairo_set_source_rgb(context_, color.red, color.green, color.blue);\n cairo_fill(context_);\n}\n\nvoid PanoRenderer::DrawStatusBar(\n double tolerance, double current_bearing,\n const std::vector<PanoNeighborBearing>& bearings) {\n // Background\n cairo_set_source_rgb(context_, kBackColor.red, kBackColor.green,\n kBackColor.blue);\n cairo_paint(context_);\n\n // Bearings - need to center everything around the current bearing. When a\n // point is in both quadrants 3 and 4 need to use the smaller angle between\n // them.\n\n // Work out the bearing closest to our current bearing down which travel is\n // possible.\n double chosen_dir(std::numeric_limits<double>::max());\n double min_distance(std::numeric_limits<double>::max());\n for (auto neighbor : bearings) {\n double diff = fabs(neighbor.bearing - current_bearing);\n if (diff > 180.0) {\n diff = 360.0 - diff;\n }\n if (diff < tolerance && neighbor.distance < min_distance) {\n chosen_dir = neighbor.bearing;\n min_distance = neighbor.distance;\n }\n }\n\n // Draw all the bearings except for the chosen direction, which will be drawn\n // last so that no other bearing is superimposed.\n for (auto neighbor : bearings) {\n if (neighbor.bearing == chosen_dir) {\n continue;\n }\n\n double pos = fabs(neighbor.bearing - current_bearing);\n if (pos > 180.0) {\n pos = 360.0 - pos;\n }\n const auto& color = fabs(pos) < tolerance ? kAmberColor : kRedColor;\n DrawBearing(current_bearing, neighbor.bearing, color);\n }\n\n if (chosen_dir < std::numeric_limits<double>::max()) {\n DrawBearing(current_bearing, chosen_dir, kGreenColor);\n }\n\n // Tolerance bars for forward movement.\n cairo_set_source_rgb(context_, kBarColor.red, kBarColor.green,\n kBarColor.blue);\n double lower_tol = (180.0 - tolerance) / degrees_pp_;\n cairo_move_to(context_, lower_tol, 0.0);\n cairo_line_to(context_, lower_tol, status_height_);\n double upper_tol = (180.0 + tolerance) / degrees_pp_;\n cairo_move_to(context_, upper_tol, 0.0);\n cairo_line_to(context_, upper_tol, status_height_);\n cairo_stroke(context_);\n\n // Cairo swaps g and b and only supports 4 bytes per pixel - need to convert.\n int image_height = height_ - status_height_;\n for (int i = 0; i < status_height_; i++) {\n const int image_row_offset = (i + image_height) * width_;\n const int status_row_offset = i * width_;\n for (int j = 0; j < width_; j++) {\n int index = 3 * (image_row_offset + j);\n int status_index = 4 * (status_row_offset + j);\n pixels_[index] = status_pixels_[status_index + 2];\n pixels_[index + 1] = status_pixels_[status_index + 1];\n pixels_[index + 2] = status_pixels_[status_index];\n }\n }\n}\n\n// The co-ordinates are calculated by uniformly scaling along the axes, which\n// may cause the signs to drift slightly towards the edges of the screen.\nvoid PanoRenderer::DrawNoEntrySigns(\n double global_yaw, double current_bearing, double current_pitch,\n const std::map<int, std::vector<TerminalGraphNode>>& inaccessible) {\n // Draw the farthest away first.\n\n for (auto iter = inaccessible.rbegin(); iter != inaccessible.rend(); ++iter) {\n for (const auto& terminal : iter->second) {\n int sign_width =\n no_entry_width_ *\n (2.0 * atan(kNoEntrySignWidthMeters / terminal.distance)) /\n math::DegreesToRadians(fov_deg_);\n double offset_x = ConstrainAngle(180, terminal.bearing - current_bearing);\n double offset_y = current_pitch;\n int x_pos = width_ * (0.5 + offset_x / fov_deg_);\n int y_pos = height_ * (0.5 - (offset_y * width_) / (fov_deg_ * height_));\n\n DrawCircle(width_, height_ - status_height_, x_pos, y_pos, sign_width,\n kNoEntryColor, pixels_.data());\n }\n }\n}\n\ndouble PanoRenderer::ConstrainAngle(double constraint, double input_angle) {\n // The idea here is to shift the problem so that we're remapping the angle to\n // [0.. 2*constraint), which makes it solvable in one line. Having clamped to\n // that range, we then unshift back to [-constraint, constraint).\n double value_range = kConstraintMultiplier * constraint;\n double value = input_angle + constraint;\n value -= value_range * std::floor(value / value_range);\n value -= constraint;\n return value;\n}\n\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.7082395553588867, "alphanum_fraction": 0.725348949432373, "avg_line_length": 34.82258224487305, "blob_id": "7079f772d3eecc33042ac06522cdedfcd2a7ac4f", "content_id": "3763bfb4d25cc5f0305aa31ed085a04d916680c1", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4442, "license_type": "permissive", "max_line_length": 77, "num_lines": 124, "path": "/streetlearn/engine/python/streetlearn_engine_test.py", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "# Copyright 2018 Google LLC\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# https://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\"\"\"Tests for streetlearn_engine clif bindings.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport numpy as np\n\nfrom absl.testing import absltest\nfrom streetlearn.engine.python import streetlearn_engine\nfrom streetlearn.engine.python.test_dataset import TestDataset\n\n_PANO_OFFSET = 32\n\n\nclass StreetlearnEngineTest(absltest.TestCase):\n\n def setUp(self):\n TestDataset.Generate()\n self.dataset_path = TestDataset.GetPath()\n\n def test_build_graph(self):\n engine = streetlearn_engine.StreetLearnEngine.Create(\n self.dataset_path, TestDataset.kImageWidth, TestDataset.kImageHeight)\n engine.InitEpisode(0, 0)\n\n root = engine.BuildGraphWithRoot('1')\n self.assertEqual(root, '1')\n\n # Check that the right sized graph is returned.\n engine.BuildRandomGraph()\n graph = engine.GetGraph()\n self.assertEqual(len(graph), TestDataset.kPanoCount)\n\n def test_set_position(self):\n engine = streetlearn_engine.StreetLearnEngine.Create(\n self.dataset_path, TestDataset.kImageWidth, TestDataset.kImageHeight)\n engine.InitEpisode(0, 0)\n engine.BuildGraphWithRoot('1')\n\n # Set position a couple of times and check the result.\n self.assertEqual(engine.SetPosition('1'), '1')\n self.assertEqual(engine.GetPano().id, '1')\n self.assertEqual(engine.SetPosition('2'), '2')\n self.assertEqual(engine.GetPano().id, '2')\n\n # Currently facing north so cannot move to the next pano.\n self.assertEqual(engine.MoveToNextPano(), '2')\n\n # Rotate to face the next pano and move should succeed.\n engine.RotateObserver(_PANO_OFFSET, 0.0)\n self.assertEqual(engine.MoveToNextPano(), '3')\n self.assertEqual(engine.GetPano().id, '3')\n\n def test_pano_calculations(self):\n engine = streetlearn_engine.StreetLearnEngine.Create(\n self.dataset_path, TestDataset.kImageWidth, TestDataset.kImageHeight)\n engine.InitEpisode(0, 0)\n engine.BuildGraphWithRoot('1')\n\n self.assertEqual(engine.GetPitch(), 0)\n self.assertEqual(engine.GetYaw(), 0)\n self.assertAlmostEqual(engine.GetPanoDistance('1', '2'), 130.902, 3)\n\n def test_observation(self):\n engine = streetlearn_engine.StreetLearnEngine.Create(\n self.dataset_path, TestDataset.kImageWidth, TestDataset.kImageHeight)\n engine.InitEpisode(0, 0)\n engine.BuildGraphWithRoot('1')\n\n # Check that obervations have the right values.\n buffer_size = 3 * TestDataset.kImageWidth * TestDataset.kImageHeight\n obs = np.zeros(buffer_size, dtype=np.ubyte)\n engine.RenderObservation(obs)\n for i in range(0, TestDataset.kImageHeight):\n for j in range(0, TestDataset.kImageWidth):\n index = i * TestDataset.kImageWidth + j\n self.assertIn(obs[index], range(0, 232))\n\n def test_neighbors(self):\n engine = streetlearn_engine.StreetLearnEngine.Create(\n self.dataset_path, TestDataset.kImageWidth, TestDataset.kImageHeight)\n engine.InitEpisode(0, 0)\n engine.BuildGraphWithRoot('1')\n engine.SetPosition('2')\n\n # Should have two neighbors.\n occupancy = engine.GetNeighborOccupancy(4)\n self.assertEqual(len(occupancy), 4)\n self.assertEqual(occupancy[0], 1)\n self.assertEqual(occupancy[1], 0)\n self.assertEqual(occupancy[2], 1)\n self.assertEqual(occupancy[3], 0)\n\n def test_metadata(self):\n engine = streetlearn_engine.StreetLearnEngine.Create(\n self.dataset_path, TestDataset.kImageWidth, TestDataset.kImageHeight)\n engine.InitEpisode(0, 0)\n engine.BuildGraphWithRoot('1')\n\n # Check that the right metadata is returned.\n metadata = engine.GetMetadata('1')\n self.assertEqual(metadata.pano.id, '1')\n self.assertEqual(len(metadata.neighbors), 1)\n self.assertEqual(metadata.neighbors[0].id, '2')\n self.assertEqual(metadata.graph_depth, 10)\n\nif __name__ == '__main__':\n absltest.main()\n" }, { "alpha_fraction": 0.7444444298744202, "alphanum_fraction": 0.7511110901832581, "avg_line_length": 31.926828384399414, "blob_id": "6d08ad57586f0c005f0e1c5d82e7d2162a54f339", "content_id": "e2a0250803a3adf507f83bd5017bc2e7d0273cb4", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1350, "license_type": "permissive", "max_line_length": 74, "num_lines": 41, "path": "/streetlearn/python/environment/goal_instruction_game.py", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "# Copyright 2019 Google LLC.\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\"\"\"StreetLearn level for the goal reward instruction-following game.\n\nIn this environment, the agent receives a reward for reaching the goal of\na given set of instructions.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl import logging\n\nfrom streetlearn.python.environment import instructions_curriculum\n\n\nclass GoalInstructionGame(instructions_curriculum.InstructionsCurriculum):\n \"\"\"StreetLang game with goal reward only.\"\"\"\n\n def __init__(self, config):\n \"\"\"Creates an instance of the StreetLearn level.\n\n Args:\n config: config dict of various settings.\n \"\"\"\n super(GoalInstructionGame, self).__init__(config)\n\n # Disable waypoint rewards.\n self._reward_at_waypoint = 0\n" }, { "alpha_fraction": 0.6671351194381714, "alphanum_fraction": 0.6691427230834961, "avg_line_length": 31.769737243652344, "blob_id": "157f9d35fe3dee22a892e14f3570f5bf2139babc", "content_id": "d634aab621ffa0ae8058a3277bd93b2b98ecdba7", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4981, "license_type": "permissive", "max_line_length": 80, "num_lines": 152, "path": "/streetlearn/python/environment/coin_game.py", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "# Copyright 2018 Google LLC.\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\"\"\"Coin game level.\n\nIn this environment, the agent receives a reward for every coin it collects.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl import logging\n\nimport numpy as np\n\nfrom streetlearn.python.environment import game\n\n\nclass CoinGame(game.Game):\n \"\"\"A simple game that allows an agent to explore the environment and collect\n coins yielding rewards, randomly scattered through the environment. Can be\n extended as needed to add more complex game logic.\"\"\"\n\n def __init__(self, config):\n \"\"\"Constructor.\n\n Panos can be assigned rewards (coins) randomly and the agent will receive\n the reward the first time they visit these panos.\n\n Args:\n config: config dict of various settings.\n \"\"\"\n super(CoinGame, self).__init__()\n\n # Create colors from the input lists.\n self._colors = {\n 'coin': config['color_for_coin'],\n 'touched': config['color_for_touched_pano'],\n }\n self._reward_per_coin = config['reward_per_coin']\n\n # List of panos (will be populated using the streetlearn object).\n self._pano_ids = None\n\n # Association between pano id and color.\n self._pano_id_to_color = {}\n\n # Panos that (can) contain coins.\n self._proportion_of_panos_with_coins = config[\n 'proportion_of_panos_with_coins']\n self._touched_pano_id_set = set()\n self._coin_pano_id_set = []\n self._num_coins = 0\n logging.info('Proportion of panos with coins: %f',\n self._proportion_of_panos_with_coins)\n logging.info('Reward per coin: %f', self._reward_per_coin)\n\n def on_step(self, streetlearn):\n \"\"\"Gets called after StreetLearn:step(). Updates the set of touched panos.\n\n Args:\n streetlearn: A streetlearn instance.\n \"\"\"\n self._touched_pano_id_set.add(streetlearn.current_pano_id)\n self._update_pano_id_to_color()\n\n def on_reset(self, streetlearn):\n \"\"\"Gets called after StreetLearn:reset().\n\n Clears the set of touched panos and randomly generates reward-yielding coins\n and populates pano_id_to_color.\n\n Args:\n streetlearn: a streetlearn instance.\n Returns:\n A newly populated pano_id_to_color dictionary.\n \"\"\"\n # Populate list of available panos.\n if not self._pano_ids:\n self._pano_ids = sorted(streetlearn.graph)\n\n self._touched_pano_id_set.clear()\n self._num_coins = int(\n self._proportion_of_panos_with_coins * len(self._pano_ids))\n print(\"Sampling {} coins through the environment\".format(self._num_coins))\n self._coin_pano_id_set = np.random.choice(\n self._pano_ids, self._num_coins, replace=False).tolist()\n self._pano_id_to_color = {coin_pano_id: self._colors['coin']\n for coin_pano_id in self._coin_pano_id_set}\n\n return self._pano_id_to_color\n\n def get_reward(self, streetlearn):\n \"\"\"Returns the reward from the last step.\n\n In this game, we give rewards when a coin is collected. Coins can be\n collected only once per episode and do not reappear.\n\n Args:\n streetlearn: a StreetLearn instance.\n Returns:\n reward: the reward from the last step.\n \"\"\"\n if streetlearn.current_pano_id in self._coin_pano_id_set:\n reward = self._reward_per_coin\n self._coin_pano_id_set.remove(streetlearn.current_pano_id)\n else:\n reward = 0\n return reward\n\n def get_info(self, streetlearn):\n \"\"\"\"Returns current information about the state of the environment.\n\n Args:\n streetlearn: a StreetLearn instance.\n Returns:\n info: information from the environment at the last step.\n \"\"\"\n info = {}\n info['num_coins_left'] = len(self._coin_pano_id_set)\n info['num_coins'] = self._num_coins\n info['current_pano_id'] = streetlearn.current_pano_id\n return info\n\n def done(self):\n \"\"\"Returns a flag indicating the end of the current episode.\n\n This game does not end when all the coins are collected.\n \"\"\"\n return False\n\n def highlighted_panos(self):\n \"\"\"Returns the list of highlighted panos and their colors.\"\"\"\n return self._pano_id_to_color\n\n def _update_pano_id_to_color(self):\n \"\"\"Update the pano id to color table.\"\"\"\n self._pano_id_to_color.update({touched_pano_id: self._colors['touched']\n for touched_pano_id\n in self._touched_pano_id_set})\n" }, { "alpha_fraction": 0.6393396854400635, "alphanum_fraction": 0.6541690230369568, "avg_line_length": 30.628318786621094, "blob_id": "fd74d8c4403bd6abe4e30f4498df57f9be8ad4e9", "content_id": "c2f9759547a49007f577b886e065f57b5230cb24", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3574, "license_type": "permissive", "max_line_length": 80, "num_lines": 113, "path": "/streetlearn/engine/image_test.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/image.h\"\n\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n\nnamespace streetlearn {\nnamespace {\n\nusing ::testing::Eq;\n\ntemplate <typename T>\nclass ImageTest : public ::testing::Test {};\nTYPED_TEST_SUITE_P(ImageTest);\n\nTYPED_TEST_P(ImageTest, EmptyImageTest) {\n constexpr int kChannels = 3;\n Image<TypeParam, kChannels> image;\n\n EXPECT_EQ(image.width(), 0);\n EXPECT_EQ(image.height(), 0);\n EXPECT_EQ(image.channels(), kChannels);\n EXPECT_TRUE(image.data().empty());\n EXPECT_EQ(image.pixel(0, 0), nullptr);\n}\n\nTYPED_TEST_P(ImageTest, EmptyImageViewTest) {\n constexpr int kChannels = 3;\n Image<TypeParam, kChannels> image;\n ImageView<TypeParam, kChannels> image_view(&image, 0, 0, image.width(),\n image.height());\n\n EXPECT_EQ(image_view.width(), 0);\n EXPECT_EQ(image_view.height(), 0);\n EXPECT_EQ(image_view.channels(), kChannels);\n EXPECT_EQ(image_view.pixel(0, 0), nullptr);\n}\n\nTYPED_TEST_P(ImageTest, CreationTest) {\n constexpr int kWidth = 5;\n constexpr int kHeight = 7;\n constexpr int kChannels = 4;\n Image<TypeParam, kChannels> image(kWidth, kHeight);\n EXPECT_EQ(image.width(), kWidth);\n EXPECT_EQ(image.height(), kHeight);\n EXPECT_EQ(image.channels(), kChannels);\n EXPECT_EQ(image.data().size(), kWidth * kHeight * kChannels);\n\n ImageView<TypeParam, kChannels> image_view(&image, 1, 1, kWidth - 1,\n kHeight - 1);\n EXPECT_EQ(image_view.width(), kWidth - 1);\n EXPECT_EQ(image_view.height(), kHeight - 1);\n EXPECT_EQ(image_view.channels(), kChannels);\n}\n\nTYPED_TEST_P(ImageTest, ImageAccessTest) {\n constexpr int kSize = 5;\n Image<TypeParam, 1> image(kSize, kSize);\n\n for (int i = 0; i < kSize; ++i) {\n EXPECT_THAT(*image.pixel(i, i), Eq(0));\n const TypeParam pixel = i;\n *image.pixel(i, i) = pixel;\n EXPECT_THAT(*image.pixel(i, i), Eq(pixel));\n\n for (int j = 0; j < kSize; ++j) {\n if (j <= i) {\n EXPECT_THAT(*image.pixel(j, j), Eq(static_cast<TypeParam>(j)));\n } else {\n EXPECT_THAT(*image.pixel(j, j), Eq(static_cast<TypeParam>(0)));\n }\n }\n }\n}\n\nTYPED_TEST_P(ImageTest, ImageViewAccessTest) {\n constexpr int kSize = 5;\n Image<TypeParam, 1> image(kSize, kSize);\n ImageView<TypeParam, 1> image_view(&image, 1, 1, kSize - 2, kSize - 2);\n\n for (int i = 0; i < kSize - 2; ++i) {\n *image_view.pixel(i, i) = static_cast<TypeParam>(i);\n }\n\n EXPECT_THAT(*image.pixel(0, 0), Eq(0));\n EXPECT_THAT(*image.pixel(kSize - 1, kSize - 1), Eq(0));\n\n for (int j = 1; j < kSize - 2; ++j) {\n EXPECT_THAT(*image.pixel(j, j), Eq(static_cast<TypeParam>(j - 1)));\n }\n}\n\nREGISTER_TYPED_TEST_SUITE_P(ImageTest, EmptyImageTest, EmptyImageViewTest,\n CreationTest, ImageAccessTest, ImageViewAccessTest);\n\nusing Types = ::testing::Types<unsigned char, float, double>;\nINSTANTIATE_TYPED_TEST_SUITE_P(TypedImageTests, ImageTest, Types);\n\n} // namespace\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.6172458529472351, "alphanum_fraction": 0.6304888725280762, "avg_line_length": 37.04166793823242, "blob_id": "3aa85b8f8dd96409f29078d0b7ec881ff180bff6", "content_id": "8f9d7d06b8752e0af1ccf1127dcdcc3e33712842", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10043, "license_type": "permissive", "max_line_length": 80, "num_lines": 264, "path": "/streetlearn/engine/pano_projection.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/pano_projection.h\"\n\n#include <cmath>\n#include <cstdint>\n#include <cstring>\n#include <iostream>\n#include <vector>\n\n#include <opencv2/calib3d/calib3d.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include \"absl/memory/memory.h\"\n#include \"streetlearn/engine/math_util.h\"\n\nnamespace {\n\n// Radius used in calculations of the X, Y, Z point cloud.\nstatic constexpr double PANO_RADIUS = 120.0;\n\n} // namespace\n\nnamespace streetlearn {\n\nnamespace {\n\n// Conversion from Image to OpenCV Mat.\nvoid ImageToOpenCV(const Image3_b& input, cv::Mat* output) {\n const int width = input.width();\n const int height = input.height();\n output->create(height, width, CV_8UC3);\n const auto image_data = input.data();\n std::copy(image_data.begin(), image_data.end(), output->data);\n}\n\n} // namespace\n\nstruct PanoProjection::Impl {\n Impl(double fov_deg, int proj_width, int proj_height)\n : fov_deg_(0), proj_width_(0), proj_height_(0) {\n // Update the projection size and pre-compute the centered XYZ point cloud.\n UpdateProjectionSize(fov_deg, proj_width, proj_height);\n }\n\n void Project(const cv::Mat& input, double yaw_deg, double pitch_deg,\n cv::Mat* output);\n\n // Prepares the centered XYZ point cloud for a specified field of view and\n // projection image width and height.\n cv::Mat PrepareXYZPointCloud();\n // Rotates a centered XYZ point cloud to given yaw and pitch angles.\n cv::Mat RotateXYZPointCloud(double yaw_deg, double pitch_deg);\n\n // Projects an XYZ point cloud to latitude and longitude maps, given panorama\n // image and projected image widths and heights.\n void ProjectXYZPointCloud(const cv::Mat& xyz, int pano_width, int pano_height,\n cv::Mat* map_lon, cv::Mat* map_lat);\n\n // Decodes the image.\n void Decode(int image_width, int image_height, int image_depth,\n int compressed_size, const char* compressed_image,\n std::vector<uint8_t>* output);\n\n // Updates the projected image size and field of view, and if there are\n // changes then recomputes the centered XYZ point cloud.\n void UpdateProjectionSize(double fov_deg, int proj_width, int proj_height);\n\n // Degrees of horizontal field of view.\n double fov_deg_;\n\n // Projected image size.\n int proj_width_;\n int proj_height_;\n\n // Point cloud of projected image coordinates, with zero yaw and pitch.\n cv::Mat xyz_centered_;\n};\n\ncv::Mat PanoProjection::Impl::PrepareXYZPointCloud() {\n // Vertical and horizontal fields of view.\n double fov_width_deg = fov_deg_;\n double fov_height_deg = fov_deg_ * proj_height_ / proj_width_;\n // Scale of the Y and Z grid.\n double half_fov_width_rad = math::DegreesToRadians(fov_width_deg / 2.0);\n double half_afov_width_rad =\n math::DegreesToRadians((180.0 - fov_width_deg) / 2.0);\n double half_fov_height_rad = math::DegreesToRadians(fov_height_deg / 2.0);\n double half_afov_height_rad =\n math::DegreesToRadians((180.0 - fov_height_deg) / 2.0);\n double ratio_width =\n std::sin(half_fov_width_rad) / std::sin(half_afov_width_rad);\n double scale_width = 2.0 * PANO_RADIUS * ratio_width / (proj_width_ - 1);\n double ratio_height =\n std::sin(half_fov_height_rad) / std::sin(half_afov_height_rad);\n double scale_height = 2.0 * PANO_RADIUS * ratio_height / (proj_height_ - 1);\n // Image centres for the projection.\n double c_x = (proj_width_ - 1.0) / 2.0;\n double c_y = (proj_height_ - 1.0) / 2.0;\n\n // Create the 3D point cloud for X, Y, Z coordinates of the image projected\n // on a sphere.\n cv::Mat xyz_centered;\n xyz_centered.create(3, proj_height_ * proj_width_, CV_32FC1);\n for (int i = 0, k = 0; i < proj_height_; i++) {\n for (int j = 0; j < proj_width_; j++, k++) {\n double x_ij = PANO_RADIUS;\n double y_ij = (j - c_x) * scale_width;\n double z_ij = -(i - c_y) * scale_height;\n double d_ij = std::sqrt(x_ij * x_ij + y_ij * y_ij + z_ij * z_ij);\n double coeff = PANO_RADIUS / d_ij;\n xyz_centered.at<float>(0, k) = coeff * x_ij;\n xyz_centered.at<float>(1, k) = coeff * y_ij;\n xyz_centered.at<float>(2, k) = coeff * z_ij;\n }\n }\n return xyz_centered;\n}\n\ncv::Mat PanoProjection::Impl::RotateXYZPointCloud(double yaw_deg,\n double pitch_deg) {\n // Rotation matrix for yaw.\n float z_axis_data[3] = {0.0, 0.0, 1.0};\n cv::Mat z_axis(3, 1, CV_32FC1, z_axis_data);\n cv::Mat z_rotation_vec = z_axis * math::DegreesToRadians(yaw_deg);\n cv::Mat z_rotation_mat(3, 3, CV_32FC1);\n cv::Rodrigues(z_rotation_vec, z_rotation_mat);\n\n // Rotation matrix for pitch.\n float y_axis_data[3] = {0.0, 1.0, 0.0};\n cv::Mat y_axis(3, 1, CV_32FC1, y_axis_data);\n cv::Mat y_rotation_vec =\n z_rotation_mat * y_axis * math::DegreesToRadians(-pitch_deg);\n cv::Mat y_rotation_mat(3, 3, CV_32FC1);\n cv::Rodrigues(y_rotation_vec, y_rotation_mat);\n\n // Apply yaw and pitch rotation to the point cloud.\n cv::Mat xyz_rotated = y_rotation_mat * (z_rotation_mat * xyz_centered_);\n\n return xyz_rotated;\n}\n\nvoid PanoProjection::Impl::ProjectXYZPointCloud(const cv::Mat& xyz,\n int pano_width, int pano_height,\n cv::Mat* map_lon,\n cv::Mat* map_lat) {\n // Image centres for the panorama.\n double pano_c_x = (pano_width - 1.0) / 2.0;\n double pano_c_y = (pano_height - 1.0) / 2.0;\n\n map_lat->create(proj_height_, proj_width_, CV_32FC1);\n map_lon->create(proj_height_, proj_width_, CV_32FC1);\n\n for (int i = 0, k = 0; i < proj_height_; i++) {\n for (int j = 0; j < proj_width_; j++, k++) {\n // Project the Z coordinate into latitude.\n double z_ij = xyz.at<float>(2, k);\n double sin_lat_ij = z_ij / PANO_RADIUS;\n double lat_ij = std::asin(sin_lat_ij);\n map_lat->at<float>(i, j) = -lat_ij / CV_PI * 2.0 * pano_c_y + pano_c_y;\n // Project the X and Y coordinates into longitude.\n double x_ij = xyz.at<float>(0, k);\n double y_ij = xyz.at<float>(1, k);\n double tan_theta_ij = y_ij / x_ij;\n double theta_ij = std::atan(tan_theta_ij);\n double lon_ij;\n if (x_ij > 0) {\n lon_ij = theta_ij;\n } else {\n if (y_ij > 0) {\n lon_ij = theta_ij + CV_PI;\n } else {\n lon_ij = theta_ij - CV_PI;\n }\n }\n map_lon->at<float>(i, j) = lon_ij / CV_PI * pano_c_x + pano_c_x;\n }\n }\n}\n\nvoid PanoProjection::Impl::UpdateProjectionSize(double fov_deg, int proj_width,\n int proj_height) {\n // Update only if there is a change.\n if ((proj_width_ != proj_width) || (proj_height_ != proj_height) ||\n (fov_deg != fov_deg_)) {\n fov_deg_ = fov_deg;\n proj_width_ = proj_width;\n proj_height_ = proj_height;\n\n // If updated the projected image or field of view parameters,\n // recompute the centered XYZ point cloud.\n xyz_centered_ = PrepareXYZPointCloud();\n }\n}\n\nvoid PanoProjection::Impl::Decode(int image_width, int image_height,\n int image_depth, int compressed_size,\n const char* compressed_image,\n std::vector<uint8_t>* output) {\n std::vector<uint8_t> input(compressed_image,\n compressed_image + compressed_size);\n cv::Mat mat = cv::imdecode(cv::Mat(input), CV_LOAD_IMAGE_ANYDEPTH);\n output->resize(image_width * image_height * image_depth);\n output->assign(mat.datastart, mat.dataend);\n}\n\nvoid PanoProjection::Impl::Project(const cv::Mat& input, double yaw_deg,\n double pitch_deg, cv::Mat* output) {\n // Assuming that the field of view has not changed, check for updates of\n // the projected image size, and optionally recompute the centered XYZ\n // point cloud.\n int proj_width = output->cols;\n int proj_height = output->rows;\n UpdateProjectionSize(fov_deg_, proj_width, proj_height);\n\n // Rotate the XYZ point cloud by given yaw and pitch.\n cv::Mat xyz = RotateXYZPointCloud(yaw_deg, pitch_deg);\n\n // Project the rotated XYZ point cloud to latitude and longitude maps.\n int pano_width = input.cols;\n int pano_height = input.rows;\n cv::Mat map_lon;\n cv::Mat map_lat;\n ProjectXYZPointCloud(xyz, pano_width, pano_height, &map_lon, &map_lat);\n\n // Remap from input to output given the latitude and longitude maps.\n cv::remap(input, *output, map_lon, map_lat, CV_INTER_CUBIC, cv::BORDER_WRAP);\n}\n\nPanoProjection::PanoProjection(double fov_deg, int proj_width, int proj_height)\n : impl_(absl::make_unique<PanoProjection::Impl>(fov_deg, proj_width,\n proj_height)) {}\n\nPanoProjection::~PanoProjection() {}\n\nvoid PanoProjection::Project(const Image3_b& input, double yaw_deg,\n double pitch_deg, Image3_b* output) {\n cv::Mat input_cv;\n ImageToOpenCV(input, &input_cv);\n cv::Mat output_cv;\n output_cv.create(impl_->proj_height_, impl_->proj_width_, CV_8UC3);\n impl_->Project(input_cv, yaw_deg, pitch_deg, &output_cv);\n std::memcpy(output->pixel(0, 0), output_cv.data,\n impl_->proj_width_ * impl_->proj_height_ * 3);\n}\n\nvoid PanoProjection::ChangeFOV(double fov_deg) {\n impl_->UpdateProjectionSize(fov_deg, impl_->proj_width_, impl_->proj_height_);\n}\n\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.7175140976905823, "alphanum_fraction": 0.7253745794296265, "avg_line_length": 35.34821319580078, "blob_id": "2c73f2c52bac109be970bf60f3f19abf2960f9fc", "content_id": "2820391f3c65d148c549d8dddf15eb8e5a66bf91", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4071, "license_type": "permissive", "max_line_length": 79, "num_lines": 112, "path": "/streetlearn/engine/pano_renderer.h", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#ifndef STREETLEARN_PANO_RENDERER_H_\n#define STREETLEARN_PANO_RENDERER_H_\n\n#include <cstdint>\n#include <map>\n#include <vector>\n\n#include <cairo/cairo.h>\n#include \"streetlearn/engine/color.h\"\n#include \"streetlearn/engine/pano_graph_node.h\"\n#include \"streetlearn/engine/pano_projection.h\"\n#include \"streetlearn/proto/streetlearn.pb.h\"\n\nnamespace streetlearn {\n\n// Renders a StreetLearn pano image along with an (optional) status bar along\n// the bottom indicating which directions of travel are available. All angles\n// are specified in degrees.\nclass PanoRenderer {\n public:\n // Height is the total screen height, including status_height.\n PanoRenderer(int screen_width, int screen_height, int status_height,\n double fov_deg);\n ~PanoRenderer();\n\n // Renders the input image at the given orientation. The global_yaw is the\n // start heading for the episode and yaw is any additional offset from it.\n // The tolerance determines which bearings are regarded as being in range and\n // can be moved to - these are rendered a different color from the rest.\n // Inaccessible nodes are marked with a no-entry sign.\n void RenderScene(\n const Image3_b& input, double global_yaw, double yaw, double pitch,\n double tolerance, const std::vector<PanoNeighborBearing>& bearings,\n const std::map<int, std::vector<TerminalGraphNode>>& inaccessible);\n\n // Returns the contents of the pixel buffer which has the format 1 byte per\n // pixel RGB.\n const std::vector<uint8_t>& Pixels() const { return pixels_; }\n\n // Returns the unique value in the range [-constraint, +constraint) that is\n // equivalent to input_angle. This considers two angles a, b to be equivalent\n // whenever a - b is an integral multiple of 2 * constraint.\n // For example:\n // ConstrainAngle(187, 180) --> 7\n // ConstrainAngle(180, 180) --> -180\n static double ConstrainAngle(double constraint, double input_angle);\n\n private:\n // Projects the portion of the pano at the given yaw and pitch.\n void ProjectPano(const Image3_b& input, double yaw, double pitch);\n\n // Draws the status bar into the image.\n void DrawStatusBar(double tolerance, double current_bearing,\n const std::vector<PanoNeighborBearing>& bearings);\n\n // Draws a bearing marker on the status bar.\n void DrawBearing(double current_bearing, double bearing, const Color& color);\n\n // Draw no entry signs where the graph has been cut at terminal nodes.\n void DrawNoEntrySigns(\n double global_yaw, double current_bearing, double current_pitch,\n const std::map<int, std::vector<TerminalGraphNode>>& inaccessible);\n\n // The dimensions of the output image.\n int width_;\n int height_;\n\n // The field of view of the output image in degrees.\n double fov_deg_;\n\n // The height of the status bar in pixels.\n int status_height_;\n\n // The width of a no entry sign in pixels.\n int no_entry_width_;\n\n // Degrees per-pixel in the output.\n double degrees_pp_;\n\n // Cairo objects used for rendering the status bar. Owned by PanoRenderer.\n cairo_surface_t* surface_;\n cairo_t* context_;\n\n // Buffer into which to re-project the StreetLearn image.\n Image3_b pano_buffer_;\n\n // Buffer for the status bar.\n std::vector<uint8_t> status_pixels_;\n\n // Buffer for the whole screen.\n std::vector<uint8_t> pixels_;\n\n // Handles the projection from equiractangular co-ordinates.\n PanoProjection pano_projection_;\n};\n\n} // namespace streetlearn\n#endif // STREETLEARN_PANO_RENDERER_H_\n" }, { "alpha_fraction": 0.826815664768219, "alphanum_fraction": 0.826815664768219, "avg_line_length": 58.66666793823242, "blob_id": "86795afd2b5870030d4f356829c1dd3aa9401174", "content_id": "55eb50ac918b47a233240518d25c63d95ea2a55a", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 179, "license_type": "permissive", "max_line_length": 90, "num_lines": 3, "path": "/get_scalable_agent.sh", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "#!/bin/bash\ngit clone https://github.com/deepmind/scalable_agent.git streetlearn/python/scalable_agent\ncp third_party/scalable_agent.BUILD streetlearn/python/scalable_agent/BUILD\n" }, { "alpha_fraction": 0.6695942878723145, "alphanum_fraction": 0.6959431171417236, "avg_line_length": 38.196720123291016, "blob_id": "47a849f50820cb4540f8c72fe8daa5c048da69c8", "content_id": "6ac24707f5a28f80bf482f9489e659108e2e438d", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2391, "license_type": "permissive", "max_line_length": 79, "num_lines": 61, "path": "/streetlearn/engine/pano_calculations.h", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#ifndef THIRD_PARTY_STREETLEARN_ENGINE_PANO_CALCULATIONS_H_\n#define THIRD_PARTY_STREETLEARN_ENGINE_PANO_CALCULATIONS_H_\n\n#include <cmath>\n#include <random>\n\n#include \"streetlearn/engine/pano_graph_node.h\"\n\nnamespace streetlearn {\n\nconstexpr double kEarthRadiusInMetres = 6371000.0;\n\n// Converts the given angle from degrees to radians.\ninline double DegreesToRadians(double angle_in_degrees) {\n return angle_in_degrees * M_PI / 180;\n}\n\n// Returns the bearing between the panos in degrees.\ninline double BearingBetweenPanos(const streetlearn::Pano& pano1,\n const streetlearn::Pano& pano2) {\n double lat1 = DegreesToRadians(pano1.coords().lat());\n double lon1 = DegreesToRadians(pano1.coords().lng());\n double lat2 = DegreesToRadians(pano2.coords().lat());\n double lon2 = DegreesToRadians(pano2.coords().lng());\n double x = std::cos(lat1) * std::sin(lat2) -\n std::sin(lat1) * std::cos(lat2) * std::cos(lon2 - lon1);\n double y = std::sin(lon2 - lon1) * std::cos(lat2);\n return 180.0 * std::atan2(y, x) / M_PI;\n}\n\n// Uses the Haversine formula to compute the distance between the panos in\n// meters.\ninline double DistanceBetweenPanos(const streetlearn::Pano& pano1,\n const streetlearn::Pano& pano2) {\n double lat1 = DegreesToRadians(pano1.coords().lat());\n double lon1 = DegreesToRadians(pano1.coords().lng());\n double lat2 = DegreesToRadians(pano2.coords().lat());\n double lon2 = DegreesToRadians(pano2.coords().lng());\n double u = std::sin((lat2 - lat1) / 2);\n double v = std::sin((lon2 - lon1) / 2);\n return 2.0 * kEarthRadiusInMetres *\n std::asin(std::sqrt(u * u + std::cos(lat1) * std::cos(lat2) * v * v));\n}\n\n} // namespace streetlearn\n\n#endif // THIRD_PARTY_STREETLEARN_ENGINE_PANO_CALCULATIONS_H_\n" }, { "alpha_fraction": 0.6619459986686707, "alphanum_fraction": 0.6695515513420105, "avg_line_length": 35.31428527832031, "blob_id": "c9f016881936e8ccc923afb83e11176a69d8f47c", "content_id": "cecd64e8ac74764f1ca6f6ce926c85b0f2832830", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3813, "license_type": "permissive", "max_line_length": 77, "num_lines": 105, "path": "/streetlearn/python/ui/scan_agent.py", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "# Copyright 2018 Google LLC.\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\"\"\"Basic panorama scanning agent for StreetLearn.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\n\nimport time\nimport numpy as np\nimport pygame\n\nfrom streetlearn.python.environment import coin_game\nfrom streetlearn.python.environment import default_config\nfrom streetlearn.python.environment import streetlearn\n\nFLAGS = flags.FLAGS\nflags.DEFINE_integer(\"width\", 400, \"Observation and map width.\")\nflags.DEFINE_integer(\"height\", 400, \"Observation and map height.\")\nflags.DEFINE_string(\"dataset_path\", None, \"Dataset path.\")\nflags.DEFINE_string(\"list_pano_ids_yaws\", None, \"List of pano IDs and yaws.\")\nflags.DEFINE_bool(\"save_images\", False, \"Save the images?\")\nflags.mark_flag_as_required(\"dataset_path\")\nflags.mark_flag_as_required(\"list_pano_ids_yaws\")\n\n\ndef interleave(array, w, h):\n \"\"\"Turn a planar RGB array into an interleaved one.\n\n Args:\n array: An array of bytes consisting the planar RGB image.\n w: Width of the image.\n h: Height of the image.\n Returns:\n An interleaved array of bytes shape shaped (h, w, 3).\n \"\"\"\n arr = array.reshape(3, w * h)\n return np.ravel((arr[0], arr[1], arr[2]),\n order='F').reshape(h, w, 3).swapaxes(0, 1)\n\ndef loop(env, screen, pano_ids_yaws):\n \"\"\"Main loop of the scan agent.\"\"\"\n for (pano_id, yaw) in pano_ids_yaws:\n\n # Retrieve the observation at a specified pano ID and heading.\n logging.info('Retrieving view at pano ID %s and yaw %f', pano_id, yaw)\n observation = env.goto(pano_id, yaw)\n\n current_yaw = observation[\"yaw\"]\n view_image = interleave(observation[\"view_image\"],\n FLAGS.width, FLAGS.height)\n graph_image = interleave(observation[\"graph_image\"],\n FLAGS.width, FLAGS.height)\n screen_buffer = np.concatenate((view_image, graph_image), axis=1)\n pygame.surfarray.blit_array(screen, screen_buffer)\n pygame.display.update()\n\n for event in pygame.event.get():\n if (event.type == pygame.QUIT or\n (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE)):\n return\n if FLAGS.save_images:\n filename = 'scan_agent_{}_{}.bmp'.format(pano_id, yaw)\n pygame.image.save(screen, filename)\n\ndef main(argv):\n config = {'width': FLAGS.width,\n 'height': FLAGS.height,\n 'graph_width': FLAGS.width,\n 'graph_height': FLAGS.height,\n 'graph_zoom': 1,\n 'full_graph': True,\n 'proportion_of_panos_with_coins': 0.0,\n 'action_spec': 'streetlearn_fast_rotate',\n 'observations': ['view_image', 'graph_image', 'yaw']}\n with open(FLAGS.list_pano_ids_yaws, 'r') as f:\n lines = f.readlines()\n pano_ids_yaws = [(line.split('\\t')[0], float(line.split('\\t')[1]))\n for line in lines]\n config = default_config.ApplyDefaults(config)\n game = coin_game.CoinGame(config)\n env = streetlearn.StreetLearn(FLAGS.dataset_path, config, game)\n env.reset()\n pygame.init()\n screen = pygame.display.set_mode((FLAGS.width, FLAGS.height * 2))\n loop(env, screen, pano_ids_yaws)\n\nif __name__ == '__main__':\n app.run(main)\n" }, { "alpha_fraction": 0.6215062737464905, "alphanum_fraction": 0.6330274939537048, "avg_line_length": 34.50757598876953, "blob_id": "589e461a2cd36f82625b9f136b39c4e9a49363f0", "content_id": "f7e0ef92a905969b90d4afa91be4ddd58d359f1f", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4687, "license_type": "permissive", "max_line_length": 80, "num_lines": 132, "path": "/streetlearn/engine/graph_region_mapper.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/graph_region_mapper.h\"\n\n#include \"streetlearn/engine/logging.h\"\n#include \"streetlearn/engine/vector.h\"\n#include \"s2/s1angle.h\"\n\nnamespace streetlearn {\n\nconstexpr double kMargin = 0.05;\n\nvoid GraphRegionMapper::SetGraphBounds(const S2LatLngRect& graph_bounds) {\n graph_bounds_ = graph_bounds;\n CalculateSceneMargin();\n}\n\nvoid GraphRegionMapper::ResetCurrentBounds(double zoom) {\n S2LatLng image_centre((graph_bounds_.lat_lo() + graph_bounds_.lat_hi()) / 2,\n (graph_bounds_.lng_lo() + graph_bounds_.lng_hi()) / 2);\n SetCurrentBounds(zoom, image_centre);\n}\n\nvoid GraphRegionMapper::SetCurrentBounds(double zoom,\n const S2LatLng& image_centre) {\n S1Angle lat_min = graph_bounds_.lat_lo() - margin_.lat();\n S1Angle lat_max = graph_bounds_.lat_hi() + margin_.lat();\n S1Angle lng_min = graph_bounds_.lng_lo() - margin_.lng();\n S1Angle lng_max = graph_bounds_.lng_hi() + margin_.lng();\n\n CHECK_GT(zoom, 0);\n\n S1Angle lat_range = (lat_max - lat_min) / zoom;\n S1Angle lng_range = (lng_max - lng_min) / zoom;\n\n // Shift the bounds if any lie off-screen.\n S1Angle minLat = image_centre.lat() - lat_range / 2;\n S1Angle lat_diff;\n if (minLat < lat_min) {\n lat_diff = lat_min - minLat;\n minLat = lat_min;\n }\n S1Angle maxLat = image_centre.lat() + lat_range / 2 + lat_diff;\n if (maxLat > lat_max) {\n minLat -= maxLat - lat_max;\n maxLat = lat_max;\n }\n\n S1Angle minLng = image_centre.lng() - lng_range / 2;\n S1Angle lng_diff;\n if (minLng < lng_min) {\n lng_diff = lng_min - minLng;\n minLng = lng_min;\n }\n S1Angle maxLng = image_centre.lng() + lng_range / 2 + lng_diff;\n if (maxLng > lng_max) {\n minLng -= maxLng - lng_max;\n maxLng = lng_max;\n }\n\n current_bounds_ =\n S2LatLngRect(S2LatLng(minLat, minLng), S2LatLng(maxLat, maxLng));\n}\n\nVector2_d GraphRegionMapper::MapToScreen(double lat, double lng) const {\n double lat_range =\n (current_bounds_.lat_hi() - current_bounds_.lat_lo()).degrees();\n double lng_range =\n (current_bounds_.lng_hi() - current_bounds_.lng_lo()).degrees();\n\n double x_coord =\n (lng - current_bounds_.lng_lo().degrees()) * screen_size_.x() / lng_range;\n double y_coord =\n (lat - current_bounds_.lat_lo().degrees()) * screen_size_.y() / lat_range;\n\n return {x_coord, screen_size_.y() - y_coord};\n}\n\nVector2_d GraphRegionMapper::MapToBuffer(double lat, double lng,\n int image_width,\n int image_height) const {\n S1Angle lat_range =\n (graph_bounds_.lat_hi() - graph_bounds_.lat_lo() + 2.0 * margin_.lat());\n S1Angle lng_range =\n (graph_bounds_.lng_hi() - graph_bounds_.lng_lo() + 2.0 * margin_.lng());\n\n double x_coord = (lng - (graph_bounds_.lng_lo() - margin_.lng()).degrees()) *\n image_width / lng_range.degrees();\n double y_coord = (lat - (graph_bounds_.lat_lo() - margin_.lat()).degrees()) *\n image_height / lat_range.degrees();\n\n return {x_coord, image_height - y_coord};\n}\n\nvoid GraphRegionMapper::CalculateSceneMargin() {\n double lat_range =\n (graph_bounds_.lat_hi() - graph_bounds_.lat_lo()).degrees();\n double lng_range =\n (graph_bounds_.lng_hi() - graph_bounds_.lng_lo()).degrees();\n double aspect_ratio =\n static_cast<double>(screen_size_.x()) / screen_size_.y();\n\n if (lat_range > lng_range) {\n lat_range *= aspect_ratio;\n double lat_margin = lat_range * kMargin;\n double deg_ppx = (lat_range + 2.0 * lat_margin) / screen_size_.y();\n double total_lng = screen_size_.x() * deg_ppx;\n double lng_margin = (total_lng - lng_range) / 2;\n margin_ = S2LatLng::FromDegrees(lat_margin, lng_margin);\n } else {\n lng_range *= aspect_ratio;\n double lng_margin = lng_range * kMargin;\n double deg_ppx = (lng_range + 2.0 * lng_margin) / screen_size_.x();\n double total_lat = screen_size_.y() * deg_ppx;\n double lat_margin = (total_lat - lat_range) / 2;\n margin_ = S2LatLng::FromDegrees(lat_margin, lng_margin);\n }\n}\n\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.737038791179657, "alphanum_fraction": 0.7407753467559814, "avg_line_length": 34.09836196899414, "blob_id": "685c047009d5a3b628a14742a9b632cf09363dbd", "content_id": "c8fdaeb56ba86d29442b5d379544995cc880ad67", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2141, "license_type": "permissive", "max_line_length": 79, "num_lines": 61, "path": "/streetlearn/engine/dataset.h", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#ifndef THIRD_PARTY_STREETLEARN_ENGINE_DATASET_H_\n#define THIRD_PARTY_STREETLEARN_ENGINE_DATASET_H_\n\n#include <memory>\n#include <string>\n\n#include \"absl/strings/string_view.h\"\n#include \"leveldb/db.h\"\n#include \"streetlearn/proto/streetlearn.pb.h\"\n\nnamespace streetlearn {\n\n// Dataset is a wrapper around a StreetLearn dataset, that currently resides in\n// LevelDB files.\nclass Dataset {\n public:\n // The key used to access the connectivity graph in the underlying database.\n static constexpr char kGraphKey[] = \"panos_connectivity\";\n\n // Create a Dataset instance that is initialised to use the levelDB database\n // at `dataset_path` on the filesystem.\n static std::unique_ptr<Dataset> Create(const std::string& dataset_path);\n\n // Construct Dataset using an already open levelDB instance. Only for testing\n // purposes. Regular users should use the Create factory method.\n Dataset(std::unique_ptr<leveldb::DB> db);\n\n Dataset(const Dataset&) = delete;\n Dataset& operator=(const Dataset&) = delete;\n\n // Get the connectivity graph from the dataset.\n bool GetGraph(StreetLearnGraph* graph) const;\n\n // Get a Pano associated with `pano_id` from the dataset. If the `pano_id` is\n // unknown, the function returns false.\n bool GetPano(absl::string_view pano_id, Pano* pano) const;\n\n private:\n // Try to get a string value stored in the dataset under `key`.\n bool GetValue(absl::string_view key, std::string* value) const;\n\n std::unique_ptr<leveldb::DB> db_;\n};\n\n} // namespace streetlearn\n\n#endif // THIRD_PARTY_STREETLEARN_ENGINE_DATASET_H_\n" }, { "alpha_fraction": 0.66689532995224, "alphanum_fraction": 0.6729933619499207, "avg_line_length": 44.39446258544922, "blob_id": "93ecac64e06ab45ebba7dca6262afe0f793f09cc", "content_id": "07513c523da664c882c098a2d48bcbff8344b76b", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13119, "license_type": "permissive", "max_line_length": 80, "num_lines": 289, "path": "/streetlearn/python/environment/instructions_curriculum.py", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "# Copyright 2019 Google LLC.\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\"\"\"StreetLearn level for the instruction-following game with a curriculum.\n\nThis environment implements the instruction-following game and selects levels\ngiven a particular curriculum strategy, either by slowly increasing the number\nof instructions per episode, the maximum distance of routes, or both.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\nimport time\nfrom absl import logging\nimport numpy as np\nimport six\nfrom six.moves import range\n\nfrom streetlearn.python.environment import instructions_base\n\n_SECONDS_IN_HOUR = 3600\n\n\n# Curriculum constants.\nCURRICULUM_NONE = 0\nCURRICULUM_LENGTH_BASED = 1\nCURRICULUM_INSTR_BASED = 2\nCURRICULUM_LENGTH_INSTR_BASED = 3\n\n# Verbosity constants\nNUM_TRAJECTORIES_VERBOSE = 10000\n\n\nclass InstructionsCurriculum(instructions_base.InstructionsBase):\n \"\"\"Instruction following game with curriculum on distance or #instructions.\"\"\"\n\n def __init__(self, config):\n \"\"\"Creates an instance of the StreetLearn level.\n\n Args:\n config: config dict of various settings.\n \"\"\"\n super(InstructionsCurriculum, self).__init__(config)\n\n # Curriculum types: 0 = none, 1 = dist. to goal, 2 = instructions\n self._curriculum_type = config['instruction_curriculum_type']\n self._timestamp_start = config['timestamp_start_curriculum']\n self._hours_curriculum_part_1 = config['hours_curriculum_part_1']\n self._hours_curriculum_part_2 = config['hours_curriculum_part_2']\n self._steps_plateau = config.get('curriculum_steps_plateau', 0)\n self._steps_ramp = config.get('curriculum_steps_ramp', 0)\n self._curriculum_num_instructions_part_1 = config[\n 'curriculum_num_instructions_part_1']\n self._min_goal_distance = config['min_goal_distance_curriculum']\n self._max_goal_distance = config['max_goal_distance_curriculum']\n self._curriculum_bin_distance = config['curriculum_bin_distance']\n if self._curriculum_type != CURRICULUM_NONE:\n logging.info('Curriculum starting at time %f', self._timestamp_start)\n if (self._curriculum_type == CURRICULUM_LENGTH_BASED) or (\n self._curriculum_type == CURRICULUM_LENGTH_INSTR_BASED):\n logging.info('Initial plateau: trajectories of distance at most %f',\n self._min_goal_distance)\n logging.info('Training ramps up to trajectories of distance at most %f',\n self._max_goal_distance)\n logging.info('Trajectories sorted in bins of distance length %f',\n self._curriculum_bin_distance)\n if (self._curriculum_type == CURRICULUM_INSTR_BASED) or (\n self._curriculum_type == CURRICULUM_LENGTH_INSTR_BASED):\n logging.info('Initial plateau: trajectories with %d instructions',\n self._curriculum_num_instructions_part_1)\n logging.info('Training ramps up to trajectories with %d instructions',\n self._num_instructions)\n logging.info('Initial training plateau lasts for %f hours',\n self._hours_curriculum_part_1)\n logging.info('Training ramps up to longer traj. for %f hours',\n self._hours_curriculum_part_2)\n\n # Frame cap curriculum\n self._curriculum_frame_cap = config['curriculum_frame_cap']\n self._curriculum_frame_cap_part_1 = config['curriculum_frame_cap_part_1']\n self._curriculum_frame_cap_extra_steps = max(\n 0, config['frame_cap'] - self._curriculum_frame_cap_part_1)\n if self._curriculum_frame_cap:\n logging.info('Initial plateau: trajectories with %d frames',\n self._curriculum_frame_cap_part_1)\n logging.info('Training ramps up to trajectories with %d extra frames',\n self._curriculum_frame_cap_extra_steps)\n\n self._init_complete = self.initialize_curricula(True)\n\n def initialize_curricula(self, first_init=False):\n \"\"\"Initializes the curriculum code.\n\n Args:\n first_init: If true, container variables are created. Should\n be false for all subsequent calls.\n\n Returns:\n True if curriculum has been fully established, False otherwise.\n \"\"\"\n\n num_bins_distance = int(math.ceil(\n self._max_goal_distance / self._curriculum_bin_distance))\n if first_init:\n self._curriculum_count = 0\n self._trajectory_data_map_per_distance = {\n k: [] for k in range(num_bins_distance + 1)\n }\n self._trajectory_data_map_per_waypoints = {\n k: [] for k in range(self._num_instructions + 1)\n }\n\n if self._curriculum_type == CURRICULUM_LENGTH_BASED:\n # Bin the trajectories by length\n for index in range(self._num_trajectories):\n v = self._trajectory_data[index]\n self._curriculum_count += 1\n # Note: goal.length stores the overall length of a route.\n bin_distance = int(\n math.ceil(v.goal.length / self._curriculum_bin_distance))\n for k in range(bin_distance, num_bins_distance + 1):\n self._trajectory_data_map_per_distance[k].append(index)\n if (self._curriculum_count % NUM_TRAJECTORIES_VERBOSE) == 0:\n logging.info('Processed %d trajectories', self._curriculum_count)\n return False\n for k in range(num_bins_distance + 1):\n logging.info('%d trajectories with distance at most %f',\n len(self._trajectory_data_map_per_distance[k]),\n k * self._curriculum_bin_distance)\n\n if self._curriculum_type == CURRICULUM_INSTR_BASED:\n # Bin the trajectories by number of instructions (waypoints)\n for index in range(self._num_trajectories):\n v = self._trajectory_data[index]\n self._curriculum_count += 1\n num_waypoints = len(v.steps)\n for k in range(num_waypoints, self._num_instructions + 1):\n self._trajectory_data_map_per_waypoints[k].append(index)\n if (self._curriculum_count % NUM_TRAJECTORIES_VERBOSE) == 0:\n logging.info('Processed %d trajectories', self._curriculum_count)\n return False\n for k in range(self._num_instructions + 1):\n logging.info('%d trajectories with %d instructions',\n len(self._trajectory_data_map_per_waypoints[k]), k)\n\n if self._curriculum_type == CURRICULUM_LENGTH_INSTR_BASED:\n # Bin the trajectories by length and instructions\n for index in range(self._num_trajectories):\n v = self._trajectory_data[index]\n self._curriculum_count += 1\n bin_distance = int(\n math.ceil(v.goal.length / self._curriculum_bin_distance))\n for k in range(bin_distance, num_bins_distance + 1):\n self._trajectory_data_map_per_distance[k].append(index)\n num_waypoints = len(v.steps)\n for k in range(num_waypoints, self._num_instructions + 1):\n self._trajectory_data_map_per_waypoints[k].append(index)\n if (self._curriculum_count % NUM_TRAJECTORIES_VERBOSE) == 0:\n logging.info('Processed %d trajectories', self._curriculum_count)\n return False\n for k in range(num_bins_distance + 1):\n logging.info('%d trajectories with distance at most %f',\n len(self._trajectory_data_map_per_distance[k]),\n k * self._curriculum_bin_distance)\n for k in range(self._num_instructions + 1):\n logging.info('%d trajectories with %d instructions',\n len(self._trajectory_data_map_per_waypoints[k]), k)\n\n return True\n\n def on_reset(self, streetlearn):\n \"\"\"Gets called after StreetLearn:reset().\n\n Args:\n streetlearn: a streetlearn instance.\n Returns:\n A newly populated pano_id_to_color dictionary.\n \"\"\"\n # Continue initialization of the curricula.\n if not self._init_complete:\n self._init_complete = self.initialize_curricula()\n return super(InstructionsCurriculum, self).on_reset(streetlearn)\n\n def _ratio_training(self):\n \"\"\"Updates the fraction of training curriculum based on elapsed time.\"\"\"\n hours_train = (time.time() - self._timestamp_start) / _SECONDS_IN_HOUR\n if hours_train > self._hours_curriculum_part_1:\n ratio_training = hours_train - self._hours_curriculum_part_1\n ratio_training /= self._hours_curriculum_part_2\n ratio_training = max(min(ratio_training, 1.0), 0.0)\n else:\n ratio_training = 0\n logging.info('Hours elapsed: %f, ratio: %f', hours_train, ratio_training)\n return ratio_training\n\n def _sample_trajectory(self, streetlearn):\n \"\"\"Sample a trajectory.\n\n Args:\n streetlearn: Streetlearn instance.\n Returns:\n trajectory object.\n \"\"\"\n if self._curriculum_type != CURRICULUM_NONE or self._curriculum_frame_cap:\n ratio_training = self._ratio_training()\n\n if self._curriculum_frame_cap:\n # Is there a curriculum on the cap on the number of frames?\n prev_frame_cap = streetlearn.frame_cap\n frame_cap = int(\n math.ceil(self._curriculum_frame_cap_part_1 + ratio_training *\n self._curriculum_frame_cap_extra_steps))\n streetlearn.frame_cap = frame_cap\n if prev_frame_cap != frame_cap:\n logging.info('Changing frame cap from %d to %d', prev_frame_cap,\n frame_cap)\n\n if self._curriculum_type == CURRICULUM_NONE:\n # Skip the curriculum sampling\n return super(InstructionsCurriculum, self)._sample_trajectory(streetlearn)\n\n if self._curriculum_type == CURRICULUM_LENGTH_BASED:\n # Curriculum based on the length/distance (in m) from start to goal.\n max_distance = self._min_goal_distance\n extra_distance = max(0, self._max_goal_distance - self._min_goal_distance)\n max_distance += math.ceil(extra_distance * ratio_training)\n logging.info('Max distance: %f', max_distance)\n bin_distance = int(math.ceil(\n max_distance / self._curriculum_bin_distance))\n map_trajectories = self._trajectory_data_map_per_distance[bin_distance]\n if self._curriculum_type == CURRICULUM_INSTR_BASED:\n # Curriculum based on the number of instructions/waypoints.\n max_num_instructions = self._curriculum_num_instructions_part_1\n num_extra_instructions = max(\n 0, self._num_instructions - self._curriculum_num_instructions_part_1)\n max_num_instructions += math.ceil(num_extra_instructions * ratio_training)\n logging.info('Max #instructions: %d', max_num_instructions)\n map_trajectories = self._trajectory_data_map_per_waypoints[\n max_num_instructions]\n if self._curriculum_type == CURRICULUM_LENGTH_INSTR_BASED:\n # Curriculum based both on the number of instructions and on length;\n # at the beginning, only short trajectories with few waypoints are sampled\n # and at the end, long trajectories with may waypoints are sampled too.\n # The final set of trajectories from which one can sample is the\n # intersection of the set of length-based curriculum trajectories and of\n # the set of instruction-based curriculum trajectories.\n max_distance = self._min_goal_distance\n extra_distance = max(0, self._max_goal_distance - self._min_goal_distance)\n max_distance += math.ceil(extra_distance * ratio_training)\n logging.info('Max distance: %f', max_distance)\n bin_distance = int(math.ceil(\n max_distance / self._curriculum_bin_distance))\n map_trajectories_1 = self._trajectory_data_map_per_distance[bin_distance]\n max_num_instructions = self._curriculum_num_instructions_part_1\n num_extra_instructions = max(\n 0, self._num_instructions - self._curriculum_num_instructions_part_1)\n max_num_instructions += math.ceil(num_extra_instructions * ratio_training)\n logging.info('Max #instructions: %d', max_num_instructions)\n map_trajectories_2 = self._trajectory_data_map_per_waypoints[\n max_num_instructions]\n map_trajectories = list(set(map_trajectories_1) & set(map_trajectories_2))\n logging.info('Intersection of two sets: %d & %d -> %d',\n len(map_trajectories_1), len(map_trajectories_2),\n len(map_trajectories))\n\n if map_trajectories:\n i = np.random.choice(map_trajectories)\n self._trajectory = self._trajectory_data[i]\n return self._trajectory\n\n logging.info('Could not find trajectories for ratio training time/steps %f',\n ratio_training)\n logging.info('Sampling trajectory without curriculum')\n self._trajectory = super(StreetLangTimedCurriculum,\n self)._sample_trajectory(streetlearn)\n return self._trajectory\n" }, { "alpha_fraction": 0.6081815958023071, "alphanum_fraction": 0.6126664876937866, "avg_line_length": 39.877777099609375, "blob_id": "c3ea4e47d651417b67f4c1b5c8161518f3801c5d", "content_id": "995bbe66408355a94aab792120ff435ece1d3219", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7358, "license_type": "permissive", "max_line_length": 80, "num_lines": 180, "path": "/streetlearn/python/agents/locale_pathway.py", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "# Copyright 2019 Google LLC\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# https://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\"\"\"Implements the locale-specific core for StreetLearn agents.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\n\nimport tensorflow as tf\nimport sonnet as snt\n\n# Outputs of the global city-specific pathway\nLocalePathwayOutput = collections.namedtuple(\n \"LocalePathwayOutput\", [\"lstm_output\", \"heading\", \"xy\", \"target_xy\"])\n\n\nclass LocalePathway(snt.RNNCore):\n \"\"\"City-specific locale core, operating on visual embeddings.\"\"\"\n\n def __init__(self,\n heading_stop_gradient=False,\n heading_num_hiddens=256,\n heading_num_bins=16,\n xy_stop_gradient=True,\n xy_num_hiddens=256,\n xy_num_bins_lat=32,\n xy_num_bins_lng=32,\n target_xy_stop_gradient=True,\n lstm_num_hiddens=256,\n dropout=0.5,\n name=\"locale_pathway_core\"):\n \"\"\"Initializes a city-specific global localisation core,\n operating on visual embeddings and target positions.\n\n Supports a single embedding tensor and a single target position tensor,\n and outputs a single hidden state as well as auxiliary localisation outputs.\n Relies on a recurrent LSTM core.\n\n Args:\n aux_config: ConfigDict with additional ConfigDict for auxiliary tasks.\n name: Optional name for the module.\n\n Returns:\n \"\"\"\n super(LocalePathway, self).__init__(name=name)\n\n self._heading_stop_gradient = heading_stop_gradient\n self._xy_stop_gradient = xy_stop_gradient\n self._target_xy_stop_gradient = target_xy_stop_gradient\n tf.logging.info(\"Stop gradient? heading:%s, XY:%s and target XY:%s\",\n str(heading_stop_gradient), str(xy_stop_gradient),\n str(target_xy_stop_gradient))\n self._lstm_num_hiddens = lstm_num_hiddens\n tf.logging.info(\"Number of hiddens in locale-specific LSTM: %d\",\n lstm_num_hiddens)\n self._dropout = dropout\n tf.logging.info(\"Dropout after LSTM: %f\", dropout)\n\n with self._enter_variable_scope():\n # Add an LSTM for global landmark, heading and XY prediction tasks\n tf.logging.info(\"Auxiliary global pathway LSTM with %d hiddens\",\n self._lstm_num_hiddens)\n assert(self._lstm_num_hiddens > 0)\n self._lstm = tf.contrib.rnn.LSTMBlockCell(self._lstm_num_hiddens,\n name=\"global_pathway_lstm\")\n # Add an MLP head for absolute heading (north) bin prediction\n tf.logging.info(\"%d-bin absolute heading prediction with %s hiddens\",\n heading_num_bins,\n heading_num_hiddens)\n self._heading_logits = snt.nets.MLP(\n output_sizes=(heading_num_hiddens, heading_num_bins),\n activate_final=False,\n name=\"heading_logits\")\n # Add an MLP head for XY location bin prediction\n xy_num_bins = xy_num_bins_lat * xy_num_bins_lng\n tf.logging.info(\"%d-bin XY location prediction (%d lat, %d lng)\",\n xy_num_bins, xy_num_bins_lat, xy_num_bins_lng)\n tf.logging.info(\"with %s hiddens\", xy_num_hiddens)\n self._xy_logits = snt.nets.MLP(\n output_sizes=(xy_num_hiddens, xy_num_bins),\n activate_final=False,\n name=\"xy_logits\")\n # Add an MLP head for XY target location bin prediction\n tf.logging.info(\"%d-bin target XY location prediction (%d lat, %d lng)\",\n xy_num_bins, xy_num_bins_lat, xy_num_bins_lng)\n tf.logging.info(\"with %s hiddens\", xy_num_hiddens)\n self._target_xy_logits = snt.nets.MLP(\n output_sizes=(xy_num_hiddens, xy_num_bins),\n activate_final=False,\n name=\"target_xy_logits\")\n\n def _build(self, (embedding, target_position), state):\n \"\"\"Connects the core into the graph.\n\n This core is designed to be used for embeddings coming from a convnet.\n\n Args:\n embedding: The result of convnet embedding.\n target_position: Representation of the target position.\n state: The current state of the global LSTM component of the core.\n\n Returns:\n A tuple `(action, other_output), next_state`, where:\n * `action` is the action selected by the core. An iterable containing\n a single Tensor with shape `[batch, 1]`, which is the zero-based index\n of the selected action.\n * `other_output` is a namedtuple with fields `policy_logits` (a Tensor\n of shape `[batch, num_actions]`) and `baseline` (a Tensor of shape\n `[batch]`).\n * `next_state` is the output of the LSTM component of the core.\n \"\"\"\n\n # Add the target to global LSTM\n with tf.name_scope(\"targets\") as scope:\n lstm_input = tf.concat([embedding, tf.cast(target_position,\n dtype=tf.float32)],\n axis=1)\n\n # Global pathway tasks\n with tf.name_scope(\"locale_pathway\") as scope:\n lstm_output, next_state = self._lstm(lstm_input, state)\n\n # Heading decoding or prediction\n if self._heading_stop_gradient:\n input_heading = tf.stop_gradient(lstm_output,\n name='heading_stop_gradient')\n else:\n input_heading = lstm_output\n heading = self._heading_logits(input_heading)\n\n # XY decoding or prediction\n if self._xy_stop_gradient:\n input_xy = tf.stop_gradient(lstm_output,\n name='xy_stop_gradient')\n else:\n input_xy = lstm_output\n xy = self._xy_logits(input_xy)\n\n # Target XY decoding\n if self._target_xy_stop_gradient:\n input_target_xy = tf.stop_gradient(lstm_output,\n name='target_xy_stop_gradient')\n else:\n input_target_xy = lstm_output\n target_xy = self._target_xy_logits(input_target_xy)\n\n # Add dropout\n if self._dropout > 0:\n lstm_output = tf.nn.dropout(lstm_output,\n keep_prob=self._dropout,\n name=\"lstm_output_dropout\")\n else:\n lstm_output = tf.identity(lstm_output,\n name=\"lstm_output_without_dropout\")\n\n # Outputs\n core_output = LocalePathwayOutput(lstm_output=lstm_output,\n heading=heading,\n xy=xy,\n target_xy=target_xy)\n return core_output, next_state\n\n def initial_state(self, batch_size):\n \"\"\"Returns an initial state with zeros, for a batch size and data type.\"\"\"\n tf.logging.info(\"Initial state includes the locale LSTM\")\n return self._lstm.zero_state(batch_size, tf.float32)\n" }, { "alpha_fraction": 0.6338205933570862, "alphanum_fraction": 0.6655746102333069, "avg_line_length": 34.42856979370117, "blob_id": "a8c595e0a62844079fd882e6fb7605b623f5ca4c", "content_id": "26e9fce05b9d8a70d8a115ab23713b7de3363022", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3968, "license_type": "permissive", "max_line_length": 79, "num_lines": 112, "path": "/streetlearn/engine/pano_renderer_test.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/pano_renderer.h\"\n\n#include <string>\n\n#include \"gtest/gtest.h\"\n#include \"streetlearn/engine/pano_graph.h\"\n#include \"streetlearn/engine/pano_renderer.h\"\n#include \"streetlearn/engine/test_dataset.h\"\n\nnamespace streetlearn {\nnamespace {\n\nconstexpr int kTolerance = 2;\nconstexpr int kFovDegrees = 30;\nconstexpr int kStatusHeight = 10;\n// Color components for bearings.\nconstexpr int kCenterBearing = 128;\nconstexpr int kSideBearing = 230;\n\nTEST(StreetLearn, PanoRendererTest) {\n PanoRenderer pano_renderer(TestDataset::kImageWidth,\n TestDataset::kImageHeight, kStatusHeight,\n kFovDegrees);\n\n const Image3_b test_image = TestDataset::GenerateTestImage();\n pano_renderer.RenderScene(test_image, 0, 0, 0, 0, {}, {});\n auto pixels = pano_renderer.Pixels();\n\n for (int y = 0; y < TestDataset::kImageHeight / 2; ++y) {\n for (int x = 0; x < TestDataset::kImageWidth; ++x) {\n int index = 3 * (y * TestDataset::kImageWidth + x);\n const auto* expected_pixel = test_image.pixel(x, y);\n EXPECT_LE(std::abs(pixels[index] - expected_pixel[0]), kTolerance);\n EXPECT_LE(std::abs(pixels[index + 1] - expected_pixel[1]), kTolerance);\n EXPECT_LE(std::abs(pixels[index + 2] - expected_pixel[2]), kTolerance);\n }\n }\n}\n\nTEST(StreetLearn, PanoRendererBearingsTest) {\n PanoRenderer pano_renderer(TestDataset::kImageWidth,\n TestDataset::kImageHeight, kStatusHeight,\n kFovDegrees);\n\n Image3_b pano_image(TestDataset::kImageWidth, TestDataset::kImageHeight);\n\n std::vector<PanoNeighborBearing> bearings = {\n {\"0\", -90, 0.0}, {\"1\", 0, 1.0}, {\"2\", 90, 2.0}};\n\n // Look at the center of the view.\n pano_renderer.RenderScene(pano_image, 0, 0, 0, 0, bearings, {});\n\n auto pixels = pano_renderer.Pixels();\n for (int j = 0; j < TestDataset::kImageWidth; ++j) {\n int index = (TestDataset::kImageHeight - 5) * TestDataset::kImageWidth + j;\n if (TestDataset::kImageWidth / 2 == j) {\n EXPECT_LE(abs(pixels[3 * index] - kCenterBearing), kTolerance);\n } else if (TestDataset::kImageWidth / 4 == j ||\n 3 * TestDataset::kImageWidth / 4 == j) {\n EXPECT_LE(abs(pixels[3 * index] - kSideBearing), kTolerance);\n }\n }\n\n // Rotate by 90 degrees.\n pano_renderer.RenderScene(pano_image, 0, 90, 0, 0, bearings, {});\n pixels = pano_renderer.Pixels();\n for (int j = 0; j < TestDataset::kImageWidth; ++j) {\n int index = (TestDataset::kImageHeight - 5) * TestDataset::kImageWidth + j;\n if (TestDataset::kImageWidth / 2 == j) {\n EXPECT_LE(abs(pixels[3 * index] - kCenterBearing), kTolerance);\n } else if (0 == j || TestDataset::kImageWidth / 4 == j) {\n EXPECT_LE(abs(pixels[3 * index] - kSideBearing), kTolerance);\n }\n }\n}\n\nTEST(StreetLearn, PanoRendererConstrainAngleTest) {\n double angle = PanoRenderer::ConstrainAngle(180, 400);\n EXPECT_EQ(angle, 40);\n\n angle = PanoRenderer::ConstrainAngle(360, 400);\n EXPECT_EQ(angle, -320);\n\n angle = PanoRenderer::ConstrainAngle(180, -400);\n EXPECT_EQ(angle, -40);\n\n angle = PanoRenderer::ConstrainAngle(360, -420);\n EXPECT_EQ(angle, 300);\n\n angle = PanoRenderer::ConstrainAngle(180, -180);\n EXPECT_EQ(angle, -180);\n\n angle = PanoRenderer::ConstrainAngle(180, 180);\n EXPECT_EQ(angle, -180);\n}\n\n} // namespace\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.6577443480491638, "alphanum_fraction": 0.6601503491401672, "avg_line_length": 32.58585739135742, "blob_id": "a99b1b815d3c4ef4b6fc073da47632eb9704be73", "content_id": "aab1d0ca90ee10e8258bb6868abffc2e10c1265b", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3325, "license_type": "permissive", "max_line_length": 80, "num_lines": 99, "path": "/streetlearn/engine/node_cache.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/node_cache.h\"\n\nnamespace streetlearn {\n\nNodeCache::NodeCache(const Dataset* dataset, int thread_count,\n std::size_t max_size)\n : max_size_(max_size),\n pano_fetcher_(dataset, thread_count,\n [this](absl::string_view pano_id,\n std::shared_ptr<const PanoGraphNode> node) {\n this->Insert(std::string(pano_id), std::move(node));\n }) {}\n\nbool NodeCache::Lookup(const std::string& pano_id, LoadCallback callback) {\n absl::MutexLock lock(&mutex_);\n auto it = cache_lookup_.find(pano_id);\n if (it == cache_lookup_.end()) {\n pano_fetcher_.FetchAsync(pano_id);\n callbacks_[pano_id].push_front(std::move(callback));\n return false;\n }\n cache_list_.splice(cache_list_.begin(), cache_list_, it->second);\n callback(it->second->pano_node.get());\n return true;\n}\n\nvoid NodeCache::Insert(const std::string& pano_id,\n std::shared_ptr<const PanoGraphNode> node) {\n std::list<LoadCallback> callbacks = InsertImpl(pano_id, node);\n RunCallbacks(callbacks, node);\n}\n\nvoid NodeCache::CancelPendingFetches() {\n std::vector<std::string> cancelled = pano_fetcher_.CancelPendingFetches();\n for (const auto& pano_id : cancelled) {\n std::list<LoadCallback> callbacks;\n {\n absl::MutexLock lock(&mutex_);\n callbacks = GetAndClearCallbacks(pano_id);\n }\n RunCallbacks(callbacks, nullptr);\n }\n}\n\nstd::list<NodeCache::LoadCallback> NodeCache::InsertImpl(\n const std::string& pano_id, std::shared_ptr<const PanoGraphNode> node) {\n absl::MutexLock lock(&mutex_);\n // Insert into the cache.\n auto it = cache_lookup_.find(pano_id);\n if (it != cache_lookup_.end()) {\n cache_list_.erase(it->second);\n cache_lookup_.erase(it);\n }\n cache_list_.push_front(CacheEntry(pano_id, std::move(node)));\n cache_lookup_[pano_id] = cache_list_.begin();\n\n // Evict an item if necessary.\n if (cache_list_.size() > max_size_) {\n cache_lookup_.erase(cache_list_.back().pano_id);\n cache_list_.pop_back();\n }\n\n return GetAndClearCallbacks(pano_id);\n}\n\nstd::list<NodeCache::LoadCallback> NodeCache::GetAndClearCallbacks(\n const std::string& pano_id) {\n std::list<LoadCallback> callbacks;\n auto it = callbacks_.find(pano_id);\n if (it != callbacks_.end()) {\n callbacks = std::move(it->second);\n callbacks_.erase(it);\n }\n return callbacks;\n}\n\nvoid NodeCache::RunCallbacks(const std::list<LoadCallback>& callbacks,\n const std::shared_ptr<const PanoGraphNode>& node) {\n const PanoGraphNode* pano_node = node ? node.get() : nullptr;\n for (const auto& callback : callbacks) {\n callback(pano_node);\n }\n}\n\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.6398134231567383, "alphanum_fraction": 0.6432054042816162, "avg_line_length": 29.237178802490234, "blob_id": "fa1db744688404795f008645cccb668764fff0b0", "content_id": "fe47091a46c022835df3ae5052733fadc6142b57", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4717, "license_type": "permissive", "max_line_length": 80, "num_lines": 156, "path": "/streetlearn/engine/metadata_cache.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/metadata_cache.h\"\n\n#include <fstream>\n#include <iostream>\n\n#include \"streetlearn/engine/logging.h\"\n#include \"absl/memory/memory.h\"\n\nnamespace streetlearn {\n\nnamespace {\n\nvoid PreprocessPano(Pano* pano) {\n for (auto& neighbor : *pano->mutable_neighbor()) {\n if (neighbor.has_snapped_coords()) {\n *neighbor.mutable_coords() = neighbor.snapped_coords();\n }\n }\n}\n\nvoid PreprocessGraph(StreetLearnGraph* graph) {\n for (auto& pano : *graph->mutable_pano()) {\n PreprocessPano(&pano);\n }\n}\n\n} // namespace\n\nstd::unique_ptr<MetadataCache> MetadataCache::Create(const Dataset* dataset,\n int min_graph_depth) {\n auto metadataCache =\n absl::WrapUnique<MetadataCache>(new MetadataCache(min_graph_depth));\n if (!metadataCache->ReadData(dataset)) {\n return nullptr;\n }\n return metadataCache;\n}\n\nMetadataCache::MetadataCache(int min_graph_depth)\n : min_lat_(-1),\n min_lng_(-1),\n max_lat_(-1),\n max_lng_(-1),\n min_graph_depth_(min_graph_depth) {}\n\nbool MetadataCache::ReadData(const Dataset* dataset) {\n StreetLearnGraph streetlearn_graph;\n if (!dataset->GetGraph(&streetlearn_graph)) {\n LOG(ERROR) << \"Cannot read StreetLearn graph!\";\n return false;\n }\n\n PreprocessGraph(&streetlearn_graph);\n\n // Min and max coords.\n const auto& min_coords = streetlearn_graph.min_coords();\n min_lat_ = min_coords.lat();\n min_lng_ = min_coords.lng();\n const auto& max_coords = streetlearn_graph.max_coords();\n max_lat_ = max_coords.lat();\n max_lng_ = max_coords.lng();\n\n // Panos - for full metadata.\n std::map<std::string, Pano> panos;\n for (const auto& pano : streetlearn_graph.pano()) {\n auto it_inserted = panos.insert({pano.id(), pano});\n if (!it_inserted.second) {\n LOG(ERROR) << \"Pano \" << pano.id() << \" has two metadata entries!\";\n }\n }\n\n ProcessNeighbors(streetlearn_graph, panos);\n\n return true;\n}\n\nvoid MetadataCache::ProcessNeighbors(const StreetLearnGraph& streetlearn_graph,\n const std::map<std::string, Pano>& panos) {\n for (const auto& neighbor : streetlearn_graph.connection()) {\n if (neighbor.subgraph_size() < min_graph_depth_) {\n continue;\n }\n const auto& pano_id = neighbor.id();\n\n const auto& pano_iter = panos.find(pano_id);\n if (pano_iter == panos.end()) {\n return;\n }\n const auto& pano = pano_iter->second;\n\n PanoMetadata metadata;\n metadata.pano = pano;\n metadata.graph_depth = neighbor.subgraph_size();\n\n for (const auto& neighbor_id : neighbor.neighbor()) {\n const auto& neighbor_iter = panos.find(neighbor_id);\n CHECK(neighbor_iter != panos.end());\n const auto& neighbor = neighbor_iter->second;\n\n PanoIdAndGpsCoords panoIdAndCoords;\n panoIdAndCoords.set_id(neighbor_id);\n LatLng* coords = panoIdAndCoords.mutable_coords();\n coords->set_lat(neighbor.coords().lat());\n coords->set_lng(neighbor.coords().lng());\n metadata.neighbors.push_back(panoIdAndCoords);\n }\n pano_metadata_.emplace(pano_id, metadata);\n }\n}\n\nconst PanoMetadata* MetadataCache::GetPanoMetadata(\n const std::string& pano_id) const {\n auto cache_iter = pano_metadata_.find(pano_id);\n if (cache_iter != pano_metadata_.end()) {\n return &cache_iter->second;\n }\n\n return nullptr;\n}\n\nstd::vector<std::string> MetadataCache::PanosInGraphsOfSize(\n int min_size) const {\n std::vector<std::string> pano_ids;\n for (const auto& entry : pano_metadata_) {\n if (entry.second.graph_depth >= min_size) {\n pano_ids.push_back(entry.first);\n }\n }\n return pano_ids;\n}\n\nstd::string MetadataCache::PanoInLargestGraph() const {\n return std::max_element(pano_metadata_.begin(), pano_metadata_.end(),\n [](const std::pair<std::string, PanoMetadata>& p1,\n const std::pair<std::string, PanoMetadata>& p2) {\n return p1.second.graph_depth <\n p2.second.graph_depth;\n })\n ->second.pano.id();\n}\n\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.6368330717086792, "alphanum_fraction": 0.6602409482002258, "avg_line_length": 26.66666603088379, "blob_id": "560fc22e70895e479cd8fdfe65f0ab56a4938c8b", "content_id": "70e801b863a8666acf454294699b4c067a8214e7", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2905, "license_type": "permissive", "max_line_length": 80, "num_lines": 105, "path": "/streetlearn/engine/rtree_helper_test.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/rtree_helper.h\"\n\n#include \"s2/s1angle.h\"\n#include \"s2/s2latlng.h\"\n#include \"s2/s2latlng_rect.h\"\n\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n\nnamespace streetlearn {\nnamespace geometry {\nnamespace {\n\nusing ::testing::ElementsAre;\n\nconstexpr int kNumBounds = 1000;\n\n// Create d by d S2LatLngRect centered at (c, c).\nS2LatLngRect GetRect(double c, double d) {\n auto r = d / 2.0;\n auto lo = S2LatLng::FromDegrees(c - r, c - r);\n auto hi = S2LatLng::FromDegrees(c + r, c + r);\n return S2LatLngRect(lo, hi);\n}\n\nTEST(RTreeHelperTest, EmptyTree) {\n S2LatLngRect rect;\n rect.mutable_lng()->set_hi(M_PI);\n rect.mutable_lng()->set_lo(0);\n\n RTree rtree;\n EXPECT_TRUE(rtree.empty());\n\n std::vector<int> out;\n EXPECT_EQ(rtree.FindIntersecting(S2LatLngRect::Full(), &out), 0);\n EXPECT_TRUE(out.empty());\n}\n\nTEST(RTreeHelperTest, Insert_Basic) {\n RTree rtree;\n S2LatLngRect bound = GetRect(10, 5);\n rtree.Insert(bound, 1);\n\n std::vector<int> out;\n EXPECT_EQ(rtree.FindIntersecting(bound, &out), 1);\n EXPECT_THAT(out, ElementsAre(1));\n}\n\nTEST(RTreeHelperTest, Insert_NonOverlapping) {\n RTree rtree;\n std::vector<S2LatLngRect> bounds;\n\n constexpr double start = 0.0;\n constexpr double step = 0.01;\n\n for (int i = 0; i < kNumBounds; ++i) {\n const double lat = start + step * i;\n bounds.push_back(S2LatLngRect(S2LatLng::FromDegrees(lat, 0),\n S2LatLng::FromDegrees(lat + (step / 2), 10)));\n std::cout << lat << \";\" << 0 << \" - \" << lat + step / 2 << \";\" << 10\n << std::endl;\n rtree.Insert(bounds[i], i);\n }\n\n for (int i = 0; i < bounds.size(); ++i) {\n std::vector<int> out;\n EXPECT_EQ(rtree.FindIntersecting(bounds[i], &out), 1);\n EXPECT_THAT(out, ElementsAre(i));\n }\n}\n\nTEST(RTreeHelperTest, Insert_Overlapping) {\n RTree rtree;\n constexpr double kCenter = 50.0;\n constexpr double kMin = 10.0;\n constexpr double kMax = 20.0;\n\n for (int i = 0; i < kNumBounds; ++i) {\n S2LatLngRect rect =\n GetRect(kCenter, kMax - (i * (kMax - kMin) / (kNumBounds - 1)));\n rtree.Insert(rect, i);\n }\n\n std::vector<int> out;\n EXPECT_EQ(rtree.FindIntersecting(GetRect(kCenter, kMin), &out), kNumBounds);\n EXPECT_EQ(kNumBounds, out.size());\n}\n\n} // namespace\n} // namespace geometry\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.6164935231208801, "alphanum_fraction": 0.6252717971801758, "avg_line_length": 38.16719055175781, "blob_id": "cc6762fe09f76cabc49bf2ec933b88afb96466e6", "content_id": "91628db1411d48eb500c57c12ac210cce60ecf28", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12417, "license_type": "permissive", "max_line_length": 80, "num_lines": 317, "path": "/streetlearn/python/environment/game.py", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "# Copyright 2018 Google LLC.\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\"\"\"Base class for all StreetLearn levels.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport abc\nimport collections\nimport math\nimport numpy as np\nfrom absl import logging\nimport six\n\nfrom streetlearn.engine.python import color\n\nEMPTY_THUMBMNAILS = np.empty((0, 3, 0, 0))\nEMPTY_GT_DIRECTION = np.empty((0,))\n# When computing which panos B_i are immediately reachable from a given pano A,\n# we look at all panos B_i up to depth TOL_DEPTH in a graph whose root is A,\n# with a difference in altitude less than TOL_ALT meters, and within a cone\n# of TOL_BEARING degrees.\nTOL_ALT = 2.0\nTOL_DEPTH = 3\nTOL_BEARING = 30\n\n\[email protected]_metaclass(abc.ABCMeta)\nclass Game(object):\n \"\"\"Base class for streetlearn levels.\"\"\"\n\n @abc.abstractmethod\n def on_reset(self, streetlearn):\n \"\"\"Gets called after StreetLearn:reset().\n\n Args:\n streetlearn: a StreetLearn instance.\n Returns:\n Dictionary that maps certain pano IDs to colors.\n \"\"\"\n return {}\n\n @abc.abstractmethod\n def on_step(self, streetlearn):\n \"\"\"\"Gets called after StreetLearn:step().\n\n Args:\n streetlearn: a StreetLearn instance.\n \"\"\"\n\n @abc.abstractmethod\n def get_reward(self, streetlearn):\n \"\"\"Returns the reward from the last step.\n\n Args:\n streetlearn: a StreetLearn instance.\n Returns:\n reward: the reward from the last step.\n \"\"\"\n\n @abc.abstractmethod\n def get_info(self, streetlearn):\n \"\"\"\"Returns current information about the environment.\n\n Args:\n streetlearn: a StreetLearn instance.\n Returns:\n info: information from the environment at the last step.\n \"\"\"\n\n @property\n def goal_id(self):\n \"\"\"Returns the id of the goal pano, if there is one.\"\"\"\n return None\n\n def ground_truth_direction(self):\n \"\"\"Returns the float angle with the ground truth direction for the agent.\"\"\"\n return EMPTY_GT_DIRECTION\n\n def thumbnails(self):\n \"\"\"Returns observation thumbnails array of shape (batch_size, 3, h, w).\"\"\"\n return EMPTY_THUMBMNAILS\n\n def instructions(self):\n \"\"\"Returns a string containing game specific instructions.\"\"\"\n return str()\n\n def highlighted_panos(self):\n \"\"\"Returns the list of highlighted panos and their colors.\"\"\"\n return {}\n\n @property\n def done(self):\n \"\"\"Returns a flag indicating the end of the current episode.\"\"\"\n return True\n\n def _compute_extended_graphs(self, streetlearn):\n \"\"\"Compute an extended directed graph accessible to the StreeLearn agent.\n\n Args:\n streetlearn: the streetlearn environment.\n \"\"\"\n logging.info('Storing the altitudes of each pano for faster retrieval.')\n altitudes = {}\n for pano_id in six.iterkeys(streetlearn.graph):\n altitudes[pano_id] = streetlearn.engine.GetMetadata(pano_id).pano.alt\n logging.info('Computing the extended directed graph.')\n self._extended_graph_from = {}\n self._extended_graph_to = collections.defaultdict(list)\n num_panos = 0\n num_panos_total = len(streetlearn.graph)\n num_edges_extended = 0\n for current_id in six.iterkeys(streetlearn.graph):\n\n # Find the neighbors up to depth 3 of the current pano, not separated\n # by a drop of 2m in altitude.\n visited = {}\n queue_panos = [(current_id, 0)]\n while queue_panos:\n elem = queue_panos.pop(0)\n pano_id = elem[0]\n depth = elem[1]\n current_alt = altitudes[current_id]\n if depth > 0:\n # Store the distance and bearing to each neighbor.\n dist = streetlearn.engine.GetPanoDistance(current_id, pano_id)\n bearing = streetlearn.engine.GetPanoBearing(current_id, pano_id)\n visited[pano_id] = (dist, bearing)\n # Look for new neighbors recursively.\n if depth < TOL_DEPTH:\n neighbors = streetlearn.graph[pano_id]\n for neighbor_id in neighbors:\n if neighbor_id not in visited:\n neighbor_alt = altitudes[neighbor_id]\n if depth == 0 or abs(neighbor_alt - current_alt) < TOL_ALT:\n queue_panos.append((neighbor_id, depth+1))\n visited.pop(current_id)\n\n # Select only neighbors that are the closest within a tolerance cone,\n # and create extended graphs.\n self._extended_graph_from[current_id] = {}\n for pano_id, (dist, bearing) in six.iteritems(visited):\n retain_pano_id = True\n for other_id, (other_dist, other_bearing) in six.iteritems(visited):\n if ((pano_id != other_id) and\n (180 - abs(abs(bearing - other_bearing) - 180) < TOL_BEARING) and\n (other_dist < dist)):\n retain_pano_id = False\n if retain_pano_id:\n self._extended_graph_from[current_id][pano_id] = (dist, bearing)\n num_edges_extended += 1\n self._extended_graph_to[pano_id].append((current_id, dist, bearing))\n\n num_panos += 1\n if num_panos % 1000 == 0:\n logging.info('Processed %d/%d panos, %d extended directed edges',\n num_panos, num_panos_total, num_edges_extended)\n\n def _bfs(self, queue_panos, graph, flagged, visited):\n \"\"\"Compute the shortest paths using BFS given a queue and pano graph.\n\n Args:\n queue_panos: list of tuples (parent_pano_id, child_pano_id).\n graph: dictionary with pano_id keys and lists of pano_id values.\n flagged: dictionary with pano_id keys and boolean values.\n visited: dictionary with child pano_id keys and parent pano id values.\n Returns:\n flagged: dictionary with pano_id keys and boolean values.\n visited: dictionary with child pano_id keys and parent pano id values.\n \"\"\"\n while queue_panos:\n # Mark the pano at the top of the queue as visited.\n elem = queue_panos.pop(0)\n current_pano_id = elem[0]\n parent_pano_id = elem[1]\n depth = elem[2]\n visited[current_pano_id] = (parent_pano_id, depth)\n # Add the neighbors of the pano.\n if current_pano_id in graph:\n neighbors = graph[current_pano_id]\n for neighbor_id in neighbors:\n if isinstance(neighbor_id, tuple):\n neighbor_id = neighbor_id[0]\n if neighbor_id not in flagged:\n flagged.add(neighbor_id)\n queue_panos.append((neighbor_id, current_pano_id, depth+1))\n return flagged, visited\n\n def _shortest_paths(self, streetlearn, target_pano_id, start_pano_id):\n \"\"\"Compute the shortest paths from all the panos to a given start pano.\n\n Args:\n streetlearn: the streetlearn environment.\n target_pano_id: a string for the target pano ID.\n start_pano_id: a string for the current pano ID, for computing the optimal\n path.\n Returns:\n shortest_path: dictionary containing (current_pano_id, next_pano_id)\n as (key, value) pairs.\n num_panos: integer number of panos in the shortest path.\n \"\"\"\n # The shortest path relies on the extended directed graph.\n if not hasattr(self, '_extended_graph_from'):\n self._compute_extended_graphs(streetlearn)\n\n # Compute the shortest paths from all the panos to the target pano\n # using the direct connection graph.\n logging.info('Computing shortest paths to %s using BFS on direct graph',\n target_pano_id)\n flagged_direct = set([target_pano_id])\n (_, visited_direct) = self._bfs(\n [(target_pano_id, None, 0)], streetlearn.graph, flagged_direct, {})\n\n # Compute the shortest paths from all the panos to the target pano\n # using the extended (reachable) graph, with shortcuts.\n logging.info('Computing shortest paths to %s using BFS on extended graph',\n target_pano_id)\n flagged_extended = set([target_pano_id])\n (_, visited_extended) = self._bfs(\n [(target_pano_id, None, 0)], self._extended_graph_to, flagged_extended,\n {})\n\n # Some panos may have been missed during the shortest path computation\n # on the extended graph because of the preferential choice of one pano\n # over the other. In order to make sure that there is a path from every\n # pano of the graph to the goal pano, we backfill visited_extended\n # with visited_direct, which is computed on the direct connection graph.\n self._panos_to_goal = {}\n for child, (parent, _) in six.iteritems(visited_direct):\n if child in visited_extended:\n (parent, _) = visited_extended[child]\n self._panos_to_goal[child] = parent\n\n # Extract the shortest path, from the current starting position, by\n # following the panos to goal as computed by the BFS search that started\n # from the goal.\n current_pano_id = start_pano_id\n list_panos = [current_pano_id]\n next_pano_id = self._panos_to_goal[current_pano_id]\n while next_pano_id:\n list_panos.append(next_pano_id)\n current_pano_id = next_pano_id\n next_pano_id = self._panos_to_goal[current_pano_id]\n\n # Because of the Street View direct graph connectivity and because of how\n # the StreetLearn extended graph adds edges when two panos that are distant\n # by up to 2 links can still be directly reached, we need to \"iron out\"\n # the path at street intersections. This code transforms a -> b -> c -> d\n # into a -> b' -> c' -> d if the latter is shorter (in metric distance)\n # and a -> b -> c into a -> b' -> c' -> c if the latter is shorter.\n shortest_path = {}\n num_panos = 0\n while num_panos < len(list_panos)-3:\n a = list_panos[num_panos]\n b = list_panos[num_panos+1]\n c = list_panos[num_panos+2]\n d = list_panos[num_panos+3]\n skipped = 1\n shortest_path[a] = b\n if (a in self._extended_graph_from and\n b in self._extended_graph_from and\n c in self._extended_graph_from and\n b in self._extended_graph_from[a] and\n c in self._extended_graph_from[b] and\n d in self._extended_graph_from[c]):\n (dist_ab, _) = self._extended_graph_from[a][b]\n (dist_bc, _) = self._extended_graph_from[b][c]\n (dist_cd, _) = self._extended_graph_from[c][d]\n dist_abc = dist_ab + dist_bc\n dist_abcd = dist_abc + dist_cd\n for b2 in six.iterkeys(self._extended_graph_from[a]):\n if b2 != b:\n for c2 in six.iterkeys(self._extended_graph_from[b2]):\n for d2 in six.iterkeys(self._extended_graph_from[c2]):\n if d2 == c or d2 == d:\n (dist_ab2, _) = self._extended_graph_from[a][b2]\n (dist_bc2, _) = self._extended_graph_from[b2][c2]\n (dist_cd2, _) = self._extended_graph_from[c2][d2]\n dist_abcd2 = dist_ab2 + dist_bc2 + dist_cd2\n if d2 == c and dist_abcd2 < dist_abc:\n self._panos_to_goal[a] = b2\n self._panos_to_goal[b2] = c2\n self._panos_to_goal[c2] = c\n shortest_path[a] = b2\n shortest_path[b2] = c2\n shortest_path[c2] = c\n logging.info('Replaced %s, %s, %s by %s, %s, %s, %s',\n a, b, c, a, b2, c2, d2)\n skipped = 2\n if d2 == d and dist_abcd2 < dist_abcd:\n self._panos_to_goal[a] = b2\n self._panos_to_goal[b2] = c2\n self._panos_to_goal[c2] = d\n shortest_path[a] = b2\n shortest_path[b2] = c2\n shortest_path[c2] = d\n logging.info('Replaced %s, %s, %s, %s by %s, %s, %s, %s',\n a, b, c, d, a, b2, c2, d2)\n skipped = 3\n num_panos += skipped\n while num_panos < len(list_panos)-1:\n shortest_path[list_panos[num_panos]] = list_panos[num_panos+1]\n num_panos +=1\n\n return shortest_path, num_panos\n\n" }, { "alpha_fraction": 0.8308207988739014, "alphanum_fraction": 0.8352875709533691, "avg_line_length": 50.17142868041992, "blob_id": "90f20c060b20bdb4dbb284ef415f22c8285d2273", "content_id": "b52e398f356caf5d9b408cad85d4b5318e6ade94", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1791, "license_type": "permissive", "max_line_length": 98, "num_lines": 35, "path": "/streetlearn/python/environment/__init__.py", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "# Copyright 2018 Google LLC\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# https://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\"\"\"Python interface to the StreetLearn engine.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom streetlearn.python.environment.coin_game import CoinGame\nfrom streetlearn.python.environment.courier_game import CourierGame\nfrom streetlearn.python.environment.curriculum_courier_game import CurriculumCourierGame\nfrom streetlearn.python.environment.default_config import ApplyDefaults\nfrom streetlearn.python.environment.default_config import CreateGame\nfrom streetlearn.python.environment.exploration_game import ExplorationGame\nfrom streetlearn.python.environment.game import Game\nfrom streetlearn.python.environment.goal_instruction_game import GoalInstructionGame\nfrom streetlearn.python.environment.incremental_instruction_game import IncrementalInstructionGame\nfrom streetlearn.python.environment.observations import Observation\nfrom streetlearn.python.environment.step_by_step_instruction_game import StepByStepInstructionGame\nfrom streetlearn.python.environment.streetlearn import get_action_set\nfrom streetlearn.python.environment.streetlearn import StreetLearn\nfrom streetlearn.python.environment.thumbnail_helper import ThumbnailHelper\n" }, { "alpha_fraction": 0.6374830007553101, "alphanum_fraction": 0.6410884261131287, "avg_line_length": 31.236841201782227, "blob_id": "08b2f7e3f805be3644d42f6f0fa2094ff002322c", "content_id": "41f080f757f95922ecf331944414e2b00bdaab18", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 14700, "license_type": "permissive", "max_line_length": 80, "num_lines": 456, "path": "/streetlearn/engine/pano_graph.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/pano_graph.h\"\n\n#include <algorithm>\n#include <cmath>\n#include <iostream>\n#include <limits>\n#include <set>\n#include <utility>\n\n#include \"streetlearn/engine/logging.h\"\n#include \"absl/synchronization/notification.h\"\n#include \"streetlearn/engine/math_util.h\"\n#include \"streetlearn/engine/metadata_cache.h\"\n#include \"streetlearn/engine/pano_calculations.h\"\n\nnamespace streetlearn {\nnamespace {\n\nconstexpr int kThreadCount = 16;\nconstexpr int kMinGraphDepth = 10;\nconstexpr double kNeighborAltituteThresholdMeters = 2.0;\n\n} // namespace\n\nPanoGraph::PanoGraph(int prefetch_depth, int max_cache_size,\n int min_graph_depth, int max_graph_depth,\n const Dataset* dataset)\n : dataset_(dataset),\n min_graph_depth_(min_graph_depth),\n max_graph_depth_(max_graph_depth),\n prefetch_depth_(prefetch_depth),\n node_cache_(dataset, kThreadCount, max_cache_size) {}\n\nPanoGraph::~PanoGraph() { CancelPendingFetches(); }\n\nbool PanoGraph::Init() {\n metadata_cache_ = MetadataCache::Create(dataset_, kMinGraphDepth);\n if (!metadata_cache_) {\n LOG(ERROR) << \"Unable to initialize Pano graph\";\n return false;\n }\n return true;\n}\n\nvoid PanoGraph::SetRandomSeed(int random_seed) { random_.seed(random_seed); }\n\nbool PanoGraph::BuildGraphWithRoot(const std::string& pano_id) {\n if (pano_id.empty()) {\n LOG(ERROR) << \"No pano ID has been specified\" << std::endl;\n return false;\n }\n\n if (!BuildGraph(pano_id, GraphRegion::kDepthBounded)) {\n return false;\n }\n PrefetchGraph(pano_id);\n return true;\n}\n\nbool PanoGraph::BuildRandomGraph() {\n std::vector<std::string> panos =\n metadata_cache_->PanosInGraphsOfSize(min_graph_depth_);\n if (panos.empty()) {\n LOG(ERROR) << \"No graphs available of the required depth between \"\n << min_graph_depth_ << \" and \" << max_graph_depth_;\n return false;\n }\n\n int pano_index = math::UniformRandomInt(&random_, panos.size() - 1);\n const auto& root_node = panos[pano_index];\n if (!BuildGraph(root_node, GraphRegion::kDepthBounded)) {\n return false;\n }\n PrefetchGraph(root_node);\n return true;\n}\n\nbool PanoGraph::BuildEntireGraph() {\n std::string pano = metadata_cache_->PanoInLargestGraph();\n if (!BuildGraph(pano, GraphRegion::kEntire)) {\n return false;\n }\n\n auto iter = node_tree_.begin();\n std::advance(iter, math::UniformRandomInt(&random_, node_tree_.size() - 1));\n const auto& root_node = iter->first;\n PrefetchGraph(root_node);\n return true;\n}\n\nvoid PanoGraph::SetGraphDepth(int min_depth, int max_depth) {\n min_graph_depth_ = min_depth;\n max_graph_depth_ = max_depth;\n}\n\nbool PanoGraph::SetPosition(const std::string& pano_id) {\n if (node_tree_.find(pano_id) == node_tree_.end()) {\n LOG(ERROR) << \"Pano \" << pano_id << \" is not in the current graph\";\n return false;\n }\n\n PrefetchGraph(pano_id);\n return true;\n}\n\nvoid PanoGraph::PrefetchGraph(const std::string& new_root) {\n std::vector<std::string> new_tree;\n std::vector<std::string> current_level = {new_root};\n std::set<std::string> already_in_tree = {new_root};\n\n // Iterate to the required depth fetching asynchronously and adding metadata\n // for children to the node tree.\n std::vector<std::string> temp_level;\n for (int i = 0; i < prefetch_depth_; ++i) {\n temp_level.clear();\n\n for (const auto& node_id : current_level) {\n const auto& metadata = node_tree_[node_id];\n new_tree.push_back(node_id);\n\n for (const auto& neighbour : metadata.neighbors) {\n if (node_tree_.find(neighbour.id()) == node_tree_.end()) {\n continue;\n }\n\n auto insert_result = already_in_tree.insert(neighbour.id());\n if (insert_result.second) {\n temp_level.push_back(neighbour.id());\n }\n }\n }\n\n current_level.swap(temp_level);\n }\n\n // Cancel any outstanding fetches.\n CancelPendingFetches();\n\n // Fetch the root of the new graph synchronously.\n root_node_ = FetchNode(new_root);\n\n // Fetch any new nodes required.\n current_subtree_ = std::move(new_tree);\n blockingCounter_ =\n absl::make_unique<absl::BlockingCounter>(current_subtree_.size());\n for (const auto& node_id : current_subtree_) {\n PrefetchNode(node_id);\n }\n}\n\nstd::shared_ptr<Image3_b> PanoGraph::RootImage() const {\n return root_node_.image();\n}\n\nbool PanoGraph::Metadata(const std::string& pano_id,\n PanoMetadata* metadata) const {\n const PanoMetadata* node_metadata = GetNodeMetadata(pano_id);\n if (!node_metadata) {\n return false;\n }\n\n *metadata = *node_metadata;\n return true;\n}\n\nbool PanoGraph::MoveToNeighbor(double current_bearing, double tolerance) {\n if (node_tree_.empty()) {\n LOG(ERROR) << \"Cannot move to a neighbor until the graph has been built!\";\n return false;\n }\n\n // Our current bearing.\n double current_bearing_rads = math::DegreesToRadians(current_bearing);\n if (-M_PI > current_bearing_rads || current_bearing_rads > M_PI) {\n LOG(ERROR) << \"current_bearing must be in range [-PI, PI]!\";\n return false;\n }\n double tolerance_rads = math::DegreesToRadians(tolerance);\n\n // Work out which neighbor is closest to the current bearing.\n // TODO: reintroduce max_neighbor_depth.\n auto neighbour_bearings = GetNeighborBearings(3 /* max_neighbor_depth */);\n\n std::string node_id;\n double min_distance = std::numeric_limits<double>::max();\n for (const auto& neighbour_bearing : neighbour_bearings) {\n double bearing = math::DegreesToRadians(neighbour_bearing.bearing);\n double offset = fabs(current_bearing_rads - bearing);\n // When either side of PI use the smaller angle between them.\n if (offset > M_PI) {\n offset = 2.0 * M_PI - offset;\n }\n\n if (offset < tolerance_rads && neighbour_bearing.distance < min_distance) {\n min_distance = neighbour_bearing.distance;\n node_id = neighbour_bearing.pano_id;\n }\n }\n\n if (!node_id.empty()) {\n PrefetchGraph(node_id);\n }\n\n return true;\n}\n\nstd::vector<PanoNeighborBearing> PanoGraph::GetNeighborBearings(\n int max_neighbor_depth) const {\n std::vector<PanoNeighborBearing> retval;\n auto root_iter = node_tree_.find(root_node_.id());\n if (root_iter != node_tree_.end()) {\n std::set<std::string> visited;\n visited.insert(root_node_.id());\n\n const auto& root_metadata = root_iter->second;\n\n std::vector<std::string> nodes;\n nodes.reserve(root_metadata.neighbors.size());\n\n auto get_pano_id = [](const PanoIdAndGpsCoords& id_and_coords) {\n return id_and_coords.id();\n };\n std::transform(root_metadata.neighbors.begin(),\n root_metadata.neighbors.end(), std::back_inserter(nodes),\n get_pano_id);\n std::vector<std::string> next_nodes;\n for (int depth = 0; depth < max_neighbor_depth; ++depth) {\n for (const auto& node_id : nodes) {\n if (visited.insert(node_id).second) {\n auto iter = node_tree_.find(node_id);\n if (iter != node_tree_.end()) {\n const auto& node = iter->second;\n if (depth == 0 ||\n std::abs(root_metadata.pano.alt() - node.pano.alt()) <\n kNeighborAltituteThresholdMeters) {\n auto bearing = BearingBetweenPanos(root_metadata.pano, node.pano);\n retval.emplace_back(PanoNeighborBearing{\n node_id, bearing,\n DistanceBetweenPanos(root_metadata.pano, node.pano)});\n next_nodes.reserve(next_nodes.size() + node.neighbors.size());\n std::transform(node.neighbors.begin(), node.neighbors.end(),\n std::back_inserter(next_nodes), get_pano_id);\n }\n }\n }\n }\n nodes.clear();\n nodes.swap(next_nodes);\n }\n }\n return retval;\n}\n\nstd::map<int, std::vector<TerminalGraphNode>>\nPanoGraph::InteriorTerminalBearings(const PanoMetadata& node) const {\n std::map<int, std::vector<TerminalGraphNode>> retval;\n if (node.neighbors.size() == 1) {\n auto neighbor_iter = node_tree_.find(node.neighbors[0].id());\n if (neighbor_iter != node_tree_.end()) {\n // Use the bearing from the neighbor to the current position.\n auto bearing = BearingBetweenPanos(neighbor_iter->second.pano, node.pano);\n auto distance =\n DistanceBetweenPanos(node.pano, neighbor_iter->second.pano) / 4;\n retval[1].emplace_back(distance, bearing);\n }\n }\n return retval;\n}\n\nstd::map<int, std::vector<TerminalGraphNode>> PanoGraph::TerminalBearings(\n const std::string& node_id) const {\n auto iter = node_tree_.find(node_id);\n if (iter == node_tree_.end()) {\n return {};\n }\n const auto& node = iter->second;\n\n // 1. Deal with terminal nodes inside the graph\n if (terminal_nodes_.find(node_id) != terminal_nodes_.end()) {\n return InteriorTerminalBearings(node);\n }\n\n // 2. Deal with terminal nodes outside, cutoff by breadth-first traversal.\n std::map<int, std::vector<TerminalGraphNode>> retval;\n for (const auto& neighbor : node.neighbors) {\n auto terminal_iter = terminal_nodes_.find(neighbor.id());\n if (terminal_iter != terminal_nodes_.end()) { // Immediate neighbors.\n auto bearing = BearingBetweenPanos(node.pano, terminal_iter->second.pano);\n auto distance =\n DistanceBetweenPanos(node.pano, terminal_iter->second.pano);\n retval[1].emplace_back(distance, bearing);\n } else {\n auto neighbor_iter = node_tree_.find(neighbor.id());\n if (neighbor_iter == node_tree_.end()) { // Neighbors two panos away.\n continue;\n }\n for (const auto& second_neighbor : neighbor_iter->second.neighbors) {\n if (node_tree_.find(second_neighbor.id()) != node_tree_.end()) {\n continue; // Terminal node inside the graph.\n }\n auto terminal_iter = terminal_nodes_.find(second_neighbor.id());\n if (terminal_iter != terminal_nodes_.end()) {\n auto bearing =\n BearingBetweenPanos(node.pano, terminal_iter->second.pano);\n auto distance =\n DistanceBetweenPanos(node.pano, terminal_iter->second.pano);\n retval[2].emplace_back(distance, bearing);\n }\n }\n }\n }\n return retval;\n}\n\nabsl::optional<double> PanoGraph::GetPanoDistance(const std::string& pano_id1,\n const std::string& pano_id2) {\n const PanoMetadata* metadata1 = GetNodeMetadata(pano_id1);\n if (metadata1) {\n const PanoMetadata* metadata2 = GetNodeMetadata(pano_id2);\n if (metadata2) {\n return DistanceBetweenPanos(metadata1->pano, metadata2->pano);\n }\n }\n\n return absl::nullopt;\n}\n\nabsl::optional<double> PanoGraph::GetPanoBearing(const std::string& pano_id1,\n const std::string& pano_id2) {\n const PanoMetadata* metadata1 = GetNodeMetadata(pano_id1);\n if (metadata1) {\n const PanoMetadata* metadata2 = GetNodeMetadata(pano_id2);\n if (metadata2) {\n return BearingBetweenPanos(metadata1->pano, metadata2->pano);\n }\n }\n\n return absl::nullopt;\n}\n\nconst PanoMetadata* PanoGraph::GetNodeMetadata(\n const std::string& pano_id) const {\n const auto it = node_tree_.find(pano_id);\n if (it == node_tree_.end()) {\n LOG(ERROR) << \"Invalid pano id: \" << pano_id;\n return nullptr;\n }\n return &it->second;\n}\n\nstd::map<std::string, std::vector<std::string>> PanoGraph::GetGraph() const {\n std::map<std::string, std::vector<std::string>> retval;\n for (const auto& node : node_tree_) {\n for (const auto& neighbor : node.second.neighbors) {\n // Only include neighbors that are in the graph.\n if (node_tree_.find(neighbor.id()) != node_tree_.end()) {\n retval[node.first].push_back(neighbor.id());\n }\n }\n }\n return retval;\n}\n\nbool PanoGraph::BuildGraph(const std::string& root_node_id,\n GraphRegion graph_region) {\n node_tree_.clear();\n terminal_nodes_.clear();\n\n // Start at start_node and iterate to max_depth.\n std::vector<std::string> current_level = {root_node_id};\n std::set<std::string> already_in_tree = {root_node_id};\n\n int max_depth = graph_region == GraphRegion::kEntire\n ? std::numeric_limits<int>::max()\n : max_graph_depth_;\n\n std::vector<std::string> temp_level;\n for (int i = 0; i < max_depth && !current_level.empty(); ++i) {\n temp_level.clear();\n\n for (const auto& node_id : current_level) {\n auto* metadata = metadata_cache_->GetPanoMetadata(node_id);\n if (metadata == nullptr) {\n LOG(ERROR) << \"Unknown pano: \" << node_id;\n return false;\n }\n node_tree_.emplace(node_id, *metadata);\n\n // Nodes with a single neighbour must be terminal.\n if (metadata->neighbors.size() == 1) {\n terminal_nodes_.emplace(node_id, *metadata);\n }\n\n for (const auto& neighbour : metadata->neighbors) {\n auto insert_result = already_in_tree.insert(neighbour.id());\n if (insert_result.second) {\n temp_level.push_back(neighbour.id());\n }\n }\n }\n\n current_level.swap(temp_level);\n }\n\n // Add terminal nodes outside the graph.\n for (const auto& node_id : current_level) {\n auto* metadata = metadata_cache_->GetPanoMetadata(node_id);\n terminal_nodes_.emplace(node_id, *metadata);\n }\n\n return true;\n}\n\nPanoGraphNode PanoGraph::FetchNode(const std::string& node_id) {\n PanoGraphNode retval;\n absl::Notification notification;\n node_cache_.Lookup(node_id,\n [&retval, &notification](const PanoGraphNode* node) {\n retval = *node;\n notification.Notify();\n });\n notification.WaitForNotification();\n return retval;\n}\n\nvoid PanoGraph::PrefetchNode(const std::string& node_id) {\n node_cache_.Lookup(node_id, [this](const PanoGraphNode* node) {\n if (blockingCounter_) {\n blockingCounter_->DecrementCount();\n }\n });\n}\n\nvoid PanoGraph::CancelPendingFetches() {\n node_cache_.CancelPendingFetches();\n if (blockingCounter_) {\n blockingCounter_->Wait();\n }\n blockingCounter_ = nullptr;\n}\n\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.6443089246749878, "alphanum_fraction": 0.6531165242195129, "avg_line_length": 32.044776916503906, "blob_id": "38ecc07162e15cd88d982140895cb402d040f822", "content_id": "405552194b74f08fcd200d633d1fe051e0f03b33", "detected_licenses": [ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4428, "license_type": "permissive", "max_line_length": 80, "num_lines": 134, "path": "/streetlearn/engine/test_utils.cc", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#include \"streetlearn/engine/test_utils.h\"\n\n#include <cstdlib>\n#include <fstream>\n#include <string>\n\n#include \"gtest/gtest.h\"\n#include <opencv/cv.h>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/types_c.h>\n#include \"absl/memory/memory.h\"\n#include \"absl/strings/str_cat.h\"\n#include \"absl/strings/string_view.h\"\n#include \"absl/time/clock.h\"\n#include \"absl/time/time.h\"\n#include \"streetlearn/engine/pano_graph_node.h\"\n\n#ifndef STREETLEARN_SUPPRESS_COMMANDLINE_FLAGS\n\n#include \"absl/flags/flag.h\"\nDECLARE_string(test_srcdir);\n#endif\n\nnamespace streetlearn {\nnamespace test_utils {\n\nstd::string TestSrcDir() {\n#ifndef STREETLEARN_SUPPRESS_COMMANDLINE_FLAGS\n return absl::GetFlag(FLAGS_test_srcdir) + \"/streetlearn\";\n#else\n const char* const test_srcdir = std::getenv(\"TEST_SRCDIR\");\n if (test_srcdir) {\n std::string path = absl::StrCat(test_srcdir, \"/\");\n const char* const test_workspace = std::getenv(\"TEST_WORKSPACE\");\n\n if (test_workspace) {\n return absl::StrCat(path, test_workspace, \"/streetlearn/\");\n }\n\n return path;\n }\n return \"[undefined TEST_SRCDIR environment variable]\";\n#endif\n}\n\n::testing::AssertionResult CompareImages(\n const ImageView4_b& image, absl::string_view expected_image_path) {\n std::vector<uint8_t> buf(image.width() * image.height() * 3);\n for (int y = 0; y < image.height(); ++y) {\n int row_offset = y * image.width();\n for (int x = 0; x < image.width(); ++x) {\n int out_offset = 3 * (row_offset + x);\n const uint8_t* pixel = image.pixel(x, y);\n buf[out_offset] = pixel[2];\n buf[out_offset + 1] = pixel[1];\n buf[out_offset + 2] = pixel[0];\n }\n }\n\n return CompareRGBBufferWithImage(absl::MakeSpan(buf), image.width(),\n image.height(), kPackedRGB,\n expected_image_path);\n}\n\n::testing::AssertionResult CompareRGBBufferWithImage(\n absl::Span<const uint8_t> buffer, int width, int height, PixelFormat format,\n absl::string_view expected_image_path) {\n cv::Mat original_image =\n cv::imread(test_utils::TestSrcDir() + std::string(expected_image_path));\n\n // Treat empty images as identical.\n if (original_image.empty() && width == 0 && height == 0) {\n return ::testing::AssertionSuccess();\n }\n\n if (width != original_image.cols || height != original_image.rows) {\n return ::testing::AssertionFailure()\n << \"Image size does not match: (\" << width << \",\" << height << \",\"\n << \") != (\" << original_image.cols << \",\" << original_image.rows\n << \")\";\n }\n\n // Construct a Mat from the buffer.\n cv::Mat image;\n uint8_t* data = const_cast<uint8_t*>(buffer.data());\n\n if (format == kPackedRGB) {\n image = cv::Mat(height, width, CV_8UC3, data);\n } else {\n cv::Mat channel_r(height, width, CV_8UC1, data);\n cv::Mat channel_g(height, width, CV_8UC1, data + width * height);\n cv::Mat channel_b(height, width, CV_8UC1, data + 2 * width * height);\n cv::merge(std::vector<cv::Mat>{channel_r, channel_g, channel_b}, image);\n }\n\n cv::Mat image_gray;\n cvtColor(image, image_gray, CV_RGB2GRAY);\n cv::Mat original_image_gray;\n cvtColor(original_image, original_image_gray, CV_BGR2GRAY);\n\n cv::Mat diff;\n cv::compare(image_gray, original_image_gray, diff, cv::CMP_NE);\n\n int diff_count = cv::countNonZero(diff);\n if (diff_count) {\n std::string diff_image_path = absl::StrCat(\n ::testing::TempDir(), \"diff_\", absl::ToUnixNanos(absl::Now()), \".png\");\n cv::imwrite(diff_image_path, diff);\n\n return ::testing::AssertionFailure()\n << \"Pixels do not match. Number of differences: \" << diff_count\n << \". Binary diff saved to: \" << diff_image_path;\n }\n\n return ::testing::AssertionSuccess();\n}\n\n} // namespace test_utils\n} // namespace streetlearn\n" }, { "alpha_fraction": 0.7105262875556946, "alphanum_fraction": 0.7179356217384338, "avg_line_length": 33.33333206176758, "blob_id": "cefec2859ed9659d5388f8539356896cb01ac60e", "content_id": "c0e5904893b3db73fa095c41705582cd551fa327", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3914, "license_type": "permissive", "max_line_length": 80, "num_lines": 114, "path": "/streetlearn/engine/graph_image_cache.h", "repo_name": "turningpoint1988/streetlearn", "src_encoding": "UTF-8", "text": "// Copyright 2018 Google LLC\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// https://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#ifndef THIRD_PARTY_STREETLEARN_ENGINE_GRAPH_IMAGE_CACHE_H_\n#define THIRD_PARTY_STREETLEARN_ENGINE_GRAPH_IMAGE_CACHE_H_\n\n#include <map>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"absl/container/node_hash_map.h\"\n#include <cairo/cairo.h>\n#include \"streetlearn/engine/color.h\"\n#include \"streetlearn/engine/graph_region_mapper.h\"\n#include \"streetlearn/engine/image.h\"\n#include \"streetlearn/engine/pano_graph.h\"\n#include \"streetlearn/engine/vector.h\"\n#include \"s2/s1angle.h\"\n#include \"s2/s2latlng.h\"\n#include \"s2/s2latlng_rect.h\"\n\nnamespace streetlearn {\n\n// Cache of graph images at different levels of zoom showing the graph edges.\n// Used by the GraphRenderer which also draws nodes when zoomed in sufficiently.\nclass GraphImageCache {\n public:\n explicit GraphImageCache(const Vector2_i& screen_size,\n const std::map<std::string, Color>& highlighted)\n : screen_size_(screen_size),\n region_manager_(screen_size),\n highlighted_nodes_(highlighted) {}\n\n GraphImageCache(const GraphRegionMapper&) = delete;\n GraphImageCache& operator=(const GraphRegionMapper&) = delete;\n\n // Populates the edge cache and draws the top level image.\n bool InitCache(const PanoGraph& pano_graph, const S2LatLngRect& graph_bounds);\n\n // Updates the map region being rendered for the current level at the given\n // centre point. Returns a view into the image buffer at this region.\n ImageView4_b Pixels(const S2LatLng& image_centre);\n\n // Sets the current zoom and creates the level image if it's not in the cache.\n void SetZoom(double zoom);\n\n // Returns the current zoom.\n double current_zoom() const { return current_zoom_; }\n\n // Maps the lat/lng provided to screen coordinates.\n Vector2_d MapToScreen(const S2LatLng& lat_lng) const {\n return region_manager_.MapToScreen(lat_lng.lat().degrees(),\n lat_lng.lng().degrees());\n }\n\n private:\n // Collect all the node and edges in the graph.\n bool SetGraph(const PanoGraph& pano_graph);\n\n // Creates and caches a graph image for the current level.\n void RenderLevel();\n\n // Draws an edge between each pair of nodes in the graph.\n void DrawEdges(int image_width, int image_height, cairo_t* context);\n\n // Draws a filled circle marker for any nodes that need highlighted.\n void DrawNodes(int image_width, int image_height, cairo_t* context);\n\n // The size of the screen into which to render.\n Vector2_i screen_size_;\n\n // The current zoom level.\n double current_zoom_ = 1.0;\n\n // Helper to map lat/lng regions to screen coordinates.\n GraphRegionMapper region_manager_;\n\n // Representation of a graph edge.\n struct GraphEdge {\n GraphEdge() = default;\n GraphEdge(S2LatLng start, S2LatLng end)\n : start(std::move(start)), end(std::move(end)) {}\n S2LatLng start;\n S2LatLng end;\n };\n\n // Collection of nodes that need rendered.\n std::map<std::string, S2LatLng> nodes_;\n\n // Collection of graph edges that need rendered.\n std::vector<GraphEdge> graph_edges_;\n\n // Collection of nodes that need colored.\n std::map<std::string, Color> highlighted_nodes_;\n\n // Cache of images at different zoom levels.\n absl::node_hash_map<double, Image4_b> image_cache_;\n};\n\n} // namespace streetlearn\n\n#endif // THIRD_PARTY_STREETLEARN_ENGINE_GRAPH_IMAGE_CACHE_H_\n" } ]
87
JarrettBillingsley/logisim
https://github.com/JarrettBillingsley/logisim
16d510725c038aa0bbb045083d2d91315ef507a0
deb87a9d82281cac2e4b0d10d64b9fa1b9b6fd1a
21d47733bd1eca0863bad332d5725e4f8d088b50
refs/heads/master
2023-08-16T19:41:06.049560
2023-08-14T23:55:31
2023-08-14T23:55:31
245,507,048
3
1
null
null
null
null
null
[ { "alpha_fraction": 0.7445945739746094, "alphanum_fraction": 0.7479729652404785, "avg_line_length": 32.13432693481445, "blob_id": "4a797c6ba26e5be835816c0182fb19dfbb039be4", "content_id": "3063f1f03bb826d33a06bdd8bd118afc7f66261c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4440, "license_type": "no_license", "max_line_length": 94, "num_lines": 134, "path": "/src/com/jfbillingsley/compiler/Compiler.java", "repo_name": "JarrettBillingsley/logisim", "src_encoding": "UTF-8", "text": "package com.jfbillingsley.compiler;\n\nimport java.net.URL;\n\nimport javax.swing.ImageIcon;\nimport java.awt.Color;\nimport java.awt.Graphics;\n\nimport com.cburch.logisim.data.Attribute;\nimport com.cburch.logisim.data.BitWidth;\nimport com.cburch.logisim.data.Bounds;\nimport com.cburch.logisim.data.Direction;\nimport com.cburch.logisim.data.Value;\nimport com.cburch.logisim.instance.Instance;\nimport com.cburch.logisim.instance.InstanceFactory;\nimport com.cburch.logisim.instance.InstancePainter;\nimport com.cburch.logisim.instance.InstanceState;\nimport com.cburch.logisim.instance.Port;\nimport com.cburch.logisim.instance.StdAttr;\nimport com.cburch.logisim.util.GraphicsUtil;\nimport com.cburch.logisim.util.StringUtil;\n\nclass Compiler extends InstanceFactory {\n\t// Port constants\n\tpublic static final int DATA = 0;\n\tpublic static final int ADDR = 1;\n\tpublic static final int NUM_PORTS = 2;\n\n\tpublic static final int PORT_DELAY = 10;\n\n\t// Compiler-related constants\n\tpublic static final CompilerCore core = new CompilerCore2204();\n\n\tprivate final int ADDRESS_WIDTH;\n\tprivate final int INSTRUCTION_WIDTH;\n\tprivate final BitWidth inBitWidth;\n\tprivate final BitWidth outBitWidth;\n\n\tpublic Compiler() {\n\t\tsuper(String.format(\"Compiler (%s)\", core.getName()));\n\n\t\tADDRESS_WIDTH = core.getAddressBits();\n\t\tINSTRUCTION_WIDTH = core.getInstructionBits();\n\t\tinBitWidth = BitWidth.create(ADDRESS_WIDTH);\n\t\toutBitWidth = BitWidth.create(INSTRUCTION_WIDTH);\n\n\t\tBounds bds = CompilerState.createOffsetBounds();\n\t\tsetOffsetBounds(bds);\n\n\t\tPort[] ps = new Port[NUM_PORTS];\n\t\tps[ADDR] = new Port(-bds.getWidth(), 0, Port.INPUT, ADDRESS_WIDTH);\n\t\tps[DATA] = new Port( 0, 0, Port.OUTPUT, INSTRUCTION_WIDTH);\n\t\tsetPorts(ps);\n\n\t\tsetInstancePoker(CompilerPoker.class);\n\n\t\t// URL url = getClass().getClassLoader().getResource(\"com/cburch/gray/counter.gif\");\n\t\t// if(url != null) setIcon(new ImageIcon(url));\n\n\t\t/*\n\t\tMemMenu is the special popup menu for memory components. It's bound to an instance.\n\t\tMemPoker is the poker. It has two subclasses, DataPoker and AddrPoker.\n\t\tMemState is the instance state; it has a MemContents.\n\t\tMemContents abstracts the pages; MemContentsSub abstracts a single page using an\n\t\t\tappropriately sized array based on the memory width.\n\t\tMem is the abstract base class instance factory for both RAM and ROM.\n\t\tRom extends Mem and returns RomAttributes.\n\t\tRomAttributes is the ROM attribute set, and also manages popup windows and change listeners.\n\t\tRomContentsListener is used to listen for changes by the hex editor.\n\n\t\tBRAIN COREDUMP:\n\t\t\tCompilerState holds the state for one instance of a Compiler component.\n\t\t\tCompilerCore is an interface that can be used for several different compilers.\n\t\t\tAdding a new compiler would mean implementing that interface, and using that as the\n\t\t\t\t\"core\" variable above.\n\t\t\tThe rest of the component just needs to:\n\t\t\t\t- Display the code\n\t\t\t\t- Display the compiled version of it next to it (with proper line info)\n\t\t\t\t- Allow the user to load programs, give them to the compiler core, and get an error\n\t\t\t\tmessage if it failed\n\t\t\tYee\n\n\t\t\tALSO remove the \"just for testing\" stuff in Builtin.java\n\n\t\tThen, to make the library:\n\t\t\tMake a jar file with META-INF/MANIFEST.MF:\n\t\t\t\tManifest-Version: 1.0\n\t\t\t\tLibrary-Class: com.jfbillingsley.compiler.Components\n\n\t\t\t(don't forget newline after last line)\n\t\t\tand the class files\n\t\t\tand that's it.\n\t\t*/\n\t}\n\n\t@Override\n\tprotected void configureNewInstance(Instance instance) {\n\n\t}\n\n\t@Override\n\tpublic void propagate(InstanceState state) {\n\t\tCompilerState myState = CompilerState.get(state, core);\n\t\tValue addrValue = state.getPort(ADDR);\n\t\tint addr = addrValue.toIntValue();\n\n\t\tif(!addrValue.isFullyDefined() || addr < 0)\n\t\t\treturn;\n\t\tif(addr != myState.getCurrent()) {\n\t\t\tmyState.setCurrent(addr);\n\t\t\tmyState.scrollToShow(addr);\n\t\t}\n\n\t\tint val = myState.getInstruction(addr);\n\t\tstate.setPort(DATA, Value.createKnown(outBitWidth, val), PORT_DELAY);\n\t}\n\n\t@Override\n\tpublic void paintInstance(InstancePainter painter) {\n\t\tGraphics g = painter.getGraphics();\n\t\tpainter.drawBounds();\n\t\tpainter.drawPort(DATA);\n\t\tpainter.drawPort(ADDR);\n\n\t\tif(painter.getShowState()) {\n\t\t\tCompilerState state = CompilerState.get(painter, core);\n\t\t\tstate.paint(painter.getGraphics(), painter.getBounds());\n\t\t} else {\n\t\t\tBounds bds = painter.getBounds();\n\t\t\tGraphicsUtil.drawCenteredText(g, \"Haha who prints circuits?\",\n\t\t\t\tbds.getCenterX(), bds.getCenterY());\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.7434782385826111, "alphanum_fraction": 0.7456521987915039, "avg_line_length": 25.285715103149414, "blob_id": "b874c96409f9c6eec0bad284285b2da8acc6b88a", "content_id": "4807f9323797727608bdbd975f455dbd52550256", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1840, "license_type": "no_license", "max_line_length": 73, "num_lines": 70, "path": "/src/com/cburch/logisim/gui/log/ScrollPanel.java", "repo_name": "JarrettBillingsley/logisim", "src_encoding": "UTF-8", "text": "/* Copyright (c) 2010, Carl Burch. License information is located in the\n * com.cburch.logisim.Main source code and at www.cburch.com/logisim/. */\n\npackage com.cburch.logisim.gui.log;\n\nimport java.awt.BorderLayout;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\n\nimport javax.swing.JButton;\nimport javax.swing.JScrollPane;\n\nimport com.cburch.logisim.data.Value;\n\nclass ScrollPanel extends LogPanel {\n\tprivate class MyListener implements ActionListener, ModelListener {\n\t\tpublic void actionPerformed(ActionEvent event) {\n\t\t\tObject src = event.getSource();\n\t\t\tif (src == clear) {\n\t\t\t\tgetModel().clearLog();\n\t\t\t}\n\t\t}\n\n\t\tpublic void selectionChanged(ModelEvent event) {}\n\t\tpublic void entryAdded(ModelEvent event, Value[] values) {}\n\t\tpublic void filePropertyChanged(ModelEvent event) {\n\t\t\tclear.setEnabled(!getModel().isFileEnabled());\n\t\t}\n\t\tpublic void logCleared(ModelEvent event) {}\n\t}\n\n\tprivate TablePanel table;\n\tprivate MyListener myListener = new MyListener();\n\tprivate JButton clear = new JButton();\n\n\tpublic ScrollPanel(LogFrame frame) {\n\t\tsuper(frame);\n\t\tthis.table = new TablePanel(frame);\n\t\tJScrollPane pane = new JScrollPane(table,\n\t\t\t\tJScrollPane.VERTICAL_SCROLLBAR_ALWAYS,\n\t\t\t\tJScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);\n\t\tpane.setVerticalScrollBar(table.getVerticalScrollBar());\n\t\tsetLayout(new BorderLayout());\n\t\tadd(pane, BorderLayout.CENTER);\n\t\tadd(clear, BorderLayout.SOUTH);\n\n\t\tclear.addActionListener(myListener);\n\t}\n\n\t@Override\n\tpublic String getTitle() {\n\t\treturn table.getTitle();\n\t}\n\n\t@Override\n\tpublic String getHelpText() {\n\t\treturn table.getHelpText();\n\t}\n\n\t@Override\n\tpublic void localeChanged() {\n\t\ttable.localeChanged();\n\t\tclear.setText(Strings.get(\"clearButton\"));\n\t}\n\n\t@Override\n\tpublic void modelChanged(Model oldModel, Model newModel) {\n\t\ttable.modelChanged(oldModel, newModel);\n\t}\n}\n" }, { "alpha_fraction": 0.7090908885002136, "alphanum_fraction": 0.7090908885002136, "avg_line_length": 26.5, "blob_id": "299044b33dad8b4def3508a2c78cd965ac38bab1", "content_id": "fc209b76f54fd0228d7eccd116a73a681f4b4b84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 55, "license_type": "no_license", "max_line_length": 45, "num_lines": 2, "path": "/run.sh", "repo_name": "JarrettBillingsley/logisim", "src_encoding": "UTF-8", "text": "#/bin/sh\njava -cp build/ com.cburch.logisim.Logisim $@\n" }, { "alpha_fraction": 0.5819112658500671, "alphanum_fraction": 0.5878839492797852, "avg_line_length": 29.85087776184082, "blob_id": "59c4fb713b685078d037580d20239a135629f23b", "content_id": "fbdc20d4fe2445163a07d9fa221784845eede33f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3516, "license_type": "no_license", "max_line_length": 87, "num_lines": 114, "path": "/scripts/pot-create.py", "repo_name": "JarrettBillingsley/logisim", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport datetime\nimport os\nimport re\nimport shutil\nimport tarfile\nfrom logisim_script import *\n\nFILENAME = 'logisim-pot.tgz'\n\ngui_dir = get_svn_dir('src', 'resources/logisim')\ndst_dir = os.path.join(os.getcwd(), 'pot-dir')\ndst_tarball = build_path(os.getcwd(), FILENAME)\nknown_langs = 'ru es'.split()\nkeep_temporary = False\n\nif '\\\\home\\\\burch\\\\' in get_svn_dir():\n tar_cmd = 'C:/cygwin/bin/tar.exe'\n \nif 'unichr' not in dir():\n unichr = chr\n\nif os.path.exists(dst_tarball):\n user = prompt('file ' + FILENAME + ' already exists. Replace [y/n]?', 'yn')\n if user == 'n':\n sys.exit('POT creation aborted on user request')\n os.remove(dst_tarball)\n\n#\n# Clear the destination directory\n#\nif os.path.exists(dst_dir):\n shutil.rmtree(dst_dir)\nos.mkdir(dst_dir)\n\nversion, copyright = determine_version_info()\ndate = datetime.datetime.now().strftime('%Y-%m-%d %H:%M%z')\n\nheader = r'''\nmsgid \"\"\nmsgstr \"\"\n\"Project-Id-Version: Logisim {version}\\n\"\n\"Report-Msgid-Bugs-To: \\n\"\n\"POT-Creation-Date: {date}\\n\"\n\"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\\n\"\n\"Last-Translator: FULL NAME <EMAIL@ADDRESS>\\n\"\n\"Language-Team: LANGUAGE <[email protected]>\\n\"\n\"MIME-Version: 1.0\\n\"\n\"Content-Type: text/plain; charset=utf-8\\n\"\n\"Content-Transfer-Encoding: 8bit\\n\"\n\"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n\"\n'''.strip().format(version=version, date=date)\n\n#\n# Create the file for .properties strings\n#\nprop_patt = re.compile(r'^([a-zA-Z0-9]+)\\s*=\\s*(\\S.*)$')\nunicode_patt = re.compile(r'\\\\u([0-9a-fA-F]{4})')\ndef unicode_repl(match):\n return unichr(int(match.group(1), 16))\n\nos.mkdir(build_path(dst_dir, 'gui'))\n\ndef load_lang(lang):\n key_list = []\n key_dict = {}\n suffix = '_' + lang + '.properties'\n for file in os.listdir(build_path(gui_dir, lang)):\n if file.endswith(suffix):\n file_base = file[:-len(suffix)]\n with open(os.path.join(gui_dir, lang, file), encoding='ISO-8859-1') as src:\n for line in src:\n match = prop_patt.match(line)\n if match:\n key = file_base + ':' + match.group(1)\n value = match.group(2).replace('\"', '\\\\\"')\n value = unicode_patt.sub(unicode_repl, value)\n key_list.append(key)\n key_dict[key] = value\n return key_list, key_dict\n\nen_keys, en_dict = load_lang('en')\nwith open(build_path(dst_dir, 'gui', 'gui.pot'), 'w', encoding='utf-8') as dst:\n dst.write(header + '\\n')\n for key in en_keys:\n dst.write('\\n')\n dst.write('msgctxt {ctxt}\\n'.format(ctxt=key))\n dst.write('msgid \"{msgid}\"\\n'.format(msgid=en_dict[key]))\n dst.write('msgstr \"{xlate}\"\\n'.format(xlate=''))\n \nfor lang in known_langs:\n lang_keys, lang_dict = load_lang(lang)\n with open(build_path(dst_dir, 'gui', lang + '.po'), 'w', encoding='utf-8') as dst:\n dst.write(header + '\\n')\n for key in en_keys:\n msgid = en_dict[key]\n if key in lang_dict:\n xlate = lang_dict[key]\n else:\n xlate = ''\n dst.write('\\n')\n dst.write('msgctxt {ctxt}\\n'.format(ctxt=key))\n dst.write('msgid \"{msgid}\"\\n'.format(msgid=msgid))\n dst.write('msgstr \"{xlate}\"\\n'.format(xlate=xlate))\n\ntarball = tarfile.open(dst_tarball, 'w:gz')\ntarball.add(dst_dir, '.')\ntarball.close()\n\nif not keep_temporary:\n shutil.rmtree(dst_dir)\n \nprint('POT creation completed')" }, { "alpha_fraction": 0.8016701340675354, "alphanum_fraction": 0.8041753768920898, "avg_line_length": 100.9148941040039, "blob_id": "14444463fb4c65ebce675347830f490dce801b23", "content_id": "5be6d5bd6dc7f73243bdcb0060f186d9de2e2f6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 4790, "license_type": "no_license", "max_line_length": 501, "num_lines": 47, "path": "/notes/2.7.1/README.TXT", "repo_name": "JarrettBillingsley/logisim", "src_encoding": "UTF-8", "text": "Logisim 2.7.1 fixes bugs, improves file handling\n\nLogisim, a graphical design and simulation tool for logic circuits, is now at version 2.7.1. This release's primary purpose is to address several issue discovered since 2.7.0 was released two weeks ago.\n\nOne of the primary bugs addressed in this release is one where a user could inadvertently change a component's attribute to an invalid value. The circuit would typically continue to work normally, but when the file is later reloaded, the file would refuse to load. This release repairs the cause of the invalid value assignments; and it enhances the file-loading process so that a dialog box appears explaining any problems found, and the portion of the file that could be interpreted is still loaded.\n\nAnother issue found in 2.7.0 was in the behavior of the transistors. In particular, a transistor would \"convert\" a floating (Z) value into an error value when told to transmit its source input; now, floating values are transmitted as floating values.\n\nBesides addressing many other issues besides these, this version also adds a \"Select Location\" attribute to the multiplexer, demultiplexer, and decoder, allowing the user to configure where these components' select (and enable) inputs are located relative to the component.\n\nFinally, this release marks the introduction of a mailing list where users can subscribe to hear about new developments regarding Logisim. We promise that the traffic on this list will average below one message per month. To subscribe, go to https://lists.sourceforge.net/lists/listinfo/circuit-announce\n\nEducational institutions around the world use Logisim as an aid to teaching about digital logic and computer architecture. As a Java application, Logisim can run on most major operating systems. Read more about Logisim at http://www.cburch.com/logisim/, and download it from SourceForge.net at http://sourceforge.net/projects/circuit/.\n\nCHANGE LOG\n\nFeature: When errors are in a file being loaded, the file is still partially loaded and displayed. If multiple errors are found, each is displayed.\n\nFeature: In Plexers library, added Select Location attribute to multiplexer, demultiplexer, and decoder.\n\nFeature: If some components somehow manage to get \"off the grid,\" they are relocated back onto the grid once they are moved. \n\nBehavior change: With transistors and transmission gates, a floating value is passed through as floating regardless of the value of gate (including a floating or error gate value).\n\nBehavior change: When clicking the currently viewed circuit, the circuit attributes are shown but no tool to add that circuit to itself is selected. This also happens with triple-clicking a circuit: The view is switched to the circuit, but the tool is not selected for adding instances to itself.\n\nBug fix: The combinational analysis \"Product of Sums\" option did not work when any variable other than the last one was to appear negated in any of the sums.\n\nBug fix: In the main editor window, when \"Close\" was selected from the Window menu, a dialog box popped up giving the Save/Discard/Cancel; but if Cancel was selected, the window was still closed (but without saving).\n\nBug fix: When \"Reset Simulation\" was selected while simulation was enabled, the reset values were not propagated through the circuit immediately.\n\nBug fix: Several types of exceptions could occur during simulation, particularly when poking the simulation while the simulation is busy. Many of these have been removed.\n\nBug fix: You could copy components from one project and paste them into another, even though the other project's libraries may not support the components being pasted.\n\nBug fix: Through starting to edit an attribute with a drop-down menu and then switching to view attributes for something else, the newly viewed attributes would actually change to the value of the previous edit.\n\nBug fix: When editing a circuit's appearances, labels would be given a color based on the fill color for rectangles/ovals/polygons rather than the color selected for text. This color was by default white, and so they appeared invisible.\n\nBug fix: When editing a circuit's appearance, changing between Border, Fill, Border & Fill didn't update attribute list (whether viewing attributes for a tool or for the current selection).\n\nBug fix: When editing a circuit's appearance and copying to the clipboard, the anchor's location and facing are stored to the clipboard if the selection includes the anchor.\n\nBug fix: In rare cases, loading files would show an error reading \"Resetting to invalid mark.\" (This seems to have involved a non-ASCII character in exactly the wrong position.)\n\nBug fix: The Windows executable's application description was changed so \"Open with\" context menu gives proper application name.\n" }, { "alpha_fraction": 0.6415209174156189, "alphanum_fraction": 0.6545343399047852, "avg_line_length": 33.640846252441406, "blob_id": "e9338d81117cbe4f111fa449121e8b0879f1e59f", "content_id": "7b3780409f997fb3fe25794c4455ec858145fa3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4918, "license_type": "no_license", "max_line_length": 121, "num_lines": 142, "path": "/scripts/build-www.py", "repo_name": "JarrettBillingsley/logisim", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport os\nimport re\nimport shutil\nimport sys\nimport xml.dom\nimport xml.dom.minidom\nfrom logisim_script import *\n\ndst_path = os.getcwd()\nsrc_path = build_path(get_svn_dir(), 'www')\n\n# see if we're on Carl Burch's platform, and if so reconfigure defaults\nif '\\\\home\\\\burch\\\\' in get_svn_dir():\n\tsvn_dir = get_svn_dir()\n\thome = svn_dir[:svn_dir.find('\\\\home\\\\burch\\\\') + 11]\n\tdst_path = build_path(home, 'logisim/Scripts/www/base')\n\tif not os.path.exists(dst_path):\n\t\tos.mkdir(dst_path)\n\tos.chdir(dst_path)\n\n# determine which HTML files are represented\nprint('determining HTML files available')\nhtml_files = { }\nlanguages = []\nfor lang in os.listdir(src_path):\n\tlang_dir = build_path(src_path, lang)\n\tif lang not in ['en', '.svn'] and os.path.isdir(build_path(src_path, lang)):\n\t\tactual = lang\n\t\tif actual == 'root':\n\t\t\tactual = 'en'\n\t\tlanguages.append((actual, lang_dir))\n\t\tfor file in os.listdir(lang_dir):\n\t\t\tif file.endswith('.html'):\n\t\t\t\tif file not in html_files:\n\t\t\t\t\thtml_files[file] = []\n\t\t\t\thtml_files[file].append(actual)\ndel html_files['template.html']\nfor file in html_files:\n\thtml_files[file].sort()\n\n# define function for creating translation menu for a file\ntemplate_langmenu_other = '''<tr>\n <th><a href=\"{rel}{xndir}{file}\">[{xn}]</a></th>\n <td><a href=\"{rel}{xndir}{file}\">{xnname}</a></td>\n</tr>'''\ntemplate_langmenu_cur = '''<tr><th>[{xn}]</th><td>{xnname}</td></tr>'''\nlangmenu_names = {\n\t'de': 'Deutsch',\n\t'el': '\\u0395\\u03BB\\u03BB\\u03B7\\u03BD\\u03B9\\u03BA\\u03AC',\n\t'en': 'English',\n\t'es': 'espa\\u00f1ol',\n\t'pt': 'Portugu\\u00eas',\n\t'ru': '\\u0420\\u0443\\u0441\\u0441\\u043a\\u0438\\u0439',\n}\n\ndef build_langmenu(file, lang):\n\tif file in html_files and len(html_files[file]) > 1:\n\t\tret = ['<div class=\"langmenu\"><table><tbody>']\n\t\trel = '../'\n\t\tif lang == 'en':\n\t\t\trel = ''\n\t\tfor xn in html_files[file]:\n\t\t\tif xn == 'en':\n\t\t\t\txndir = ''\n\t\t\telse:\n\t\t\t\txndir = xn + '/'\n\t\t\tif xn == lang:\n\t\t\t\ttemplate = template_langmenu_cur\n\t\t\telse:\n\t\t\t\ttemplate = template_langmenu_other\n\t\t\txnname = langmenu_names.get(xn, '???')\n\t\t\tret.append(template.format(xn=xn, xndir=xndir, rel=rel, file=file,\n\t\t\t\t\t\t\t\t\txnname=xnname))\n\t\tret.append('</tbody></table></div>')\n\t\treturn '\\n'.join(ret)\n\telse:\n\t\treturn ''\n\n# Now go through each language directory\ntemplate_head_re = re.compile(r'<head>\\s*<meta http-equiv=\"content-type[^>]*>\\s*(\\S.*)</head>', re.MULTILINE | re.DOTALL)\ntemplate_body_re = re.compile(r'<body>(.*)</body>', re.MULTILINE | re.DOTALL)\nfile_head_re = re.compile(r'</head>')\nfile_body_re = re.compile(r'<body>(.*)</body>', re.MULTILINE | re.DOTALL)\nrepl_langmenu_re = re.compile(r'<langmenu\\s*/?>', re.MULTILINE)\nrepl_contents_re = re.compile(r'<contents\\s*/?>', re.MULTILINE)\nfor lang, lang_src in languages:\n\tprint('building directory for ' + lang)\n\t# load the template\n\ttemplate_path = build_path(lang_src, 'template.html')\n\ttemplate_head = ''\n\ttemplate_body = '<contents />'\n\tif os.path.exists(template_path):\n\t\twith open(template_path, encoding='utf-8') as template_file:\n\t\t\ttemplate_text = template_file.read()\n\t\ttemplate_head_match = template_head_re.search(template_text)\n\t\tif template_head_match is None: print(' ' + lang + ' template: no head' + str(len(template_text)))\n\t\tif template_head_match is not None:\n\t\t\ttemplate_head = template_head_match.group(1)\n\t\ttemplate_body_match = template_body_re.search(template_text)\n\t\tif template_body_match is None: print(' ' + lang + ' template: no body' + str(len(template_text)))\n\t\tif template_body_match is not None:\n\t\t\ttemplate_body = template_body_match.group(1)\n\t\t\n\t# determine the destination directory\n\tif lang == 'en':\n\t\tlang_dst = dst_path\n\telse:\n\t\tlang_dst = build_path(dst_path, lang)\n\t\tif not os.path.exists(lang_dst) or os.path.getsize(lang_dst) == 0:\n\t\t\tos.mkdir(lang_dst)\n\t\n\t# copy each file over\n\tfor file in os.listdir(lang_src):\n\t\tfile_ext_start = file.rindex('.')\n\t\tif file_ext_start >= 0:\n\t\t\tfile_ext = file[file_ext_start + 1:]\n\t\tfile_src = build_path(lang_src, file)\n\t\tfile_dst = build_path(lang_dst, file)\n\t\tif file_ext in ['png', 'css', 'ico']:\n\t\t\tshutil.copy(file_src, file_dst)\n\t\telif file_ext == 'html' and file != 'template.html':\n\t\t\twith open(file_src, encoding='utf-8') as html_file:\n\t\t\t\thtml_text = html_file.read()\n\t\t\thtml_text = file_head_re.sub(template_head + '</head>', html_text)\n\t\t\thtml_body_match = file_body_re.search(html_text)\n\t\t\tif html_body_match is None:\n\t\t\t\thtml_body = ''\n\t\t\telse:\n\t\t\t\thtml_body = html_body_match.group(1)\n\t\t\t\tbody_start = html_body_match.start()\n\t\t\t\tbody_end = html_body_match.end()\n\t\t\t\thtml_text = (html_text[:body_start] + '<body>' + template_body\n\t\t\t\t\t\t\t+ '</body>' + html_text[body_end:])\n\t\t\tlangmenu = build_langmenu(file, lang)\n\t\t\thtml_text = repl_langmenu_re.sub(langmenu, html_text)\n\t\t\thtml_text = repl_contents_re.sub(html_body, html_text)\n\t\t\twith open(file_dst, 'w', encoding='utf-8') as html_file:\n\t\t\t\thtml_file.write(html_text)\n\nprint('HTML generation complete')" }, { "alpha_fraction": 0.7130621075630188, "alphanum_fraction": 0.7269807457923889, "avg_line_length": 24.94444465637207, "blob_id": "eb6ffbe9df858d44d9877c79f7980a2080c1cf96", "content_id": "ba15a86e9285147a1a536f6a3ff9e8fd244ee470", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 934, "license_type": "no_license", "max_line_length": 73, "num_lines": 36, "path": "/src/com/cburch/logisim/std/wiring/ConstantConfigurator.java", "repo_name": "JarrettBillingsley/logisim", "src_encoding": "UTF-8", "text": "/* Copyright (c) 2010, Carl Burch. License information is located in the\n * com.cburch.logisim.Main source code and at www.cburch.com/logisim/. */\n\npackage com.cburch.logisim.std.wiring;\n\nimport com.cburch.logisim.data.AttributeSet;\nimport com.cburch.logisim.data.BitWidth;\nimport com.cburch.logisim.instance.StdAttr;\nimport com.cburch.logisim.tools.key.IntegerConfigurator;\n\nclass ConstantConfigurator extends IntegerConfigurator {\n\tpublic ConstantConfigurator() {\n\t\tsuper(Constant.ATTR_VALUE, 0, 0, 0, 10);\n\t}\n\n\t@Override\n\tpublic int getMaximumValue(AttributeSet attrs) {\n\t\tBitWidth width = attrs.getValue(StdAttr.WIDTH);\n\t\tint ret = width.getMask();\n\t\tif (ret >= 0) {\n\t\t\treturn ret;\n\t\t} else {\n\t\t\treturn Integer.MAX_VALUE;\n\t\t}\n\t}\n\n\t@Override\n\tpublic int getMinimumValue(AttributeSet attrs) {\n\t\tBitWidth width = attrs.getValue(StdAttr.WIDTH);\n\t\tif (width.getWidth() < 32) {\n\t\t\treturn 0;\n\t\t} else {\n\t\t\treturn Integer.MIN_VALUE;\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.7987133264541626, "alphanum_fraction": 0.8010639548301697, "avg_line_length": 84.97872161865234, "blob_id": "04a11e2fe7a9ffbf28a50c5b0b6d1f282d6548c0", "content_id": "b2112c8e32b93314ec9e7c1b894a960567b2471a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 8083, "license_type": "no_license", "max_line_length": 740, "num_lines": 94, "path": "/notes/2.7.0/README.TXT", "repo_name": "JarrettBillingsley/logisim", "src_encoding": "UTF-8", "text": "LOGISIM 2.7.0 HAS SIMULATION TREE, GREEK, MUCH MORE\n\nLogisim, a graphical design and simulation tool for logic circuits, is now at version 2.7.0. The new version includes numerous enhancements and fixes; the most radical are a new Wiring library, a new method for drawing splitters, and enhancements to the main window's left-side explorer and attribute pane.\n\nThis version introduces the \"Wiring\" library, into which have been moved the circuit components previously found in \"Base\": splitter, pin, probe, clock, tunnel, pull resistor, and bit extender (and also constant, previously located in \"Gates\"). Additionally, the \"Wiring\" library now includes a transistor, transmission gate, power, and ground.\n\nAnother major change was in how splitters are drawn. The new technique conforms more closely to traditional circuit diagrams, and it includes labels showing the bit(s) to which each split end corresponds. The new \"Appearance\" attribute allows one to continue using the older technique, and projects created in older versions of Logisim will continue to load using this legacy support. However, projects can easily switch to the new appearance with labels by changing the splitters' Appearance attribute to \"Centered\".\n\nThe GUI has also received several updates. The explorer pane in the upper left corner has traditionally shown the current project's circuits and libraries; this is now called its \"Toolbox\" view. However, one can switch the explorer pane to instead show the \"Simulation Tree,\" which includes a toolbar for controlling the simulation and the hierarchy of subcircuits in the current simulation. This provides a visualization of the full hierarchy as well as an alternative to right-clicking subcircuits (or double-clicking them using the Poke Tool) to descend into viewing their states. Another notable enhancement to the GUI is an addition of a title bar to the attribute table, which indicates whose attributes are currently being displayed.\n\nAdditional features include a Greek translation of the GUI elements, labels specific to one instance of a subcircuit, an enable input for multiplexers/demultiplexers/decoders, an Output Value attribute for gates allowing them to emit floating values (permitting wired-and and wired-or logic), and support for product-of-sums expressions in the combinational analysis module. This version also marks the removal of the Legacy library and other code meant for supporting projects built in Logisim 1.0. And the \"project toolbar\" - previously disabled by default - is now always enabled.\n\nEducational institutions around the world use Logisim as an aid to teaching about digital logic and computer architecture. As a Java application, Logisim can run on most major operating systems. Read more about Logisim at http://www.cburch.com/logisim/, and download it from SourceForge.net at http://sourceforge.net/projects/circuit/.\n\n\nGUI\n\nFeature: Added the option of switching the \"explorer pane\" between viewing the \"toolbox\" (the project's circuits and libraries that has appeared in the explorer pane in previous versions) and a simulation hierarchy.\n\nFeature: A Greek translation of the GUI elements was added. (The documentation is not yet translated.)\n\nFeature: The attribute table contains a header line describing which attributes are being edited.\n\nFeature: Added a \"Close\" item to the Window menu, which closes the current window. The \"Close\" item in the File menu continues to close the current project; its shortcut is now Control-Shift-W.\n\nFeature: Added 250%, 300%, 400% to the options for zooming.\n\nFeature: File dialogs \"remember\" the location of the last-accessed file, and the next file dialog starts from there - even when Logisim is started again.\n\nFeature: During a rectangular selection, the rectangle is drawn with a light blue, and components that will be affected are indicated with a slate-blue outline.\n\nDesign change: Removed option to disable the project toolbar.\n\nBug fix: In moving a component whose output is connected to itself, it was possible for an exception to cause the program to hang.\n\nBug fix: The \"Second radix when wire poked\" preference was ignored - the \"First radix\" was displayed twice when the wire was poked.\n\nBug fix: Enabled the \"-clearprops\" command-line option for clearing all application preferences. (The previous version worked with \"-clearprefs\", but it was described as \"-clearprops\" in the \"-help\" text and in the documentation. Both now work.)\n\nBug fix: The Logging module's window title did not change when the file's name was changed.\n\n\nCORE\n\nFeature: Saving project files is more cautious, creating a backup before starting to write to disk and recovering from the backup if for some reason the save is detected to fail (whether nothing has been written to the file or an error has occurred while saving).\n\nFeature: Individual subcircuit instances can have a label, in addition to the \"shared label\" that is displayed in the center of each instance of a subcircuit.\n\nBug fix: When simulation is disabled, selecting Tick Once will still cause a tick once the simulation is stepped.\n\n\nLIBRARIES\n\nFeature: Added a Wiring library containing transistor, transmission gate, power and ground components. Also, the splitter, pin, probe, tunnel, clock, pull resistor, and bit extender were moved into the Wiring library from the Base library, and constant was moved into the Wiring library from the Gates library.\n\nFeature: In the Wiring library, splitters can be configured to show which bits correspond to each end using the new Appearance attribute. It uses this new appearance by default.\n\nFeature: In the Wiring library, the pop-up menu associated with splitters includes menu items for distributing the bits in ascending or descending order.\n\nFeature: In the Gates library, the gates (except Controlled Buffer and Controlled Inverter) have a new Output Value attribute so that a gate can output a floating value when the result is true or when the result is false. This is useful for building a wired-or and wired-and connections.\n\nFeature: In the Plexers library, an enable input was added to the multiplexer, demultiplexer, and decoder.\n\nFeature: In the Plexers library, the priority encoder received a new Disabled Output attribute.\n\nFeature: In the I/O library, the LED Matrix's Input Format attribute can be changed after the matrix is added into the circuit.\n\nDesign change: Deleted the \"Legacy\" library for loading files saved in versions 1.x of Logisim.\n\nDesign change: For the Memory library's Random component, a reset when the seed is 0 computes a new initial seed based on the current time. (It previously reset to the initial seed for the current simulation.)\n\nDesign change: All components except Constant now use the included GIF icons rather than Java code.\n\nBug fix: In the Wiring library, changing the label for a Tunnel would not immediately affect the values propagated through the circuit.\n\nBug fix: In the Wiring library, Pull Resistors did not respect \"printer view,\" which is meant to be black and white.\n\n\n\nCOMBINATIONAL ANALYSIS\n\nFeature: In the Combinational Analysis module, the user can select between using a sum of products or a product of sums.\n\nFeature: The Combinational Analysis module supports apostrophes (as in \"x'\" for NOT x).\n\nDesign change: The Combinational Analysis module's expression pane uses a larger font size than previously.\n\nBug fix: Some run-time exceptions that would occur upon doing \"Analyze Circuit\" a second time were removed.\n\nBug fix: In the Karnaugh maps drawn by the Combinational Analysis module, each implicant was indicated by a red rectangle, but they were meant to use varied colors.\n\nBug fix: The Combinational Analysis module's \"Build Circuit\" feature could create excess wire segments and even overlapping wires when a gate with an even number of inputs had several of its first half of inputs wired directly to the circuit inputs.\n\nBug fix: The \"Set As Expression\" button would sometimes not be disabled when pressed (particularly when the previous expression was the same except for spaces).\n\n" }, { "alpha_fraction": 0.8019417524337769, "alphanum_fraction": 0.8038834929466248, "avg_line_length": 50.599998474121094, "blob_id": "b20ef5212c2fcc67925319d1b803df1215e71093", "content_id": "10e49370dc81569931f0c5b8607ddf2a3030b24c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 515, "license_type": "no_license", "max_line_length": 79, "num_lines": 10, "path": "/www/README.TXT", "repo_name": "JarrettBillingsley/logisim", "src_encoding": "UTF-8", "text": "The Web site as it appears in translated versions is different in several small\nways from the original English version. The English version meant for\ntranslation is found in the 'en' subdirectory. (The original English version is\nin the 'root' subdirectory.)\n\nEach translation directory has a file named 'template.html', which is the\ntemplate used for generating the various HTML files in that translation. The\nother HTML files contain just the main body.\n\nPlease be sure to save each file using the UTF-8 encoding." }, { "alpha_fraction": 0.7831799983978271, "alphanum_fraction": 0.7884362936019897, "avg_line_length": 43.764705657958984, "blob_id": "76b735c029d7edae5d4903a676a2552103d97ee3", "content_id": "7a8d6d912d36027d2f41584019c1f18fb52f5972", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 761, "license_type": "no_license", "max_line_length": 86, "num_lines": 17, "path": "/src/com/cburch/logisim/circuit/CircuitMutator.java", "repo_name": "JarrettBillingsley/logisim", "src_encoding": "UTF-8", "text": "/* Copyright (c) 2010, Carl Burch. License information is located in the\n * com.cburch.logisim.Main source code and at www.cburch.com/logisim/. */\n\npackage com.cburch.logisim.circuit;\n\nimport com.cburch.logisim.comp.Component;\nimport com.cburch.logisim.data.Attribute;\n\npublic interface CircuitMutator {\n\tpublic void clear(Circuit circuit);\n\tpublic void add(Circuit circuit, Component comp);\n\tpublic void remove(Circuit circuit, Component comp);\n\tpublic void replace(Circuit circuit, Component oldComponent, Component newComponent);\n\tpublic void replace(Circuit circuit, ReplacementMap replacements);\n\tpublic void set(Circuit circuit, Component comp, Attribute<?> attr, Object value);\n\tpublic void setForCircuit(Circuit circuit, Attribute<?> attr, Object value);\n}\n" }, { "alpha_fraction": 0.744027316570282, "alphanum_fraction": 0.7576791644096375, "avg_line_length": 31.55555534362793, "blob_id": "4fde786d092572699b64e6c21833e5b84087a2be", "content_id": "06b33af107729f4be1686f18ffda9c18b15518a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 293, "license_type": "no_license", "max_line_length": 73, "num_lines": 9, "path": "/src/com/cburch/logisim/util/UnionFindElement.java", "repo_name": "JarrettBillingsley/logisim", "src_encoding": "UTF-8", "text": "/* Copyright (c) 2010, Carl Burch. License information is located in the\n * com.cburch.logisim.Main source code and at www.cburch.com/logisim/. */\n\npackage com.cburch.logisim.util;\n\npublic interface UnionFindElement<E> {\n\tpublic E getUnionFindParent();\n\tpublic void setUnionFindParent(E value);\n}\n" }, { "alpha_fraction": 0.6968525648117065, "alphanum_fraction": 0.7073439955711365, "avg_line_length": 31.92727279663086, "blob_id": "d1ecb2afd403f9813f7db0cc9aa9b431deec6bbf", "content_id": "180513c105e96479201b4334496945b6d0fd52e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1811, "license_type": "no_license", "max_line_length": 74, "num_lines": 55, "path": "/src/com/jfbillingsley/compiler/CompilerPoker.java", "repo_name": "JarrettBillingsley/logisim", "src_encoding": "UTF-8", "text": "package com.jfbillingsley.compiler;\n\nimport java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.event.KeyEvent;\nimport java.awt.event.MouseEvent;\n\nimport com.cburch.logisim.data.BitWidth;\nimport com.cburch.logisim.data.Bounds;\nimport com.cburch.logisim.data.Value;\nimport com.cburch.logisim.instance.InstancePainter;\nimport com.cburch.logisim.instance.InstancePoker;\nimport com.cburch.logisim.instance.InstanceState;\nimport com.cburch.logisim.instance.StdAttr;\n\npublic class CompilerPoker extends InstancePoker {\n\tpublic CompilerPoker() { }\n\n\t@Override\n\tpublic boolean init(InstanceState state, MouseEvent e) {\n\t\treturn state.getInstance().getBounds().contains(e.getX(), e.getY());\n\t}\n\n\t@Override\n\tpublic void paint(InstancePainter painter) {\n\t\tBounds bds = painter.getBounds();\n\t\t// BitWidth width = painter.getAttributeValue(StdAttr.WIDTH);\n\t\t// int len = (width.getWidth() + 3) / 4;\n\n\t\t// Graphics g = painter.getGraphics();\n\t\t// g.setColor(Color.RED);\n\t\t// int wid = 7 * len + 2; // width of caret rectangle\n\t\t// int ht = 16; // height of caret rectangle\n\t\t// g.drawRect(bds.getX() + (bds.getWidth() - wid) / 2,\n\t\t// \t\tbds.getY() + (bds.getHeight() - ht) / 2, wid, ht);\n\t\t// g.setColor(Color.BLACK);\n\n\t\tGraphics g = painter.getGraphics();\n\t\tg.setColor(Color.RED);\n\t\tg.drawRect(bds.getX() + 2, bds.getY() + 2, 10, 10);\n\t}\n\n\t@Override\n\tpublic void keyTyped(InstanceState state, KeyEvent e) {\n\t\t/*int val = Character.digit(e.getKeyChar(), 16);\n\t\tBitWidth width = state.getAttributeValue(StdAttr.WIDTH);\n\t\tif (val < 0 || (val & width.getMask()) != val) return;\n\n\t\tCompilerState cur = CompilerState.get(state, width);\n\t\tint newVal = (cur.getValue().toIntValue() * 16 + val) & width.getMask();\n\t\tValue newValue = Value.createKnown(width, newVal);\n\t\tcur.setValue(newValue);\n\t\tstate.fireInvalidated();*/\n\t}\n}\n" }, { "alpha_fraction": 0.7174796462059021, "alphanum_fraction": 0.7256097793579102, "avg_line_length": 17.185184478759766, "blob_id": "e45a5b27fc26dc37ac37eca22f7efeedda67b004", "content_id": "5637857059d503e03b797af96df7e142697bc32e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 492, "license_type": "no_license", "max_line_length": 41, "num_lines": 27, "path": "/src/com/jfbillingsley/compiler/Components.java", "repo_name": "JarrettBillingsley/logisim", "src_encoding": "UTF-8", "text": "package com.jfbillingsley.compiler;\n\nimport java.util.Arrays;\nimport java.util.List;\n\nimport com.cburch.logisim.tools.AddTool;\nimport com.cburch.logisim.tools.Library;\n\npublic class Components extends Library {\n\tprivate List<AddTool> tools;\n\n\tpublic Components() {\n\t\ttools = Arrays.asList(new AddTool[] {\n\t\t\tnew AddTool(new Compiler()),\n\t\t});\n\t}\n\n\t@Override\n\tpublic String getDisplayName() {\n\t\treturn \"CS0447 Compiler\";\n\t}\n\n\t@Override\n\tpublic List<AddTool> getTools() {\n\t\treturn tools;\n\t}\n}\n\n" }, { "alpha_fraction": 0.7480403184890747, "alphanum_fraction": 0.7525196075439453, "avg_line_length": 25.264705657958984, "blob_id": "8b332b793cd7e5b0cff6a8f20e1086f4b642144f", "content_id": "0407cec0e96dab0fa9c60da141866d6365806ede", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 893, "license_type": "no_license", "max_line_length": 73, "num_lines": 34, "path": "/src/com/cburch/logisim/gui/main/AttrTableToolModel.java", "repo_name": "JarrettBillingsley/logisim", "src_encoding": "UTF-8", "text": "/* Copyright (c) 2011, Carl Burch. License information is located in the\n * com.cburch.logisim.Main source code and at www.cburch.com/logisim/. */\n\npackage com.cburch.logisim.gui.main;\n\nimport com.cburch.logisim.data.Attribute;\nimport com.cburch.logisim.gui.generic.AttributeSetTableModel;\nimport com.cburch.logisim.proj.Project;\nimport com.cburch.logisim.tools.Tool;\n\npublic class AttrTableToolModel extends AttributeSetTableModel {\n\tProject proj;\n\tTool tool;\n\t\n\tpublic AttrTableToolModel(Project proj, Tool tool) {\n\t\tsuper(tool.getAttributeSet());\n\t\tthis.proj = proj;\n\t\tthis.tool = tool;\n\t}\n\t\n\t@Override\n\tpublic String getTitle() {\n\t\treturn Strings.get(\"toolAttrTitle\", tool.getDisplayName());\n\t}\n\t\n\tpublic Tool getTool() {\n\t\treturn tool;\n\t}\n\t\n\t@Override\n\tpublic void setValueRequested(Attribute<Object> attr, Object value) {\n\t\tproj.doAction(ToolAttributeAction.create(tool, attr, value));\n\t}\n}\n" }, { "alpha_fraction": 0.6392573118209839, "alphanum_fraction": 0.6476569175720215, "avg_line_length": 25.928571701049805, "blob_id": "64a69a52ec6ff02c9a552a017cab06a18c21b605", "content_id": "85f625ded47bf2bf9e06c118c0e343c62c4d2278", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2262, "license_type": "no_license", "max_line_length": 74, "num_lines": 84, "path": "/scripts/logisim_script.py", "repo_name": "JarrettBillingsley/logisim", "src_encoding": "UTF-8", "text": "import os.path\nimport platform\nimport re\nimport sys\n\ndef build_path(first, *subdirs, **kwargs):\n\tdir = first\n\tfor subdir in subdirs:\n\t\tfor subsub in subdir.split('/'):\n\t\t\tdir = os.path.join(dir, subsub)\n\tif 'cygwin' in kwargs and not kwargs['cygwin']:\n\t\treturn uncygwin(dir)\n\telse:\n\t\treturn dir\n\ndef get_svn_dir(*subdirs):\n\tscript_parent = os.path.dirname(sys.path[0])\n\treturn build_path(script_parent, *subdirs)\n\ndef uncygwin(path, verbose=False):\n\tsys = platform.system()\n\tif sys.startswith('CYGWIN'):\n\t\tif path.startswith('/cygdrive/'):\n\t\t\tpath = path[10].upper() + ':' + path[11:]\n\t\telif path.startswith('/'):\n\t\t\tpath = 'C:/cygwin' + path\n\t\treturn path\n\telse:\n\t\treturn path\n\ndef is_same_file(a, b):\n\tsamefile = getattr(os.path, 'samefile', None)\n\tif samefile is None:\n\t\ta_norm = os.path.normcase(os.path.abspath(a))\n\t\tb_norm = os.path.normcase(os.path.abspath(b))\n\t\treturn a_norm == b_norm\n\telse:\n\t\treturn samefile(a, b)\n\ndef system(*args):\n\treturn os.system(' '.join(args))\n\ndef prompt(prompt, accept=None):\n\twhile True:\n\t\tret = input(prompt + ' ')\n\t\tret = ret.rstrip()\n\t\tif accept is None or ret in accept:\n\t\t\treturn ret\n\ndef determine_version_info():\n\tversion = None\n\tversion_line = -1\n\tcopyright = None\n\tcopyright_line = -1\n\tmain_name = get_svn_dir('src/com/cburch/logisim/Logisim.java')\n\twith open(main_name) as main_file:\n\t\tversion_re = re.compile(r'.*VERSION = LogisimVersion.get\\(([0-9, ]*)\\)')\n\t\tyear_re = re.compile(r'COPYRIGHT_YEAR = ([0-9]+)')\n\t\tline_num = -1\n\t\tfor line in main_file:\n\t\t\tline_num += 1\n\t\t\tmat = version_re.search(line)\n\t\t\tif mat:\n\t\t\t\tif version_line < 0:\n\t\t\t\t\tversion = re.sub(r'\\s*,\\s*', '.', mat.group(1))\n\t\t\t\t\tversion_line = line_num\n\t\t\t\telse:\n\t\t\t\t\tsys.stderr.write('duplicate version on line '\n\t\t\t\t\t\t+ str(version_line) + ' and ' + str(line_num) + '\\n')\n\t\t\t\t\tversion = None\n\t\t\tmat = year_re.search(line)\n\t\t\tif mat:\n\t\t\t\tif copyright_line < 0:\n\t\t\t\t\tcopyright = mat.group(1)\n\t\t\t\t\tcopyright_line = line_num\n\t\t\t\telse:\n\t\t\t\t\tsys.stderr.write('duplicate copyright year on line '\n\t\t\t\t\t\t+ str(copyright_line) + ' and ' + str(line_num) + '\\n')\n\t\t\t\t\tcopyright = None\n\tif version_line < 0:\n\t\tsys.stderr.write('version number not found\\n')\n\tif copyright_line < 0:\n\t\tsys.stderr.write('copyright year not found\\n')\n\treturn version, copyright\n" }, { "alpha_fraction": 0.7555555701255798, "alphanum_fraction": 0.7555555701255798, "avg_line_length": 21.5, "blob_id": "d5dc178b1f2139c3327fe13c05f4d3ed3e5f51f8", "content_id": "2fb0bb25eaedffe758938db98af7c634a8ec1d69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 45, "license_type": "no_license", "max_line_length": 35, "num_lines": 2, "path": "/compile.sh", "repo_name": "JarrettBillingsley/logisim", "src_encoding": "UTF-8", "text": "#/bin/sh\npython scripts/create-jar.py -nojar\n" }, { "alpha_fraction": 0.6400628089904785, "alphanum_fraction": 0.6438571214675903, "avg_line_length": 30.200000762939453, "blob_id": "76fdd5155215bacf814b8192aae07ec6fffc8ec0", "content_id": "835ad3108ebdb3c530058269b238213614745c86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7644, "license_type": "no_license", "max_line_length": 85, "num_lines": 245, "path": "/scripts/doc2www.py", "repo_name": "JarrettBillingsley/logisim", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport os\nimport re\nimport shutil\nimport sys\nimport xml.dom\nimport xml.dom.minidom\nimport copy_doc\nfrom logisim_script import *\n\nsrc_dir = get_svn_dir('doc')\ndst_dir = os.getcwd()\n\n# see if we're on Carl Burch's platform, and if so reconfigure defaults\nif '\\\\home\\\\burch\\\\' in get_svn_dir():\n\tsvn_dir = get_svn_dir()\n\thome = svn_dir[:svn_dir.find('\\\\home\\\\burch\\\\') + 11]\n\tdst_dir = build_path(home, 'logisim/Scripts/www/docs')\n\nhead_end = r'''\n<link rel=\"shortcut icon\" href=\"{rel}/../../../logisim.ico\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{rel}/../docstyle.css\" />\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{rel}/../simpletree.css\" /> \n<script type=\"text/javascript\" src=\"{rel}/../simpletreemenu.js\">\n\n/***********************************************\n* Simple Tree Menu- © Dynamic Drive DHTML code library (www.dynamicdrive.com)\n* This notice MUST stay intact for legal use\n* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code\n***********************************************/\n\n// (from http://www.dynamicdrive.com/dynamicindex1/navigate1.htm)\n</script>\n'''.strip()\n\nbody_start = r'''\n<div id=\"content\">\n'''.strip()\n\nbody_end = r'''\n</div>\n\n<div id=\"map\">\n<a href=\"{langhome}/index.html\"><img src=\"{langhome}/header.png\"\n border=\"0\" width=\"227\" height=\"137\"></a>\n<ul id=\"maptree\" class=\"treeview\">\n{map}\n</ul>\n</div>\n<script type=\"text/javascript\"><!--\nddtreemenu.setPath('{rel}/..');\nddtreemenu.createTree(\"maptree\");\n// --></script>\n'''.strip()\n\n#\n# determine the source and destination directories\n#\nif not os.path.exists(src_dir):\n\tsys.exit('source directory doc/{lang} not found, aborted'.format(lang=lang))\nif not os.path.exists(dst_dir):\n\tsys.exit('destination directory not found, aborted')\nif is_same_file(dst_dir, src_dir) or os.path.exists(os.path.join(dst_dir, 'doc.hs')):\n\tsys.exit('cannot place result into source directory')\n\n#\n# deal with replacing files\n#\nreplace_all = 0 # 0 unknown, 1 yes to all, -1 no to all\ndef confirm_replace(filename):\n\tglobal replace_all\n\tif replace_all == 0:\n\t\tprint('{file} already exists.'.format(file=filename))\n\t\toptions = '[y]es, [Y]es to all, [n]o, [N]o to all, [a]bort'\n\t\tdispose = prompt('Replace (' + options + ')?', 'yYnNa')\n\t\tif dispose == 'y':\n\t\t\treturn True\n\t\telif dispose == 'Y':\n\t\t\treplace_all = 1\n\t\t\treturn True\n\t\telif dispose == 'n':\n\t\t\treturn False\n\t\telif dispose == 'N':\n\t\t\treplace_all = -1\n\t\t\treturn False\n\t\telif dispose == 'a':\n\t\t\tsys.exit('aborted on user request')\n\telse:\n\t\treturn replace_all >= 0\n\n# create the support directory\nsupport_src = build_path(src_dir, 'support/www')\nsupport_dst = dst_dir\nif not os.path.exists(support_dst):\n\tos.mkdir(support_dst)\nfor file in os.listdir(support_src):\n\tif file != '.svn':\n\t\tfile_dst = build_path(support_dst, file)\n\t\tif os.path.exists(file_dst):\n\t\t\tos.remove(file_dst)\n\t\tshutil.copy(build_path(support_src, file), file_dst)\n\n# create the directory for each locale\nfor locale in copy_doc.get_doc_locales(src_dir):\n\tlocale_src = build_path(src_dir, locale)\n\tlocale_dst = build_path(dst_dir, locale)\n\tif not os.path.exists(locale_dst):\n\t\tos.mkdir(locale_dst)\n\t\t\t\n\t# determine how targets correspond to URLs\n\tmap_target = {}\n\tmap_url = {}\n\tclass MapNode():\n\t\tdef __init__(self, target, url):\n\t\t\tself.target = target\n\t\t\tself.url = url\n\t\n\tmap_text = copy_doc.get_map(locale, src_dir)\n\tmap_dom = xml.dom.minidom.parseString(map_text)\n\tfor mapid in map_dom.getElementsByTagName('mapID'):\n\t\tif not mapid.hasAttribute('target') or not mapid.hasAttribute('url'):\n\t\t\tprint('node is missing target or url attribute, ignored')\n\t\t\tcontinue\n\t\ttarget = mapid.getAttribute('target')\n\t\turl = mapid.getAttribute('url')\n\t\tnode = MapNode(target, url)\n\t\tmap_target[target] = node\n\t\tmap_url[url] = node\n\tmap_dom = None\n\t\n\t# determine the table of contents\n\ttoc_nodes = []\n\tdef walk_contents(node, ancestors):\n\t\tret = []\n\t\tfor child in node.childNodes:\n\t\t\tif getattr(child, 'tagName', '-') != 'tocitem':\n\t\t\t\tret.extend(walk_contents(child, ancestors))\n\t\t\telif not child.hasAttribute('target'):\n\t\t\t\tprint('contents.xml: node is missing target')\n\t\t\t\tret.extend(walk_contents(child, ancestors))\n\t\t\telif child.getAttribute('target') not in map_target:\n\t\t\t\tprint('contents.xml: unknown target ' + target)\n\t\t\t\tret.extend(walk_contents(child, ancestors))\n\t\t\telse:\n\t\t\t\ttarget = child.getAttribute('target')\n\t\t\t\tmap_node = map_target[target]\n\t\t\t\tmap_node.ancestors = ancestors\n\t\t\t\tmap_node.text = child.getAttribute('text')\n\t\t\t\ttoc_nodes.append(map_node)\n\t\t\t\tret.append(map_node)\n\t\t\t\tmap_node.children = walk_contents(child, (map_node, ) + ancestors)\n\t\treturn ret\n\tcontents_text = copy_doc.get_contents(locale, src_dir)\n\tcontents_dom = xml.dom.minidom.parseString(contents_text)\n\twalk_contents(contents_dom.documentElement, ())\n\n\t# create function for creating contents section corresponding to a filename\n\tdef create_map(filename):\n\t\tdst_filename = os.path.join(dst_dir, filename)\n\t\turl = filename.replace('\\\\', '/')\n\t\tif url in map_url:\n\t\t\tancestors = getattr(map_url[url], 'ancestors', ())\n\t\telse:\n\t\t\tancestors = ()\n\t\tmap_lines = []\n\t\tcur_depth = 1\n\t\tfor node in toc_nodes:\n\t\t\tdepth = len(node.ancestors)\n\t\t\tif depth == 0: # ignore the root node\n\t\t\t\tcontinue\n\t\t\t\n\t\t\twhile cur_depth > depth:\n\t\t\t\tcur_depth -= 1\n\t\t\t\tmap_lines.append(' ' * cur_depth + '</ul></li>')\n\t\t\t\n\t\t\tif node.url == url:\n\t\t\t\ttext_fmt = '<b{text_clss}>{text}</b>'\n\t\t\telse:\n\t\t\t\ttext_fmt = '<a href=\"{arel}\"{text_clss}>{text}</a>'\n\t\t\tnode_filename = os.path.join(dst_dir, node.url)\n\t\t\tarel = os.path.relpath(node_filename, os.path.dirname(dst_filename))\n\t\t\tarel = arel.replace('\\\\', '/')\n\t\t\tif node in ancestors or node.url == url:\n\t\t\t\ttext_clss = ' class=\"onpath\"'\n\t\t\telse:\n\t\t\t\ttext_clss = ' class=\"offpath\"'\n\t\t\tentry = text_fmt.format(arel=arel, text_clss=text_clss, text=node.text)\n\t\t\tif len(node.children) == 0:\n\t\t\t\tmap_lines.append(' ' * cur_depth + '<li>' + entry + '</li>')\n\t\t\telse:\n\t\t\t\tif node in ancestors or node.url == url:\n\t\t\t\t\tul = '<ul rel=\"open\">'\n\t\t\t\telse:\n\t\t\t\t\tul = '<ul>'\n\t\t\t\tmap_lines.append(' ' * cur_depth + '<li>' + entry + ul)\n\t\t\t\tcur_depth += 1\n\t\twhile cur_depth > 1:\n\t\t\tcur_depth -= 1\n\t\t\tmap_lines.append(' ' * cur_depth + '</ul></li>')\n\t\treturn '\\n'.join(map_lines)\n\t\t\t\n\t# create function for translating HTML in source file to HTML in destination\n\tre_body_start = re.compile('<body[^>]*>')\n\tre_path_dir = re.compile('[^/]*/')\n\tdef wrap_html(html_text, rel_filename):\n\t\tmap = create_map(locale + '/' + rel_filename)\n\t\trel_base = re_path_dir.sub('../', rel_filename)\n\t\tslash = rel_base.rfind('/')\n\t\tif slash >= 0:\n\t\t\trel_base = rel_base[:slash]\n\t\t\n\t\tif locale == 'en':\n\t\t\tlanghome = rel_base + '/../../..'\n\t\telse:\n\t\t\tlanghome = rel_base + '/../../../' + locale\n\n\t\ttext = html_text\n\t\thead_end_pos = text.find('</head>')\n\t\tif head_end_pos >= 0:\n\t\t\tto_head = head_end.format(rel=rel_base, lang=locale)\n\t\t\ttext = text[:head_end_pos] + to_head + '\\n' + text[head_end_pos:]\n\t\t\t\n\t\tbody_start_match = re_body_start.search(text)\n\t\tif body_start_match:\n\t\t\tbody_start_pos = body_start_match.end()\n\t\t\t\n\t\t\tto_body = body_start.format(rel=rel_base, map=map, lang=locale,\n\t\t\t\tlanghome=langhome)\n\t\t\ttext = text[:body_start_pos] + '\\n' + to_body + text[body_start_pos:]\n\t\t\t\n\t\tbody_end_pos = text.find('</body>')\n\t\tif body_end_pos >= 0:\n\t\t\tto_body = body_end.format(rel=rel_base, map=map, lang=locale,\n\t\t\t\tlanghome=langhome)\n\t\t\ttext = text[:body_end_pos] + to_body + '\\n' + text[body_end_pos:]\n\t\t\t\n\t\treturn text\n\t\n\t# copy the files over\n\tprint('creating files [' + locale + ']')\n\tcopy_doc.copy_files(locale, src_dir, dst_dir, translate_html=wrap_html,\n\t\t\t\t\tconfirm_replace=confirm_replace)\n\t\nprint('file generation complete')" }, { "alpha_fraction": 0.6728248000144958, "alphanum_fraction": 0.6758045554161072, "avg_line_length": 31.58576011657715, "blob_id": "48a67f2b978d093b38fa640957156a82d3e6dc7a", "content_id": "7ab90d90ca414fe7db354702e273fe1bf253cf75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10068, "license_type": "no_license", "max_line_length": 81, "num_lines": 309, "path": "/scripts/create-jar.py", "repo_name": "JarrettBillingsley/logisim", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nimport os\nimport platform\nimport sys\nimport shutil\nimport time\nimport copy_doc\nfrom logisim_script import *\n\nsrc_dir = get_svn_dir('src')\ndoc_dir = get_svn_dir('doc')\nlibs_dir = get_svn_dir('libs')\ndata_dir = get_svn_dir('scripts/data')\ndest_dir = os.getcwd()\ncreate_jar_start_time = time.time()\n\n# configure defaults\ninclude_source = True\ninclude_documentation = True\nbin_dir = None\ndest_dir = os.getcwd()\ntemp_dir = None\nkeep_temp = False\njdk_dir = None\nmake_jar = True\n\n# see if we're on Carl Burch's platform, and if so reconfigure defaults\nif '\\\\home\\\\burch\\\\' in get_svn_dir():\n\tsvn_dir = get_svn_dir()\n\thome = svn_dir[:svn_dir.find('\\\\home\\\\burch\\\\') + 11]\n\tbin_dir = build_path(home, 'logisim/TrunkSource/bin')\n\tdest_dir = build_path(home, 'logisim/Scripts')\n\tkeep_temp = False\n\nusage = '''usage: create-jar ARGS\narguments:\n -bin DIR compiled files are already present in DIR\n -d DIR place created JAR file in DIR\n -j DIR directory for JDK binaries (for java, javac, jar)\n -keep keep temporary directory after completion\n -nodoc omit documentation from created JAR file\n -nosrc omit source code from created JAR file\n -temp DIR use DIR as the temporary directory\n -nojar makes a 'build' directory in the destination dir,\n compiles into it, and does not create a jar.\n overrides -keep, -temp, and -bin; implies -nodoc and -nosrc.\n'''.rstrip()\n\nargi = 0\nprint_usage = False\nwhile argi + 1 < len(sys.argv):\n\targi += 1\n\targ = sys.argv[argi]\n\tif arg == '-bin' and argi + 1 < len(sys.argv):\n\t\targi += 1\n\t\tbin_dir = sys.argv[argi]\n\telif arg == '-d' and argi + 1 < len(sys.argv):\n\t\targi += 1\n\t\tdest_dir = os.path.abspath(sys.argv[argi])\n\telif arg == '-j' and argi + 1 < len(sys.argv):\n\t\targi += 1\n\t\tjdk_dir = sys.argv[argi]\n\telif arg == '-keep':\n\t\tkeep_temp = True\n\telif arg == '-nodoc':\n\t\tinclude_documentation = False\n\telif arg == '-nosrc':\n\t\tinclude_source = False\n\telif arg == '-nojar':\n\t\tmake_jar = False\n\t\tinclude_documentation = False\n\t\tinclude_source = False\n\telif arg == '-temp' and argi + 1 < len(sys.argv):\n\t\targi += 1\n\t\ttemp_dir = sys.argv[argi]\n\telse:\n\t\tprint_usage = True\nif print_usage:\n\tsys.exit(usage)\n\nif not make_jar:\n\tbin_dir = None\n\nif bin_dir is not None and not os.path.exists(bin_dir):\n\tsys.exit('binary directory ' + bin_dir + ' does not exist')\nif not os.path.exists(dest_dir):\n\tsys.exit('destination directory ' + dest_dir + ' does not exist')\nif temp_dir is not None and not os.path.exists(os.path.dirname(temp_dir)):\n\tsys.exit('temporary directory\\'s parent ' + os.path.dirname(temp_dir)\n\t\t\t+ ' does not exist')\nif jdk_dir is None:\n\tjar_exec = 'jar'\n\tjava_exec = 'java'\n\tjavac_exec = 'javac'\nelif os.path.exists(jdk_dir):\n\tfor file in ['jar', 'java', 'javac']:\n\t\tfile_path = build_path(jdk_dir, 'bin', file)\n\t\tif not os.path.exists(file_path):\n\t\t\tfile_path += '.exe' # see if it exists with .exe extension\n\t\t\tif not os.path.exists(file_path):\n\t\t\t\tsys.exit('could not find \\'' + file + '\\' executable in JDK '\n\t\t\t\t\t\t+ 'directory ' + jdk_dir)\n\t\tfile_path = '\"' + uncygwin(file_path) + '\"'\n\t\tif file == 'jar': jar_exec = file_path\n\t\telif file == 'java': java_exec = file_path\n\t\telse: javac_exec = file_path\nelse:\n\tsys.exit('JDK directory ' + jdk_dir + ' does not exist')\n\n#\n# Determine the version number and copyright year\n#\nversion, copyright = determine_version_info()\nif version is None or copyright is None:\n\tsys.exit(-1)\nprint('version ' + version + ', (c) ' + copyright)\n\nif make_jar and bin_dir is None:\n\tprint('warning: no \"-bin\" argument provided - will have to compile all sources')\n\n#\n# prepare the temporary directory to be completely empty\n#\nif not make_jar:\n\ttemp_dir = os.path.join(dest_dir, 'build')\n\tif os.path.exists(temp_dir):\n\t\tshutil.rmtree(temp_dir)\nelif temp_dir is None:\n\tcurrent = os.listdir(dest_dir)\n\tfor i in range(1, 11):\n\t\tname = 'files' if i == 1 else 'files' + str(i)\n\t\tif name not in current:\n\t\t\ttemp_dir = os.path.join(dest_dir, name)\n\t\t\tbreak\n\tif temp_dir is None:\n\t\tsys.exit('all default temporary directories (files* in ' + dest_dir\n\t\t\t\t+ ') already exist, please clean')\n\tprint('using temporary directory ' + temp_dir)\nelif os.path.exists(temp_dir):\n\tprint('Temporary directory ' + temp_dir + ' already exists.')\n\tuser = prompt('Do you want to replace it ([y]es, [n]o)?', 'yn')\n\tif user == 'n':\n\t\tsys.exit()\n\tshutil.rmtree(temp_dir)\nos.mkdir(temp_dir)\n\n# from here to the end, any fatal errors should first delete the temporary\n# directory - we set this up so this happens automatically\nold_sys_exit = sys.exit\ndef fatal_error(msg=None):\n\tif not keep_temp and not make_jar:\n\t\tos.chdir(dest_dir)\n\t\tshutil.rmtree(temp_dir)\n\tif msg is None:\n\t\told_sys_exit(-1)\n\telse:\n\t\told_sys_exit(msg)\nsys.exit = fatal_error\n\n# set things up so dot-files are excluded when copying directories\ndef copytree(src_dir, dst_dir, ignore=None):\n\tdef ignore_hidden(dir, files):\n\t\tret = [] if ignore is None else ignore(dir, files)\n\t\tret.extend([f for f in files if f.startswith('.') and f not in ret])\n\t\treturn ret\n\tshutil.copytree(src_dir, dst_dir, ignore=ignore_hidden)\n\n#\n# copy the binary directory if provided\n#\n# first determine which JAR files we're using\njar_files = [f for f in os.listdir(libs_dir) if f.endswith('.jar')]\n# now get the .class files\nif bin_dir is None:\n\tprint('compiling .class files - this may take a full minute')\n\tclasspath = []\n\tfor jar_file in jar_files:\n\t\tclasspath.append(build_path(libs_dir, jar_file, cygwin=False))\n\tsyst = platform.system().upper()\n\tif syst.startswith(\"CYGWIN\"):\n\t\tclasspath = '\"' + ';'.join(classpath) + '\"'\n\telif syst.startswith('WINDOWS'):\n\t\tclasspath = ';'.join(classpath)\n\telse:\n\t\tclasspath = ':'.join(classpath)\n\tos.chdir(src_dir)\n\tjava_files_path = build_path(temp_dir, 'source_files')\n\n\tprint(\"PATH:\", java_files_path)\n\n\twith open(java_files_path, 'w') as java_files:\n\t\tfor path, dirs, files in os.walk('.'):\n\t\t\tif '.svn' in dirs:\n\t\t\t\tdirs.remove('.svn')\n\t\t\tfor file in files:\n\t\t\t\tif file.endswith('.java'):\n\t\t\t\t\tif path.startswith(src_dir):\n\t\t\t\t\t\tfile_path = build_path(path[len(src_dir) + 1:], file)\n\t\t\t\t\telse:\n\t\t\t\t\t\tfile_path = build_path(path, file)\n\t\t\t\t\tjava_files.write(uncygwin(file_path) + '\\n')\n\tjavac_args = [javac_exec, '-Xlint:-options', '--release', '10',\n\t\t\t\t'-d', uncygwin(temp_dir), '-classpath', classpath,\n\t\t\t\t'@' + uncygwin(java_files_path, verbose=True)]\n\tbefore_compile = time.time()\n\texit_code = system(*javac_args)\n\telapse = format(time.time() - before_compile, '.1f')\n\tprint(' (' + elapse + 's elapsed during compile)')\n\tos.remove(java_files_path)\n\tif exit_code != 0:\n\t\tfatal_error('error during compilation, JAR creation script aborted')\nelse:\n\tprint('copying .class files')\n\tcopytree(build_path(bin_dir, 'com'), build_path(temp_dir, 'com'))\n\n#\n# unpack all the JARs being used\n#\nprint('unpacking JAR libraries')\nos.chdir(temp_dir)\n# if not include_documentation and 'jh.jar' in jar_files:\n\t# jar_files.remove('jh.jar')\nfor jar_file in jar_files:\n\tsystem(jar_exec, 'fx', build_path(libs_dir, jar_file, cygwin=False))\n# remove any directories from JARs that will be used for Logisim's purposes\nfor exclude in ['src', 'resources', 'META-INF', 'COPYING.TXT']:\n\tif os.path.exists(build_path(temp_dir, exclude)):\n\t\tshutil.rmtree(build_path(temp_dir, exclude))\n\n\n#\n# create the resources, src, and documentation directories\n#\nprint('copying resources')\ncopytree(build_path(src_dir, 'resources'), build_path(temp_dir, 'resources'))\n\nif include_source:\n\tprint('copying source code')\n\tos.mkdir(build_path(temp_dir, 'src'))\n\tcopytree(build_path(src_dir, 'com'), build_path(temp_dir, 'src/com'))\n\nif include_documentation:\n\tprint('copying documentation')\n\tdoc_dst = build_path(temp_dir, 'doc')\n\tcopy_doc.copy_files_all_locales(doc_dir, doc_dst)\n\tcopy_doc.build_contents(doc_dir, doc_dst)\n\tcopy_doc.build_map(doc_dir, doc_dst)\n\tcopy_doc.build_helpset(doc_dir, doc_dst)\n\n\tjhindexer = build_path(data_dir, 'javahelp/bin/jhindexer.jar', cygwin=False)\n\tos.chdir(doc_dst)\n\tfor locale in os.listdir(doc_dst):\n\t\tlocale_dst = build_path(doc_dst, locale)\n\t\tif os.path.isdir(locale_dst):\n\t\t\tcmd_args = [java_exec, '-jar', jhindexer]\n\t\t\tif os.path.exists('jhindexer.cfg'):\n\t\t\t\tcmd_args.extend(['-c', 'jhindexer.cfg'])\n\t\t\tcmd_args.extend(['-db', 'search_lookup_' + locale])\n\t\t\tcmd_args.extend(['-locale', locale])\n\t\t\tfound = False\n\t\t\tfor sub in [locale + '/html/guide', locale + '/html/libs']:\n\t\t\t\tif os.path.exists(build_path(doc_dst, sub)):\n\t\t\t\t\tcmd_args.append(sub)\n\t\t\t\t\tfound = True\n\t\t\tif found:\n\t\t\t\tprint('indexing documentation [' + locale + ']')\n\t\t\t\tsystem(*cmd_args)\n\n#\n# copy in the .class files that were compiled under MacOS\n#\nprint('adding MacOS support')\nmacos_dir = build_path(data_dir, 'macos-classes')\nfor macos_file in os.listdir(macos_dir):\n\tif macos_file.endswith('.class'):\n\t\tmacos_dst = build_path(temp_dir, 'com/cburch/logisim/gui/start', macos_file)\n\t\tshutil.copyfile(build_path(macos_dir, macos_file), macos_dst)\n\n#\n# insert GPL, create manifest\n#\n\nif not make_jar:\n\tprint('done.')\nelse:\n\tprint('creating JAR file')\n\t# include COPYING.TXT and manifest\n\tshutil.copyfile(build_path(data_dir, 'COPYING.TXT'),\n\t\t\t\tbuild_path(temp_dir, 'COPYING.TXT'))\n\tos.mkdir(build_path(temp_dir, 'META-INF'))\n\twith open(build_path(temp_dir, 'META-INF/MANIFEST.MF'), 'w') as manifest:\n\t\tmanifest.write('Main-Class: com.cburch.logisim.Logisim\\n')\n\t# and now create the JAR\n\tos.chdir(temp_dir)\n\tfiles_to_include = os.listdir('.')\n\tfiles_to_include.remove('META-INF')\n\tjar_filename = 'logisim-fragile-' + version + '.jar'\n\tjar_pathname = build_path(dest_dir, jar_filename, cygwin=False)\n\tsystem(jar_exec, 'fcm', jar_pathname, 'META-INF/MANIFEST.MF', *files_to_include)\n\n\tos.chdir(dest_dir)\n\tif not keep_temp:\n\t\tprint('deleting temporary directory')\n\t\tshutil.rmtree(temp_dir)\n\tsize = str(int(round(os.path.getsize(jar_pathname) / 1024.0)))\n\telapse = format(time.time() - create_jar_start_time, '.1f')\n\tsummary = 'JAR file created! (name: {name}, size: {size}KB, elapsed: {elapse}s)'\n\tprint(summary.format(name=jar_filename, size=str(size), elapse=elapse))" }, { "alpha_fraction": 0.7581227421760559, "alphanum_fraction": 0.7595667839050293, "avg_line_length": 62, "blob_id": "65af5583b2c2338668000ffc3132879f17010daa", "content_id": "e78c7460d5ff4f0c822c3411221648a1c1a4edfa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1385, "license_type": "no_license", "max_line_length": 124, "num_lines": 22, "path": "/README.md", "repo_name": "JarrettBillingsley/logisim", "src_encoding": "UTF-8", "text": "List of things I've changed or fixed:\n\n- **Backwards-compatible changes:**\n\t- Tunnels will appear \"ghosted\" if they have no partners (unconnected to anything).\n\t- Tunnels can be color-coded.\n\t- Plexers default to NOT having an enable input.\n\t- Multi-bit wires with unknown values now display blue, instead of black.\n\t- Duplicate/paste put the copied components at the mouse cursor, where they can be placed wherever the user wants.\n\t- Displays Logisim icon in taskbar on modern OSes.\n\t- Now clearer when you are viewing an embedded subcircuit's state vs. the subcircuit's prototype.\n\t- Added an icon in the toolbar that shows whether simulation is enabled (green triangle) or not (red square).\n- **Non-backwards-compatible changes:**\n\t- Gates default to narrow with 2 inputs. (Sometimes this breaks old circuits)\n\t- No more asynchronous 0 clear on registers.\n- **Bugfixes**:\n\t- When duplicated, tunnels no longer stack up on themselves (they are offset like everything else).\n\t- Using arrow keys/home/end when editing labels no longer scrolls the circuit view.\n- **Mac-specific bugfixes:**\n\t- Exits when closing last window.\n\t- Confirms save on exit, as Logisim was using an old method of detecting that which breaks on newer versions of macOS/Java.\n\t- Fixed Cmd+K/Cmd+E shortcuts (they were being run twice due to a bug in Swing).\n\t- Title now displays as \"Logisim\" instead of \"Main\"." } ]
19
fmeirinhos/VergoldeMich
https://github.com/fmeirinhos/VergoldeMich
e512e0a970aa913f614bd53c656fae32c3d6e1b3
69fd9f629bccfd2de8b74c9939755ece8135417a
ba62d947556393775fbf9351c32eaded86ae8782
refs/heads/master
2020-03-16T19:27:15.266599
2019-05-29T17:36:00
2019-05-29T17:36:00
132,916,819
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6227847933769226, "alphanum_fraction": 0.6303797364234924, "avg_line_length": 16.954545974731445, "blob_id": "aa1c9e86c3d45d0844c6df52fa390465772b7136", "content_id": "3d7737bd1aeab04ff4fefdff5372d1df719476f2", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 395, "license_type": "permissive", "max_line_length": 25, "num_lines": 22, "path": "/vergoldemich/strategies/signal.py", "repo_name": "fmeirinhos/VergoldeMich", "src_encoding": "UTF-8", "text": "(\n SIGNAL_NONE,\n SIGNAL_LONGSHORT,\n SIGNAL_LONG,\n SIGNAL_LONG_INV,\n SIGNAL_LONG_ANY,\n SIGNAL_SHORT,\n SIGNAL_SHORT_INV,\n SIGNAL_SHORT_ANY,\n SIGNAL_LONGEXIT,\n SIGNAL_LONGEXIT_INV,\n SIGNAL_LONGEXIT_ANY,\n SIGNAL_SHORTEXIT,\n SIGNAL_SHORTEXIT_INV,\n SIGNAL_SHORTEXIT_ANY,\n) = range(14)\n\n(\n POSITION_NONE,\n POSITION_SHORT,\n POSITION_LONG,\n) = range(3)\n" }, { "alpha_fraction": 0.7358490824699402, "alphanum_fraction": 0.7358490824699402, "avg_line_length": 16.66666603088379, "blob_id": "bd4b665fc6415d7af7f43d5f021f5f822cb7df75", "content_id": "1e5c1cb6976e157ded173b16f01eec0c679305df", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 53, "license_type": "permissive", "max_line_length": 35, "num_lines": 3, "path": "/tools/local_script.sh", "repo_name": "fmeirinhos/VergoldeMich", "src_encoding": "UTF-8", "text": "#!/usr/bin/bash\n\nsource ~/catalyst-venv/bin/activate\n" }, { "alpha_fraction": 0.7317073345184326, "alphanum_fraction": 0.7479674816131592, "avg_line_length": 19.5, "blob_id": "f1ceced7943ae448910f2159fa60e8b4b5491d7e", "content_id": "772acfb9bb38843024f0add22e62d0ea024e4a75", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 123, "license_type": "permissive", "max_line_length": 47, "num_lines": 6, "path": "/README.md", "repo_name": "fmeirinhos/VergoldeMich", "src_encoding": "UTF-8", "text": "# VergoldeMich\n\n## Important websites:\n\n1. https://www.quantopian.com/help\n2. https://enigma.co/catalyst/live-trading.html\n" }, { "alpha_fraction": 0.5785645246505737, "alphanum_fraction": 0.5790494680404663, "avg_line_length": 25.10126495361328, "blob_id": "4dd9c5b079c2aaea33769fb5011a6b72c6f68a96", "content_id": "c3a4cbb7fef55f30f8f07bb9314f560979b72c14", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2062, "license_type": "permissive", "max_line_length": 98, "num_lines": 79, "path": "/vergoldemich/broker.py", "repo_name": "fmeirinhos/VergoldeMich", "src_encoding": "UTF-8", "text": "import logbook\nfrom datetime import timedelta\n\nfrom catalyst.api import (\n schedule_function,\n record\n)\n\n\nclass Broker(object):\n \"\"\"\n Defines the trading strategies and exchange pairs\n\n Attributes\n agents (dict) The crypto currency agents\n \"\"\"\n\n def __init__(self):\n self.agents = {}\n\n self.logger = logbook.Logger(self.__class__.__name__)\n self.logger.info(\"initialized. \\n\\n++++ Get rich or die tryin ++++\\n\")\n\n def add_agent(self, agent):\n \"\"\"\n Adds a currency agent\n\n Arguments:\n agent (Agent) The crypto currency agent\n \"\"\"\n self.agents[agent.market] = agent\n self.logger.info(str(agent) + ' added')\n\n def initialize(self, context):\n \"\"\"\n Initialize is a required setup method for initializing state or \n other bookkeeping. This method is called only once at the beginning of \n your algorithm.\n\n Arguments:\n context (dict) Used for maintaining state during your backtest or live trading session\n \"\"\"\n\n # schedule_function here\n pass\n\n def handle_data(self, context, data):\n \"\"\"\n You should only use handle_data for things you really need to happen every minute\n\n Arguments:\n context (dict) Used for maintaining state during your backtest or live trading session\n \"\"\"\n\n # self.logger.info(\"Trading at {}\".format(data.current_dt))\n\n # try:\n self._handle_data(context, data)\n\n # except Exception as e:\n # self.logger.warn('ABORTING the frame on error {}'.format(e))\n # context.errors.append(e)\n\n # if len(context.errors) > 0:\n # self.logger.info('The errors:\\n{}'.format(context.errors))\n\n def _handle_data(self, context, data):\n \"\"\"\n\n Arguments:\n context ()\n data ()\n \"\"\"\n for market, agent in self.agents.items():\n agent.trade(context, data)\n\n record(\n cash=context.portfolio.cash\n )\n" }, { "alpha_fraction": 0.7485380172729492, "alphanum_fraction": 0.7485380172729492, "avg_line_length": 23.428571701049805, "blob_id": "e9c90a3fedfe05c22be8ace76249dfd3fa08a514", "content_id": "4b1a3c9cd4cfb79aca77d2caa0a0b35ae39565aa", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 171, "license_type": "permissive", "max_line_length": 36, "num_lines": 7, "path": "/vergoldemich/__init__.py", "repo_name": "fmeirinhos/VergoldeMich", "src_encoding": "UTF-8", "text": "from .broker import *\nfrom .agent import *\nfrom .plotter import *\n\nfrom .strategies.rsi_fawner import *\nfrom .strategies.adx_di import *\nfrom .strategies.adx_rsi import *\n" }, { "alpha_fraction": 0.554246723651886, "alphanum_fraction": 0.5688158869743347, "avg_line_length": 28.327272415161133, "blob_id": "c80b3262bad6ce9bd00143525cfc9dcd4b2065bc", "content_id": "f3106ece9e14566cbc9d4001ca6c9d984c4bbad3", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3226, "license_type": "permissive", "max_line_length": 74, "num_lines": 110, "path": "/vergoldemich/strategies/rsi_fawner.py", "repo_name": "fmeirinhos/VergoldeMich", "src_encoding": "UTF-8", "text": "from .signal import *\nfrom .strategy import *\n\nimport talib\n\n\nclass RSI_BB_Fawner(Strategy):\n \"\"\"\n Basic strategy solely based on following RSI.\n\n The Relative Strength Index is a useful indicator for determining when\n prices over overbought or oversold.\n RSI measures the velocity and magnitude of directional price moves and\n represents the data graphically by oscillating between 0 and 100.\n [source: Investopedia]\n \"\"\"\n\n params = dict(\n RSIlength=16,\n RSIoversold=30,\n RSIoverbought=70,\n RSICandle='5T',\n\n BBlength=20,\n BBsa=2\n )\n\n def __init__(self, **kwargs):\n \"\"\"\n Keyword Args:\n RSIlength (int) RSI period Length\n RSIoversold (int) RSI oversold threshold\n RSIoverbought (int) RSI overbought threshold\n RSICandle (str) RSI candle size\n\n BBlength (int) BB SMA period Length\n BBsa (int) BB standard deviation\n \"\"\"\n super(RSI_BB_Fawner, self).__init__(**kwargs)\n\n def check(self):\n \"\"\"\n Sanity checks for the strategy\n \"\"\"\n if self.p.RSIoverbought is None:\n self.p.RSIoverbought = 100 - self.p.RSIoversold\n\n if self.p.BBsa < 0.001 or self.p.BBsa > 50:\n self.logger.error(\"Bollinger Bands Standard Deviation not OK\")\n\n def eval(self, market, context, data):\n # Fetch market history\n try:\n prices = data.history(\n market,\n fields='price',\n bar_count=200,\n frequency=self.p.RSICandle\n )\n\n except Exception as e:\n self.logger.warn('historical data not available: '.format(e))\n return\n\n return self.signal(prices)\n\n def signal(self, prices):\n\n rsi = talib.RSI(prices.values, timeperiod=self.p.RSIlength)\n\n bb_upper, middleband, bb_lower = talib.BBANDS(\n prices.values, timeperiod=self.p.BBlength,\n nbdevup=self.p.BBsa, nbdevdn=self.p.BBsa, matype=0)\n\n # Record everything useful to analyze later\n record(\n rsi=rsi[-1],\n bb_upper=bb_upper[-1],\n bb_lower=bb_lower[-1]\n )\n\n close = data.current(market, 'close')\n\n if rsi[-1] <= self.p.RSIoversold and close <= bb_lower[-1]:\n arg = 'RSI at {:.3f}'.format(rsi[-1])\n return SIGNAL_LONG, arg\n\n elif rsi[-1] >= self.p.RSIoverbought and close >= bb_upper[-1]:\n arg = 'RSI at {:.3f}'.format(rsi[-1])\n return SIGNAL_SHORT, arg\n\n return SIGNAL_NONE, ''\n\n def plot(self, ax, chart):\n \"\"\"\n Plots the data calculated for the strategy\n \"\"\"\n\n self.get_data(chart)\n\n t = chart['Time'].values\n bbupper = self.sma.add(self.bbdev).values\n bblower = self.sma.subtract(self.bbdev).values\n\n ax.plot(t, self.sma.values, c='grey', label='BB SMA', lw=0.75)\n ax.plot(t, bbupper, c='grey', label='BB Upper', lw=0.5)\n ax.plot(t, bblower, c='grey', label='BB Lower', lw=0.5)\n\n # ax.fill_between(t, bblower, bblower, where=bbupper >\n # bbupper, facecolor='black', alpha=0.3, interpolate=True)\n" }, { "alpha_fraction": 0.5713750720024109, "alphanum_fraction": 0.5792431831359863, "avg_line_length": 31.156625747680664, "blob_id": "f42dbba0629dd033dde9def58a128d766692c71f", "content_id": "5258e66e04638d8ecda21b27bacdc18dbf1adcce", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2671, "license_type": "permissive", "max_line_length": 77, "num_lines": 83, "path": "/vergoldemich/strategies/stop_loss.py", "repo_name": "fmeirinhos/VergoldeMich", "src_encoding": "UTF-8", "text": "from .signal import *\nfrom .strategy import *\n\nimport logbook\n\n\nclass StopLoss(Strategy):\n \"\"\"\n A stop-loss order is an order placed with a broker to sell a security\n when it reaches a certain price. Stop loss orders are designed to\n limit an investor’s loss on a position in a security. Although most\n investors associate a stop-loss order with a long position, it can also\n protect a short position, in which case the security gets bought if it\n trades above a defined price.\n\n Source:\n https://www.investopedia.com/terms/s/stop-lossorder.asp\n https://www.investopedia.com/terms/t/trailingstop.asp\n \"\"\"\n params = dict(\n shrt_target_profit=0.11,\n shrt_stop_loss=0.04,\n\n long_target_profit=0.1,\n long_stop_loss=0.05,\n\n trail=False,\n )\n\n def __init__(self, **kwargs):\n \"\"\"\n Keyword Args:\n shrt_target_profit (float)\n shrt_stop_loss (float)\n\n long_target_profit (float)\n long_stop_loss (float)\n \"\"\"\n super(StopLoss, self).__init__(**kwargs)\n\n def check(self):\n \"\"\"\n Sanity checks for the strategy\n \"\"\"\n if self.p.long_target_profit <= 0 or self.p.shrt_target_profit <= 0:\n self.logger.error(\"Invalid target_profit percentage\")\n raise RuntimeError\n\n if self.p.long_stop_loss <= 0 or self.p.shrt_stop_loss <= 0:\n self.logger.error(\"Invalid stop_loss percentage\")\n raise RuntimeError\n\n def signal(self, market, context, data):\n price = data.current(market, 'price')\n\n # Get position\n pos = context.portfolio.positions[market]\n # print(pos)\n\n if pos.amount > 0:\n if price <= pos.cost_basis * (1 - self.p.long_stop_loss):\n arg = 'StopLoss at {}'.format(self.p.long_stop_loss)\n return SIGNAL_SHORT, arg\n\n elif price >= pos.cost_basis * (1 + self.p.long_target_profit):\n arg = 'Target profit at {}'.format(self.p.long_target_profit)\n return SIGNAL_SHORT, arg\n\n elif pos.amount == 0:\n last_sale_price = context.short_positions.get(\n market.symbol, float('nan'))\n\n if price <= last_sale_price * (1 - self.p.shrt_target_profit):\n arg = 'Target profit at {}'.format(self.p.shrt_target_profit)\n return SIGNAL_LONG, arg\n\n elif price >= last_sale_price * (1 + self.p.shrt_stop_loss):\n arg = 'StopLoss at {}'.format(self.p.shrt_stop_loss)\n return SIGNAL_LONG, arg\n\n return SIGNAL_NONE, ''\n\n # def plot(self, )\n" }, { "alpha_fraction": 0.5621242523193359, "alphanum_fraction": 0.5664662718772888, "avg_line_length": 25.972972869873047, "blob_id": "f64c16ac0119113a7311d008ee87dfa3480cfcc4", "content_id": "38d4ee196ad00097c8569fefec935acfd59b80ae", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2994, "license_type": "permissive", "max_line_length": 95, "num_lines": 111, "path": "/vergoldemich/agent.py", "repo_name": "fmeirinhos/VergoldeMich", "src_encoding": "UTF-8", "text": "import numpy as np\n\nfrom .base import MetaBase\n\nfrom .strategies.signal import *\nfrom .strategies.stop_loss import StopLoss\n\nfrom catalyst.api import (\n get_open_orders,\n symbol,\n record,\n order,\n order_percent,\n order_target,\n order_target_percent,\n order_target_value,\n order_value\n)\n\n\nclass Agent(MetaBase):\n \"\"\"\n Agent for a crypto asset. The agent manages everything associated with\n the market, such as activating stop losses, trading and changing\n strategies.\n\n Attributes\n market (str) The currency market\n strategy (Strategy) The to-be-used strategy\n \"\"\"\n\n params = dict(\n )\n\n def __init__(self, market, strategy):\n super(Agent, self).__init__()\n\n self.logger.info(\"Initialized agent with {}\".format(\n strategy.__class__.__name__))\n\n self.market = symbol(market)\n self.strategy = strategy\n # self.stop_loss = StopLoss()\n\n def __repr__(self):\n return 'Agent ' + self.market.symbol + ' with ' + str(self.strategy.__class__.__name__)\n\n def trade(self, context, data):\n \"\"\"\n This is the brain of the agent and it is what carries out trades\n \"\"\"\n\n # Get current price\n price = data.current(self.market, 'price')\n\n # Check if price is ok\n if price is np.nan:\n self.logger.warn('No pricing data')\n return\n\n record(\n price=price\n )\n\n # Activate possible stop losses\n # if self.order(self.stop_loss, context, data):\n # return\n\n # Check current orders for this market\n # if len(get_open_orders(self.market)) > 0:\n # self.logger.info('Skipping frame until all open orders execute')\n # return\n\n # if not data.can_trade(self.market):\n # self.logger.warn(\"Can't trade!\")\n # return\n\n # Call strategy\n self.order(self.strategy, context, data)\n\n def order(self, strategy, context, data):\n \"\"\"\n Places the order(s) generated by the trading algorithm\n \"\"\"\n\n signal, arg = strategy.eval(self.market, context, data)\n\n if signal == SIGNAL_NONE:\n return False\n\n pos = context.portfolio.positions[self.market]\n price = data.current(self.market, 'price')\n\n if signal == SIGNAL_LONG:\n if pos.amount == 0:\n self.logger.info(\n '{0}: LONGING - price: {1:.4f}\\t {2}'.format(data.current_dt, price, arg))\n order_target_percent(self.market, target=1)\n\n elif signal == SIGNAL_SHORT:\n if pos.amount > 0:\n self.logger.info(\n '{0}: SHRTING - price: {1:.4f}\\t {2}'.format(data.current_dt, price, arg))\n order_target_percent(self.market, target=0)\n\n context.short_positions[self.market.symbol] = price\n\n else:\n raise NotImplementedError\n\n return True\n" }, { "alpha_fraction": 0.49702632427215576, "alphanum_fraction": 0.5293118357658386, "avg_line_length": 26.372093200683594, "blob_id": "acd38765e75ecd2d234cfc934b5307e70449fe1a", "content_id": "f495ad67547a90571dc7d3f1aaf480a00e126443", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1177, "license_type": "permissive", "max_line_length": 126, "num_lines": 43, "path": "/tools/scraper.py", "repo_name": "fmeirinhos/VergoldeMich", "src_encoding": "UTF-8", "text": "from coinmarketcap import Market\nimport time\n\n\nclass CoinMarketcap:\n\n def __init__(self):\n self.cmc = Market()\n self.investments = {}\n\n def get_percentage(self, start=0, limit=100):\n\n ticker = self.cmc.ticker(start=start, limit=limit, convert='Eur')\n\n for key, val in ticker['data'].items():\n name = val['name']\n pc1h = val['quotes']['USD']['percent_change_1h']\n\n if name in self.investments:\n self.investments[name].append(pc1h)\n\n else:\n self.investments[name] = [pc1h]\n\n\ncmc = CoinMarketcap()\n\nwhile True:\n\n cmc.get_percentage(start=000, limit=100)\n cmc.get_percentage(start=101, limit=200)\n\n for key, val in cmc.investments.items():\n if val[-1] > 2:\n print(\"Invest in: {}\\t1h % change: {}\".format(key, val[-1]))\n\n # TODO: What if val[-2] == 0?\n if len(val) > 1 and (val[-1] - val[-2]) / abs(val[-2]) > 2:\n print(\n \"\\nPOSSIBLE PUMP\\nInvest in: {}\\n1h % change in the last 2 minutes{} -> {}\\n\\n\".format(key, val[-2], val[-1]))\n\n print(\"\\n\\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\\n\\n\")\n time.sleep(120)\n" }, { "alpha_fraction": 0.5640703439712524, "alphanum_fraction": 0.5640703439712524, "avg_line_length": 20.513513565063477, "blob_id": "5cdf4cff32f31c4d33ef79d46eab93674c66e7d1", "content_id": "c140ede6972453a8cd3b8698b6542b584d91443a", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 796, "license_type": "permissive", "max_line_length": 74, "num_lines": 37, "path": "/vergoldemich/strategies/strategy.py", "repo_name": "fmeirinhos/VergoldeMich", "src_encoding": "UTF-8", "text": "from .signal import *\nfrom ..base import MetaBase\n\nfrom catalyst.api import (\n record\n)\n\n\nclass Strategy(MetaBase):\n\n \"\"\"Docstring for Strategy. \"\"\"\n\n def __str__(self):\n return \"{}\".format(self.__class__.__name__)\n\n def __init__(self, **kwargs):\n super(Strategy, self).__init__()\n self.p.update(**kwargs)\n self.check()\n\n def check(self):\n \"\"\"\n Sanity checks for the strategy\n \"\"\"\n raise NotImplementedError\n\n def signal(self, market, context, data):\n \"\"\"\n Will return either a BUY, SELL or WAIT signal for the given market\n \"\"\"\n raise NotImplementedError\n\n def plot(self, ax, chart):\n \"\"\"\n Plots the relevant data of the strategy\n \"\"\"\n raise NotImplementedError\n" }, { "alpha_fraction": 0.540942907333374, "alphanum_fraction": 0.5452289581298828, "avg_line_length": 28.95270347595215, "blob_id": "070e813f004f3ea7e7e079b1a5240ab101e3a5c6", "content_id": "6a660cab47597b758ea406dd86cd88c6a17023cf", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4433, "license_type": "permissive", "max_line_length": 85, "num_lines": 148, "path": "/vergoldemich/plotter.py", "repo_name": "fmeirinhos/VergoldeMich", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\n# import matplotlib.dates as mdates\n# import datetime\nimport logbook\nfrom catalyst.exchange.utils.stats_utils import extract_transactions\n\n\nclass Plotter(object):\n \"\"\"\n Main crypto plotter\n \"\"\"\n\n def __init__(self, context, performance, **kwargs):\n \"\"\"\n Sets the seaborn options\n\n Args:\n perf (Pandas.DataFrame): The algo performance DataFrame.\n **kwargs: See seaborn options\n \"\"\"\n self.perf = performance\n self.context = context\n\n self._logger = logbook.Logger(self.__class__.__name__)\n\n try:\n import seaborn as sns\n\n # Set the default seaborn options\n self.options = {'palette': 'Set2'}\n self.options.update(**kwargs)\n\n sns.set(**self.options)\n sns.set_color_codes()\n\n except ImportError:\n self._logger.warn(\n 'Seaborn not installed. Skipping seaborn options')\n\n def plot(self, *args):\n \"\"\"\n Draws several plots\n\n Args:\n *args (str) the functions to plot\n \"\"\"\n self.plots = [*args]\n self.subplot = str(len(self.plots)) + '1' # vertical plot\n\n self.subplot_kwargs = {'sharex': plt.subplot(int(self.subplot + '1'))}\n\n for plot in self.plots:\n ax = self._get_axis(plot)\n getattr(self, plot)(ax)\n\n plt.show()\n\n def _get_axis(self, plot):\n \"\"\"\n Fetches the axis of the plot ``plot``\n\n Arguments:\n plot (str)\n \"\"\"\n loc = int(self.subplot + str(self.plots.index(plot) + 1))\n\n return plt.subplot(loc, **self.subplot_kwargs)\n\n def asset_trades(self, ax):\n \"\"\"\n Plots the asset price and trades\n\n Args:\n ax (matplotlib.pyplot.subplot) Subplot\n \"\"\"\n self.perf.loc[:, ['price', 'short_mavg', 'long_mavg']].plot(\n ax=ax, label='Price')\n ax.legend_.remove()\n ax.set_ylabel('{asset}\\n({base})'.format(\n asset=self.context.asset.symbol, base=self.context.quote_currency))\n\n start, end = ax.get_ylim()\n ax.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))\n self.mark_purchases(ax)\n\n def mark_purchases(self, ax):\n \"\"\"\n Marks the purchases made\n\n Args:\n ax (matplotlib.pyplot.subplot) Subplot\n \"\"\"\n\n transaction_df = extract_transactions(self.perf)\n if not transaction_df.empty:\n buy_df = transaction_df[transaction_df['amount'] > 0]\n sell_df = transaction_df[transaction_df['amount'] < 0]\n ax.scatter(buy_df.index.to_pydatetime(), self.perf.loc[\n buy_df.index, 'price'], marker='^', s=20, c='green', label='')\n ax.scatter(sell_df.index.to_pydatetime(), self.perf.loc[\n sell_df.index, 'price'], marker='v', s=20, c='red', label='')\n\n def portfolio_value(self, ax):\n \"\"\"\n Plots the portfolio value using the base currency\n\n Args:\n ax (matplotlib.pyplot.subplot) Subplot\n \"\"\"\n\n self.perf.loc[:, ['portfolio_value']].plot(ax=ax)\n ax.legend_.remove()\n ax.set_ylabel('Portfolio Value\\n({})'.format(\n self.context.quote_currency))\n start, end = ax.get_ylim()\n ax.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))\n\n def portfolio_change(self, ax):\n \"\"\"\n Plots the percentual change of the portfolio and the asset\n\n Args:\n ax (matplotlib.pyplot.subplot) Subplot\n \"\"\"\n price = self.perf.loc[:, ['price']].values\n price0 = price[1]\n self.perf['price_change'] = (price - price0) / price0\n\n self.perf.loc[:, ['algorithm_period_return']].plot(ax=ax)\n self.perf.loc[:, ['price_change']].plot(ax=ax)\n\n # ax.legend_.remove()\n ax.set_ylabel('Percentage Change')\n start, end = ax.get_ylim()\n ax.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))\n\n def cash(self, ax):\n \"\"\"\n Plots the cash\n\n Args:\n ax (matplotlib.pyplot.subplot) Subplot\n \"\"\"\n self.perf.cash.plot(ax=ax)\n ax.set_ylabel('Cash\\n({})'.format(self.context.quote_currency))\n start, end = ax.get_ylim()\n ax.yaxis.set_ticks(np.arange(0, end, end / 5))\n" }, { "alpha_fraction": 0.5434861183166504, "alphanum_fraction": 0.5532298684120178, "avg_line_length": 31.220930099487305, "blob_id": "168c9cea9053cece748e48757ed2fa452ee8a1d7", "content_id": "b86b8dba2acecc88ac204e659fcc0ed45c4f7143", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2771, "license_type": "permissive", "max_line_length": 81, "num_lines": 86, "path": "/vergoldemich/strategies/adx_rsi.py", "repo_name": "fmeirinhos/VergoldeMich", "src_encoding": "UTF-8", "text": "from .signal import *\nfrom .strategy import *\n\nimport talib\nimport numpy as np\n\n\nclass ADX_RSI(Strategy):\n \"\"\"\n Basic strategy based on RSI, BBs and ADX.\n\n If RSI is satisfied, a timewindow of of trade is opened.\n If the cross is satisfied within the timeframe, the trading is \n \"\"\"\n\n params = dict(\n RSI_timeperiod=14,\n RSI_oversold=33,\n RSI_overbought=70,\n\n ADX_timeperiod=3,\n threshold=60,\n\n candlesize='5T',\n trading_window=7,\n long_trigger=3,\n short_trigger=2,\n )\n\n def __init__(self, **kwargs):\n super(ADX_RSI, self).__init__(**kwargs)\n\n def check(self):\n pass\n\n def eval(self, market, context, data):\n try:\n prices = data.history(\n market,\n fields=['low', 'high', 'close', 'price'],\n bar_count=50,\n frequency=self.p.candlesize\n )\n\n except Exception as e:\n self.logger.warn(\"Historical data not available {}\".format(e))\n return\n\n return self.signal(prices)\n\n def signal(self, prices):\n\n rsi = talib.RSI(prices['price'].values,\n timeperiod=self.p.RSI_timeperiod)\n\n d_p = talib.PLUS_DI(prices['high'].values, prices['low'].values, prices[\n 'close'].values, timeperiod=self.p.ADX_timeperiod)\n d_m = talib.MINUS_DI(prices['high'].values, prices['low'].values, prices[\n 'close'].values, timeperiod=self.p.ADX_timeperiod)\n\n crosscall = d_p[-self.p.ADX_timeperiod:] > d_m[-self.p.ADX_timeperiod:]\n\n # if rsi[-1] <= self.p.RSI_oversold:\n # if crosscall[-1]:\n # return SIGNAL_LONG, 'Crosscall and RSI'.format(rsi[-1])\n # elif rsi[-1] >= self.p.RSI_overbought:\n # if not crosscall[-1]:\n # return SIGNAL_SHORT, 'Crossput and RSI'.format(rsi[-1])\n\n # if crosscall[-1]:\n # if np.any(rsi[-self.p.trading_window::] <= self.p.RSI_oversold):\n # return SIGNAL_LONG, 'Crosscall and RSI'.format(rsi[-1])\n\n # else:\n # if np.any(rsi[-self.p.trading_window::] >= self.p.RSI_overbought):\n # return SIGNAL_SHORT, 'Crossput and RSI'.format(rsi[-1])\n\n if np.sum(crosscall) >= self.p.long_trigger:\n if np.any(rsi[-self.p.trading_window:] <= self.p.RSI_oversold):\n return SIGNAL_LONG, 'Crosscall and RSI {}'.format(rsi[-1])\n\n # elif not crosscall[-1]:\n if self.p.trading_window - np.sum(crosscall) >= self.p.short_trigger:\n if np.any(rsi[-self.p.trading_window:] >= self.p.RSI_overbought):\n return SIGNAL_SHORT, 'Crossput and RSI {}'.format(rsi[-1])\n return SIGNAL_NONE, ''\n" }, { "alpha_fraction": 0.5482866168022156, "alphanum_fraction": 0.5519210696220398, "avg_line_length": 28.18181800842285, "blob_id": "a0d5338e22b53310ed7cdd9ea644a6b929364b52", "content_id": "eae2bd8a52a0cd717b19571fb21bfd024d6746ba", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1926, "license_type": "permissive", "max_line_length": 86, "num_lines": 66, "path": "/vergoldemich/strategies/adx_di.py", "repo_name": "fmeirinhos/VergoldeMich", "src_encoding": "UTF-8", "text": "from .signal import *\nfrom .strategy import *\n\nimport talib\nimport numpy as np\n\n\nclass ADX_DI(Strategy):\n \"\"\"\n Trading in the direction of a strong trend reduces risk and increases profit\n potential. The average directional index (ADX) is used to determine when\n price is trending strongly.\n\n Source:\n https://www.investopedia.com/articles/trading/07/adx-trend-indicator.asp\n \"\"\"\n params = dict(\n ADX_timeperiod=5,\n candle_size='5T',\n trading_window=3\n )\n\n def __init__(self, **kwargs):\n \"\"\"\n Args:\n ADX_length (int) The MA length of ADX\n \"\"\"\n super(ADX_DI, self).__init__(**kwargs)\n\n def check(self):\n pass\n\n def eval(self, market, context, data):\n # Fetch market history\n try:\n prices = data.history(\n market,\n fields=['low', 'high', 'close'],\n bar_count=20,\n frequency=self.p.candle_size\n )\n\n except Exception as e:\n self.logger.warn('historical data not available: {}'.format(e))\n return\n\n return self.signal(prices)\n\n def signal(self, prices):\n\n di_plus = talib.PLUS_DI(prices['high'].values, prices['low'].values, prices[\n 'close'].values, timeperiod=self.p.ADX_timeperiod)\n di_minus = talib.MINUS_DI(prices['high'].values, prices['low'].values, prices[\n 'close'].values, timeperiod=self.p.ADX_timeperiod)\n\n crosscall = di_plus[-self.p.trading_window:] > di_minus[\n -self.p.trading_window:]\n\n if np.all(crosscall[-self.p.trading_window:]):\n arg = 'DIPcross'\n return SIGNAL_LONG, arg\n elif not np.any(crosscall[-self.p.trading_window:]):\n arg = 'DIPput'\n return SIGNAL_SHORT, arg\n else:\n return SIGNAL_NONE, ''\n" }, { "alpha_fraction": 0.5659909248352051, "alphanum_fraction": 0.5705419778823853, "avg_line_length": 30.389610290527344, "blob_id": "ed9bae7cb26859e1d0f32d8b8b99eea7a32dfcb6", "content_id": "b5fce97810863cf42c4d0957d2e3a5c4fb0b1a53", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2417, "license_type": "permissive", "max_line_length": 79, "num_lines": 77, "path": "/vergoldemich/candlestick.py", "repo_name": "fmeirinhos/VergoldeMich", "src_encoding": "UTF-8", "text": "from __future__ import division\n\nfrom matplotlib.lines import Line2D\nfrom matplotlib.patches import Rectangle\n\n\ndef candlestick(ax, df, width=0.01, colorup='g', colordown='r',\n alpha=1.0, colorline=None):\n \"\"\"\n Modified from matplotlib.finance module to change color of high-low lines.\n df is a sequence of (time, open, close, high, low, ...) sequences.\n As long as the first 5 elements are these values,\n the record can be as long as you want (eg it may store volume).\n time must be in float days format - see date2num\n Plots the time, open, close, high, low as a vertical line ranging\n from low to high. Uses a rectangular bar to represent the\n open-close span. If close >= open, uses colorup to color the bar,\n otherwise uses colordown.\n ax : an Axes instance to plot to\n width : fraction of a day for the rectangle width\n colorup : the color of the rectangle where close >= open\n colordown : the color of the rectangle where close < open\n alpha : the rectangle alpha level\n colorline : the color of the high-low line; defaults to colorup/colordown\n return value is lines, patches where lines is a list of lines\n added and patches is a list of the rectangle patches added\n \"\"\"\n\n OFFSET = width / 2.0\n\n lines = []\n patches = []\n # for row in quotes:\n for (idx, row) in df.iterrows():\n t = row['Time']\n opn = row['Open']\n high = row['High']\n low = row['Low']\n close = row['Close']\n\n if close >= opn:\n color = colorup\n lower = opn\n height = close - opn\n else:\n color = colordown\n lower = close\n height = opn - close\n\n if colorline:\n cl = colorline\n else:\n cl = color\n\n vline = Line2D(\n xdata=(t, t), ydata=(low, high),\n color=cl,\n linewidth=width,\n antialiased=True,\n alpha=alpha)\n\n rect = Rectangle(\n xy=(t - OFFSET, lower),\n width=width,\n height=height,\n facecolor=color,\n edgecolor=color,\n )\n rect.set_alpha(alpha)\n\n lines.append(vline)\n patches.append(rect)\n ax.add_line(vline)\n ax.add_patch(rect)\n ax.autoscale_view()\n\n return lines, patches\n" }, { "alpha_fraction": 0.6193921566009521, "alphanum_fraction": 0.6432706117630005, "avg_line_length": 22.423728942871094, "blob_id": "728baad0cc250b657ddaf74060a94206f5f4348e", "content_id": "846aee3c7a15eb5f0c15383890b262078863f185", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1382, "license_type": "permissive", "max_line_length": 79, "num_lines": 59, "path": "/examples/rsi_follower.py", "repo_name": "fmeirinhos/VergoldeMich", "src_encoding": "UTF-8", "text": "import sys\nimport os\nsys.path.insert(1, os.path.join(sys.path[0], '..'))\n\nfrom catalyst.utils.run_algo import run_algorithm\n\nfrom vergoldemich import (\n Broker,\n Agent,\n RSI_BB_Fawner,\n Plotter\n)\n\nfrom logbook import Logger\nimport time\nimport pandas as pd\n\n# Initialize broker\nbroker = Broker()\n\n\ndef initialize(context):\n context.start_time = time.time()\n\n broker.add_agent(Agent('eth_btc', RSI_BB_Fawner()))\n\n # Find alternative!\n context.short_positions = {}\n\n # Add commission and slippage\n context.set_commission(maker=0.000, taker=0.001)\n context.set_slippage(spread=0.000)\n\n\ndef analyze(context, perf):\n Logger(__name__).info('elapsed time: {}'.format(\n time.time() - context.start_time))\n\n context.quote_currency = list(context.exchanges.values())[\n 0].quote_currency.upper()\n\n context.asset = list(broker.agents.keys())[0]\n\n plotter = Plotter(context, perf)\n plotter.plot('portfolio_value', 'asset_trades', 'portfolio_change', 'cash')\n\n\nif __name__ == '__main__':\n run_algorithm(\n capital_base=1,\n data_frequency='minute',\n initialize=initialize,\n handle_data=broker.handle_data,\n analyze=analyze,\n exchange_name='binance',\n quote_currency='eth',\n start=pd.to_datetime('2018-05-10', utc=True),\n end=pd.to_datetime('2018-05-25', utc=True),\n )\n" }, { "alpha_fraction": 0.586309552192688, "alphanum_fraction": 0.586309552192688, "avg_line_length": 18.764705657958984, "blob_id": "7302978907e98988f8e0502ac42116e8422d852c", "content_id": "5910101331f62adf6bdab590667225b7904fcb0f", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 336, "license_type": "permissive", "max_line_length": 61, "num_lines": 17, "path": "/vergoldemich/base.py", "repo_name": "fmeirinhos/VergoldeMich", "src_encoding": "UTF-8", "text": "import logbook\n\n\nclass Parameters(object):\n\n def __init__(self, **kwargs):\n self.update(**kwargs)\n\n def update(self, **kwargs):\n self.__dict__.update(**kwargs)\n\n\nclass MetaBase(object):\n\n def __init__(self):\n self.p = Parameters(**self.params)\n self.logger = logbook.Logger(self.__class__.__name__)\n" }, { "alpha_fraction": 0.7263157963752747, "alphanum_fraction": 0.7263157963752747, "avg_line_length": 22.75, "blob_id": "afc9242ebeb5c7f5b525de23223aab07e07d8052", "content_id": "bd099c5c563b1302e291f3e7d789ea1b2b75b6bd", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 95, "license_type": "permissive", "max_line_length": 25, "num_lines": 4, "path": "/vergoldemich/strategies/__init__.py", "repo_name": "fmeirinhos/VergoldeMich", "src_encoding": "UTF-8", "text": "from .rsi_fawner import *\nfrom .signal import *\nfrom .strategy import *\nfrom .adx_rsi import *\n" } ]
17
lorranapereira/exerpython-
https://github.com/lorranapereira/exerpython-
9b32bd6d128dba9b1a7394b93ffc4d45e2e6fb5a
a1a82a33ee83a32c5065e5be581620267510a017
4b233f2ebf8a4c085f880785757cd85d4810e92f
refs/heads/master
2020-04-30T03:29:17.440542
2019-03-19T19:46:56
2019-03-19T19:46:56
176,587,295
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5665158629417419, "alphanum_fraction": 0.5837104320526123, "avg_line_length": 28.891891479492188, "blob_id": "11d23f043eb96f98b5a7e10aecdc448a225b4cf4", "content_id": "27601992c360d02747d4551992dc0a408f7d6f37", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1111, "license_type": "permissive", "max_line_length": 116, "num_lines": 37, "path": "/exercicios/exercicio7.py", "repo_name": "lorranapereira/exerpython-", "src_encoding": "UTF-8", "text": "#import datetime \n\n#def func(year,month,day,aux):\n# x = datetime.datetime(year,month,day)\n# if aux==1:\n# print(x.strftime('%Y')+','+x.strftime('%d')+' of '+x.strftime('%B'))\n# if aux==2:\n# print(x.strftime('%d')+'/'+x.strftime('%m')+'/'+x.strftime('%Y'))\n#func(2000,9,8,1)\n#func(2000,9,8,2)\n#---------\n\nfrom datetime import datetime\n\ndef func(nome,dt,vet):\n dt = dt.split(\"/\")\n date = datetime(int(dt[2]),int(dt[1]),int(dt[0]))\n d = dict()\n vet = vet.split(';')\n d = {\"nome\": nome, \"dataNascimento\":date, \"telefone\":vet } \n print(d[\"dataNascimento\"])\n\nnome = input(\"Dígite seu nome: \")\ndt = input(\"Dígite sua Data de aniversario no formato dia/mes/ano: \")\nvet = input(\"Dígite seu número de telefone, sem pontos ou traços. Caso tenha mais de um número, os separe com ;: \")\nteste = func(nome,dt,vet)\n#class Pessoa:\n# def __init__(self,nome):\n# self._nome = nome\n# def _get_nome(self):\n# return self._nome\n# def _set_nome(self, nome):\n# self._nome = nome\n# nome = property(_get_nome, _set_nome)\n\n# p = Pessoa('Julio')\n# print(p.nome)" } ]
1
adamako/python-blockchain
https://github.com/adamako/python-blockchain
d3782f5b5a7cdae645186f367b057bed448af029
3f1822710a473acd4a9d5d951cc923dca0392b2e
3747abfbefb7a7e7e4d7983b6f53fc0dd84e9bb0
refs/heads/main
2023-01-02T03:46:12.249492
2020-10-24T00:14:29
2020-10-24T00:14:29
306,770,872
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6063096523284912, "alphanum_fraction": 0.6108165383338928, "avg_line_length": 31.73043441772461, "blob_id": "6d77601dd8bb9aa6456c73cc4257277d91fb665b", "content_id": "779fae75a5f4652a2721c7057bf551eba7f6049d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3772, "license_type": "no_license", "max_line_length": 162, "num_lines": 115, "path": "/block.py", "repo_name": "adamako/python-blockchain", "src_encoding": "UTF-8", "text": "from hashlib import sha256\nimport json\nimport time\n\nclass Block:\n def __init__(self, index, transactions, timestamp, previous_hash):\n \"\"\"\n Constructor for the `Block` class.\n :param index: Unique ID of the block.\n :param transactions: List of transactions.\n :param timestamp: Time of generation of the block.\n :param previous_hash: Hash of the previous block in the chain which this block is part of. \n\n \"\"\"\n self.index=index\n self.transactions=transactions\n self.timestamp=timestamp\n self.previous_hash=previous_hash\n\n def compute_hash(self):\n \"\"\"\n Returns the hash of the block instance by first converting it\n into JSON string.\n \"\"\" \n\n block_string= json.dumps(self.__dict__,sort_keys=True) \n\n return sha256(block_string.encode()).hexdigest()\n\nclass Blockchain:\n dificulty=2\n def __init__(self):\n self.unconfirmed_transactions= []\n self.chain=[]\n self.create_genesis_block()\n \n\n def create_genesis_block(self):\n \"\"\"\n A function to generate genesis block and appends it to\n the chain. The block has index 0, previous_hash as 0, and\n a valid hash.\n \"\"\"\n genesis_block = Block(0, [], time.time(), \"0\")\n genesis_block.hash = genesis_block.compute_hash()\n self.chain.append(genesis_block)\n\n @property\n def last_block(self):\n \"\"\"\n A quick pythonic way to retrieve the most recent block in the chain. Note that\n the chain will always consist of at least one block (i.e., genesis block)\n \"\"\"\n return self.chain[-1]\n\n def proof_of_work(self, block):\n \"\"\"\n Function that tries different values of the nonce to get a hash\n that satisfies our difficulty criteria.\n \"\"\"\n block.nonce=0\n computed_hash= block.compute_hash()\n while not computed_hash.startswith('0'*Blockchain.dificulty):\n block.nonce+=1\n computed_hash=block.compute_hash()\n return computed_hash \n\n def add_block(self, block, proof):\n \"\"\"\n A function that adds the block to the chain after verification.\n Verification includes:\n * Checking if the proof is valid.\n * The previous_hash referred in the block and the hash of a latest block\n in the chain match.\n \"\"\" \n previous_hash=self.last_block.hash\n if previous_hash!=block.previous_hash:\n return False \n if not self.is_valid_proof(block,proof):\n return False\n block.hash=proof\n self.chain.append(block)\n return True \n \n\n def is_valid_proof(self, block, block_hash):\n \"\"\"\n Check if block_hash is valid hash of block and satisfies\n the difficulty criteria.\n \"\"\"\n\n return (block_hash.startswith('0'*Blockchain.dificulty) and block_hash==block.compute_hash())\n\n def add_new_transaction(self, transaction):\n self.unconfirmed_transactions.append(transaction)\n\n def mine(self):\n \"\"\"\n This function serves as an interface to add the pending\n transactions to the blockchain by adding them to the block\n and figuring out proof of work.\n \"\"\"\n \n if not self.unconfirmed_transactions:\n return False\n last_block=self.last_block\n\n new_block= Block(index=self.last_block.index+1,transactions=self.unconfirmed_transactions,timestamp=time.time(),previous_hash=last_block.previous_hash) \n\n proof= self.proof_of_work(new_block)\n self.add_block(new_block,proof)\n self.unconfirmed_transactions=[]\n\n\n return new_block.index " }, { "alpha_fraction": 0.6740740537643433, "alphanum_fraction": 0.6851851940155029, "avg_line_length": 22.434782028198242, "blob_id": "2f60b3ecc5eeb127e0c1491cfa01ea3e6db0d8f6", "content_id": "3d814f3549948873e2db7cad4468facb8ce1e6f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 540, "license_type": "no_license", "max_line_length": 49, "num_lines": 23, "path": "/interface.py", "repo_name": "adamako/python-blockchain", "src_encoding": "UTF-8", "text": "from block import *\nfrom flask import Flask,request\n\n#Initialize flask application\napp= Flask(__name__)\n\n#Initialize a blockchain object\nblockchain= Blockchain()\n\[email protected]('/new_transaction',methods=['POST'])\ndef new_transaction():\n tx_data=request.get_json()\n required_fields=[\"author\",\"content\"]\n\n for field in required_fields:\n if not tx_data.get(field):\n return \"Invalid transaction data\",404\n \n tx_data[\"timestamp\"]=time.time()\n\n blockchain.add_new_transaction(tx_data)\n\n return \"Success\",201\n\n" } ]
2
geekhub-python/if-else-conditions-lists-GeorgeGarkavenko
https://github.com/geekhub-python/if-else-conditions-lists-GeorgeGarkavenko
036a8c43ec125dd956555ac1497f78d3ab8dd30d
241af06fd449e3d198a6c1fdf56b8239b52b0f7d
4f00e3ab51b590154021d96923ddbafc2def5741
refs/heads/master
2021-01-12T13:10:01.395198
2016-10-29T11:17:30
2016-10-29T11:17:30
72,130,632
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.31856822967529297, "alphanum_fraction": 0.40850111842155457, "avg_line_length": 26.268293380737305, "blob_id": "478d87037bedbf98bf8be36f0d13ad10d963d735", "content_id": "7d6cfec7ef4ff9b6e3a27cd83c09cae0cab3878c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2237, "license_type": "no_license", "max_line_length": 75, "num_lines": 82, "path": "/solved_tasks.py", "repo_name": "geekhub-python/if-else-conditions-lists-GeorgeGarkavenko", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\ndef handle_task_1(year):\n from calendar import isleap\n return 'YES' if isleap(year) else 'NO'\n\ndef handle_task_2(a, b, c):\n arguments = locals().values()\n original_len = len(set(arguments))\n return 4 - original_len if original_len < 3 else 0\n \ndef handle_task_3(n, m, k):\n condition_not= (m * n < k) or (k % n) and (k % m)\n return 'NO' if condition_not else 'YES'\n\ndef handle_task_4(params):\n from itertools import combinations\n comb = combinations(params, 2)\n equl_pairs = filter( lambda pair: pair[0] == pair[1] , comb)\n return len(tuple(equl_pairs))\n\ndef handle_task_5(params):\n pairs = zip(params[:-1], params[1:])\n needed_pairs_gen = filter((lambda pair: pair[0] * pair[1] > 0 ), pairs)\n needed_pairs = tuple(needed_pairs_gen)\n if needed_pairs:\n return needed_pairs[0]\n else:\n return None\n \n \n \ndef main():\n \n test_inputs = (\n (1, (2012,)),\n (1, (2011,)),\n (1, (1492,)),\n (1, (1800,)),\n \n (2, (10, 5, 10)),\n (2, (17, 17, -9)),\n (2, (4, -82, -82)),\n (2, (5, 2, 4)),\n (2, (-149, -146, -142)),\n (2, (666, 666, 666)),\n \n (3, (4, 2, 6)),\n (3, (2, 10, 7)),\n (3, (5, 7, 1)),\n (3, (7, 4, 21)),\n (3, (5, 12, 100)),\n \n (4, ([1, 2, 3, 2, 3],) ), \n (4, ([1, 1, 1, 1, 1],) ), \n (4, ([1, 2, 3],) ), \n (4, ([1, 1, 1],) ), \n (4, ([2, 3],) ), \n (4, ([2, 2],) ), \n (4, ([0, 0],) ), \n (4, ([0, 0, 6, 1, 1, 4, 2, 1, 2, 2],) ), \n (4, ([0, 1, 43, 10, 13, 33, 15, 8, 18, 21],)), \n (4, ([3, 2, 1, 2, 2, 4, 3, 2, 5, 3, 2],)), \n \n (5, ([-1, 2, 3, -1, -2], )), \n (5, ([1, 2, -3, -4, -5], )), \n (5, ([1, -2, 3, -4, -5], )), \n (5, ([1, -2, 3, -4, 5, 6], ))\n )\n \n for i, values in test_inputs:\n print('Task {0} '.format(i))\n print('Input: ' + str(values))\n print('Output: ', end='')\n handler_name = 'handle_task_' + str(i)\n handler = globals()[handler_name]\n print(handler(*values))\n print('=================================')\n\n \nif __name__ == '__main__':\n main()" } ]
1
nevil-brownlee/check_svg
https://github.com/nevil-brownlee/check_svg
816892a086bec748d58875926d50448232f99a6c
0fbbbdbcc281c7e580a3160fa99ae619ee7241b5
388195d6627412ae153bf0fb6dc5db4e71416eba
refs/heads/master
2021-01-24T20:26:35.219513
2018-01-21T23:07:13
2018-01-21T23:07:13
19,806,757
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7580645084381104, "alphanum_fraction": 0.7675521969795227, "avg_line_length": 61, "blob_id": "bee0413df27fca7a55968905b09f1473631d5db8", "content_id": "02fe3ec3b7fd40ed2f4737e91da7b77740135c6f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1054, "license_type": "permissive", "max_line_length": 222, "num_lines": 17, "path": "/README.md", "repo_name": "nevil-brownlee/check_svg", "src_encoding": "UTF-8", "text": "XML parser to check SVG against [draft-brownlee-svg](http://tools.ietf.org/html/draft-iab-svg-rfc).\n\ncheck-svg.py will read a .svg file and display messages about elements in the svg file that don't conform to the SVG-1.2-RFC syntax published as\ndraft-iab-svg-rfc-01.txt\n\ncheck-svg.py -n xxx.svg will strip out non-conforming elements and write a new file, xxx-new.svg, that does conform. You can then display the -new file (e.g. with Firefox) to check that it looks the same.\n\ncheck-svg.py is a simple (not to say 'quick and dirty') test program, it does not use the full RNC syntax set out in the draft. Instead, word_properties.py contains a python version of the syntax, which check-svg.py uses.\n\ncheck-svg.py has been tested with .svg files produced by Inkscape, LibreOffice, Dia, Graphviz and several other svg drawing programs.\n\nIn the longer term a better, production program will be developed to do these checks and transformations.\n\nThe LICENSE.md file continues to apply to check-svg.py and word_properties.py.\n\n\nNevil Brownlee, 28 Jan 2016 (NZDT)\n" }, { "alpha_fraction": 0.5056443810462952, "alphanum_fraction": 0.5157102346420288, "avg_line_length": 35.27986526489258, "blob_id": "7103269cdbec2032d6c556df8159c3a2ec24d32e", "content_id": "18306c265f98e5491ae410731ffa8356467bb151", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10630, "license_type": "permissive", "max_line_length": 104, "num_lines": 293, "path": "/check-svg.py", "repo_name": "nevil-brownlee/check_svg", "src_encoding": "UTF-8", "text": "# 1305, 9 Jan 2018 (NZDT)\n#\n# Nevil Brownlee, U Auckland\n# From a simple original version by Joe Hildebrand\n\n# ElementTree doesn't have nsmap\ntry:\n import xml.etree.cElementTree as ET\nexcept ImportError:\n import xml.etree.ElementTree as ET\n#from lxml import etree as ET\n\nimport getopt, sys, re\n\nimport word_properties as wp\n\nindent = 4\nwarn_nbr = 0\ncurrent_file = None\n\nverbose = False # set by -v\nwarn_limit = 40 # set by -w nnn\nnew_file = False # set by -n\ntrace = False # set by -t\n\nbad_namespaces = []\n\ndef help_msg(msg):\n suffix = ''\n if msg:\n suffix = \": %s\" % msg\n print(\"Nevil's SVG checker%s\" % suffix)\n print(\"\\n ./check.py [options] input-svg-file(s)\\n\")\n print(\"options:\")\n print(\" -n write .new.svg file, stripping out anything\\n not allowed in SVG 1.2 RFC\")\n print(\" -w nn stop after nn warning messages\\n\")\n exit()\n\ntry:\n options, rem_args = getopt.getopt(sys.argv[1:], \"hntvw:\")\nexcept getopt.GetoptError:\n help_msg(\"Unknown option\")\n \nfilter = None\nfor o,v in options:\n if o == \"-w\":\n warn_limit = int(v)\n elif o == \"-v\":\n verbose = True\n elif o == \"-h\":\n help_msg(None)\n elif o == \"-n\":\n new_file = True\n elif o == \"-t\":\n trace = True\n\nif len(rem_args) == 0:\n help_msg(\"No input file(s) specified!\")\n\ndef warn(msg, depth):\n global indent, warn_nbr, warn_limit, current_file\n warn_nbr += 1\n print(\"%5d %s%s\" % (warn_nbr, ' '*(depth*indent), msg))\n if warn_nbr == warn_limit:\n print(\"warning limit (%d) reached for %s <<\" % (\n warn_nbr, current_file))\n exit()\n\n#def check_some_props(attr, val, depth): # For [style] properties\n# Not needed Jan 2018 versionq\n# props_to_check = wp.property_lists[attr]\n# new_val = ''; ok = True\n# style_props = val.rstrip(';').split(';')\n# print(\"style_props = %s\" % style_props)\n# for prop in style_props:\n# print(\"prop = %s\" % prop)\n# p, v = prop.split(':')\n# v = v.strip() # May have leading blank\n# if p in props_to_check:\n# #allowed_vals = wp.properties[p]\n# #print(\"$csp p=%s, allowed_vals=%s.\" % (p, allowed_vals))\n# allowed = value_ok(v, p, depth)\n# if not allowed:\n# warn(\"['%s' attribute: value %s not valid for '%s']\" % (\n# attr,v, p), depth)\n# ok = False\n# else:\n# new_val += ';' + prop\n# return (ok, new_val)\n\ndef value_ok(v, obj, depth): # Is value v OK for attrib/property obj?\n # Returns (T/F/int, val that matched)\n #print(\"V++ value_ok(%s, %s, %s) type(v) = %s, type(obj)=%s\" % (\n # v, obj, depth, type(v), type(obj)))\n if obj in wp.properties:\n values = wp.properties[obj]\n elif obj in wp.basic_types:\n values = wp.basic_types[obj]\n elif isinstance(obj, str):\n return (v == obj, v)\n else: # Unknown attribute\n return (False, None)\n\n #print(\"2++ values = %s <%s>\" % ((values,), type(values)))\n if len(values) == 0: # Empty values tuple, can't check\n return (True, None)\n elif isinstance(values, str): # values is a string\n if values[0] == '<':\n #print(\"4++ values=%s, v=%s\" % (values, v))\n ok_v, matched_v = value_ok(v, values, depth)\n #print(\"5++ ok_v = %s, matched_v = %s\" % (ok_v, matched_v))\n return (ok_v, matched_v)\n if values[0] == '+g': # Any integer or real\n n = re.match(r'\\d+\\.\\d+$', v)\n rv = None\n if n:\n rv = n.group()\n return (True, rv)\n if values[0] == '+h': # [100,900] in hundreds\n n = re.match(r'\\d00$', v)\n rv = None\n if n:\n rv = n.group()\n return (True, rv)\n if values == v:\n print(\"4++ values=%s, v=%s.\" % (values, v))\n return (True, values)\n if values[0] == \"[\":\n some_ok, matched_val = check_some_props(values, v, depth)\n return (some_ok, matched_val)\n #if values == '#': # RGB value\n # lv = v.lower()\n # if lv[0] == '#': #rrggbb hex\n # if len(lv) == 7:\n # return (lv[3:5] == lv[1:3] and lv[5:7] == lv[1:3], None)\n # if len(lv) == 4:\n # return (lv[2] == lv[1] and lv[3] == lv[1], None)\n # return (False, None)\n # elif lv.find('rgb') == 0: # integers\n # rgb = re.search(r'\\((\\d+),(\\d+),(\\d+)\\)', lv)\n # if rgb:\n # return ((rgb.group(2) == rgb.group(1) and\n # rgb.group(3) == rgb.group(1)), None)\n # return (False, None)\n\n #print(\"6++ values tuple = %s\" % (values,))\n for val in values: # values is a tuple\n ok_v, matched_v = value_ok(v, val, depth)\n #print(\"7++ ok_v = %s, matched_v = %s\" % (ok_v, matched_v))\n if ok_v:\n return (True, matched_v)\n\n #print(\"8++ values=%s, (%s) <<<\" % ((values,), type(values)))\n return (True, None) # Can't check it, so it's OK\n \ndef strip_prefix(element): # Remove {namespace} prefix\n global bad_namespaces\n ns_ok = True\n if element[0] == '{':\n rbp = element.rfind('}') # Index of rightmost }\n if rbp >= 0:\n ns = element[1:rbp]\n if not ns in wp.xmlns_urls:\n if not ns in bad_namespaces:\n bad_namespaces.append(ns)\n ns_ok = False\n #print(\"@@ element=%s\" % element[rbp+1:])\n element = element[rbp+1:]\n return element, ns_ok # return False if not in a known namespace\n\ndef check(el, depth):\n global new_file, trace\n if trace:\n print(\"T1: %s tag = %s (depth=%d <%s>)\" % (\n ' '*(depth*indent), el.tag, depth, type(depth)))\n if warn_nbr >= warn_limit:\n return False\n element, ns_ok = strip_prefix(el.tag) # name of element\n # ElementTree prefixes elements with default namespace in braces\n #print(\"element=%s, ns_ok=%s\" % (element, ns_ok))\n if not ns_ok:\n return False # Remove this el\n if verbose:\n print(\"%selement % s: %s\" % (' '*(depth*indent), element, el.attrib))\n\n attrs_to_remove = [] # Can't remove them inside the iteration!\n attrs_to_set = []\n for attrib, val in el.attrib.items():\n # (attrib,val) tuples for each attribute\n attr, ns_ok = strip_prefix(attrib)\n if trace:\n print(\"%s attrib %s = %s (ns_ok = %s), val = %s\" % (\n ' ' * (depth*(indent+1)), attr, val, ns_ok, val))\n if attrib in wp.elements: # Is it an element?\n warn(\"element '%s' not allowed as attribute\" % element, depth )\n attrs_to_remove.append(attrib)\n else:\n atr_ok, matched_val = value_ok(val, attr, depth)\n #print(\"$1-- val=%s, attr=%s -> atr_ok=%s, matched_val=%s\" % (\n # val, attr, atr_ok, matched_val))\n if not atr_ok:\n warn(\"value '%s' not allowed for attribute %s\" % (val, attrib),\n depth)\n attrs_to_remove.append(attrib)\n if matched_val != val and attrib == 'font-family':\n # Special case!\n if val.find('sans') >= 0:\n attrs_to_set.append( (attrib, 'sans-serif') )\n if val.find('serif') >= 0:\n attrs_to_set.append( (attrib, 'serif') )\n #print(\"%s is %s, matched_val %s\" % (attr, atr_ok, matched_val))\n for atr in attrs_to_remove:\n el.attrib.pop(atr)\n for ats in attrs_to_set:\n el.set(ats[0], ats[1])\n\n children_to_remove = []\n for child in el: # Children of this svg element\n ch_el, el_ok = strip_prefix(child.tag) # name of element\n #print(\"$$ el=%s, child=%s, el_ok=%s, child.tag=%s, %s\" % (\n # el, ch_el, el_ok, child.tag, type(child)))\n # Check for not-allowed elements\n if ch_el in wp.element_children:\n allowed_children = wp.element_children[element]\n else: # not in wp.element_children\n allowed_children = []\n if not ch_el in allowed_children:\n msg = \"'%s' may not appear in a '%s'\" % (ch_el, element)\n warn(msg, depth)\n children_to_remove.append(child)\n else:\n ch_ok = check(child, depth+1) # OK, check this child\n #print(\"@2@ check(depth %d) returned %s\" % (depth, ch_ok))\n\n #print(\"@3@ children_to_remove = %s\" % children_to_remove)\n for child in children_to_remove:\n el.remove(child)\n return True # OK\n\ndef remove_namespace(doc, namespace):\n return True # OKace):\n # From http://stackoverflow.com/questions/18159221/\n # remove-namespace-and-prefix-from-xml-in-python-using-lxml\n ns = u'{%s}' % namespace\n nsl = len(ns)\n for elem in doc.getiterator():\n if elem.tag.startswith(ns):\n print(\"elem.tag before= %s,\" % elem.tag)\n elem.tag = elem.tag[nsl:]\n print(\"after=%s.\" % elem.tag)\n\ndef checkFile(fn, options):\n global current_file, warn_nbr, root\n current_file = fn\n print(\"Starting %s%s\" % (fn, options))\n tree = ET.parse(fn)\n root = tree.getroot()\n #print(\"root.attrib=%s, test -> %d\" % (root.attrib, \"xmlns\" in root.attrib))\n # # attrib list doesn't have includes \"xmlns\", even though it's there\n #print(\"root.tag=%s\" % root.tag)\n no_ns = root.tag.find(\"{\") < 0\n #print(\"no_ns = %s\" % no_ns)\n\n ET.register_namespace(\"\", \"http://www.w3.org/2000/svg\")\n # Stops tree.write() from prefixing above with \"ns0\"\n check(root, 0)\n if trace and len(bad_namespaces) != 0:\n print(\"bad_namespaces = %s\" % bad_namespaces)\n if new_file:\n sp = fn.rfind('.svg')\n if sp+3 != len(fn)-1: # Indeces of last chars\n print(\"filename doesn't end in '.svg' (%d, %d)\" % (sp, len(fn)))\n else:\n if no_ns:\n root.attrib[\"xmlns\"] = \"http://www.w3.org/2000/svg\"\n for ns in bad_namespaces:\n remove_namespace(root, ns)\n new_fn = fn.replace(\".svg\", \".new.svg\")\n print(\"writing to %s\" % (new_fn))\n tree.write(new_fn)\n\n return warn_nbr\n\nif __name__ == \"__main__\":\n options = ''\n if len(sys.argv) > 2:\n options = \" %s\" % ' '.join(sys.argv[1:-1])\n for arg in rem_args:\n warn_nbr = 0\n n_warnings = checkFile(arg, options)\n print(\"%d warnings for %s\" % (n_warnings, arg))\n if len(rem_args) == 1:\n exit(n_warnings)\n" } ]
2
pride829/TCPY
https://github.com/pride829/TCPY
15ea49108a1af07eae2b223a25c0f411d34fef29
70d63c2bc75fd009c1dc471aff79b87a3e20c88d
316f812fce11645ee4c7ebd5b8e6f963d0b43f81
refs/heads/main
2023-06-29T19:37:57.294430
2021-08-03T09:12:27
2021-08-03T09:12:27
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7587476968765259, "alphanum_fraction": 0.7900552749633789, "avg_line_length": 32.9375, "blob_id": "3ae7e4e25f9a6de23bc87d1482c5a5ab06a0ccad", "content_id": "5a2a7e928da9b1c9a7f285f4797c72a2ae072f4c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 987, "license_type": "permissive", "max_line_length": 127, "num_lines": 16, "path": "/README.md", "repo_name": "pride829/TCPY", "src_encoding": "UTF-8", "text": "# TCPY\nTCPY 是專為 TOUCHANCE 行情服務用戶提供的 Python 程式交易串接 API。\n提供台灣期貨行情(台指期)與海外期貨(海期)串接範例與程式交易應用的專案。\n\n# TOUCHANCE\n是專為國內外金融交易市場所研發的「自動交易」解決方案,提供 MultiCharts, Python, 即時行情與交易串接服務。\n\n## 申請試用\n- [加入會員](https://www.touchance.com.tw)即可享有 14 天試用期間。\n- [立即加入](https://www.touchance.com.tw/signup)\n\n## TOUCHANCE Python API FaceBook 社團\n- 現在加入 [TOUCHANCE Python API 社團](https://www.facebook.com/groups/508068750594807),分享你的使用心得即可獲得 TOUCHANCE Python 行情 API 的免費試用授權。\n\n## TOUCHANCE 海期報價\n- Python API提供的海外行情,是直接從聯合報價平台上直送的行情;所以收取海期報價時,若有遇到使用上被認定為不方便或是不適合的資料,請自行使用程式來濾除\n" }, { "alpha_fraction": 0.5228226780891418, "alphanum_fraction": 0.5443336963653564, "avg_line_length": 31.033613204956055, "blob_id": "48965dd2f67e9117cd9695a3c1c8f7e772b2f82f", "content_id": "6a3b91cdb6aad4216f989c49b2d4ffb585384e95", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4156, "license_type": "permissive", "max_line_length": 153, "num_lines": 119, "path": "/history_sample(DK).py", "repo_name": "pride829/TCPY", "src_encoding": "UTF-8", "text": "import time\nfrom tcoreapi_mq import * \nimport tcoreapi_mq\nimport threading\n\ng_QuoteZMQ = None\ng_QuoteSession = \"\"\n\n#實時行情回補\ndef OnRealTimeQuote(symbol):\n print(\"商品:\", symbol[\"Symbol\"], \"成交價:\",symbol[\"TradingPrice\"], \"開:\", symbol[\"OpeningPrice\"], \"高:\", symbol[\"HighPrice\"], \"低:\", symbol[\"LowPrice\"])\n\n#行情消息接收\ndef quote_sub_th(obj,sub_port,filter = \"\"):\n socket_sub = obj.context.socket(zmq.SUB)\n #socket_sub.RCVTIMEO=7000 #ZMQ超時設定\n socket_sub.connect(\"tcp://127.0.0.1:%s\" % sub_port)\n socket_sub.setsockopt_string(zmq.SUBSCRIBE,filter)\n while(True):\n message = (socket_sub.recv()[:-1]).decode(\"utf-8\")\n index = re.search(\":\",message).span()[1] # filter\n message = message[index:]\n message = json.loads(message)\n #for message in messages:\n if(message[\"DataType\"]==\"REALTIME\"):\n OnRealTimeQuote(message[\"Quote\"])\n elif(message[\"DataType\"]==\"GREEKS\"):\n OnGreeks(message[\"Quote\"])\n elif(message[\"DataType\"]==\"TICKS\" or message[\"DataType\"]==\"1K\" or message[\"DataType\"]==\"DK\" ):\n #print(\"@@@@@@@@@@@@@@@@@@@@@@@\",message)\n strQryIndex = \"\"\n while(True):\n s_history = obj.GetHistory(g_QuoteSession, message[\"Symbol\"], message[\"DataType\"], message[\"StartTime\"], message[\"EndTime\"], strQryIndex)\n historyData = s_history[\"HisData\"]\n if len(historyData) == 0:\n break\n\n last = \"\"\n for data in historyData:\n last = data\n #print(\"歷史行情:Time:%s, Volume:%s, QryIndex:%s\" % (data[\"Time\"], data[\"Volume\"], data[\"QryIndex\"]))\n \n strQryIndex = last[\"QryIndex\"]\n \n return\n\n\ndef main():\n\n global g_QuoteZMQ\n global g_QuoteSession\n\n #登入(與 TOUCHANCE zmq 連線用,不可改)\n g_QuoteZMQ = QuoteAPI(\"ZMQ\",\"8076c9867a372d2a9a814ae710c256e2\")\n q_data = g_QuoteZMQ.Connect(\"51237\")\n print(\"q_data=\",q_data)\n\n if q_data[\"Success\"] != \"OK\":\n print(\"[quote]connection failed\")\n return\n\n g_QuoteSession = q_data[\"SessionKey\"]\n\n\n #查詢指定合约訊息\n quoteSymbol = \"TC.F.TWF.FITX.HOT\"\n #print(\"查詢指定合約:\",g_QuoteZMQ.QueryInstrumentInfo(g_QuoteSession, quoteSymbol))\n #查詢指定類型合約列表\n #期貨:Fut\n #期權:Opt\n #證券:Sto\n #print(\"查詢合約:\",g_QuoteZMQ.QueryAllInstrumentInfo(g_QuoteSession,\"Fut\"))\n\n#####################################################################行情################################################\n #建立一個行情線程\n t2 = threading.Thread(target = quote_sub_th,args=(g_QuoteZMQ,q_data[\"SubPort\"],))\n t2.start()\n\n #資料週期\n type = \"DK\"\n #起始時間\n StrTim = '2021010100'\n #結束時間\n EndTim = '2021031700'\n #資料頁數\n QryInd = '0'\n\n #訂閱歷史資料\n SubHis = g_QuoteZMQ.SubHistory(g_QuoteSession,quoteSymbol,type,StrTim,EndTim)\n print(\"訂閱歷史資料:\",SubHis)\n #等待回補\n #獲取回補的資料\n i = 0\n while(1): #等待訂閱回補\n i=i+1\n time.sleep(10)\n QPong = g_QuoteZMQ.Pong(g_QuoteSession)\n print(\"第\"+str(i*10)+\"秒,Pong:\",QPong)\n HisData = g_QuoteZMQ.GetHistory(g_QuoteSession, quoteSymbol, type, StrTim, EndTim, QryInd)\n if (len(HisData['HisData']) != 0):\n print(\"回補成功\")\n i = 0\n break\n print(\"取得歷史資料:\", HisData)\n f = open(\"歷史資料(DK).txt\", 'w')\n f.close()\n while (1): # 獲取訂閱成功的全部歷史資料並另存\n i = i + 1\n HisData = g_QuoteZMQ.GetHistory(g_QuoteSession, quoteSymbol, type, StrTim, EndTim, QryInd)\n print(HisData['HisData'][0])\n f = open(\"歷史資料(DK).txt\", 'a')\n for key in HisData['HisData'][0]:\n f.write(key + \":\" + HisData['HisData'][0][key] + \",\")\n f.write('\\n')\n QryInd = str(int(QryInd) + 1)\n time.sleep(1)\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5197110176086426, "alphanum_fraction": 0.5373017191886902, "avg_line_length": 31.81958770751953, "blob_id": "2d2a88b363192856a13a2bead391c6f7e75ab6a4", "content_id": "2984d58364339f728654d5fc7da3596b4d9918d1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6901, "license_type": "permissive", "max_line_length": 123, "num_lines": 194, "path": "/trade_sample.py", "repo_name": "pride829/TCPY", "src_encoding": "UTF-8", "text": "import time\nfrom tcoreapi_mq import * \nimport tcoreapi_mq\nimport threading\n\ng_TradeZMQ = None\ng_TradeSession = \"\"\nReportID=\"\"\n\n#已登入資金帳號變更\ndef OnGetAccount(account):\n print(account[\"BrokerID\"])\n\n#實時委託回報消息\ndef OnexeReport(report):\n global ReportID\n print(\"OnexeReport:\", report[\"ReportID\"])\n ReportID=report[\"ReportID\"]\n return None\n\n#實時成交回報回補\ndef RtnFillReport(report):\n print(\"RtnFillReport:\", report[\"ReportID\"])\n\n#查詢當日歷史委託回報回補\ndef ShowEXECUTIONREPORT(ZMQ,SessionKey,reportData):\n if reportData[\"Reply\"] == \"RESTOREREPORT\":\n Orders = reportData[\"Orders\"]\n if len(Orders) == 0:\n return\n last = \"\"\n for data in Orders:\n last = data\n print(\"查詢回報\",data)\n reportData = g_TradeZMQ.QryReport(SessionKey,last[\"QryIndex\"])\n ShowEXECUTIONREPORT(g_TradeZMQ,SessionKey,reportData)\n\n#查詢當日歷史委託成交回補\ndef ShowFillReport(ZMQ,SessionKey,reportData):\n if reportData[\"Reply\"] == \"RESTOREFILLREPORT\":\n Orders = reportData[\"Orders\"]\n if len(Orders) == 0:\n return\n\n last = \"\"\n for data in Orders:\n last = data\n print(\"查詢成交回報\",data)\n reportData = g_TradeZMQ.QryFillReport(SessionKey,last[\"QryIndex\"])\n ShowFillReport(g_TradeZMQ,SessionKey,reportData)\n#查詢部位消息回補\ndef ShowPOSITIONS(ZMQ,SessionKey,AccountMask,positionData):\n if positionData[\"Reply\"] == \"POSITIONS\":\n position = positionData[\"Positions\"]\n if len(position) == 0:\n return\n\n last = \"\"\n for data in position:\n last = data\n print(\"部位:\" + data[\"Symbol\"])\n\n positionData = g_TradeZMQ.QryPosition(SessionKey,AccountMask,last[\"QryIndex\"])\n ShowPOSITIONS(g_TradeZMQ,SessionKey,AccountMask,positionData)\n\n\n#交易消息接收\ndef trade_sub_th(obj,sub_port,filter = \"\"):\n socket_sub = obj.context.socket(zmq.SUB)\n #socket_sub.RCVTIMEO=5000 #ZMQ超時設定\n socket_sub.connect(\"tcp://127.0.0.1:%s\" % sub_port)\n socket_sub.setsockopt_string(zmq.SUBSCRIBE,filter)\n while True:\n message = socket_sub.recv()\n if message:\n message = json.loads(message[:-1])\n #print(\"in trade message\",message)\n if(message[\"DataType\"] == \"ACCOUNTS\"):\n for i in message[\"Accounts\"]:\n OnGetAccount(i)\n elif(message[\"DataType\"] == \"EXECUTIONREPORT\"):\n OnexeReport(message[\"Report\"])\n elif(message[\"DataType\"] == \"FILLEDREPORT\"):\n RtnFillReport(message[\"Report\"])\n\ndef main():\n\n global g_TradeZMQ\n global g_TradeSession\n\n #登入(與 TOUCHANCE zmq 連線用,不可改)\n g_TradeZMQ = TradeAPI(\"ZMQ\",\"8076c9867a372d2a9a814ae710c256e2\")\n t_data = g_TradeZMQ.Connect(\"51207\")\n print(t_data)\n\n if t_data[\"Success\"] != \"OK\":\n print(\"[trade]connection failed\")\n return\n\n g_TradeSession = t_data[\"SessionKey\"]\n\n#######################################################################交易##################################################\n #建立一個交易線程\n t1 = threading.Thread(target = trade_sub_th,args=(g_TradeZMQ,t_data[\"SubPort\"],))\n t1.start()\n #查詢已登入資金帳號\n accountInfo = g_TradeZMQ.QryAccount(g_TradeSession)\n print(\"查詢已登入的資金帳號:\",accountInfo)\n\n strAccountMask=\"\"\n if accountInfo != None:\n arrInfo = accountInfo[\"Accounts\"]\n if len(arrInfo) != 0:\n #print(\"@@@@@@@@@@@:\",arrInfo[0],\"\\n\")\n strAccountMask = arrInfo[0][\"AccountMask\"]\n print(strAccountMask)\n\n #查詢委託紀錄\n reportData = g_TradeZMQ.QryReport(g_TradeSession,\"\")\n print('查詢所有回報:',reportData)\n ShowEXECUTIONREPORT(g_TradeZMQ,g_TradeSession,reportData)\n fillReportData = g_TradeZMQ.QryFillReport(g_TradeSession,\"\")\n print('查詢成交回報:', fillReportData)\n ShowFillReport(g_TradeZMQ,g_TradeSession,fillReportData)\n\n #查詢資金\n if strAccountMask !=\"\":\n print(\"查詢資金帳號:\",g_TradeZMQ.QryMargin(g_TradeSession,strAccountMask))\n \n #查詢持倉\n positionData = g_TradeZMQ.QryPosition(g_TradeSession,strAccountMask,\"\")\n print('查詢持倉部位:',positionData)\n ShowPOSITIONS(g_TradeZMQ,g_TradeSession,strAccountMask,positionData)\n\n #下單\n orders_obj = {\n \"Symbol\":\"TC.F.TWF.FITX.HOT\",\n \"BrokerID\":arrInfo[0]['BrokerID'],\n \"Account\":arrInfo[0]['Account'],\n \"Price\":\"15000\",\n \"TimeInForce\":\"1\",\n \"Side\":\"1\",\n \"OrderType\":\"2\",\n \"OrderQty\":\"1\",\n \"PositionEffect\":\"0\"\n }\n s_order = g_TradeZMQ.NewOrder(g_TradeSession,orders_obj)\n print('下單結果:',s_order)\n\n \"\"\"\n if s_order['Success']==\"OK\":\n print(\"下單成功\")\n elif s_order['ErrCode']==\"-10\":\n print(\"unknow error\")\n elif s_order['ErrCode']==\"-11\":\n print(\"買賣別錯誤\")\n elif s_order['ErrCode']==\"-12\":\n print(\"複式單商品代碼解析錯誤 \")\n elif s_order['ErrCode']==\"-13\":\n print(\"下單帳號,不可下此交易所商品\")\n elif s_order['ErrCode']==\"-14\":\n print(\"下單錯誤,不支持的 價格 或 OrderType 或 TimeInForce\")\n elif s_order['ErrCode']==\"-15\":\n print(\"不支援證券下單\")\n elif s_order['ErrCode']==\"-20\":\n print(\"未建立連線\")\n elif s_order['ErrCode']==\"-22\":\n print(\"價格的 TickSize 錯誤\")\n elif s_order['ErrCode']==\"-23\":\n print(\"下單數量超過該商品的上下限 \")\n elif s_order['ErrCode']==\"-24\":\n print(\"下單數量錯誤 \")\n elif s_order['ErrCode']==\"-25\":\n print(\"價格不能小於和等於 0 (市價類型不會去檢查) \")\n \"\"\"\n\n #改單\n reporders_obj={\n \"ReportID\":\"4094755221B\",\n \"ReplaceExecType\":\"0\",\n \"Price\":\"16500\"\n }\n reorder=g_TradeZMQ.ReplaceOrder(g_TradeSession,reporders_obj)\n\n #刪單\n print(\"%%%%%%%%%%%%%%%%%%%%%%%%%\",reorder)\n canorders_obj={\n \"ReportID\":\"4094755221B\",\n }\n canorder=g_TradeZMQ.CancelOrder(g_TradeSession,canorders_obj)\n print(\"%%%%%%%%%%%%%%%%%%%%%%%%%\",canorder)\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5449976325035095, "alphanum_fraction": 0.5694989562034607, "avg_line_length": 33.983516693115234, "blob_id": "16114be82fdc07e7bd09e1fa375fabc2bc42841e", "content_id": "fcd2e93f276286b22e7a100145ac502ca5c98c0a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6903, "license_type": "permissive", "max_line_length": 153, "num_lines": 182, "path": "/backtest_sample.py", "repo_name": "pride829/TCPY", "src_encoding": "UTF-8", "text": "import time\nfrom tcoreapi_mq import *\nimport tcoreapi_mq\nimport threading\n\ng_QuoteZMQ = None\ng_QuoteSession = \"\"\nBuyerParam = {\n \"Money\":\"2000000\",\n \"HoldValue\":\"0\",\n \"ShortAverage\":\"0\",\n \"LongAverage\":\"0\",\n \"Side\":\"0\",\n \"TradeTimes\":0\n}\n\nShoAvg = [0,0,0,0,0]\nLonAvg = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n\n#實時行情回補\ndef OnRealTimeQuote(symbol):\n print(\"商品:\", symbol[\"Symbol\"], \"成交價:\",symbol[\"TradingPrice\"], \"開:\", symbol[\"OpeningPrice\"], \"高:\", symbol[\"HighPrice\"], \"低:\", symbol[\"LowPrice\"])\n\n#行情消息接收\ndef quote_sub_th(obj,sub_port,filter = \"\"):\n socket_sub = obj.context.socket(zmq.SUB)\n #socket_sub.RCVTIMEO=7000 #ZMQ超時設定\n socket_sub.connect(\"tcp://127.0.0.1:%s\" % sub_port)\n socket_sub.setsockopt_string(zmq.SUBSCRIBE,filter)\n while(True):\n message = (socket_sub.recv()[:-1]).decode(\"utf-8\")\n index = re.search(\":\",message).span()[1] # filter\n message = message[index:]\n message = json.loads(message)\n #for message in messages:\n if(message[\"DataType\"]==\"REALTIME\"):\n OnRealTimeQuote(message[\"Quote\"])\n elif(message[\"DataType\"]==\"GREEKS\"):\n OnGreeks(message[\"Quote\"])\n elif(message[\"DataType\"]==\"TICKS\" or message[\"DataType\"]==\"1K\" or message[\"DataType\"]==\"DK\" ):\n #print(\"@@@@@@@@@@@@@@@@@@@@@@@\",message)\n strQryIndex = \"\"\n while(True):\n s_history = obj.GetHistory(g_QuoteSession, message[\"Symbol\"], message[\"DataType\"], message[\"StartTime\"], message[\"EndTime\"], strQryIndex)\n historyData = s_history[\"HisData\"]\n if len(historyData) == 0:\n break\n\n last = \"\"\n for data in historyData:\n last = data\n #print(\"歷史行情:Time:%s, Volume:%s, QryIndex:%s\" % (data[\"Time\"], data[\"Volume\"], data[\"QryIndex\"]))\n\n strQryIndex = last[\"QryIndex\"]\n return\n\ndef AverageHandler(Price):\n global ShoAvg,LonAvg,BuyerParam\n for i in range(4):\n ShoAvg[i] = ShoAvg[i+1]\n ShoAvg[4] = Price\n if (ShoAvg[0] != 0):\n intAvg = 0\n for i in range(5):\n intAvg = intAvg + ShoAvg[i]\n intAvg = int(round(float(intAvg)/5))\n BuyerParam['ShortAverage'] = str(intAvg)\n for i in range(19):\n LonAvg[i] = LonAvg[i+1]\n LonAvg[19] = Price\n if (LonAvg[0] != 0):\n intAvg = 0\n for i in range(20):\n intAvg = intAvg +LonAvg[i]\n intAvg = int(round(float(intAvg)/20))\n BuyerParam['LongAverage'] = str(intAvg)\n\ndef TradeHadler(Price,Kbar):\n global BuyerParam\n floatMoney = float(BuyerParam['Money'])\n intHoldValue = int(BuyerParam['HoldValue'])\n intShoAvg = int(BuyerParam['ShortAverage'])\n intLonAvg = int(BuyerParam['LongAverage'])\n intSide = int(BuyerParam['Side'])\n ValChange = floatMoney - (intHoldValue - Price)*200\n if (intHoldValue == 0):\n ValChange = floatMoney\n if (intSide == 0 and intShoAvg > intLonAvg and intLonAvg != 0):\n floatMoney = str(ValChange)\n BuyerParam['HoldValue'] = str(Price)\n BuyerParam['Side'] = '1'\n BuyerParam['TradeTimes'] = BuyerParam['TradeTimes'] + 1\n Move = \"第\"+str(Kbar)+\"根K棒,短線:\"+BuyerParam['ShortAverage']+\",長線:\"+BuyerParam['LongAverage']+\",買進一口,進場點位:\"+str(Price)+\\\n \",第\"+str(BuyerParam['TradeTimes'])+\"次進場\\n當前權益數:\"+floatMoney\n KeepNote(Move)\n elif(intSide == 1 and ValChange <= floatMoney*0.95):\n BuyerParam['Money'] = str(ValChange)\n BuyerParam['HoldValue'] = '0'\n BuyerParam['Side'] = '0'\n Move = \"第\"+str(Kbar)+\"根K棒,短線:\"+BuyerParam['ShortAverage']+\",長線:\"+BuyerParam['LongAverage']+\",停損出場,進場點位:\" + str(Price) + \\\n \",第\"+str(BuyerParam['TradeTimes'])+\"次出場\\n當前權益數:\" + BuyerParam['Money']\n KeepNote(Move)\n elif(intSide == 1 and intShoAvg <= intLonAvg):\n BuyerParam['Money'] = str(ValChange)\n BuyerParam['HoldValue'] = '0'\n GP = Price - intHoldValue\n BuyerParam['Side'] = '0'\n Move = \"第\"+str(Kbar)+\"根K棒,短線:\"+BuyerParam['ShortAverage']+\",長線:\"+BuyerParam['LongAverage']+\",策略出場,出場點位:\"+str(Price)+\\\n \",第\"+str(BuyerParam['TradeTimes'])+\"次出場\\n損益\"+str(GP)+\"點,相當於\"+str(GP*200)+\"元,當前權益數:\"+BuyerParam['Money']\n KeepNote(Move)\n\ndef KeepNote(Note):\n f = open(\"績效紀錄.txt\", 'a')\n f.write(Note+\"\\n\")\n f.close()\n\ndef main():\n\n global g_QuoteZMQ\n global g_QuoteSession\n\n #登入(與 TOUCHANCE zmq 連線用,不可改)\n g_QuoteZMQ = QuoteAPI(\"ZMQ\",\"8076c9867a372d2a9a814ae710c256e2\")\n q_data = g_QuoteZMQ.Connect(\"51237\")\n print(\"q_data=\",q_data)\n\n if q_data[\"Success\"] != \"OK\":\n print(\"[quote]connection failed\")\n return\n\n g_QuoteSession = q_data[\"SessionKey\"]\n\n #查詢指定合约訊息\n quoteSymbol = \"TC.F.TWF.FITX.HOT\"\n #print(\"查詢指定合約:\",g_QuoteZMQ.QueryInstrumentInfo(g_QuoteSession, quoteSymbol))\n #查詢指定類型合約列表\n #期貨:Fut\n #期權:Opt\n #證券:Sto\n #print(\"查詢合約:\",g_QuoteZMQ.QueryAllInstrumentInfo(g_QuoteSession,\"Fut\"))\n\n#####################################################################行情################################################\n #建立一個行情線程\n t2 = threading.Thread(target = quote_sub_th,args=(g_QuoteZMQ,q_data[\"SubPort\"],))\n t2.start()\n\n #資料週期\n type = \"1K\"\n #起始時間\n StrTim = '2020030100'\n #結束時間\n EndTim = '2021042200'\n #資料頁數\n QryInd = '0'\n\n #訂閱歷史資料\n SubHis = g_QuoteZMQ.SubHistory(g_QuoteSession,quoteSymbol,type,StrTim,EndTim)\n print(\"訂閱歷史資料:\",SubHis)\n while(1): #等待訂閱回補\n HisData = g_QuoteZMQ.GetHistory(g_QuoteSession, quoteSymbol, type, StrTim, EndTim, QryInd)\n if (len(HisData['HisData']) != 0):\n print(\"回補成功\")\n break\n time.sleep(1)\n\n #開始使用獲取的歷史資料進行回測\n level = 0\n while (1):\n global BuyerParam\n HisData = g_QuoteZMQ.GetHistory(g_QuoteSession, quoteSymbol, type, StrTim, EndTim, QryInd)\n for i in range(50):\n Kbar = level+i+1\n OrdPrice = int(HisData['HisData'][i]['Close'])\n AverageHandler(OrdPrice)\n print(\"第\" + str(Kbar) +\"根K棒,收盤價:\", OrdPrice)\n print(\"短線:\"+BuyerParam['ShortAverage']+\",長線:\"+BuyerParam['LongAverage'])\n TradeHadler(OrdPrice,Kbar)\n QryInd = str(int(QryInd) + 50)\n level = level + 50\n\nif __name__ == '__main__':\n main()\n" } ]
4
masQelec/plugin.video.netflix
https://github.com/masQelec/plugin.video.netflix
62e4f6416c0f9bf547a8a5980de9747f677236b6
90ebf3343ebeaf6b790fdb1048d78fe5bf127dde
e0934ca26ac6c3f8816952ceafb3c84ace34d6aa
refs/heads/master
2023-02-09T17:07:36.200308
2021-01-04T01:36:55
2021-01-04T01:36:55
288,575,867
0
0
MIT
2020-08-18T22:17:06
2020-11-26T21:33:10
2021-01-04T01:36:56
Python
[ { "alpha_fraction": 0.6434136033058167, "alphanum_fraction": 0.6466005444526672, "avg_line_length": 26.417476654052734, "blob_id": "0bb1c8eac19775983e0df6d9cf8e7f872f29d881", "content_id": "dd89d6489975c415e444c52e3d618e0e0786a729", "detected_licenses": [ "MIT", "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2824, "license_type": "permissive", "max_line_length": 97, "num_lines": 103, "path": "/tests/xbmcvfs.py", "repo_name": "masQelec/plugin.video.netflix", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n Copyright (C) 2019 Dag Wieers (@dagwieers) <[email protected]>\n This file implements the Kodi xbmcvfs module, either using stubs or alternative functionality\n\n SPDX-License-Identifier: GPL-3.0-only\n See LICENSES/GPL-3.0-only.md for more information.\n\"\"\"\nimport os\nimport shutil\n\n\ndef File(path, flags='r'):\n \"\"\"A reimplementation of the xbmcvfs File() function\"\"\"\n try:\n return open(path, flags)\n except IOError:\n from io import StringIO\n return StringIO('')\n\n\ndef Stat(path):\n \"\"\"A reimplementation of the xbmcvfs Stat() function\"\"\"\n\n class stat: # pylint: disable=too-few-public-methods\n \"\"\"A reimplementation of the xbmcvfs stat class\"\"\"\n\n def __init__(self, path):\n \"\"\"The constructor xbmcvfs stat class\"\"\"\n self._stat = os.stat(path)\n\n def st_mtime(self):\n \"\"\"The xbmcvfs stat class st_mtime method\"\"\"\n return self._stat.st_mtime\n\n return stat(path)\n\n\ndef copy(source, destination):\n \"\"\"A reimplementation of the xbmcvfs copy() function\"\"\"\n return shutil.copyfile(source, destination)\n\n\ndef delete(path):\n \"\"\"A reimplementation of the xbmcvfs delete() function\"\"\"\n\n try:\n os.remove(path)\n except OSError:\n pass\n\n\ndef exists(path):\n \"\"\"A reimplementation of the xbmcvfs exists() function\"\"\"\n return os.path.exists(path)\n\n\ndef listdir(path):\n \"\"\"A reimplementation of the xbmcvfs listdir() function\"\"\"\n files = []\n dirs = []\n for f in os.listdir(path):\n if os.path.isfile(f):\n files.append(f)\n if os.path.isdir(f):\n dirs.append(f)\n return dirs, files\n\n\ndef mkdir(path):\n \"\"\"A reimplementation of the xbmcvfs mkdir() function\"\"\"\n return os.mkdir(path)\n\n\ndef mkdirs(path):\n \"\"\"A reimplementation of the xbmcvfs mkdirs() function\"\"\"\n return os.makedirs(path)\n\n\ndef rename(file, newFileName): # pylint: disable=redefined-builtin\n \"\"\"A reimplementation of the xbmcvfs rename() function\"\"\"\n return os.rename(file, newFileName)\n\n\ndef rmdir(path):\n \"\"\"A reimplementation of the xbmcvfs rmdir() function\"\"\"\n return os.rmdir(path)\n\n\ndef makeLegalFilename(filename):\n \"\"\"A reimplementation of the xbmc makeLegalFilename() function\"\"\"\n return os.path.basename(filename)\n\n\ndef translatePath(path):\n \"\"\"A stub implementation of the xbmc translatePath() function\"\"\"\n if path.startswith('special://home'):\n return path.replace('special://home', os.path.join(os.getcwd(), 'test'))\n if path.startswith('special://profile'):\n return path.replace('special://profile', os.path.join(os.getcwd(), 'tests/usedata'))\n if path.startswith('special://userdata'):\n return path.replace('special://userdata', os.path.join(os.getcwd(), 'tests/userdata'))\n return path\n" } ]
1
dtrckd/cython-test
https://github.com/dtrckd/cython-test
d760e5067c5bb7b23dd65d9a1c1fb663020bdc02
b68d3c8be371d0915f750b5b8485f151e859a007
303c7d2fd5d87b3380aabb6bc110e3cb2a0920b3
refs/heads/master
2020-03-18T09:48:42.357606
2019-08-31T09:54:58
2019-08-31T09:54:58
134,581,147
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.44398340582847595, "alphanum_fraction": 0.5020747184753418, "avg_line_length": 16.14285659790039, "blob_id": "d99b3e243481286d50513e651d256b9c751a08de", "content_id": "06e5fb85b986c7d17ac479305e4cb18abec592cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 241, "license_type": "no_license", "max_line_length": 44, "num_lines": 14, "path": "/main.py", "repo_name": "dtrckd/cython-test", "src_encoding": "UTF-8", "text": "from test import test1\n\nimport numpy as np\n\n\nif __name__ == '__main__':\n\n #a = np.ones(((10,3)), dtype=int)\n a = np.array(([1,3,3],[1,4,3],[1,3,4]))\n\n print(a)\n b = test1(a, len(a))\n print(b) # is a memory view\n print(a)\n\n" }, { "alpha_fraction": 0.7605633735656738, "alphanum_fraction": 0.7605633735656738, "avg_line_length": 17.933332443237305, "blob_id": "65dee3a45f4056c30dab8d30481e8d4c2ea97825", "content_id": "ac037e551aa3109f50994456901a04b9bb3c3220", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 284, "license_type": "no_license", "max_line_length": 41, "num_lines": 15, "path": "/setup.py", "repo_name": "dtrckd/cython-test", "src_encoding": "UTF-8", "text": "from distutils.core import setup\nfrom distutils.extension import Extension\nfrom Cython.Build import cythonize\nfrom Cython.Distutils import build_ext\n\nextensions = [\n\n\tExtension(\"test\", [\"test.pyx\"])\n\n]\n\nsetup(\n\tcmdclass={'build_ext': build_ext},\n\text_modules=cythonize(extensions),\n)\n" }, { "alpha_fraction": 0.7222222089767456, "alphanum_fraction": 0.7333333492279053, "avg_line_length": 11.714285850524902, "blob_id": "add34063983d42e5ff467de6865f5f0179a787b4", "content_id": "e8b8b4262795bba013c8138c0c174944dba04ee4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 90, "license_type": "no_license", "max_line_length": 37, "num_lines": 7, "path": "/Makefile", "repo_name": "dtrckd/cython-test", "src_encoding": "UTF-8", "text": "\ndefault:cython\n\ncython:\n\tpython3 setup.py build_ext --inplace\n\nhtml:\n\tcython test.pyx -a\n" } ]
3
derrick0714/web_search_engine
https://github.com/derrick0714/web_search_engine
40861e0bfeb37e8a972488d941edc4f7ba8741c3
7dcb83dd408ac34687bb2407ff337ac9f64036d8
a23852d6279ca70d8623cb8f8bbedda03187351a
refs/heads/master
2016-09-05T19:13:51.316127
2013-05-28T05:08:48
2013-05-28T05:08:54
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5181623697280884, "alphanum_fraction": 0.5288461446762085, "avg_line_length": 26.393939971923828, "blob_id": "bed05a5849a7b54d233395384eb0c76bf7f423ac", "content_id": "cd6b29093eda9f80a69ff3a608d8580b304c2d98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 936, "license_type": "no_license", "max_line_length": 62, "num_lines": 33, "path": "/crawling/strategies/linksextractor.py", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "'''\nCreated on Feb 7, 2013\n\n@author: Adam57\n'''\nimport htmllib\nimport formatter\nimport urllib\n\nclass LinksExtractor(htmllib.HTMLParser):\n \n def __init__(self,formatter):\n htmllib.HTMLParser.__init__(self, formatter)\n \"\"\"for storing the hyperlinks\"\"\"\n self.links = []\n \"\"\"override handler of <A..>...</A> tags\"\"\"\n def start_a(self,attrs):\n if len(attrs) > 0 :\n for attr in attrs :\n if attr[0]==\"href\" :\n self.links.append(attr[1])\n def get_links(self):\n return self.links\n \nif __name__ == \"__main__\":\n \n format = formatter.NullFormatter()\n htmlparser = LinksExtractor(format) \n data = urllib.urlopen(\"http://cis.poly.edu/index.htm\")\n htmlparser.feed(data.read())\n htmlparser.close()\n links = htmlparser.get_links()\n print(links)\n \n \n \n\n " }, { "alpha_fraction": 0.5747460126876831, "alphanum_fraction": 0.5805515050888062, "avg_line_length": 19.909090042114258, "blob_id": "f0ff7f3e71b181121520a8bbd3d4a28e252a50f7", "content_id": "819e72e1e9d19565710e5683fab448a0170cc568", "detected_licenses": [ "Apache-2.0", "CC-BY-3.0" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 689, "license_type": "permissive", "max_line_length": 121, "num_lines": 33, "path": "/crawling/www/commit.php", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "<?php\n\n$host = \"localhost\"; \n$user = \"web_search\"; \n$pass = \"dengxu_wangqi\"; \n$db = \"web_search_engine\";\n\n\n$conn = mysql_connect($host, $user, $pass);\n\nif (!$conn)\n{\n echo \"Could not connect to server\\n\";\n exit();\n} \n\nmysql_select_db($db,$conn);\n\n$sql = \"UPDATE `configuation` SET `seed_keywords`= '\".$_GET[\"key_words\"].\"',`downloader_thread` ='\".$_GET[\"down_thread\"].\n\"',`parser_thread` ='\".$_GET[\"parse_thread\"].\"',`seed_resultnum` ='\".$_GET[\"result_count\"].\"', `is_start` = 1, \n`key_word_start`=0,`status_start` = 0 WHERE id = 1\";\n\n\n$result = mysql_query($sql);\n\n\nif (!$result) \n{\n echo 'Could not run query: ' . mysql_error();\n exit;\n}\nheader(\"Location: ./realtime.html\")\n?>" }, { "alpha_fraction": 0.5939887762069702, "alphanum_fraction": 0.6128374934196472, "avg_line_length": 24.828947067260742, "blob_id": "61bd9a7b901c4e0427dcc91329437767d366517c", "content_id": "7cb8b659f610a7be6467421784eee9d3fe846ff0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1963, "license_type": "no_license", "max_line_length": 171, "num_lines": 76, "path": "/crawling/models/html.py", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "\"\"\"\nCreated on Feb 4, 2013\n\n@author: derrick\n\n\"\"\"\nimport hashlib\nfrom urlparse import urlparse\n\n\n\"\"\" URL model :http://www.webreference.com/html/tutorial2/2.html\nhttp://WebReference.com:80/html/tutorial2/2.html?query\n|--| |--------------||-||--------------------||----|\n 1 2 3 4 5\n\n 1:scheme name :file, ftp, gopher, hdl, http, https, imap, mailto, mms, news, nntp, prospero, rsync, rtsp, rtspu, sftp, shttp, sip, sips, snews, svn, svn+ssh, telnet, wais\n 2:hostname\n 3:port\n 4:path\n 5:query_string\n\"\"\"\n\nclass Html(object):\n\n\tdef __init__(self, url):\n\t\t\"\"\" related to url\"\"\"\n\t\tself._url \t\t\t= url\n\t\tself._scheme \t\t= \"\"\n\t\tself._hostname\t\t= \"\" \t#domain name\n\t\tself._hostname_hash\t= \"\"\n\t\tself._port\t\t\t= 0\n\t\tself._path\t\t\t= \"\"\n\t\tself._query_string\t= \"\"\n\t\tself._md5\t\t\t= \"\"\n\t\tself._id \t\t\t= 0 #increase at engine.finishdownload\n\t\tself._depth\t\t\t= 0 #increase at parser parse_page\n\t\tself._parent\t\t= -1 #increase at parser parse_page\n\n\t\tself._parent_url\t= \"\" # for test\n\n\n\t\t\"\"\" analyse url \"\"\"\n\t\tself.parse_url()\n\n\t\t\"\"\" related to html data\"\"\"\n\t\tself._return_code\t= \"\"\t#html return code\n\t\tself._data\t\t\t= \"\"\t#html data\n\t\tself._data_size\t\t= 0\t \t#html size\n\t\tself._crawled_time\t= 0\t\t#html download time\n\t\t\n\n\tdef update_url(self,url):\n\t\tself._url \t\t\t= url\n\t\tself.parse_url()\n\n\tdef parse_url(self):\n\t\t\n\t\t\n\t\tparse_result \t\t= urlparse(self._url)\n\t\tself._scheme \t\t= parse_result.scheme\n\t\tself._hostname\t\t= parse_result.hostname\n\t\tself._homesiteurl\t= str(parse_result.scheme) + \"://\" + str(parse_result.hostname)\n\t\t#self._hostname_hash\t= hashlib.sha256( parse_result.hostname )\n\t\t#self._port\t\t\t= parse_result.port\n\t\tself._path\t\t\t= parse_result.path\n\t\tself._query_string\t= parse_result.query\n\t\tmd5 = hashlib.md5()\n\t\tmd5.update(self._url)\n\t\tself._md5 = md5.hexdigest()\t\n\t\t#print(self._md5)\n\t\t\n\t\t\n\t\t\nif __name__==\"__main__\":\n\thtml = Html(\"http://www.nba.com/standings/team_record_comparison/conferenceNew_Std_Cnf.html\")\n\tprint html._homesiteurl\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5409091114997864, "avg_line_length": 14.714285850524902, "blob_id": "caf23ce67dc19059d9256a3073136a3c54c6157e", "content_id": "a701a152f11e55bddbde59c7e36a6025af88cb51", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 220, "license_type": "no_license", "max_line_length": 43, "num_lines": 14, "path": "/crawling/strategies/cgihandler.py", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "'''\nCreated on Feb 13, 2013\n\n@author: Adam57\n'''\n\nclass CGIHandler(object):\n\n def FindCGI(self, html_task):\n \n if html_task._url.find(\".cgi\")==-1:\n return False\n else:\n return True\n" }, { "alpha_fraction": 0.6814701557159424, "alphanum_fraction": 0.6914241909980774, "avg_line_length": 19.10769271850586, "blob_id": "f7a4e54b5a33f679b1ce887cd08f9b161a553cd6", "content_id": "843cc80433d2dd077bdc10473906d00bb030e7a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1306, "license_type": "no_license", "max_line_length": 93, "num_lines": 65, "path": "/newyorktimes/src/searching/searching_algorim.h", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "#ifndef __SEARCHING_ALGORIM_H__\n#define __SEARCHING_ALGORIM_H__\n#include <iostream>\n#include <fstream>\n#include <string>\n#include \"models/Docmap.h\"\n#include \"models/WordMap.h\"\n#include \"result_ctrl.h\"\n#include \"utility/gzip.h\"\n#include <vector>\n#include \"4ops.h\"\n#include \"parser/parser.h\"\n\n//#include \"vbyte.h\"\n\nusing namespace std;\n\nstruct TAGS\n{\n\tstring word;\n\tint count;\n\tTAGS()\n\t{\n\t\tword =\"\";\n\t\tcount = 0;\n\t}\n};\n\nclass SearchingAlgorim\n{\npublic:\n\tSearchingAlgorim();\n\t~SearchingAlgorim();\npublic:\n\tvoid init_data();\n\tchar* init_buffer_from_file(string file_name,int& size);\n\tvoid do_searching(char* words);\n\tvoid sort(STRU_RESULT* array, int left , int right,std::string type);\n\tchar* get_result();\n\tbool get_one_word(char* source ,int& pos,string& str);\n\tvoid get_around_text(char* html, int len,int tartget_pos,string& title,string& around_text);\n\tbool isInThisLocation(string askLocation, string sourceLocation);\n\tvoid sort_tags(TAGS* arr,int left, int right);\n\nprivate:\n\tDocMap \t\t_doc_map;\n\tWordMap\t\t_word_map;\n\tResultCrtl\t_result;\n\tfloat \t\tk1;\n\tfloat \t\tb;\n\tint \td_agv;\n\tint \t\tN;\n\tSTRU_RESULT result_array[10];\n\tint \t\tresult_count;\n\tchar\t\tresult[1024];\n\tTAGS \t\ttags[200];\npublic:\n\tint \t\t_whole_time;\n\tint \t\t_searching_time;\n\tmap<int,string> _word_map2;\n\n};\n\n\n#endif //__SEARCHING_ALGORIM_H__" }, { "alpha_fraction": 0.6038709878921509, "alphanum_fraction": 0.6206451654434204, "avg_line_length": 18.350000381469727, "blob_id": "e8b52ec680a1d070a8efadc7871bc4c9fbccfada", "content_id": "efd3a1db27653bba0885dddf3eae1643abfbc95d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 775, "license_type": "no_license", "max_line_length": 86, "num_lines": 40, "path": "/crawling/models/safe_loop_array.py", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "\"\"\"\nCreated on Feb 12, 2013\n\n@author: derrick\n\n\"\"\"\n\nfrom threading import Condition\nfrom threading import Lock\n\nclass SafeLoopArray(object):\n\tdef __init__(self , data, lengh = 10):\n\t\tself._lengh = lengh\n\t\tself._data\t= []\n\t\tself._index = 0;\n\t\tself._lock = Condition(Lock())\n\n\t\tfor i in range(lengh):\n\t\t\tself._data.append(data)\n\t\t\t\n\n\tdef add(self , data):\n\t\tself._lock.acquire()\n\t\ttry:\n\t\t\ti = self._index%self._lengh\n\t\t\t#print \"self._lengh = {0},self._index={1},i={2}\".format(self._lengh,self._index, i)\n\t\t\tself._data[i] = data\n\t\t\tself._index = self._index+1\n\t\tfinally:\n\t\t\tself._lock.release()\n\n\tdef get(self , pos):\n\t\tif (pos >= self._lengh):\n\t\t\tprint(\"out of range\")\n\t\t\treturn None\n\t\tself._lock.acquire()\n\t\ttry:\n\t\t\treturn self._data[pos]\n\t\tfinally:\n\t\t\tself._lock.release()\n\n" }, { "alpha_fraction": 0.5297157764434814, "alphanum_fraction": 0.5361757278442383, "avg_line_length": 14.5, "blob_id": "f10a01683e53fbfc75712b52a7be3886667e9881", "content_id": "54f63cdc1666cbc7881907d8ccc04d438c75fe47", "detected_licenses": [ "Apache-2.0", "CC-BY-3.0" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 774, "license_type": "permissive", "max_line_length": 49, "num_lines": 50, "path": "/crawling/www/test.php", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "<?php\n$host = \"localhost\"; \n$user = \"web_search\"; \n$pass = \"dengxu_wangqi\"; \n$db = \"web_search_engine\";\n\n$conn = mysql_connect($host, $user, $pass);\n\nif (!$conn)\n{\n echo \"Could not connect to server\\n\";\n exit();\n} \n\nmysql_select_db($db,$conn);\n\n$sql = \"SELECT * FROM `status` WHERE `id` =1\";\n\n\n$result = mysql_query($sql);\nif (!$result) {\n echo 'Could not run query: ' . mysql_error();\n exit;\n}\n#$row = mysql_fetch_row($result);\n\necho \"<table border='1'>\n<tr>\n<th>Last update time</th>\n<th>crawled pages</th>\n<th>keywords</th>\n</tr>\";\n\nwhile($row = mysql_fetch_array($result))\n {\n echo \"<tr>\";\n echo \"<td>\" . $row[2] . \"</td>\";\n echo \"<td>\" . $row[1] . \"</td>\";\n echo \"<td>\" . $row[3] . \"</td>\";\n echo \"</tr>\";\n }\necho \"</table>\";\n\n\n\n\n\nmysql_close();\n\n?>" }, { "alpha_fraction": 0.5657001733779907, "alphanum_fraction": 0.5768044590950012, "avg_line_length": 28.685184478759766, "blob_id": "167da370bd89b3db8162743e25ee2732cf106228", "content_id": "00a79fed346cc765b5f76bd104b842ca49019f2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1621, "license_type": "no_license", "max_line_length": 55, "num_lines": 54, "path": "/crawling/include/setting.py", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "'''\nCreated on Feb 2, 2013\n\n@author: Adam\n'''\n#import configparser #python3.3\nimport ConfigParser\n\n\nclass Setting(object): \n \n def load(self, path):\n self.path = path \n \n def get_section(self, section):\n #conf = configparser.ConfigParser() #python3.3\n conf = ConfigParser.ConfigParser()\n conf.read(self.path)\n return conf.items(section)\n \n def get_param(self, section, param):\n #conf = configparser.ConfigParser() #python3.3\n try:\n conf = ConfigParser.ConfigParser()\n conf.read(self.path)\n return conf.get(section,param)\n except (Exception) as e:\n raise(e)\n \n def set_param(self, section, param, new_value):\n #conf = configparser.ConfigParser() #python3.3\n conf = ConfigParser.ConfigParser()\n conf.read(self.path)\n conf.set(section, param, new_value)\n conf.write(open(self.path, \"w\"))\n \n def add_param(self, section, new_param, new_value):\n #conf = configparser.ConfigParser() #python3.3\n conf = ConfigParser.ConfigParser()\n conf.read(self.path)\n conf.set(section, new_param, new_value)\n conf.write(open(self.path, \"w\")) \n#\"c:\\\\config.ini\" \n\n \nif __name__ == \"__main__\": \n config = Setting() \n config.load(\"c:\\\\config.ini\" );\n print (config.get_section(\"log\"))\n config.set_param(\"log\", \"L1\", \"trial\") \n print (config.get_section(\"log\"))\n config.add_param(\"log\",\"L4\", \"new trial\") \n print (config.get_section(\"log\")) \n print(config.get_param(\"log\",\"L4\"))\n \n \n " }, { "alpha_fraction": 0.6517841815948486, "alphanum_fraction": 0.6620283126831055, "avg_line_length": 32.43714141845703, "blob_id": "daef7b0567c31f2d2f2c6552dcbf4b4616867635", "content_id": "04daff997eba245ce615b4f3030a804691ec131f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11714, "license_type": "no_license", "max_line_length": 218, "num_lines": 350, "path": "/crawling/core/engine.py", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "\"\"\"\nCreated on Feb 2, 2013\n\n@author: derrick\n\n\"\"\"\n#import basic lib\nfrom threading import Thread\t \nfrom time import time, sleep,localtime,strftime\nimport os\n\n#import core lib\nfrom core.downloader import Downloader\nfrom core.parser import Parser\nfrom core.searchgoogle import SearchGoogle\n\n#import auxiliary lib\nfrom include.log import Log\nfrom include.database_manager import DatabseManager\n\n#import modles\nfrom models.html import Html\nfrom models.status import Status\nfrom models.safe_queue import SafeQueue\nfrom models.safe_loop_array import SafeLoopArray\nfrom models.safe_dic import SafeDictionary\nfrom models.configuration import Configuration\n\n#include strategies\nfrom strategies.robothandler import RobotHandler\nfrom strategies.earlyvisithandler import EarlyVisitHandler\nfrom strategies.cgihandler import CGIHandler\nfrom strategies.nestlevelhandler import NestLevelHandler\nfrom strategies.schemehandler import SchemeHandler\nfrom strategies.filetypehandler import FileTypeHandler\nfrom strategies.bookmarkhandler import BookMarkHandler\nfrom strategies.urlextender import URLExtender\nfrom strategies.omitindex import OmitIndex\n\n\n\nclass Engine(object):\n\tdef __init__( self):\n\t\tself._istart\t\t= False\n\t\tself._status\t\t= Status()\n\n\t\t\"\"\"--- load config file----\"\"\"\n\t\tself._config \t\t= Configuration();\n\t\n\t\t\"\"\"--- core object ----\"\"\"\n\t\tself._downloader\t= None\n\t\tself._parser\t\t= None\n\n\t\t\"\"\"--- memory models --- \"\"\"\n\t\tself._download_pool\t= SafeQueue() #Store the html objects to be downloaded by the downloader\n\t\tself._parse_pool\t= SafeQueue() #Store the html objects to be parsed by the parser\n\t\t\n\t\t\"\"\"--- checker threads --- \"\"\"\n\t\t\"\"\"The target is the function passed in to \n\t\trun in the thread. Those two threads keep checking \n\t\tand assigning jobs to the two thread pools\"\"\"\n\t\tself._downloader_pool_checker = Thread( target=self.download_pool_checker)\n\t\tself._parse_pool_checker = Thread( target=self.parse_pool_checker)\n\t\t\n\t\t\"\"\"--- threads --- \"\"\"\n\t\tself._status_update = Thread( target=self.status_update) #every second, this thread post runtime info to remote mysql\n\n\t\t\"\"\" ---strategies--- \"\"\"\n\t\tself._earlyvisithandler\t=\tEarlyVisitHandler()\n\t\tself._robothandler \t=\tRobotHandler()\n\t\tself._cgihandler\t\t=\tCGIHandler()\n\t\tself._nestlevelhandler \t=\tNestLevelHandler()\n\t\tself._schemehandler \t=\tSchemeHandler()\n\t\tself._filetypehandler\t=\tFileTypeHandler()\n\t\tself._bookmarkhandler\t=\tBookMarkHandler()\n\t\tself._omitindex\t\t\t=\tOmitIndex()\n\t\tself._urlextender\t\t=\tURLExtender()\t\t\t\n\t\n\t\t\"\"\" ---init the path for saving data, if the folder don't exist, create it ---\"\"\"\n\t\tself._path\t\t\t= self._config._down_path+\"/\"+ strftime('%Y-%m-%d', localtime())+\"/\"+ strftime('%H-%M-%S', localtime())+\"/\"\n\t\tif not os.path.exists(self._path):\n\t\t\tos.makedirs(self._path)\n\n\t\tself._config._down_path = self._path\n\t\t\n\t\tself._keywords_links= []\n\n\t\t\"\"\" ---Mysql Manager--- \"\"\"\n\t\tself.sqlex = DatabseManager(self._config)\n\n\t\t#self.f= open(\"data.txt\", 'w')\n\n\tdef load_seeds(self):\n\t\t#load seed info from config file\t\n\t\t#print \"load_seeds 1\"\n\t\t#load seed from \n\t\tcontacter = SearchGoogle(self._config._keywords, self._config._result_num)\n\t\tself._keywords_links = contacter.getURLs()\n\t\t#append seeds, which from google search result, into download pool\n\t\t#print \"load_seeds 2\"\n\t\t#self._keywords_links.insert(0, \"https://twitter.com/\")\n\t\t#self._keywords_links.insert(0, \"https://twitter.com/signup?context=login\")\n\t\t\n\t\ti = 0\n\t\tfor url in self._keywords_links:\n\t\t\tif i < self._config._result_num:\n\t\t\t\t#print \"@@{0}\".format(url)\n\t\t\t\thtml_task = Html(url)\n\n\t\t\t\t#print \"@@1\"\n\t\t\t\tif(self._schemehandler.SchemeChecker(html_task)==False):\n\t\t\t\t\t#print(\"Ingore the wrong scheme, this link is within page {0} , so don't download\".format(html_task._parent), html_task._url)\n\t\t\t\t\t#print \"@@2\"\n\t\t\t\t\tself._status._scheme+=1\n\t\t\t\t\tcontinue\n\t\t\t\tif(self._bookmarkhandler.BookMarkChecker(html_task)==True):\n\t\t\t\t\t#print(\"Ingore bookmark link, this link is within page {0} , so don't download\".format(html_task._parent), html_task._url)\n\t\t\t\t\t#print \"@@3\"\n\t\t\t\t\tself._status._bookmark+=1\n\t\t\t\t\tcontinue\n\t\t\t\tif(self._cgihandler.FindCGI(html_task)==True):\n\t\t\t\t\t#print(\"Ingore the link contain cgi, this link is within page {0} , so don't download\".format(html_task._parent), html_task._url)\n\t\t\t\t\t#print \"@@4\"\n\t\t\t\t\tself._status._cgi+=1\n\t\t\t\t\tcontinue\n\t\t\t\tif(self._nestlevelhandler.checknestlevel(html_task,self._config._parser_nlv)==True):\n\t\t\t\t\tself._status._nestlv +=1\n\t\t\t\t\t#print \"@@5\"\n\t\t\t\t\t#print(\"Ingore the link nested too much, this link is within page {0} , so don't download\".format(html_task._parent), html_task._url)\n\t\t\t\t\tcontinue\n\t\t\t\tif(self._filetypehandler.FileTypeChecker(html_task)==False):\n\t\t\t\t\t#print \"@@6\"\n\t\t\t\t\tself._status._file_type +=1\n\t\t\t\t\tcontinue\n\t\t\t\t#print \"@@7\"\n\t\t\t\t'''\n\t\t\t\tif(self._earlyvisithandler.check_visited(html_task) == True):\n\t\t\t\t\tself._status._early_visit +=1\n\t\t\t\t\t#print(\"Ingore the link visited before, this link is within page {0} , so don't download\".format(html_task._parent), html_task._url)\n\t\t\t\t\tcontinue\n\t\t\t\t'''\n\t\t\t\tself._omitindex.Omit(html_task)\n\t\t\t\t\"\"\"\n\t\t\t\tprint \"@@8\"\n\t\t\t\tif(self._robothandler.is_allowed(html_task) == False):\n\t\t\t\t\tprint \"@@9\"\n\t\t\t\t\tself._status._robot +=1\n\t\t\t\t\t#print(\"Blocked by the Robot.txt, this link is within page {0} , so don't download\".format(html_task._parent), html_task._url)\n\t\t\t\t\tcontinue\n\t\t\t\tprint \"@@10\"\n\t\t\t\t\"\"\"\n\t\t\t\tself._earlyvisithandler.add_entry(html_task._md5, html_task)\n\t\t\t\tself._download_pool.append(html_task)\n\t\t\t\t'''If use the following two line of code, then the program won't run, which means checking for revisit works'''\n\t\t\t\t'''however, the dic should be safe with a lock'''\n\t\t\t\t#self._visited_dic[html_task._md5] = html_task._url \n\t\t\t\t#print(len(self._visited_dic))\n\t\t\t\t#print \"@@11\"\n\t\t\telse:\n\n\t\t\t\tbreak\n\t\t\ti+=1\n\t\t#print \"load_seeds 3\"\n\tdef show_welcome(self):\n\t\tprint(\"download folder:\"+self._path)\n\t\tprint \"key words:\"+self._config._keywords\n\t\tprint \"donload thread num: {0}\".format(self._config._down_num)\n\t\tprint \"parse thread num: {0}\".format(self._config._parser_num)\n\t\tprint \"Load \" +str(self._config._result_num)+\" results from google search:\"\n\t\t\n\t\ti = 0\n\t\tfor url in self._keywords_links:\n\t\t\tif i < self._config._result_num:\n\t\t\t\tprint (\"[{0}]\".format(i)+url)\n\t\t\ti+=1\n\t\tprint \"\\n------------------------------------------------------------------------\\n\"\n\n\t\t#raw_input(\"press any key to start crawling, press second key to stop\")\n\t\n\tdef wait_for_start(self):\n\t\tprint \"ready for start.....\"\n\t\tprint \"go to http://dengxu.me/crawling/ to input some key words & see the result \"\n\n\t\twhile( self.sqlex.read_if_start(self._config)!= True):\n\t\t\tsleep(1)\n\t\tprint \"\\n------------------------------------------------------------------------\\n\"\n\t\tprint \"starting crawling engine....\"\n\n\n\tdef start(self):\n\t\ttry:\n\t\t\tself.wait_for_start()\n\n\t\t\tself._istart = True\n\t\t\t\n\t\t\t\"\"\"load seed \"\"\"\n\t\t\tself.load_seeds()\t#load seeds from google search \n\n\t\t\t\n\t\t\t\"\"\"show welcome info\"\"\"\n\t\t\tself.show_welcome()\n\t\t\tself._status._sys_start\t= time()\n\n\t\t\t\"\"\"start threads\"\"\"\n\t\t\tself._downloader = Downloader( self._config._down_num, self._status)\n\t\t\tself._downloader.start()\n\t\t\tself._parser = Parser(self._config._parser_num, self._status )\n\t\t\tself._parser.start()\n\t\t\tself._downloader_pool_checker.start()\n\t\t\tself._parse_pool_checker.start()\n\t\t\tself._status_update.start()\n\n\n\t\t\t\"\"\"notify mysql, i am started\"\"\"\n\t\t\tself.sqlex.write_if_start()\n\t\t\t\n\t\texcept (Exception) as e:\n\t\t\tLog().debug(\"start failed\")\n\t\t\traise(e)\n\t\t\treturn False\n\n\t\t\n\t\t\n\tdef stop(self):\n\t\tself._istart = False\n\t\t\"\"\"\"clear download and parse popl\"\"\"\n\t\tself._download_pool.clear()\n\t\tself._parse_pool.clear()\n\n\t\t\"\"\"stop downloader and parser threads\"\"\"\n\t\tself._downloader.stop()\n\t\tself._parser.stop()\n\t\t\"\"\"\"Those two checker threads will end when the thread who calls them ends\"\"\"\n\t\tself._downloader_pool_checker.join()\n\t\tself._parse_pool_checker.join()\n\t\tself._status_update.join()\n\t\tprint (\"Engine is stopping\")\n\n\tdef pause(self):\n\t\tpass\n\n\tdef finish_download(self, html_task):\n\t\t\t\n\t\t\n\t\t\n\t\t\n\t\tsentence = \"Downloaded:[No.{0}] time:{1:0.1f} page:depth_parent {2}_{3} http-code: {4} data-size: {5}byes url: {6}\"\\\n\t\t\t.format(self._status._download_times,time()-self._status._sys_start,html_task._depth,\\\n\t\thtml_task._parent,html_task._return_code, html_task._data_size, html_task._url )\n\n\t\t#if self._status._download_times <= 500 :\n\t\t#\tself.f.write(sentence+\"\\n\")\n\t\t\t\n\n\n\t\t\"\"\"caculate the path for saving files\"\"\"\n\t\tfull_path = self._path+\"[No.{0}]_\".format(self._status._download_times)+\".html\"\n\n\t\t\"\"\"save html data to files\"\"\"\n\t\t#f= open(full_path, 'w')\n\t\t#f.write(html_task._data)\n\t\t#f.close()\n\n\n\t\t\"\"\"After downloading, pass the data(still using the html objects) to the parse pool\"\"\"\n\t\tself._parse_pool.append(html_task)\n\n\n\n\n\tdef finish_parse(self, html_task):\n\t\t'''\n\t\tprint(\"parsed:[No.{0}] time:{1:0.1f} page:depth_parent {2}_{3} http-status: {4} data-size: {5}byes url:{6}\"\\\n\t\t\t.format(self._status._download_times,time()-self._status._sys_start,html_task._depth,\\\n\t\thtml_task._parent,html_task._return_code, html_task._data_size, html_task._url))\n\t\t'''\n\t\t\"\"\"After parsing, pass the urls to be downloaded to the download pool\"\"\"\n\t\tif(self._earlyvisithandler.check_visited(html_task) == True):\n\t\t\t#print(\"Ingore the link visited before, this link is within page {0} , so don't put it in queue\".format(html_task._parent), html_task._url)\n\t\t\tself._status._early_visit +=1\n\t\t\treturn\n\t\tif(self._robothandler.is_allowed(html_task) == False):\n\t\t\t#print(\"Blocked by the Robot.txt, this link is within page {0} , so don't download\".format(html_task._parent), html_task._url)\n\t\t\tself._status._robot +=1\n\t\t\treturn\n\t\t\n\t\tself._earlyvisithandler.add_entry(html_task._md5, html_task)\n\t\tself._download_pool.append(html_task)\n\t\t\n\n\n\n\n\tdef download_pool_checker(self):\n\t\twhile (self._istart == True):\n\t\t\tnew_download_task = self._download_pool.pop_left()\n\t\t\t\"\"\"If there is no task remain in the download pool, put the thread into sleep\"\"\"\n\t\t\t\"\"\"else pop the new task, and download it\"\"\"\n\t\t\t\"\"\"for the engine to get the result to put into the parse pool, we need to pass the function finish_download down as a callback\"\"\"\n\t\t\t\n\t\t\tif (new_download_task == None):\n\t\t\t\t#print(\"No task remaining in download_pool\")\n\t\t\t\tsleep(0.1)\n\t\t\telse:\n\t\t\t\tself._downloader.queue_download_task(new_download_task , self.finish_download)\n\n\n\tdef parse_pool_checker(self):\n\t\twhile (self._istart == True):\n\t\t\tnew_parse_task = self._parse_pool.pop_left()\n\t\t\tif (new_parse_task == None):\n\t\t\t\t#print(\"sleeping\")\n\t\t\t\tsleep(0.1)\t\t\t\t\n\t\t\telse:\n\n\t\t\t\tself._parser.queue_parse_task(new_parse_task, self.finish_parse)\n\n\n\n\n\n\t#~~~see result at http://dengxu.me/crawling/\n\tdef status_update(self):\n\n\t\twhile (self._istart == True):\n\n\t\t\tself._status._download_queue = self._downloader.len()\n\t\t\tself._status._parse_queue = self._parser.len()\n\t\t\t\n\t\t\t\n\t\t\tsentence = \"[time: {0:0.1f}],queue:{8}, down: {1}, total: {2:0.1f}MB | queue:{9}, parsed: {3},scheme:{10}, cig: {4}, bookmark: {11} type {12} visited: {5}, robot: {6},nestlv: {7} | error: 404: {13} , timeout: {14}\"\\\n\t\t\t.format( time()-self._status._sys_start,\\\n\t\t \tself._status._download_times, float(self._status._download_size)/1024/1024, self._status._parse_times\\\n\t\t \t,self._status._cgi, self._status._early_visit, self._status._robot, self._status._nestlv\\\n\t\t \t,self._downloader.len(), self._parser.len(),self._status._scheme_type, self._status._bookmark, self._status._file_type\\\n\t\t \t,self._status._404,self._status._socket_timeout)\n\t\t\t\n\t\t\tprint sentence\n\n\t\t\t#if( self._status._download_times > 500):\n\t\t\t#\tself.f.write( sentence+\"\\n\")\n\t\t\t\n\n\t\t\t\"\"\"update status tp mysql\"\"\"\n\t\t\tself.sqlex.write_status(self._status)\n\t\t\t\n\t\t\t\"\"\"update recent download url\"\"\"\n\t\t\tself.sqlex.write_recent_download(self._status)\n\t\t\t\n\t\t\tsleep(1)\n\n\n\t\t\n \n\n\n" }, { "alpha_fraction": 0.6790831089019775, "alphanum_fraction": 0.6790831089019775, "avg_line_length": 17.810810089111328, "blob_id": "3b71ac11d6f7f7efaa7d70c845da60e9b07bc833", "content_id": "9de9b43fd4a4992dc07164de6982296ce942dbd3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 698, "license_type": "no_license", "max_line_length": 66, "num_lines": 37, "path": "/newyorktimes/src/include/models/Docmap.h", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "\n\n#ifndef _DOC_MAP_H\n#define _DOC_MAP_H\n#include <map>\n#include <string>\n#include \"StreamBuffer.h\"\nusing namespace std;\n\n\nstruct STRU_DOC\n{\n\tstring doc_name;\n\tstring doc_path;\n\tstring doc_title;\n\tstring doc_url;\n\tstring doc_location;\n\tint doc_time;\n\tint len;\n\n\t//int file_id;\n\t//int offset;\n};\nclass DocMap \n{\npublic:\n\tDocMap();\n\t~DocMap();\n\tSTRU_DOC& operator[](int key){return _data[key];}\n\tvoid serialize( StreamBuffer &stream );\n\tvoid deserialize( char* buffer, int size ,int&d_agv, int& N );\n\t\n\t//friend StreamBuffer& operator<<(StreamBuffer &stream, DocMap&);\n\tfriend StreamBuffer& operator>>(StreamBuffer &stream, DocMap&);\npublic:\n\tmap<int, STRU_DOC> _data;\n};\n\n#endif /* _DOC_MAP_H */\n" }, { "alpha_fraction": 0.59375, "alphanum_fraction": 0.5989583134651184, "avg_line_length": 11.733333587646484, "blob_id": "d8ca9447d4d0176ce2959777758aed362496f1ac", "content_id": "1b64ccbaa64f6e9fb00e39c7d99ecda7469cacb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 192, "license_type": "no_license", "max_line_length": 43, "num_lines": 15, "path": "/newyorktimes/src/generating/generating.cpp", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "\n#include \"parser/parser.h\"\n#include \"analysis_ctrl.h\"\n\n\n\n\n\nint main( char /* **argv */, int/* argc */)\n{\n\tanalysis_ctrl demo;\n\tdemo.start();\n\t//display::get_instance()->run();\n\t\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.6137624979019165, "alphanum_fraction": 0.6322604417800903, "avg_line_length": 33.64102554321289, "blob_id": "5c6ccf2ec34dd9b4c4c606225bf4f6646b1824d0", "content_id": "71dc7b73c98aa1285557fa74c8d8cd7c8645f315", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2703, "license_type": "no_license", "max_line_length": 131, "num_lines": 78, "path": "/crawling/include/database_manager.py", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "\"\"\"\nCreated on Feb 13, 2013\n\n@author: derrick\n\n\"\"\"\n\nfrom models.status import Status\nfrom models.configuration import Configuration\nfrom include.database import Database\nfrom time import time\n\nclass DatabseManager(object):\n\tdef __init__(self, config):\n\t\tself._database\t= Database(config)\n\t\t\n\n\t\"\"\"\n\tdef write_configuration(self, config):\n\t\tsql = \"UPDATE\\\n\t\t`configuation` SET `downloader_thread` = {0} ,`downloader_folder`= '{1}',\\\n\t\t `parser_thread`= {2}, `seed_keywords`='{3}', `seed_resultnum`={4} WHERE `configuation`.`id` =1\".\\\n\t\t\t\tformat(config._down_num, config.download_path, parser_thread, key_words, result_num)\n\n\t\tself._database.execute(sql)\t\n\t\"\"\"\t\n\n\tdef write_status(self, status):\n\t\tsql = \"UPDATE `web_search_engine`.`status` SET `crawled_url_count` = '{0}', `crawled_time` = '{1}', `crawled_size` = '{2}',\\\n\t\t `crawled_queue` = '{3}', `parse_count` = '{4}', `parse_queue` = '{5}', `parse_scheme_type` = '{6}', `parse_cgi` = '{7}',\\\n\t\t `parse_visited` = '{8}', `parse_robot` = '{9}', `parse_nestlv` = '{10}' WHERE `status`.`id` = 1;\"\\\n\t\t\t.format( status._download_times, time()-status._sys_start, status._download_size, status._download_queue,\\\n\t\t \tstatus._parse_times, status._parse_queue, status._scheme_type, status._cgi, status._early_visit, status._robot, status._nestlv)\n\t\t \n\t\t#print sql\n\t\tself._database.execute(sql)\t\n\t\t\n\n\tdef read_if_start(self, config):\n\t\t\n\t\tsql = \"SELECT `is_start`, `seed_keywords`,`downloader_thread`,`parser_thread`,`seed_resultnum` FROM `configuation` WHERE `id` =1\"\n\t\t#print sql\n\t\tresult = self._database.execute(sql)\t\n\t\t\n\t\tif(result[0][0] == True):\n\t\t\tsql = \"UPDATE `web_search_engine`.`configuation` SET `is_start` = '0' WHERE `configuation`.`id` = 1\"\n\t\t\tself._database.execute(sql)\n\t\t\t\n\t\t\t#update config\n\t\t\tconfig._keywords = result[0][1]\n\t\t\tconfig._down_num = result[0][2]\n\t\t\tconfig._parser_num = result[0][3]\n\t\t\tconfig._result_num = result[0][4]\n\n\t\t\t#print \"####\"\n\t\t\t#print config._down_num\n\n\n\t\tif(result != None):\n\t\t\treturn result[0][0]\n\t\telse:\n\t\t\treturn None\n\n\tdef write_if_start(self):\n\t\t \n\t\tsql = \"UPDATE `web_search_engine`.`configuation` SET `key_word_start` = '1', `status_start` = '1' WHERE `configuation`.`id` = 1\" \n\t\tresult = self._database.execute(sql)\t\n\t\t\n\n\tdef write_recent_download(self,status):\n\t\tfor i in range(10):\n\t\t\thtml_task = status._recent_url.get(i)\n\t\t\tif html_task._url != \"#\":\n\t\t\t\tsql = \"INSERT INTO `web_search_engine`.`log` (`url`, `download_time`, `data_size`, `code`, `parent`, `depth`)\\\n\t\t\t\t\tVALUES ('{0}', now(), '{2}', '{3}', '{4}', '{5}')\".format\\\n\t\t\t\t\t(html_task._url, html_task._crawled_time, html_task._data_size, html_task._return_code, html_task._parent, html_task._depth)\n\t\t\t\t\t\n\t\t\t\tself._database.execute(sql)\n\n" }, { "alpha_fraction": 0.5422138571739197, "alphanum_fraction": 0.5497185587882996, "avg_line_length": 23.227272033691406, "blob_id": "a64ce04f9a02535a4265a2c735af19e483ef94d9", "content_id": "ae04066ef2410f158a93f0ec3baf46368059c1f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 533, "license_type": "no_license", "max_line_length": 96, "num_lines": 22, "path": "/search/interface/template/query.php", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "<div class=\"result_top\">\n\t<form class=\"form-search\" action=\"query.php\" method=\"get\">\n\t <input name=\"key\" type=\"text\" class=\"input-xlarge\" value=<?php echo \"\\\"\".$_GET[\"key\"].\"\\\"\"?>>\n\t <button type=\"submit\" class=\"btn\">Search</button>\n\t</form>\n</div>\n<div class=\"container\">\n\t<? \n\t$result= $GLOBALS['result'];\n\tforeach( $result as $key=>$value)\n\t{\n\t?>\n\t<div class=\"one_result\">\n\t\t<p><a href=\"http://<?=$value['url']?>\"><?=$value['title']?></a> BM25:<?=$value['bm25']?></p>\n\t\t<p> <?=$value['round']?></p>\n\t</div>\n\t<?\n\t} \n\t?>\n\n\n</div>\n" }, { "alpha_fraction": 0.5299999713897705, "alphanum_fraction": 0.5699999928474426, "avg_line_length": 10.11111068725586, "blob_id": "cc0d8dd3bb2f4b930a4c458b75828cc202c337b3", "content_id": "73ff438aa33d3b5b151faa5a0722f2dec3b5bd60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 200, "license_type": "no_license", "max_line_length": 28, "num_lines": 18, "path": "/newyorktimes/src/include/models/Heap.h", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "/*\n * Heap.h\n *\n * Created on: Feb 25, 2013\n * Author: Adam57\n */\n\n#ifndef HEAP_H_\n#define HEAP_H_\nusing namespace std;\n\nclass Heap {\npublic:\n\tHeap();\n\tvirtual ~Heap();\n};\n\n#endif /* HEAP_H_ */\n" }, { "alpha_fraction": 0.5080459713935852, "alphanum_fraction": 0.5316091775894165, "avg_line_length": 21.037975311279297, "blob_id": "ae12cdb971ac0af31061b7dfe65bb7cd9aa42c65", "content_id": "e9dcd7193f7f22e2dae1a9ac769cb1e59b0b1f9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1740, "license_type": "no_license", "max_line_length": 78, "num_lines": 79, "path": "/indexing/src/helper/helper.cpp", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "#include <sys/socket.h>\n#include <sys/types.h>\n#include <netinet/in.h>\n#include <netdb.h>\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <errno.h>\n#include <arpa/inet.h> \n#include <iostream>\nusing namespace std;\n\nint main(int argc, char *argv[])\n{\n int sockfd = 0, n = 0;\n char sendBuff[1024];\n char recvBuff[1024];\n struct sockaddr_in serv_addr; \n\n \n int offset = 0;\n char c=' ';\n cout<<argv[0]<<endl;\n for( int i = 1 ; i < argc; i++)\n {\n memcpy(sendBuff+offset, argv[i], strlen(argv[i]));\n offset+=strlen(argv[i]);\n if(i != argc- 1)\n {\n memcpy(sendBuff+offset, &c, 1);\n offset+=1;\n }\n }\n sendBuff[offset]='\\0';\n //cout<<sendBuff<<endl;\n \n\n memset(recvBuff, '0',sizeof(recvBuff));\n if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)\n {\n printf(\"\\n Error : Could not create socket \\n\");\n return 1;\n } \n\n memset(&serv_addr, '0', sizeof(serv_addr)); \n\n serv_addr.sin_family = AF_INET;\n serv_addr.sin_port = htons(9999); \n\n if(inet_pton(AF_INET, \"127.0.0.1\", &serv_addr.sin_addr)<=0)\n {\n printf(\"\\n inet_pton error occured\\n\");\n return 1;\n } \n\n if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)\n {\n printf(\"\\n Error : Connect Failed \\n\");\n return 1;\n } \n\n write(sockfd, sendBuff, strlen(recvBuff));\n while ( (n = read(sockfd, recvBuff, sizeof(recvBuff)-1)) > 0)\n {\n recvBuff[n] = 0;\n if(fputs(recvBuff, stdout) == EOF)\n {\n printf(\"\\n Error : Fputs error\\n\");\n }\n } \n\n if(n < 0)\n {\n printf(\"\\n Read error \\n\");\n } \n\n return 0;\n}" }, { "alpha_fraction": 0.5738636255264282, "alphanum_fraction": 0.5928030014038086, "avg_line_length": 21.95652198791504, "blob_id": "be5ff624d0b6ff925b7bdc16953d829f31f20dd9", "content_id": "dc583584dbbca64d40d7a9f42b2c22d145c4dfef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 528, "license_type": "no_license", "max_line_length": 61, "num_lines": 23, "path": "/crawling/strategies/earlyvisithandler.py", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "'''\nCreated on Feb 13, 2013\n\n@author: Adam57\n'''\n\nfrom models.safe_dic import SafeDictionary\n\nclass EarlyVisitHandler(object):\n \n def __init__(self):\n \"\"\"this dic stores normlized url(md5) and the html\"\"\"\n self._visited_dic = SafeDictionary()\n \n def check_visited(self, html_task):\n \n if self._visited_dic.has_key(html_task._md5):\n return True\n else: \n return False\n \n def add_entry(self,key,value):\n self._visited_dic.addorupdate(key, value)\n" }, { "alpha_fraction": 0.636192262172699, "alphanum_fraction": 0.6588124632835388, "avg_line_length": 20.653060913085938, "blob_id": "fd3c0c451330c88e2fe835d80e1914c9f7e338d1", "content_id": "c77410c8b4b5d0b1eef92aa245f68886d7229e4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1061, "license_type": "no_license", "max_line_length": 93, "num_lines": 49, "path": "/indexing/src/searching/Lp.h", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "/*\n * Lp.h\n *\n * Created on: Mar 31, 2013\n * Author: Adam57\n */\n\n#ifndef LP_H_\n#define LP_H_\n#include<string.h>\n#include<vector>\n#include<string>\n#include<map>\nusing namespace std;\n#define MAXDID 100000000;\n#define FILESIZE 1200000;\ntypedef struct {int chunk_last_wordid; int chunk_last_docid; int filenum; int offset;} chunk;\ntypedef struct {int doc_num; int chunk_num; int posting_num;} word_inf;\ntypedef struct {int wordid; int docid; int freq;} posting;\nstatic map<int, word_inf> word_index;\nstatic map<int, chunk> chunk_index;\nstatic map<string, int> word_map;\nclass Lp {\n\n//private:\n//\tstring word;\n//\tint word_id;\n//\tint start_chunk;\n//\tint end_chunk;\n//\tint start_posting_num;\n//\tint end_posting_num;\n//\tint doc_num;\n//\tFILE* start_file;\n//\tint file_offset;\n\npublic:\n\tint word_id;\n\tint doc_num;\n\tint\t start_chunk;\n\tint start_posting_num;\n\tint end_posting_num;\n\tint num_of_chunks;\n\tint cur_posting_docid;\n\tint\t cur_posting_freq;\n\tint cur_first_pos;\n\tvector <chunk> chunkvector;\n};\n\n#endif /* LP_H_ */\n" }, { "alpha_fraction": 0.4498172700405121, "alphanum_fraction": 0.46696653962135315, "avg_line_length": 19.096044540405273, "blob_id": "c4a33e5a4fbcbd5320d6f4652982dd91276357b2", "content_id": "96173b47d41fd448f835a791edd6692a3d372fbb", "detected_licenses": [ "Apache-2.0", "CC-BY-3.0" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 3557, "license_type": "permissive", "max_line_length": 92, "num_lines": 177, "path": "/crawling/www/realtime_data.php", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "<?php\n$host = \"localhost\"; \n$user = \"web_search\"; \n$pass = \"dengxu_wangqi\"; \n$db = \"web_search_engine\";\n\n$conn = mysql_connect($host, $user, $pass);\n\nif (!$conn)\n{\n echo \"Could not connect to server\\n\";\n exit();\n} \n\nmysql_select_db($db,$conn);\n\n$sql = \"SELECT * FROM `configuation` WHERE `id` =1\";\n\n$result = mysql_query($sql);\nif (!$result) \n{\n echo 'Could not run query: ' . mysql_error();\n exit;\n}\n\n$row = mysql_fetch_array($result);\n\nif($row ['key_word_start'] != '1' && $row ['status'] != '1')\n{\n\n?>\n<div class=\"my_content2\">\n<h1>Loading Data</h1>\n\n<div class=\"progress progress-striped active\">\n <div class=\"bar\" style=\"width: 40%;\"></div>\n</div>\n</div>\n<?\nexit(1);\n}\n\n\n$sql = \"SELECT * FROM `status` WHERE `id` =1\";\n\n\n$result = mysql_query($sql);\nif (!$result) \n{\n echo 'Could not run query: ' . mysql_error();\n exit;\n}\n\n$row = mysql_fetch_array($result);\n\n//var_dump($row)\n\n?>\n\n<div id=\"breadcrumb\">\n <ul>\n \n<li>Realtime Statistics : [<? echo number_format($row[crawled_time], 1, '.', ',') ?>s]</li>\n\n </ul>\n </div>\n\t<div class=\"my_span\"></div>\n\t<div class=\"my_content\">\n\t\t<table class=\"table table-bordered\">\n\t\t <thead>\n\t\t <tr>\n\t\t <th olspan=\"2\"><b>Downloader:</b></th>\n\t\t </tr>\n\t\t </thead>\n\t\t <tbody>\n\t\t <tr>\n\t\t <td width=\"200\"><b>crawled pages:</b></td>\n\t\t <td> <?=$row['crawled_url_count']?></td>\n\t\t </tr>\n\t\t <tr>\n\t\t <td>crawled total size:</td>\n\t\t <td>\n\t\t <?\n\t\t $num = $row[crawled_size]*1.0/1024/1024;\n\t\t echo number_format($num, 1, '.', ',')\n\t\t ?> MB</td>\n\t\t </tr>\n\t\t <tr>\n\t\t <td width=\"200\"><b>crawled queue:</b></td>\n\t\t <td> <?=$row['crawled_queue']?></td>\n\t\t </tr>\n\t\t </tbody>\n\t\t</table>\t\n\t</div>\n\t<div class=\"my_content\">\n\t\t<table class=\"table table-bordered\">\n\t\t <thead>\n\t\t <tr>\n\t\t <th olspan=\"2\"><b>Parser:</b></th>\n\t\t </tr>\n\t\t </thead>\n\t\t <tbody>\n\t\t <tr>\n\t\t <td width=\"200\"><b>parsed pages:</b></td>\n\t\t <td> <?=$row['parse_count']?></td>\n\t\t </tr>\n\t\t <tr>\n\t\t <td>praser queue:</td>\n\t\t <td> <?=$row['parse_queue']?></td>\n\t\t </tr>\n\t\t <tr>\n\t\t <td width=\"200\"><b>scheme type:</b></td>\n\t\t <td> <?=$row['parse_scheme_type']?></td>\n\t\t </tr>\n\t\t <tr>\n\t\t <td width=\"200\"><b>cgi</b></td>\n\t\t <td> <?=$row['parse_cgi']?></td>\n\t\t </tr>\n\t\t <tr>\n\t\t <td width=\"200\"><b>visited:</b></td>\n\t\t <td> <?=$row['parse_visited']?></td>\n\t\t </tr>\n\t\t <tr>\n\t\t <td width=\"200\"><b>robot</b></td>\n\t\t <td> <?=$row['parse_robot']?></td>\n\t\t </tr>\n\t\t <tr>\n\t\t <td width=\"200\"><b>nest level</b></td>\n\t\t <td> <?=$row['parse_nestlv']?></td>\n\t\t </tr>\n\t\t </tbody>\n\t\t</table>\t\n\t</div>\n\n\t<div class=\"my_content\">\n\t\t<table class=\"table table-bordered AutoNewline\">\n\t\t <thead>\n\t\t <tr>\n\t\t <th width=\"500\">recent download url</th>\n\t\t <th>code</th>\n\t\t <th>size</th>\n\t\t <th>parent</th>\n\t\t <th>depth</th>\n\t\t </tr>\n\t\t </thead>\n\t\t <tbody>\n\t\t <tr>\n\t\t \t<?php \n\t\t \t$sql = \"SELECT * FROM `log` order by `id` desc LIMIT 0 , 10\";\n\t\t\t\t$result = mysql_query($sql);\n\t\t \t$i=1;\n\t\t \twhile ($array = mysql_fetch_array($result))\n\t\t\t\t{\n\t\t\t\t\techo \"<tr>\";\n\t\t\t\t\techo \"<td width='500'>\".$array['url'].substr(1,20).\"</td>\";\n\t\t\t\t\techo \"<td>\".$array['code'].\"</td>\";\n\t\t\t\t\techo \"<td>\".$array['data_size'].\"</td>\";\n\t\t\t\t\techo \"<td>\".$array['parent'].\"</td>\";\n\t\t\t\t\techo \"<td>\".$array['depth'].\"</td>\";\n\t\t\t\t\techo \"</tr>\";\n\t\t\t\t}\n\t\t ?>\n\n\t\t </tr>\n\t\t</table>\t\n\t</div>\n\n\n </div>\n\n\n\n<?php\n\nmysql_close();\n\n?>\n" }, { "alpha_fraction": 0.6814650297164917, "alphanum_fraction": 0.6825749278068542, "avg_line_length": 22.415584564208984, "blob_id": "1c1c0b2a76a40c5aaab116056c01727fb4961053", "content_id": "77711619e7fb78377347b74cae575599a9970c6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1802, "license_type": "no_license", "max_line_length": 156, "num_lines": 77, "path": "/newyorktimes/src/generating/analysis_ctrl.h", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "#ifndef __ANALYSIS_CTRL_\n#define __ANALYSIS_CTRL_\n\n#include \"utility/display.h\"\n#include \"utility/gzip.h\"\n#include \"utility/path_finder.h\"\n#include \"models/original_index.h\"\n#include \"models/TempLexicon.h\"\n#include \"models/WordMap.h\"\n#include \"parser/parser.h\"\n#include \"models/StreamBuffer.h\"\n#include \"models/Docmap.h\"\n#include <set>\n#include <ctime>\n\n#include <string>\n\n\nstruct status\n{\n\tint _deal_docs;\n\tint _deal_words;\n\n\tstatus()\n\t{\n\t\t_deal_docs = 0;\n\t\t_deal_words= 0;\n\t}\n};\n\n\nclass analysis_ctrl : d_key_event\n{\npublic:\n\tanalysis_ctrl();\n\t~analysis_ctrl();\n\n\tbool start();\n\tvoid stop();\n\n\t/*key input callback*/\n\tvoid input_event( char* key );\n\nprivate:\n\tvoid do_it();\n\tbool save_index(char* index_data, int len, original_index& index, int file_num);\n\tbool parse_data(char* html_data, int len, original_index& index);\n\tbool save_data(int doc_id, char* save_data, int len);\n\tint get_doc_id(std::string doc_name, std::string doc_path,std::string doc_title,std::string doc_url,std::string doc_location,int doc_date, int doc_len );\n\tint get_word_id(std::string word);\n\tbool parse_xml(std::string file_path, char* buf, int buf_len,std::string& title,string& url, string& location,int& date, int& doc_len);\n\tbool get_one_word(char* source, int& pos,string& str);\n\tbool get_new_info(char* source, int max, int& start_pos, std::string key_start, std::string key_end, string& content);\n\tint find(char* source, int max_len, int start, std::string key_words);\nprivate:\n\t\n\tstatus\t\t\t_status;\n\tstd::string\t\t_dataset_path;\t\n\tint \t\t\t_file_now;\n\tint \t\t\t_file_start;\n\tint \t\t\t_file_end;\n\tint \t\t\t_doc_id;\n\tint \t\t\t_word_id;\n\tStreamBuffer* \t_intermediate;\n\ttime_t \t\t\t_time_now ; \n\n\n\tWordMap\t\t\t_word_map;\n\tDocMap \t\t\t_docs_map;\n\tmap<string,int>\t_checker;\n\tset<string> \t_locations;\n\tPathFinder \t\t_finder;\n\n};\n\n\n#endif" }, { "alpha_fraction": 0.5261261463165283, "alphanum_fraction": 0.5441441535949707, "avg_line_length": 26.5, "blob_id": "aa0b904f07e273973f80797405be8b4c9c8458a2", "content_id": "462204152ee23ce7427abee8459c01dab9d12baa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 555, "license_type": "no_license", "max_line_length": 62, "num_lines": 20, "path": "/crawling/strategies/urlextender.py", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "'''\nCreated on Feb 14, 2013\n\n@author: Adam57\n'''\nclass URLExtender(object):\n def ExtendURL(self, child, parent):\n\n # if root folder\n if child._url[0] == '/':\n child.update_url(parent._homesiteurl + child._url)\n\n else :\n if parent._url[len(parent._url)-1] != '/':\n parent._url = parent._url + '/'\n child.update_url(parent._url + child._url)\n \t\t#print child._url \n #print \"extentd url: \"+ parent._url + \" *** \"+child._url\n # child.update_url(parent._url + child._url)\n # child._url\n \n" }, { "alpha_fraction": 0.5707316994667053, "alphanum_fraction": 0.5829268097877502, "avg_line_length": 11.84375, "blob_id": "c0e61a4aee59ae07290892f7fe0a2aad7297dc95", "content_id": "af02eed5951032ffb141577e53d02b50cd7ca101", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 410, "license_type": "no_license", "max_line_length": 42, "num_lines": 32, "path": "/newyorktimes/src/searching/result_ctrl.cpp", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "#include \"result_ctrl.h\"\n\nResultCrtl::ResultCrtl()\n{\n\t_max = 10;\n\t_now =0;\n\t_result = new STRU_RESULT[_max];\n\n}\nResultCrtl::~ResultCrtl()\n{\n\tif(_result != NULL)\n\t\tdelete _result;\n}\n\nvoid ResultCrtl::clear()\n{\n\t_now = 0;\n}\n\nvoid ResultCrtl::add_one(STRU_RESULT& res)\n{\n\tif( _now >= _max)\n\t\treturn;\n\t_result[_now++] = res;\n}\n\nvoid ResultCrtl::print()\n{\n//\tfor(int i = 0 ; i < _now; i++)\n//\t\t_result[i].print();\n}" }, { "alpha_fraction": 0.6394850015640259, "alphanum_fraction": 0.6394850015640259, "avg_line_length": 14.909090995788574, "blob_id": "9d182017ebbc9396937aa55ee0f6297b8dbe8505", "content_id": "f5ed2bf1f5e42ec6e0c458439d70dd7381240a10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 699, "license_type": "no_license", "max_line_length": 57, "num_lines": 44, "path": "/indexing/src/include/utility/timer.h", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "/*Author: derrick*/\n#ifndef D_TIMER_H\n#define D_TIMER_H\n\n#include \"lock.h\"\n#include \"system_ex.h\"\n#include <list>\n\nclass timer\n{\n\ttypedef void (*func)(void*);\n\n\tstruct struct_func\n\t{\n\t\tfunc\t\t\t_p_func;\n\t\tunsigned short\t_times;\n\t\tunsigned short\t_now;\n\t\tvoid*\t\t\t_data;\n\t};\n\nprivate:\n\ttimer();\n\t~timer();\npublic:\n\tstatic timer* get_instance();\n\tvoid do_register( func , void* , unsigned short times);\n\tvoid do_unregister( func );\nprivate:\n\tstatic void thread( void *p);\n\tvoid thread();\n\nprivate:\n\tstatic timer*\t\t\t_this;\n\tstatic lock\t\t\t\t_instance_lock;\n\tlock\t\t\t\t\t_thread_lock;\n\tlock\t\t\t\t\t_list_lock;\n\tbool\t\t\t\t\t_is_close;\n\tint\t\t\t\t\t\t_reference;\n\tstd::list<struct_func>\t_func_list;\n\t\n\n};\n\n#endif //D_TIMER_H" }, { "alpha_fraction": 0.6457023024559021, "alphanum_fraction": 0.6614255905151367, "avg_line_length": 17.365385055541992, "blob_id": "ba57a31b868efb24eb2863af99e7d171a69a13c6", "content_id": "4d18099d9f4bb4a5868c63fdb98522fe992c2cb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 954, "license_type": "no_license", "max_line_length": 47, "num_lines": 52, "path": "/newyorktimes/src/include/utility/shell.h", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "/*Author: derrick*/\n#ifndef D_SHELL_H\n#define D_SHELL_H\n\n#include <string>\n#include <deque>\n//#include <conio.h>\n#include \"system_ex.h\"\n\nconst int shell_backspace\t= 8;\nconst int shell_tab\t\t\t= 9;\nconst int shell_enter\t\t= 13;\n\nconst int shell_arrow\t\t= 224;\nconst int shell_up\t\t\t= 72;\nconst int shell_down\t\t= 80;\nconst int shell_left\t\t= 75;\nconst int shell_right\t\t= 78;\n\nclass shell\n{\npublic :\n\tshell();\n\t~shell();\n\tvoid test();\n\tvoid start();\n\tvoid stop();\npublic:\n\tvoid reg_command( std::string cmd_text , ...);\nprivate:\n\tstatic void fire_recv_thread(void *p);\n\tvoid thread_recv();\n\tvoid inster_command( int ch );\n\t//void \n\n\tvoid show_ch(int ch);\n\tvoid show_current_command();\n\tvoid add_command();\n\tvoid backspace();\n\tvoid clear_line();\n\n\tvoid get_next_command();\n\tvoid get_prev_command();\nprivate:\n\tstd::deque<std::string>\t\t_history_cmd;\n\tstd::string\t\t\t\t\t_current_cmd;\n\tunsigned short\t\t\t\t_save_count;\n\tunsigned short\t\t\t\t_cmd_pos;\n\t\n};\n\n#endif //D_SHELL_H" }, { "alpha_fraction": 0.5476529002189636, "alphanum_fraction": 0.5604552030563354, "avg_line_length": 14.644444465637207, "blob_id": "45bb477d72677eef5bbe8804c431ec9bce9bf663", "content_id": "0eef765c4e0dd3c80293474ada46e58bc0d89d8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 703, "license_type": "no_license", "max_line_length": 39, "num_lines": 45, "path": "/search/interface/query.php", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "<?php\n\nrequire_once( './loader.php' );\n\n\n\n$key_words = $_GET[\"key\"];\n$output = query( $key_words);\n//var_dump($output);\n//exit(0);\n\n$result = format_result($output);\nload_template(\"query\");\n\n\nfunction query( $key_words )\n{\n\t$cmd = \"demo/helper \".$key_words;\n\texec($cmd ,$output);\n\treturn $output;\n}\n\nfunction format_result( $output )\n{\n\t//var_dump($rs);\n\t$len =count($output);\n\t$result = array();\n\t$j=0;\n\tfor( $i = 1; $i < $len; $i+=4)\n\t{\n\t\t$one_result = array();\n\t\t$one_result['url'] = $output[$i];\n\t\t$one_result['bm25'] = $output[$i+1];\n\t\t$one_result['round'] = $output[$i+2];\n\t\t$one_result['title'] = $output[$i+3];\n\t\t\n\t\t\n\t\t$result[$j++] =$one_result;\n\t}\n\t//var_dump($result);\n\n\treturn $result;\n}\n\n?>" }, { "alpha_fraction": 0.5098516345024109, "alphanum_fraction": 0.518122136592865, "avg_line_length": 27.93661880493164, "blob_id": "d8edbdf317241ba489b91bf3a93699b4f220eaf4", "content_id": "64908639f1d60207a111870fe78d8d1acdb888e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4111, "license_type": "no_license", "max_line_length": 99, "num_lines": 142, "path": "/crawling/include/thread_pool.py", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "\n\"\"\"\nCreated on Feb 2, 2013\n\n@author: derrick\n\nThis is a thread pool\n\"\"\"\n#from queue import deque #python 3.3\nfrom collections import deque #python 2.7\nfrom threading import Thread\nfrom threading import Condition\nfrom threading import Lock\nfrom time import sleep\nfrom include.log import Log\n\n\nclass Worker(Thread):\n \"\"\"request new task to execute from ThreadPool\"\"\"\n\n def __init__(self, thread_pool, worker_id):\n \"\"\"initial data and start myself as a new thread\"\"\" \n Thread.__init__(self)\n self._pool = thread_pool\n self._woker_id = worker_id;\n self._is_dying = False\n self._work_times = 0\n self._rest_time = 0.01\n self._log = Log()\n \n\n def run(self):\n \"\"\"ask and do works from task pool\"\"\"\n while (self._is_dying == False):\n \"\"\"get the function name, parameter and the callback function\"\"\"\n func, args, callback = self._pool.get_new_task() \n if func == None: #no task, have a rest\n sleep(self._rest_time)\n else:\n try:\n \"\"\"run the function with its parameter and the callback function\"\"\"\n func(args, callback)\n except (Exception) as e: \n self._log.debug(e)\n #sys.exit(1)\n ++self._work_times\n\n def goaway(self):\n \"\"\" stop myself, this lead to the end of the run function, which will kill the thread\"\"\"\n self._is_dying = True\n\nclass ThreadPool():\n \"\"\" Consuming tasks using threads in poll\"\"\"\n def __init__(self, threads_num, task_queue_max=None):\n self._threads_num = threads_num\n self._tasks = deque()\n self._threads = []\n self._task_num = 0\n self._task_lock = Condition(Lock())\n self._thead_lock = Condition(Lock())\n\n\n def start(self):\n \"\"\"start all threads \"\"\"\n self._thead_lock.acquire()\n try:\n for i in range(self._threads_num): \n \"\"\"start workers from here, pass itself as thread pool to the new started worker\"\"\"\n new_thread = Worker(self, i)\n self._threads.append(new_thread)\n new_thread.start()\n finally:\n self._thead_lock.release()\n\n def stop(self):\n #clear the task\n self._task_lock.acquire()\n try:\n self._tasks.clear(); \n finally:\n self._task_lock.release()\n \n \"\"\"stop all threads \"\"\"\n self._thead_lock.acquire()\n try:\n for one_thread in self._threads: \n one_thread.goaway()\n self._threads = []\n self._threads_num = 0\n finally:\n self._thead_lock.release()\n\n \n\n def queue_task(self, task, args, callback):\n self._task_lock.acquire()\n try:\n self._task_num += 1\n \"\"\"the task queue store the function name, parameters and callback function\"\"\"\n self._tasks.append((task, args, callback))\n finally:\n self._task_lock.release()\n\n def get_new_task(self):\n self._task_lock.acquire()\n try:\n if (self._task_num <= 0):\n return ( None, None, None )\n else:\n self._task_num -= 1\n \"\"\"pop out the new task and return\"\"\"\n return self._tasks.popleft()\n finally:\n self._task_lock.release()\n\n def get_queue_count(self):\n self._task_lock.acquire()\n try:\n return len(self._tasks)\n finally:\n self._task_lock.release()\n\n \n\n#test\nif __name__ == \"__main__\":\n\n def test_task1(num,callback):\n print(\"this is task 1: do {0}\".format(num))\n callback()\n\n def test_task2():\n print(\"this is task 2\")\n\n pool = ThreadPool(3, 10)\n\n pool.start()\n for i in range(10): \n pool.queue_task(test_task1,i,test_task2)\n i += 1\n sleep(0.5)\n input('press any key to exit')\n pool.stop()\n\n" }, { "alpha_fraction": 0.4881141185760498, "alphanum_fraction": 0.500792384147644, "avg_line_length": 24.280000686645508, "blob_id": "9cfd1709e8b24d2a263c2b03b5692bdceab367f1", "content_id": "34d067f2027e97cfc0aa59e71a713d3fbc8c40c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 631, "license_type": "no_license", "max_line_length": 42, "num_lines": 25, "path": "/crawling/strategies/omitindex.py", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "'''\nCreated on Feb 15, 2013\n\n@author: Adam57\n'''\nclass OmitIndex(object):\n def Omit(self, html_task):\n \n url = html_task._url\n\n url = url.replace('index.htm','')\n url = url.replace('index.html','')\n url = url.replace('index.jsp','')\n url = url.replace('index.asp','')\n url = url.replace('index.php','')\n \n url = url.replace('main.htm','')\n url = url.replace('main.html','')\n url = url.replace('main.jsp','')\n url = url.replace('main.asp','')\n url = url.replace('main.php','')\n \n html_task.update_url(url)\n \n del url" }, { "alpha_fraction": 0.48275861144065857, "alphanum_fraction": 0.4913793206214905, "avg_line_length": 26.117647171020508, "blob_id": "ca2885137b43919beac555b50b4b47a07fde50d1", "content_id": "108743ed781da72b775bc76ab989a924c10c67e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 464, "license_type": "no_license", "max_line_length": 124, "num_lines": 17, "path": "/newyorktimes/interface/template/index.php", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "\n<div class=\"searchResults\" id=\"searchResults\">\n <? \n\t$result= $GLOBALS['result'];\n\tforeach( $result as $key=>$value)\n\t{\n\t?>\n\t<div >\n\t\t<p><b>Title:</b><a class=\"result\" href=\"<?=$value['url']?>\"><?=$value['title']?></a> <b>Score:</b><?=$value['bm25']?> </p>\n\t\t<p> <b>Date:</b> <?=$value['time']?> <b>Location:</b> <?=$value['location']?></p>\n\t\t<p> -----------</p>\n\t</div>\n\t<?\n\t} \n\t?>\n</div>\n<center><h1><b>MAPS</b></h1></center>\n <div id=\"map-canvas\" ></div>\n\n\n" }, { "alpha_fraction": 0.6576576828956604, "alphanum_fraction": 0.6801801919937134, "avg_line_length": 12.117647171020508, "blob_id": "bb1be600f08dd0764beefa4240c55704d068a661", "content_id": "45d9dd67d778493f0902d4a16da7dc564131c132", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 222, "license_type": "no_license", "max_line_length": 24, "num_lines": 17, "path": "/crawling/config.ini", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "[Downloader]\nThreadnum = 1\nSavePath = ./data\n\n[Parser]\nThreadnum = 1\nNestlevel = 6\n\n[seed]\nkeywords = NBA ZOO\nresult_num = 10\n\n[Mysql]\nhost \t= www.dengxu.me\nuser \t= web_search\npasswd = dengxu_wangqi\ndb \t\t= web_search_engine" }, { "alpha_fraction": 0.500905454158783, "alphanum_fraction": 0.5132198333740234, "avg_line_length": 22.323944091796875, "blob_id": "3c73d9c86828d69039914805878409653e7c74ff", "content_id": "d23dff565b22d5597b5df97bba516810000696f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8283, "license_type": "no_license", "max_line_length": 154, "num_lines": 355, "path": "/indexing/src/generating/analysis_ctrl.cpp", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "#include \"analysis_ctrl.h\"\n#include <sys/stat.h>\n#include <iostream>\n\nusing namespace std;\n\n#define INDEX_CHUNK 409600 //50KB\n#define DATA_CHUNK 20971520 //2.5MB\n\nanalysis_ctrl::analysis_ctrl()\n{\n _dataset_path = \"./dataset/\";\n\n _file_start = 0;\n _file_end = 82;\n _file_now = _file_start;\n _doc_id = 1;\n _word_id =1;\n buffer = new StreamBuffer(12*1024*1024/4);\n mkdir(\"intermediate\", S_IRWXU|S_IRGRP|S_IXGRP);\n buffer->setfilename(\"intermediate/posting\");\n buffer->setpostingsize(12);\n buffer->set_sort(true);\n _time_now = time(0); \n\n}\n\nanalysis_ctrl::~analysis_ctrl()\n{\n if(buffer != NULL)\n delete buffer;\n}\n\nbool analysis_ctrl::start()\n{\n //set display call back\n //display::get_instance()->set_input_call_back(this);\n \n do_it();\n\n return true;\n}\n\nvoid analysis_ctrl::stop()\n{\n //stop display\n display::get_instance()->stop();\n\n}\n\nvoid analysis_ctrl::input_event( char* key )\n{\n\n if( strcmp(key,\"quit\") == 0)\n stop();\n else\n cout<<\"press 'quit' to exit\"<<endl;\n}\n\n// core algorithm\nvoid analysis_ctrl::do_it()\n{\n DataSet data_set(_dataset_path);\n while( get_next_file_name(data_set) )\n {\n //cout<<\"loop\"<<endl;\n int already_len = 0;\n\n //get index data from file\n char* index_data = gzip::uncompress_from_file(data_set._index.c_str(), INDEX_CHUNK, already_len);\n if( index_data == NULL || already_len == 0)\n {\n cout<<\"read index data error: \"<<data_set._index.c_str()<<endl;\n continue;\n }\n\n \n\n //cout<<\"doc_id:\"<<doc_id<<endl;\n //save raw data into orgnized data structer\n original_index index;\n\n if( !save_index(index_data, already_len, index, data_set._file_num) )\n {\n cout<<\"save index data error\"<<endl;\n continue;\n }\n\n free(index_data);\n\n //get html data from file\n char* html_data = gzip::uncompress_from_file(data_set._data.c_str(), DATA_CHUNK, already_len);\n if( html_data == NULL || already_len == 0)\n {\n cout<<\"read html data error :\"<<data_set._data.c_str()<<endl;\n continue;\n }\n\n //parse word from html data \n if(!parse_data(html_data, already_len, index))\n {\n cout<<\"parse index data error\"<<endl;\n continue;\n }\n\n \n free(html_data);\n //break;\n // cout<<\"loop\"<<endl;\n }\n\n //save word map;\n //_word_map\n\n \n StreamBuffer buffer1(50*1024*1024);\n buffer1.setfilename(\"intermediate/word_map.data\");\n buffer1>>_word_map;\n buffer1.savetofile();\n\n //save docs map;\n StreamBuffer buffer2(50*1024*1024);\n buffer2.setfilename(\"intermediate/docs_map.data\");\n buffer2>>_docs_map;\n buffer2.savetofile();\n\n //\n \n buffer->savetofile();\n\n cout<<\"[finish] time consumed: \"<<time(0)-_time_now<<\"s\"<<endl;\n \n}\n\n//read file name\nbool analysis_ctrl::get_next_file_name(DataSet& data_set)\n{\n\n if( _file_now <= _file_end)\n {\n data_set.set_num(_file_now);\n \n _file_now++;\n return true;\n }\n return false;\n}\n\n\nbool analysis_ctrl::parse()\n{\n\n}\n\n\n\nbool analysis_ctrl::parse_data(char* html_data, int len, original_index& index)\n{\n original_index_content index_val;\n int doc_id =0;\n\n index.set_to_start();\n\n\n // get one doc offset and id from index list \n while(index.get_next(doc_id ,index_val))\n {\n \n cout<<\"parsing: \"<<doc_id<<\" => \"<<index_val.url<<\":\"<<index_val.offset<<\":\"<<index_val.len<<endl;\n\n char *pool;\n\n pool = (char*)malloc(2*index_val.len+1);\n\n\n //parsing page\n char* page = new char[index_val.len+1];\n \n memcpy(page, html_data+index_val.offset, index_val.len);\n page[index_val.len]='\\0';\n \n\n int ret = parser((char*)index_val.url.c_str(), page , pool, 2*index_val.len+1);\n \n delete page;\n\n // cout<<pool<<endl;\n //return false;\n //output words and their contexts\n if (ret > 0)\n {\n //printf(\"%s\", pool);\n //save raw data into rgnized data structer\n if( !save_data( doc_id , pool, 2*index_val.len+1) )\n {\n cout<<\"save index data error\"<<endl;\n // continue;\n }\n\n }\n \n free(pool);\n \n \n \n }\n return true;\n \n}\n\nbool analysis_ctrl::save_index(char* index_data , int len ,original_index& index, int file_num)\n{\n if( index_data == NULL || len == 0)\n return false;\n cout<<len<<\" \"<<strlen(index_data)<<endl;\n int pos = 0;\n int offset_val =0;\n while(pos < len)\n {\n string url =\"\", ip=\"\", port=\"\",state=\"\",len=\"\",unknow1=\"\",unknow2=\"\";\n //get host\n if(\n !get_one_word(index_data,pos,url) || \n !get_one_word(index_data,pos,unknow1) ||\n !get_one_word(index_data,pos,unknow2) ||\n !get_one_word(index_data,pos,len) ||\n !get_one_word(index_data,pos,ip) ||\n !get_one_word(index_data,pos,port)||\n !get_one_word(index_data,pos,state)\n )\n break; // if read finish, break\n int len_val = atoi(len.c_str());\n\n // if exit doc id, return it else create new id \n int doc_id = get_doc_id(url.c_str(),file_num, offset_val,len_val);\n index.put(doc_id,(url).c_str(), offset_val,len_val);\n offset_val+=len_val;\n \n }\n\n return true;\n}\n\nbool analysis_ctrl::save_data(int doc_id, char* save_data, int len)\n{\n int pos = 0;\n int offset_val =0;\n\n int percent = _file_end - _file_start == 0? 100 : ( (float)(_file_now -1 - _file_start) / (float)(_file_end - _file_start) )*100;\n \n int pos_count = 0;\n // cout<<\"[-\"<<percent<<\"\\%-][doc:\"<<doc_id<<\"]\"<<endl;\n while(pos < len )\n {\n string word=\"\";\n string context=\"\";\n string positon=\"\";\n\n if(\n !get_one_word(save_data , pos, word) ||\n !get_one_word(save_data , pos, positon) ||\n !get_one_word(save_data , pos, context)\n )\n break;\n\n //cout<<\"[\"<<pos<<\"]\"<<\"word=>\"<<word<<\" pos=>\"<<positon<<\" context=>\"<<context<<endl ;\n\n\n //continue;\n //if it is word \n \n TempLexicon new_lexicon;\n\n new_lexicon.word_id = get_word_id(word);\n new_lexicon.doc_id = doc_id;\n new_lexicon.startpos =pos_count++;//atoi(positon.c_str()); //atoi(positon.c_str());\n\n //cout<<\"[-\"<<percent<<\"\\%-][doc:\"<<new_lexicon.doc_id<<\"] : \"<<word<<\"=>word_id:\"<<new_lexicon.word_id<<\" position:\"<<new_lexicon.startpos<<endl;\n\n //save temp Lexicon\n (*buffer)>>new_lexicon;\n \n \n \n }\n \n //cout<<pos<<\"--------------------------------\"<<endl<<endl<<endl<<endl<<endl;\n\n return true;\n}\n\n//get on word from file\nbool analysis_ctrl::get_one_word(char* source ,int& pos,string& str)\n{\n\n\n char get_num = 0;\n while( source[pos] != '\\0')\n {\n\n if(source[pos] == '\\r' || source[pos]=='\\n' || source[pos] == ' ')\n {\n \n if( get_num == 0)\n {\n pos++;\n\n continue;\n }\n else\n {\n pos++;\n return true;\n }\n }\n else \n {\n str+=source[pos++];\n get_num++;\n //cout<<str.c_str()<<endl;\n }\n }\n //if( source[pos] == '\\0')\n return false;\n}\n\nint analysis_ctrl::get_doc_id(string doc_name,int file_num, int offset, int len)\n{\n\n if(_checker.find(doc_name) != _checker.end())\n { \n cout<<\"doc repeat:\"<<doc_name<<\"=>\"<<_checker[doc_name]<<endl;\n return _checker[doc_name];\n }\n _checker[doc_name]= _doc_id;\n\n _docs_map[_doc_id].doc_name = doc_name;\n _docs_map[_doc_id].file_id = file_num;\n _docs_map[_doc_id].offset = offset;\n _docs_map[_doc_id].len = len;\n return _doc_id++;\n}\n\nint analysis_ctrl::get_word_id(string word)\n{\n if(_word_map.isHas(word))\n { \n // cout<<\"word repeat:\"<<word<<\"=>\"<<_word_map[word]<<endl;\n return _word_map[word];\n }\n\n _word_map[word] = _word_id;\n return _word_id++;\n\n} \n" }, { "alpha_fraction": 0.5739644765853882, "alphanum_fraction": 0.584319531917572, "avg_line_length": 17.73611068725586, "blob_id": "4da99316956535bdd0b6952cebed5748a473baf6", "content_id": "537b2af5bebaad266cbf1f439b8fc5725563d54b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1352, "license_type": "no_license", "max_line_length": 136, "num_lines": 72, "path": "/indexing/src/include/models/WordMap.cpp", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "/*\n * WordMap.cpp\n *\n * Created on: Feb 25, 2013\n * Author: Adam57\n */\n\n#include \"WordMap.h\"\n\nWordMap::WordMap() {\n\t// TODO Auto-generated constructor stub\n\n}\n\nWordMap::~WordMap() {\n\t// TODO Auto-generated destructor stub\n}\n\nbool WordMap::isHas(string key)\n{\n\treturn map.find(key) != map.end();\n}\n\nvoid WordMap::serialize( StreamBuffer &stream )\n{\n\tfor ( std::map<string, int>::iterator it = map.begin(); it!=map.end(); ++it)\n\t{\n\t\t\tint tmp = it->first.length();\n\t\t\tstream.write(&tmp);\n\t\t\tstream.write(it->first.c_str(), it->first.length());\n\t\t\tstream.write(&it->second);\n\t}\n\t\t\t\t\n}\n\n\nvoid WordMap::deserialize( char* buffer, int size )\n{\n\tmap.clear();\n\t//cout<<\"buffer:\"<<buffer<<\"size:\"<<size<<endl;\n\tint offset = 0;\n\tchar key[1000];\n\n\twhile(offset < size)\n\t{\n\t\tint len;\n\t\tmemcpy(&len, buffer+offset, sizeof(int));\n\t\toffset += sizeof(int);\n\n\t \n\t key[len]='\\0';\n\t \tmemcpy(key, buffer+offset, len);\n\t offset+= len;\n\n\t int val;\n\t memcpy(&val, buffer+offset, sizeof(int));\n\t offset += sizeof(int);\n\t \n\n \tmap[key]=val;\n\n \t//cout<<\"word:\"<<key<<\"=>id:\"<<val<<endl;\n // \tcout<<\"url:\"<<key<<\" doc_id:\"<<val.doc_id<<\" file_id:\"<<val.file_id<<\" offset:\"<<val.offset<<\" len:\"<<val.len<<endl;\t \n\t }\n}\n\n\n\nStreamBuffer& operator>>(StreamBuffer &stream, WordMap &map) {\n map.serialize(stream);\n return stream;\n}\n\n\n\n" }, { "alpha_fraction": 0.5690789222717285, "alphanum_fraction": 0.5953947305679321, "avg_line_length": 9.857142448425293, "blob_id": "b53abe8151c1daec037ce561dd8691e56d0fb3fb", "content_id": "7cb7117982eeee2f0cfd7a94ce45537068e80dd0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 304, "license_type": "no_license", "max_line_length": 28, "num_lines": 28, "path": "/indexing/src/include/models/Tuple.h", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "/*\n * Tuple.h\n *\n * Created on: Feb 25, 2013\n * Author: Adam57\n */\n\n#ifndef TUPLE_H_\n#define TUPLE_H_\n\nusing namespace std;\n\nclass Tuple {\npublic:\n\tTuple();\n\tvirtual ~Tuple();\n\nprivate:\n\tstring \tword;\n\tint\t\tword_id;\n\tint\t\tdoc_id;\n\tint\t\tfreq;\n\tint\t\tpos;\n\tstring content;\n\n};\n\n#endif /* TUPLE_H_ */\n" }, { "alpha_fraction": 0.5321811437606812, "alphanum_fraction": 0.5685339570045471, "avg_line_length": 18.988094329833984, "blob_id": "7c3c9082ee0786b1690b9753695bf8159541c7c0", "content_id": "3c9d37f022ae247547968e4af9be850e7e53436b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1678, "license_type": "no_license", "max_line_length": 92, "num_lines": 84, "path": "/indexing/src/include/utility/time_ex.h", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "/*Author: derrick*/\n#ifndef ___Time_H_\n#define ___Time_H_\n\n#pragma warning (push)\n#pragma warning (disable:4996)\n#pragma warning (disable:4244)\n#include <memory.h>\n#include <time.h>\n#include <stdio.h>\n\nconst time_t _day\t= 60 * 60 * 24;\nconst time_t _hour\t= 60 * 60 ;\nconst time_t _min\t= 60 ;\n\ntemplate <typename T>\nclass time_ex\n{\npublic:\n\ttime_ex(void):_time_point(0){memset(_time_format , 0 , 128);}\n\t~time_ex(void){}\npublic:\n\tvoid\tset_time_point(){ _time_point = (T)time(NULL);}\n\n\tT\t\tget_time_point(){ return _time_point;}\n\n\tT\t\tget_time_span() { return (T)time(NULL) - _time_point ;}\n\n\tchar*\tget_span_string(T span_time)\n\t{\n\n\t\tint count = 0;\n\t\ttime_t t = (time_t)span_time;\n\n\t\t*_time_format = '\\0';\n\t\tif( t > _day && count < 2)\n\t\t{\n\t\t\tsprintf(_time_format , \"%d day(s)\" , t / _day);\n\t\t\tt = t % _day;\n\t\t\tcount++;\n\t\t}\n\t\tif( t > _hour && count < 2)\n\t\t{\n\t\t\tsprintf(_time_format , \"%s %02d hour(s)\" ,_time_format , t / _hour);\n\t\t\tt = t % _hour;\n\t\t\tcount++;\n\t\t}\n\t\tif( t > _min && count < 2)\n\t\t{\n\t\t\tsprintf(_time_format , \"%s %02d min(s)\" ,_time_format , t / _min);\n\t\t\tt = t % _min;\n\t\t\tcount++;\n\t\t}\n\t\tif( count < 2)\n\t\tsprintf(_time_format , \"%s %02d sec(s)\" ,_time_format , t );\n\n\t\treturn _time_format;\n\t}\n\n\n\tchar*\tget_time_string(T time)\n\t{\n\t\ttime_t t = (time_t)time;\n\t\ttm* p = localtime(&t); \n\t\tsprintf(_time_format , \"%04d-%02d-%02d %02d:%02d:%02d\" , p->tm_year + 1900 , p->tm_mon + 1\n\t\t\t, p->tm_mday , p->tm_hour , p->tm_min , p->tm_sec );\n\t\treturn _time_format;\n\t\t\n\t}\n\n\tT\t\tget_time_now()\n\t{\n\t\treturn (T)time(NULL);\n\t}\n\nprivate:\n\tchar\t_time_format[128];\n\tT\t\t_time_point;\n};\nstatic time_ex<long>\t_Time32;\nstatic time_ex<time_t>\t_Time64;\n\n#pragma warning (pop)\n#endif //___Time_H_" }, { "alpha_fraction": 0.5484745502471924, "alphanum_fraction": 0.5532203316688538, "avg_line_length": 13.057143211364746, "blob_id": "fda574d59af707788fd8608b1b8812d6c06efad2", "content_id": "d7abdb79d70336a4868460a7de4f7292d81ce2d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1475, "license_type": "no_license", "max_line_length": 70, "num_lines": 105, "path": "/indexing/src/include/utility/timer.cpp", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "/*Author: derrick*/\n#include \"timer.h\"\n\ntimer*\ttimer::_this\t= NULL;\nlock\ttimer::_instance_lock;\n\ntimer::timer()\n:_reference( 0 )\n,_is_close( false)\n{\n\n}\n\ntimer::~timer()\n{\n\n}\n\ntimer* timer::get_instance()\n{\n\tLockHelper( _instance_lock );\n\tif( _this == NULL)\n\t{\n\t\t_this = new timer;\n\t}\n\n\treturn _this;\n}\n\nvoid timer::do_register( func f , void* data , unsigned short times)\n{\n\tLockHelper( _list_lock );\n\n\tstruct_func new_func;\n\tnew_func._now\t\t= 0 ;\n\tnew_func._p_func\t= f ;\n\tnew_func._times\t\t= times;\n\tnew_func._data\t\t= data;\n\t_func_list.push_back( new_func );\n\n\tif( _reference == 0 )\n\t{\n\t\t_is_close = false;\n\t\t_System.create_thread( thread , this);\n\t}\n\n\t++_reference;\n}\n\nvoid timer::do_unregister( func f )\n{\n\t{\n\t\tLockHelper( _list_lock );\n\t\tstd::list<struct_func>::iterator iter ; \n\t\tfor( iter = _func_list.begin() ; iter != _func_list.end() ; )\n\t\t{\n\t\t\tif((*iter)._p_func == f)\n\t\t\t{\n\t\t\t\t_func_list.erase( iter++ ); \n\t\t\t\t\n\t\t\t\t_is_close = --_reference <= 0;\n\t\t\t\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\titer++;\n\t\t\t}\n\t\t}\n\t}\n\n\tif(_is_close)\n\t{\n\t\tLockHelper( _thread_lock );\n\t}\n\t\n}\n\nvoid timer::thread( void *p)\n{\n\t((timer*)p)->thread();\n}\n\nvoid timer::thread()\n{\n\tLockHelper( _thread_lock );\n\n\twhile( !_is_close )\n\t{\n\t\tLockHelper( _list_lock );\n\n\t\tstd::list<struct_func>::iterator iter = _func_list.begin(); \n\t\twhile( iter != _func_list.end() )\n\t\t{\n\t\t\tif( ++iter->_now >= iter->_times )\n\t\t\t{\n\t\t\t\titer->_p_func(iter->_data);\n\t\t\t\titer->_now = 0; \n\t\t\t}\n\t\t\titer++;\n\t\t}\n\n\t\tsleep(20);\n\t}\n}" }, { "alpha_fraction": 0.5399448871612549, "alphanum_fraction": 0.5399448871612549, "avg_line_length": 18.105262756347656, "blob_id": "4691e24390166b6ec9074a4bbff4923bd21ff981", "content_id": "b96a62ba9cc7f8cb30ddbc0f1140863ca9d27b8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 363, "license_type": "no_license", "max_line_length": 56, "num_lines": 19, "path": "/indexing/Makefile", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "SRC_DIR= $(CURDIR)/src\nMAKE_DIR= $(CURDIR)\nOBJ_DIR= ./build\nDIST_DIR= ../dist\nINSTALL_PREFIX= ../test\n\n\n.SUFFIXES: \n\nall:\n\n%:\n\t[ -d $(OBJ_DIR) ] || mkdir -p $(OBJ_DIR)\n\t$(MAKE) -C $(OBJ_DIR) -f $(MAKE_DIR)/Makefile.include \\\n\t\t\t\t\t\t\tMAKE_DIR=$(CURDIR) \\\n\t\t\t\t\t\t\tSRC_DIR=$(SRC_DIR) \\\n\t\t\t\t\t\t\tDIST_DIR=$(DIST_DIR) \\\n\t\t\t\t\t\t\tINSTALL_PREFIX=$(INSTALL_PREFIX) \\\n\t\t\t\t\t\t\t$@\n" }, { "alpha_fraction": 0.569254994392395, "alphanum_fraction": 0.5813221335411072, "avg_line_length": 13.022058486938477, "blob_id": "633150caf068a733da63f9b113fed1725660a9e1", "content_id": "951f67368819afafc057b255091a68efeb6e3fa7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1906, "license_type": "no_license", "max_line_length": 95, "num_lines": 136, "path": "/indexing/src/include/utility/display.cpp", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "/*Author: derrick*/\n\n#include \"display.h\"\n#include \"time_ex.h\"\n//#include \"conio.h\"\n#include <unistd.h>\n\nusing namespace std;\n#pragma warning (disable:4996)\n\ndisplay*\tdisplay::_this = NULL;\n\ndisplay::display()\n:_state(false)\n,_progrma(\"\")\n,_version(\"\")\n,_extern(\"\")\n,_p_call_back(NULL)\n{\n\t\n}\n\ndisplay::~display()\n{\n\tif( _this != NULL)\n\t\tdelete _this;\n\t_this = NULL;\n}\n\ndisplay* display::get_instance()\n{\n\tif( _this == NULL )\n\t\t_this = new display;\n\treturn _this;\n}\n\nvoid display::run()\n{\n\t_state = true;\n\n//\treg_commond(\"?\",\"\",\"for help\");\n\t//reg_commond(\"error\",\"\",\"\");\n\t_Time32.set_time_point();\n\n\t_System.create_thread(show , this);\n\n\tcommand();\n}\n\nvoid display::show(void* p)\n{\n\tdisplay *pthis = (display*)p;\n\tpthis->show();\n}\n\nvoid display::show()\n{\n\twhile(_state)\n\t{\n\t\ttitle();\n\t\n\t\tbody();\n\n\t\tsleep(500);\n\t}\n}\n\nvoid display::title()\n{\n\tchar temp_show[255];\n\tsprintf(temp_show , \"%s\" , _progrma.c_str() );\n\t\n\tsprintf(temp_show , \"%s | %s \" , temp_show , _version.c_str());\n\n\tsprintf(temp_show , \"%s | %s \" , temp_show ,_Time32.get_span_string(_Time32.get_time_span()));\n\n\tif( _extern != \"\")\n\tsprintf(temp_show , \"%s | %s \" , temp_show , _extern.c_str());\n\n\t//SetConsoleTitle(temp_show);\n\t\n}\n\n\nvoid display::body()\n{\n\t\n}\n\nvoid display::stop()\n{\n\t_state = false;\n}\n\nvoid display::set_input_call_back(d_key_event* p_call_back , int type )\n{\n\t_p_call_back\t= p_call_back;\n\t_call_back_type\t= type;\n}\n\nvoid display::command()\n{\n\tif( _p_call_back == NULL)\n\t{\n\t\twhile( _state )\n\t\t{\n\t\t\tsleep(50);\n\t\t}\n\t\treturn;\n\t}\n\t\n\tchar buf[255];\n\tstring last_com;\n\tbool state = true;\n\twhile( _state )\n\t{\n\n\t\tif( _call_back_type == 0 )\n\t\t{\n\t\t\tprintf(\">\");\n\t\t\tscanf(\"%s\" , buf);\n\t\t\t_p_call_back->input_event( buf );\n\t\t}\n\t\telse if ( _call_back_type == 1)\n\t\t{\n\t\t\tchar c = getchar();\n\t\t\t_p_call_back->input_event( &c );\n\t\t}\n\t\t\n\t}\n}\n\nvoid display::reg_commond(char* com_name , char* describe)\n{\n\t_commond_all[com_name] = describe;\n}" }, { "alpha_fraction": 0.5259786248207092, "alphanum_fraction": 0.5430604815483093, "avg_line_length": 39.739131927490234, "blob_id": "a59f848ec40ab3bfb4e643a8ddc51edef352ad6e", "content_id": "1ef4e85fd7369d81c7cf30fd02cb7a0d3b2c8109", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2810, "license_type": "no_license", "max_line_length": 121, "num_lines": 69, "path": "/search/interface/template/header.php", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>Web Search Engine - CS6913</title>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <meta name=\"description\" content=\"\">\n <meta name=\"author\" content=\"\">\n\n <!-- Le styles -->\n <link href=\"<?=CSS?>bootstrap.css\" rel=\"stylesheet\">\n <link href=\"<?=CSS?>bootstrap-responsive.css\" rel=\"stylesheet\">\n <link href=\"<?=CSS?>docs.css\" rel=\"stylesheet\">\n <link href=\"<?=CSS?>mystyle.css\" rel=\"stylesheet\">\n\n <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->\n <!--[if lt IE 9]>\n <script src=\"assets/js/html5shiv.js\"></script>\n <![endif]-->\n\n <!-- Le fav and touch icons -->\n <link rel=\"apple-touch-icon-precomposed\" sizes=\"144x144\" href=\"assets/ico/apple-touch-icon-144-precomposed.png\">\n <link rel=\"apple-touch-icon-precomposed\" sizes=\"114x114\" href=\"assets/ico/apple-touch-icon-114-precomposed.png\">\n <link rel=\"apple-touch-icon-precomposed\" sizes=\"72x72\" href=\"assets/ico/apple-touch-icon-72-precomposed.png\">\n <link rel=\"apple-touch-icon-precomposed\" href=\"assets/ico/apple-touch-icon-57-precomposed.png\">\n <link rel=\"shortcut icon\" href=\"assets/ico/favicon.png\">\n\n <script type=\"text/javascript\">\n var _gaq = _gaq || [];\n _gaq.push(['_setAccount', 'UA-146052-10']);\n _gaq.push(['_trackPageview']);\n (function() {\n var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;\n ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';\n var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);\n })();\n </script>\n\n </head>\n\n <body data-spy=\"scroll\" data-target=\".bs-docs-sidebar\">\n\n <!-- Navbar\n ================================================== -->\n <div class=\"navbar navbar-inverse navbar-fixed-top\">\n <div class=\"navbar-inner\">\n <div class=\"container\">\n <button type=\"button\" class=\"btn btn-navbar\" data-toggle=\"collapse\" data-target=\".nav-collapse\">\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n </button>\n <a class=\"brand\" href=\"./index.html\">dengxu &amp; wangqi </a>\n <div class=\"nav-collapse collapse\">\n <ul class=\"nav\">\n <?\n foreach ($GLOBALS[navigation] as $title => $url)\n {\n echo \"<li class=''>\";\n echo \"<a href=\".$url.\">\".$title.\"</a>\";\n echo \" </li>\";\n } \n ?>\n \n </ul>\n </div>\n </div>\n </div>\n </div>" }, { "alpha_fraction": 0.7333333492279053, "alphanum_fraction": 0.7333333492279053, "avg_line_length": 31.66666603088379, "blob_id": "74f4710bf1156d0c85ab3874d3a3d1e86ae3f754", "content_id": "34b93c44078c99e4a2d79aa6f2e0b89b066f0827", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 195, "license_type": "no_license", "max_line_length": 63, "num_lines": 6, "path": "/newyorktimes/interface/test.php", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "<?php\n// outputs the username that owns the running php/httpd process\n// (on a system with the \"whoami\" executable in the path)\nexec('demo/searching happy newyork',$output);\nvar_dump($output);\n?>" }, { "alpha_fraction": 0.6356877088546753, "alphanum_fraction": 0.6369268894195557, "avg_line_length": 24.25, "blob_id": "194fb7e684a0f643e6d83c6ccd86b6299ab92eb9", "content_id": "566f8dbe601e2be8009f730dedb3ffdae0e01bb2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 807, "license_type": "no_license", "max_line_length": 95, "num_lines": 32, "path": "/newyorktimes/interface/gen_maps.php", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "<?php\n\ninclude_once(\"maps/GoogleMap.php\");\ninclude_once(\"maps/JSMin.php\");\n\n$MAP_OBJECT = new GoogleMapAPI(); $MAP_OBJECT->_minify_js = isset($_REQUEST[\"min\"])?FALSE:TRUE;\n//setDSN is optional\n//$MAP_OBJECT->setDSN(\"mysql://user:password@localhost/db_name\");\n//var_dump($MAP_OBJECT);\n//$geocodes = $MAP_OBJECT->getGeoCode(\"Vail, CO\");\n//var_dump($geocodes);\n\n$geocodes_full = $MAP_OBJECT->geoGetCoordsFull(\"Vail, CO\");\n\n\n$lines = file('location.data0');\n// Loop through our array, show HTML source as HTML source; and line numbers too.\nforeach ($lines as $line_num => $line) {\n\tif($line == \"\\n\")\n\t\tcontinue;\t\n $geocodes = $MAP_OBJECT->getGeoCode($line);\n var_dump($geocodes);\n \n echo $line.\"<br>\";\n echo $geocodes['lon'].\"<br>\";\n echo $geocodes['lat'].\"<br>\";\n break;\n}\n\necho \"ok!\\n\";\n\n?>" }, { "alpha_fraction": 0.6747967600822449, "alphanum_fraction": 0.6747967600822449, "avg_line_length": 13.909090995788574, "blob_id": "3c477d339768ff0cbfc1c7f1828a4824467ba43e", "content_id": "fc1134a0916a119d4e7a1bc4873c2f911898b32b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 492, "license_type": "no_license", "max_line_length": 68, "num_lines": 33, "path": "/newyorktimes/src/include/utility/path_finder.h", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "#ifndef __PATH_FINDER_H_\n#define __PATH_FINDER_H_\n#include <string>\n#include <deque>\n#include <iostream>\n\nstruct STRU_PATH\n{\n\tstd::string name;\n\tstd::string path;\n};\n\nclass PathFinder\n{\n\npublic:\n\tPathFinder();\n\t~PathFinder();\n\tbool get_next_file(std::string& file_name, std::string& file_path);\nprivate:\n\tvoid load_folder();\n\tint add_files(std::string dir);\nprivate:\n\tint now_year;\n\tint now_month;\n\tint now_day;\n\tint end_year;\n\tstd::deque<STRU_PATH> _files;\n\t\n\n};\n\n#endif //__PATH_FINDER_H_\n" }, { "alpha_fraction": 0.470085471868515, "alphanum_fraction": 0.49857550859451294, "avg_line_length": 19.705883026123047, "blob_id": "d7f2e50688983437a169dfca581e38e126dc975a", "content_id": "9a0b12f343d8ab32523e269b54dfb0217930c6c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 351, "license_type": "no_license", "max_line_length": 40, "num_lines": 17, "path": "/crawling/strategies/bookmarkhandler.py", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "'''\nCreated on Feb 14, 2013\n\n@author: Adam57\n'''\nclass BookMarkHandler(object):\n \n def BookMarkChecker(self,html_task):\n url = list(html_task._url)\n '''block links starts with #''' \n if len(url) <= 0: \n return False\n \n if url[0] == \"#\":\n return True\n else:\n return False" }, { "alpha_fraction": 0.5484444499015808, "alphanum_fraction": 0.551111102104187, "avg_line_length": 19.089284896850586, "blob_id": "7c1015e71e419d8147fea796e901aaf3736fc2f2", "content_id": "2f102afa82854f58bcb3eb7032fee6a72f9ab6b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1125, "license_type": "no_license", "max_line_length": 84, "num_lines": 56, "path": "/newyorktimes/src/include/utility/gzip.cpp", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "#include \"gzip.h\"\n#include <zlib.h>\n#include <iostream>\nusing namespace std;\ngzip::gzip()\n{\n\n}\n\ngzip::~gzip()\n{\n\n}\n\nchar* gzip::uncompress_from_file(const char* file_name, int size, int& already_len )\n{\n\tif( file_name == NULL)\n\t\treturn NULL;\n\n\tgzFile *p_file;\n p_file=(gzFile *)gzopen(file_name,\"r\");\n if(p_file == NULL)\n {\t\n \tcout<<\"gzip::uncompress - open file fail -\"<<endl;\n \treturn NULL;\n }\n already_len = 0;\n char *buffer=(char *)malloc(size);\n int oldSize=size;\n while (!gzeof(p_file))\n { \n already_len+=gzread(p_file, buffer+already_len, oldSize); \n if (already_len==size) // Reallocate when buffer is full\n {\n oldSize=size;\n size*=2;\n buffer=(char *)realloc(buffer,size);\n }\n }\n\n return buffer;\n}\n\nbool gzip::compress_to_file(const char* file_name, char* data, int len)\n{\n if( file_name == NULL || data == NULL || len ==0)\n return false;\n gzFile *fi = (gzFile *)gzopen(file_name,\"wb\");\n\n if( fi == NULL)\n return false;\n\n gzwrite(fi, data,len);\n gzclose(fi);\n\n}\n" }, { "alpha_fraction": 0.5882353186607361, "alphanum_fraction": 0.5882353186607361, "avg_line_length": 8.714285850524902, "blob_id": "920a475014870df3958da00b0d73a88533c7bb54", "content_id": "bf241ec70fb15742a3b001c70e46fef97bb0d431", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 68, "license_type": "no_license", "max_line_length": 31, "num_lines": 7, "path": "/search/interface/index.php", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "<?php\n\nrequire_once( './loader.php' );\n\nload_template(\"index\");\n\n?>\n" }, { "alpha_fraction": 0.6576182246208191, "alphanum_fraction": 0.6576182246208191, "avg_line_length": 18.70689582824707, "blob_id": "2aa77654438430a2dccfd7fef3bb885dabc94489", "content_id": "d3e3d42ff1d02407f23a11741d3474205a241880", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1142, "license_type": "no_license", "max_line_length": 86, "num_lines": 58, "path": "/indexing/src/include/models/original_index.h", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "#ifndef __ORIGINAL_INDEX_H__\n#define __ORIGINAL_INDEX_H__\n\n\n#include <string>\n#include <map>\n#include <iostream>\nusing namespace std;\n\nstruct original_index_content\n{\n\tstring url;\n\tint offset;\n\tint len;\n};\n\nclass original_index\n{\npublic:\n\tbool put(int id, string url, int offset, int len)\n\t{\n\t\tif(_original_index.find(id) != _original_index.end())\n\t\t\treturn false;\n\t\toriginal_index_content one;\n\t\tone.url = url;\n\t\tone.offset = offset;\n\t\tone.len = len;\n\t\t_original_index[id] = one;\n\t}\n\tbool get(int id, original_index_content & content)\n\t{\n\t\tif( _original_index.find(id) == _original_index.end())\n\t\t\treturn false;\t\n\t\tcontent = _original_index[id];\n\t}\n\tvoid set_to_start()\n\t{\n\t\t_it = _original_index.begin();\n\t}\n\n\tbool get_next(int& id,original_index_content& content)\n\t{\n\t\tif( _it == _original_index.end())\n\t\t\treturn false;\n\t\tcontent = _it->second;\n\t\tid = _it->first;\n\t\t_it++;\n\t\treturn true;\n\t}\n\nprivate:\n\t//key=> doc_id\n\t//value original_index_content[ \"html url\", \"doc offset start posistion\", \"data len\"]\n\tmap<int , original_index_content> _original_index;\n\tmap<int , original_index_content>::iterator _it;\n};\n\n#endif //__ORIGINAL_INDEX_H__" }, { "alpha_fraction": 0.7347449660301208, "alphanum_fraction": 0.7429417371749878, "avg_line_length": 59.83333206176758, "blob_id": "26f0cb06e27442c96d3dec6df1409b8b491c92d3", "content_id": "54caf0b691da41dd7f5497fb4983faa3ae366186", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 4392, "license_type": "no_license", "max_line_length": 392, "num_lines": 72, "path": "/indexing/readme.txt", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "CS 6913 Spring 2013\nWeb Search Engine\nHomeWork 2\n\nXu Deng, Qi Wang\n\n[How to run the program:]\n1.cd indexing/ (go to the root folder of source code )\n2.gmake \t\t\t (make the whole poject, will generate two executable files : generating and merge, \n\t\t\t\t\t\tthese two files will be generated under the 'test' folder)\n3.uncompress the data into the 'test' folder which should named 'dataset'\n4.go to the 'test' folder, \n\trun ./generate \n\t\tto generate all the intermediate posting , doc_id table and word_id table \n\trun ./merge \n\t\tto merge the intermediate posting to the final posting lists and gentate inverted index\t \n\n[Filelist:]\n\t\n\treadme.txt\n\tmakefile files\n\tinclude.models.orignal_index.h\t\tstore the orignal data from the index file corresponding to the html data\n\tinclude.models.streamBuffer.h\t\ta buffer that stores the data can auto save to file when the data reaches a particular size\n\tinclude.models.streamBuffer.cpp\t\tfunction definitions of streamBuffer\n\tinclude.models.TempleLexicon.h\t\tintermediate posting data structure\n\tinclude.models.WordMap.cpp\t\t\tuse to store the word_id table and url_table\n\t\n\tinclude.utility.display.h\t\t\tdisplay with user input interaction for program testing\n\tinclude.utility.display.cpp\t\t\tfunction definitions of display\n\tinclude.utility.gizp.h\t\t\t\timplement gizp compression\n\tinclude.utility.gizp.cpp\t\t\tfunction definitions of gizp\n\t\n\tinclude.parser.h\t\t\t\t\tparse posting information from the raw data, adapted from the parser on the website\n\tinclude.parser.c\t\t\t\t\tfunction definitions of parser\n\t\n\tmerge.heap.h\t\t\t\t\t\timplement the heap structure and some function definitions of heap and functions used in merge\n\tmerge.merge.cpp\t\t\t\t\t\timplement the merge process\n\t\n\tgenerating.analysis_ctrl.h\t\t\timplement simultaneously reading data from index file and raw data file, generating\n\t\t\t\t\t\t\t\t\t\tdata structures of word_id table url_id table and intermediate postings\n\tgenerating.analysis_ctrl.h\t\t\tfunction definitions of analysis_ctrl\n\tgenerating.cpp\t\t\t\t\t\trun analysis_ctrl\n\t\n[Data Structure:]\n\tdoc_id table\t\t\t\t\t\tassgin each (string)url(since each url corresponds to a doc) an int id, \n\t\t\t\t\t\t\t\t\t\timplemented by Class WordMap\n\t\t\t\t\t\t\t\t\t\tthe store format in memory is int(doc_id) int(url_length) char[](url)\n\tword_id table \t\t\t\t\t\tassgin each (string)word an int id, implemented by Class WordMap\n\t\t\t\t\t\t\t\t\t\tthe store format in memory is int(word_id) int(word_length) char[](word)\n\tintermediate posting\t\t\t\t(int)word_id (int)doc_id (int)postion each intermediate posting takes up 12 bytes\n\t\t\t\t\t\t\t\t\t\timplemented by Class TempleLexicon\n\t\t\t\t\t\t\t\t\t\tthe store format in memory is int(word_id) int(doc_id) int(postion)\n\t\t\t\t\t\t\t\t\t\tAnd all the intermediate postings in a particular file is ordered by word_id then doc_id then postion\n\tinverted index\t\t\t\t\t\tthe store format in memory is int(word id) int(file_id) int(offset)\n\t\n\tfinal posting lists\t\t\t\t\tthe store format in memory is(each element is int, taking up 4 bytes):\n\t\t\t\t\t\t\t\t\t\t(pos_1_1,pos_1_2,...,pos_1_n, doc_id1, freq), (pos_2_1,pos_2_2,...,pos_2_n, doc_id2,freq),...,\n\t\t\t\t\t\t\t\t\t\t(pos_m_1,pos_m_2,...,pos_m_n, doc_id2, freq) this list belongs to a word, but we don't write this word into this structure, we mantain an offset and a filenum for each word to fetch this posting list whenever we need it.\n[Breif Description:]\n\t1.Parsing Phase:\t\t\t\t\tAccording to the index files and raw data files we generate doc_id table and word_id table\n\t\t\t\t\t\t\t\t\t\tand a set of files of intermediate postings, in each of these files, the postings is ordered as mentioned above\n\t2.Merge Phase:\t\t\t\t\t\tAll the intermediate postings are feed into the merge module, according to the file numbers \n\t\t\t\t\t\t\t\t\t\twe build a min heap of that size, everytime we extract the root of the heap, we fill in another intermediate posting from the file of the root, for each element in the heap, we build a buffer to read data from the correspondin file and another two StreamBuffer objects for writing inverted index and corresponding posting lists, in this way we implement the I/O-efficient mergesort.\n\t\t\t\t\t\t\t\t\t\t\n[Special Features beyond basic requirement:]\n\t1. gizp compression out of main memory, uncompressed in main memory, including the intermediate posting\n\t2. add postion info in the inverted index\n\t\n[Statistics & Performance:]\n\t1. base on the small_set( );\n\t\tgenerating and sort will finish all the docs in \n\t\tMerge will finish all the docs in \t\t\t\t\t\t\t\t\n\t\n\t" }, { "alpha_fraction": 0.5796371102333069, "alphanum_fraction": 0.5796371102333069, "avg_line_length": 22.0930233001709, "blob_id": "e92a397d50d3334a25f03e414e583b39c94de8c8", "content_id": "2e71f30c5967f1bf5cd7e12491228127f8fd9a17", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 992, "license_type": "no_license", "max_line_length": 153, "num_lines": 43, "path": "/search/interface/loader.php", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "<?php\n\nerror_reporting( E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_ERROR | E_WARNING | E_PARSE | E_USER_ERROR | E_USER_WARNING | E_RECOVERABLE_ERROR );\n\n/** Define ABSPATH as this file's directory */\ndefine( 'ABSPATH', dirname(__FILE__) . '/' );\ndefine( 'WSE_INC', ABSPATH.'include/' );\ndefine( 'TEMPLEATE',ABSPATH. 'template/' );\ndefine( 'CSS', './css/' );\ndefine( 'IMG', './img/' );\ndefine( 'JS', './js/' );\n//require_once( ABSPATH . WSE_INC . '/load.php' );\n//require_once( ABSPATH . WSE_INC . '/version.php' );\n\nfunction load_template( $page )\n{\n\t//echo ABSPATH;\n\tload_header();\n\trequire_once(TEMPLEATE.$page.\".php\");\n\tload_footer();\n}\n\nfunction load_header()\n{\n\tglobal $navigation;\n\t$navigation = array(\n\t \"Search\" => \"./index.php\",\n\t \"Image\" => \"#\",\n\t \"Maps\" => \"#\",\n\t \"Play\" => \"#\",\n\t \"Youtube\" => \"#\",\n\t \"Github\" => \"#\",\n\t \"About\" => \"#\"\n\t);\n\n\trequire_once(TEMPLEATE.\"header.php\");\n}\n\nfunction load_footer()\n{\n\trequire_once(TEMPLEATE.\"footer.php\");\n}\n?>" }, { "alpha_fraction": 0.5832363367080688, "alphanum_fraction": 0.5890570282936096, "avg_line_length": 13.818965911865234, "blob_id": "01b4eb72332ec030149b033cad2f280308a4cf4f", "content_id": "bffde829ad51da58d2b6eb3e753b1598a358a165", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1718, "license_type": "no_license", "max_line_length": 74, "num_lines": 116, "path": "/newyorktimes/src/include/utility/shell.cpp", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "/*Author: derrick*/\n#include \"shell.h\"\n#include \"iostream\"\nusing namespace std;\n#pragma warning ( disable:4996 )\n\nshell::shell()\n{\n\t_save_count = 50;\n\t_cmd_pos = 0;\n\t_history_cmd.resize(50,\"\");\n}\n\nshell::~shell()\n{\n\n}\nvoid shell::test()\n{\n\tstart();\n\t\n}\n\nvoid shell::start()\n{\n\t_System.create_thread( fire_recv_thread , this );\n}\n\nvoid shell::stop()\n{\n\n}\n\nvoid shell::reg_command( std::string cmd_text , ...)\n{\n\t\n}\n\nvoid shell::fire_recv_thread(void *p)\n{\n\t((shell*)p)->thread_recv();\n}\n\nvoid shell::thread_recv()\n{\n\tint ch;\n\twhile( true )\n\t{\n\n\t\tch = getchar();\n\t\t//printf(\"%d\\r\\n\",ch);\n\n\t\tswitch( ch )\n\t\t{\n\t\t\tcase\tshell_arrow\t\t:\t\n\t\t\t\t{\n\t\t\t\t\tch = getchar();\n\t\t\t\t\tswitch ( ch )\n\t\t\t\t\t{\n\t\t\t\t\t\tcase\tshell_up\t:\tget_prev_command();show_current_command();break;\n\t\t\t\t\t\tcase\tshell_down\t:\tget_next_command();show_current_command();break;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\tcase\tshell_backspace\t:\tbackspace();break;\n\t\t\tcase\tshell_tab\t\t:\tbreak;\n\n\t\t\tcase\tshell_enter\t\t: show_ch(ch);inster_command(ch);add_command();break;\n\t\t\tdefault\t\t\t\t\t: show_ch(ch);inster_command(ch);break;\n\t\t}\n\t\t\n\t}\n}\n\nvoid shell::show_ch(int ch)\n{\n\tprintf( \"%c\" , (char)ch );\n}\nvoid shell::show_current_command()\n{\n\tclear_line();\n\tprintf( \"%s\" , _current_cmd.c_str() );\n}\n\nvoid shell::add_command()\n{\n\t_history_cmd[ ++_cmd_pos ] = _current_cmd ;\n\t_current_cmd = \"\";\n\tclear_line();\n}\nvoid shell::backspace()\n{\n\n}\n\nvoid shell::get_next_command()\n{\n\tif( _cmd_pos < _history_cmd.size() )\n\t\t_current_cmd = _history_cmd[ ++_cmd_pos] ;\n}\n\nvoid shell::get_prev_command()\n{\n\tif( _cmd_pos > 1 )\n\t\t_current_cmd = _history_cmd[ --_cmd_pos] ;\n}\n\nvoid shell::inster_command( int ch )\n{\n\t_current_cmd.push_back( (char)ch );\n}\n\nvoid shell::clear_line()\n{\n\tprintf(\"\\r\\t\\t\\t\\t\\t\\r\");\n}" }, { "alpha_fraction": 0.63919597864151, "alphanum_fraction": 0.647236168384552, "avg_line_length": 16.456140518188477, "blob_id": "6a45a0fd9bfe176ce718e3052c57aa49fec606da", "content_id": "117fdc1ea5668c87cd57dcc61532fd35607f1310", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 995, "license_type": "no_license", "max_line_length": 37, "num_lines": 57, "path": "/crawling/models/safe_queue.py", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "\"\"\"\nCreated on Feb 5, 2013\n\n@author: derrick\n\n\"\"\"\n#from queue import deque #python3.3\nfrom collections import deque\nfrom threading import Condition\nfrom threading import Lock\n\nclass SafeQueue( object ):\n\tdef __init__(self):\n\t\tself._data_queue = deque()\n\t\tself._lock = Condition(Lock())\n\n\n\tdef append(self, data ):\n\t\tself._lock.acquire()\n\t\ttry:\n\t\t\tself._data_queue.append( data )\n\t\tfinally:\n\t\t\tself._lock.release()\n\t\t\n\n\tdef pop_left(self):\n\t\tself._lock.acquire()\n\t\ttry:\n\t\t\tif ( len(self._data_queue) == 0 ):\n\t\t\t\treturn None\n\t\t\treturn self._data_queue.popleft()\n\t\tfinally:\n\t\t\tself._lock.release()\n\n\tdef clear(self):\n\t\tself._lock.acquire()\n\t\ttry:\n\t\t\tself._data_queue.clear()\n\t\tfinally:\n\t\t\tself._lock.release()\n\t\t\t\n\tdef has_value(self,value):\n\t\tself._lock.acquire()\n\t\ttry:\n\t\t\tif value in self._data_queue:\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\t\tfinally:\n\t\t\tself._lock.release()\n\n\tdef size(self):\n\t\tself._lock.acquire()\n\t\ttry:\n\t\t\treturn len(self._data_queue)\n\t\tfinally:\n\t\t\tself._lock.release()\n" }, { "alpha_fraction": 0.5320754647254944, "alphanum_fraction": 0.5660377144813538, "avg_line_length": 16.2391300201416, "blob_id": "b2a0eb390922d8c5c57a9b083f9e0007e978d0cb", "content_id": "9e023288acf1e1b49c69ce0bb51dc23d76e179c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 795, "license_type": "no_license", "max_line_length": 50, "num_lines": 46, "path": "/crawling/models/status.py", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "\n\"\"\"\nCreated on Feb 2, 2013\n\n@author: derrick\n\n\"\"\"\nfrom models.html import Html\nfrom models.safe_loop_array import SafeLoopArray\n\nclass Status:\n\tdef __init__(self):\n\t\t\n\t\t\"\"\"--- system ---\"\"\"\n\t\tself._sys_start\t\t\t= 0\n\n\n\t\t\"\"\"--- downloads ---\"\"\"\n\t\tself._download_id\t\t= 0\n\t\tself._download_times \t= 0\n\t\tself._download_size \t= 0\n\t\tself._sites\t\t\t\t= 0\n\t\tself._recent_url\t\t= SafeLoopArray( Html(\"#\"),10)\n\t\t\n\t\t\n\n\t\t\"\"\"--- parse ---\"\"\"\n\t\tself._parse_times\t\t= 0\n\t\tself._early_visit\t\t= 0\n\t\tself._cgi\t\t\t\t= 0\n\t\tself._robot\t\t\t\t= 0\n\t\tself._nestlv\t\t\t= 0\n\t\tself._abandon\t\t\t= 0\n\t\tself._scheme_type\t\t= 0\n\t\tself._bookmark\t\t\t= 0\n\t\tself._file_type\t\t\t= 0\n\n\t\t\"\"\"--- error ---\"\"\"\n\t\tself._socket_timeout\t= 0\n\t\tself._404\t\t\t\t= 0\n\n\n\n\n\tdef get_new_id(self):\n\t\tself._download_id = self._download_id+1\n\t\treturn self._download_id\n\n" }, { "alpha_fraction": 0.5749765038490295, "alphanum_fraction": 0.5794920325279236, "avg_line_length": 37.244606018066406, "blob_id": "5116ff157e616f55cbba9168a5da62a949c745e0", "content_id": "c6d16f5fd8a6fcc548917ad590e9785a1c69d49c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5315, "license_type": "no_license", "max_line_length": 149, "num_lines": 139, "path": "/crawling/core/parser.py", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "'''\nCreated on Feb 6, 2013\n\n@author: Adam57\n'''\nfrom models.html import Html \nfrom include.thread_pool import ThreadPool\nfrom include.log import Log\nfrom include.setting import Setting\nfrom strategies.linksextractor import LinksExtractor\nfrom models.safe_queue import SafeQueue\nimport urllib, formatter\nfrom models.status import Status\nfrom models.configuration import Configuration\nfrom strategies.cgihandler import CGIHandler\nfrom strategies.nestlevelhandler import NestLevelHandler\nfrom strategies.schemehandler import SchemeHandler\nfrom strategies.filetypehandler import FileTypeHandler\nfrom strategies.bookmarkhandler import BookMarkHandler\nfrom strategies.urlextender import URLExtender\nfrom strategies.omitindex import OmitIndex\n\n\nclass Parser(object):\n \n def __init__(self, num_thread, status):\n self._num_threads = num_thread\n self._parse_workers = ThreadPool(num_thread)\n self._parsing_depth = 0\n self._parsing_id = 0\n self._status = status\n self._cgihandler = CGIHandler()\n self._nestlevelhandler = NestLevelHandler()\n self._schemehandler = SchemeHandler()\n self._filetypehandler = FileTypeHandler()\n self._bookmarkhandler = BookMarkHandler()\n self._urlextender = URLExtender()\n self._filetypehandler = FileTypeHandler()\n self._omitindex = OmitIndex()\n self._config = Configuration()\n \n def queue_parse_task(self, html_task, callback):\n \"\"\"assign the tasks(function, parameter, and callback) to the workers(thread pool)\"\"\"\n self._parse_workers.queue_task(self.parse_page, html_task, callback)\n\n def start(self):\n self._parse_workers.start()\n\n def stop(self):\n self._parse_workers.stop()\n\n def len(self):\n return self._parse_workers.get_queue_count()\n \n def parse_page(self, html_task, callback):\n \n links = []\n format = formatter.NullFormatter()\n htmlparser = LinksExtractor(format)\n self._parsing_depth = html_task._depth\n self._parsing_id = html_task._id\n try: \n htmlparser.feed(html_task._data)\n htmlparser.close()\n links = htmlparser.get_links()\n except (Exception) as e:\n #print(html_task._data)\n #print(html_task._url)\n #Log().debug(e)\n return\n #finally:\n # del html_task\n\n\n for link in links:\n #print (link)\n \n html_task_child = Html(link)\n \n self._status._parse_times+=1\n\n \"\"\"load all strategies to determine if this link can be download\"\"\"\n if(self._schemehandler.SchemeChecker(html_task_child)==False):\n #print(\"Ingore the wrong scheme, this link is within page {0} , so don't download\".format(html_task._parent), html_task._url)\n self._status._scheme_type+=1\n continue \n if(self._bookmarkhandler.BookMarkChecker(html_task_child)==True):\n #print(\"Ingore bookmark link, this link is within page {0} , so don't download\".format(html_task._parent), html_task._url)\n self._status._bookmark+=1\n continue\n if(self._cgihandler.FindCGI(html_task_child)==True):\n #print(\"Ingore the link contain cgi, this link is within page {0} , so don't download\".format(html_task._parent), html_task._url)\n self._status._cgi+=1\n continue \n if(self._nestlevelhandler.checknestlevel(html_task_child,self._config._parser_nlv)==True):\n #print(\"Ingore the link nested too much, this link is within page {0} , so don't download\".format(html_task._parent), html_task._url)\n self._status._nestlv +=1\n continue \n if(self._filetypehandler.FileTypeChecker(html_task_child)==False):\n self._status._file_type +=1\n continue\n \n self._omitindex.Omit(html_task)\n \n if(html_task_child._scheme == \"\" and html_task_child._hostname==None):\n self._urlextender.ExtendURL(html_task_child, html_task)\n \n #if self.parse_link( html_task_child ) == True:\n \n html_task_child._depth = self._parsing_depth+1\n html_task_child._parent = self._parsing_id\n\n #for test\n html_task_child._parent_url = html_task._url\n callback(html_task_child)\n\n del html_task\n ''' \n def parse_link(self, html_task ):\n self._status._parse_times+=1\n \n '\n #simple filter of no _scheme & _hostname for test\n \n if (html_task._scheme ==\"\") | (html_task._hostname == \"\"):\n #print(\"no _scheme & _hostname \")\n self._status._abandon+=1\n return False\n \n \n #simple filter of type of scheme for test\n \n if html_task._scheme !=\"http\":\n #print(\" html_task._scheme={0}\".format(html_task._scheme))\n self._status._abandon+=1\n return False\n \n return True\n '''" }, { "alpha_fraction": 0.5942491888999939, "alphanum_fraction": 0.6230031847953796, "avg_line_length": 35.82352828979492, "blob_id": "374ac239ced5e7848251ac6db7ab02dbb40916b8", "content_id": "3f6f075f9859f5ebf5d1a35a9627cd00c45c2093", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 626, "license_type": "no_license", "max_line_length": 167, "num_lines": 17, "path": "/search/interface/template/index.php", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "<div class=\"container\">\n\t<div class= \"my_main\">\n\t\t<span class=\"ctr-p\">\n\t\t\t<center>\n\t\t\t\t<div id=\"lga\" style=\"height:231px;margin-top:-22px\">\n\t\t\t\t\t<img alt=\"Web Search Engin CS6913\" height=\"95\" src=\"<?=IMG?>google_logo.png\" width=\"275\" id=\"hplogo\" onload=\"window.lol&amp;&amp;lol()\" style=\"padding-top:112px\">\n\t\t\t\t</div>\n\t\t\t\t<form class=\"form-search\" action=\"query.php\" method=\"get\">\n\t\t\t\t <input name=\"key\" type=\"text\" class=\"input-xlarge\" data-provide=\"typeahead\" data-items=\"4\" data-source='[\"Alabama\",\"Alaska\"]'>\n\t\t\t\t <button type=\"submit\" class=\"btn\">Search</button>\n\t\t\t\t </form>\n\t\t\t</center>\n\t\t\t</span>\n\t</div>\n\t\n\n</div>\n" }, { "alpha_fraction": 0.5838544368743896, "alphanum_fraction": 0.601478099822998, "avg_line_length": 24.128570556640625, "blob_id": "2741d57b443841d0ff64088eaed6933da2007b85", "content_id": "6f9e2bf1dc5a1ee75c44566830c26a331104a3c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1759, "license_type": "no_license", "max_line_length": 93, "num_lines": 70, "path": "/newyorktimes/src/searching/searching.cpp", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "#include<iostream>\n\n#include \"searching_algorim.h\"\n#include <vector>\n#include <string>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <errno.h>\n#include <string.h>\n#include <sys/types.h>\n#include <time.h> \nusing namespace std;\n\n\nint main(int argc,char** argv)\n{\n\n\t\n\t//cout<<query.size()<<endl;\n\t//start a http server \n\tint listenfd = 0, connfd = 0;\n struct sockaddr_in serv_addr; \n\n char sendBuff[1025];\n char recvBuff[1025];\n time_t ticks; \n\n listenfd = socket(AF_INET, SOCK_STREAM, 0);\n memset(&serv_addr, '0', sizeof(serv_addr));\n memset(sendBuff, '0', sizeof(sendBuff)); \n\n serv_addr.sin_family = AF_INET;\n serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);\n serv_addr.sin_port = htons(9997); \n\n bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); \n\n listen(listenfd, 10); \n cout<<\"start searching service...listen to 9998\"<<endl;\n SearchingAlgorim demo;\n\n //demo.do_searching(\"investigation\");\n // cout<<\"result:\"<<demo.get_result()<<endl;\n \n while(1)\n {\n connfd = accept(listenfd, (struct sockaddr*)NULL, NULL); \n int numbytes = 0;\n \tif((numbytes = recv(connfd,recvBuff,sizeof(recvBuff),0))!=-1)\n \t{\n \t\tcout<<\"query request:\"<<recvBuff<<endl;\n\t //snprintf(sendBuff, sizeof(sendBuff), \"%.24s\\r\\n\", ctime(&ticks));\n demo.do_searching(recvBuff);\n string send_data = demo.get_result();\n \n\t write(connfd, send_data.c_str(), send_data.length()); \n // cout<<\"send reasult: len:\"<<send_data.length()<<endl<<\"data:\"<<send_data<<endl;\n \t}\n \n\n close(connfd);\n sleep(1);\n }\n\t\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.5541795492172241, "alphanum_fraction": 0.5644994974136353, "avg_line_length": 16.636363983154297, "blob_id": "344bc020538a6a25ef880453b986e2122bae1786", "content_id": "420755de809e8ca2cbab1792d36802dd92c3231e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 969, "license_type": "no_license", "max_line_length": 60, "num_lines": 55, "path": "/newyorktimes/interface/query.php", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "<?php\n\nrequire_once( './loader.php' );\n\n\n\n$key_words = $_GET[\"key\"];\n$type = $_GET[\"type\"];\n$location = $_GET[\"location\"];\nif( !isset($type))\n\t$type = \"relevance\";\nif( !isset($location) || $location==\"\")\n\t$location = \"NULL\";\n\n$output = query( $key_words, $type,$location);\n//var_dump($output);\n//exit(0);\n\n$result = format_result($output);\nload_template(\"index\");\n\n\nfunction query( $key_words, $type,$location )\n{\n\t\n\n\t$cmd = \"demo/helper \".$type.\" \".$location.\" $ \".$key_words;\n\texec($cmd ,$output);\n\treturn $output;\n}\n\nfunction format_result( $output )\n{\n\t//var_dump($output);\n\t$len =count($output);\n\t$result = array();\n\t$j=0;\n\tfor( $i = 1; $i < $len; $i+=5)\n\t{\n\t\t$one_result = array();\n\t\t$one_result['url'] = $output[$i];\n\t\t$one_result['bm25'] = $output[$i+1];\n\t\t$one_result['time'] = $output[$i+2];\n\t\t$one_result['title'] = $output[$i+3];\n\t\t$one_result['location'] = $output[$i+4];\n\t\t\n\t\t\n\t\t$result[$j++] =$one_result;\n\t}\n\t//var_dump($result);\n\n\treturn $result;\n}\n\n?>" }, { "alpha_fraction": 0.4622288644313812, "alphanum_fraction": 0.46896034479141235, "avg_line_length": 22.05172348022461, "blob_id": "a789f02d5cb80bfda903b5eb73fe7faa788c6b18", "content_id": "8d238927dd3b87006d69913d3428b1304e1e7d0e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1337, "license_type": "no_license", "max_line_length": 47, "num_lines": 58, "path": "/crawling/models/safe_dic.py", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "'''\nCreated on Feb 12, 2013\n\n@author: Adam57\n'''\n\nfrom threading import Condition\nfrom threading import Lock\n\nclass SafeDictionary( object ): \n def __init__(self):\n self._data_dic = {}\n self._lock = Condition(Lock())\n\n\n def addorupdate(self, key, data):\n self._lock.acquire()\n try:\n self._data_dic[key] = data\n finally:\n self._lock.release()\n \n\n def pop_left(self):\n self._lock.acquire()\n try:\n if ( len(self._data_dic) == 0 ):\n return None\n return self._data_dic.popleft()\n finally:\n self._lock.release()\n \n def clear(self):\n self._lock.acquire()\n try:\n self._data_dic.clear()\n finally:\n self._lock.release()\n \n def has_key(self, key):\n self._lock.acquire()\n try:\n if self._data_dic.has_key(key):\n return True\n else:\n return False\n finally:\n self._lock.release()\n \n def valueofkey(self,key):\n self._lock.acquire()\n try:\n if not self._data_dic.has_key(key):\n return None\n else:\n return self._data_dic[key]\n finally:\n self._lock.release()\n" }, { "alpha_fraction": 0.6604735851287842, "alphanum_fraction": 0.674316942691803, "avg_line_length": 25.384614944458008, "blob_id": "b6ae2b0a4712875ffa9a757eb61303d186a809db", "content_id": "6337027229c720e0a836d842a74427284a05d9b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2745, "license_type": "no_license", "max_line_length": 91, "num_lines": 104, "path": "/crawling/core/downloader.py", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "\"\"\"\nCreated on Feb 2, 2013\n\n@author: derrick\n\nThis is a downloader\n\"\"\"\n\nimport time\nfrom models.html import Html \nfrom include.thread_pool import ThreadPool\nfrom include.log import Log\nfrom models.status import Status\nimport urllib2\nimport socket\n\n #python2.7\n#import urllib.request #python3.3\n#import urllib.parse #python3.3\n\n\nclass Downloader(object):\n\t\n\tdef __init__(self, num_thread, status):\n\t\tself._num_threads\t \t= num_thread\n\t\tself._status\t\t\t= status\n\t\tself._download_workers\t= ThreadPool(num_thread)\n\t\n\n\tdef queue_download_task(self, html_task, callback):\t\t\n\t\t\"\"\"assign the tasks(function, parameter, and callback) to the workers(thread pool)\"\"\"\n\t\tself._download_workers.queue_task(self.download_page , html_task , callback )\n\n\n\tdef start(self):\n\t\tself._download_workers.start()\n\n\tdef stop(self):\n\t\tself._download_workers.stop()\n\n\tdef len(self):\n\t\treturn self._download_workers.get_queue_count()\n\n\tdef download_page(self, html_task, callback):\n\t\t#req = urllib.request.Request(html_task._url) #python3.3\n\t\t#data = urllib.request.urlopen(req) #python3.3\n\t\t#html_task._data = data.read()#.decode('utf-8') #python3.3\n\t\ttry:\n\t\t\ttimeout = 2\n\t\t\tsocket.setdefaulttimeout(timeout)\n\t\t\t\"\"\"download files\"\"\"\n\n\t\t\t#decode url\n\t\t\turl = urllib2.unquote(html_task._url)\n\t\t\treq = urllib2.Request(url)\n\n\t\t\t#set refer and user-agent\n\t\t\treq.add_header('Referer', 'http://www.poly.edu/')\n\t\t\treq.add_header('User-agent', 'Mozilla/5.0')\n\n\t\t\t#print \"download url :\"+url\n\t\t\t\n\t\t\tnetowrk_object \t\t\t= urllib2.urlopen(req,None,timeout)\n\t\t\thtml_task._data \t\t= netowrk_object.read()\n\t\t\tnetowrk_object.close()\n\t\t\t#print \"finish download\"+html_task._url\n\t\t\t\"\"\"pull html data,fill the info into html model\"\"\"\n\t\t\thtml_task._id \t\t\t= self._status.get_new_id()\n\t\t\thtml_task._crawled_time = time.time() \n\t\t\thtml_task._return_code\t= netowrk_object.getcode()\n\t\t\thtml_task._data_size\t= len(html_task._data)\n\n\n\t\t\t\"\"\"fill information to status model\"\"\"\n\t\t\tself._status._recent_url.add(html_task)\n\t\t\tself._status._download_times+=1\n\t\t\tself._status._download_size+=html_task._data_size\n\n\t\t\tcallback(html_task)\n\t\t#except urllib2.URLError as e:\n\t\t\t#print \"Url error:\"\n\t\t\t#Log().debug(e)\n\t\t\t#print \"url error: url=\"+url+\", code={0}\".format(e.code)+\" ,resaon=\"+e.reason\n\t\t\t#print e\n\t\t\t#print url\n\t\t\t#print html_task._parent_url\n\t\t\t#return\n\t\texcept urllib2.HTTPError as e:\n\t\t\tif e.code == 404:\n\t\t\t\tself._status._404+=1\t\n\t\t\t#print \"url error: url=\"+html_task._url+\", code={0}\".format(e.code)+\" ,resaon=\"+e.reason\n\t\t\treturn\n\t\texcept socket.error: \n\t\t\t#print('socket time out')\n\t\t\tself._status._socket_timeout+=1\n\t\t\t#print \"time out: \"+html_task._url\n\t\t\treturn\n\t\texcept (Exception) as e:\n\t\t\t#Log().debug(\"download_page failed\")\n\t\t\t#print e\n\t\t\treturn\n\t\t\n\t\t#finally:\t\n\t\t\t#callback(html_task)\n\n" }, { "alpha_fraction": 0.4849188029766083, "alphanum_fraction": 0.49961331486701965, "avg_line_length": 30.439023971557617, "blob_id": "c5e5ac4fdf758110b99ca2b22a0aadce2acbd650", "content_id": "6ce176024f3c3b951e2b50a0e92625ad2b2bed3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1293, "license_type": "no_license", "max_line_length": 86, "num_lines": 41, "path": "/crawling/core/searchgoogle.py", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "'''\nCreated on Feb 10, 2013\n\n@author: Adam57\n'''\n\nimport urllib2,urllib\nimport json\nfrom include.log import Log\n\nclass SearchGoogle(object):\n def __init__(self, searchstr = 'NYU', resultnum = 10):\n self._keywords = searchstr\n self._links = []\n self._result_num = resultnum\n def getURLs(self):\n for x in range(self._result_num): \n #start = x*1 \n url = ('https://ajax.googleapis.com/ajax/services/search/web'\n '?v=1.0&q=%s&rsz=1&start=%s') % (urllib.quote(self._keywords),x)\n try:\n request = urllib2.Request(url, None, {'Referer':'http://www.nyu.edu'})\n response = urllib2.urlopen(request)\n\n \"\"\"Process the JSON string.\"\"\"\n results = json.load(response)\n info = results['responseData']['results']\n except Exception,e:\n Log().debug(e)\n else:\n for minfo in info:\n self._links.append(minfo['url'])\n # print(minfo['url'])\n finally:\n response.close()\n\n return self._links \n \nif __name__ == \"__main__\": \n contacter = SearchGoogle(\"Torsten Suel\",15) \n print(contacter.getURLs())\n " }, { "alpha_fraction": 0.5887371897697449, "alphanum_fraction": 0.6040955781936646, "avg_line_length": 11.739130020141602, "blob_id": "ad9feb698f8660fa7b3b2ca9f31ccdf8513eb72b", "content_id": "f94e2396e3d7eb1703204854df64a6691f9a9ec7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 586, "license_type": "no_license", "max_line_length": 33, "num_lines": 46, "path": "/newyorktimes/src/searching/result_ctrl.h", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "#ifndef __RESULT_CTRL_H_\n#define __RESULT_CTRL_H_\n\n#include <string>\n#include <iostream>\nusing namespace std;\nstruct STRU_RESULT\n{\n\tstd::string _url;\n\tstd::string _title;\n\tstd::string _location;\n\tint _time;\n\tfloat _bm25;\n\tint _doc_id;\n\tint _pos;\n\n\tSTRU_RESULT()\n\t{\n\t\t_url = \"\";\n\t\t_title = \"\";\n\t\t_location=\"\";\n\t\t_time=0;\n\t\t_bm25=0.0;\n\t\t_doc_id=0;\n\t\t_pos=0;\n\t}\n};\n\nclass ResultCrtl\n{\npublic:\n\tResultCrtl();\n\t~ResultCrtl();\npublic:\n\tvoid clear();\n\tvoid add_one(STRU_RESULT& res); \n\tvoid print();\nprivate:\n\tSTRU_RESULT* \t_result;\n\tint \t\t\t_max;\n\tint \t\t\t_now;\n\n};\n\n\n#endif //__RESULT_CTRL_H_\n" }, { "alpha_fraction": 0.5907065272331238, "alphanum_fraction": 0.5970719456672668, "avg_line_length": 21.44285774230957, "blob_id": "72a549ad13005cbb50a79fbf792f29fa4a0df89f", "content_id": "5ac85cff842e4a720e669de7764e280df365ad23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1571, "license_type": "no_license", "max_line_length": 92, "num_lines": 70, "path": "/indexing/src/include/models/URLTable.cpp", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "/*\n * URLTable.cpp\n *\n * Created on: Feb 25, 2013\n * Author: Adam57\n */\n\n#include \"URLTable.h\"\n\nURLTable::URLTable() {\n\t// TODO Auto-generated constructor stub\n\n}\n\nURLTable::~URLTable() {\n\t// TODO Auto-generated destructor stub\n}\n\nvoid URLTable::serialize( StreamBuffer &stream ) {\n\tfor ( std::map<int, string>::iterator it = map.begin(); it!=map.end(); ++it){\n\n\t\t\tstream.write(&it->first);\n\t\t\tint tmp = it->second.length();\n\t\t\tstream.write(&tmp);\n\t\t\tstream.write(it->second.c_str(), it->second.length());\n\t}\n\n}\n\nvoid URLTable::deserialize( StreamBuffer &stream ){\n\tmap.clear();\n\n\t \t\twhile(stream.active()){\n\t\t\t\tint key;\n\t stream.read(&key);\n\t int length;\n\t stream.read(&length);\n\t char buffer[length+1];\n\t buffer[length]='\\0';\n\t stream.read(buffer,length);\n\t string buf(buffer);\n\t map.insert(pair<int,string>(key,buf));\n\t \t\t}\n}\n\nvoid URLTable::addentry(int doc_id, string url){\n\n\tmap.insert(pair<int, string>(doc_id,url));\n}\n\nStreamBuffer& operator<<(StreamBuffer &stream, URLTable &table){\n\ttable.deserialize(stream);\n\treturn stream;\n}\n\nStreamBuffer& operator>>(StreamBuffer &stream, URLTable &table) {\n table.serialize(stream);\n return stream;\n}\n\n\n\nstd::ostream& operator<<(std::ostream &stream, URLTable &table) {\n stream << \"map {\" << std::endl;\n for( std::map<int, string>::iterator it = table.map.begin(); it!=table.map.end(); ++it){\n stream << it->first << \": \" << it->second<< std::endl;\n }\n stream << \"}\" << std::endl;\n return stream;\n}\n" }, { "alpha_fraction": 0.7332857847213745, "alphanum_fraction": 0.7357817888259888, "avg_line_length": 45.75, "blob_id": "b16b14c49f9633acb8408914355a0071f4126220", "content_id": "3e5838f013fd2955d45ed7ec4d8f6611e3926303", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5609, "license_type": "no_license", "max_line_length": 185, "num_lines": 120, "path": "/README.md", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "# Simple Crawler\nThe first project for Web Search Engine\n<img src=\"https://raw.github.com/derrick0714/web_search_engin/master/crawling/docs/crawler_architecture.png\" />\n\nFilelist:\n\t\n\treadme.txt\n\texplain.txt\n\tconfig.ini\t\t\t\t\t\t\t\tprogram parameters' configuraton\n\tcrawler.py\t\t\t\t\t\t\t\tmain program\n\t\t\n\tcore.engine.py\t\t\t\t\t\t\tload config file and manage the parser queue and download queue\n\tcore.downloader.py\t\t\t\t\t\tdownloader implementation assgins download tasks to thread pool\n\tcore.parser.py\t\t\t\t\t\t\tparser implementation assgins parse tasks to thread pool\n\tcore.searchgoogle.py\t\t\t\t\tGoogle search API implementation\n\t\n\tmodels.configuration.py\t\t\t\t\tload all configurations from local file and remote mysql\n\tmodels.html.py\t\t\t\t\t\t\tthe data structure maintain the crawled page infomation\n\tmodels.safe_dic.py\t\t\t\t\t\timplementation of dictionary with lock\n\tmodels.safe_queue.py\t\t\t\t\timplementation of queue with lock\n\tmodels.safe_loop_array.py\t\t\t\timplementation of array with lock\n\tmodels.status.py\t\t\t\t\t\tsystem global variables\n\t\n\tinclude.database_manager.py\t\t\t\tinteract with remote mysql\n\tinclude.database.py\t\t\t\t\t\tsql executer\n\tinclude.log.py\t\t\t\t\t\t\timplementation of logger\n\tinclude.setting.py\t\t\t\t\t\tread program parameters from local configuration file\n\tinclude.thread_pool.py\t\t\t\t\timplementation of a thread pool\t\t\n\t\n\tstrategies.bookmarkhandler.py\t\t\thandle page anchor\n\tstrategies.cgihandler.py\t\t\t\tblock url address with cgi in it\n\tstrategies.earlyvisithandler.py\t\t\tblock pages visited before\n\tstrategies.filetypehandler.py\t\t\tdecide whether a page is crawable according to its MIME type\n\tstrategies.linksextractor.py\t\t\textract links from a downloaded page\n\tstrategies.nestlevelhandler.py\t\t\tblock pages exceed a cetain depth in a site\n\tstrategies.omitindex.py\t\t\t\t\tomit the part of 'index.htm','main.htm',etc with in a url\n\tstrategies.robotexclusionrulesparser.py\ta robot exclusion rules parser \n\tstrategies.robothandler.py\t\t\t\tdecide whether a page is crawable according to the robot.txt\n\tstrategies.schemehandler.py\t\t\t\tscheme whitelist\n\tstrategies.urlextender.py\t\t\t\textend partial url\n\t\n\twww.\n\t\nProgram parameters:\n\t\nThe config.ini file contains runtime parameters:\n\tDownloader.Threadnum\t\t\t\t\tThe number of thread for download\n\tDownloader.SavePath\t\t\t\t\t\tThe directory stores the downloaded pages\n\t\n\tParser.Threadnum\t\t\t\t\t\tThe number of thread for parse\n\tParser.Nestlevel\t\t\t\t\t\tThe maximum depth of a page in a website\n\t\n\tseed.keywords\t\t\t\t\t\t\tThe search key words\n\tseed.result_num\t\t\t\t\t\t\tThe result num returned from the Google API\n\t\n\tMysql.host\t\t\t\t\t\t\t\tmysql hostname\n\tMysql.user\t\t\t\t\t\t\t\tmysql username\n\tMysql.passwd\t\t\t\t\t\t\tmysql passwprd\n\tMysql.db\t\t\t\t\t\t\t\tmysql database name\n\t\nDesgin:\n\t\n\t# Engine \n\t----------------------\n\t\tEngine is the main controller in the crawler.\n\t\t\n\t\t\tIt has:\n\t\t\t-a downloader object and a parser object, \n\t\t\t-two safe queues each for the download and parse tasks, \n\t\t\t-a status object holding the global status variables for the crawler, \n\t\t\t-a mysql manager, \n\t\t\t-objects for every filter strategy,the safe dictionary within the object of earlyvisithandler actually maintains the tree structure of the visited url\n\t\t\t\n\t\t\n\t\tOnce the Engine starts up:\t\t\n\t\t\t-it first apply the filter rules to the seeds from the Google API, and then load the valid ones into the download queue;\n\t\t\t-it starts two threads each keep checking the download queue and parse queue, once a html task is found in the queues, it is then assigned to the downloader or the parser; \n\t\t\t-The downloader will return html tasks to be parse and push them into the parse queue, and the parser will return the html tasks to be download and push them into the download queue;\n\t\t\t-it starts a thread keep checking the status of the crawler and post runtime info to remote mysql;\n\t\t\n\t\n\t# Parser\n\t----------------------\n\t\tParser will assgin the parsing tasks passed from engine to the thread pool object it maintains\n\t\t\t\n\t\tExcept applying filtering rules when loading seeds from Google API to download queue in the engine, we mainly apply all the filtering rules in parser:\n\t\t\t-robothandler \t\t\t\tcheck against robot exclusion rules through robot.txt, it maintains a dictionary,\n\t\t\t\t\t\t\t\t\t\tof which the key is the url's homesite, the value is a object of robotexclutionrulesparser.\n\t\t\t-earlyvisithandler\t\t\tcheck against the url visited before, it maintains a dictionary,\n\t\t\t\t\t\t\t\t\t\tof which the key is the md5 hashcode of the url, the value is the url's corresponding html object.\n\t\t\t-cgihandler\t\t\t\t\tblock the url with cgi in it\n\t\t\t-bookmarkhandler\t\t\tblock the link of page anchor\n\t\t\t-filetypehandler\t\t\tblock the url according to the MIME type\n\t\t\t-nestlevelhandler\t\t\tblock url exceed a cetain depth in a site\n\t\t\t-omitindex\t\t\t\t\tomit the part of 'index.htm','main.htm',etc with in a url\n\t\t\t-schemehandler\t\t\t\tblock the scheme outside the scheme whitelist\n\t\t\t-urlextender\t\t\t\treturn the complete url\n\t\n\t# Downloader\n\t----------------------\n\t\tDownloader will assgin the download tasks passed from engine to the thread pool object it maintains;\n\t\t\n\t\tThe timeout is set as 2 secs, then it returns a exception;\n\t\t\n\t\tIt saves download files to local directory\n\t\n\t# Html\n\t----------------------\n\t\tIt stores the information of a certain url and its corresponding page data:\n\t\t\t_url \t\t\t\t\t\tinitial url and the extended url\n\t\t\t_scheme\t\t\t\t\t\tscheme of the url\n\t\t\t_hostname\t\t\t\t\thostname of the url\n\t\t\t_md5\t\t\t\t\t\tmd5 hash code of the url\n\t\t\t_id\t\t\t\t\t\t\tdownload sequence\n\t\t\t_depth\t\t\t\t\t\tdistance to the initial seed\n\t\t\t_parent\t\t\t\t\t\tparent Html object\n\t\t\t_return_code\t\t\t\t200, 404, etc\n\t\t\t_data\t\t\t\t\t\ttext within the page\n\t\t\t_data_size\t\t\t\t\tsize of data\n\t\t\t_crawled_time\t\t\t\tdownload time" }, { "alpha_fraction": 0.644318163394928, "alphanum_fraction": 0.6556817889213562, "avg_line_length": 16.600000381469727, "blob_id": "eb3736e2bf510552d8a3b9126e34ea6896ac3891", "content_id": "c425c85867955df8fad03864a87a60c9c1cb2096", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 880, "license_type": "no_license", "max_line_length": 83, "num_lines": 50, "path": "/newyorktimes/src/include/models/TempLexicon.h", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "/*\n * LexiconDic.h\n *\n * Created on: Feb 25, 2013\n * Author: Adam57\n */\n\n#ifndef LEXICONDIC_H_\n#define LEXICONDIC_H_\n#include <map>\nusing namespace std;\n#include \"StreamBuffer.h\"\n\nclass TempLexicon \n{\npublic:\n\tint\t\tword_id;\n\tint\t\tdoc_id;\n\tint\t\tstartpos;\n\n\tTempLexicon(){word_id = 0; doc_id= 0;}\n\n\tvoid serialize(StreamBuffer &stream )\n\t{\n\t\tstream.write(&word_id);\n\t\tstream.write(&doc_id);\n\t\tstream.write(&startpos);\n\t\t//cout<<\"word_id \" <<word_id << \" doc_id:\"<<doc_id<<\" startpos:\"<<startpos<<endl;\n\n\t}\n\tvoid deserialize( StreamBuffer &stream )\n\t{\n\t\tstream.read(&word_id);\n\t\tstream.read(&doc_id);\n\t\tstream.read(&startpos);\n\n\t}\n\t\n\tfriend StreamBuffer& operator<<(StreamBuffer &stream, TempLexicon& obj)\n\t{\n\t\tobj.deserialize(stream);\n\t}\n\tfriend StreamBuffer& operator>>(StreamBuffer &stream, TempLexicon& obj)\n\t{\n\t\t obj.serialize(stream);\n\t}\n};\n\n\n#endif /* LEXICONDIC_H_ */\n" }, { "alpha_fraction": 0.7619515657424927, "alphanum_fraction": 0.765880823135376, "avg_line_length": 41.41666793823242, "blob_id": "98c17860113675e438e23242bc9ebc1fa9adca74", "content_id": "814b59edeb140ffa8cf10751d6150a1107a6219a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 3054, "license_type": "no_license", "max_line_length": 118, "num_lines": 72, "path": "/crawling/readme.txt", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "CS 6913 Spring 2013\nWeb Search Engine\nHomeWork 1\n\nXu Deng, Qi Wang\n\n[How to run the program:]\n\n1.cd to the root folder of source code \n2.excute python crawler.py\n3.Go to the http://dengxu.me/crawling/ input the keywords and threads numbers, click search\n\n\n[Filelist:]\n\t\n\treadme.txt\n\texplain.txt\n\tconfig.ini\t\t\t\t\t\tprogram parameters' configuraton\n\tcrawler.py\t\t\t\t\t\tmain program\n\t\t\n\tcore.engine.py\t\t\t\t\t\tload config file and manage the parser queue and download queue\n\tcore.downloader.py\t\t\t\t\tdownloader implementation assgins download tasks to thread pool\n\tcore.parser.py\t\t\t\t\t\tparser implementation assgins parse tasks to thread pool\n\tcore.searchgoogle.py\t\t\t\t\tGoogle search API implementation\n\t\n\tmodels.configuration.py\t\t\t\t\tload all configurations from local file and remote mysql\n\tmodels.html.py\t\t\t\t\t\tthe data structure maintain the crawled page infomation\n\tmodels.safe_dic.py\t\t\t\t\timplementation of dictionary with lock\n\tmodels.safe_queue.py\t\t\t\t\timplementation of queue with lock\n\tmodels.safe_loop_array.py\t\t\t\timplementation of array with lock\n\tmodels.status.py\t\t\t\t\tsystem global variables\n\t\n\tinclude.database_manager.py\t\t\t\tinteract with remote mysql\n\tinclude.database.py\t\t\t\t\tsql executer\n\tinclude.log.py\t\t\t\t\t\timplementation of logger\n\tinclude.setting.py\t\t\t\t\tread program parameters from local configuration file\n\tinclude.thread_pool.py\t\t\t\t\timplementation of a thread pool\t\t\n\t\n\tstrategies.bookmarkhandler.py\t\t\t\thandle page anchor\n\tstrategies.cgihandler.py\t\t\t\tblock url address with cgi in it\n\tstrategies.earlyvisithandler.py\t\t\t\tblock pages visited before\n\tstrategies.filetypehandler.py\t\t\t\tdecide whether a page is crawable according to its MIME type\n\tstrategies.linksextractor.py\t\t\t\textract links from a downloaded page\n\tstrategies.nestlevelhandler.py\t\t\t\tblock pages exceed a cetain depth in a site\n\tstrategies.omitindex.py\t\t\t\t\tomit the part of 'index.htm','main.htm',etc with in a url\n\tstrategies.robotexclusionrulesparser.py\t\t\ta robot exclusion rules parser \n\tstrategies.robothandler.py\t\t\t\tdecide whether a page is crawable according to the robot.txt\n\tstrategies.schemehandler.py\t\t\t\tscheme whitelist\n\tstrategies.urlextender.py\t\t\t\textend partial url\n\t\n\twww/index.html\t\t\t\t\t\tinput the keywords and download & parser threads\n\twww/commit.php\t\t\t\t\t\twrite configuration info into mysql and set the start flag to true,then redirect to realtime page\n\twww/realtime.html\t\t\t\t\tdisplay realtime info of crawler\n\twww/realtime_data.php\t\t\t\t\trealtime ajax data which fetch from mysql\n\twww/about.html\t\t\t\t\t\tauthor info\n\t\n[Program parameters:]\n\t\nThe config.ini file contains runtime parameters:\n\tDownloader.Threadnum\t\t\t\t\tThe number of thread for download\n\tDownloader.SavePath\t\t\t\t\tThe directory stores the downloaded pages\n\t\n\tParser.Threadnum\t\t\t\t\tThe number of thread for parse\n\tParser.Nestlevel\t\t\t\t\tThe maximum depth of a page in a website\n\t\n\tseed.keywords\t\t\t\t\t\tThe search key words\n\tseed.result_num\t\t\t\t\t\tThe result num returned from the Google API\n\t\n\tMysql.host\t\t\t\t\t\tmysql hostname\n\tMysql.user\t\t\t\t\t\tmysql username\n\tMysql.passwd\t\t\t\t\t\tmysql passwprd\n\tMysql.db\t\t\t\t\t\tmysql database name\n" }, { "alpha_fraction": 0.5086206793785095, "alphanum_fraction": 0.5258620977401733, "avg_line_length": 39.349998474121094, "blob_id": "6cd2495cc76902fc50cbc203054c4b80d4b91d43", "content_id": "f6aadbf0852dafb2cf0ff0f29b4a1f4d7eb48cd4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 812, "license_type": "no_license", "max_line_length": 213, "num_lines": 20, "path": "/search/interface/template/footer.php", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": " <!-- Footer\n ================================================== -->\n <footer class=\"footer\">\n <div class=\"container\">\n <p></p>\n <p>Developed by <a href = \"https://github.com/derrick0714\" target=\"blank\">@deng xu</a> and <a href = \"https://github.com/Adam57\" target=\"blank\">@wang qi</a> </p>\n <p>Code licensed under <a href=\"http://www.apache.org/licenses/LICENSE-2.0\" target=\"_blank\">Apache License v2.0</a>, documentation under <a href=\"http://creativecommons.org/licenses/by/3.0/\">CC BY 3.0</a>.</p>\n\n </div>\n</footer>\n\n\n <!-- Le javascript\n ================================================== -->\n <!-- Placed at the end of the document so the pages load faster -->\n \n <script src=\"<?=JS?>/bootstrap.js\"></script>\n <script src=\"<?=JS?>/jquery.js\"></script>\n </body>\n</html>\n\n" }, { "alpha_fraction": 0.6829268336296082, "alphanum_fraction": 0.6829268336296082, "avg_line_length": 14, "blob_id": "50ffaeca5c52d7aa02a246565314d5e33d521437", "content_id": "4766bfb80480c26e158d74a6bd01f0d960779c26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 164, "license_type": "no_license", "max_line_length": 38, "num_lines": 11, "path": "/search/interface/include/template.php", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "<?php\n\n\nfunction load_template( $page )\n{\n\trequire_once(TEMPLEATE.\"header.php\");\n\trequire_once(TEMPLEATE.$page.\".php\");\n\trequire_once(TEMPLEATE.\"footer.php\");\n}\n\n?>" }, { "alpha_fraction": 0.4654807150363922, "alphanum_fraction": 0.4769165515899658, "avg_line_length": 17.88800048828125, "blob_id": "a802bab720851f255999fa01d063bf8f3d329c52", "content_id": "1156565b48516ad2659036e562f064df84e3075e", "detected_licenses": [ "Apache-2.0", "CC-BY-3.0" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2361, "license_type": "permissive", "max_line_length": 83, "num_lines": 125, "path": "/crawling/www/configuration_data.php", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "<?php\n$host = \"localhost\"; \n$user = \"web_search\"; \n$pass = \"dengxu_wangqi\"; \n$db = \"web_search_engine\";\n\n$conn = mysql_connect($host, $user, $pass);\n\nif (!$conn)\n{\n echo \"Could not connect to server\\n\";\n exit();\n} \n\nmysql_select_db($db,$conn);\n\n$sql = \"SELECT * FROM `configuation`\";\n\n\n$result = mysql_query($sql);\nif (!$result) \n{\n echo 'Could not run query: ' . mysql_error();\n exit;\n}\n\n$row = mysql_fetch_array($result);\n\n$sql = \"SELECT * FROM `key_words`\";\n$result = mysql_query($sql);\n\n\n?>\n\n\n <div class=\"my_span\"></div>\n\t<div class=\"my_content\">\n\n \n\t<div class=\"my_content\">\n\t\t<table class=\"table table-bordered\">\n\t\t <thead>\n\t\t <tr>\n\t\t <th olspan=\"2\"><b>Seed:</b></th>\n\t\t </tr>\n\t\t </thead>\n\t\t <tbody>\n\n\t\t <tr>\n\t\t <td width=\"200\"><b> result count : </b></td>\n\t\t <td> <input type=\"text\" name=\"result_count\" value=\"10\"></td>\n\t\t \t</tr>\n\t\t</div>\n\t\t <div class=\"my_span\"></div>\n\t\t<table class=\"table table-bordered\">\n\t\t <thead>\n\t\t <tr>\n\t\t <th olspan=\"2\"><b>Downloader:</b></th>\n\t\t </tr>\n\t\t </thead>\n\t\t <tbody>\n\t\t <tr>\n\t\t <td width=\"200\"><b> thread num: </b></td>\n\t\t <td> <input type=\"text\" name=\"down_thread\" value=\"1\"></td>\n\n\t\t </tr>\n\t\t <tr>\n\t\t <td>download folder:</td>\n\t\t <td>./data</td>\n\n\t\t </tr>\n\t\t </tbody>\n\t\t</table>\t\n\t</div>\n\t<div class=\"my_span\"></div>\n\t<div class=\"my_content\">\n\t\t<table class=\"table table-bordered\">\n\t\t <thead>\n\t\t <tr>\n\t\t <th olspan=\"2\"><b>Parser:</b></th>\n\t\t </tr>\n\t\t </thead>\n\t\t <tbody>\n\t\t <tr>\n\t\t <td width=\"200\"><b> thread num: </b></td>\n\t\t <td> <input type=\"text\" name=\"parse_thread\" value=\"1\"></td>\n\t\t </tr>\n\t\t</table>\t\n\t</div>\n\t\n\t<div class=\"my_span\"></div>\n\t<div class=\"my_content\">\n\t\t<table class=\"table table-bordered\">\n\t\t <thead>\n\t\t <tr>\n\t\t <th olspan=\"2\"><b>Seed:</b></th>\n\t\t </tr>\n\t\t </thead>\n\t\t <tbody>\n\t\t <tr>\n\t\t <td width=\"200\"><b> key words : </b></td>\n\t\t <td> <?=$row['seed_keywords']?></td>\n\t\t </tr>\n\t\t <tr>\n\t\t <td width=\"200\"><b> result count : </b></td>\n\t\t <td> <?=$row['seed_resultnum']?></td>\n\t\t </tr>\n\t\t <?php \n\t\t \t\t$i=1;\n\t\t \t\twhile ($array = mysql_fetch_array($result))\n\t\t\t\t\t{\n\t\t\t\t\t\techo \"<tr><td width='200'>\".$i++.\"</td> <td>\".$array['url'].\"</td></tr>\";\t\t\t\n\t\t\t\t\t}\n\t\t ?>\t\n\t</div>\n\n </div>\n\n\n\n<?php\n\nmysql_close();\n\n?>\n" }, { "alpha_fraction": 0.6502242088317871, "alphanum_fraction": 0.6547085046768188, "avg_line_length": 14.964285850524902, "blob_id": "85f6d31d59fa79e6993ab5d8bea0f295e8b6cacf", "content_id": "d0eae0882f8ae6294b08aa10c9dc1b9e4b5268df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 446, "license_type": "no_license", "max_line_length": 58, "num_lines": 28, "path": "/crawling/crawler.py", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "from core.engine import Engine\nfrom time import sleep\nfrom include.log import Log\nimport sys\n\n\ndef main():\n\n\ttry:\t\n\t\t#create crawler engin\n\t\tcrawler_engine = Engine()\n\n\n\t\t#start engine \n\t\tcrawler_engine.start( )\n\n\t\t#hold the main thread here, wait for any input to finish\n\t\traw_input(\"\")\n\t\t#stop engin \n\t\tcrawler_engine.stop()\n\n\texcept (Exception) as e: \n\t\t#Log().debug(e)\n\t\tsys.exit(0)\n\t\t\nif __name__ == \"__main__\":\n\t#main(sys.argv[1:])\n\tmain()" }, { "alpha_fraction": 0.5133438110351562, "alphanum_fraction": 0.5290423631668091, "avg_line_length": 29.380952835083008, "blob_id": "b55d52110cbd0c9d275982595dc31f9ef2a1ca20", "content_id": "427de9e9226ad266f453fc15629f200ba6ba758e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 637, "license_type": "no_license", "max_line_length": 113, "num_lines": 21, "path": "/crawling/strategies/schemehandler.py", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "'''\nCreated on Feb 14, 2013\n\n@author: Adam57\n'''\nclass SchemeHandler(object):\n def SchemeChecker(self, html_task):\n \n #print (html_task._url, html_task._scheme, html_task._hostname, html_task._path, html_task._query_string)\n '''block url links less or equal than 0'''\n #url = list(html_task._url)\n if len(html_task._url) <= 0: \n return False\n \n '''scheme white list'''\n if not html_task._scheme in ['http', 'https', \"\"]:\n \n return False \n #if (html_task._hostname == None and html_task._path == \"\"): \n \n return True" }, { "alpha_fraction": 0.6765957474708557, "alphanum_fraction": 0.6879432797431946, "avg_line_length": 15.809523582458496, "blob_id": "5231e42a82385b045e9ce8c24a8c09425e38312c", "content_id": "54c718e17e033589ee79b577cc6a9239ef41a075", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 705, "license_type": "no_license", "max_line_length": 90, "num_lines": 42, "path": "/newyorktimes/src/include/utility/system_ex.h", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "/*Author: derrick*/\n#ifndef D_SYSTEM_H\n#define D_SYSTEM_H\n\n#ifdef WIN32\n#include <atlbase.h>\nclass system_win\n{\npublic:\n\tvoid create_thread(void(*progarm)(void*), void* parameter)\n\t{\n\t\t::CreateThread(NULL , 0 ,(LPTHREAD_START_ROUTINE)progarm ,parameter ,0 , NULL);\n\t}\n\t \n};\n\n#else\n#include <pthread.h>\nclass system_linux\n{\n\tpublic:\n\tvoid create_thread(void(callback_func)(void*), void* param)\n\t{\n\t\tpthread_t thread;\n\t\tpthread_create(&thread, NULL , reinterpret_cast<void*(*)(void*)>(callback_func), param);\n\t\t//pthread_create(&thread, 0, &callback_func, 0);\n\t}\n\n};\n\n#endif\n\n\n\n#ifdef WIN32\ntypedef system_win\t\t_system;\n#else\ntypedef system_linux\t_system;\n#endif\n\nstatic _system _System;\n#endif //D_SYSTEM_H" }, { "alpha_fraction": 0.5286195278167725, "alphanum_fraction": 0.5622895359992981, "avg_line_length": 16.891565322875977, "blob_id": "f484d7e30b4773100e03b6661dd924628cfbc719", "content_id": "f67d4a8f8d010577c13fd9d79eff79edeba671e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1485, "license_type": "no_license", "max_line_length": 78, "num_lines": 83, "path": "/newyorktimes/src/include/utility/path_finder.cpp", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "#include \"path_finder.h\"\n#include <sys/types.h>\n#include <dirent.h>\n#include <errno.h>\n\nusing namespace std;\nstatic int DAYS[12]={31,28,31,30,31,30,31,31,30,31,30,31};\nPathFinder::PathFinder()\n{\n\tnow_year = 1987;\n\tend_year = 2007;\n\tnow_month = 1;\n\tnow_day = 1;\n\tload_folder();\n}\n\nPathFinder::~PathFinder()\n{\n\n}\n\nvoid PathFinder::load_folder()\n{\n\twhile( now_year <= end_year)\n\t{\t\n\t\tchar path_now[255];\n\t\tsprintf( path_now, \"./data/%d/%02d/%02d\",now_year,now_month, now_day);\n\t\t//cout<<\"folder:\"<<path_now<<endl;\n\t\tadd_files(path_now);\n\n\t\tnow_day++;\n\t\tif(now_day > DAYS[now_month-1])\n\t\t{\n\t\t\tnow_day = 1;\n\t\t\tnow_month++;\n\t\t}\n\t\tif(now_month > 12)\n\t\t{\n\t\t\tnow_month=1;\n\t\t\tnow_year++;\n\t\t}\n\t}\n\t\n}\n\nint PathFinder::add_files(string dir)\n{\n DIR *dp;\n struct dirent *dirp;\n if((dp = opendir(dir.c_str())) == NULL) \n {\n cout << \"Error(\" << errno << \") opening \" << dir << endl;\n return errno;\n }\n\n while ((dirp = readdir(dp)) != NULL) \n {\n \tstring tmpName = string(dirp->d_name);\n \t\t//cout<<tmpName<<endl;\n\n \tif( tmpName != \".\" && tmpName != \"..\")\n \t{\n \t\tSTRU_PATH path;\n \t\tpath.name = tmpName;\n \t\tpath.path = dir+\"/\"+tmpName;\n \t\t_files.push_back( path );\n \t}\n }\n closedir(dp);\n return 0;\n}\n\nbool PathFinder::get_next_file(std::string& file_name, std::string& file_path)\n{\n\tif(_files.size() == 0)\n\t\treturn false;\n\n\tfile_path = _files.front().path;\n\tfile_name = _files.front().name;\n\t\n\t_files.pop_front();\n\treturn true;\n}\n" }, { "alpha_fraction": 0.6557971239089966, "alphanum_fraction": 0.6557971239089966, "avg_line_length": 15.29411792755127, "blob_id": "1a999e1362898feccd718242a27c6646234c26c0", "content_id": "cdd4e1c728e2648b7a8d0ece16452c65d691c35d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 276, "license_type": "no_license", "max_line_length": 87, "num_lines": 17, "path": "/indexing/src/include/utility/gzip.h", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "#ifndef __GZIP_H__\n#define __GZIP_H__\n\n\nclass gzip\n{\npublic:\n\tgzip();\n\t~gzip();\npublic:\n\tstatic char* uncompress_from_file(const char* file_name, int size, int& already_len );\n\tstatic bool compress_to_file(const char* file_name, char* data, int len);\n\n};\n\n\n#endif //__GZIP_H__" }, { "alpha_fraction": 0.5134345293045044, "alphanum_fraction": 0.5250306129455566, "avg_line_length": 24.990196228027344, "blob_id": "491d95752a97421006a60589430bd339e56807ce", "content_id": "14d79d90b2c4e3fd571c0a050b09a997819b4aec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10607, "license_type": "no_license", "max_line_length": 155, "num_lines": 408, "path": "/newyorktimes/src/generating/analysis_ctrl.cpp", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "#include \"analysis_ctrl.h\"\n#include <sys/stat.h>\n#include <iostream>\n#include <fstream>\n#include <stdlib.h>\n\nusing namespace std;\n\n#define INDEX_CHUNK 409600 //50KB\n#define DATA_CHUNK 20971520 //2.5MB\n\nanalysis_ctrl::analysis_ctrl()\n{\n _dataset_path = \"./dataset/\";\n\n _file_start = 0;\n _file_end = 82;\n _file_now = _file_start;\n _doc_id = 1;\n _word_id =1;\n _intermediate = new StreamBuffer(120*1024*1024*5);\n mkdir(\"intermediate\", S_IRWXU|S_IRGRP|S_IXGRP);\n _intermediate->setfilename(\"intermediate/posting\");\n _intermediate->setpostingsize(12);\n _intermediate->set_sort(true);\n _time_now = time(0); \n\n}\n\nanalysis_ctrl::~analysis_ctrl()\n{\n if(_intermediate != NULL)\n delete _intermediate;\n}\n\nbool analysis_ctrl::start()\n{\n //set display call back\n //display::get_instance()->set_input_call_back(this);\n \n do_it();\n\n\n \n return true;\n}\n\nvoid analysis_ctrl::stop()\n{\n //stop display\n display::get_instance()->stop();\n\n}\n\nvoid analysis_ctrl::input_event( char* key )\n{\n\n if( strcmp(key,\"quit\") == 0)\n stop();\n else\n cout<<\"press 'quit' to exit\"<<endl;\n}\n\n\n// core algorithm\nvoid analysis_ctrl::do_it()\n{\n string next_file_name, next_file_path;\n char* parsed_data = new char[DATA_CHUNK];\n int data_len = 0;\n int doc_len;\n while( _finder.get_next_file(next_file_name,next_file_path))\n {\n string doc_title,doc_url=\"\",doc_location=\"\";\n int doc_date=0;\n // parse xml data from file \n if( !parse_xml(next_file_path, parsed_data, DATA_CHUNK, doc_title,doc_url,doc_location, doc_date,doc_len))\n {\n cout<<\"parse xml failed:\"<<next_file_path<<endl;\n continue; \n }\n //cout<<parsed_data<<endl;\n\n //gen a new doc id, store docs' information, and build index of docs\n int doc_id = get_doc_id(next_file_name ,next_file_path ,doc_title,doc_url,doc_location,doc_date, doc_len);\n cout<<\"parsing doc id:\"<<doc_id<<\"=>\"<<next_file_path<<\" title:\"<<doc_title<<endl;\n // cout<<\"url:\"<<doc_url<<\" location:\"<<doc_location<<\" date:\"<<doc_date<<endl;\n\n\n //save the data to form intermediate\n save_data(doc_id, parsed_data, DATA_CHUNK);\n \n //break;\n }\n \n \n StreamBuffer buffer1(50*1024*1024);\n buffer1.setfilename(\"intermediate/word_map.data\");\n buffer1>>_word_map;\n buffer1.savetofile();\n\n //save docs map;\n StreamBuffer buffer2(450*1024*1024);\n buffer2.setfilename(\"intermediate/docs_map.data\");\n buffer2>>_docs_map;\n buffer2.savetofile();\n\n //\n _intermediate->savetofile();\n\n\n StreamBuffer buffer3(50*1024*1024); \n buffer3.setfilename(\"intermediate/location.data\");\n\n for (set<string>::iterator it=_locations.begin(); it!=_locations.end(); ++it)\n { \n int tmp = (*it).length();\n buffer3.write((*it).c_str(), (*it).length());\n buffer3.write(\"\\n\");\n // cout<<tmp<<\" \"<<(*it).c_str()<<endl;\n }\n\n buffer3.savetofile();\n \n\n cout<<\"location count:\"<<_locations.size()<<endl;\n\n cout<<\"[finish] time consumed: \"<<time(0)-_time_now<<\"s\"<<endl;\n \n}\n\n\n\n\n\nbool analysis_ctrl::parse_xml(std::string file_path, char* buf, int buf_len,string& title, string& url, string& location,int& date,int& doc_len)\n{\n if( buf == NULL)\n return false;\n\n //open file\n ifstream file;\n file.open(file_path.c_str());\n int off_start, off_end;\n\n if (file.is_open())\n {\n file.seekg (0, file.end);\n int length = file.tellg();\n file.seekg (0, file.beg);\n char * xml_buffer = new char [length];\n // read data as a block:\n file.read(xml_buffer,length);\n\n int start_pos=0;\n string year,month,day;\n\n\n //get title\n if( !get_new_info(xml_buffer,length, start_pos, \"<title>\", \"</title>\", title) )\n {\n cout<< \"get title failed!\"<<endl;\n }\n\n //get day\n if( !get_new_info(xml_buffer,length, start_pos, \"meta content=\\\"\", \"\\\" name=\\\"publication_day_of_month\\\"\", day) )\n {\n cout<< \"get day failed!\"<<endl;\n }\n\n //get month\n if( !get_new_info(xml_buffer,length, start_pos, \"meta content=\\\"\", \"\\\" name=\\\"publication_month\\\"\", month) )\n {\n cout<< \"get month failed!\"<<endl;\n }\n\n //get year\n if( !get_new_info(xml_buffer,length, start_pos, \"meta content=\\\"\", \"\\\" name=\\\"publication_year\\\"\", year) )\n {\n cout<< \"get year failed!\"<<endl;\n }\n\n //cout<<\"year:\"<<year<<\" month:\"<<month<<\" day:\"<<day<<endl;\n date = atoi(year.c_str())*10000 + atoi(month.c_str())*100 + atoi(day.c_str());\n\n // cout<<date<<endl;\n\n //get location\n if( !get_new_info(xml_buffer,length, start_pos, \"indexing_service\\\">\", \"</location>\", location) )\n {\n //cout<< \"get url failed!\"<<endl;\n location = \"NULL\";\n }\n //if( location != \"NULL\")\n // cout<<location<<endl;\n\n //get url\n if( !get_new_info(xml_buffer,length, start_pos, \"ex-ref=\\\"\", \"\\\" i\", url) )\n {\n cout<< \"get url failed!\"<<endl;\n }\n\n\n //get content & parse\n string content;\n if( !get_new_info(xml_buffer,length, start_pos, \"<block class=\\\"full_text\\\">\\n\", \"</block>\", content) )\n {\n cout<< \"get title failed!\"<<endl;\n }\n // parse content\n int ret = parser((char*)title.c_str(), (char*)content.c_str() , buf, buf_len);\n doc_len = content.length();\n //output words and their contexts\n if (ret < 0)\n {\n cout<<\"error during the parse\"<<endl;\n\n }\n\n //\n delete[] xml_buffer;\n file.close();\n\n return true;\n }\n else \n {\n cout << \"Unable to open file:\"<<file_path<<endl;\n return false;\n } \n \n return true;\n\n}\n\nbool analysis_ctrl::get_new_info(char* source, int max, int& start_pos, std::string key_start, std::string key_end, string& content)\n{\n int offset_start;\n int offset_end;\n\n if( (offset_start = find(source, max, start_pos,key_start )) != -1 && (offset_end = find(source, max, offset_start+key_start.length(), key_end)) != -1)\n {\n offset_start = offset_start + key_start.length();\n int len = offset_end - offset_start;\n char* tmp = new char[len + 1];\n tmp[len]= '\\0';\n memcpy( tmp, source+offset_start, len );\n content = tmp;\n\n delete[] tmp;\n //cout<<\"$$$\"<<content<<endl;\n start_pos = offset_end+key_end.length();\n return true;\n }\n\n return false;\n}\n\nint analysis_ctrl::find(char* source, int max_len, int start, std::string key_words)\n{\n if(source == NULL)\n return false;\n \n int same_len = 0;\n int same_max = key_words.length();\n for(int i = start; i< max_len; i++)\n {\n if(source[i] == key_words[same_len]) \n {\n same_len++;\n if( same_len == same_max)\n {\n // cout<<\"find_key:\"<<key_words<<endl;\n return (i - same_max+1);\n }\n }\n else\n same_len = 0;\n }\n\n return -1;\n}\n\n\nbool analysis_ctrl::save_data(int doc_id, char* save_data, int len)\n{\n int pos = 0;\n int offset_val =0;\n\n // int percent = _file_end - _file_start == 0? 100 : ( (float)(_file_now -1 - _file_start) / (float)(_file_end - _file_start) )*100;\n \n int pos_count = 0;\n // cout<<\"[-\"<<percent<<\"\\%-][doc:\"<<doc_id<<\"]\"<<endl;\n while(pos < len )\n {\n string word=\"\";\n string context=\"\";\n string positon=\"\";\n\n if(\n !get_one_word(save_data , pos, word) ||\n !get_one_word(save_data , pos, positon) ||\n !get_one_word(save_data , pos, context)\n )\n break;\n\n //cout<<\"[\"<<pos<<\"]\"<<\"word=>\"<<word<<\" pos=>\"<<positon<<\" context=>\"<<context<<endl ;\n\n\n //continue;\n //if it is word \n \n TempLexicon new_lexicon;\n\n new_lexicon.word_id = get_word_id(word);\n new_lexicon.doc_id = doc_id;\n new_lexicon.startpos =pos_count++;//atoi(positon.c_str()); //atoi(positon.c_str());\n //new_lexicon.issue_date = \n\n //cout<<\"[doc:\"<<new_lexicon.doc_id<<\"] : \"<<word<<\"=>word_id:\"<<new_lexicon.word_id<<\" position:\"<<new_lexicon.startpos<<endl;\n\n //save temp Lexicon\n (*_intermediate)>>new_lexicon;\n \n \n \n }\n \n //cout<<pos<<\"--------------------------------\"<<endl<<endl<<endl<<endl<<endl;\n\n return true;\n}\n\n//get on word from file\nbool analysis_ctrl::get_one_word(char* source ,int& pos,string& str)\n{\n\n\n char get_num = 0;\n while( source[pos] != '\\0')\n {\n\n if(source[pos] == '\\r' || source[pos]=='\\n' || source[pos] == ' ')\n {\n \n if( get_num == 0)\n {\n pos++;\n\n continue;\n }\n else\n {\n pos++;\n return true;\n }\n }\n else \n {\n str+=source[pos++];\n get_num++;\n //cout<<str.c_str()<<endl;\n }\n }\n //if( source[pos] == '\\0')\n return false;\n}\n\nint analysis_ctrl::get_doc_id(string doc_name, string doc_path, string doc_title,string doc_url,string doc_location, int doc_time, int doc_len )\n{\n\n if(_checker.find(doc_name) != _checker.end())\n { \n cout<<\"doc repeat:\"<<doc_name<<\"=>\"<<_checker[doc_name]<<endl;\n return _checker[doc_name];\n }\n _checker[doc_name]= _doc_id;\n\n _docs_map[_doc_id].doc_name = doc_name;\n _docs_map[_doc_id].doc_path = doc_path;\n _docs_map[_doc_id].doc_title = doc_title;\n _docs_map[_doc_id].doc_url = doc_url;\n _docs_map[_doc_id].doc_location = doc_location;\n _docs_map[_doc_id].doc_time = doc_time;\n _docs_map[_doc_id].len = doc_len;\n if(doc_location!= \"NULL\"&& doc_location.length()<20 && _locations.find(doc_location)== _locations.end() )\n {\n _locations.insert(doc_location);\n //cout<<doc_location<<endl;\n }\n // _docs_map[_doc_id].offset = offset;\n // _docs_map[_doc_id].len = len;\n // cout<<\"doc_title:\"<<_docs_map[_doc_id].doc_title<<\"doc_time:\"<<_docs_map[_doc_id].doc_time<<endl;\n return _doc_id++;\n}\n\nint analysis_ctrl::get_word_id(string word)\n{\n if(_word_map.isHas(word))\n { \n // cout<<\"word repeat:\"<<word<<\"=>\"<<_word_map[word]<<endl;\n return _word_map[word];\n }\n\n _word_map[word] = _word_id;\n return _word_id++;\n\n} \n" }, { "alpha_fraction": 0.6448215246200562, "alphanum_fraction": 0.6477472186088562, "avg_line_length": 17, "blob_id": "4e3d513473180674a300f765a97244fd3b53200e", "content_id": "842944f98917ff43edeb4775b1eddb3dd2dfc6ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1709, "license_type": "no_license", "max_line_length": 81, "num_lines": 95, "path": "/indexing/src/generating/analysis_ctrl.h", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "#ifndef __ANALYSIS_CTRL_\n#define __ANALYSIS_CTRL_\n\n#include \"utility/display.h\"\n#include \"utility/gzip.h\"\n#include \"models/original_index.h\"\n#include \"models/TempLexicon.h\"\n#include \"models/WordMap.h\"\n#include \"parser/parser.h\"\n#include \"models/StreamBuffer.h\"\n#include \"models/Docmap.h\"\n#include <ctime>\n\n#include <string>\n\n\nstruct status\n{\n\tint _deal_docs;\n\tint _deal_words;\n\n\tstatus()\n\t{\n\t\t_deal_docs = 0;\n\t\t_deal_words= 0;\n\t}\n};\n\nstruct DataSet\n{\n\tstd::string\t_index;\n\tstd::string _data;\n\tstd::string _path;\n\tint \t\t_file_num;\n\n\tDataSet(std::string path)\n\t{\n\t\t_path = path;\n\t}\n\tvoid set_num(int num)\n\t{\n\t\t_file_num = num;\n\t\tchar temp[64] = {0};\n\t\tsprintf ( temp, \"%d_index\", num );\n\t\t_index = _path+temp;\n\t\tsprintf ( temp, \"%d_data\", num );\n\t\t_data = _path+temp;\n\t}\n};\n\nclass analysis_ctrl : d_key_event\n{\npublic:\n\tanalysis_ctrl();\n\t~analysis_ctrl();\n\n\tbool start();\n\tvoid stop();\n\n\t/*key input callback*/\n\tvoid input_event( char* key );\n\nprivate:\n\tvoid do_it();\n\tbool save_index(char* index_data, int len, original_index& index, int file_num);\n\tbool parse_data(char* html_data, int len, original_index& index);\n\tbool save_data(int doc_id, char* save_data, int len);\n\tbool get_next_file_name(DataSet& data_set);\t\t//get next file name\n\tint get_doc_id(std::string doc_name,int file_num, int offset, int len);\n\tint get_word_id(std::string word);\n\tbool parse();\n\tbool get_one_word(char* source, int& pos,string& str);\n\n\nprivate:\n\t\n\tstatus\t\t\t_status;\n\tstd::string\t\t_dataset_path;\t\n\tint \t\t\t_file_now;\n\tint \t\t\t_file_start;\n\tint \t\t\t_file_end;\n\tint \t\t\t_doc_id;\n\tint \t\t\t_word_id;\n\tStreamBuffer* \tbuffer;\n\ttime_t \t\t\t_time_now ; \n\n\n\tWordMap\t\t\t_word_map;\n\tDocMap \t\t\t_docs_map;\n\tmap<string,int>\t_checker;\n\n};\n\n\n#endif" }, { "alpha_fraction": 0.588447630405426, "alphanum_fraction": 0.6209385991096497, "avg_line_length": 18.85714340209961, "blob_id": "1804a09aeb1682d6cb43fc83e24472a1314ace49", "content_id": "e05c94aed92f8ffc0367e54e48c6c1a9aad783d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 277, "license_type": "no_license", "max_line_length": 74, "num_lines": 14, "path": "/crawling/strategies/filetypehandler.py", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "'''\nCreated on Feb 14, 2013\n\n@author: Adam57\n'''\n\nimport mimetypes\n\nclass FileTypeHandler(object):\n def FileTypeChecker(self,html_task):\n if mimetypes.guess_type(html_task._url)[0] in ['text/html', None]:\n return True\n else:\n return False" }, { "alpha_fraction": 0.6705107092857361, "alphanum_fraction": 0.6836903095245361, "avg_line_length": 19.233333587646484, "blob_id": "45878612c27cf71511aaad4d6414e2a0b9c12427", "content_id": "3740a67c784b983080258375ea334db3933c6075", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 607, "license_type": "no_license", "max_line_length": 67, "num_lines": 30, "path": "/indexing/src/include/models/WordMap.h", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "/*\n * WordMap.h\n *\n * Created on: Feb 25, 2013\n * Author: Adam57\n */\n\n#ifndef WORDMAP_H_\n#define WORDMAP_H_\n#include <map>\n#include <string>\nusing namespace std;\n#include \"StreamBuffer.h\"\n\nclass WordMap {\npublic:\n\tWordMap();\n\tvirtual ~WordMap();\n\tbool isHas(string key);\n\tint& operator[](string key){return map[key];}\n\tvoid serialize( StreamBuffer &stream );\n\tvoid deserialize( char* buffer, int size );\n\t\n\t//friend StreamBuffer& operator<<(StreamBuffer &stream, WordMap&);\n\tfriend StreamBuffer& operator>>(StreamBuffer &stream, WordMap&);\nprivate:\n\tmap<string, int> map;\n};\n\n#endif /* WORDMAP_H_ */\n" }, { "alpha_fraction": 0.6055172681808472, "alphanum_fraction": 0.6151723861694336, "avg_line_length": 21.59375, "blob_id": "b03d59ec62ab1b129f8f8d22660d6af2b51b0580", "content_id": "4d940a822cbf3d5aea0919077eee86c933582a7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 725, "license_type": "no_license", "max_line_length": 129, "num_lines": 32, "path": "/crawling/include/database.py", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "\"\"\"\nCreated on Feb 12, 2013\n\n@author: derrick\n\n\"\"\"\nimport MySQLdb\nfrom include.log import Log\nfrom models.configuration import Configuration\n\nclass Database(object):\n\t\n def __init__(self, config ):\n\t\tself._config \t\t= config\n\n def execute(self,sql):\n try: \n conn = MySQLdb.connect(host=self._config._host,\tuser=self._config._user, passwd=self._config._passwd, db=self._config._db) \n conn.autocommit(True)\n cur = conn.cursor()\n \t\t\t#sql=\"select * from `status`\" \n \t\t\t#print sql\n cur.execute(sql)\n \t\t\t#for row in cur.fetchall() :\n \t\t#\t\t print row[1]\n return cur.fetchall()\n except (Exception) as e: \n# \t\t\tLog().debug(e)\n \t\t\treturn None\n finally:\n if conn:\n conn.close()\n\n\n" }, { "alpha_fraction": 0.6158823370933533, "alphanum_fraction": 0.6205882430076599, "avg_line_length": 30.462963104248047, "blob_id": "d9c486907dc19605f94a198df3ea3ee3b0230c2d", "content_id": "b4fd1bff34e852f7a7a33d3676ba9af7b270433e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1700, "license_type": "no_license", "max_line_length": 107, "num_lines": 54, "path": "/crawling/include/log.py", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "\"\"\"\nCreated on Feb 1, 2013\n\n@author: Adam57\n\nThis part takes care of the logging\n\"\"\"\nimport os \nimport time \nimport logging \nimport inspect\nimport sys, traceback\n\nclass Log(object):\t \n def __init__(self): \n self.__logger = logging.getLogger() \n path = os.path.abspath(\"Log.log\") \n handler=logging.FileHandler(path) \n self.__logger.addHandler(handler) \n self.__logger.setLevel(logging.WARNING)\n def getLogMessage(self,level,message):\n frame,filename,lineNo,functionName,code,otherinfo = inspect.stack()[2] \n return \"[%s] [%s] [%s - %s - %s] %s\" %(self.printfNow(),level,filename,lineNo,functionName,message)\n def info(self,message): \n message = self.getLogMessage(\"info\",message) \n print(message)\n self.__logger.info(message)\n def error(self,message): \n message = self.getLogMessage(\"error\",message)\n print(message)\n self.__logger.error(message)\n def warning(self,message): \n message = self.getLogMessage(\"warning\",message)\n print(message) \n self.__logger.warning(message)\n def debug(self,message): \n message = self.getLogMessage(\"debug\",message) \n print(message)\n traceback.print_exc(file=sys.stdout)\n self.__logger.debug(message)\n def critical(self,message): \n message = self.getLogMessage(\"critical\",message) \n print(message)\n self.__logger.critical(message)\n def printfNow(self): \n return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())\n def write(self, string):\n print(string)\t\n\n\nif __name__ == \"__main__\": \n logger = Log() \n logger.info(\"hello\")\n logger.warning(\"hello\")\n\n" }, { "alpha_fraction": 0.5305810570716858, "alphanum_fraction": 0.567278265953064, "avg_line_length": 23.259260177612305, "blob_id": "928c8ef5eaa75c50c5ca6a9e01d924d2792c9942", "content_id": "58e1a41e7227d086cebc6d87a048d727513e3301", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 654, "license_type": "no_license", "max_line_length": 83, "num_lines": 27, "path": "/crawling/strategies/nestlevelhandler.py", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "'''\nCreated on Feb 13, 2013\n\n@author: Adam57\n'''\n\nfrom urlparse import urlsplit\nfrom models.html import Html\n\nclass NestLevelHandler(object):\n \n def checknestlevel(self, html_task, level):\n\n if (len(list(set(urlsplit(html_task._url).path.split('/')))) - 1 >= level):\n #print len(list(set(urlsplit(html_task._url).path.split('/')))) - 1\n return True\n else:\n return False\n \n \nif __name__ ==\"__main__\":\n h = Html(\"http://www.test.com/1/2/3/4/5/6\")\n n = NestLevelHandler()\n print n.checknestlevel(h,4)\n \n list = \"http://www.test.com/1/2/3/4/5/6\"\n print list.replace('6','')" }, { "alpha_fraction": 0.6276497840881348, "alphanum_fraction": 0.6294931173324585, "avg_line_length": 9.647058486938477, "blob_id": "acb8f03f40c74db0a0d540ab4557833538b562ad", "content_id": "483c9a3e1adb16eb9fefb87f1e2103bb51ffb5fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1085, "license_type": "no_license", "max_line_length": 45, "num_lines": 102, "path": "/newyorktimes/src/include/utility/lock.h", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "/*Author: derrick*/\n#ifndef D_LOCK_H\n#define D_LOCK_H\n\n#ifdef WIN32\n#include <windows.h>\n\n\nclass win_lock\n{\npublic:\n\twin_lock()\n\t{\n\t\tInitializeCriticalSection(&_section);\n\t}\n\n\t~win_lock()\n\t{\n\t\tDeleteCriticalSection(&_section);\n\t}\n\n\tvoid Enter()\n\t{\n\t\t\n\t\t EnterCriticalSection(&_section);\n\t}\n\t\n\tvoid Leave()\n\t{\n\t\tLeaveCriticalSection(&_section);\n\t}\n\nprivate:\n\tCRITICAL_SECTION\t_section;\n};\n\n\ntypedef win_lock lock;\n#else\n#include <pthread.h>\n\nclass linux_lock\n{\npublic:\n\tlinux_lock()\n\t{\n\t\tpthread_mutex_init(&_mutex, NULL);\n\t}\n\n\t~linux_lock()\n\t{\n\t\tpthread_mutex_destroy(&_mutex);\n\t}\n\n\tvoid Enter()\n\t{\n\t\t pthread_mutex_lock(&_mutex);\n\t}\n\t\n\tvoid Leave()\n\t{\n\t\tpthread_mutex_unlock(&_mutex);\n\t}\nprivate:\n\t pthread_mutex_t _mutex;\n};\n\ntypedef linux_lock lock;\n\n#endif\n\nclass none_lock\n{\npublic:\n\tnone_lock(){}\n\t~none_lock(){}\n\tvoid Enter(){}\n\tvoid Leave(){}\n};\n\nclass lock_helper\n{\npublic:\n\tlock_helper(lock& alock) : _lock(alock)\n\t{\n\t\t\n\t\t_lock.Enter();\n\t}\t\n\t~lock_helper()\n\t{\n\t\n\t\t_lock.Leave();\n\t}\nprivate:\n\tlock& _lock;\n};\n\n\n#define LockHelper(T) lock_helper loHelper(T)\n\n\n#endif //D_LOCK_H" }, { "alpha_fraction": 0.5421180129051208, "alphanum_fraction": 0.5598768591880798, "avg_line_length": 23.877761840820312, "blob_id": "f7f1d209450ca5deac1cd65474a47eecd1b0a33f", "content_id": "7b8d0593eb0da08b41ee33cc6d066bfd7ebca1d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 16893, "license_type": "no_license", "max_line_length": 176, "num_lines": 679, "path": "/newyorktimes/src/searching/searching_algorim.cpp", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "#include \"searching_algorim.h\"\n#include <stdio.h>\n#include <math.h>\n#include <sys/time.h>\n#include <stdio.h>\n#include <unistd.h>\nusing namespace std;\n#define INDEX_CHUNK 409600 //50KB\n#define DATA_CHUNK 20971520 //2.5MB\nenum SERACH_TYPE { REVL, TIME_DESC, TIME_ASC, LOCATION };\n\n\nSearchingAlgorim::SearchingAlgorim()\n{\n\tinit_data();\n}\n\nSearchingAlgorim::~SearchingAlgorim()\n{\n\n}\n\nvoid SearchingAlgorim::init_data()\n{\n\tk1 = 1.2;\n\tb = 0.75;\n\t//read doc map\n\t \n\tint size = 0;\n\tchar* buffer = init_buffer_from_file(\"intermediate/docs_map.data0\",size);\n\tif( buffer == NULL)\n\t\treturn;\n\t//cout<<buffer<<size;\n\t_doc_map.deserialize(buffer,size,d_agv,N);\n\tcout<<\"d:\"<<d_agv<<\" N:\"<<N<<endl;\n\n\tdelete buffer;\n\n\t//read word map\n\tbuffer = init_buffer_from_file(\"intermediate/word_map.data0\",size);\n\tif( buffer == NULL)\n\t\treturn;\n\t//cout<<buffer<<size;\n\t_word_map.deserialize(buffer,size);\n\t\n\tdelete buffer;\n/*\n\tint offset;\n\tfor(map<string, STRU_DOC>::iterator it=_doc_map._data.begin(); it != _doc_map._data.end(); it++)\n\t{\n\t\tif(it->second.doc_id == 4167)\n\t\t{\n\t\t\tcout<<\"file_id:\"<<it->second.file_id<<\"offset:\"<<it->second.offset<<endl;\n\n\t\t}\n\t}\n\n\tifstream file (\"/intermediate\" , ios::in|ios::binary);\n\tif (file.is_open())\n\t{\n\t\tfile.seekg(5043003, ios::beg);\n\t\tsize = file.tellg();\n\t}\n*/\n\tstd::string file=\"result/\";\n\tchar filename[50]={0};\n\tint index_num = 5;\n\tint part1,part2,part3,part4,part5,len,test;\n\tchar tmp[4];\n\n\t/*load word_index*/\n\tfor(int i=0; i<index_num; i++){\n\tsprintf (filename, \"word_index%d\", i);\n\tfile = file + filename;\n\tifstream myFile (file.c_str(), ios::in | ios::binary);\n\n\twhile(myFile.peek()!=EOF){\n\tmyFile.read(tmp,sizeof(int));\n\tmemcpy(&part1, tmp, sizeof(int));\n\tmyFile.read(tmp,sizeof(int));\n\tmemcpy(&part2, tmp, sizeof(int));\n\tmyFile.read(tmp,sizeof(int));\n\tmemcpy(&part3, tmp, sizeof(int));\n\tmyFile.read(tmp,sizeof(int));\n\tmemcpy(&part4, tmp, sizeof(int));\n\tword_inf inf1 = {part2,part3,part4};\n\tword_index.insert(pair<int, word_inf>(part1,inf1));\n\t }\n\tfile=\"result/\";\n\t}\n\t//for ( map<int, word_inf>::iterator it = word_index.begin(); it!=word_index.end(); ++it)\n\t//\t\tcout << it->first << \" => \" << it->second.doc_num << \" => \" << it->second.chunk_num << \" => \" << it->second.posting_num << '\\n';\n\tprintf(\"the size of word_index map %d\\n\", word_index.size());\n\n\t/*load chunk_index*/\n\tfile=\"result/\";\n\tchar filename1[50]={0};\n\tfor(int i=0; i<2; i++){\n\tsprintf (filename1, \"chunk_index%d\", i);\n\tfile = file + filename1;\n\tifstream myFile (file.c_str(), ios::in | ios::binary);\n\n\twhile(myFile.peek()!=EOF){\n\tmyFile.read(tmp,sizeof(int));\n\tmemcpy(&part1, tmp, sizeof(int));\n\tmyFile.read(tmp,sizeof(int));\n\tmemcpy(&part2, tmp, sizeof(int));\n\tmyFile.read(tmp,sizeof(int));\n\tmemcpy(&part3, tmp, sizeof(int));\n\tmyFile.read(tmp,sizeof(int));\n\tmemcpy(&part4, tmp, sizeof(int));\n\tmyFile.read(tmp,sizeof(int));\n\tmemcpy(&part5, tmp, sizeof(int));\n\tchunk chunk1 = {part2,part3,part4,part5};\n\tchunk_index.insert(pair<int, chunk>(part1,chunk1));\n\t }\n\tfile=\"result/\";\n\t}\n\t//for ( map<int, chunk>::iterator it = chunk_index.begin(); it!=chunk_index.end(); ++it)\n\t//\t\tcout << it->first << \" => \" << it->second.chunk_last_wordid << \" => \" << it->second.chunk_last_docid << \" => \" << it->second.filenum <<\" => \" <<it->second.offset << endl;\n\tprintf(\"the size of chunk_index map %d\\n\", chunk_index.size());\n\n\t/*load word_map*/\n\tfile=\"intermediate/\";\n\t\tchar filename2[50]={0};\n\t\tfor(int i=0; i<1; i++){\n\t\tsprintf (filename2, \"word_map.data%d\", i);\n\t\tfile = file + filename2;\n\t\tifstream myFile (file.c_str(), ios::in | ios::binary);\n\n\t\twhile(myFile.peek()!=EOF){\n\n\t\tmyFile.read(tmp,sizeof(int));\n\t\tmemcpy(&len, tmp, sizeof(int));\n\t\tchar tmp_buf[len+1];\n\t\ttmp_buf[len]='\\0';\n\t\tmyFile.read(tmp_buf,len);\n\t\tstring mystring(tmp_buf);\n\n\t\tmyFile.read(tmp,sizeof(int));\n\t\tmemcpy(&part2, tmp, sizeof(int));\n\n\t\tword_map.insert(pair<string, int>(mystring, part2));\n\t\t }\n\t\tfile=\"intermediate/\";\n\t\t}\n\t\t//for ( map<string, int>::iterator it = word_map.begin(); it!=word_map.end(); ++it)\n\t\t//\t\tcout << it->second << \" => \" << it->first<<endl;\n\t\tprintf(\"the size of word_map %d\\n\", word_map.size());\n\n\t\tcout<<\"making tages...\"<<endl;\n\n\t\tfor (map<string, int>::iterator it=_word_map.map.begin(); it!=_word_map.map.end(); ++it)\n\t {\n\t \t_word_map2[it->second]=it->first;\n\t }\n\t\t\n\t\tint big = 0;\n\t\tint last_chunk_num = 0;\n\t\tint last_word_id = 0;\n\t\tint count = 0;\n\t\tfor(int i = 1; i < word_index.size()-1;i++)\n\t\t{\n\t\t\tint num_of_chunks = word_index[i+1].chunk_num - word_index[i].chunk_num+1;\n\t\t\tif(count< 200)\n\t\t\t{\n\t\t\t\ttags[count].count = num_of_chunks;\n\t\t\t\ttags[count].word = _word_map2[i];\n\t\t\t\tcount++;\n\t\t\t}\n\t\t\telse if(num_of_chunks > tags[0].count)\n\t\t\t{\n\t\t\t\ttags[0].count = num_of_chunks;\n\t \t\ttags[0].word = _word_map2[i];\n\t\n\t\t\t}\n\t\t\tsort_tags(tags,0,count-1);\n\n\t\t}\n\t\tint base = tags[80].count;\n\t\tint max_font_size = 7;\n\t\tint min_font_size = 1;\n\n\t\tfor(int i =0;i<20;i++)\n\t {\n\t \ttags[i].count = (float)(tags[i+60].count- base)/(float)(tags[60].count-base)*(max_font_size-min_font_size) + min_font_size;\n\t \ttags[i].word = tags[i+60].word;\n\n\t \tcout<<tags[i].word<<\" font:\"<<tags[i].count<<endl;\n\t }\n\n}\nvoid SearchingAlgorim::sort_tags(TAGS* arr,int left, int right)\n{\n\tif(arr == NULL)\n\t\treturn;\n\tint pivot = arr[(left+right)/2].count;\n\n\tint i = left, j=right;\n\n\t//partition\n\twhile(i <= j)\n\t{\n\t\twhile(arr[i].count < pivot)\n\t\t\ti++;\n\t\twhile(arr[j].count > pivot)\n\t\t\tj--;\n\t\t\n\t\tif(i <= j)\n\t\t{\n\t\t\tTAGS tmp = arr[i];\n\t\t\tarr[i] = arr[j];\n\t\t\tarr[j] = tmp;\n\t\t\ti++;\n\t\t\tj--;\n\t\t}\n\t}\n\tif( j > left)\n\t\tsort_tags(arr, left ,j);\n\tif( i < right)\n\t\tsort_tags(arr, i , right);\n}\n\nchar* SearchingAlgorim::init_buffer_from_file(string file_name, int& size)\n{\t\n\t//cout<<file_name<<endl;\n\tifstream file (file_name.c_str() , ios::in|ios::binary);\n\tif (file.is_open())\n\t{\n\t\tfile.seekg(0, ios::end);\n\t\tsize = file.tellg();\n\t\t//cout<<size<<endl;\n\t\tchar *buffer = new char [size];\n\t\tfile.seekg (0, ios::beg);\n\t\tfile.read (buffer, size);\n\t\tfile.close();\t\n\n\t\t//cout<<\"buf:\"<<buffer<<endl;\n\n\t\t//int a;\n\t\t/*char *b = new char[55];\n\t\tb[54]='\\0';\n\t\tmemcpy(b,buffer+4,54);\n\t\tcout<<\"b:\"<<b<<endl;*/\t\t\n\t\treturn buffer;\n\t}\n\telse\n\t{\n\t\tcout<<file_name<<\" open filed\"<<endl;\n\t\treturn NULL;\n\t}\n}\n\nvoid SearchingAlgorim::do_searching(char* words)\n{\t\n\tstruct timeval start, end;\n \n gettimeofday(&start, NULL);\n \n\tcout<<\"do searching....\"<<words<<endl;\n\t//for(int i =0; i< key_words.size();i++)\n\t//\tcout<<key_words[i]<<\" \";\n\tresult_count = 0;\n\tint request_count = 0;\n\tstring word=\"\";\n\tint pos=0;\n\tvector<string> request_list;\n\tint bType = 0;\n\tstring searchType = \"\";\n\tstring searchLocation = \"\";\n\twhile(get_one_word(words,pos,word))\n\t{\n\t\tif( bType == 0)\n\t\t{\n\t\t\tsearchType = word;\n\t\t\tcout<<\"Search type:\"<<searchType<<endl;\n\t\t\tbType = 1;\n\t\t\tword=\"\";\n\t\t\tcontinue;\n\t\t}\n\t\tif( bType == 1)\n\t\t{\n\t\t\tif(word == \"$\")\n\t\t\t{\n\t\t\t\tbType = 2;\n\t\t\t\tword = \"\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif(searchLocation == \"\")\n\t\t\t\tsearchLocation = word;\n\t\t\telse\n\t\t\t\tsearchLocation += \" \"+word;\n\t\t\tword=\"\";\n\t\t\tcontinue;\n\n\t\t}\n\n\t\tcout<<\"new words:\"<<word<<endl;\n\t\trequest_list.push_back(word);\n\t\trequest_count++;\n\t\tword=\"\";\n\n\t}\n\tcout<<\"Search location:\"<<searchLocation<<endl;\n\n\tif(request_count == 0)\n\t\treturn;\n\n\tvector<Lp*> p;\n//\t_result.print();\n\tfor(int i = 0 ; i < request_list.size();i++)\n\t{\n\t\tint word_id=_word_map[request_list[i]];\n\t\tcout<<\"word: \"<<request_list[i]<<\" word_id:\"<<word_id<<endl;\n\t\tif(word_id == 0)\n\t\t\tcontinue;\n\t\tLp* tmp = openList(word_id);\n\t\tif(tmp == NULL)\n\t\t\tcontinue;\n\t\tp.push_back(tmp);\n\t}\n\tif(p.size() == 0)\n\t\treturn;\n\tcout<<\"p.size:\"<<p.size()<<endl;\n\tcout<<\"doc_map_size\"<<_doc_map._data.size()<<endl;\n\n\tint did = 0;\n\twhile(did < N)\n\t{\n\t\tint d = 0;\n\t \tdid = nextGEQ(p[0],did);\n\t \tif( did == 0)\n \t\t{\t\n \t\t\tcout<<\"did = 0\"<<endl; \n \t\t\tcontinue;\n \t\t}\n\t \tfor(int i = 1; (i< p.size())&& ((d=nextGEQ(p[i],did))==did);i++);\n\t \tif(did> N)\n\t \t\tbreak;\n\t\tif(d > did) did = d-1;\n\t\telse\n\t\t{\n\n\t\t\tfloat bm25_all = 0.0;\n\t\t\tSTRU_DOC one_doc = _doc_map[did];\n\t\t\t//location\n\t\t\tif(!isInThisLocation(one_doc.doc_location,searchLocation))\n\t\t\t{\n\t\t\t\tdid++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t//cout<<\"doc_id:\"<<did<<\"url:\"<<one_doc.doc_name<<\" file: \"<<one_doc.file_id<<\" offset:\"<<one_doc.offset<<\" len:\"<<one_doc.len<<endl;\n\t\t\tint target_pos = getPos(p[0]);\n\t\t\tfor( int k = 0 ; k<p.size(); k++)\n\t\t\t{\n\t\t\t \tint freq= getFreq(p[k]);\n\n\t\t\t \tint ft=p[k]->doc_num;\n\t\t\t \t\n\t\t\t \tif(one_doc.doc_name == \"\")\n\t\t\t \t\tcontinue;\n\t\t\t \t//cout<<\"doc_id:\"<<did<<\"url:\"<<one_doc.doc_name<<\" file: \"<<one_doc.file_id<<\" offset:\"<<one_doc.offset<<\" len:\"<<one_doc.len<<endl;\n\t\t\t \t//cout<<\"req:\"<<freq<<\" ft:\"<<ft<<endl;\n\t\t\t \t//comput bm25\n\t\t\t \tfloat K = (float)k1 * (float)((1-b) + b* ((float)one_doc.len / (float)d_agv ) );\n\t\t\t \tfloat bm25 = log ( (float)(N-ft+0.5)/(float)(ft+0.5) ) * ((k1 + 1)*(float)freq)/(float)(K + freq);\n\t\t\t \t//cout<<\"bm25:\"<<bm25<<endl;\n\t\t\t \tbm25_all+=bm25;\n\t \t\t}\n\t \t\tbool change_data = false;\n\t\t \tif(result_count < 10)\n\t\t \t{\n\t\t \t\t\n\t\t\t\tresult_array[result_count]._url =one_doc.doc_url;\n\t\t\t\tresult_array[result_count]._title =one_doc.doc_title;\n\t\t\t\t//cout<<one_doc.doc_url<<endl;\n\n\t\t\t\tresult_array[result_count]._bm25=bm25_all;\n\t\t\t\tresult_array[result_count]._doc_id = did;\n\t\t\t\tresult_array[result_count]._pos = target_pos;\n\t\t\t\tresult_array[result_count]._time = one_doc.doc_time;\n\t\t\t\tresult_array[result_count]._location = one_doc.doc_location;\n \t\t\n\t\t \t\tresult_count++;\n\t\t \t}\n\t\t \telse if(searchType == \"time_new\")\n\t\t \t{\n\t\t \t\tif( one_doc.doc_time > result_array[0]._time && one_doc.doc_time<20070701 )\n\t\t \t\t{\n\t\t \t\t\tchange_data = true;\n\t\t \t\t}\n\t\t \t}\n\t\t \telse if(searchType == \"time_old\")\n\t\t \t{\n\t\t \t\tif( one_doc.doc_time < result_array[0]._time)\n\t\t \t\t{\n\t\t \t\t\tchange_data = true;\n\t\t \t\t}\n\t\t \t}\n\t\t \telse if(bm25_all > result_array[0]._bm25)\n\t\t \t{\n\t\t\t\tchange_data = true;\n\t\t \t}\n\n\t\t \tif( change_data == true)\n\t\t \t{\n\t\t \t\tresult_array[0]._url =one_doc.doc_url;\n\t\t\t\tresult_array[0]._title =one_doc.doc_title;\n\t\t\t\tresult_array[0]._bm25=bm25_all;\n\t\t\t\tresult_array[0]._doc_id = did;\n\t\t\t\tresult_array[0]._pos = target_pos;\n\t\t\t\tresult_array[0]._time = one_doc.doc_time;\n\t\t\t\tresult_array[0]._location = one_doc.doc_location;\n\t\t \t}\n\n\t\t \t//cout<<\"new bm25:\"<<bm25_all<<\" time: \"<<one_doc.doc_time<<\" 0:\"<<result_array[0]._bm25<<endl;\n\n\t \t\tsort(result_array,0,result_count-1,searchType);\n\t \t\t//cout<<\"after sort bm25:\"<<bm25_all<<\" time\"<<one_doc.doc_time<<\" 0:\"<<result_array[0]._bm25<<endl;\n\t \t}\n\t \t//cout<<\"list:\";\n\t \t//for(int j =0; j < result_count; j++)\n\t \t//\tcout<<\"[\"<<j<<\"] \"<<result_array[j]._bm25<<endl;\n\n\t\tdid++;\n\t}\n\t gettimeofday(&end, NULL);\n\t_searching_time = (end.tv_sec - start.tv_sec)*1000+ (end.tv_usec - start.tv_usec)/1000.0;\n\n\t// cout<<\"start to :get around text\"<<endl;\n\t// //around text\n\t// for(int i =0; i < result_count;i++)\n\t// {\n\t// \tcout<<\"get around text. doc id:\"<<result_array[i]._doc_id<<endl;\n\t// \tSTRU_DOC one_doc = _doc_map[result_array[i]._doc_id];\n\t// \tchar filename[20];\n\t// \tsprintf(filename,\"dataset/%d_data\",one_doc.file_id);\n\t// \tint already_len = 0;\n\t// \tchar* index_data = gzip::uncompress_from_file(filename, INDEX_CHUNK, already_len);\n // if( index_data == NULL || already_len == 0)\n // {\n // cout<<\"read index data error: \"<<filename<<endl;\n // continue;\n // }\n // char* html = new char[already_len];\n // memcpy(html,index_data+one_doc.offset,one_doc.len);\n // char *pool;\n\n // pool = (char*)malloc(2*one_doc.len+1);\n \n\n // int ret = parser((char*)one_doc.doc_name.c_str(), html , pool, 2*one_doc.len+1);\n \n \t\n // \t\tcout<<\"aound text:\"<<request_list[0]<<endl;\n\n // get_around_text(pool,already_len,result_array[i]._pos,result_array[i]._title,result_array[i]._round_text );\n // //\tcout<<\"\taound:\"<<result_array[i]._round_text<<\" title:\"<<result_array[i]._title<<endl;\n\n // \tfree(pool);\n // \tdelete[] html;\n // // cout<<html<<endl;\n\n\t// //\tresult_array[result_count]._round_text=;\n\t// }\n\n\tfor(int i =0 ;i <p.size();i++)\n\t\tcloseList(p[i]);\n\tgettimeofday(&end, NULL);\n\t_whole_time = (end.tv_sec - start.tv_sec)*1000+ (end.tv_usec - start.tv_usec)/1000.0;\n\t//cout<<\"end.tv_sec:\"<<end.tv_sec<<\" start.tv_sec:\"<<start.tv_sec<<\" end.tv_usec:\"<<end.tv_usec<<\" start.tv_usec:\"<<start.tv_usec<<endl;\n\tcout<<\"-Time Use- \"<<\" all(searching+surrounding text):\"<<_whole_time<<\"(ms), just searching:\"<<_searching_time<<\"(ms)\"<<endl;\n\tcout<<\"finsh searching\"<<endl;\n\tcout<<\"-------------------\"<<endl;\n}\nvoid SearchingAlgorim::get_around_text(char* html, int len,int tartget_pos,string& title, string& around_text)\n{\n\taround_text=\"\";\n\ttitle = \"\";\n int pos = 0;\n int offset_val =0;\n int start_colletion = 0;\n\n cout<<\"target_pos:\"<<tartget_pos<<endl;\n if(tartget_pos > 10)\n \tstart_colletion = tartget_pos-7;\n int end_colletion = start_colletion +15;\n\n int pos_count = 0;\n // cout<<\"[-\"<<percent<<\"\\%-][doc:\"<<doc_id<<\"]\"<<endl;\n while(pos < len )\n {\n string word=\"\";\n string context=\"\";\n string positon=\"\";\n\n if(\n !get_one_word(html , pos, word) ||\n !get_one_word(html , pos, positon) ||\n !get_one_word(html , pos, context)\n )\n break;\n\n //cout<<\"[\"<<pos<<\"]\"<<\"word=>\"<<word<<\" pos=>\"<<positon<<\" context=>\"<<context<<endl ;\n \n if(pos_count >= start_colletion && pos_count <= end_colletion)\n {\n \t//cout<<word<<\" \"<<context<<endl;\n \tif(around_text==\"\")\n \t\taround_text+=word;\n \telse\n \t\taround_text+=\" \"+word;\n \t\n }\n if(context==\"T\")\n {\n \tif(title==\"\")\n \t\ttitle+=word;\n \telse\n \t\ttitle+=\" \"+word;\n }\n\n pos_count++;//atoi(positon.c_str()); //atoi(positon.c_str());\n \n }\n\n // cout<<\"title\"<<title<<endl;\n //cout<<pos<<\"--------------------------------\"<<endl<<endl<<endl<<endl<<endl;\n\n \n\t\n}\nvoid SearchingAlgorim::sort(STRU_RESULT* arr, int left , int right,string type)\n{\n\tif(arr == NULL)\n\t\treturn;\n\tfloat pivot = 0.0;\n\tint piv_day = 0;\n\tif( type == \"time_new\")\n\t{\n\t\tpiv_day = arr[(left+right)/2]._time;\n\t}\n\telse if( type == \"time_old\")\n\t{\n\t\tpiv_day = arr[(left+right)/2]._time;\n\t}\n\telse\n\t{\n\t\tpivot = arr[(left+right)/2]._bm25;\n\t}\n\tint i = left, j=right;\n\n\t//partition\n\twhile(i <= j)\n\t{\n\t\tif( type == \"time_new\")\n\t\t{\n\t\t\t//cout<<\"time:\"<<arr[i]._time<<\" pivot:\"<<piv_day<<endl;\n\t\t\twhile(arr[i]._time < piv_day)\n\t\t\t\ti++;\n\t\t\twhile(arr[j]._time > piv_day)\n\t\t\t\tj--;\n\t\t}\n\t\telse if( type == \"time_old\")\n\t\t{\n\t\t\twhile(arr[i]._time > piv_day)\n\t\t\t\ti++;\n\t\t\twhile(arr[j]._time < piv_day)\n\t\t\t\tj--;\n\t\t}\n\t\telse\n\t\t{\n\t\t\twhile(arr[i]._bm25 < pivot)\n\t\t\t\ti++;\n\t\t\twhile(arr[j]._bm25 > pivot)\n\t\t\t\tj--;\n\t\t}\n\t\tif(i <= j)\n\t\t{\n\t\t\tSTRU_RESULT tmp = arr[i];\n\t\t\tarr[i] = arr[j];\n\t\t\tarr[j] = tmp;\n\t\t\ti++;\n\t\t\tj--;\n\t\t}\n\t}\n\tif( j > left)\n\t\tsort(arr, left ,j,type);\n\tif( i < right)\n\t\tsort(arr, i , right,type);\n}\nchar* SearchingAlgorim::get_result()\n{\n\n\tif(result_count ==0)\n\t\treturn \"\";\n\t\n\tint offset = 0;\n\tfor(int i = result_count-1; i >=0; i --)\n\t{\n\t\tsprintf(result+offset,\"%s\\n\",result_array[i]._url.c_str());\n\t\toffset+=strlen(result+offset);\n\t\tsprintf(result+offset,\"%f\\n\",result_array[i]._bm25);\n\t\toffset+=strlen(result+offset);\n\t\tsprintf(result+offset,\"%d\\n\",result_array[i]._time);\n\t\toffset+=strlen(result+offset);\n\t\tsprintf(result+offset,\"%s\\n\",result_array[i]._title.c_str());\n\t\toffset+=strlen(result+offset);\n\t\tsprintf(result+offset,\"%s\\n\",result_array[i]._location.c_str());\n\t\toffset+=strlen(result+offset);\n\n\t}\n\t//cout<<result<<endl;\n\treturn result;\n}\nbool SearchingAlgorim::get_one_word(char* source ,int& pos,string& str)\n{\n\n\n char get_num = 0;\n while( source[pos] != '\\0')\n {\n\n if(source[pos] == '\\r' || source[pos]=='\\n' || source[pos] == ' ')\n {\n \n if( get_num == 0)\n {\n pos++;\n\n continue;\n }\n else\n {\n pos++;\n return true;\n }\n }\n else \n {\n str+=source[pos++];\n get_num++;\n //cout<<str.c_str()<<endl;\n }\n }\n if( source[pos] == '\\0' && get_num>0)\n {\n \treturn true; \n }\n return false;\n}\n\nbool SearchingAlgorim::isInThisLocation(string askLocation,string sourceLocation)\n{\n\tif(sourceLocation == \"NULL\")\n\t\treturn true;\n\tif(askLocation == sourceLocation)\n\t\treturn true;\n\treturn false;\n}\n\n\n// char filename[20];\n// \t \tsprintf(filename,\"dataset/%d_data\",one_doc.file_id);\n// \t \tint already_len = 0;\n// \t \tchar* index_data = gzip::uncompress_from_file(filename, INDEX_CHUNK, already_len);\n// if( index_data == NULL || already_len == 0)\n// {\n// cout<<\"read index data error: \"<<filename<<endl;\n// continue;\n// }\n// char* html = new char[already_len];\n// memcpy(html,index_data+one_doc.offset,one_doc.len);\n// cout<<html<<endl;\n\n// float SearchingAlgorim::BM25( int doc_id )\n// {\n\n// }\n\n" }, { "alpha_fraction": 0.5505154728889465, "alphanum_fraction": 0.5505154728889465, "avg_line_length": 10.853658676147461, "blob_id": "6f1d219244ddc9faca3d70e85f2f36ed1488eb35", "content_id": "f4f07f9fef8cac8628726b1df6e2b917501b0d31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 485, "license_type": "no_license", "max_line_length": 27, "num_lines": 41, "path": "/newyorktimes/src/include/utility/factory_model.h", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "/*Author: derrick*/\n#ifndef VI_FACTORY_MODEL_H\n#define VI_FACTORY_MODEL_H\n\n\n//////////////\n//declaration \n//////////////\ntemplate < class T >\nclass factory\n{\nprivate:\n\tfactory(){}\n\t~factory(){}\npublic:\n\tstatic T* instance();\nprivate:\n\tstatic T* _obj;\n};\n\n/////////////\n//definition\n/////////////\ntemplate < class T >\nT* factory<T>::_obj = NULL;\n\ntemplate < class T >\nT* factory<T>::instance()\n{\n\tif( _obj == NULL )\n\t{\n\t\t_obj = new T;\n\t}\n\n\treturn _obj;\n}\n\n\n\n\n#endif //VI_FACTORY_MODEL_H" }, { "alpha_fraction": 0.6032944321632385, "alphanum_fraction": 0.61015784740448, "avg_line_length": 20.761194229125977, "blob_id": "bb011a330d1b4d597eb1c391e4037d9decac1ca4", "content_id": "fe7f909541e56cc81ecb6b4d571fb30bd23404ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1457, "license_type": "no_license", "max_line_length": 77, "num_lines": 67, "path": "/crawling/models/configuration.py", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "\"\"\"\nCreated on Feb 13, 2013\n\n@author: derrick\n\n\"\"\"\n\nfrom include.setting import Setting\nfrom include.log import Log\n\nclass Configuration(object):\n\tdef __init__(self):\n\n\t\tself._setting = Setting()\n\t\n\t\t#[Downloader]\n\t\tself._down_num \t\t= 0\n\t\tself._down_path \t= \"\"\n\n\t\t#[Parser]\n\t\tself._parser_num \t= 0\n\t\tself._parser_nlv \t= 0\n\n\t\t#[seed]\n\t\tself._keywords \t\t= \"\"\n\t\tself._result_num \t= 0\n\n\n\t\t#[Mysql]\n\t\tself._host \t\t\t= \"\"\n\t\tself._user \t\t= \"\"\n\t\tself._passwd \t\t= \"\"\n\t\tself._db \t\t\t= \"\"\n\t\n\t\tself.load()\n\n\t\"\"\"load all configuration from files or remote mysql\"\"\"\n\tdef load(self):\n\t\ttry:\n\t\t\t\n\t\t\tself._setting.load(\"config.ini\")\n\n\t\t\t#[Downloader]\n\t\t\tself._down_num \t= int( self._setting.get_param(\"Downloader\",\"Threadnum\") )\n\t\t\tself._down_path\t= self._setting.get_param(\"Downloader\",\"SavePath\")\n\n\t\t\t#[Parser]\n\t\t\tself._parser_num \t= int(self._setting.get_param(\"Parser\",\"Threadnum\"))\n\t\t\tself._parser_nlv \t= int(self._setting.get_param(\"Parser\",\"Nestlevel\"))\n\n\t\t\t#[seed]\n\t\t\tself._keywords \t\t= self._setting.get_param(\"seed\",\"keywords\")\n\t\t\tself._result_num \t= int(self._setting.get_param(\"seed\",\"result_num\"))\n\n\t\t\t#[Mysql]\n\t\t\tself._host \t\t= self._setting.get_param(\"Mysql\",\"host\")\n\t\t\tself._user \t= self._setting.get_param(\"Mysql\",\"user\")\n\t\t\tself._passwd \t= self._setting.get_param(\"Mysql\",\"passwd\")\n\t\t\tself._db \t\t= self._setting.get_param(\"Mysql\",\"db\")\n\n\n\t\texcept (Exception) as e:\n\t\t\tLog().debug(\"load config fail\")\n\t\t\traise(e)\n\t\t\treturn False\n \n\t\treturn True;" }, { "alpha_fraction": 0.6269437670707703, "alphanum_fraction": 0.645836353302002, "avg_line_length": 33.06435775756836, "blob_id": "eace706bc081002ffc1a891c3bf2b13c837f458b", "content_id": "dcbef5e064751ae9504620db7b3ccc155b9f4178", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6881, "license_type": "no_license", "max_line_length": 376, "num_lines": 202, "path": "/indexing/src/searching/4ops.h", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "/*\n * 4ops.h\n *\n * Created on: Mar 24, 2013\n * Author: Adam57\n */\n\n/**/\n#include \"Lp.h\"\n#include \"vbyte.h\"\nusing namespace std;\n\ninline Lp* openList(int wordid){\n Lp* mylp = new Lp;\n chunk mychunk;\n mylp->word_id = wordid;\n mylp->doc_num = word_index[wordid].doc_num;\n mylp->start_chunk = word_index[wordid].chunk_num;\n mylp->start_posting_num = word_index[wordid].posting_num;\n mylp->end_posting_num = word_index[wordid+1].posting_num-1;\n mylp->cur_posting_docid = mylp->start_posting_num;\n mylp->num_of_chunks = word_index[wordid+1].chunk_num - word_index[wordid].chunk_num+1;\n int chunk_num = word_index[wordid].chunk_num;\n for (int i=0;i<mylp->num_of_chunks;i++){\n\t mychunk.chunk_last_docid = chunk_index[chunk_num+i].chunk_last_docid;\n\t mychunk.chunk_last_wordid = chunk_index[chunk_num+i].chunk_last_wordid;\n\t mychunk.filenum = chunk_index[chunk_num+i].filenum;\n\t mychunk.offset = chunk_index[chunk_num+i].offset;\n\t mylp->chunkvector.push_back(mychunk);\n }\n cout<<\"word_id: \"<<mylp->word_id<<endl;\n cout<<\"doc_num: \"<<mylp->doc_num<<endl;\n cout<<\"start_chunk: \"<<mylp->start_chunk<<endl;\n cout<<\"start_posting_num: \"<<mylp->start_posting_num<<endl;\n cout<<\"end_posting_num: \"<<mylp->end_posting_num<<endl;\n cout<<\"cur_posting: \"<<mylp->cur_posting_docid<<endl;\n cout<<\"num_of_chunks: \"<<mylp->num_of_chunks<<endl;\n cout<<\"size of chunkvector: \"<<mylp->chunkvector.size()<<endl;\n // for(int s = 0; s<mylp->chunkvector.size(); s++){\n // cout<<\"chunk_id: \"<<mylp->start_chunk+s<<\" chunk_last_wordid: \"<<mylp->chunkvector.at(s).chunk_last_wordid<<\" chunk_last_docid: \"<<mylp->chunkvector.at(s).chunk_last_docid<<\" filenum: \"<<mylp->chunkvector.at(s).filenum<<\" offset: \"<<mylp->chunkvector.at(s).offset<< \" chunk_size: \"<<chunk_index[mylp->start_chunk+s+1].offset-chunk_index[mylp->start_chunk+s].offset<<endl;\n //}\n return mylp;\n}\n\ninline void closeList(Lp* mylp){\n\tdelete mylp;\n}\n\ninline int nextGEQ(Lp* mylp, int search_docid){\n\tint docid = 0;\n\tint start_chunk_num;\n\tint start_posting_num = 1;\n\tint end_posting_num = 128;\n\tint posting_num = 1;\n\tint filenum;\n\tint offset;\n\tint i;\n\tint chunk_size;\n\tint total_len = 0;\n\tint len = 0;\n\tint n;\n\tint test;\n\tunsigned int res1;\n\tunsigned int res2;\n\tunsigned int res3;\n\tunsigned int* res_arr;\n\tint last_docid = 0;\n\tstring file=\"result/\";\n\tchar filename[50]={0};\n\tchar* chunk;\n\tunsigned char* uchunk;\n\n\tstart_chunk_num = mylp->start_chunk;\n\n\tfor (i=0; i< mylp->num_of_chunks-1;i++){\n\t\tif(mylp->chunkvector.at(i).chunk_last_docid>=search_docid){\n\t\t\tstart_chunk_num = mylp->start_chunk + i;\n\t\t\tbreak;\n\t\t}\n\t\tend_posting_num = mylp->end_posting_num+1;\n\t}\n\t\tstart_chunk_num = mylp->start_chunk + i;\n\n\t\tif(i==0)\n\t\tstart_posting_num = mylp->start_posting_num+1;\n\n\t\t//cout<<\"start_chunk_num: \"<<start_chunk_num<<endl;\n\n\t\tif(chunk_index[start_chunk_num].filenum == chunk_index[start_chunk_num+1].filenum){\n\t\t\t//cout<<\"chunk didn't cross file\"<<endl;\n\t\t\tchunk_size = chunk_index[start_chunk_num+1].offset - chunk_index[start_chunk_num].offset;\n\t\t\tchunk = new char[chunk_size];\n\t\t\tuchunk = new unsigned char[chunk_size];\n\t\t\tsprintf (filename, \"data%d\", chunk_index[start_chunk_num].filenum);\n\t\t\tfile = file + filename;\n\t\t\tifstream myFile (file.c_str(), ios::in | ios::binary);\n\t\t\tmyFile.seekg(chunk_index[start_chunk_num].offset, ios::beg);\n\t\t\tmyFile.read(chunk,chunk_size);\n\t\t\tmemcpy(uchunk, chunk, chunk_size);\n\t\t}\n\n\t\tif(chunk_index[start_chunk_num].filenum < chunk_index[start_chunk_num+1].filenum){\n\t\t\tint num_of_files = chunk_index[start_chunk_num+1].filenum - chunk_index[start_chunk_num].filenum-1;\n\t\t\tchunk_size = (1200000 - chunk_index[start_chunk_num].offset) + chunk_index[start_chunk_num+1].offset + 1200000*num_of_files;\n\t\t\tchunk = new char[chunk_size];\n\t\t\tuchunk = new unsigned char[chunk_size];\n\t\t\tsprintf (filename, \"data%d\", chunk_index[start_chunk_num].filenum);\n\t\t\tfile = file + filename;\n\t\t\tifstream myFile1 (file.c_str(), ios::in | ios::binary);\n\t\t\tmyFile1.seekg(chunk_index[start_chunk_num].offset, ios::beg);\n\t\t\tmyFile1.read(chunk,1200000 - chunk_index[start_chunk_num].offset);\n\t\t\tfile = \"result/\";\n\t\t\tint chunk_offset = 1200000 - chunk_index[start_chunk_num].offset;\n\n\t\t\tfor(int k=0; k<num_of_files; k++){\n\t\t\t\tsprintf (filename, \"data%d\", chunk_index[start_chunk_num].filenum+1+k);\n\t\t\t\tfile = file + filename;\n\t\t\t\tifstream myFile2 (file.c_str(), ios::in | ios::binary);\n\t\t\t\tmyFile2.read(chunk+chunk_offset,1200000);\n\t\t\t\tchunk_offset = chunk_offset + 1200000;\n\t\t\t\tfile = \"result/\";\n\t\t\t}\n\n\t\t\tsprintf (filename, \"data%d\", chunk_index[start_chunk_num+1].filenum);\n\t\t\tfile = file + filename;\n\t\t\tifstream myFile3 (file.c_str(), ios::in | ios::binary);\n\t\t\tmyFile3.read(chunk+chunk_offset,chunk_index[start_chunk_num+1].offset);\n\t\t\tchunk_offset = chunk_offset + chunk_index[start_chunk_num+1].offset;\n\t\t\tfile = \"result/\";\n\t\t\tmemcpy(uchunk, chunk, chunk_size);\n\t\t}\n\n\t\t//cout<<\"start_posting_num: \"<<start_posting_num<<endl;\n\t\t//cin>>test;\n\n\t\twhile(posting_num<=128){\n\t\t if(posting_num<start_posting_num){\n\t\t len = readVbyte(uchunk+total_len, res1);\n\t\t total_len = total_len + len;\n\t\t //cout<<\"docid diff: \"<<res1<<endl;\n\t\t len = readVbyte(uchunk+total_len, res2);\n\t\t total_len = total_len + len;\n//\t\t cout<<\"freq: \"<<res2<<endl;\n\n\t\t for(int h = 0; h<res2; h++){\n\t\t\t len = readVbyte(uchunk+total_len, res3);\n\t\t\t total_len = total_len + len;\n//\t\t\t cout<<\"pos diff: \"<<res3<<endl;\n\t\t }\n\t\t // cout<<\"total_len: \"<<total_len<<endl;\n\t\t }\n\n\t\t if(posting_num>=start_posting_num){\n\t\t\t// cout<<\"when posting_num equals start_posting_num\"<<endl;\n\t\t\t len = readVbyte(uchunk+total_len, res1);\n\t\t\t //cout<<\"total_len: \"<<total_len<<endl;\n\t\t\t total_len = total_len + len;\n\t\t\t //cout<<\"total_len: \"<<total_len<<endl;\n\t\t\t //cout<<\"res1: \"<<res1<<endl;\n\t\t\t last_docid = last_docid + res1;\n\t\t\t //cout<<\"docid: \"<<last_docid<<endl;\n\t\t\t len = readVbyte(uchunk+total_len, res2);\n\t\t\t total_len = total_len + len;\n\t\t\t //cout<<\"freq: \"<<res2<<endl;\n\n\n\t\t\t if (last_docid>=search_docid){\n\t\t\t\t mylp->cur_posting_docid = last_docid;\n\t\t\t\t mylp->cur_posting_freq = res2;\n\t\t\t\t len = readVbyte(uchunk+total_len, res3);\n\t\t\t\t total_len = total_len + len;\n\t\t\t\t mylp->cur_first_pos = res3;\n\t\t\t\t return mylp->cur_posting_docid;\n\t\t\t }\n\n\t\t\t for(int h = 0; h<res2; h++){\n\t\t\t \tlen = readVbyte(uchunk+total_len, res3);\n\t\t\t \ttotal_len = total_len + len;\n\t\t\t \t//cout<<\"pos diff: \"<<res3<<endl;\n\t\t\t }\n\n\t\t}\n//\t\t res_arr = new unsigned int[res2];\n\t\t// cout<<\"posting_num: \"<<posting_num<<endl;\n\t\t posting_num++;\n\t }\n\n//\tfilenum = chunk_index[start_chunk_num].filenum;\n//\toffset = chunk_index[start_chunk_num].offset;\n//\tcout<<\"start_chunk_num: \"<<start_chunk_num<<\" filenum: \"<<filenum<<\" offset: \"<<offset<<\" chunk_size: \"<<chunk_size<<endl;\n//\treturn docid;\n\n\t\treturn 100000000;\n}\n\ninline int getFreq(Lp* mylp){\n return mylp->cur_posting_freq;\n}\n\ninline int getPos(Lp* mylp){\n\t return mylp->cur_first_pos;\n}\n" }, { "alpha_fraction": 0.5574193596839905, "alphanum_fraction": 0.5664516091346741, "avg_line_length": 35.92856979370117, "blob_id": "a2466c8b4aacea23763d9f083c6477bcd1e8d783", "content_id": "ba8b240796a74874b63b8682c0b2e5ec7e69cbb3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1550, "license_type": "no_license", "max_line_length": 79, "num_lines": 42, "path": "/crawling/strategies/robothandler.py", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "'''\nCreated on Feb 12, 2013\n\n@author: Adam57\n'''\nfrom models.safe_dic import SafeDictionary\nfrom strategies.robotexclusionrulesparser import RobotExclusionRulesParser\nimport socket\n\nclass RobotHandler(object):\n \n def __init__(self):\n self._hostname_pool = SafeDictionary()\n self._user_agent = \"Mozilla/5.0\"\n \n def check_hostname(self, html_task):\n if (self._hostname_pool.has_key(html_task._homesiteurl)==True):\n return True\n else: \n return False\n def is_allowed(self,html_task):\n try:\n timeout = 2\n socket.setdefaulttimeout(timeout)\n \n rerp = RobotExclusionRulesParser()\n if (self.check_hostname(html_task) == False):\n # print (\"home_site for Robot\", html_task._homesiteurl)\n #print html_task._url\n #print \"fecth: robots:\"+ html_task._homesiteurl + \"/robots.txt\"\n rerp.fetch(html_task._homesiteurl + \"/robots.txt\", 2)\n self._hostname_pool.addorupdate(html_task._homesiteurl,rerp) \n #print \"finish fecth\"\n else:\n #print \"in is_allowed1\"+html_task._homesiteurl\n rerp = self._hostname_pool.valueofkey(html_task._homesiteurl)\n # print \"in is_allowed 2\" \n return rerp.is_allowed(self._user_agent, html_task._url) \n #return rerp.is_allowed(html_task._url) \n except Exception as e:\n # print e\n return True" }, { "alpha_fraction": 0.5633803009986877, "alphanum_fraction": 0.6009389758110046, "avg_line_length": 11.470588684082031, "blob_id": "faf99fe97817785db5d17669b9c76c7f42f3c558", "content_id": "d2237817888cf878f5ae88332c9bea48a534b6f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 213, "license_type": "no_license", "max_line_length": 40, "num_lines": 17, "path": "/indexing/src/include/models/Heap.cpp", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "/*\n * Heap.cpp\n *\n * Created on: Feb 25, 2013\n * Author: Adam57\n */\n\n#include \"Heap.h\"\n\nHeap::Heap() {\n\t// TODO Auto-generated constructor stub\n\n}\n\nHeap::~Heap() {\n\t// TODO Auto-generated destructor stub\n}\n\n" }, { "alpha_fraction": 0.6902173757553101, "alphanum_fraction": 0.7010869383811951, "avg_line_length": 18.891891479492188, "blob_id": "a7e0ba9ebf821d2b7b137075fd32aaa97c53aa6c", "content_id": "75d30bda6d0740153f09cb0d8d95d331c86c0aa4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 736, "license_type": "no_license", "max_line_length": 66, "num_lines": 37, "path": "/indexing/src/include/models/URLTable.h", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "/*\n * URLTable.h\n *\n * Created on: Feb 25, 2013\n * Author: Adam57\n */\n\n#ifndef URLTABLE_H_\n#define URLTABLE_H_\n#include <map>\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <string>\n#include <fstream>\n#include <cstring>\n#include \"StreamBuffer.h\"\nusing namespace std;\n\nclass URLTable {\n\nprivate:\n\tmap<int, string> map;\n\npublic:\n\tURLTable();\n\tvirtual ~URLTable();\n\tvoid \taddentry(int doc_id, string url);\n\tvoid \tserialize( StreamBuffer &stream);\n\tvoid \tdeserialize( StreamBuffer &stream);\n\tfriend StreamBuffer& operator<<(StreamBuffer &stream, URLTable&);\n\tfriend StreamBuffer& operator>>(StreamBuffer &stream, URLTable&);\n\tfriend ostream&\t operator<<(ostream &stream, URLTable&);\n\n};\n\n#endif /* URLTABLE_H_ */\n" }, { "alpha_fraction": 0.6556962132453918, "alphanum_fraction": 0.6582278609275818, "avg_line_length": 15.479166984558105, "blob_id": "9eb333087e8af2c00382ee5d0a355ba3c908e5c5", "content_id": "a1e3709d777449719eb888b2db188c10e3a9e110", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 790, "license_type": "no_license", "max_line_length": 68, "num_lines": 48, "path": "/newyorktimes/src/include/utility/display.h", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "/*Author: derrick*/\n#ifndef D_DISPLAY_H\n#define D_DISPLAY_H\n\n#include \"system_ex.h\"\n#include <string>\n#include <map>\n\nclass d_key_event\n{\npublic:\n\tvirtual void input_event( char* key ) = 0;\n};\n\n\nclass display\n{\n\nprivate:\n\tdisplay();\n\t~display();\npublic:\n\tstatic display* get_instance();\n\tvoid run();\n\tvoid set_input_call_back(d_key_event* p_call_back , int type = 0 );\n\tvoid stop();\nprivate:\n\tstatic void show(void*);\n\tvoid show();\n\tvoid title();\n\tvoid body();\n\tvoid command();\n\tvoid reg_commond(char* com_name , char* describe);\npublic:\n\tstd::string _progrma;\n\tstd::string _version;\n\tstd::string _extern;\nprivate:\n\tbool\t\t\t\t_state;\n\tint\t\t\t\t\t_call_back_type;\n\tstatic display*\t\t_this;\n\td_key_event*\t\t_p_call_back;\t\n\tstd::map<std::string , std::string> _commond_all;\n\n};\n\n\n#endif //D_DISPLAY_H" }, { "alpha_fraction": 0.49938470125198364, "alphanum_fraction": 0.51070636510849, "avg_line_length": 36.45161437988281, "blob_id": "808d4be8300805a40fc39209d419d92c465e24eb", "content_id": "a7a537faaaa9a97a5906858a6239c8be2bf21bf1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 8126, "license_type": "no_license", "max_line_length": 201, "num_lines": 217, "path": "/newyorktimes/interface/template/header.php", "repo_name": "derrick0714/web_search_engine", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>WSE Final Project</title>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n <meta name=\"robots\" content=\"noarchive\">\n <meta name=\"CG\" content=\"Search\">\n <meta name=\"SCG\" content=\"cse\">\n <meta name=\"PT\" content=\"Search\">\n <meta name=\"PST\" content=\"Search Results\">\n <meta name=\"PSST\" content=\"\">\n <meta name=\"PS\" content=\"\">\n <meta name=\"ttl\" content=\"\">\n \n \n <link rel=\"stylesheet\" type=\"text/css\" href=\"http://graphics8.nytimes.com/css/0.1/screen/build/search/styles.css\" />\n <script type=\"text/javascript\" src=\"http://js.nyt.com/js/app/lib/jquery/jquery-1.6.2.min.js\"></script>\n <script type=\"text/javascript\" src=\"http://js.nyt.com/js/app/lib/jquery/jquery-ui-1.8.16.min.js\"></script>\n <meta name=\"viewport\" content=\"initial-scale=1.0, user-scalable=no\">\n <meta charset=\"utf-8\">\n <title>Region code biasing (US)</title>\n <script src=\"https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false\"></script>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"css/mystyle.css\" />\n <script>\nvar geocoder;\nvar map;\nvar query = 'New York';\nfunction initialize() {\n geocoder = new google.maps.Geocoder();\n var mapOptions = {\n zoom: 8,\n mapTypeId: google.maps.MapTypeId.ROADMAP\n }\n map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);\n codeAddress();\n}\n\nfunction codeAddress() {\n var address = query;\n geocoder.geocode( { 'address': address}, function(results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n map.setCenter(results[0].geometry.location);\n var marker = new google.maps.Marker({\n map: map,\n position: results[0].geometry.location\n });\n } else {\n alert('Geocode was not successful for the following reason: ' + status);\n }\n });\n}\n\ngoogle.maps.event.addDomListener(window, 'load', initialize);\n\n </script>\n\n <!--[if IE]>\n <style type=\"text/css\">\n @import url(http://graphics8.nytimes.com/css/0.1/screen/common/ie.css);\n </style>\n <![endif]-->\n <!--[if IE 6]>\n <style type=\"text/css\">\n @import url(http://graphics8.nytimes.com/css/0.1/screen/common/ie6.css);\n </style>\n <![endif]-->\n <!--[if lt IE 9]>\n <script src=\"http://graphics8.nytimes.com/js/html5shiv.js\"></script>\n <![endif]-->\n </head>\n <body>\n \n <a name=\"top\"></a>\n <div id=\"shell\">\n <div id=\"page\" class=\"tabContent active\">\n <div id=\"masthead\" class=\"clearfix\">\n <div id=\"branding\">\n <a href=\"http://www.nytimes.com\"><img id=\"NYTLogo\" alt=\"New York Times\" src=\"http://graphics8.nytimes.com/images/misc/nytlogo152x23.gif\"></a>\n </div>\n <h2> <a href=\"/\">Final Project</a> </h2>\n\n <div class=\"mostPopularSearches\" id=\"mostPopularSearches\">\n <div class=\"tabDropDown\">\n <div class=\"tabDropDownHeader\">\n <div class=\"inset\">\n <h5 class=\"\"><a class=\"toggleControl\">By Xu Deng & Qi Wang</a></h5>\n </div>\n </div><!-- close tabDropDownHeader -->\n\n <div class=\"tabDropDownContent\">\n <div class=\"subColumns noBackground\">\n <div class=\"column firstColumn\">\n <div class=\"inset\"> \n <ol class=\"flush\"></ol>\n </div><!-- close inset -->\n </div><!-- close column -->\n\n <div class=\"column lastColumn\">\n <div class=\"inset\">\n <ol class=\"flush\" start=\"6\"></ol>\n </div><!-- close .inset -->\n </div><!-- close .column -->\n </div><!-- close .subColumns -->\n </div><!-- close .tabDropDownContent -->\n\n </div><!-- close .tabDropDown -->\n </div><!-- close .mostPopularSearches -->\n\n</div> <!-- close #masthead --> \n <div id=\"searchHeader\" class=\"searchHeader\">\n <div class=\"insetPadded opposingFloatControl wrap\">\n <div id=\"inlineSearchControl\" class=\"searchInputForm inlineSearchControl element1\">\n <form class=\"form-search\" action=\"query.php\" method=\"get\">\n <div class=\"control horizontalControl lastControl\">\n <div class=\"labelContainer\">\n <label for=\"newSearchQueryTop\">Your Search</label>\n </div>\n <div class=\"fieldContainer containingBlock\" id=\"yourSearch\">\n <input type=\"text\" value=\"<?=$_GET[\"key\"]?>\" name=\"key\" class=\"newSearchQuery autoSuggestQuery\" autocomplete=\"off\">\n <ol class=\"autoSuggestQueryResults\"></ol>\n <button class=\"button\" type=\"submit\">Go</button>\n </div>\n <div class=\"fieldContainer containingBlock\">\n <label for=\"newSearchQueryTop\">Near By</label>\n <input type=\"text\" value=\"<?=$_GET[\"location\"]?>\" name=\"location\" class=\"\" autocomplete=\"\">\n </div>\n \n </div>\n </div>\n </form>\n </div><!-- .inlineSearchControl -->\n <ul class=\"breadCrumbFilterList element1\"></ul>\n <div class=\"resetFilters element2\">\n <a data-refineby=\"resetFilters\" class=\"searchFilter\">Clear All Filters</a>\n </div>\n </div><!-- .inset -->\n</div><!-- .searchHeader -->\n \n <div id=\"main\">\n \n <div class=\"spanAB wrap\">\n <div class=\"search \">\n <div class=\"abColumn\"><!-- open abColumn -->\n <div class=\"aColumn\"><!-- open aColumn -->\n \n\n <!--cur: prev:-->\n <div class=\"columnGroup first\">\n \n <div class=\"columnGroup firstColumn dateFilters\">\n <h2>Tag Cloud:<h2>\n <h2>world</h2>\n <h6>against</h6>\n \n\n <h3>today</h3>\n \n\n<h6>our</h6>\n<h2>back</h2>\n<h5>state</h5>\n\n\n\n<h4>both</h4>\n<h1>get<h1>\n <h6>take</h6>\n<h4>say</h4>\n<h3>5</h3>\n<h5>work</h5>\n<h3>down</h3>\n<h3>these</h3>\n<h6>week</h6>\n<h2>being</h2>\n<h6>part</h6> \n<h2>her</h2> \n<h5>under</h5> \n\n\n </div><!-- .pubTypeFilters -->\n\n \n\n <div class=\"columnGroup imageSearch\">\n <ul class=\"filterList flush\">\n <li class=\"firstItem\">\n <a href=\"http://beta620.nytimes.com/app/image-search/\"> <span></span></a>\n </li>\n </ul>\n </div> \n </div>\n </div><!-- close aColumn -->\n <div class=\"bColumn\"><!-- open bColumn -->\n \n \n <div class=\"columnGroup first\">\n \n \n <div class=\"sortContainer opposingFloatControl wrap\">\n <div class=\"sortResults element1\" id=\"sortResults\">\n <!--<h3 class=\"horizontalMenuLabel\">Sort by:</h3> -->\n <ul class=\"horizontalMenu piped\" >\n <li><a <?if($_GET[\"type\"]==\"time_new\"){?>class=\"selectedSort\"<?}?> href=\"query.php?type=time_new&key=<?=$_GET[\"key\"]?>&location=<?=$_GET[\"location\"]?>\">Newest</a></li>\n <li><a <?if($_GET[\"type\"]==\"time_old\"){?>class=\"selectedSort\"<?}?> href=\"query.php?type=time_old&key=<?=$_GET[\"key\"]?>&location=<?=$_GET[\"location\"]?>\">Oldest</a></li>\n <li><a <?if($_GET[\"type\"]!=\"time_new\"&&$_GET[\"type\"]!=\"time_old\" ){?>class=\"selectedSort\"<?}?> href=\"query.php?key=<?=$_GET[\"key\"]?>&location=<?=$_GET[\"location\"]?>\" >Relevance</a></li>\n <li><a href=\"#map-canvas\">Maps</a></li>\n </ul>\n </div>\n <div id=\"totalResultsCount\" class=\"totalResultsCount element2\">\n <p></p>\n </div>\n </div>\n\n <div class=\"textAds firstTextAds wrap\">\n <div id=\"SponSearch1\">\n </div>\n </div>" } ]
85
shmohammadi86/snSZ_backup
https://github.com/shmohammadi86/snSZ_backup
b8a2f6495c557bb6193ee929c84b0f4aeab17f62
c5c1264255bcc5fa9a32e8e59f7b3cf4cbb751ff
de10a0379c19d6edc36002337c53ecd97b50b304
refs/heads/main
2023-06-10T18:54:38.767897
2021-06-28T16:54:33
2021-06-28T16:54:33
365,610,511
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5908586382865906, "alphanum_fraction": 0.631341814994812, "avg_line_length": 26.785844802856445, "blob_id": "3fd0b541f60e642356bce08c725f8366196c9fbb", "content_id": "df90c1a75f67c2c265c45448021b2b86b9c37478", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 15315, "license_type": "no_license", "max_line_length": 251, "num_lines": 551, "path": "/ancient/Fig4_Cellstates_CMC_XGBoost.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"Assess significance and relevance of cell states/archetypes\"\noutput: html_notebook\n---\n\n# Setup\n```{r include=FALSE}\nrequire(ACTIONet)\nrequire(stringr)\nrequire(ComplexHeatmap)\n\nrequire(muscat)\nrequire(edgeR)\nrequire(limma)\n\ndataset.path = \"~/results/datasets/\"\nresults.path = \"~/results\"\nfigures.folder = \"~/results/figures\"\ninput.folder = \"~/results/input\"\n\n\n```\n\n\n```{r}\nparam_list <- list(booster = \"gbtree\",\n objective = \"binary:logistic\",\n eval_metric = \"auc\")\n```\n\n\nMain archetypes to analyze are A7 (NRGN), A11 (Ex-SZ), A17 (SZTR), and A29 (In-SZ)\n\n# Show markers\n## A11 and A29 are Mt-reach but also neuro-specific\n# Plot projection of archetypes on the ACTIONet ()\n```{r}\npb.logcounts = readr::read_rds(file.path(dataset.path, \"PB_sce_final.rds\"))\n\nACTIONet_summary = readr::read_rds(file.path(dataset.path, \"ACTIONet_summary_filtered_individuals.rds\"))\n\ncelltype.gene.spec = readr::read_rds(file.path(dataset.path, \"celltype_gene_specificity.rds\"))\narchetype.gene.spec = readr::read_rds(file.path(dataset.path, \"archetype_gene_specificity.rds\"))\n\ncolor.df = readRDS(file.path(dataset.path, \"celltype_colors.rds\"))\n\n\n\n\ncolors = color.df$color\nnames(colors) = color.df$celltype\n```\n\n\n# Load CMC data\n```{r}\nace.MPP = readr::read_rds(\"~/results/input/MPP_bulk_expression_SZandCON.rds\")\nace.HBCC = readr::read_rds(\"~/results/input/HBCC_bulk_expression_SZandCON.rds\")\n\n```\n\n\n```{r}\nace.MPP = reduce.ace(ace.MPP, assay_name = \"voom\")\nace.MPP = run.ACTIONet(ace.MPP, assay_name = \"voom\")\n\nplot.ACTIONet(ace.MPP, ace.MPP$Dx)\n\nEn = annotate.archetypes.using.labels(ace.MPP, ace.MPP$Dx)\n\nZ = En$Enrichment\nZ[abs(Z) < 3] = 0\nHeatmap(Z)\n\nCC = cor(ace.MPP$unified_feature_specificity[cg, ], arch.gene.spec[cg, ], method = \"spearman\")\nHeatmap(CC[, c(7, 11, 17, 29)]) + Heatmap(Z)\n\nHeatmap(CC)\n\n\n\npcs = irlba::prcomp_irlba(t(assays(ace.MPP)$voom))\n\nplot.ACTIONet(pcs$x, ace.MPP$Dx)\n\n\n```\n\n\n\n```{r}\narch.gene.spec = ACTIONet_summary$unified_feature_specificity\n\narch.genes = rownames(arch.gene.spec) #[which(apply(scale(as.matrix(arch.gene.spec[, c(7, 11, 17, 29)])), 1, max) > 1)]\n#arch.genes = arch.genes [-grep(\"^RPL|^RPS|^MT-|^MT[:.:]\", arch.genes)]\n\ncg = intersect(rownames(ace.MPP), arch.genes)\nsubArch = (arch.gene.spec[cg, ])\n\n\n```\n\n```{r}\ntrain.set = sample(1:ncol(ace.MPP), round(2*ncol(ace.MPP)/3))\ntest.set = setdiff(1:ncol(ace.MPP), train.set)\n\n\n\n```\n\n```{r}\narchs = c(29)\n\nS = as.matrix(scale(subArch))\n\n```\n\n# Project on archetypes (training)\n```{r}\n subBulk = assays(ace.MPP)$voom[cg, train.set]\n\n A = subBulk #scale(subBulk)\n A.ortho = orthoProject(A, fast_row_sums(A))\n \n # A_r = S %*% MASS::ginv(t(S) %*% S) %*% (t(S) %*% A.ortho)\n # training_features = Matrix::t(A_r)\n # \n \n # A.scaled = scale(apply(A, 2, function(x) x * S[, 29]))\n # training_features = Matrix::t(A.scaled)\n\n perm = order(S[, 29], decreasing = T)\n # \n # training_features = sapply(seq(100, 2000, by = 100), function(i) cor(A.ortho[perm[1:i], ], S[perm[1:i], 29]))\n # \n # training_features = t(A.ortho)\n \n training_features = cor(A.ortho, S[, archs], method = \"pearson\")\n\n training_labels = as.numeric(ace.MPP$Dx[train.set] == \"SCZ\")\n \n```\n\n# Train\n```{r}\n system.time( {model <- xgboost::xgboost(data = training_features,\n label = training_labels,\n params = param_list, nrounds = 1000, early_stopping_rounds = 10, max_depth = 10,\n verbose = FALSE, nthread = parallel::detectCores() - 2) } )\n```\n\n\n\n# Project on archetypes (test)\n```{r}\n subBulk = assays(ace.MPP)$voom[cg, test.set]\n\n A = subBulk #scale(subBulk)\n A.ortho = orthoProject(A, fast_row_sums(A))\n \n # A_r = S %*% MASS::ginv(t(S) %*% S) %*% (t(S) %*% A.ortho)\n # testing_features = Matrix::t(A_r)\n # \n \n # A.scaled = scale(apply(A, 2, function(x) x * S[, 29]))\n # testing_features = Matrix::t(A.scaled)\n\n # perm = order(S[, 29], decreasing = T)\n # \n # testing_features = sapply(seq(100, 2000, by = 100), function(i) cor(A.ortho[perm[1:i], ], S[perm[1:i], 29]))\n # \n # testing_features = t(A.ortho)\n testing_features = cor(A.ortho, S[, archs], method = \"pearson\")\n\n testing_labels = as.numeric(ace.MPP$Dx[test.set] == \"SCZ\")\n \n```\n\n\n```{r}\n xgbpred <- predict(model, testing_features)\n\n # cor(xgbpred, pstel.data.labels.NASH.filtered[mask])\n\n perf.out = PRROC::roc.curve(xgbpred, weights.class0 = testing_labels, curve = T)\n print(perf.out)\n \n \n```\n\n\n\n```{r}\nparam <- list(objective = \"multi:softprob\",\n eval_metric = \"mlogloss\",\n num_class = 12,\n max_depth = 8,\n eta = 0.05,\n gamma = 0.01, \n subsample = 0.9,\n colsample_bytree = 0.8, \n min_child_weight = 4,\n max_delta_step = 1\n )\ncv.nround = 1000\ncv.nfold = 5\nmdcv <- xgb.cv(data=dtrain, params = param, nthread=6, \n nfold=cv.nfold, nrounds=cv.nround,\n verbose = T)\n\n\n```\n\n\n```{r}\narch.genes = rownames(arch.gene.spec) # [which(apply(scale(as.matrix(arch.gene.spec[, c(7, 11, 17, 29)])), 1, max) > 3)]\n\n\nZ = scale(subArch)\nmarkers.genes = as.list(as.data.frame(apply(Z, 2, function(z) rownames(Z)[order(z, decreasing = T)[1:500]])))\n\n\nsubBulk.orth = orthoProject(subBulk, fast_row_sums(subBulk))\nX = -subBulk.orth\nX[X < 0] = 0\n\nEn = annotate.profile.using.markers(t(X), markers.genes)\nHeatmap(En$Enrichment)\n\n```\n\n\n\n```{r}\n\n\nsubBulk.orth = orthoProject(subBulk, fast_row_sums(subBulk))\n\nSZ.samples = list(SZ = ace.bulk$SampleID[which(ace.bulk$Dx == \"SCZ\")])\nrequire(fgsea)\n\nArch.cor = -cor(subBulk.orth, subArch, method = \"pearson\")\narch.enrichment = -log10(p.adjust(apply(Arch.cor, 2, function(x) {\n gsea.out = fgsea(SZ.samples, x)\n gsea.out$padj\n # perm = order(x, decreasing = T)\n # l = SZ.mask[perm]\n # mhg.out = mhg::mhg_test(l, length(l), sum(l), length(l)/4, 1, upper_bound = F, tol = 1e-300)\n # mhg.out$pvalue\n}), \"fdr\"))\n\nsort(round(arch.enrichment, 1), decreasing = T)\n\n\n# cor(Arch.cor[, \"A11\"], Arch.cor[, \"A29\"], method = \"spearman\")\n# \n# x = -(Arch.cor[, \"A11\"] + Arch.cor[, \"A29\"]) / 2\n# gsea.out = fgsea(SZ.samples, x)\n# plotEnrichment(SZ.samples$SZ, x)\n# print(gsea.out)\n\n\n# \n# \n# \n# x = Arch.cor[, \"A29\"]\n# fgsea::plotEnrichment(SZ.samples[[1]], x)\n# \n# df = data.frame(A29 = scale(Arch.cor[, \"A29\"]), A11 = scale(Arch.cor[, \"A11\"]), Phenotype = PEC.sce.matched$diagnosis, Sample = rownames(Arch.cor), x = PEC.sce.matched$ethnicity, PEC.sce.matched$ageDeath, PEC.sce.matched$sex, PEC.sce.matched$smoker)\n# df$combined = (df$A29 + df$A11)/2\n# \n# ggscatter(df, x = \"A11\", y = \"A29\",\n# add = \"reg.line\", # Add regression line\n# conf.int = TRUE, # Add confidence interval\n# color = \"Phenotype\", \n# palette = c(\"gray\", \"red\"),\n# add.params = list(color = \"blue\",\n# fill = \"lightgray\")\n# ) \n# \n# +\n# stat_cor(method = \"pearson\", label.x = 3, label.y = 30) # Add correlation coefficient\n# \n# \n\n\n\n\n```\n\n\n```{r}\nsample.meta = as.data.frame(colData(pb.logcounts))\nsample.meta$scores = scale(sample.meta$A11.signature) + scale(sample.meta$A29.signature)\n\nEn = annotate.archetypes.using.labels(t(ACTIONet_summary$H_unified), ACTIONet_summary$metadata$Phenotype)\nHeatmap(En$Enrichment)\n\n\n\nHeatmap(sample.meta$Phenotype[order(sample.meta$scores, decreasing = T)], cluster_rows = F)\n\n```\n\n```{r}\n\narch.sig.avg = as.matrix(sample.meta[, 33:36])\nmed.mat = as.matrix(sample.meta[, 17:22])\n\nArch.vs.Med.enrichment = apply(arch.sig.avg, 2, function(sig) {\n perm = order(sig, decreasing = T)\n X = med.mat[perm, ]\n logPvals = apply(X, 2, function(x) {\n l = as.numeric(x != 0)\n mhg.out = mhg::mhg_test(l, length(l), sum(l), length(l), 1, upper_bound = F, tol = 1e-100)\n -log10(mhg.out$pvalue)\n })\n return(logPvals)\n})\nHeatmap(Arch.vs.Med.enrichment)\n\n(apply(arch.sig.avg, 2, function(x) cor(x, sample.meta$Age, method = \"spearman\")))\n\napply(arch.sig.avg, 2, function(x) cor.test(x, as.numeric(factor(sample.meta$Phenotype)), method = \"spearman\", use = \"complete.obs\")$p.value)\n\n\n```\n\n\n# Load PEC data\n```{r}\nPEC.expr.table = read.table(file.path(input.folder, \"DER-01_PEC_Gene_expression_matrix_normalized.txt\"), header = T)\nrownames(PEC.expr.table) = PEC.expr.table$gene_id\n\nPEC.expr.mat = as.matrix(PEC.expr.table[, -1])\n\n\nlibrary(org.Hs.eg.db)\ngg = as.character(sapply(PEC.expr.table$gene_id, function(str) str_split(str, fixed(\".\"))[[1]][[1]]))\nsuppressWarnings(ids <- AnnotationDbi::mapIds(org.Hs.eg.db, keys = gg, keytype = \"ENSEMBL\", column = \"SYMBOL\", multiVals = \"first\"))\nmask = !is.na(ids)\n\nPEC.expr.mat = PEC.expr.mat[mask, ]\nrownames(PEC.expr.mat) = ids[mask]\n\n\n\n\nPEC.expr.table.TPM = read.table(file.path(input.folder, \"DER-02_PEC_Gene_expression_matrix_TPM.txt\"), header = T)\nrownames(PEC.expr.table.TPM) = PEC.expr.table.TPM$GeneName\n\nPEC.expr.mat.TPM = as.matrix(PEC.expr.table.TPM[, -1])\n\n\nlibrary(org.Hs.eg.db)\nmask = !is.na(ids)\nsuppressWarnings(ids <- AnnotationDbi::mapIds(org.Hs.eg.db, keys = PEC.expr.table.TPM$GeneName, keytype = \"ENSEMBL\", column = \"SYMBOL\", multiVals = \"first\"))\n\nPEC.expr.mat.TPM = PEC.expr.mat.TPM[mask, ]\nrownames(PEC.expr.mat.TPM) = ids[mask]\n\n\n\n\n\ngg = sort(unique(intersect(rownames(PEC.expr.mat.TPM), rownames(PEC.expr.mat))))\ncc = sort(unique(intersect(colnames(PEC.expr.mat), colnames(PEC.expr.mat.TPM))))\n\nPEC.sce = SingleCellExperiment(assays = list(normexpr = PEC.expr.mat[gg, cc], TPM = PEC.expr.mat.TPM[gg, cc]))\n\n\nmeta.PEC.full = read.table(\"~/results/input/Job-138522884223735377851224577.tsv\", header = T, sep = \"\\t\")\n\n\nmeta.PEC = read.table(\"~/results/input/Job-138522891409304015015695443.tsv\", header = T, sep = \"\\t\")\nmask = meta.PEC$diagnosis %in% c(\"Control\", \"Schizophrenia\")\nmeta.PEC = meta.PEC[mask, ]\n\ncommon.samples = sort(unique(intersect((meta.PEC$individualID), (cc))))\n\nmeta.PEC.matched = meta.PEC[match(common.samples, meta.PEC$individualID), ]\nPEC.sce.matched = PEC.sce[, match(common.samples, colnames(PEC.sce))]\ncolData(PEC.sce.matched) = DataFrame(meta.PEC.matched)\ncolnames(PEC.sce.matched) = PEC.sce.matched$individualID\n\nreadr::write_rds(PEC.sce.matched, \"~/results/input/PEC_bulk_expression_SZandCON.rds\")\n\n```\n\n\n# A11 and A19 specific\n```{r}\n# 0 1 \n# 452 367\nSZ.mask = as.numeric(PEC.sce.matched$diagnosis == \"Schizophrenia\")\n\n\nX = assays(PEC.sce.matched)$normexpr\narch.gene.spec = ACTIONet_summary$unified_feature_specificity\n\ncg = intersect(rownames(X), rownames(arch.gene.spec))\nsubX = X[cg, ]\nsubArch = arch.gene.spec[cg, ]\n\nArch.cor = cor(subX, subArch)\n\narch.enrichment = apply(Arch.cor, 2, function(x) {\n perm = order(x, decreasing = T)\n l = SZ.mask[perm]\n mhg.out = mhg::mhg_test(l, length(l), sum(l), length(l), 1, upper_bound = F, tol = 1e-300)\n -log10(mhg.out$pvalue)\n})\nsort(round(arch.enrichment, 1), decreasing = T)\n# A30 A6 A26 A22 A19 A2 A29 A11 A15 A21 A16 A24 A7 A28 A1 A4 A12 A17 A27 A3 A5 A8 A9 A10 A13 A14 A18 A20 A23 A25 A31 \n# 8.0 6.0 3.2 1.8 1.7 1.6 1.6 1.1 0.8 0.7 0.6 0.5 0.3 0.3 0.2 0.1 0.1 0.1 0.1 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0\n\n\nArch.cor = cor(subX, subArch, method = \"spearman\")\narch.enrichment = apply(Arch.cor, 2, function(x) {\n perm = order(x, decreasing = F)\n l = SZ.mask[perm]\n mhg.out = mhg::mhg_test(l, length(l), sum(l), length(l), 1, upper_bound = F, tol = 1e-300)\n -log10(mhg.out$pvalue)\n})\nsort(round(arch.enrichment, 1), decreasing = T)\n# A30 A6 A22 A19 A2 A29 A26 A11 A15 A13 A21 A4 A16 A1 A14 A12 A24 A27 A28 A5 A7 A9 A18 A20 A3 A8 A10 A17 A23 A25 A31 \n# 8.5 8.4 4.0 2.6 2.1 2.1 1.5 1.4 1.2 1.0 1.0 0.8 0.6 0.3 0.3 0.2 0.2 0.2 0.2 0.1 0.1 0.1 0.1 0.1 0.0 0.0 0.0 0.0 0.0 0.0 0.0\n\nsubX.orth = orthoProject(subX, fast_row_sums(subX))\nArch.cor = cor(subX.orth, subArch, method = \"spearman\")\narch.enrichment = apply(Arch.cor, 2, function(x) {\n perm = order(x, decreasing = F)\n l = SZ.mask[perm]\n mhg.out = mhg::mhg_test(l, length(l), sum(l), length(l), 1, upper_bound = F, tol = 1e-300)\n -log10(mhg.out$pvalue)\n})\nsort(round(arch.enrichment, 1), decreasing = T)\n\n\n\n\n\n\n\n```\n\n\n\n```{r}\nX = assays(PEC.sce.matched)$normexpr\n# arch.genes = rownames(arch.gene.spec)[which(apply(as.matrix(arch.gene.spec[, c(11, 29)]), 1, max) > 100)]\narch.genes = rownames(arch.gene.spec)[which(apply(scale(as.matrix(arch.gene.spec[, c(7, 11, 17, 29)])), 1, max) > 3)]\narch.genes = arch.genes[-grep(\"^RPL|^RPS|^MT-|^MT[:.:]\", arch.genes)]\n\n\ncg = intersect(rownames(X), arch.genes)\nsubArch = (arch.gene.spec[cg, c(7, 11, 17, 29)])\nsubX = X[cg, ]\n# subX = log1p(subX)\n\n# X = assays(PEC.sce.matched)$normexpr\n# cg = intersect(rownames(X), rownames(arch.gene.spec))\n# subX = X[cg, ]\n\n\n# Arch.cor = -cor(subX, subArch, method = \"pearson\")\n# arch.enrichment = apply(Arch.cor, 2, function(x) {\n# perm = order(x, decreasing = T)\n# l = SZ.mask[perm]\n# mhg.out = mhg::mhg_test(l, length(l), sum(l), 1000, 1, upper_bound = F, tol = 1e-300)\n# -log10(mhg.out$pvalue)\n# })\n# sort(round(arch.enrichment, 1), decreasing = T)\n# \n# \nsubX.orth = orthoProject(subX, fast_row_sums(subX))\n\nSZ.samples = list(SZ = PEC.sce.matched$individualID[which(SZ.mask == 1)])\nrequire(fgsea)\n\nArch.cor = cor(subX.orth, subArch, method = \"spearman\")\narch.enrichment = apply(Arch.cor, 2, function(x) {\n gsea.out = fgsea(SZ.samples, x)\n -log10(gsea.out$padj)\n # perm = order(x, decreasing = T)\n # l = SZ.mask[perm]\n # mhg.out = mhg::mhg_test(l, length(l), sum(l), length(l)/4, 1, upper_bound = F, tol = 1e-300)\n # -log10(mhg.out$pvalue)\n})\nsort(round(arch.enrichment, 1), decreasing = T)\n\n```\n\n```{r}\nx = Arch.cor[, \"A29\"]\nfgsea::plotEnrichment(SZ.samples[[1]], x)\n\ndf = data.frame(A29 = scale(Arch.cor[, \"A29\"]), A11 = scale(Arch.cor[, \"A11\"]), Phenotype = PEC.sce.matched$diagnosis, Sample = rownames(Arch.cor), x = PEC.sce.matched$ethnicity, PEC.sce.matched$ageDeath, PEC.sce.matched$sex, PEC.sce.matched$smoker)\ndf$combined = (df$A29 + df$A11)/2\n\nggscatter(df, x = \"A11\", y = \"A29\",\n add = \"reg.line\", # Add regression line\n conf.int = TRUE, # Add confidence interval\n color = \"Phenotype\", \n palette = c(\"gray\", \"red\"),\n add.params = list(color = \"blue\",\n fill = \"lightgray\")\n ) \n\n+\n stat_cor(method = \"pearson\", label.x = 3, label.y = 30) # Add correlation coefficient\n\n\n\nArch.cor = cor(subX.orth, subArch, method = \"spearman\")\narch.enrichment = apply(Arch.cor, 2, function(x) {\n x = exp(df$A11)\n names(x) = df$Sample\n fgsea::plotEnrichment(SZ.samples[[1]], x)\n\n # gsea.out = fgsea(SZ.samples, x)\n # -log10(gsea.out$padj)\n perm = order(x, decreasing = T)\n l = SZ.mask[perm]\n mhg.out = mhg::mhg_test(l, length(l), sum(l), length(l)/4, 1, upper_bound = F, tol = 1e-300)\n -log10(mhg.out$pvalue)\n})\nsort(round(arch.enrichment, 1), decreasing = T)\n\n\n\n\n# 0.9115914\n# cor(Arch.cor[, \"A11\"], Arch.cor[, \"A29\"], method = \"spearman\")\n\nfgsea::plotEnrichment(SZ.samples[[1]], x)\n\n\nscores = exp(Arch.cor*5)\n\nX = sapply(sort(unique(PEC.sce.matched$a)), function(x) as.numeric(PEC.sce.matched$ethnicity == x))\nrownames(X) = colnames(PEC.sce.matched)\ngender.enrichment = assess.geneset.enrichment.from.scores(scores, X)\n\ncolnames(gender.enrichment$logPvals) = colnames(scores)\n\nHeatmap(gender.enrichment$logPvals)\n\n\n\n```\n\n\n\n\n\n" }, { "alpha_fraction": 0.6469544768333435, "alphanum_fraction": 0.6664695739746094, "avg_line_length": 29.80364418029785, "blob_id": "92ae6544430423036d1c4fbbd9dbf6939c7a06ec", "content_id": "196a1e2b1c0203cfeaeca4230ef93db3b1b37ab0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 15219, "license_type": "no_license", "max_line_length": 512, "num_lines": 494, "path": "/ChEA_analysis.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"Analyze DE geens\"\nsubtitle: \"\"\nauthor: \"Shahin Mohammadi\"\ndate: \"Run on `r Sys.time()`\"\ndocumentclass: article\noutput:\n html_document:\n toc: true\n toc_float: true\n---\n\n```{r setup, include=FALSE}\nsuppressPackageStartupMessages({\nlibrary(ACTIONet)\nlibrary(data.table)\nlibrary(ggplot2)\nlibrary(ggrepel)\nlibrary(cowplot)\nlibrary(corrplot)\nlibrary(limma)\nlibrary(muscat)\nlibrary(metafor)\nlibrary(ggcorrplot)\nlibrary(openxlsx)\nlibrary(simplifyEnrichment)\nlibrary(synapser)\nlibrary(synExtra)\nsynLogin(rememberMe = TRUE)\nsource(\"functions.R\")\n})\n\nknitr::opts_chunk$set(\n\terror = FALSE,\n\tmessage = FALSE,\n\twarning = FALSE,\n\tcache = TRUE,\n\tdev = c(\"png\", \"pdf\"),\n\tinclude = FALSE,\n\ttidy = FALSE\n)\n```\n\n\n# Setup environment\n```{r}\ndataset.path = \"~/results/datasets/\"\nfigures.path = \"~/results/figures\"\ntables.path = \"~/results/tables\"\ninput.path = \"~/results/input\"\n\n# Load pseudobulk samples\npb.logcounts = loadDataset(\"pseudobulk_mean_logcounts\", dataset.path = dataset.path)\nACTIONet_summary = loadDataset(\"ACTIONet_summary\", dataset.path = dataset.path)\ncolors = loadDataset(\"celltype_colors\", dataset.path = dataset.path)\n\nSZ.genes = loadInputDataset(\"SCZ_associated_genesets\", extension = \"rds\")\n\nDE.new = loadDataset(\"DE_genes_pseudobulk\", dataset.path = dataset.path)\nUp.genes = DE.new$Up.genes\nDown.genes = DE.new$Down.genes\nDE.sc = DE.new$DE.sc\n\nX = cbind(sapply(DE.new$Up.genes, length),sapply(DE.new$Down.genes, length))\nordered.celltypes = rownames(X)[order(apply(X, 1, sum), decreasing = T)]\n\n```\n\n\n# Perform ChEA analysis using REST API\n```{r}\n ChEA3.Up = lapply(Up.genes, function(genes) {\n if(length(genes) > 30)\n queryChEA3(genes)\n })\n \n ChEA3.Down = lapply(Down.genes, function(genes) {\n if(length(genes) > 30)\n queryChEA3(genes)\n })\n \n names(ChEA3.Up) = names(ChEA3.Down) = names(Up.genes)\n \n ChEA.analysis = c(ChEA3.Up, ChEA3.Down)\n names(ChEA.analysis) = c(paste(\"Up\", names(Up.genes), sep = \"_\"), paste(\"Down\", names(Down.genes), sep = \"_\"))\n\n\n storeDataset(ChEA.analysis, \"ChEA_DE_TF_enrichment_min30genes\", dataset.path = dataset.path)\n\n```\n\n\n## Load significant variants and mapped genes\n```{r}\nPGC3.loci = loadInputDataset(\"PGC3_SZ_significant_loci\", \"tsv\", input.path = input.path)\n\nassociated.genes = PGC3.loci$`ENSEMBL genes all (clear names)`\n\n\nPGC3.all.genes.raw = sort(unique(unlist(sapply(PGC3.loci$`ENSEMBL genes all (clear names)`, function(str) {\n if(str == \"-\") {\n return(\"-\")\n }\n gs = str_split(str, \",\")[[1]]\n \n return(gs)\n}))))\n\nPGC3.all.genes = intersect(PGC3.all.genes.raw, rownames(pb.logcounts))\n\n\n\n```\n\n\n# Export TF ChEA scores as excel tables\n```{r}\nUp.DFs = lapply(1:length(ChEA3.Up), function(i) {\n res = ChEA3.Up[[i]]\n if(is.null(res)) {\n return(NULL)\n }\n \n X = res$`Integrated--topRank`\n \n X$Score = -log10(as.numeric(X$Score))\n X$Rank = as.numeric(X$Rank)\n X = X[, -c(1, 2, 5)]\n X$inPGC3 = as.numeric(X$TF %in% PGC3.all.genes)\n \n})\nnames(Up.DFs) = names(ChEA3.Up)\nUp.DFs = Up.DFs[!sapply(Up.DFs, is.null)]\n\nstoreTable(Up.DFs, name = \"TFs_ChEA_scores_Up\", tables.path = tables.path)\n\n\nDown.DFs = lapply(1:length(ChEA3.Down), function(i) {\n res = ChEA3.Down[[i]]\n if(is.null(res)) {\n return(NULL)\n }\n \n X = res$`Integrated--topRank`\n \n X$Score = -log10(as.numeric(X$Score))\n X$Rank = as.numeric(X$Rank)\n X = X[, -c(1, 2, 5)]\n \n X$inPGC3 = as.numeric(X$TF %in% PGC3.all.genes)\n})\nnames(Down.DFs) = names(ChEA3.Down)\nDown.DFs = Down.DFs[!sapply(Down.DFs, is.null)]\nstoreTable(Down.DFs, name = \"TFs_ChEA_scores_Down\", tables.path = tables.path)\n\n```\n\n\n# Construct ChEA score matrix for up- and down-regulated genes\n```{r}\nTFs = sort(unique(ChEA.analysis[[1]]$`Integrated--meanRank`$TF))\n\n\nTF.up = matrix(0, nrow = length(TFs), length(ChEA3.Up))\nrownames(TF.up) = TFs\ncolnames(TF.up) = names(ChEA3.Up)\nfor(i in 1:length(ChEA3.Up)) {\n res = ChEA3.Up[[i]]\n if(is.null(res)) {\n next\n }\n \n X = res$`Integrated--topRank`\n \n TF.up[match(X$TF, TFs), i] = -log10(as.numeric(X$Score))\n}\n\nTF.down = matrix(0, nrow = length(TFs), length(ChEA3.Down))\nrownames(TF.down) = TFs\ncolnames(TF.down) = names(ChEA3.Down)\nfor(i in 1:length(ChEA3.Down)) {\n res = ChEA3.Down[[i]]\n if(is.null(res)) {\n next\n }\n \n X = res$`Integrated--topRank`\n \n TF.down[match(X$TF, TFs), i] = -log10(as.numeric(X$Score))\n}\n\n# Only neuronal\nTF.mean.scores = apply(cbind(TF.down[, 1:17], TF.up[, 1:17]), 1, mean)\nnames(TF.mean.scores) = rownames(TF.down)\n\n\nTF.up = TF.up[, fast_column_sums(TF.up) != 0]\nTF.down = TF.down[, fast_column_sums(TF.down) != 0]\n\n```\n\n\n# Construct TF modules\n## Filter PB samples\n```{r}\nncells = sapply(int_colData(pb.logcounts)$n_cells, as.numeric)\nrownames(ncells) = names(assays(pb.logcounts))\n\ncs = Matrix::colSums(ncells)\nncells.freq = 100*scale(ncells, center = F, scale = cs)\nEx.perc = (fast_column_sums(ncells.freq[grepl(\"^Ex\", rownames(ncells.freq)) & !grepl(\"^Ex-NRGN\", rownames(ncells.freq)), ]))\n\nmask = (Ex.perc >= 10) & (Ex.perc <= 80)\n\npb.logcounts.filtered = pb.logcounts [, mask]\n\n```\n\n## Compute TF-TF expression correlation within each cell type\n```{r}\nTFs = ChEA.analysis[[1]]$`Integrated--topRank`$TF\ncts = names(assays(pb.logcounts.filtered))\n\nsubTFs = intersect(TFs, rownames(pb.logcounts))\nPB.assays.norm = lapply(cts, function(nn) {\n print(nn)\n E = assays(pb.logcounts.filtered)[[nn]]\n cs = Matrix::colSums(E)\n mask = (cs > 0)\n E = E[, mask]\n E = median(cs[mask])*scale(E, center = F, scale = cs[mask])\n\n return(E[subTFs, ])\n})\nnames(PB.assays.norm) = cts\n\n```\n\n# Convert to WGCNA compatible format\n```{r}\nnSets = length(cts)\nmultiExpr = vector(mode = \"list\", length = nSets)\nfor(i in 1:length(cts)) {\n multiExpr[[i]] = list(data = as.data.frame(t(PB.assays.norm[[i]])))\n}\n\n```\n\n\n\n# Run WGCNA\n## Calculation of network adjacencies\n```{r}\nnGenes = length(subTFs)\nnSets = length(cts)\n\n# Initialize an appropriate array to hold the adjacencies\nadjacencies = array(0, dim = c(nSets, nGenes, nGenes));\n# Calculate adjacencies in each individual data set\nfor (set in 1:nSets) {\n adj = abs(cor(multiExpr[[set]]$data, use = \"p\"))^6\n # adj = ((1+cor(multiExpr[[set]]$data, use = \"p\"))/2)^12\n adj[is.na(adj)] = 0\n adjacencies[set, , ] = adj\n}\n\n```\n\n## Calculation of Topological Overlap\n```{r}\n# Initialize an appropriate array to hold the TOMs\nTOM = array(0, dim = c(nSets, nGenes, nGenes));\n# Calculate TOMs in each individual data set\nfor (set in 1:nSets)\n TOM[set, , ] = TOMsimilarity(adjacencies[set, , ]);\n\n\n```\n\n## Calculation of consensus Topological Overlap\n```{r}\n# selected.cts = names(DE.new$Up.genes)\nscaleP = 0.95\nselected.cts = names(DE.new$Up.genes)\nindices = match(selected.cts, cts)\n\nscaleQuant = sapply(1:length(indices), function(i) quantile(as.numeric(TOM[indices[[i]], ,]), probs = scaleP, type = 8))\n\nindices = indices[order(scaleQuant, decreasing = T)]\nkappa = as.numeric(log(scaleQuant[1])/log(scaleQuant))\n\nconsensusTOM = matrix(1, nGenes, nGenes)\nconsensusTOM = TOM[indices[[1]], ,]\n\nfor(i in 2:length(indices)) {\n curTOM = TOM[indices[[i]], ,]\n scaledTOM = curTOM^kappa[i]\n # consensusTOM = consensusTOM * (scaledTOM)\n consensusTOM = consensusTOM + (scaledTOM)\n # consensusTOM = pmin(consensusTOM, scaledTOM)\n \n}\nconsensusTOM = consensusTOM *(1/length(indices))\n\nrownames(consensusTOM) = colnames(consensusTOM) = subTFs\n \n```\n\n## Store Consensus TOM\n```{r}\nstoreDataset(consensusTOM, name = \"WGCNA_consensusTOM\", dataset.path = dataset.path)\n\n```\n\n\n```{r}\n# Clustering\nconsTree = hclust(as.dist(1-consensusTOM), method = \"average\");\n# We like large modules, so we set the minimum module size relatively high:\nminModuleSize = 20;\n# Module identification using dynamic tree cut:\nunmergedLabels = cutreeDynamic(dendro = consTree, distM = 1- consensusTOM, method = \"hybrid\", deepSplit = 1, cutHeight = 0.99, minClusterSize = minModuleSize, pamRespectsDendro = TRUE );\n\nunmergedColors = labels2colors(unmergedLabels)\n\n\n```\n\n\n\n\n\n```{r}\nTF.mean.scores = apply(cbind(TF.down, TF.up), 1, mean)\nnames(TF.mean.scores) = rownames(TF.down)\n\nff = factor(unmergedColors)\nTF.mods = split(subTFs, ff)\nperm = order(sapply(TF.mods, function(gs) mean(TF.mean.scores[gs])), decreasing = T)\nsorted.TFmods = levels(ff)[perm]\nTF.mods = TF.mods[sorted.TFmods]\nTF.mods = TF.mods[-which(sorted.TFmods == \"grey\")]\nTF.mods = lapply(TF.mods, function(gs) gs[order(TF.mean.scores[gs], decreasing = T)])\n\n\nTF.df = data.frame(TFs = subTFs, modules = unmergedLabels, colors = factor(unmergedColors, rev(sorted.TFmods)), GWAS.linked.PGC3 = as.numeric(subTFs %in% PGC3.all.genes), ChEA.aggregate.association = TF.mean.scores[subTFs])\n\nTF.df = TF.df[TF.df$modules != 0, ]\nTF.df = TF.df[order(TF.df$colors, TF.df$ChEA.aggregate.association, decreasing = T), ]\n\nTF.df$modules = paste(\"M\", match(TF.df$modules, unique(TF.df$modules)), sep = \"\")\n\nTF.df = droplevels(TF.df)\n\n\n```\n\n## Store final TF modules\n```{r}\nstoreTable(TF.df, name = \"TF_modules_WGCNA\", tables.path = tables.path)\n\n\n```\n\n\n\n```{r}\nTF.mods = split(TF.df$TFs, factor(TF.df$colors, unique(TF.df$colors)))\n\ndf.up = reshape2::melt(cbind(TF.df[, c(1, 3)], data.frame(TF.up[TF.df$TFs, ])))\ndf.down = reshape2::melt(cbind(TF.df[, c(1, 3)], data.frame(TF.down[TF.df$TFs, ])))\ndf.down$value = df.down$value\ndf.up$Direction = \"Up\"\ndf.down$Direction = \"Down\"\ndf.combined = rbind(df.up, df.down)\ndf.combined$colors = factor(df.combined$colors, unique(TF.df$colors))\n\ngg = ggbarplot(df.combined, \"colors\", \"value\", fill = \"Direction\", palette = c(\"#3288bd\", \"#d53e4f\"), add = \"mean_se\") + ylab(\"ChEA Score (combined)\") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1, color = unique(TF.df$colors))) + xlab(\"TF Modules (sorted)\")\n \nstoreFigure(gg, \"ChEA_aggr_scores_per_module_barplot\", extension = \"pdf\", width = 6, height = 4, figures.path = figures.path)\n\n\n\n```\n\n\n```{r}\n\nsorted.TFs = unlist(TF.mods)\nChEA.up.per.TF = as.matrix(apply(TF.up[sorted.TFs, ], 1, mean))\nChEA.down.per.TF = as.matrix(apply(TF.up[sorted.TFs, ], 1, mean))\n\n# Heatmap(ChEA.down.per.TF, cluster_rows = F)\n# \n\nww = consensusTOM[sorted.TFs, sorted.TFs]\ndiag(ww) = NA\n\nMPal = names(TF.mods)\nnames(MPal) = MPal\nha_row = rowAnnotation(Module = factor(unlist(lapply(1:length(TF.mods), function(i) rep(names(TF.mods)[[i]], length(TF.mods[[i]])))), names(TF.mods)), col = list(Module = MPal))\n\nha_row = rowAnnotation(Module = factor(unlist(lapply(1:length(TF.mods), function(i) rep(names(TF.mods)[[i]], length(TF.mods[[i]])))), names(TF.mods)), col = list(Module = MPal))\n\nX = ChEA.up.per.TF\nY = ChEA.down.per.TF\nrownames(ww) = colnames(ww) = c()\ncolnames(X) = colnames(Y) = c()\n\nPal = as.character(pals::brewer.ylorrd(11))\n\nht = Heatmap(ww, row_names_side = \"left\", name = \"ConsensusTOM\", col = Pal, column_title = \"TF-TF expression correlation\", column_title_gp = gpar(fontsize = 21), cluster_rows = F, cluster_columns = F, left_annotation = ha_row)\n\nstoreFigure(ht, \"TF_modules_unlabeled_colored\", extension = \"pdf\", width = 7, height = 7, figures.path = figures.path)\n\n\n\n```\n\n## ChEA scores of the top-ranked (purple module)\n```{r}\npurpleMod = TF.mods[[1]]\nmask = purpleMod %in% PGC3.all.genes\nTF.colors = rep(\"black\", length(sorted.TFs))\nTF.colors[mask] = \"red\"\n\n\nX.U = TF.up[purpleMod,]\nredCol_fun = circlize::colorRamp2(c(0, exp(quantile(log(X.U), seq(0.25, 0.95, length.out = 12)))), c(\"#ffffff\", pals::brewer.reds(12)))\n\nX.D = TF.down[purpleMod,]\nblueCol_fun = circlize::colorRamp2(c(0, exp(quantile(log(X.D), seq(0.25, 0.95, length.out = 12)))), c(\"#ffffff\", pals::brewer.blues(12)))\n\n# row.names(X.U) = rownames(X.D) = annots\n# CC = (cor(t(X.U)) + cor(t(X.D))) / 2\n# CC[is.na(CC)] = 0\n# perm = get_order(seriate)\n\nht = Heatmap(X.U, rect_gp = gpar(col = \"black\"), name = \"Up\", column_title = \"Up\", cluster_rows = F, cluster_columns = F, col = redCol_fun, row_names_side = \"left\", column_names_gp = gpar(fontsize = 14, fontface=\"bold\", col = colors[colnames(X.U)]), row_names_gp = gpar(fontsize = 14, fontface=\"bold\", col = TF.colors), column_title_gp = gpar(fontsize = 18, fontface=\"bold\"), row_title_gp = gpar(fontsize = 18, fontface=\"bold\"), row_names_max_width = unit(150, \"cm\"), column_names_max_height = unit(150, \"cm\"))+\nHeatmap(X.D, rect_gp = gpar(col = \"black\"), name = \"Down\", cluster_rows = F, cluster_columns = F, col = blueCol_fun, row_names_side = \"left\", column_title = \"Down\", column_names_gp = gpar(fontsize = 14, fontface=\"bold\", col = colors[colnames(X.D)]), row_names_gp = gpar(fontsize = 14, fontface=\"bold\"), column_title_gp = gpar(fontsize = 18, fontface=\"bold\"), row_title_gp = gpar(fontsize = 18, fontface=\"bold\"), row_names_max_width = unit(150, \"cm\"), column_names_max_height = unit(150, \"cm\"))\n\nstoreFigure(ht, \"TF_module_purple_ChEA_scores\", extension = \"pdf\", width = 8, height = 8, figures.path = figures.path)\n\n```\n\n\n\n\n\n# Overlap with ME37\n```{r}\nDev.modules = loadInputDataset(\"DevPEC_modules\", \"tsv\",input.path = input.path)\n\nSATB2.module = TF.mods$purple\n\nrequire(stringr)\nDev.modules.genes = lapply(Dev.modules$X16, function(mod) {\n mod = str_split(mod, \",\")[[1]]\n intersect(as.character(sapply(mod, function(g) str_split(g, fixed(\"|\"))[[1]][[2]])), TFs)\n})\nnames(Dev.modules.genes) = Dev.modules$Module\n\nphyper(length(intersect(Dev.modules.genes$ME37, SATB2.module)), length(SATB2.module), length(TFs)- length(SATB2.module), length(Dev.modules.genes$ME37), lower.tail = F) # 4.493923e-06\n\nprint(intersect(Dev.modules.genes$ME37, SATB2.module))\n\n```\n\n## Analyze TGs with CUTTag\n```{r}\nCUTTag = loadDataset(\"CUTTag_linked_genes\", dataset.path = dataset.path)\nCUTTag = CUTTag[-2]\n\nCUTTAG.vs.DE.up = assess.genesets(Up.genes, CUTTag, nrow(pb.logcounts), correct = \"local\")\nCUTTAG.vs.DE.down = assess.genesets(Down.genes, CUTTag, nrow(pb.logcounts), correct = \"local\")\n\n\nX.U = (CUTTAG.vs.DE.up)\nX.D = (CUTTAG.vs.DE.down)\ncolnames(X.U) = colnames(X.D) = names(CUTTag)\nX.U = X.U[, -3]\nX.D = X.D[, -3]\n\nredCol_fun = circlize::colorRamp2(c(0, exp(quantile(log(X.U)[X.U > -log10(0.05)], seq(0.05, 0.99, length.out = 12)))), c(\"#ffffff\", pals::brewer.reds(12)))\n\nblueCol_fun = circlize::colorRamp2(c(0, exp(quantile(log(X.D)[X.D > -log10(0.05)], seq(0.05, 0.99, length.out = 12)))), c(\"#ffffff\", pals::brewer.blues(12)))\n\n\nht = Heatmap(X.U, rect_gp = gpar(col = \"black\"), name = \"Up\", column_title = \"Up\", cluster_rows = F, cluster_columns = F, col = redCol_fun, row_names_side = \"left\", column_names_gp = gpar(fontsize = 14, fontface=\"bold\"), row_names_gp = gpar(fontsize = 14, fontface=\"bold\", col = colors), column_title_gp = gpar(fontsize = 12, fontface=\"bold\"), row_title_gp = gpar(fontsize = 12, fontface=\"bold\"), row_names_max_width = unit(150, \"cm\"), column_names_max_height = unit(150, \"cm\"))+\nHeatmap(X.D, rect_gp = gpar(col = \"black\"), name = \"Down\", cluster_rows = F, cluster_columns = F, col = blueCol_fun, row_names_side = \"left\", column_title = \"Down\", column_names_gp = gpar(fontsize = 14, fontface=\"bold\"), row_names_gp = gpar(fontsize = 14, fontface=\"bold\"), column_title_gp = gpar(fontsize = 12, fontface=\"bold\"), row_title_gp = gpar(fontsize = 12, fontface=\"bold\"), row_names_max_width = unit(150, \"cm\"), column_names_max_height = unit(150, \"cm\"))\n\nstoreFigure(ht, \"CUTTag_vs_DE_genes\", extension = \"pdf\", width = 4, height = 6, figures.path = figures.path)\n\n```\n\n\n" }, { "alpha_fraction": 0.6336392164230347, "alphanum_fraction": 0.6618788242340088, "avg_line_length": 39.85688400268555, "blob_id": "22c2d5b672c60a5776bdcc741d214cbd0bf2b183", "content_id": "0991c096ebc3afefc646bde31ae0ebaedf0c2cef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 22557, "license_type": "no_license", "max_line_length": 568, "num_lines": 552, "path": "/old/AnalyzeDE_preliminary.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"Analyze DE genes\"\nsubtitle: \"Step 3: Postprocessing the alignment of DE results across datasets\"\n\noutput: html_notebook\n---\n\n# Setup\n```{r include=FALSE}\nrequire(ACTIONet)\nrequire(stringr)\nrequire(ComplexHeatmap)\n\n\nresults.path = \"~/results\"\ninput.path = \"~/results/input\"\ndataset.path = \"~/results/datasets\"\ntables.path = \"~/results/tables\"\nfigures.path = \"~/results/figures\"\n\n```\n\n\n## Enrichment function\n```{r}\nassess.genesets <-function (arch.gs, terms.gs, N, min.pval = 1e-100, correct = \"none\"){\n shared = t(sapply(terms.gs, function(gs1) {\n sapply(arch.gs, function(gs2) {\n nn = intersect(gs1, gs2)\n })\n }))\n colnames(shared) = names(arch.gs)\n GS.sizes = sapply(terms.gs, length)\n logPvals.out = sapply(1:ncol(shared), function(i) {\n gg = shared[, i]\n x = as.numeric(sapply(gg, length))\n n.sample = length(arch.gs[[i]])\n n.success = as.numeric(GS.sizes)\n v = rep(1, length(x))\n min.overlap = n.success * n.sample/N\n idx = which(x >= min.overlap)\n if (length(idx) == 0) \n return(v)\n v[idx] = (phyper(x[idx]-1, n.sample, N-n.sample, n.success[idx], lower.tail = F))\n # v[idx] = HGT_tail(population.size = N, success.count = n.success[idx], \n # sample.size = n.sample, observed.success = x[idx])\n return(v)\n })\n if(correct == \"global\") {\n logPvals.out = matrix(p.adjust(logPvals.out, \"fdr\"), nrow = nrow(logPvals.out))\n } else if(correct == \"local\") {\n logPvals.out = apply(logPvals.out, 2, function(x) p.adjust(x, \"fdr\"))\n }\n rownames(logPvals.out) = names(terms.gs)\n colnames(logPvals.out) = names(arch.gs)\n return(-log10(Matrix::t(logPvals.out)))\n}\n```\n\n# Load primary datasets\n```{r, eval = T}\nACTIONet_summary = readr::read_rds(file.path(dataset.path, \"ACTIONet_summary_filtered_individuals.rds\"))\npb.logcounts = readr::read_rds(file.path(dataset.path, \"PB_mean_logcounts_final.RDS\"))\n\ncolor.df = readRDS(file.path(dataset.path, \"celltype_colors.rds\"))\ncolors = color.df$color\nnames(colors) = color.df$celltype\n\n```\n\n# Load DE results\n```{r, eval = T}\nresDE = readr::read_rds(file.path(dataset.path, \"Cohort_specific_DE_results.rds\"))\nfiltered.tables = readr::read_rds(file.path(dataset.path, \"Cohort_specific_DE_results_filtered.rds\"))\ncombined.analysis.tables = readr::read_rds(file.path(dataset.path, \"meta_analysis_results.rds\"))\n\nDE.new = readRDS(file.path(dataset.path, \"DE_genes_pseudobulk.rds\"))\nUp.genes = DE.new$Up.genes\nDown.genes = DE.new$Down.genes\nDE.sc = DE.new$DE.sc\n# ordered.celltypes = rownames(X)[order(apply(X, 1, sum), decreasing = T)]\n\n```\n\n\n\n# Compute overlap of selected DE genes with bulk (PEC)\n```{r}\nSZ.genes = readr::read_rds(file.path(input.path, \"SCZ_associated_genesets.rds\"))\n\nUp.genes.overlap = sapply(Up.genes, function(gs) intersect(gs, SZ.genes$`DE.Up (PEC)`))\nUp.genes.size = sapply(Up.genes.overlap, length) \nUp.En = assess.genesets(Up.genes[ordered.celltypes], SZ.genes[c(5, 6)], nrow(pb.logcounts), correct = \"local\")[, 1]\n\nDown.genes.overlap = sapply(Down.genes, function(gs) intersect(gs, SZ.genes$`DE.Down (PEC)`))\nDown.genes.size = sapply(Down.genes.overlap, length) \nDown.En = assess.genesets(Down.genes[ordered.celltypes], SZ.genes[c(5, 6)], nrow(pb.logcounts), correct = \"local\")[, 2]\n\n\nDE.overlap.tbl = data.frame(Celltype = ordered.celltypes, Up = sapply(Up.genes[ordered.celltypes], length), Up_vs_bulk_count = Up.genes.size, Up_vs_bulk_enrichment = Up.En, Down = sapply(Down.genes[ordered.celltypes], length), Down_vs_bulk_count = Down.genes.size, Down_vs_bulk_enrichment = Down.En)\n\nwrite.table(DE.overlap.tbl, file.path(tables.path, \"DE_vs_bulk_overlap.tsv\"), sep = \"\\t\", row.names = F, col.names = T, quote = F)\n```\n\n\n# Plot the total number of DE genes\n```{r}\ncelltype.colors = colors[names(Up.genes)]\n# names(celltype.colors) = names(Up.genes)\n\ndf.Up = data.frame(Counts = sapply(Up.genes, function(x) length(setdiff(x, SZ.genes$`DE.Up (PEC)`))), Celltype = names(Up.genes), Direction=\"Up\", Color = celltype.colors[names(Up.genes)], stringsAsFactors = F)\n\ndf.UpandBulk = data.frame(Counts = sapply(Up.genes, function(x) length(intersect(x, SZ.genes$`DE.Up (PEC)`))), Celltype = names(Up.genes), Direction=\"Up & Bulk\", Color = celltype.colors[names(Up.genes)], stringsAsFactors = F)\n\n\ndf.Down = data.frame(Counts = -sapply(Down.genes, function(x) length(setdiff(x, SZ.genes$`DE.Down (PEC)`))), Celltype = names(Down.genes), Direction=\"Down\", Color = celltype.colors[names(Down.genes)], stringsAsFactors = F)\n\ndf.DownandBulk = data.frame(Counts = -sapply(Down.genes, function(x) length(intersect(x, SZ.genes$`DE.Down (PEC)`))), Celltype = names(Down.genes), Direction=\"Down & Bulk\", Color = celltype.colors[names(Down.genes)], stringsAsFactors = F)\n\n\n\ndf = rbind(df.Up, df.UpandBulk, df.Down, df.DownandBulk)\n\ntotal.Up = sapply(Up.genes, length)\ntotal.Down = sapply(Down.genes, length)\n\nset.seed(0)\n# total = total.Up + total.Down + 0.001*rnorm(length(Up.genes))\ntotal = apply(cbind(total.Up, total.Down), 1, max)\n\narch.perm = order(total, decreasing = F)\ndf$Celltype = factor(df$Celltype, rev(ordered.celltypes))\n\npdf(file.path(figures.path, \"NumDysregGenes.pdf\"), width = 8, height = 5)\nggplot(data = df, aes(x = Celltype, y = Counts, fill = Direction)) + geom_bar(stat = \"identity\")+\n coord_flip()+ylab(\"Sorted Celltypes\")+\nlabs(y = \"# Genes\", x = \"Sorted Celltypes\")+\n theme_minimal()+\n guides(fill = FALSE)+ scale_fill_manual(values=c(\"#3288bd\", colorspace::darken(\"#3288bd\", 0.35), \"#d53e4f\", colorspace::darken(\"#d53e4f\", 0.35))) + theme(axis.text.y = element_text(face=\"bold\", color=celltype.colors[levels(df$Celltype)], size=12, angle=0), axis.text.x = element_text(face=\"bold\", color=\"black\", size=12, angle=0), axis.title = element_text(face=\"bold\", size=14, angle=0))\ndev.off()\n\n```\n\n\n# Visualize selected genes\n## Read bulk DE results\n```{r}\nPEC.DE = read.table(file.path(input.path, \"PEC_DE_table.csv\"), header = T)\ncommon.genes = intersect(rownames(pb.logcounts), PEC.DE$gene_name)\nPEC.tstat = PEC.DE$SCZ.t.value[match(common.genes, PEC.DE$gene_name)]\nnames(PEC.tstat) = common.genes\n\n```\n\n## Plot heatmap\n```{r}\nselected.genes.tbl = read.xlsx(file.path(dataset.path, \"Top50Genes.xlsx\"))\n\nselected.genes = sort(unique(unlist(as.list(selected.genes.tbl))))\nselected.genes = intersect(selected.genes, names(PEC.tstat))\n\nX = DE.new$DE.sc[selected.genes, ]\nperm = order(fast_row_sums(X), decreasing = T)\nY = as.matrix(PEC.tstat[selected.genes])\ncolnames(Y) = c(\"Bulk\")\nRdBu.pal = circlize::colorRamp2(seq(-5, 5, length.out = 7), rev(pals::brewer.rdbu(7)))\n\npdf(file.path(figures.path, \"Top50_selected_DE_genes_v3.pdf\"), width = 6, height = 16)\nHeatmap(X[perm, ], cluster_rows = F, rect_gp = gpar(col = \"black\"), cluster_columns = F, column_title = \"Celltypes\", column_title_gp = gpar(fontsize = 21), column_names_gp = gpar(col = colors[colnames(DE.new$DE.sc)]), name = \"DE\", col = RdBu.pal, row_names_side = \"left\") + Heatmap(Y[perm, ], cluster_rows = F, rect_gp = gpar(col = \"black\"), cluster_columns = F, name = \"Bulk\", col = RdBu.pal, row_names_side = \"left\")\ndev.off()\n\n```\n\n```{r}\nRdBu.pal = circlize::colorRamp2(seq(-5, 5, length.out = 7), rev(pals::brewer.rdbu(7)))\n\n\ntbl = read.table(\"~/Top50genesForFig2b.csv\", sep = \",\", header = T)\n\nDE.sc.masked = DE.sc\nDE.sc.masked[ (DE.new$logPvals < -log10(0.05)) | (abs(DE.new$logFC) < 0.1) ] = 0\n\nhts = lapply(1:ncol(tbl), function(j) {\n selected.genes = intersect(setdiff(tbl[1:10, j], \"\"), names(PEC.tstat))\n \n X = DE.sc.masked[selected.genes, ]\n perm = order(fast_row_sums(X), decreasing = T)\n \n Y = as.matrix(PEC.tstat[selected.genes])\n colnames(Y) = c(\"Bulk\")\n RdBu.pal = circlize::colorRamp2(seq(-5, 5, length.out = 7), rev(pals::brewer.rdbu(7)))\n \n ht = Heatmap(X[perm, ], cluster_rows = F, rect_gp = gpar(col = \"black\"), cluster_columns = F, column_title = \"Celltypes\", column_title_gp = gpar(fontsize = 21), column_names_gp = gpar(col = colors[colnames(DE.new$DE.sc)]), name = colnames(tbl)[[j]], col = RdBu.pal, row_names_side = \"left\", row_title = colnames(tbl)[[j]], row_title_side = \"left\", row_title_gp = gpar(fontsize = 18)) \n \n return(ht)\n})\n\npdf(file.path(figures.path, \"selected_DE_genes_splitted_v3.pdf\"), height = 18)\nhts[[1]] %v% hts[[2]] %v% hts[[3]] %v% hts[[4]] %v% hts[[5]]\ndev.off()\n\n\nselected.genes = unlist(lapply(1:ncol(tbl), function(j) {\n selected.genes = intersect(setdiff(tbl[1:10, j], \"\"), names(PEC.tstat))\n \n X = DE.sc.masked[selected.genes, ]\n perm = order(fast_row_sums(X), decreasing = T)\n selected.genes[perm]\n}))\n\nY = as.matrix(PEC.tstat[selected.genes])\ncolnames(Y) = c(\"Bulk\")\n\npdf(file.path(figures.path, \"selected_DE_genes_splitted_matched_bulk_v3.pdf\"), width = 1.8, height = 16)\nHeatmap(Y, cluster_rows = F, rect_gp = gpar(col = \"black\"), cluster_columns = F, name = \"Bulk\", col = RdBu.pal, row_names_side = \"left\")\ndev.off()\n\n\n```\n\n\n# Functional enrichment\n## Load annotations\n```{r}\nFunCat = readRDS(file.path(dataset.path, \"FunCat.rds\"))\n\nFunCat.genes = split(FunCat$FunCat2Gene$Gene, factor(FunCat$FunCat2Gene$Category, unique(FunCat$FunCat2Gene$Category)))[-15]\nnames(FunCat.genes) = FunCat$FunCat2Class$Category\n\nFunCat.annotation = FunCat$FunCat2Class$Classification\n\nFunCatPal = ggpubr::get_palette(\"npg\", length(unique(FunCat.annotation)))\nnames(FunCatPal) = unique(FunCat.annotation)\n\n\n```\n\n## Perform enrichment\n```{r}\nUp.enrichment = assess.genesets(FunCat.genes, Up.genes[1:17], nrow(pb.logcounts), correct = \"local\")\nDown.enrichment = assess.genesets(FunCat.genes, Down.genes[1:17], nrow(pb.logcounts), correct = \"local\")\n\nUp.enrichment[Up.enrichment < -log10(0.05)] = 0\nDown.enrichment[Down.enrichment < -log10(0.05)] = 0\n\nha_rows = rowAnnotation(df = list(\"Class\" = FunCat.annotation), col = list(\"Class\" = FunCatPal), annotation_legend_param = list(\"Class\"=list(title_gp = gpar(fontsize = 0), labels_gp = gpar(fontsize = 10))))\n\n\nX.U = (Up.enrichment)\n# redCol_fun = circlize::colorRamp2(c(quantile(X.U, 0.25), quantile(X.U, 0.5), quantile(X.U, 0.85), quantile(X.U, 0.99)), c(\"#ffffff\", \"#fee5d9\", \"#ef3b2c\", \"#99000d\"))\nredCol_fun = circlize::colorRamp2(c(0, exp(quantile(log(X.U)[X.U > -log10(0.05)], seq(0.05, 0.95, length.out = 12)))), c(\"#ffffff\", pals::brewer.reds(12)))\n\nX.D = (Down.enrichment)\n# blueCol_fun = circlize::colorRamp2(c(quantile(X.D, 0.25), quantile(X.U, 0.5), quantile(X.D, 0.85), quantile(X.D, 0.99)), c( \"#ffffff\", \"#9ecae1\", \"#2171b5\", \"#08306b\"))\n\nblueCol_fun = circlize::colorRamp2(c(0, exp(quantile(log(X.D)[X.D > -log10(0.05)], seq(0.05, 0.95, length.out = 12)))), c(\"#ffffff\", pals::brewer.blues(12)))\n\n# pals::brewer.reds()\n\n\npdf(file.path(figures.path, \"DE_FunCat.pdf\"), width = 14, height = 7)\npar(mar=c(0,150,0,0))\nHeatmap(X.U, rect_gp = gpar(col = \"black\"), name = \"Up\", column_title = \"Up-regulated\", cluster_rows = F, cluster_columns = F, col = redCol_fun, row_names_side = \"left\", column_names_gp = gpar(fontsize = 14, fontface=\"bold\", col = colors[colnames(X.U)]), row_names_gp = gpar(fontsize = 14, fontface=\"bold\", col = FunCatPal[FunCat.annotation]), column_title_gp = gpar(fontsize = 18, fontface=\"bold\"), row_title_gp = gpar(fontsize = 18, fontface=\"bold\"), row_names_max_width = unit(150, \"cm\"), column_names_max_height = unit(150, \"cm\"))+\nHeatmap(X.D, rect_gp = gpar(col = \"black\"), name = \"Down\", cluster_rows = F, cluster_columns = F, col = blueCol_fun, row_names_side = \"left\", column_title = \"Down-regulated\", column_names_gp = gpar(fontsize = 14, fontface=\"bold\", col = colors[colnames(X.D)]), row_names_gp = gpar(fontsize = 14, fontface=\"bold\", col = FunCatPal[FunCat.annotation]), column_title_gp = gpar(fontsize = 18, fontface=\"bold\"), row_title_gp = gpar(fontsize = 18, fontface=\"bold\"), right_annotation = ha_rows, row_names_max_width = unit(150, \"cm\"), column_names_max_height = unit(150, \"cm\"))\ndev.off()\n\n```\n\n# Generate supplementary plots\n\n## Volcano plot\n### Excitatory neurons\n```{r}\nrequire(EnhancedVolcano)\n\nidx = grep(\"^Ex\", colnames(DE.new$DE.sc))\nGrobs = vector(\"list\", length(idx))\nfor(i in 1:length(idx)) {\n k = idx[[i]]\n df = data.frame(\"log2FoldChange\" = DE.new$logFC[, k], \"pvalue\" = 10^(-DE.new$logPvals[, k]))\n rownames(df) = rownames(DE.new$DE.sc)\n df = df[df$log2FoldChange != 0, ]\n \n keyvals <- rep('#cccccc', nrow(df))\n names(keyvals) <- rep('None', nrow(df))\n \n keyvals[which( (df$log2FoldChange > 0.1) & (df$pvalue < 0.05) )] <- '#ca0020'\n names(keyvals)[which( (df$log2FoldChange > 0.1) & (df$pvalue < 0.05) )] <- rep('Up', sum(keyvals == '#ca0020'))\n \n keyvals[which( (df$log2FoldChange < -0.1) & (df$pvalue < 0.05) )] <- '#0571b0'\n names(keyvals)[which( (df$log2FoldChange < -0.1) & (df$pvalue < 0.05) )] <- rep('Down', sum(keyvals == '#0571b0'))\n \n \n \n Grobs[[i]] = EnhancedVolcano(df,\n lab = rownames(df),\n x = 'log2FoldChange',\n y = 'pvalue', pCutoff = 0.05, FCcutoff = 0.1, xlim = c(-0.6, 0.6), ylim = c(0, 5), title = \"Excitatory neurons\", subtitle = colnames(DE.new$logFC)[[k]], colCustom = keyvals, labCol = 'black',\n labFace = 'bold', caption = \"\")\n} \n\n\npdf(file.path(figures.path, \"Supp\", \"Volcano_Ex.pdf\"), width = 8*4, height = 8*3)\n# png(file.path(figures.path, \"Supp\", \"Volcano_Ex.png\"), width = 2400, height = 1800, res = 150)\ngridExtra::grid.arrange( grobs = Grobs, nrow = 3)\ndev.off()\n\n```\n\n### Inhibitory neurons\n```{r}\nrequire(EnhancedVolcano)\n\n\nidx = grep(\"^In\", colnames(DE.new$DE.sc))\nGrobs = vector(\"list\", length(idx))\nfor(i in 1:length(idx)) {\n k = idx[[i]]\n df = data.frame(\"log2FoldChange\" = DE.new$logFC[, k], \"pvalue\" = 10^(-DE.new$logPvals[, k]))\n rownames(df) = rownames(DE.new$DE.sc)\n df = df[df$log2FoldChange != 0, ]\n \n keyvals <- rep('#cccccc', nrow(df))\n names(keyvals) <- rep('None', nrow(df))\n \n keyvals[which( (df$log2FoldChange > 0.1) & (df$pvalue < 0.05) )] <- '#ca0020'\n names(keyvals)[which( (df$log2FoldChange > 0.1) & (df$pvalue < 0.05) )] <- rep('Up', sum(keyvals == '#ca0020'))\n \n keyvals[which( (df$log2FoldChange < -0.1) & (df$pvalue < 0.05) )] <- '#0571b0'\n names(keyvals)[which( (df$log2FoldChange < -0.1) & (df$pvalue < 0.05) )] <- rep('Down', sum(keyvals == '#0571b0'))\n \n \n \n Grobs[[i]] = EnhancedVolcano(df,\n lab = rownames(df),\n x = 'log2FoldChange',\n y = 'pvalue', pCutoff = 0.05, FCcutoff = 0.1, xlim = c(-0.6, 0.6), ylim = c(0, 5), title = \"Inhibitory neurons\", subtitle = colnames(DE.new$logFC)[[k]], colCustom = keyvals, labCol = 'black',\n labFace = 'bold', caption = \"\")\n} \n\n\n\npdf(file.path(figures.path, \"Supp\", \"Volcano_In.pdf\"), width = 8*4, height = 8*2)\n# png(file.path(figures.path, \"Supp\", \"Volcano_Ex.png\"), width = 2400, height = 1800, res = 150)\ngridExtra::grid.arrange( grobs = Grobs, nrow = 2)\ndev.off()\n\n\n```\n\n### Glial cell types\n```{r}\nrequire(EnhancedVolcano)\n\n\nidx = which(!grepl(\"^In|^Ex\", colnames(DE.new$DE.sc)))\nGrobs = vector(\"list\", length(idx))\nfor(i in 1:length(idx)) {\n k = idx[[i]]\n df = data.frame(\"log2FoldChange\" = DE.new$logFC[, k], \"pvalue\" = 10^(-DE.new$logPvals[, k]))\n rownames(df) = rownames(DE.new$DE.sc)\n df = df[df$log2FoldChange != 0, ]\n \n keyvals <- rep('#cccccc', nrow(df))\n names(keyvals) <- rep('None', nrow(df))\n \n keyvals[which( (df$log2FoldChange > 0.1) & (df$pvalue < 0.05) )] <- '#ca0020'\n names(keyvals)[which( (df$log2FoldChange > 0.1) & (df$pvalue < 0.05) )] <- rep('Up', sum(keyvals == '#ca0020'))\n \n keyvals[which( (df$log2FoldChange < -0.1) & (df$pvalue < 0.05) )] <- '#0571b0'\n names(keyvals)[which( (df$log2FoldChange < -0.1) & (df$pvalue < 0.05) )] <- rep('Down', sum(keyvals == '#0571b0'))\n \n \n \n Grobs[[i]] = EnhancedVolcano(df,\n lab = rownames(df),\n x = 'log2FoldChange',\n y = 'pvalue', pCutoff = 0.05, FCcutoff = 0.1, xlim = c(-0.6, 0.6), ylim = c(0, 5), title = \"Non-neuronal\", subtitle = colnames(DE.new$logFC)[[k]], colCustom = keyvals, labCol = 'black',\n labFace = 'bold', caption = \"\")\n} \n\npdf(file.path(figures.path, \"Supp\", \"Volcano_Glial.pdf\"), width = 8*3, height = 8*1)\n# png(file.path(figures.path, \"Supp\", \"Volcano_Ex.png\"), width = 2400, height = 1800, res = 150)\ngridExtra::grid.arrange( grobs = Grobs, nrow = 1)\ndev.off()\n\n\n```\n\n# Functional enrichment (v2.0)\n## Perform functional enrichment using gProfiler\n```{r}\nGS = c(Up.genes, Down.genes)\nnames(GS) = c(paste(\"Up_\", names(Up.genes), sep = \"\"),paste(\"Down_\", names(Down.genes), sep = \"\"))\n\nDE.gp = gprofiler2::gost(GS, exclude_iea = TRUE, multi_query = T, source = c(\"GO:BP\"))\nreadr::write_rds(DE.gp, file.path(dataset.path, \"DE_gProfiler_enrichment.rds\"))\n\ntbl = DE.gp$result[ -11]\nUp.DE.tbls = lapply(1:20, function(k) {\n print(k)\n parts = apply(tbl, 2, function(x) {\n if(min(sapply(x, length)) > 1) {\n z = lapply(x, function(y) y[[k]])\n } else {\n return(x)\n }\n })\n \n sub.tbl = as.data.frame(do.call(cbind, parts))\n sub.tbl = sub.tbl[order(as.numeric(sub.tbl$p_values)), ]\n sub.tbl = sub.tbl[sub.tbl$significant == T, ]\n \n return(sub.tbl)\n})\nnames(Up.DE.tbls) = names(Up.genes)\nUp.DE.tbls = Up.DE.tbls[sapply(Up.DE.tbls, nrow) > 0]\n\nDown.DE.tbls = lapply(21:40, function(k) {\n print(k)\n parts = apply(tbl, 2, function(x) {\n if(min(sapply(x, length)) > 1) {\n z = lapply(x, function(y) y[[k]])\n } else {\n return(x)\n }\n })\n \n sub.tbl = as.data.frame(do.call(cbind, parts))\n sub.tbl = sub.tbl[order(as.numeric(sub.tbl$p_values)), ]\n sub.tbl = sub.tbl[sub.tbl$significant == T, ]\n \n return(sub.tbl)\n})\nnames(Down.DE.tbls) = names(Down.genes)\nDown.DE.tbls = Down.DE.tbls[sapply(Down.DE.tbls, nrow) > 0]\n\n\n```\n\n\n## Export gProfiler results as excel tables\n```{r}\nUp.wb <- createWorkbook()\nfor(i in 1:length(Up.DE.tbls)) {\n res = Up.DE.tbls[[i]]\n n = names(Up.DE.tbls)[[i]]\n \n addWorksheet(wb=Up.wb, sheetName = n)\n writeData(Up.wb, sheet = n, res) \n\n}\nsaveWorkbook(Up.wb, file.path(tables.path, \"Up_DE_gProfiler.xlsx\"), overwrite = TRUE)\n\n\nDown.wb <- createWorkbook()\nfor(i in 1:length(Down.DE.tbls)) {\n res = Down.DE.tbls[[i]]\n n = names(Down.DE.tbls)[[i]]\n \n addWorksheet(wb=Down.wb, sheetName = n)\n writeData(Down.wb, sheet = n, res) \n\n}\nsaveWorkbook(Down.wb, file.path(tables.path, \"Down_DE_gProfiler.xlsx\"), overwrite = TRUE)\n\n```\n\n## Identify meta-terms / GO clusters\nNeurodevelopment\nRegulation of AMPA receptor activity/regulation of NMDA receptor activity\nSynaptic signaling\nOxidative phosphorylation\nSynapse organization\nChaperone-mediated autophagy\nResponse to axon injury/response to heat\nRegulation of postsynaptic membrane potential\nLearning/memory\nCognition\n[Regulation of catalytic activity]\nNegative regulation of apoptosis\n\n\n```{r}\nmin.GO.size = 3\n\nDE.gp.enrichment = -log10(t(do.call(cbind, DE.gp$result$p_values)))\nrownames(DE.gp.enrichment) = DE.gp$result$term_id\n\nlibrary(simplifyEnrichment)\nGOSemSim = GO_similarity(DE.gp$result$term_id, ont = \"BP\")\n\n\nset.seed(0)\npdf(file.path(figures.path, \"DE_gp_SemSim_min3.pdf\"), width = 10)\nGOdf = simplifyGO(GOSemSim, min_term = min.GO.size, order_by_size = T)\ndev.off()\n\ncl.size = sapply(split(1:nrow(GOdf), GOdf$cluster), length)\nGOdf$cluster = factor(GOdf$cluster, order(cl.size, decreasing = T))\n\nGOdf2 = GOdf[order(GOdf$cluster), ]\nGOdf2 = GOdf2[GOdf2$cluster %in% which(cl.size >= min.GO.size), ]\n\nGOdf2$GO_module = match(GOdf2$cluster, unique(GOdf2$cluster))\nGOdf2$max_enrichment = apply(DE.gp.enrichment[GOdf2$id, ], 1, max)\n\nwrite.table(GOdf2, file.path(tables.path, \"Combined_DE_BP_clusters_min3.tsv\"), sep = \"\\t\", row.names = F, col.names = T, quote = F)\n\n```\n\n\n\n## Combine enrichment of terms within each GO cluster\n```{r}\nIDX = split(GOdf2$id, GOdf2$GO_module)\ncombined_enrichment = do.call(rbind, lapply(IDX, function(idx) combine.logPvals(DE.gp.enrichment[idx, ])))\ncombined_enrichment[combined_enrichment < 0] = 0\ncombined_enrichment.corrected = -log10(matrix(p.adjust(10^(-combined_enrichment)), ncol = 40))\n# combined_enrichment.corrected = -log10(apply(10^(-combined_enrichment), 2, function(p) p.adjust(p, \"fdr\")))\n\ncombined_enrichment.corrected[combined_enrichment.corrected < -log10(0.05)] = 0\n\ncombined_enrichment.corrected.up = combined_enrichment.corrected[, 1:20]\ncolnames(combined_enrichment.corrected.up) = names(Up.genes)\ncombined_enrichment.corrected.up = combined_enrichment.corrected.up[, fast_column_sums(combined_enrichment.corrected.up) > 0]\n\ncombined_enrichment.corrected.down = combined_enrichment.corrected[, 21:40]\ncolnames(combined_enrichment.corrected.down) = names(Down.genes)\ncombined_enrichment.corrected.down = combined_enrichment.corrected.down[, fast_column_sums(combined_enrichment.corrected.down) > 0]\n\n\nha_rows = rowAnnotation(df = list(\"Class\" = FunCat.annotation), col = list(\"Class\" = FunCatPal), annotation_legend_param = list(\"Class\"=list(title_gp = gpar(fontsize = 0), labels_gp = gpar(fontsize = 10))))\n\nannots = c(\"Neurodevelopment\", \"Glutamate signaling\", \"Synaptic transmission\", \"Oxidative phosphorylation\", \"Synapse organization\", \"Autophagy\", \"Cellular stress response\", \"Postsynaptic organization\", \"Learning / Memory\", \"Cognition\", \"Catalytic activity\", \"Apoptosis\")\n\nX.U = (combined_enrichment.corrected.up)\nredCol_fun = circlize::colorRamp2(c(0, exp(quantile(log(X.U)[X.U > -log10(0.05)], seq(0.05, 0.95, length.out = 12)))), c(\"#ffffff\", pals::brewer.reds(12)))\n\nX.D = (combined_enrichment.corrected.down)\nblueCol_fun = circlize::colorRamp2(c(0, exp(quantile(log(X.D)[X.D > -log10(0.05)], seq(0.05, 0.95, length.out = 12)))), c(\"#ffffff\", pals::brewer.blues(12)))\n\nrow.names(X.U) = rownames(X.D) = annots\n\npdf(file.path(figures.path, \"DE_gProfiler_Simplified_annotated.pdf\"), width = 6.5, height = 5)\npar(mar=c(0,150,0,0))\nHeatmap(X.U, rect_gp = gpar(col = \"black\"), name = \"Up\", column_title = \"Up\", cluster_rows = F, cluster_columns = F, col = redCol_fun, row_names_side = \"left\", column_names_gp = gpar(fontsize = 14, fontface=\"bold\", col = colors[colnames(X.U)]), row_names_gp = gpar(fontsize = 14, fontface=\"bold\"), column_title_gp = gpar(fontsize = 18, fontface=\"bold\"), row_title_gp = gpar(fontsize = 18, fontface=\"bold\"), row_names_max_width = unit(150, \"cm\"), column_names_max_height = unit(150, \"cm\"))+\nHeatmap(X.D, rect_gp = gpar(col = \"black\"), name = \"Down\", cluster_rows = F, cluster_columns = F, col = blueCol_fun, row_names_side = \"left\", column_title = \"Down\", column_names_gp = gpar(fontsize = 14, fontface=\"bold\", col = colors[colnames(X.D)]), row_names_gp = gpar(fontsize = 14, fontface=\"bold\"), column_title_gp = gpar(fontsize = 18, fontface=\"bold\"), row_title_gp = gpar(fontsize = 18, fontface=\"bold\"), row_names_max_width = unit(150, \"cm\"), column_names_max_height = unit(150, \"cm\"))\ndev.off()\n\n\n```\n\n\n\n\n" }, { "alpha_fraction": 0.6452512145042419, "alphanum_fraction": 0.6708817481994629, "avg_line_length": 36.69486999511719, "blob_id": "66360dc259a4f149dda268d6618ca273b26f38ca", "content_id": "f227bb20931e0f3e1016ab17ffccfa524d07c535", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 14709, "license_type": "no_license", "max_line_length": 495, "num_lines": 390, "path": "/AnalyzeDE.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"Analyze DE geens\"\nsubtitle: \"\"\nauthor: \"Shahin Mohammadi\"\ndate: \"Run on `r Sys.time()`\"\ndocumentclass: article\noutput:\n html_document:\n toc: true\n toc_float: true\n---\n\n```{r setup, include=FALSE}\nsuppressPackageStartupMessages({\nlibrary(ACTIONet)\nlibrary(data.table)\nlibrary(ggplot2)\nlibrary(ggrepel)\nlibrary(cowplot)\nlibrary(corrplot)\nlibrary(limma)\nlibrary(muscat)\nlibrary(metafor)\nlibrary(ggcorrplot)\nlibrary(openxlsx)\nlibrary(simplifyEnrichment)\nlibrary(synapser)\nlibrary(synExtra)\nsynLogin(rememberMe = TRUE)\nsource(\"functions.R\")\n})\n\nknitr::opts_chunk$set(\n\terror = FALSE,\n\tmessage = FALSE,\n\twarning = FALSE,\n\tcache = TRUE,\n\tdev = c(\"png\", \"pdf\"),\n\tinclude = FALSE,\n\ttidy = FALSE\n)\n```\n\n\n# Setup environment\n```{r}\ndataset.path = \"~/results/datasets/\"\nfigures.path = \"~/results/figures\"\ntables.path = \"~/results/tables\"\ninput.path = \"~/results/input\"\n\n# Load pseudobulk samples\npb.logcounts = loadDataset(\"pseudobulk_mean_logcounts\", dataset.path = dataset.path)\nACTIONet_summary = loadDataset(\"ACTIONet_summary\", dataset.path = dataset.path)\ncolors = loadDataset(\"celltype_colors\", dataset.path = dataset.path)\n\nSZ.genes = loadInputDataset(\"SCZ_associated_genesets\", extension = \"rds\")\n\nDE.new = loadDataset(\"DE_genes_pseudobulk\", dataset.path = dataset.path)\nUp.genes = DE.new$Up.genes\nDown.genes = DE.new$Down.genes\nDE.sc = DE.new$DE.sc\n\nX = cbind(sapply(DE.new$Up.genes, length),sapply(DE.new$Down.genes, length))\nordered.celltypes = rownames(X)[order(apply(X, 1, sum), decreasing = T)]\n\n```\n\n\n\n\n# Compute overlap of selected DE genes with bulk (PEC)\n```{r}\nUp.genes.overlap = sapply(Up.genes, function(gs) intersect(gs, SZ.genes$`DE.Up (PEC)`))\nUp.genes.size = sapply(Up.genes.overlap, length) \nUp.En = assess.genesets(Up.genes[ordered.celltypes], SZ.genes[c(5, 6)], nrow(pb.logcounts), correct = \"local\")[, 1]\n\nDown.genes.overlap = sapply(Down.genes, function(gs) intersect(gs, SZ.genes$`DE.Down (PEC)`))\nDown.genes.size = sapply(Down.genes.overlap, length) \nDown.En = assess.genesets(Down.genes[ordered.celltypes], SZ.genes[c(5, 6)], nrow(pb.logcounts), correct = \"local\")[, 2]\n\n\nDE.overlap.tbl = data.frame(Celltype = ordered.celltypes, Up = sapply(Up.genes[ordered.celltypes], length), Up_vs_bulk_count = Up.genes.size, Up_vs_bulk_enrichment = Up.En, Down = sapply(Down.genes[ordered.celltypes], length), Down_vs_bulk_count = Down.genes.size, Down_vs_bulk_enrichment = Down.En)\n\nstoreTable(list(DE_vs_bulk = DE.overlap.tbl), \"DE_vs_bulk_overlap\", tables.path = tables.path)\n\n```\n\n\n# Plot the total number of DE genes\n```{r}\ncelltype.colors = colors[names(Up.genes)]\n# names(celltype.colors) = names(Up.genes)\n\ndf.Up = data.frame(Counts = sapply(Up.genes, function(x) length(setdiff(x, SZ.genes$`DE.Up (PEC)`))), Celltype = names(Up.genes), Direction=\"Up\", Color = celltype.colors[names(Up.genes)], stringsAsFactors = F)\n\ndf.UpandBulk = data.frame(Counts = sapply(Up.genes, function(x) length(intersect(x, SZ.genes$`DE.Up (PEC)`))), Celltype = names(Up.genes), Direction=\"Up & Bulk\", Color = celltype.colors[names(Up.genes)], stringsAsFactors = F)\n\n\ndf.Down = data.frame(Counts = -sapply(Down.genes, function(x) length(setdiff(x, SZ.genes$`DE.Down (PEC)`))), Celltype = names(Down.genes), Direction=\"Down\", Color = celltype.colors[names(Down.genes)], stringsAsFactors = F)\n\ndf.DownandBulk = data.frame(Counts = -sapply(Down.genes, function(x) length(intersect(x, SZ.genes$`DE.Down (PEC)`))), Celltype = names(Down.genes), Direction=\"Down & Bulk\", Color = celltype.colors[names(Down.genes)], stringsAsFactors = F)\n\n\n\ndf = rbind(df.Up, df.UpandBulk, df.Down, df.DownandBulk)\n\ntotal.Up = sapply(Up.genes, length)\ntotal.Down = sapply(Down.genes, length)\n\nset.seed(0)\n# total = total.Up + total.Down + 0.001*rnorm(length(Up.genes))\ntotal = apply(cbind(total.Up, total.Down), 1, max)\n\narch.perm = order(total, decreasing = F)\ndf$Celltype = factor(df$Celltype, rev(ordered.celltypes))\n\ngg = ggplot(data = df, aes(x = Celltype, y = Counts, fill = Direction)) + geom_bar(stat = \"identity\")+\n coord_flip()+ylab(\"Sorted Celltypes\")+\nlabs(y = \"# Genes\", x = \"Sorted Celltypes\")+\n theme_minimal()+\n guides(fill = FALSE)+ scale_fill_manual(values=c(\"#3288bd\", colorspace::darken(\"#3288bd\", 0.35), \"#d53e4f\", colorspace::darken(\"#d53e4f\", 0.35))) + theme(axis.text.y = element_text(face=\"bold\", color=celltype.colors[levels(df$Celltype)], size=12, angle=0), axis.text.x = element_text(face=\"bold\", color=\"black\", size=12, angle=0), axis.title = element_text(face=\"bold\", size=14, angle=0))\n\n\n\nstoreFigure(gg, name = \"NumDysregGenes\", extension = \"pdf\", width = 8, height = 5, figures.path = figures.path)\n\n```\n\n\n# Generate supplementary plots\n\n## Volcano plot\n### Excitatory neurons\n```{r}\nrequire(EnhancedVolcano)\n\nidx = grep(\"^Ex\", colnames(DE.new$DE.sc))\nGrobs = vector(\"list\", length(idx))\nfor(i in 1:length(idx)) {\n k = idx[[i]]\n df = data.frame(\"log2FoldChange\" = DE.new$logFC[, k], \"pvalue\" = 10^(-DE.new$logPvals[, k]))\n rownames(df) = rownames(DE.new$DE.sc)\n df = df[df$log2FoldChange != 0, ]\n \n keyvals <- rep('#cccccc', nrow(df))\n names(keyvals) <- rep('None', nrow(df))\n \n keyvals[which( (df$log2FoldChange > 0.1) & (df$pvalue < 0.05) )] <- '#ca0020'\n names(keyvals)[which( (df$log2FoldChange > 0.1) & (df$pvalue < 0.05) )] <- rep('Up', sum(keyvals == '#ca0020'))\n \n keyvals[which( (df$log2FoldChange < -0.1) & (df$pvalue < 0.05) )] <- '#0571b0'\n names(keyvals)[which( (df$log2FoldChange < -0.1) & (df$pvalue < 0.05) )] <- rep('Down', sum(keyvals == '#0571b0'))\n \n \n \n Grobs[[i]] = EnhancedVolcano(df,\n lab = rownames(df),\n x = 'log2FoldChange',\n y = 'pvalue', pCutoff = 0.05, FCcutoff = 0.1, xlim = c(-0.6, 0.6), ylim = c(0, 5), title = \"Excitatory neurons\", subtitle = colnames(DE.new$logFC)[[k]], colCustom = keyvals, labCol = 'black',\n labFace = 'bold', caption = \"\")\n} \n\ngg <- gridExtra::marrangeGrob(grobs = Grobs, nrow = 3, ncol = 4)\n\nstoreFigure(gg, name = \"Volcano_Ex\", extension = \"pdf\", width = 8*4, height = 8*3, figures.path = figures.path)\n\n```\n\n### Inhibitory neurons\n```{r}\nrequire(EnhancedVolcano)\n\n\nidx = grep(\"^In\", colnames(DE.new$DE.sc))\nGrobs = vector(\"list\", length(idx))\nfor(i in 1:length(idx)) {\n k = idx[[i]]\n df = data.frame(\"log2FoldChange\" = DE.new$logFC[, k], \"pvalue\" = 10^(-DE.new$logPvals[, k]))\n rownames(df) = rownames(DE.new$DE.sc)\n df = df[df$log2FoldChange != 0, ]\n \n keyvals <- rep('#cccccc', nrow(df))\n names(keyvals) <- rep('None', nrow(df))\n \n keyvals[which( (df$log2FoldChange > 0.1) & (df$pvalue < 0.05) )] <- '#ca0020'\n names(keyvals)[which( (df$log2FoldChange > 0.1) & (df$pvalue < 0.05) )] <- rep('Up', sum(keyvals == '#ca0020'))\n \n keyvals[which( (df$log2FoldChange < -0.1) & (df$pvalue < 0.05) )] <- '#0571b0'\n names(keyvals)[which( (df$log2FoldChange < -0.1) & (df$pvalue < 0.05) )] <- rep('Down', sum(keyvals == '#0571b0'))\n \n \n \n Grobs[[i]] = EnhancedVolcano(df,\n lab = rownames(df),\n x = 'log2FoldChange',\n y = 'pvalue', pCutoff = 0.05, FCcutoff = 0.1, xlim = c(-0.6, 0.6), ylim = c(0, 5), title = \"Inhibitory neurons\", subtitle = colnames(DE.new$logFC)[[k]], colCustom = keyvals, labCol = 'black',\n labFace = 'bold', caption = \"\")\n} \n\n\ngg <- gridExtra::marrangeGrob(grobs = Grobs, nrow = 3, ncol = 3)\nstoreFigure(gg, name = \"Volcano_In\", extension = \"pdf\", width = 8*3, height = 8*3, figures.path = figures.path)\n\n\n```\n\n### Glial cell types\n```{r}\nrequire(EnhancedVolcano)\n\n\nidx = which(!grepl(\"^In|^Ex\", colnames(DE.new$DE.sc)))\nGrobs = vector(\"list\", length(idx))\nfor(i in 1:length(idx)) {\n k = idx[[i]]\n df = data.frame(\"log2FoldChange\" = DE.new$logFC[, k], \"pvalue\" = 10^(-DE.new$logPvals[, k]))\n rownames(df) = rownames(DE.new$DE.sc)\n df = df[df$log2FoldChange != 0, ]\n \n keyvals <- rep('#cccccc', nrow(df))\n names(keyvals) <- rep('None', nrow(df))\n \n keyvals[which( (df$log2FoldChange > 0.1) & (df$pvalue < 0.05) )] <- '#ca0020'\n names(keyvals)[which( (df$log2FoldChange > 0.1) & (df$pvalue < 0.05) )] <- rep('Up', sum(keyvals == '#ca0020'))\n \n keyvals[which( (df$log2FoldChange < -0.1) & (df$pvalue < 0.05) )] <- '#0571b0'\n names(keyvals)[which( (df$log2FoldChange < -0.1) & (df$pvalue < 0.05) )] <- rep('Down', sum(keyvals == '#0571b0'))\n \n \n \n Grobs[[i]] = EnhancedVolcano(df,\n lab = rownames(df),\n x = 'log2FoldChange',\n y = 'pvalue', pCutoff = 0.05, FCcutoff = 0.1, xlim = c(-0.6, 0.6), ylim = c(0, 5), title = \"Non-neuronal\", subtitle = colnames(DE.new$logFC)[[k]], colCustom = keyvals, labCol = 'black',\n labFace = 'bold', caption = \"\")\n} \n\ngg <- gridExtra::marrangeGrob(grobs = Grobs, nrow = 3, ncol = 4)\nstoreFigure(gg, name = \"Volcano_Glial\", extension = \"pdf\", width = 8*3, height = 8*1, figures.path = figures.path)\n\n\n```\n\n# Functional enrichment\n## Perform functional enrichment using gProfiler\n```{r}\nGS = c(Up.genes, Down.genes)\nnames(GS) = c(paste(\"Up_\", names(Up.genes), sep = \"\"),paste(\"Down_\", names(Down.genes), sep = \"\"))\n\nDE.gp = gprofiler2::gost(GS, exclude_iea = TRUE, multi_query = T, source = c(\"GO:BP\"))\n\nstoreDataset(DE.gp, name = \"DE_gProfiler_enrichment\", dataset.path = dataset.path)\n\n\n```\n## Parse tables\n```{r}\ntbl = DE.gp$result[ -11]\nUp.DE.tbls = lapply(1:20, function(k) {\n print(k)\n parts = apply(tbl, 2, function(x) {\n if(min(sapply(x, length)) > 1) {\n z = lapply(x, function(y) y[[k]])\n } else {\n return(x)\n }\n })\n \n sub.tbl = as.data.frame(do.call(cbind, parts))\n sub.tbl = sub.tbl[order(as.numeric(sub.tbl$p_values)), ]\n sub.tbl = sub.tbl[sub.tbl$significant == T, ]\n \n return(sub.tbl)\n})\nnames(Up.DE.tbls) = names(Up.genes)\nUp.DE.tbls = Up.DE.tbls[sapply(Up.DE.tbls, nrow) > 0]\n\nDown.DE.tbls = lapply(21:40, function(k) {\n print(k)\n parts = apply(tbl, 2, function(x) {\n if(min(sapply(x, length)) > 1) {\n z = lapply(x, function(y) y[[k]])\n } else {\n return(x)\n }\n })\n \n sub.tbl = as.data.frame(do.call(cbind, parts))\n sub.tbl = sub.tbl[order(as.numeric(sub.tbl$p_values)), ]\n sub.tbl = sub.tbl[sub.tbl$significant == T, ]\n \n return(sub.tbl)\n})\nnames(Down.DE.tbls) = names(Down.genes)\nDown.DE.tbls = Down.DE.tbls[sapply(Down.DE.tbls, nrow) > 0]\n\n\n```\n\n\n## Export gProfiler results as excel tables\n```{r}\nstoreTable(Up.DE.tbls, name = \"Up_DE_gProfiler\", tables.path = tables.path)\nstoreTable(Down.DE.tbls, name = \"Down_DE_gProfiler\", tables.path = tables.path)\n\n```\n\n## Identify meta-terms / GO clusters\nNeurodevelopment\nRegulation of AMPA receptor activity/regulation of NMDA receptor activity\nSynaptic signaling\nOxidative phosphorylation\nSynapse organization\nChaperone-mediated autophagy\nResponse to axon injury/response to heat\nRegulation of postsynaptic membrane potential\nLearning/memory\nCognition\n[Regulation of catalytic activity]\nNegative regulation of apoptosis\n\n## Identify GO clusters\n```{r}\nmin.GO.size = 3\n\nDE.gp.enrichment = -log10(t(do.call(cbind, DE.gp$result$p_values)))\nrownames(DE.gp.enrichment) = DE.gp$result$term_id\n\nGOSemSim = GO_similarity(DE.gp$result$term_id, ont = \"BP\")\n\n\nset.seed(0)\n# pdf(file.path(figures.path, \"DE_gp_SemSim_min3.pdf\"), width = 10)\nGOdf = simplifyGO(GOSemSim, min_term = min.GO.size, order_by_size = T)\n# dev.off()\n\ncl.size = sapply(split(1:nrow(GOdf), GOdf$cluster), length)\nGOdf$cluster = factor(GOdf$cluster, order(cl.size, decreasing = T))\n\nGOdf2 = GOdf[order(GOdf$cluster), ]\nGOdf2 = GOdf2[GOdf2$cluster %in% which(cl.size >= min.GO.size), ]\n\nGOdf2$GO_module = match(GOdf2$cluster, unique(GOdf2$cluster))\nGOdf2$max_enrichment = apply(DE.gp.enrichment[GOdf2$id, ], 1, max)\n\nstoreTable(list(GO = GOdf2), \"Combined_DE_BP_clusters_min3\", tables.path = tables.path)\n\n```\n\n\n\n## Combine enrichment of terms within each GO cluster\n```{r}\nIDX = split(GOdf2$id, GOdf2$GO_module)\ncombined_enrichment = do.call(rbind, lapply(IDX, function(idx) combine.logPvals(DE.gp.enrichment[idx, ])))\ncombined_enrichment[combined_enrichment < 0] = 0\ncombined_enrichment.corrected = -log10(matrix(p.adjust(10^(-combined_enrichment)), ncol = 40))\n# combined_enrichment.corrected = -log10(apply(10^(-combined_enrichment), 2, function(p) p.adjust(p, \"fdr\")))\n\ncombined_enrichment.corrected[combined_enrichment.corrected < -log10(0.05)] = 0\n\ncombined_enrichment.corrected.up = combined_enrichment.corrected[, 1:20]\ncolnames(combined_enrichment.corrected.up) = names(Up.genes)\ncombined_enrichment.corrected.up = combined_enrichment.corrected.up[, fast_column_sums(combined_enrichment.corrected.up) > 0]\n\ncombined_enrichment.corrected.down = combined_enrichment.corrected[, 21:40]\ncolnames(combined_enrichment.corrected.down) = names(Down.genes)\ncombined_enrichment.corrected.down = combined_enrichment.corrected.down[, fast_column_sums(combined_enrichment.corrected.down) > 0]\n\n# \n# ha_rows = rowAnnotation(df = list(\"Class\" = FunCat.annotation), col = list(\"Class\" = FunCatPal), annotation_legend_param = list(\"Class\"=list(title_gp = gpar(fontsize = 0), labels_gp = gpar(fontsize = 10))))\n\nannots = c(\"Neurodevelopment\", \"Glutamate signaling\", \"Synaptic transmission\", \"Oxidative phosphorylation\", \"Synapse organization\", \"Autophagy\", \"Cellular stress response\", \"Postsynaptic organization\", \"Learning / Memory\", \"Cognition\", \"Catalytic activity\", \"Apoptosis\")\n\nX.U = (combined_enrichment.corrected.up)\nredCol_fun = circlize::colorRamp2(c(0, exp(quantile(log(X.U)[X.U > -log10(0.05)], seq(0.05, 0.95, length.out = 12)))), c(\"#ffffff\", pals::brewer.reds(12)))\n\nX.D = (combined_enrichment.corrected.down)\nblueCol_fun = circlize::colorRamp2(c(0, exp(quantile(log(X.D)[X.D > -log10(0.05)], seq(0.05, 0.95, length.out = 12)))), c(\"#ffffff\", pals::brewer.blues(12)))\n\nrow.names(X.U) = rownames(X.D) = annots\n\nht = Heatmap(X.U, rect_gp = gpar(col = \"black\"), name = \"Up\", column_title = \"Up\", cluster_rows = F, cluster_columns = F, col = redCol_fun, row_names_side = \"left\", column_names_gp = gpar(fontsize = 14, fontface=\"bold\", col = colors[colnames(X.U)]), row_names_gp = gpar(fontsize = 14, fontface=\"bold\"), column_title_gp = gpar(fontsize = 18, fontface=\"bold\"), row_title_gp = gpar(fontsize = 18, fontface=\"bold\"), row_names_max_width = unit(150, \"cm\"), column_names_max_height = unit(150, \"cm\"))+\nHeatmap(X.D, rect_gp = gpar(col = \"black\"), name = \"Down\", cluster_rows = F, cluster_columns = F, col = blueCol_fun, row_names_side = \"left\", column_title = \"Down\", column_names_gp = gpar(fontsize = 14, fontface=\"bold\", col = colors[colnames(X.D)]), row_names_gp = gpar(fontsize = 14, fontface=\"bold\"), column_title_gp = gpar(fontsize = 18, fontface=\"bold\"), row_title_gp = gpar(fontsize = 18, fontface=\"bold\"), row_names_max_width = unit(150, \"cm\"), column_names_max_height = unit(150, \"cm\"))\n\nstoreFigure(ht, name = \"DE_gProfiler_Simplified_annotated\", extension = \"pdf\", width = 6.5, height = 5, figures.path = figures.path)\n\n\n```\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.647489607334137, "alphanum_fraction": 0.6748758554458618, "avg_line_length": 35.05063247680664, "blob_id": "09160ebe2df4c0aec2bc4fa4849b879a1ed0c98f", "content_id": "12f09a5a3bd7f30fcf0fdc1a7bc5367c3087f9b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 19937, "license_type": "no_license", "max_line_length": 523, "num_lines": 553, "path": "/ancient/Fig4_Cellstates.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"Assess significance and relevance of cell states/archetypes\"\noutput: html_notebook\n---\n\n# Setup\n```{r include=FALSE}\nrequire(ACTIONet)\nrequire(stringr)\nrequire(ComplexHeatmap)\n\n\ndataset.path = \"~/results/datasets/\"\nresults.path = \"~/results\"\nfigures.folder = \"~/results/figures\"\ninput.folder = \"~/results/input\"\n\n\n```\n\n\n## Enrichment function\n```{r}\nassess.genesets <-function (arch.gs, terms.gs, N, min.pval = 1e-100, correct = \"none\"){\n shared = t(sapply(terms.gs, function(gs1) {\n sapply(arch.gs, function(gs2) {\n nn = intersect(gs1, gs2)\n })\n }))\n colnames(shared) = names(arch.gs)\n GS.sizes = sapply(terms.gs, length)\n logPvals.out = sapply(1:ncol(shared), function(i) {\n gg = shared[, i]\n x = as.numeric(sapply(gg, length))\n n.sample = length(arch.gs[[i]])\n n.success = as.numeric(GS.sizes)\n v = rep(1, length(x))\n min.overlap = n.success * n.sample/N\n idx = which(x >= min.overlap)\n if (length(idx) == 0) \n return(v)\n v[idx] = (phyper(x[idx]-1, n.sample, N-n.sample, n.success[idx], lower.tail = F))\n # v[idx] = HGT_tail(population.size = N, success.count = n.success[idx], \n # sample.size = n.sample, observed.success = x[idx])\n return(v)\n })\n if(correct == \"global\") {\n logPvals.out = matrix(p.adjust(logPvals.out, \"fdr\"), nrow = nrow(logPvals.out))\n } else if(correct == \"local\") {\n logPvals.out = apply(logPvals.out, 2, function(x) p.adjust(x, \"fdr\"))\n }\n rownames(logPvals.out) = names(terms.gs)\n colnames(logPvals.out) = names(arch.gs)\n return(-log10(Matrix::t(logPvals.out)))\n}\n\n\nassess.geneset.enrichment.from.archetypes <- function (ace, associations, min.counts = 0, specificity.slot = \"unified_feature_specificity\") \n{\n if(is.matrix(ace) | is.sparseMatrix(ace)) {\n scores = as.matrix(ace)\n } else {\n scores = rowMaps(ace)[[specificity.slot]] \n }\n if (max(scores) > 100) {\n scores = log1p(scores)\n }\n if (is.list(associations)) {\n associations = sapply(associations, function(gs) as.numeric(rownames(scores) %in% \n gs))\n rownames(associations) = rownames(scores)\n }\n common.features = intersect(rownames(associations), rownames(scores))\n rows = match(common.features, rownames(associations))\n associations = as(associations[rows, ], \"dgCMatrix\")\n scores = scores[common.features, ]\n enrichment.out = assess_enrichment(scores, associations)\n rownames(enrichment.out$logPvals) = colnames(associations)\n rownames(enrichment.out$thresholds) = colnames(associations)\n enrichment.out$scores = scores\n return(enrichment.out)\n}\n\nannotate_H_with_markers <- function (ace, markers, features_use = NULL, significance_slot = \"unified_feature_specificity\") \n{\n features_use = ACTIONet:::.preprocess_annotation_features(ace, features_use)\n marker_mat = ACTIONet:::.preprocess_annotation_markers(markers, features_use)\n marker_stats = Matrix::t(assess.geneset.enrichment.from.archetypes(ace, \n marker_mat)$logPvals)\n colnames(marker_stats) = colnames(marker_mat)\n marker_stats[!is.finite(marker_stats)] = 0\n annots = colnames(marker_mat)[apply(marker_stats, 1, which.max)]\n conf = apply(marker_stats, 1, max)\n out = list(Label = annots, Confidence = conf, Enrichment = marker_stats)\n return(out)\n}\n\n\n```\n\n# Load primary datasets\n```{r, eval = T}\nACTIONet_summary = readr::read_rds(file.path(dataset.path, \"ACTIONet_summary_filtered_individuals.rds\"))\n\npb.logcounts = readr::read_rds(file.path(dataset.path, \"PB_mean_logcounts_final.RDS\"))\n\ncolor.df = readRDS(file.path(dataset.path, \"celltype_colors.rds\"))\n\ncolors = color.df$color\nnames(colors) = color.df$celltype\n\n```\n\n# Load DE results\n```{r, eval = F}\nresDE = readr::read_rds(file.path(dataset.path, \"Cohort_specific_DE_results_final_wit_logumi_baseline_full_filter_extended_cell_filtering.rds\"))\n\nfiltered.tables = readr::read_rds(file.path(dataset.path, \"individual_diff_results_filtered_full_wit_logumi_baseline_full_filter_extended_cell_filtering.rds\"))\n\nDE.new = readRDS(file.path(dataset.path, \"DE_genes_pseudobulk_final_wit_logumi_baseline_full_filter_extended_cell_filtering.rds\"))\n\nUp.genes = DE.new$Up.genes\nDown.genes = DE.new$Down.genes\n\n```\n\n\n\n```{r}\ngene.spec = ACTIONet_summary$unified_feature_specificity\n\ngs = DE.new$Up.genes\nscores = (gene.spec)\nrequire(fgsea)\nUp.enrichment = sapply(gs, function(genes) {\n l = as.numeric(rownames(scores) %in% genes)\n print(sum(l))\n pvals = apply(scores, 2, function(x) {\n perm = order(x, decreasing = T)\n sorted.l = l[perm]\n mhg.out = mhg::mhg_test(sorted.l, length(l), sum(l), length(l)/4, 5, upper_bound = F, tol = 1e-300) \n mhg.out$pvalue\n })\n pvals[is.na(pvals)] = 1\n -log10(pvals)\n\n # gsea.out = fgsea(gs, x)\n # -log10(gsea.out$padj)\n})\nHeatmap(Up.enrichment)\n\n\n\n\ngs = DE.new$Down.genes\nscores = (gene.spec)\nrequire(fgsea)\nDown.enrichment = sapply(gs, function(genes) {\n l = as.numeric(rownames(scores) %in% genes)\n print(sum(l))\n pvals = apply(scores, 2, function(x) {\n perm = order(x, decreasing = T)\n sorted.l = l[perm]\n mhg.out = mhg::mhg_test(sorted.l, length(l), sum(l), length(l)/4, 5, upper_bound = F, tol = 1e-300) \n mhg.out$pvalue\n })\n pvals[is.na(pvals)] = 1\n -log10(pvals)\n\n # gsea.out = fgsea(gs, x)\n # -log10(gsea.out$padj)\n})\nHeatmap(Down.enrichment)\n\n\n\narch.enrichment.DE.up = annotate.profile.using.markers(log1p(t(gene.spec)), )\n\n# arch.enrichment.DE.up = annotate.profile.using.markers(log1p(t(gene.spec)), DE.new$Up.genes)\n# arch.enrichment.DE.up = arch.enrichment.DE.up$Enrichment\n# \n# arch.enrichment.DE.down = annotate.profile.using.markers(log1p(t(gene.spec)), DE.new$Down.genes)\n# arch.enrichment.DE.down = arch.enrichment.DE.down$Enrichment\n# \n# arch.enrichment.DE.up[abs(arch.enrichment.DE.up) < 3] = 0\n# arch.enrichment.DE.down[abs(arch.enrichment.DE.down) < 3] = 0\n# Heatmap(arch.enrichment.DE.up) + Heatmap(arch.enrichment.DE.down) \n\n\narch.enrichment.phenotype = presto::wilcoxauc(t(ACTIONet_summary$H_unified), ACTIONet_summary$metadata$Phenotype)\narch.enrichment.phenotype = matrix(arch.enrichment.phenotype$auc-0.5, nrow=ncol(ACTIONet_summary$H_unified))\nrownames(arch.enrichment.phenotype) = paste(\"A\", 1:nrow(arch.enrichment.phenotype), sep = \"\")\ncolnames(arch.enrichment.phenotype) = levels(ACTIONet_summary$metadata$Phenotype)\n\narch.enrichment.ind = presto::wilcoxauc(t(ACTIONet_summary$H_unified), ACTIONet_summary$metadata$Individual)\narch.enrichment.ind = matrix(arch.enrichment.ind$auc-0.5, nrow=ncol(ACTIONet_summary$H_unified))\nrownames(arch.enrichment.ind) = paste(\"A\", 1:nrow(arch.enrichment.ind), sep = \"\")\n\n\n\n# Ll = as.character(ACTIONet_summary$metadata$Labels)\n# Ll[grep(\"^In\", Ll)] = \"In\"\n# Ll[grep(\"^Ex\", Ll)] = \"Ex\"\n# Ll = factor(Ll)\narch.enrichment.celltype = presto::wilcoxauc(t(ACTIONet_summary$H_unified), ACTIONet_summary$metadata$Labels)\nrn = unique(arch.enrichment.celltype$group)\narch.enrichment.celltype = matrix(arch.enrichment.celltype$auc-0.5, nrow=ncol(ACTIONet_summary$H_unified))\nrownames(arch.enrichment.celltype) = paste(\"A\", 1:nrow(arch.enrichment.celltype), sep = \"\")\ncolnames(arch.enrichment.celltype) = rn\n\nX = as.matrix(ACTIONet_summary$H_unified)\nY = cbind(ACTIONet_summary$metadata$umi_count, ACTIONet_summary$metadata$gene_counts, ACTIONet_summary$metadata$mito_perc)\narch.enrichment.geneumi = cor(X, Y)\ncolnames(arch.enrichment.geneumi) = c(\"UMIs\", \"Genes\", \"Mito %\")\n\nHeatmap(arch.enrichment.phenotype) + Heatmap(arch.enrichment.ind) + Heatmap(arch.enrichment.celltype)\n\n\n\n\n\n```\n\n\n\n\n```{r}\nncells = sapply(int_colData(pb.logcounts)$n_cells, as.numeric)\nrownames(ncells) = names(assays(pb.logcounts))\n\ncs = Matrix::colSums(ncells)\nncells.freq = 100*scale(ncells, center = F, scale = cs)\nEx.perc = (fast_column_sums(ncells.freq[grepl(\"^Ex\", rownames(ncells.freq)) & !grepl(\"^Ex-NRGN\", rownames(ncells.freq)), ]))\n\nselected.samples = which((Ex.perc >= 10) & (Ex.perc <= 80))\n\npb.logcounts.filtered = pb.logcounts [, selected.samples]\n\n```\n\n\n```{r}\nEn = annotate.archetypes.using.labels(t(ACTIONet_summary$H_unified), ACTIONet_summary$metadata$Phenotype)\nperm = order(En$Enrichment[, 1], decreasing = T)\n\nHeatmap(En$Enrichment)\n\n```\n\n```{r}\n\narch.sig.avg = as.matrix(sample.meta[, 33:36])\nmed.mat = as.matrix(sample.meta[, 17:22])\n\nArch.vs.Med.enrichment = apply(arch.sig.avg, 2, function(sig) {\n perm = order(sig, decreasing = T)\n X = med.mat[perm, ]\n logPvals = apply(X, 2, function(x) {\n l = as.numeric(x != 0)\n mhg.out = mhg::mhg_test(l, length(l), sum(l), length(l), 1, upper_bound = F, tol = 1e-100)\n -log10(mhg.out$pvalue)\n })\n return(logPvals)\n})\nHeatmap(Arch.vs.Med.enrichment)\n\n(apply(arch.sig.avg, 2, function(x) cor(x, sample.meta$Age, method = \"spearman\")))\n\napply(arch.sig.avg, 2, function(x) cor.test(x, as.numeric(factor(sample.meta$Phenotype)), method = \"spearman\", use = \"complete.obs\")$p.value)\n\n\n```\n\n\n# Load PEC data\n```{r}\nPEC.expr.table = read.table(file.path(input.folder, \"DER-01_PEC_Gene_expression_matrix_normalized.txt\"), header = T)\nrownames(PEC.expr.table) = PEC.expr.table$gene_id\n\nPEC.expr.mat = as.matrix(PEC.expr.table[, -1])\n\n\nlibrary(org.Hs.eg.db)\ngg = as.character(sapply(PEC.expr.table$gene_id, function(str) str_split(str, fixed(\".\"))[[1]][[1]]))\nsuppressWarnings(ids <- AnnotationDbi::mapIds(org.Hs.eg.db, keys = gg, keytype = \"ENSEMBL\", column = \"SYMBOL\", multiVals = \"first\"))\nmask = !is.na(ids)\n\nPEC.expr.mat = PEC.expr.mat[mask, ]\nrownames(PEC.expr.mat) = ids[mask]\n\n\n\n\nPEC.expr.table.TPM = read.table(file.path(input.folder, \"DER-02_PEC_Gene_expression_matrix_TPM.txt\"), header = T)\nrownames(PEC.expr.table.TPM) = PEC.expr.table.TPM$GeneName\n\nPEC.expr.mat.TPM = as.matrix(PEC.expr.table.TPM[, -1])\n\n\nlibrary(org.Hs.eg.db)\nmask = !is.na(ids)\nsuppressWarnings(ids <- AnnotationDbi::mapIds(org.Hs.eg.db, keys = PEC.expr.table.TPM$GeneName, keytype = \"ENSEMBL\", column = \"SYMBOL\", multiVals = \"first\"))\n\nPEC.expr.mat.TPM = PEC.expr.mat.TPM[mask, ]\nrownames(PEC.expr.mat.TPM) = ids[mask]\n\n\n\n\n\ngg = sort(unique(intersect(rownames(PEC.expr.mat.TPM), rownames(PEC.expr.mat))))\ncc = sort(unique(intersect(colnames(PEC.expr.mat), colnames(PEC.expr.mat.TPM))))\n\nPEC.sce = SingleCellExperiment(assays = list(normexpr = PEC.expr.mat[gg, cc], TPM = PEC.expr.mat.TPM[gg, cc]))\n\n\nmeta.PEC.full = read.table(\"~/results/input/Job-138522884223735377851224577.tsv\", header = T, sep = \"\\t\")\n\n\nmeta.PEC = read.table(\"~/results/input/Job-138522891409304015015695443.tsv\", header = T, sep = \"\\t\")\nmask = meta.PEC$diagnosis %in% c(\"Control\", \"Schizophrenia\")\nmeta.PEC = meta.PEC[mask, ]\n\ncommon.samples = sort(unique(intersect((meta.PEC$individualID), (cc))))\n\nmeta.PEC.matched = meta.PEC[match(common.samples, meta.PEC$individualID), ]\nPEC.sce.matched = PEC.sce[, match(common.samples, colnames(PEC.sce))]\ncolData(PEC.sce.matched) = DataFrame(meta.PEC.matched)\ncolnames(PEC.sce.matched) = PEC.sce.matched$individualID\n\nreadr::write_rds(PEC.sce.matched, \"~/results/input/PEC_bulk_expression_SZandCON.rds\")\n\n```\n\n\n# A11 and A19 specific\n```{r}\n# 0 1 \n# 452 367\nSZ.mask = as.numeric(PEC.sce.matched$diagnosis == \"Schizophrenia\")\n\n\nX = assays(PEC.sce.matched)$normexpr\narch.gene.spec = ACTIONet_summary$unified_feature_specificity\n\ncg = intersect(rownames(X), rownames(arch.gene.spec))\nsubX = X[cg, ]\nsubArch = arch.gene.spec[cg, ]\n\nArch.cor = cor(subX, subArch)\n\narch.enrichment = apply(Arch.cor, 2, function(x) {\n perm = order(x, decreasing = T)\n l = SZ.mask[perm]\n mhg.out = mhg::mhg_test(l, length(l), sum(l), length(l), 1, upper_bound = F, tol = 1e-300)\n -log10(mhg.out$pvalue)\n})\nsort(round(arch.enrichment, 1), decreasing = T)\n# A30 A6 A26 A22 A19 A2 A29 A11 A15 A21 A16 A24 A7 A28 A1 A4 A12 A17 A27 A3 A5 A8 A9 A10 A13 A14 A18 A20 A23 A25 A31 \n# 8.0 6.0 3.2 1.8 1.7 1.6 1.6 1.1 0.8 0.7 0.6 0.5 0.3 0.3 0.2 0.1 0.1 0.1 0.1 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0\n\n\nArch.cor = cor(subX, subArch, method = \"spearman\")\narch.enrichment = apply(Arch.cor, 2, function(x) {\n perm = order(x, decreasing = F)\n l = SZ.mask[perm]\n mhg.out = mhg::mhg_test(l, length(l), sum(l), length(l), 1, upper_bound = F, tol = 1e-300)\n -log10(mhg.out$pvalue)\n})\nsort(round(arch.enrichment, 1), decreasing = T)\n# A30 A6 A22 A19 A2 A29 A26 A11 A15 A13 A21 A4 A16 A1 A14 A12 A24 A27 A28 A5 A7 A9 A18 A20 A3 A8 A10 A17 A23 A25 A31 \n# 8.5 8.4 4.0 2.6 2.1 2.1 1.5 1.4 1.2 1.0 1.0 0.8 0.6 0.3 0.3 0.2 0.2 0.2 0.2 0.1 0.1 0.1 0.1 0.1 0.0 0.0 0.0 0.0 0.0 0.0 0.0\n\nsubX.orth = orthoProject(subX, fast_row_sums(subX))\nArch.cor = cor(subX.orth, subArch, method = \"spearman\")\narch.enrichment = apply(Arch.cor, 2, function(x) {\n perm = order(x, decreasing = F)\n l = SZ.mask[perm]\n mhg.out = mhg::mhg_test(l, length(l), sum(l), length(l), 1, upper_bound = F, tol = 1e-300)\n -log10(mhg.out$pvalue)\n})\nsort(round(arch.enrichment, 1), decreasing = T)\n\n\n\n\n\n\n\n```\n\n\n\n```{r}\nX = assays(PEC.sce.matched)$normexpr\n# arch.genes = rownames(arch.gene.spec)[which(apply(as.matrix(arch.gene.spec[, c(11, 29)]), 1, max) > 100)]\narch.genes = rownames(arch.gene.spec)[which(apply(scale(as.matrix(arch.gene.spec[, c(7, 11, 17, 29)])), 1, max) > 3)]\narch.genes = arch.genes[-grep(\"^RPL|^RPS|^MT-|^MT[:.:]\", arch.genes)]\n\n\ncg = intersect(rownames(X), arch.genes)\nsubArch = (arch.gene.spec[cg, c(7, 11, 17, 29)])\nsubX = X[cg, ]\n# subX = log1p(subX)\n\n# X = assays(PEC.sce.matched)$normexpr\n# cg = intersect(rownames(X), rownames(arch.gene.spec))\n# subX = X[cg, ]\n\n\n# Arch.cor = -cor(subX, subArch, method = \"pearson\")\n# arch.enrichment = apply(Arch.cor, 2, function(x) {\n# perm = order(x, decreasing = T)\n# l = SZ.mask[perm]\n# mhg.out = mhg::mhg_test(l, length(l), sum(l), 1000, 1, upper_bound = F, tol = 1e-300)\n# -log10(mhg.out$pvalue)\n# })\n# sort(round(arch.enrichment, 1), decreasing = T)\n# \n# \nsubX.orth = orthoProject(subX, fast_row_sums(subX))\n\nSZ.samples = list(SZ = PEC.sce.matched$individualID[which(SZ.mask == 1)])\nrequire(fgsea)\n\nArch.cor = cor(subX.orth, subArch, method = \"spearman\")\narch.enrichment = apply(Arch.cor, 2, function(x) {\n gsea.out = fgsea(SZ.samples, x)\n -log10(gsea.out$padj)\n # perm = order(x, decreasing = T)\n # l = SZ.mask[perm]\n # mhg.out = mhg::mhg_test(l, length(l), sum(l), length(l)/4, 1, upper_bound = F, tol = 1e-300)\n # -log10(mhg.out$pvalue)\n})\nsort(round(arch.enrichment, 1), decreasing = T)\n\n```\n\n```{r}\nx = Arch.cor[, \"A29\"]\nfgsea::plotEnrichment(SZ.samples[[1]], x)\n\ndf = data.frame(A29 = scale(Arch.cor[, \"A29\"]), A11 = scale(Arch.cor[, \"A11\"]), Phenotype = PEC.sce.matched$diagnosis, Sample = rownames(Arch.cor), x = PEC.sce.matched$ethnicity, PEC.sce.matched$ageDeath, PEC.sce.matched$sex, PEC.sce.matched$smoker)\ndf$combined = (df$A29 + df$A11)/2\n\nggscatter(df, x = \"A11\", y = \"A29\",\n add = \"reg.line\", # Add regression line\n conf.int = TRUE, # Add confidence interval\n color = \"Phenotype\", \n palette = c(\"gray\", \"red\"),\n add.params = list(color = \"blue\",\n fill = \"lightgray\")\n ) \n\n+\n stat_cor(method = \"pearson\", label.x = 3, label.y = 30) # Add correlation coefficient\n\n\n\nArch.cor = cor(subX.orth, subArch, method = \"spearman\")\narch.enrichment = apply(Arch.cor, 2, function(x) {\n x = exp(df$A11)\n names(x) = df$Sample\n fgsea::plotEnrichment(SZ.samples[[1]], x)\n\n # gsea.out = fgsea(SZ.samples, x)\n # -log10(gsea.out$padj)\n perm = order(x, decreasing = T)\n l = SZ.mask[perm]\n mhg.out = mhg::mhg_test(l, length(l), sum(l), length(l)/4, 1, upper_bound = F, tol = 1e-300)\n -log10(mhg.out$pvalue)\n})\nsort(round(arch.enrichment, 1), decreasing = T)\n\n\n\n\n# 0.9115914\n# cor(Arch.cor[, \"A11\"], Arch.cor[, \"A29\"], method = \"spearman\")\n\nfgsea::plotEnrichment(SZ.samples[[1]], x)\n\n\nscores = exp(Arch.cor*5)\n\nX = sapply(sort(unique(PEC.sce.matched$a)), function(x) as.numeric(PEC.sce.matched$ethnicity == x))\nrownames(X) = colnames(PEC.sce.matched)\ngender.enrichment = assess.geneset.enrichment.from.scores(scores, X)\n\ncolnames(gender.enrichment$logPvals) = colnames(scores)\n\nHeatmap(gender.enrichment$logPvals)\n\n\n\n```\n\n\n\n\n```{r}\nInd.enrichment = annotate.archetypes.using.labels(t(ACTIONet_summary$H_unified), ACTIONet_summary$metadata$Individual)\nInd.wilcox.out = presto::wilcoxauc(t(ACTIONet_summary$H_unified), ACTIONet_summary$metadata$Individual)\n\ncelltype.enrichment = annotate.archetypes.using.labels(t(ACTIONet_summary$H_unified), ACTIONet_summary$metadata$Labels)\n\nphenotype.enrichment = annotate.archetypes.using.labels(t(ACTIONet_summary$H_unified), ACTIONet_summary$metadata$Phenotype)\n\nX = t(Ind.enrichment$Enrichment)\nrownames(X) = levels(ACTIONet_summary$metadata$Individual)\ncolnames(X) = paste(\"A\", 1:ncol(X), \"-\", celltype.enrichment$Label, sep = \"\")\n\npdf(file.path(figures.folder, \"Archetype_vs_sample_enrichment.pdf\"), height = 28)\nHeatmap(X, row_names_side = \"left\", rect_gp = gpar(col = \"black\"), show_row_dend = F, show_column_dend = F, column_names_gp = gpar(col = colors[celltype.enrichment$Label]))\ndev.off()\n\n\ncc = c(\"CON\" = \"gray\", \"SZ\" = \"red\")\npdf(file.path(figures.folder, \"Archetype_vs_phenotype_enrichment.pdf\"), height = 2)\nHeatmap(t(scale(phenotype.enrichment$Enrichment[order(phenotype.enrichment$Enrichment[, 1]), ])), row_names_side = \"left\", rect_gp = gpar(col = \"black\"), cluster_columns = F, show_row_dend = F, show_column_dend = F, column_names_gp = gpar(col = cc[phenotype.enrichment$Label[order(phenotype.enrichment$Enrichment[, 1])]]), name = \"Enrichment(scaled)\")\ndev.off()\n\n\n\nHeatmap(scale(X[, c(7, 11, 17, 29)]), row_names_side = \"left\", rect_gp = gpar(col = \"black\"), show_row_dend = F, show_column_dend = F) + Heatmap(pb.logcounts$Phenotype, row_names_side = \"left\", rect_gp = gpar(col = \"black\"), show_row_dend = F, show_column_dend = F, col = c(\"gray\", \"red\"))\n \n #Heatmap(phenotype.enrichment$Enrichment, row_names_side = \"left\", rect_gp = gpar(col = \"black\"), show_row_dend = F, show_column_dend = F)\n\n\n\n down.enrichment = assess_enrichment(ACTIONet_summary$unified_feature_specificity, ACTIONet:::.preprocess_annotation_markers(DE.new$Down.genes, rownames(pb.logcounts)))$logPvals\n\n up.enrichment = assess_enrichment(ACTIONet_summary$unified_feature_specificity, ACTIONet:::.preprocess_annotation_markers(DE.new$Up.genes, rownames(pb.logcounts)))$logPvals\n\n colnames(down.enrichment) = colnames(up.enrichment) = paste(\"A\", 1:ncol(X), \"-\", celltype.enrichment$Label, sep = \"\")\n rownames(down.enrichment) = rownames(up.enrichment) = names(DE.new$Down.genes)\nHeatmap(down.enrichment)\n\npdf(file.path(figures.folder, \"Archetype_vs_DE_up.pdf\"), height = 7, width = 8)\nHeatmap(up.enrichment, row_names_side = \"left\", rect_gp = gpar(col = \"black\"), show_row_dend = F, show_column_dend = F, column_names_gp = gpar(col = colors[celltype.enrichment$Label]), row_names_gp = gpar(col = colors[rownames(up.enrichment)]), name = \"Up\")\ndev.off()\n\npdf(file.path(figures.folder, \"Archetype_vs_DE_down.pdf\"), height = 7, width = 8)\nHeatmap(down.enrichment, row_names_side = \"left\", rect_gp = gpar(col = \"black\"), show_row_dend = F, show_column_dend = F, column_names_gp = gpar(col = colors[celltype.enrichment$Label]), row_names_gp = gpar(col = colors[rownames(down.enrichment)]), name = \"Down\")\ndev.off()\n\n\n\npdf(file.path(figures.folder, \"Archetype_vs_DE.pdf\"), height = 7, width = 16)\nHeatmap(up.enrichment, row_names_side = \"left\", rect_gp = gpar(col = \"black\"), show_row_dend = F, show_column_dend = F, column_names_gp = gpar(col = colors[celltype.enrichment$Label]), row_names_gp = gpar(col = colors[rownames(up.enrichment)]), name = \"Up\") + Heatmap(down.enrichment, row_names_side = \"left\", rect_gp = gpar(col = \"black\"), show_row_dend = F, show_column_dend = F, column_names_gp = gpar(col = colors[celltype.enrichment$Label]), row_names_gp = gpar(col = colors[rownames(down.enrichment)]), name = \"Down\")\ndev.off()\n\n```\n\n" }, { "alpha_fraction": 0.6476166248321533, "alphanum_fraction": 0.6642747521400452, "avg_line_length": 22.082839965820312, "blob_id": "d034acde04aad9f7d1c69f280f47bbe7996606e3", "content_id": "a01d3841870d8fa7614ee3c659dabbfbe9cd38e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 3902, "license_type": "no_license", "max_line_length": 130, "num_lines": 169, "path": "/ancient/Fig2_Run_iDEA.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"Run iDEA Analysis of DE genes\"\noutput: html_notebook\n---\n\n# Setup\n```{r include=FALSE}\nrequire(ACTIONet)\nrequire(stringr)\nrequire(ComplexHeatmap)\nrequire(iDEA)\n\ndataset.path = \"~/results/datasets/\"\nresults.path = \"~/results\"\nfigures.folder = \"~/results/figures\"\ninput.folder = \"~/results/input\"\n\n\n```\n\n\n\n\n\n```{r}\nACTIONet_summary = readr::read_rds(file.path(dataset.path, \"ACTIONet_summary_filtered_individuals.rds\"))\n\npb.logcounts = readr::read_rds(file.path(dataset.path, \"PB_mean_logcounts_final.RDS\"))\n\ncolor.df = readRDS(file.path(dataset.path, \"celltype_colors.rds\"))\n\ncolors = color.df$color\nnames(colors) = color.df$celltype\n\n```\n\n\n```{r}\nresDE = readr::read_rds(file.path(dataset.path, \"Cohort_specific_DE_results_final.rds\"))\n\nfiltered.tables = readr::read_rds(file.path(dataset.path, \"individual_diff_results_filtered.rds\"))\n\ncombined.analysis.tables = readr::read_rds(file.path(dataset.path, \"meta_analysis_diff_results.rds\"))\n\nDE.new = readr::read_rds(file.path(dataset.path, \"DE_genes_pseudobulk_final.rds\"))\n\n```\n\n\n```{r}\niDEA.summary.tables = lapply(combined.analysis.tables, function(res_DE) {\n ## Assume you have obtained the DE results from i.e. zingeR, edgeR or MAST with the data frame res_DE (column: pvalue and LogFC)\n pvalue <- res_DE$P.Value #### the pvalue column\n zscore <- qnorm(pvalue/2.0, lower.tail=FALSE) #### convert the pvalue to z-score\n beta <- res_DE$logFC ## effect size\n se_beta <- abs(beta/zscore) ## to approximate the standard error of beta\n beta_var = se_beta^2 ### square \n summary = data.frame(beta = beta,beta_var = beta_var)\n ## add the gene names as the rownames of summary\n rownames(summary) = res_DE$gene ### or the gene id column in the res_DE results\n return(summary) \n})\n\n\n```\n\n\n```{r}\ndata(\"gProfilerDB_human\")\nBP = gProfilerDB_human$SYMBOL$`GO:BP`\ncs = fast_column_sums(BP)\nmask = (cs >= 10) & (cs <= 1000)\nBP = BP[, mask]\nrow.mask = rownames(BP) %in% rownames(pb.logcounts)\nBP = BP[row.mask, ]\nBP.df = as.data.frame(BP)\n```\n\n\n\n```{r}\ndata(\"humanGeneSets\")\ndata(\"humanGeneSetsInfo\")\nmask = humanGeneSetsInfo$gsetBioName %in% c(\"GO biological process\", \"KEGG\", \"Reactome\")\nhumanGeneSets.subset = humanGeneSets[, mask]\nhumanGeneSets.subset = humanGeneSets.subset[intersect(rownames(humanGeneSets.subset), rownames(pb.logcounts)), ]\n\n\n\n```\n\n```{r}\nplot(density(idea.res$`Ex-L4_MYLK`@BMA_pip$BMA_pip))\n\nsum(idea.res$`Ex-L6_CC_SEMA3A`@BMA_pip$BMA_pip >0.5)\n\n\nDF = (idea.res$`Ex-L6_CC_SEMA3A`@gsea)\n\n```\n\n\n\n```{r}\nidea.res = vector(\"list\", length(iDEA.summary.tables))\nnames(idea.res) = names(iDEA.summary.tables) \nfor(i in 1:length(iDEA.summary.tables)) {\n print(names(idea.res)[[i]])\n summary_data = iDEA.summary.tables[[i]]\n \n idea <- CreateiDEAObject(summary_data, humanGeneSets.subset, max_var_beta = 100, min_precent_annot = 0.0025, num_core=46)\n\n idea <- iDEA.fit(idea,\n fit_noGS=FALSE,\n \t init_beta=NULL, \n \t init_tau=c(-2,0.5),\n \t min_degene=5,\n \t em_iter=15,\n \t mcmc_iter=1000, \n \t fit.tol=1e-5,\n modelVariant = F,\n \t verbose=TRUE) \n idea <- iDEA.louis(idea)\n idea <- iDEA.BMA(idea)\n idea.res[[i]] = idea\n}\n\nreadr::write_rds(idea.res, \"~/results/datasets/idea_output.rds\")\n\n\n```\n\n\n```{r}\nidea.res = readr::read_rds(\"~/results/datasets/idea_output.rds\")\n\nDF = idea.res$`Ex-L45_LRRK1`@gsea\n\nDF2 = idea.res$`In-PV_Basket`@gsea\n\nDF3 = idea.res$`Ex-L23`@gsea\n\n\nrequire(simplifyEnrichment)\nsimplifyEnrichment::simplifyGO()\n\n\n```\n\n\n\n\n```{r}\nx = -log10(combined.analysis.tables$`Ex-L45_LRRK1`$P.Value)\nnames(x) = combined.analysis.tables$`Ex-L45_LRRK1`$gene\n\ny = idea.res$`Ex-L45_LRRK1`@BMA_pip$BMA_pip\nnames(y) = rownames(idea.res$`Ex-L45_LRRK1`@BMA_pip)\n\nz = x[names(y)]\n\ncor(z, y)\n\n# DF = idea.res$`Ex-L45_LRRK1`\n# gg = lapply(idea.res, function(DF) rownames(DF@BMA_pip)[DF@BMA_pip$BMA_pip > 0.5])\n\nX = DF@gsea\n\n```\n\n" }, { "alpha_fraction": 0.8188976645469666, "alphanum_fraction": 0.8188976645469666, "avg_line_length": 41.33333206176758, "blob_id": "9fe1ac706a7cde11b024362982a433226e3a9943", "content_id": "03c69e0da1ca17d29e3b1d61bfde9bcc8b7b681d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 127, "license_type": "no_license", "max_line_length": 73, "num_lines": 3, "path": "/README.md", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "## Single-cell multi-cohort dissection of the schizophrenia transcriptome\n\n![ACTIONet](results/figures/ACTIONet_annotated.png)\n" }, { "alpha_fraction": 0.6454896330833435, "alphanum_fraction": 0.6591786742210388, "avg_line_length": 30.291208267211914, "blob_id": "9fc39f8607fbbebcc02dbbff792a29b33d7c412d", "content_id": "9e1040a19c085fa754d144e4d557019884817fe5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 5698, "license_type": "no_license", "max_line_length": 265, "num_lines": 182, "path": "/ancient/Fig3_HMAGMA.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"Fig3: H-MAGMA analysis\"\noutput: html_notebook\n---\n\n# Setup\n```{r include=FALSE}\nlibrary(org.Hs.eg.db)\n\ndataset.path = \"~/results/datasets/\"\nresults.path = \"~/results\"\nfigures.folder = \"~/results/figures\"\n\nMAGMA.path = \"~/magma\"\n\n\n```\n\n# Load DE genes\n```{r include=FALSE}\nDE.new = readRDS(file.path(dataset.path, \"DE_genes_pseudobulk_final_with_umi.rds\"))\n\nUp.genes = DE.new$Up.genes\nDown.genes = DE.new$Down.genes\n\ncolor.df = readRDS(file.path(dataset.path, \"celltype_colors.rds\"))\n\ncolors = color.df$color\nnames(colors) = color.df$celltype\n\n```\n\n\n\n```{r}\n# Up.genes = sapply(resDE$McLean$table$PhenotypeSZ, function(df) {\n# mask = (df$p_val < 0.05) & (df$logFC > 0.1)\n# df$gene[mask]\n# })\n# Down.genes = sapply(resDE$McLean$table$PhenotypeSZ, function(df) {\n# mask = (df$p_val < 0.05) & (df$logFC < -0.1)\n# df$gene[mask]\n# })\n\n\n\n\n\n```\n\n\n\n# Convert DE genes to ENSG and export\n```{r}\nrequire(org.Hs.eg.db)\n\nsuppressWarnings(ids <- AnnotationDbi::mapIds(org.Hs.eg.db, keys = row.names(DE.new$DE.sc), keytype = \"SYMBOL\", column = \"ENSEMBL\", multiVals = \"first\"))\nids[is.na(ids)] = \"\"\n\nUp.genes.ENSG = sapply(Up.genes, function(gs) {\n setdiff(sort(unique(ids[match(gs, rownames(pb.logcounts))])), \"\")\n})\nUp.genes.ENSG.df = reshape2::melt(Up.genes.ENSG)\nUp.genes.ENSG.df = Up.genes.ENSG.df[, c(2, 1)]\nUp.genes.ENSG.df$L1 = factor(Up.genes.ENSG.df$L1, names(Up.genes))\nUp.genes.ENSG.df = Up.genes.ENSG.df[order(Up.genes.ENSG.df$L1), ]\nwrite.table(Up.genes.ENSG.df, file.path(MAGMA.path, \"genesets\", \"Up_genes_ENSG.tsv\"), sep = \"\\t\", col.names = F, row.names = F, quote = F)\n\nDown.genes.ENSG = sapply(Down.genes, function(gs) {\n setdiff(sort(unique(ids[match(gs, rownames(pb.logcounts))])), \"\")\n})\nDown.genes.ENSG.df = reshape2::melt(Down.genes.ENSG)\nDown.genes.ENSG.df = Down.genes.ENSG.df[, c(2, 1)]\nDown.genes.ENSG.df$L1 = factor(Down.genes.ENSG.df$L1, names(Down.genes))\nDown.genes.ENSG.df = Down.genes.ENSG.df[order(Down.genes.ENSG.df$L1), ]\n\nwrite.table(Down.genes.ENSG.df, file.path(MAGMA.path, \"genesets\", \"Down_genes_ENSG.tsv\"), sep = \"\\t\", col.names = F, row.names = F, quote = F)\n\n\nUpAndDown.genes.ENSG.df = rbind(Up.genes.ENSG.df, Down.genes.ENSG.df)\nUpAndDown.genes.ENSG.df$L1 = factor(UpAndDown.genes.ENSG.df$L1, names(Up.genes))\nUpAndDown.genes.ENSG.df = UpAndDown.genes.ENSG.df[order(UpAndDown.genes.ENSG.df$L1), ]\n\nwrite.table(UpAndDown.genes.ENSG.df, file.path(MAGMA.path, \"genesets\", \"UpAndDown_genes_ENSG.tsv\"), sep = \"\\t\", col.names = F, row.names = F, quote = F)\n\n\n```\n\n\n\n\n\n# Run H-MAGMA\nWe run HMAGMA using **for f in `ls hmagma/`; do (./magma --gene-results ./hmagma/$f/$f.genes.raw --set-annot genesets/UpAndDown_genes_ENSG.tsv col=2,1 --out $f\\_UpAndDown &); done`**, from inside the magma folder, where hmagma are prestored the gene models scores.\n\n# Load H-MAGMA results\n\n```{r}\ndl = list.dirs(file.path(MAGMA.path, \"psych_arch/\"), full.names = F, recursive = F)\n\nHMAGMA.Pvals = vector(\"list\", 1)\nnames(HMAGMA.Pvals) = c(\"UpAndDown\")\nfor (d in names(HMAGMA.Pvals)) {\n HMAGMA.Pvals[[d]] = matrix(1, nrow = 20, ncol = length(dl))\n colnames(HMAGMA.Pvals[[d]]) = dl\n rownames(HMAGMA.Pvals[[d]]) = names(Up.genes)\n for(cond in dl) {\n print(cond)\n file.name = sprintf(\"%s/out/%s_%s.gsa.out\", MAGMA.path, cond, d)\n lines = readLines(con <- file(file.name))\n lines = str_split(lines, \"\\n\")[-c(1:5)]\n \n pvals = sapply(lines, function(ll) {\n parts = str_split(ll, \" \")\n as.numeric(parts[[1]][length(parts[[1]])])\n })\n \n names(pvals) = sapply(lines, function(ll) {\n parts = str_split(ll, \" \")\n parts[[1]][[1]]\n })\n\n HMAGMA.Pvals[[d]][names(pvals), cond] = pvals \n }\n}\n\n\n# readr::write_rds(HMAGMA.Pvals, file.path(results.path, \"HMAGMA_results_raw.rds\"))\n\n\n```\n\n# Or load preprocessed results\n```{r}\nHMAGMA.Pvals = readr::read_rds(file.path(results.path, \"HMAGMA_results_raw.rds\"))\n\n```\n\n\n\n## Export selected results\n```{r}\n# selected.traits = c(\"hmagmaAdultBrain__sz3\", \"hmagmaAdultBrain__bip2\", \"hmagmaAdultBrain__mdd_without_23andMe\", \"hmagmaAdultBrain__alz2noapoe\")\n# \n# trait.labels = c(\"Schizophrenia (SZ)\", \"Bipolar (BP)\", \"Depression (MDD)\", \"Alzheimer (AD)\")\n\n selected.traits = c(\"hmagmaAdultBrain__sz3\", \"hmagmaAdultBrain__bip2\", \"hmagmaAdultBrain__asd\", \"hmagmaAdultBrain__adhd\", \"hmagmaAdultBrain__mdd_without_23andMe\", \"hmagmaAdultBrain__alz2noapoe\")\n\ntrait.labels = c(\"Schizophrenia (SZ)\", \"Bipolar (BP)\",\"Autism (ASD)\", \"ADHD\", \"Depression (MDD)\", \"Alzheimer (AD)\")\n\n# selected.traits = c(\"hmagmaAdultBrain__sz3\", \"hmagmaAdultBrain__bip2\", \"hmagmaAdultBrain__adhd\", \"hmagmaAdultBrain__alz2noapoe\")\n# \n# trait.labels = c(\"Schizophrenia (SZ)\", \"Bipolar (BP)\",\"ADHD\", \"Alzheimer (AD)\")\n\n# X = -log10(HMAGMA.Pvals$UpAndDown)\n# Heatmap(X)\n\n\nX = HMAGMA.Pvals$UpAndDown[, selected.traits]\ncts = intersect(color.df$celltype, rownames(X))\ncts = cts[grep(\"^In|^Ex\", cts)]\n# \n# X = X[, grep(\"Adult\", colnames(X))]\nX = X[cts, ]\n# X = matrix(p.adjust(as.numeric(X), \"fdr\"), nrow = length(cts))\nX = apply(X, 2, function(p) p.adjust(p, \"fdr\"))\nrownames(X) = intersect(names(colors), rownames(X))\nX = -log10(X)\n# X[X < -log10(0.05)] = 0\ncolnames(X) = trait.labels\nrownames(X) = cts\n\nPurPal = colorRampPalette(RColorBrewer::brewer.pal(9, \"Purples\"))(200)\nPurPal = c(rep(PurPal[1], length(PurPal)*(sum(X < 1) / length(X))), PurPal)\n\nrequire(corrplot)\npdf(file.path(figures.folder, \"HMAGMA_adultBrain_UpAndDown_corrplot_logumi_baseline_full_filter_extended_cell_filtering_localFDR_neuro.pdf\"), width =7, height = 7)\ncorrplot(X, is.corr = F, method = \"pie\", col = PurPal, cl.lim = c(0, 5), cl.length = 5, outline = T, sig.level = 0.05, p.mat = 10^(-X), insig = \"blank\", tl.col = \"black\")\ndev.off()\n\n\n```\n\n\n\n" }, { "alpha_fraction": 0.607905387878418, "alphanum_fraction": 0.63866126537323, "avg_line_length": 29.08506965637207, "blob_id": "2e6ab4c8a59540846ac4ab7dd651a1627a40669f", "content_id": "880b06ba8abd8fa11f06b1120fe7595bb10ae013", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 17338, "license_type": "no_license", "max_line_length": 474, "num_lines": 576, "path": "/old/PEC_modules.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"R Notebook\"\noutput: html_notebook\n---\n\n```{r}\n#‘A function to plot roc or prc outputs from PRROC::pr.curve or PRROC::roc.curve functions\n#‘@param pr_curve list with keys sample names, values outputs of pr.curve or roc.curve\n#‘@param cpal string indicating color palette to use i.e. Dark2\n#’\nplot_roc <- function(pr_curve_list,cpal) {\n library(ggplot2)\n keys=names(pr_curve_list)\n list_to_plot=list()\n auc_to_plot=list()\n for(key in keys){\n cur_df=as.data.frame(pr_curve_list[[key]]$curve)\n cur_df$sample=key\n cur_auc=pr_curve_list[[key]]$auc\n list_to_plot[[key]]=cur_df\n auc_to_plot[[key]]=round(cur_auc,3)\n }\n auc_to_plot=data.frame(names(auc_to_plot),as.numeric(auc_to_plot))\n colnames(auc_to_plot)=c(\"sample\",\"auc\")\n auc_to_plot=within(auc_to_plot, sample_perf <- paste(sample,auc,sep='-'))\n auc_to_plot=auc_to_plot[order(auc_to_plot$auc, decreasing = T),]\n df_to_plot = do.call(rbind, list_to_plot)\n\n colnames(df_to_plot)=c(\"recall\",\"precision\",\"thresh\",\"sample\")\n merged=merge(df_to_plot,auc_to_plot,by='sample')\n merged$sample=factor(merged$sample,levels=auc_to_plot$sample)\n merged=within(merged, sample_perf <- paste(sample,auc,sep='-'))\n merged$sample_perf=factor(merged$sample_perf,levels=auc_to_plot$sample_perf) \n return(ggplot(data=merged)+\n geom_line(aes(x=merged$recall,\n y=merged$precision,\n group=merged$sample,\n color=merged$sample_perf))+\n geom_abline()+\n xlab(\"False Positive Rate\")+ \n ylab(\"True Positive Rate\")+\n # ylab(\"Sensitivity\")+\n # xlab(\"1-Specificity\")+\n theme_bw(20)+\n scale_color_manual(values = cpal,name=\"Sample, auROC\"))\n}\n\nplot_prc <- function(pr_curve_list,cpal = CPal_default) {\n library(ggplot2)\n keys=names(pr_curve_list)\n list_to_plot=list()\n auc_to_plot=list()\n for(key in keys){\n cur_df=as.data.frame(pr_curve_list[[key]]$curve)\n cur_df$sample=key\n cur_auc=pr_curve_list[[key]]$auc\n list_to_plot[[key]]=cur_df\n auc_to_plot[[key]]=round(cur_auc,3)\n }\n auc_to_plot=data.frame(names(auc_to_plot),as.numeric(auc_to_plot))\n colnames(auc_to_plot)=c(\"sample\",\"auc\")\n auc_to_plot=within(auc_to_plot, sample_perf <- paste(sample,auc,sep='-'))\n auc_to_plot=auc_to_plot[order(auc_to_plot$auc, decreasing = T),]\n df_to_plot = do.call(rbind, list_to_plot)\n\n colnames(df_to_plot)=c(\"recall\",\"precision\",\"thresh\",\"sample\")\n merged=merge(df_to_plot,auc_to_plot,by='sample')\n merged$sample=factor(merged$sample,levels=auc_to_plot$sample)\n merged=within(merged, sample_perf <- paste(sample,auc,sep='-'))\n merged$sample_perf=factor(merged$sample_perf,levels=auc_to_plot$sample_perf) \n return(ggplot(data=merged)+\n geom_line(aes(x=merged$recall,\n y=merged$precision,\n group=merged$sample,\n color=merged$sample_perf))+\n xlab(\"Precision\")+ \n ylab(\"Recall\")+\n # ylab(\"Sensitivity\")+\n # xlab(\"1-Specificity\")+\n theme_bw(20)+\n scale_color_manual(values = cpal,name=\"Sample, auPR\"))\n}\n```\n\n\n```{r}\nrequire(openxlsx)\n\nPEC_modules = readLines(con <- file(\"~/PEC_modules/INT-09_WGCNA_modules_hgnc_ids.csv\"))\n\n\nmod.names = lapply(PEC_modules, function(x) str_split(x, \"\\t\")[[1]][1])\nPEC_modules.genes = lapply(PEC_modules, function(x) sort(unique(str_split(x, \"\\t\")[[1]][-1])))\nnames(PEC_modules.genes) = mod.names\n\nSZ.mods = c(\"module_3628\", \"module_3636\", \"module_3711\", \"module_3251\", \"module_1749\", \"module_2752\", \"module_3001\", \"module_3009\", \"module_3172\", \"module_3332\", \"module_3333\", \"module_3464\", \"module_3614\", \"module_725\", \"module_738\", \"module_1685\", \"module_1755\", \"module_2692\", \"module_3107\", \"module_3184\", \"module_3316\", \"module_3349\", \"module_3381\", \"module_3496\", \"module_3543\", \"module_3616\", \"module_3673\", \"module_3678\", \"module_3693\", \"module_3709\", \"module_3731\")\nPEC_modules.genes.SZ = PEC_modules.genes[SZ.mods]\n\n\narch.spec = ACTIONet_summary$unified_feature_specificity\nassociations = do.call(cbind, lapply(PEC_modules.genes, function(mod) as.numeric(rownames(arch.spec) %in% mod)))\ncolnames(associations) = mod.names\nrownames(associations) = rownames(arch.spec)\nPEC.mod.en = assess.geneset.enrichment.from.scores(arch.spec, associations)\nPEC.mod.logPvals = PEC.mod.en$logPvals\ncolnames(PEC.mod.logPvals) = colnames(arch.spec)\nrownames(PEC.mod.logPvals) = mod.names\n \n# plot.top.k.features(PEC.mod.logPvals)\n\n\narch.annot = annotate.archetypes.using.labels(t(ACTIONet_summary$H_unified), ACTIONet_summary$metadata$Labels)\n\narch.labels = paste(\"A\", 1:ncol(ACTIONet_summary$H_unified), \"-\", arch.annot$Label, sep = \"\")\narch.labels[c(7, 11, 17, 29)] = paste(\"A\", c(7, 11, 17, 29), \"-\", c(\"Ex-NRGN\", \"Ex-SZ\", \"Ex-SZTR\", \"In-SZ\"), sep = \"\")\n\narch.order = c(setdiff(order(match(arch.annot$Label, names(colors))), c(7, 11, 17, 29)), c(7, 11, 17, 29))\n\nX = PEC.mod.logPvals[SZ.mods, arch.order]\ncolnames(X) = arch.labels[arch.order]\nHeatmap(X, cluster_columns = F)\n\n```\n\n\n```{r}\nassociations = do.call(cbind, lapply(DE.new$Down.genes, function(mod) as.numeric(rownames(arch.spec) %in% mod)))\ncolnames(associations) = names(DE.new$Down.genes)\nrownames(associations) = rownames(arch.spec)\nPEC.mod.en = assess.geneset.enrichment.from.scores(arch.spec, associations)\nPEC.mod.logPvals = PEC.mod.en$logPvals\ncolnames(PEC.mod.logPvals) = colnames(arch.spec)\nrownames(PEC.mod.logPvals) = names(DE.new$Down.genes)\n \n# plot.top.k.features(PEC.mod.logPvals)\n\n\narch.annot = annotate.archetypes.using.labels(t(ACTIONet_summary$H_unified), ACTIONet_summary$metadata$Labels)\n\narch.labels = paste(\"A\", 1:ncol(ACTIONet_summary$H_unified), \"-\", arch.annot$Label, sep = \"\")\narch.labels[c(7, 11, 17, 29)] = paste(\"A\", c(7, 11, 17, 29), \"-\", c(\"Ex-NRGN\", \"Ex-SZ\", \"Ex-SZTR\", \"In-SZ\"), sep = \"\")\n\narch.order = c(setdiff(order(match(arch.annot$Label, names(colors))), c(7, 11, 17, 29)), c(7, 11, 17, 29))\n\nX = PEC.mod.logPvals[, arch.order]\ncolnames(X) = arch.labels[arch.order]\nHeatmap(X, cluster_columns = F)\n\n\n\n```\n\n\n```{r}\ndf = data.frame(Gene = rownames(arch.spec), A11 = (arch.spec[, 11]), A29 = (arch.spec[, 29]))\n# mask = (df$A11 > 3) & (df$A29 > 3)\n# df = df[mask, ]\n# df$A11 = (df$A11 - median(df$A11)) / mad(df$A11)\n# df$A29 = (df$A29 - median(df$A29)) / mad(df$A29)\ndf$A11 = scale(df$A11)\ndf$A29 = scale(df$A29)\ndf$Label = \"\"\nmask = (df$A11 > 3) & (df$A29 > 3)\ndf$Label[mask] = df$Gene[mask]\n\nggscatter(df, \"A11\", \"A29\", repel = T, label = \"Label\")\n\n\n```\n\n\n```{r}\nbulk = readr::read_rds(\"~/results/input/MPP_bulk_expression_SZandCON.rds\")\nbulk.profile = assays(bulk)$voom\nbulk.profile.orth = orthoProject(bulk.profile, Matrix::rowMeans(bulk.profile))\n\n```\n\n```{r}\ntbl1 = read.csv(\"~/results/input/Prioritised_PGC3_SZ_Genes.csv\", sep = \"\\t\")\nPGC3.prioritized.genes = sort(unique(tbl1$Symbol.ID[tbl1$Prioritised == 1]))\n\ntbl2 = read.csv(\"~/results/input/INT-17_SCZ_High_Confidence_Gene_List.csv\", sep = \",\")\nPEC_HighConf.genes = sort(unique(tbl2$sczgenenames))\n\n\nA11 = scale(arch.spec[, 11])\nA29 = scale(arch.spec[, 29])\nmask = (A11 > 4) & (A29 > 4)\narch.genes = rownames(arch.spec)[mask]\n\npred.genes = list(arch.genes = arch.genes, PEC_HighConf.genes = PEC_HighConf.genes, PGC3.prioritized.genes = PGC3.prioritized.genes)\npred.genes = lapply(pred.genes, function(gs) intersect(gs, rownames(bulk)))\n\n```\n\n\n```{r}\nhot1 <- function (x, y = NULL, mu = 0, paired = FALSE, step_size = 0, \n skip_check = FALSE) {\n nx <- dim(x)[1]\n ny <- dim(y)[1]\n stat <- fdahotelling:::stat_hotelling_impl(x = x, y = y, mu = mu, paired = paired, \n step_size = step_size)\n df1 <- min(nx + ny - 2, p)\n df2 <- abs(nx + ny - 2 - p) + 1\n pvalue <- 1 - stats::pf(stat, df1, df2)\n dplyr::data_frame(statName = names(stat), statVal = stat, \n pValue = pvalue, df1 = df1, df2 = df2)\n}\n\n```\n\n\n```{r}\nlibrary(Hotelling)\n\ngs = pred.genes$arch.genes\ncommon.genes = intersect(rownames(bulk.profile.orth), gs)\n# Z = apply(t(bulk.profile[gs[1:10], ]) , 2, RNOmni::RankNorm)\nX = t(bulk.profile.orth[gs, ])\nX1 = X[bulk$Dx == \"SCZ\", ]\nX2 = X[bulk$Dx != \"SCZ\", ]\n\nstat <- fdahotelling:::stat_hotelling_impl(x = X1, y = X2, mu = 0, paired = F, step_size = 0)\nrand.stats = sapply(1:100, function(i) {\n rand.samples = sample(1:nrow(bulk.profile.orth), length(gs))\n randX = t(bulk.profile.orth[rand.samples, ])\n randX1 = randX[bulk$Dx == \"SCZ\", ]\n randX2 = randX[bulk$Dx != \"SCZ\", ]\n rand.stat <- fdahotelling:::stat_hotelling_impl(x = randX1, y = randX2, mu = 0, paired = F, step_size = 0)\n \n return(rand.stat)\n})\n\nz = (stat - mean(rand.stats) ) / sd(rand.stats)\n\n# require(DescTools)\n# out = DescTools::HotellingsT2Test(X1, X2, test = \"chi\")\n\n\n\n\n```\n\n\n```{r}\n\nstat <- hot1(x = X1, y = X2, mu = 0, step_size = 0)\n\n# x = Hotelling::hotelling.test(X1, X2)\n# \n# \n# N = nx + ny\n# print(stat$statVal*(N - p - 1)/((N-2)*p))\n# print(x)\n\n```\n\n```{r}\n\n\n\nfdahotelling::test_twosample\n\n\n\n\n\n# X1 = x\n# X2 = y\n# \n\nout = fdahotelling::test_twosample(x, y)\n\nstat <- out$statVal\nnx = nrow(x)\nny = nrow(y)\np = ncol(x)\ndf1 <- min(nx + ny - 2, p)\ndf2 <- abs(nx + ny - 2 - p) + 1\npvalue <- 1 - stats::pf(stat, df1, df2)\n\ndplyr::data_frame(statName = names(stat), statVal = stat, \n pValue = pvalue) \n\n\nstat = Hotelling::hotelling.test(x, y, perm = F)\nprint(stat)\n\n\n# pred.scores = cor(bulk.profile[common.genes, ], xx, method = \"pearson\")\n\n\n\nHot <- function(X1, X2) {\n p = ncol(X1)\n n1 = nrow(X1)\n n2 = nrow(X2)\n \n X1.mean = Matrix::colMeans(X1)\n X2.mean = Matrix::colMeans(X2)\n Delta.means = X1.mean - X2.mean\n \n Delta1 = apply(X1, 1, function(x) x - X1.mean)\n Delta2 = apply(X2, 1, function(x) x - X2.mean)\n Sigma1 = (Delta1 %*% t(Delta1)) / (n1-1)\n Sigma2 = (Delta2 %*% t(Delta2)) / (n2-1)\n Sigma = (n1 - 1) * Sigma1 + (n2 - 1) * Sigma2 / (((1 / n1) + (1 / n2) )*(n1+n2-2))\n \n HT = t(Delta.means) %*% Sigma %*% Delta.means\n \n require(fdahotelling)\n out = fdahotelling::test_twosample(X1, X2, B = 0)\n \n \n\n \n # x = Hotelling::hotelling.stat(X1, X2)\n \n \n # fdahotelling:::parametric_test\n \n parametric_test\n print(x2)\n\n x2 = hotelling.stat(X1, X2)\n print(x2)\n \n}\n\nx\n\n```\n\n\n```{r}\ncommon.genes = intersect(rownames(bulk.profile.orth), rownames(U))\nxx = arch.spec[common.genes, ]\npred.scores = cor(bulk.profile[common.genes, ], xx, method = \"pearson\")\n\nsc = apply(pred.scores, 2, function(x) 1 / (1 + exp(-scale(x))))\n# sc = apply(pred.scores, 2, function(x) 1 + x)\nrownames(sc) = bulk$SampleID\n\n\nxx = split(bulk$SampleID, bulk$Dx)\nassociations = do.call(cbind, lapply(xx, function(mod) as.numeric(bulk$SampleID %in% mod)))\ncolnames(associations) = names(xx)\nrownames(associations) = bulk$SampleID\n\nPEC.mod.logPvals = t(assess.geneset.enrichment.from.scores(sc, associations)$logPvals)\nrownames(PEC.mod.logPvals) = 1:nrow(PEC.mod.logPvals)\nHeatmap(PEC.mod.logPvals)\n\n```\n\n\n```{r}\n# scores = exp(bulk.profile.orth/10)\nscores = 1 / (1 + exp(-bulk.profile.orth))\n# scores[scores < 0] = 0\nassociations = do.call(cbind, lapply(pred.genes, function(gs) as.numeric(rownames(scores) %in% gs)))\ncolnames(associations) = names(pred.genes)\nrownames(associations) = rownames(scores)\npred.scores = t(assess.geneset.enrichment.from.scores(scores, associations)$logPvals)\ncolnames(pred.scores) = colnames(associations)\nrownames(pred.scores) = colnames(scores)\n\n\ncommon.genes = intersect(rownames(bulk.profile.orth), rownames(U))\nxx = (arch.spec[common.genes, c(29, 11)])\n# xx = cbind(sqrt(xx[, 1] * xx[, 2]), xx)\npred.scores = cor(bulk.profile[common.genes, ], xx, method = \"pearson\")\n\n\n# pred.scores = sapply(pred.genes, function(gs) stats = scale(Matrix::colMeans(bulk.profile.orth[gs, ])))\n\ndf = as.data.frame(scale(pred.scores))\nrownames(df) = bulk$SampleID\ndf$phenotype = bulk$Dx\n\nSZ.samples = list(SZ = bulk$SampleID[which(bulk$Dx == \"SCZ\")])\nv = df[, 1]\nnames(v) = rownames(df)\nx = fgsea::fgsea(SZ.samples, v)\n\n# fgsea::plotEnrichment(SZ.samples$SZ, v)\n\nprint(-log10(x$pval))\n\n# df2 = reshape2::melt(df)\n# colnames(df2) = c(\"phenotype\", \"method\", \"z\")\n\n# ggbarplot(df2, x = \"method\", y = \"z\", color = \"phenotype\",\n# add = \"mean_se\", palette = c(\"#00AFBB\", \"#E7B800\"),\n# position = position_dodge())\n\n\n\n```\n\n```{r}\n# arch.genes, PEC_HighConf.genes, PGC3.prioritized.genes)\n\n# zz = sapply(pred.genes, function(gs) stats = scale(Matrix::colMeans(bulk.profile.orth[gs, ])))\n\nll = lapply(pred.genes, function(gs) {\n l = as.numeric(rownames(bulk.profile.orth) %in% gs)\n logPvals=-log10(p.adjust(apply(bulk.profile.orth, 2, function(x) {\n perm = order(x, decreasing = T)\n mhg.out = mhg::mhg_test(l[perm], length(l), sum(l), length(l)/4, 5, upper_bound = F, tol = 1e-300)\n mhg.out$pvalue\n }), method = \"fdr\"))\n})\nX = do.call(cbind, ll)\n\ndf = as.data.frame(zz)\ndf$phenotype = bulk$Dx\ndf2 = reshape2::melt(df)\ncolnames(df2) = c(\"phenotype\", \"method\", \"z\")\n\n# ggbarplot(df2, x = \"method\", y = \"z\", color = \"phenotype\",\n# add = \"mean_se\", palette = c(\"#00AFBB\", \"#E7B800\"),\n# position = position_dodge())\n# \n# \n# \n# ggbarplot(df, x = \"phenotype\", y = \"arch.genes\", fill = \"phenotype\", palette = c(\"#666666\", \"#cccccc\"),\n# add = \"mean_se\", label = TRUE, lab.vjust = -1.6)\n\n\nperfs = apply(pred.scores, 2, function(x) PRROC::roc.curve(1 / (1 + exp(-scale(x))), weights.class0 = as.numeric(bulk$Dx == \"SCZ\"), curve = T))\nplot_roc(perfs, as.character(pals::brewer.dark2(3)))\n# prefs = apply(zz, 2, function(pred) PRROC::roc.curve(pred, weights.class0 = as.numeric(bulk$Dx == \"SCZ\"), curve = T, sorted = T))\n\nperfs = apply(pred.scores, 2, function(pred) PRROC::pr.curve(pred, weights.class0 = as.numeric(bulk$Dx == \"SCZ\"), curve = T))\nplot_prc(perfs)\n\n# \n# x = sapply(istel.perfs, function(x) x$auc)\n# cor(Cat.AC.z, x[names(Cat.AC.z)])\n# cor(C1.line.z[names(Cat.AC.z)], Cat.AC.z)\n# \n# CPal = as.character(pals::brewer.spectral(length(sorted.istels)))\n# AUCs = sapply(istel.perfs, function(x) x$auc)\n# perm = order(AUCs, decreasing = T)\n# gp = plot_roc(istel.perfs[perm], CPal)\n\n\n\n```\n\n\n```{r}\nlibrary(fda)\nlibrary(fdahotelling)\n\nSZ.mask = bulk$Dx == \"SCZ\"\nx = t(bulk.profile[pred.genes$arch.genes, SZ.mask])\ny = t(bulk.profile[pred.genes$arch.genes, !SZ.mask])\n\nout = fdahotelling::test_twosample(x, y, B = 0)\n\n# Hotelling \n# 750.1352 \n# out$statVal\n\nx = t(bulk.profile[pred.genes$PEC_HighConf.genes, SZ.mask])\ny = t(bulk.profile[pred.genes$PEC_HighConf.genes, !SZ.mask])\n\nout = fdahotelling::test_twosample(x, y, B = 0, verbose = T)\n\n\n\n```\n\n\n```{r}\nl = as.numeric(rownames(bulk.profile.orth) %in% pred.genes$arch.genes)\n\n# logPvals=-log10(p.adjust(apply(bulk.profile.orth, 2, function(x) {\n# perm = order(x, decreasing = T)\n# mhg.out = mhg::mhg_test(l[perm], length(l), sum(l), length(l), 5, upper_bound = F, tol = 1e-300)\n# mhg.out$pvalue\n# }), method = \"fdr\"))\n\ndf3 = data.frame(scores = logPvals, phenotype = bulk$Dx)\nggbarplot(df3, x = \"phenotype\", y = \"scores\", fill = \"phenotype\", palette = c(\"#666666\", \"#cccccc\"),\n add = \"mean_se\", label = TRUE, lab.vjust = -1.6) + geom_hline(yintercept = -log10(0.05), linetype=\"dashed\", \n color = \"red\", size=1)\n\n```\n\n\n\n```{r}\nLabels = sort(unique(ace.istel$Label))\nistel.perfs = vector(\"list\", length(Labels))\nnames(istel.perfs) = Labels\n\n\nfor(label in Labels) {\n print(label)\n mask.test = ace.istel$Label == label\n \n xgbpred <- predict(PCA.model.full, istel.data.reduced[mask.test, ])\n \n istel.perfs[[label]] = PRROC::roc.curve(xgbpred, weights.class0 = istel.data.labels[mask.test], curve = T)\n}\n\nx = sapply(istel.perfs, function(x) x$auc)\ncor(Cat.AC.z, x[names(Cat.AC.z)])\ncor(C1.line.z[names(Cat.AC.z)], Cat.AC.z)\n\nCPal = as.character(pals::brewer.spectral(length(sorted.istels)))\nAUCs = sapply(istel.perfs, function(x) x$auc)\nperm = order(AUCs, decreasing = T)\ngp = plot_roc(istel.perfs[perm], CPal)\n\n# L = c(istel.perfs, list(LX2 = lx2.perfs))\n# CPal = as.character(c(CPal.istel[rownames(X)[order(X[, 4])]], \"LX2\" = \"#aaaaaa\"))\n# perm = order(sapply(L, function(x) x$auc), decreasing = T)\n# gp = plot_roc(L[perm], CPal[perm])\n\n\n# sort(sapply(L, function(x) x$auc))\n\npdf(\"~/figures/TGFb_ROC_pStel_vs_iStel.pdf\", width = 12)\nprint(gp)\ndev.off()\n```\n\n\n```{r}\ngs = df$Label[df$Label != \"\"]\ngs = gs[-grep(\"MT-\", gs)]\n\n\n\n\n# SZ.genes = readr::read_rds(file.path(input.path, \"SCZ_associated_genesets.rds\"))\n# \n# gs = SZ.genes$\n\nl = as.numeric(rownames(bulk.profile.orth) %in% gs)\n\nlogPvals=-log10(p.adjust(apply(bulk.profile.orth, 2, function(x) {\n perm = order(x, decreasing = T)\n mhg.out = mhg::mhg_test(l[perm], length(l), sum(l), length(l), 5, upper_bound = F, tol = 1e-300)\n mhg.out$pvalue\n}), method = \"fdr\"))\n\ndf3 = data.frame(scores = logPvals, phenotype = bulk$Dx)\nggbarplot(df3, x = \"phenotype\", y = \"scores\", fill = \"phenotype\", palette = c(\"#666666\", \"#cccccc\"),\n add = \"mean_se\", label = TRUE, lab.vjust = -1.6) + geom_hline(yintercept = -log10(0.05), linetype=\"dashed\", \n color = \"red\", size=1)\n\nll = c(\"CON\", \"SZ\")\nisSZ.pred = ll[as.numeric(logPvals > -log10(0.05))+1]\ntable(isSZ.pred, bulk$Dx)\n\nsum((isSZ.pred == \"SZ\") & (bulk$Dx == \"SCZ\")) / sum((bulk$Dx == \"SCZ\"))\n\n ## AUC curve ...\n\n```\n\n\n\n```{r}\nplot.ACTIONet.gradient(ACTIONet_summary$ACTIONet2D, ACTIONet_summary$H_unified[, 30], alpha = 0)\nplot.ACTIONet.gradient(ACTIONet_summary$ACTIONet2D, ACTIONet_summary$H_unified[, 6], alpha = 0)\n\n\n```\n\n" }, { "alpha_fraction": 0.6374873518943787, "alphanum_fraction": 0.6632662415504456, "avg_line_length": 37.17719268798828, "blob_id": "78faeb2d0c5013175a6c7d2acfcbd89147a66dfe", "content_id": "dbad9aabdde43b0265b6e5f55511f6ee9adda21e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 21762, "license_type": "no_license", "max_line_length": 568, "num_lines": 570, "path": "/ancient/Fig2_Analyze_DE.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"Analyze DE genes\"\noutput: html_notebook\n---\n\n# Setup\n```{r include=FALSE}\nrequire(ACTIONet)\nrequire(stringr)\nrequire(ComplexHeatmap)\n\n\ndataset.path = \"~/results/datasets/\"\nresults.path = \"~/results\"\nfigures.folder = \"~/results/figures\"\ninput.folder = \"~/results/input\"\n\n\n```\n\n\n# Load primary datasets\n```{r}\nACTIONet_summary = readr::read_rds(file.path(dataset.path, \"ACTIONet_summary_filtered_individuals.rds\"))\n\npb.logcounts = readr::read_rds(file.path(dataset.path, \"PB_mean_logcounts_final.RDS\"))\n\ncolor.df = readRDS(file.path(dataset.path, \"celltype_colors.rds\"))\n\ncolors = color.df$color\nnames(colors) = color.df$celltype\n\n```\n\n# Load DE results\n```{r}\nresDE = readr::read_rds(file.path(dataset.path, \"Cohort_specific_DE_results_final_with_umi_scaled.rds\"))\n\nfiltered.tables = readr::read_rds(file.path(dataset.path, \"individual_diff_results_filtered_with_umi_scaled.rds\"))\n\ncombined.analysis.tables = readr::read_rds(file.path(dataset.path, \"meta_analysis_diff_results_with_umi_scaled.rds\"))\n\nfiltered.tables = readr::read_rds(file.path(dataset.path, \"individual_diff_results_filtered_full_with_umi_scaled.rds\"))\n\n\nDE.new = readr::read_rds(file.path(dataset.path, \"DE_genes_pseudobulk_final_with_umi_scaled.rds\"))\n\nUp.genes = DE.new$Up.genes\nDown.genes = DE.new$Down.genes\nDE.sc = DE.new$DE.sc\n\n```\n\n\n\n\n# Read bulk DE\n```{r}\nCMC.DE = read.table(\"~/results/input/CMC_DE_table.csv\", header = T)\nPEC.DE = read.table(\"~/results/input/PEC_DE_table.csv\", header = T)\n\ncommon.genes = intersect(rownames(pb.logcounts), intersect(CMC.DE$MAPPED_genes, PEC.DE$gene_name))\n\nCMC.tstat = CMC.DE$t[match(common.genes, CMC.DE$MAPPED_genes)]\nPEC.tstat = PEC.DE$SCZ.t.value[match(common.genes, PEC.DE$gene_name)]\n\nnames(PEC.tstat) = names(CMC.tstat) = common.genes\npval = cor.test(CMC.tstat, PEC.tstat, method = \"spearman\")$p.value\n\n\n```\n\n```{r}\ngg = intersect(Reduce(\"intersect\", lapply(resDE$McLean$table$PhenotypeSZ, function(df) df$gene)), Reduce(\"intersect\", lapply(resDE$MtSinai$table$PhenotypeSZ, function(df) df$gene)))\n\ncts = intersect(names(resDE$McLean$table$PhenotypeSZ), names(resDE$MtSinai$table$PhenotypeSZ))\n\nMcLean.tstat = do.call(cbind, lapply(1:length(cts), function(i) {\n df1 = resDE$McLean$table$PhenotypeSZ[[cts[[i]]]]\n df2 = resDE$MtSinai$table$PhenotypeSZ[[cts[[i]]]]\n\n df1 = df1[match(gg, df1$gene), ]\n df2 = df2[match(gg, df2$gene), ]\n \n v=df1$t\n names(v) = df1$gene\n \n mask = (abs(scale(df1$logFC)) > 1) & (abs(scale(df2$logFC)) > 1)\n v[!mask] = 0 \n return(v)\n}))\n\nMtSinai.tstat = do.call(cbind, lapply(1:length(cts), function(i) {\n df1 = resDE$McLean$table$PhenotypeSZ[[cts[[i]]]]\n df2 = resDE$MtSinai$table$PhenotypeSZ[[cts[[i]]]]\n\n df1 = df1[match(gg, df1$gene), ]\n df2 = df2[match(gg, df2$gene), ]\n \n v=df2$t\n names(v) = df1$gene\n \n mask = (abs(scale(df1$logFC)) > 1) & (abs(scale(df2$logFC)) > 1)\n v[!mask] = 0 \n return(v)\n}))\n\n# RdBu.pal = circlize::colorRamp2(seq(-0.5, 0.5, length.out = 7), rev(pals::brewer.puor(7)))\nCC = cor(McLean.tstat, MtSinai.tstat)\nrownames(CC) = colnames(CC) = cts\nCC[CC < 0] = 0\nct = intersect(names(resDE$MtSinai$table$PhenotypeSZ), names(resDE$McLean$table$PhenotypeSZ))\npdf(\"~/results/figures/pairwise_cor_masked_with_umi_scaled.pdf\")\nHeatmap(CC, cluster_rows = F, cluster_columns = F, name = \"Correlation (truncated)\", col = blues9, rect_gp = gpar(col = \"black\"), row_names_side = \"left\", row_names_gp = gpar(col = colors[rownames(CC)]), column_names_gp = gpar(col = colors[colnames(CC)]))\ndev.off()\n\n\n\n```\n\n\n```{r}\nlibrary(qvalue)\nMcLean.Pi1 = sapply(resDE$McLean$table$PhenotypeSZ, function(df) {\n pvals = df$p_val\n pi1 = 1 - qvalue(pvals)$pi0\n})\n\nMtSinai.Pi1 = sapply(resDE$MtSinai$table$PhenotypeSZ, function(df) {\n pvals = df$p_val\n pi1 = 1 - qvalue(pvals)$pi0\n})\ndf = data.frame(Celltype = union(names(resDE$MtSinai$table$PhenotypeSZ), names(resDE$McLean$table$PhenotypeSZ)))\ndf$McLean = McLean.Pi1[df$Celltype]\ndf$MtSinai = MtSinai.Pi1[df$Celltype]\n\ndf2 = reshape2::melt(df)\ncolnames(df2) = c(\"Celltype\", \"Cohort\", \"Pi1\")\n\ndf2$Celltype = factor(df2$Celltype, intersect(names(colors), df2$Celltype))\n\n# Genes + mit: 0.13294483 0.04830563\n# umis + mit: 0.12460625 0.04745068\nprint(c(mean(df$McLean[!is.na(df$McLean)]), mean(df$MtSinai[!is.na(df$MtSinai)], rm.na = T)))\n\nrequire(ggpubr)\ngg =ggbarplot(df2, \"Celltype\", \"Pi1\", fill = \"Cohort\", color = \"black\", palette = rev(pals::brewer.paired(5)),\n position = position_dodge(0.9), xlab = \"Celltype\", ylab = \"Pi1\")+ theme(axis.text.x = element_text(face=\"bold\", size=8, angle=90,hjust=0.95,vjust=0.2, color = colors[levels(df2$Celltype)]), axis.text.y = element_text(face=\"bold\", size=12, angle=0), axis.title = element_text(face=\"bold\", size=18, angle=0))\n\npdf(file.path(figures.folder, \"Pi1_with_umi_scaled.pdf\"))\nplot(gg)\ndev.off()\n\n\n```\n\n\n\n```{r}\nMcLean.PEC.cor.pvals = sapply(resDE$McLean$table$PhenotypeSZ, function(DF) {\n tstats = DF$t\n names(tstats) = DF$gene\n cg = intersect(common.genes, DF$gene)\n x = -log10(cor.test(tstats[cg], PEC.tstat[cg], method = \"spearman\")$p.value)\n \n return(x)\n})\n\n\nMtSinai.PEC.cor.pvals = sapply(resDE$MtSinai$table$PhenotypeSZ, function(DF) {\n tstats = DF$t\n names(tstats) = DF$gene\n cg = intersect(common.genes, DF$gene)\n x = -log10(cor.test(tstats[cg], PEC.tstat[cg], method = \"spearman\")$p.value)\n \n return(x)\n})\n\n\nMcLean.CMC.cor.pvals = sapply(resDE$McLean$table$PhenotypeSZ, function(DF) {\n tstats = DF$t\n names(tstats) = DF$gene\n cg = intersect(common.genes, DF$gene)\n x = -log10(cor.test(tstats[cg], CMC.tstat[cg], method = \"spearman\")$p.value)\n \n return(x)\n})\n\n\nMtSinai.CMC.cor.pvals = sapply(resDE$MtSinai$table$PhenotypeSZ, function(DF) {\n tstats = DF$t\n names(tstats) = DF$gene\n cg = intersect(common.genes, DF$gene)\n x = -log10(cor.test(tstats[cg], CMC.tstat[cg], method = \"spearman\")$p.value)\n \n return(x)\n})\n\ndf = data.frame(Celltypes = names(resDE$MtSinai$table$PhenotypeSZ), McLean.PEC = McLean.PEC.cor.pvals[names(resDE$MtSinai$table$PhenotypeSZ)], MtSinai.PEC = MtSinai.PEC.cor.pvals[names(resDE$MtSinai$table$PhenotypeSZ)], McLean.CMC = McLean.CMC.cor.pvals[names(resDE$MtSinai$table$PhenotypeSZ)], MtSinai.CMC = MtSinai.CMC.cor.pvals[names(resDE$MtSinai$table$PhenotypeSZ)])\ndf$Combined = combine.logPvals(t(as.matrix(df[, -1])))\ndf = df[order(df$Combined, decreasing = T), ]\n\ndf = df[, 1:3]\n\ndf2 = reshape2::melt(df)\ncolnames(df2) = c(\"Celltype\", \"Test\", \"Enrichment\")\ndf2$Test = factor(as.character(df2$Test), c(\"McLean.PEC\", \"MtSinai.PEC\", \"McLean.CMC\", \"MtSinai.CMC\"))\n# df2$Celltype = factor(df2$Celltype, df$Celltypes[order(pmax(cbind(df$McLean.PEC, df$MtSinai.PEC)), decreasing = T)])\ndf2$Celltype = factor(df2$Celltype, intersect(names(colors), df$Celltypes))\n\nrequire(ggpubr)\ngg =ggbarplot(df2, \"Celltype\", \"Enrichment\", fill = \"Test\", color = \"black\", palette = rev(pals::brewer.paired(5)),\n position = position_dodge(0.9), xlab = \"Celltype\", ylab = \"Enrichment\")+ theme(axis.text.x = element_text(face=\"bold\", size=8, angle=90,hjust=0.95,vjust=0.2, color = colors[levels(df2$Celltype)]), axis.text.y = element_text(face=\"bold\", size=12, angle=0), axis.title = element_text(face=\"bold\", size=18, angle=0))\n\npdf(file.path(figures.folder, \"DE_vs_bulk_with_umi_scaled.pdf\"))\nplot(gg)\ndev.off()\n\n\n\n\n```\n\n\n\n## Overlap among DE genes of different archetypes\n### Compute pairwise overlap using RRHO\n```{r}\nlibrary(RRHO)\nlibrary(gplots)\n\n\tcts = names(DE.new$Up.genes)\n\tDE.overlap.RRHO.mats = vector(\"list\", length(cts)*length(cts))\n\t\n\tfor(i1 in 1:length(cts)) {\n\t ct1 = cts[[i1]]\n DE.results1 = filtered.tables[[ct1]]$McClean\n\t df1 = data.frame(Gene = DE.results1$gene, tstats = DE.results1$t)\n\t\n\t for(i2 in 1:length(cts)) {\n \t ct2 = cts[[i2]]\n DE.results2 = filtered.tables[[ct1]]$MtSinai\n # DE.results2 = resDE$MtSinai$table$PhenotypeSZ[[ct2]]\n \t df2 = data.frame(Gene = DE.results2$gene, tstats = DE.results2$t)\n\t \n \t \n\t R.utils::printf(\"\\t%s vs %s ... \", ct1, ct2)\n\t \n\t n1 = paste(\"McLean\", ct1, sep = \"_\")\n\t n2 = paste(\"MtSinai\", ct2, sep = \"_\")\n\t \n\t RRHO.example = RRHO(df1, df2, outputdir= file.path(results.path, \"RRHO\"), alternative=\"enrichment\", labels=c(n1, n2), BY=TRUE, log10.ind=TRUE, plot=TRUE)\n\t \n\t idx = (i1-1)*length(cts)+i2\n\t DE.overlap.RRHO.mats[[idx]] = apply(t(RRHO.example[[4]]),1,rev)\n\t \n\t # DE.overlap.RRHO.mats[[(i2-1)*length(ct)+i1]] = DE.overlap.RRHO.mats[[(i1-1)*length(ct)+i2]]\n\t \n\t # Heatmap(apply(t(RRHO.example[[4]]),1,rev), cluster_columns = F, cluster_rows = F)\n\t # \n\t R.utils::printf(\"%.2f (%d)\\n\", max(DE.overlap.RRHO.mats[[idx]]), idx)\n\t \n\t }\n\t}\n\n\t\n\t\n\tsaveRDS(DE.overlap.RRHO.mats, file.path(results.path, \"DE_overlap_RRHO.RDS\"))\n\n\n```\n\n### Plot RRHO heatmaps as a grid\n```{r}\nrequire(viridis)\ngradPal_fun = circlize::colorRamp2(c(5, 50, 100, 200, 250, 350), viridis::viridis(6))\n\n\n# pdf(sprintf(\"%s/Limma_tstat_RRHO.pdf\", width = 30, height = 30)\npng(sprintf(\"%s/tstat_RRHO_v3.png\", figures.folder), width = 10000, height = 10000, res = 300)\npushViewport(viewport(layout = grid.layout(20, 20)))\n\ni = 0\nfor(r in 1:length(cts)) {\n ht = c()\n for(c in 1:length(cts)) {\n idx = (r-1)*length(cts)+c\n X = DE.overlap.RRHO.mats[[idx]]\n X[X > 350] = 350\n ht = Heatmap(X, cluster_rows = F, cluster_columns = F, col = gradPal_fun, show_heatmap_legend = FALSE, gap = 0, column_gap = 0)\n \n pushViewport(viewport(layout.pos.col=c, layout.pos.row=r))\n draw(ht, newpage = FALSE) # or draw(ht_list, newpage = FALSE)\n popViewport()\n } \n}\ndev.off()\n\n\n```\n\n\n\n\n```{r}\nSZ.genes = readr::read_rds(file.path(input.folder, \"SCZ_associated_genesets.rds\"))\n\n```\n\n## Total number of DE genes\n```{r}\nUp.genes.overlap = sapply(Up.genes, function(gs) intersect(gs, SZ.genes$`Up.genes (PEC)`))\nUp.genes.size = sapply(Up.genes.overlap, length) # 287 unique genes (14% of DE up bulk)\n\nDown.genes.overlap = sapply(Down.genes, function(gs) intersect(gs, SZ.genes$`Down.genes (PEC)`))\nDown.genes.size = sapply(Down.genes.overlap, length) # 475 unique genes (26.5% of DE down bulk)\n\ncelltype.colors = colors[names(Up.genes)]\n# names(celltype.colors) = names(Up.genes)\n\ndf.Up = data.frame(Counts = sapply(Up.genes, function(x) length(setdiff(x, SZ.genes$`DE.Up (PEC)`))), Celltype = names(Up.genes), Direction=\"Up\", Color = celltype.colors[names(Up.genes)], stringsAsFactors = F)\n\ndf.UpandBulk = data.frame(Counts = sapply(Up.genes, function(x) length(intersect(x, SZ.genes$`DE.Up (PEC)`))), Celltype = names(Up.genes), Direction=\"Up & Bulk\", Color = celltype.colors[names(Up.genes)], stringsAsFactors = F)\n\n\ndf.Down = data.frame(Counts = -sapply(Down.genes, function(x) length(setdiff(x, SZ.genes$`DE.Down (PEC)`))), Celltype = names(Down.genes), Direction=\"Down\", Color = celltype.colors[names(Down.genes)], stringsAsFactors = F)\n\ndf.DownandBulk = data.frame(Counts = -sapply(Down.genes, function(x) length(intersect(x, SZ.genes$`DE.Down (PEC)`))), Celltype = names(Down.genes), Direction=\"Down & Bulk\", Color = celltype.colors[names(Down.genes)], stringsAsFactors = F)\n\n\n\ndf = rbind(df.Up, df.UpandBulk, df.Down, df.DownandBulk)\n\ntotal.Up = sapply(Up.genes, length)\ntotal.Down = sapply(Down.genes, length)\n\nset.seed(0)\ntotal = total.Up + total.Down + 0.001*rnorm(length(Up.genes))\n\narch.perm = order(total, decreasing = F)\ndf$Celltype = factor(df$Celltype, names(total)[arch.perm])\n\npdf(file.path(figures.folder, \"NumDysregGenes_with_umi_scaled.pdf\"), width = 8, height = 5)\nggplot(data = df, aes(x = Celltype, y = Counts, fill = Direction)) + geom_bar(stat = \"identity\")+\n coord_flip()+ylab(\"Sorted Celltypes\")+\nlabs(y = \"# Genes\", x = \"Sorted Celltypes\")+\n theme_minimal()+\n guides(fill = FALSE)+ scale_fill_manual(values=c(\"#3288bd\", colorspace::darken(\"#3288bd\", 0.35), \"#d53e4f\", colorspace::darken(\"#d53e4f\", 0.35))) + theme(axis.text.y = element_text(face=\"bold\", color=celltype.colors[levels(df$Celltype)], size=12, angle=0), axis.text.x = element_text(face=\"bold\", color=\"black\", size=12, angle=0), axis.title = element_text(face=\"bold\", size=14, angle=0))\ndev.off()\n\n\n\n\n\n```\n# Functional enrichment\n## Load annotations\n```{r}\nFunCat = readRDS(file.path(dataset.path, \"FunCat.rds\"))\n\nFunCat.genes = split(FunCat$FunCat2Gene$Gene, factor(FunCat$FunCat2Gene$Category, unique(FunCat$FunCat2Gene$Category)))[-15]\nnames(FunCat.genes) = FunCat$FunCat2Class$Category\n\nFunCat.annotation = FunCat$FunCat2Class$Classification\n\nFunCatPal = ggpubr::get_palette(\"npg\", length(unique(FunCat.annotation)))\nnames(FunCatPal) = unique(FunCat.annotation)\n\n\n```\n## Perform enrichment\n\n```{r}\nassess.genesets <-function (arch.gs, terms.gs, N, min.pval = 1e-100, correct = NULL){\n shared = t(sapply(terms.gs, function(gs1) {\n sapply(arch.gs, function(gs2) {\n nn = intersect(gs1, gs2)\n })\n }))\n colnames(shared) = names(arch.gs)\n GS.sizes = sapply(terms.gs, length)\n logPvals.out = sapply(1:ncol(shared), function(i) {\n gg = shared[, i]\n x = as.numeric(sapply(gg, length))\n n.sample = length(arch.gs[[i]])\n n.success = as.numeric(GS.sizes)\n v = rep(1, length(x))\n min.overlap = n.success * n.sample/N\n idx = which(x >= min.overlap)\n if (length(idx) == 0) \n return(v)\n v[idx] = (phyper(x[idx], n.sample, N-n.sample, n.success[idx], lower.tail = F))\n # v[idx] = HGT_tail(population.size = N, success.count = n.success[idx], \n # sample.size = n.sample, observed.success = x[idx])\n return(v)\n })\n if(correct == \"global\") {\n logPvals.out = matrix(p.adjust(logPvals.out, \"fdr\"), nrow = nrow(logPvals.out))\n } else if(correct == \"local\") {\n logPvals.out = apply(logPvals.out, 2, function(x) p.adjust(x, \"fdr\"))\n }\n rownames(logPvals.out) = names(terms.gs)\n colnames(logPvals.out) = names(arch.gs)\n return(-log10(Matrix::t(logPvals.out)))\n}\n```\n\n\n```{r}\nUp.enrichment.GS = assess.genesets(Up.genes, SZ.genes, nrow(pb.logcounts), correct = \"global\")\nDown.enrichment.GS = assess.genesets(Down.genes, SZ.genes, nrow(pb.logcounts), correct = \"global\")\n\n\nDd = cbind(Up.enrichment.GS[, 5], Down.enrichment.GS[, 6])\ncolnames(Dd) = c(\"Up\", \"Down\")\nwrite.table(Dd, file.path(results.path, \"DE_overlap_with_bulk.tsv\"), sep = \"\\t\", row.names = T, col.names = T, quote = F)\n\n\n```\n\n\n```{r}\nUp.enrichment = assess.genesets(FunCat.genes, Up.genes[1:17], nrow(pb.logcounts), correct = \"global\")\nDown.enrichment = assess.genesets(FunCat.genes, Down.genes[1:17], nrow(pb.logcounts), correct = \"global\")\n\nUp.enrichment[Up.enrichment < -log10(0.05)] = 0\nDown.enrichment[Down.enrichment < -log10(0.05)] = 0\n\nha_rows = rowAnnotation(df = list(\"Class\" = FunCat.annotation), col = list(\"Class\" = FunCatPal), annotation_legend_param = list(\"Class\"=list(title_gp = gpar(fontsize = 0), labels_gp = gpar(fontsize = 10))))\n\n\nX.U = (Up.enrichment)\n# redCol_fun = circlize::colorRamp2(c(quantile(X.U, 0.25), quantile(X.U, 0.5), quantile(X.U, 0.85), quantile(X.U, 0.99)), c(\"#ffffff\", \"#fee5d9\", \"#ef3b2c\", \"#99000d\"))\nredCol_fun = circlize::colorRamp2(c(0, exp(quantile(log(X.U)[X.U > 2], seq(0.01, 0.95, length.out = 12)))), c(\"#ffffff\", pals::brewer.reds(12)))\n\nX.D = (Down.enrichment)\n# blueCol_fun = circlize::colorRamp2(c(quantile(X.D, 0.25), quantile(X.U, 0.5), quantile(X.D, 0.85), quantile(X.D, 0.99)), c( \"#ffffff\", \"#9ecae1\", \"#2171b5\", \"#08306b\"))\n\nblueCol_fun = circlize::colorRamp2(c(0, exp(quantile(log(X.D)[X.D > 2], seq(0.01, 0.95, length.out = 12)))), c(\"#ffffff\", pals::brewer.blues(12)))\n\n# pals::brewer.reds()\n\n\npdf(file.path(figures.folder, \"DE_FunCat_enrichment_meta_filtered_with_umi_scaled_neuro.pdf\"), width = 14, height = 7)\npar(mar=c(0,150,0,0))\nHeatmap(X.U, rect_gp = gpar(col = \"black\"), name = \"Up\", column_title = \"Up-regulated\", cluster_rows = F, cluster_columns = F, col = redCol_fun, row_names_side = \"left\", column_names_gp = gpar(fontsize = 14, fontface=\"bold\", col = colors[colnames(X.U)]), row_names_gp = gpar(fontsize = 14, fontface=\"bold\", col = FunCatPal[FunCat.annotation]), column_title_gp = gpar(fontsize = 18, fontface=\"bold\"), row_title_gp = gpar(fontsize = 18, fontface=\"bold\"), row_names_max_width = unit(150, \"cm\"), column_names_max_height = unit(150, \"cm\"))+\nHeatmap(X.D, rect_gp = gpar(col = \"black\"), name = \"Down\", cluster_rows = F, cluster_columns = F, col = blueCol_fun, row_names_side = \"left\", column_title = \"Down-regulated\", column_names_gp = gpar(fontsize = 14, fontface=\"bold\", col = colors[colnames(X.D)]), row_names_gp = gpar(fontsize = 14, fontface=\"bold\", col = FunCatPal[FunCat.annotation]), column_title_gp = gpar(fontsize = 18, fontface=\"bold\"), row_title_gp = gpar(fontsize = 18, fontface=\"bold\"), right_annotation = ha_rows, row_names_max_width = unit(150, \"cm\"), column_names_max_height = unit(150, \"cm\"))\ndev.off()\n\n```\n\n\n\n```{r}\ngp.stringent.up = gProfileR::gprofiler(DE.new$Up.genes, hier_filtering = \"strong\", src_filter = c(\"GO:BP\"))\ngp.moderate.up = gProfileR::gprofiler(DE.new$Up.genes, hier_filtering = \"moderate\", src_filter = c(\"GO:BP\"))\ngp.none.up = gProfileR::gprofiler(DE.new$Up.genes, hier_filtering = \"none\", src_filter = c(\"GO:BP\"))\n\n\ngp.stringent.down = gProfileR::gprofiler(DE.new$Down.genes, hier_filtering = \"strong\", src_filter = c(\"GO:BP\"))\ngp.moderate.down = gProfileR::gprofiler(DE.new$Down.genes, hier_filtering = \"moderate\", src_filter = c(\"GO:BP\"))\ngp.none.down = gProfileR::gprofiler(DE.new$Down.genes, hier_filtering = \"none\", src_filter = c(\"GO:BP\"))\n\n# \n# \n# common.terms.id = sort(unique(union(gp.none.up$term.id, gp.none.down$term.id)))\n\ndata(\"gProfilerDB_human\")\nBP = gProfilerDB_human$SYMBOL$`GO:BP`\n\ngp.combined = rbind(gp.none.up, gp.none.down)\ngp.combined = gp.combined[gp.combined$term.name %in% colnames(BP), ]\n\nwrite.table(gp.combined, file.path(results.path, \"Combined_DE_BP_enrichment.tsv\"), sep = \"\\t\", row.names = F, col.names = T, quote = F)\n\ncommon.terms.id = sort(unique(gp.combined$term.id))\nselected.cols = match(gp.combined$term.name[match(common.terms.id, gp.combined$term.id)], colnames(BP))\n\ncommon.terms.names = colnames(BP)[selected.cols]\n\n\n\nlibrary(simplifyEnrichment)\nGOSemSim = GO_similarity(common.terms.id)\n\n\n# compare_clustering_methods(GOSemSim, plot_type = \"heatmap\")\n\nset.seed(0)\npdf(file.path(figures.folder, \"GO_simplified.pdf\"), width = 10)\nGOdf = simplifyGO(GOSemSim)\ndev.off()\n\nGOdf2 = GOdf[order(GOdf$cluster), ]\n\n\ngo.cl = split(GOdf$term, GOdf$cluster)\nGOdf2 = GOdf2[GOdf2$cluster %in% which(sapply(go.cl, length) > 2), ]\nGOdf2$row = match(GOdf2$cluster, unique(GOdf2$cluster))\n\nwrite.table(GOdf2, file.path(results.path, \"Combined_DE_BP_clusters.tsv\"), sep = \"\\t\", row.names = F, col.names = T, quote = F)\n\n\ngo.cl = go.cl[sapply(go.cl, length) > 2]\n\ndfs = split(gp.none.up, gp.none.up$query.number)\nUp.go.cl.enrichment = matrix(0, nrow = length(go.cl), ncol = length(Up.genes))\ncolnames(Up.go.cl.enrichment) = names(Up.genes)\nfor(i in 1:length(dfs)) {\n df = dfs[[i]]\n for(j in 1:length(go.cl)) {\n kk = which(df$term.name %in% go.cl[[j]])\n if(length(kk) == 0) {\n next \n } else {\n Up.go.cl.enrichment[j, names(dfs)[[i]]] = combine.logPvals(as.matrix(-log10(df$p.value[kk])))\n }\n }\n}\n\ndfs = split(gp.none.down, gp.none.down$query.number)\nDown.go.cl.enrichment = matrix(0, nrow = length(go.cl), ncol = length(Down.genes))\ncolnames(Down.go.cl.enrichment) = names(Down.genes)\nfor(i in 1:length(dfs)) {\n df = dfs[[i]]\n for(j in 1:length(go.cl)) {\n kk = which(df$term.name %in% go.cl[[j]])\n if(length(kk) == 0) {\n next \n } else {\n Down.go.cl.enrichment[j, names(dfs)[[i]]] = combine.logPvals(as.matrix(-log10(df$p.value[kk])))\n }\n }\n}\n\n\n# go.cl = split(df$term, df$cluster)\n# go.cl.genes = lapply(go.cl, function(terms) {\n# terms = intersect(terms, colnames(BP))\n# if(length(terms) == 1) {\n# selected.rows = which(BP[, terms] > 0)\n# } else {\n# selected.rows = which(fast_column_sums(BP[, terms]) > 0)\n# }\n# rownames(BP)[selected.rows]\n# })\n# Up.go.cl.enrichment = assess.genesets(go.cl.genes, Up.genes, nrow(pb.logcounts))\n# Down.go.cl.enrichment = assess.genesets(go.cl.genes, Down.genes, nrow(pb.logcounts))\n\n\n\n# MPal = pals::polychrome(length(TF.mods))\n# names(MPal) = paste(\"BP_M\", 1:length(TF.mods), sep = \"\")\n# ha_row = rowAnnotation(Module = factor(unlist(lapply(1:length(TF.mods), function(i) paste(\"BP_M\", rep(i, length(TF.mods[[i]])), sep = \"\"))), paste(\"BP_M\", 1:length(TF.mods), sep = \"\")), col = list(Module = MPal))\n\n\nX.U = (Up.go.cl.enrichment)\n# redCol_fun = circlize::colorRamp2(c(quantile(X.U, 0.25), quantile(X.U, 0.5), quantile(X.U, 0.85), quantile(X.U, 0.99)), c(\"#ffffff\", \"#fee5d9\", \"#ef3b2c\", \"#99000d\"))\nredCol_fun = circlize::colorRamp2(c(0, exp(quantile(log(X.U)[X.U > 2], seq(0.05, 0.95, length.out = 12)))), c(\"#ffffff\", pals::brewer.reds(12)))\n\nX.D = (Down.go.cl.enrichment)\n# blueCol_fun = circlize::colorRamp2(c(quantile(X.D, 0.25), quantile(X.U, 0.5), quantile(X.D, 0.85), quantile(X.D, 0.99)), c( \"#ffffff\", \"#9ecae1\", \"#2171b5\", \"#08306b\"))\n\nblueCol_fun = circlize::colorRamp2(c(0, exp(quantile(log(X.D)[X.D > 2], seq(0.05, 0.95, length.out = 12)))), c(\"#ffffff\", pals::brewer.blues(12)))\n\npdf(file.path(figures.folder, \"GO_modules_enrichment.pdf\"), width = 12, height = 6)\nHeatmap(Up.go.cl.enrichment, rect_gp = gpar(col = \"black\"), cluster_columns = F, cluster_rows = F, column_title = \"Up\", column_title_gp = gpar(fontsize = 12), column_names_gp = gpar(col = colors[colnames(TF.up)]), name = \"Up\", col = redCol_fun) + Heatmap(Down.go.cl.enrichment, rect_gp = gpar(col = \"black\"), cluster_columns = F, cluster_rows = F, column_title = \"Down\", column_title_gp = gpar(fontsize = 12), column_names_gp = gpar(col = colors[colnames(TF.down)]), name = \"Down\", row_names_side = \"left\", col = blueCol_fun)\ndev.off()\n\n```\n\n" }, { "alpha_fraction": 0.6256188154220581, "alphanum_fraction": 0.666460394859314, "avg_line_length": 25.933332443237305, "blob_id": "c708484c38041e9a80aaeb765d31cc7d9ed6104d", "content_id": "e7029056750e7bfd3bb7d4ff098fce1993bc8770", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1616, "license_type": "no_license", "max_line_length": 72, "num_lines": 60, "path": "/old/filter_Panos.py", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "import scrublet as scr\nimport scanpy as sc\nimport anndata as ad\nimport numpy as np\nfrom scipy.sparse import csr_matrix\n\nadata = ad.read_h5ad(\"Panos_raw_sce_simplified.h5ad\") # (187277, 33226)\nadata.var[\"mt\"] = adata.var_names.str.startswith(\n \"MT-\"\n) # annotate the group of mitochondrial genes as 'mt'\nsc.pp.calculate_qc_metrics(\n adata, qc_vars=[\"mt\"], percent_top=None, log1p=False, inplace=True,\n)\nadata = adata[\n (1000 <= adata.obs.n_genes_by_counts)\n & (adata.obs.pct_counts_mt <= 10)\n & (adata.obs.total_counts <= 50000),\n] # (144543, 33226)\n\naces = []\nsets = np.unique(adata.obs[\"set_ID\"])\nfor set_id in sets:\n print(set_id)\n sub_adata = adata[\n adata.obs[\"set_ID\"] == set_id,\n ]\n # Remove doublets\n counts_matrix = sub_adata.X\n scrub = scr.Scrublet(counts_matrix)\n doublet_scores, predicted_doublets = scrub.scrub_doublets()\n sub_adata.obs[\"scrublet_doublet_scores\"] = doublet_scores\n sub_adata.obs[\"scrublet_is_doublet\"] = predicted_doublets\n sub_adata = sub_adata[\n sub_adata.obs[\"scrublet_is_doublet\"] == False,\n ]\n aces.append(sub_adata)\n\nmerged_ace = ad.concat(aces) # (140917, 33226)\nmerged_ace.obs_names_make_unique()\n\nsc.pp.filter_genes(\n merged_ace,\n min_counts=None,\n min_cells=round(0.001 * merged_ace.shape[0]),\n max_counts=None,\n max_cells=None,\n inplace=True,\n copy=False,\n) # (140917, 24458)\n\nmerged_ace.X = csr_matrix(merged_ace.X)\n\n\"\"\"\nsc.pp.normalize_total(merged_ace)\nsc.pp.log1p(merged_ace)\n\nsc.pp.highly_variable_genes(merged_ace)\n\"\"\"\n\nmerged_ace.write_h5ad(\"Panos_doublet_removed_counts.h5ad\")\n" }, { "alpha_fraction": 0.8095238208770752, "alphanum_fraction": 0.8095238208770752, "avg_line_length": 20, "blob_id": "ebd2ce30d0892ed5e94ccfdb89bccc6139766778", "content_id": "3e4ad21b6e45ce9df6649d0f429f9d65d2f1375a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 42, "license_type": "no_license", "max_line_length": 34, "num_lines": 2, "path": "/ancient/README.md", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "# snSZ\nSingle-cell atlas of schizophrenia\n" }, { "alpha_fraction": 0.613766610622406, "alphanum_fraction": 0.6460071206092834, "avg_line_length": 34.80908966064453, "blob_id": "0c6751fad9b58c2e218388357c60cca90a0f84e4", "content_id": "c10eb0ef4377c1d16d3f19e24066b2c85e941140", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 27574, "license_type": "no_license", "max_line_length": 474, "num_lines": 770, "path": "/old/CellStates_vs_bulk.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"Fig3: H-MAGMA analysis\"\noutput: html_notebook\n---\n# Setup\n```{r include=FALSE}\n# library(org.Hs.eg.db)\nrequire(ACTIONet)\nrequire(stringr)\nrequire(ComplexHeatmap)\n\n\nresults.path = \"~/results\"\ninput.path = \"~/results/input\"\ndataset.path = \"~/results/datasets\"\ntables.path = \"~/results/tables\"\nfigures.path = \"~/results/figures\"\n\n\n```\n\n# Load primary datasets\n```{r, eval = T}\nACTIONet_summary = readr::read_rds(file.path(dataset.path, \"ACTIONet_summary_filtered_individuals.rds\"))\npb.logcounts = readr::read_rds(file.path(dataset.path, \"PB_mean_logcounts_final.RDS\"))\n\ncolor.df = readRDS(file.path(dataset.path, \"celltype_colors.rds\"))\ncolors = color.df$color\nnames(colors) = color.df$celltype\n\n```\n\n\n# Load DE results\n```{r, eval = T}\nresDE = readr::read_rds(file.path(dataset.path, \"Cohort_specific_DE_results.rds\"))\nfiltered.tables = readr::read_rds(file.path(dataset.path, \"Cohort_specific_DE_results_filtered.rds\"))\ncombined.analysis.tables = readr::read_rds(file.path(dataset.path, \"meta_analysis_results.rds\"))\n\nDE.new = readRDS(file.path(dataset.path, \"DE_genes_pseudobulk.rds\"))\nUp.genes = DE.new$Up.genes\nDown.genes = DE.new$Down.genes\nDE.sc = DE.new$DE.sc\n\n```\n\n\n\n# Load bulk expression\n```{r}\nbulk = readr::read_rds(\"~/results/input/MPP_bulk_expression_SZandCON.rds\")\nbulk.profile = assays(bulk)$voom\nbulk.profile.orth = orthoProject(bulk.profile, Matrix::rowMeans(bulk.profile))\n\n```\n\n\n```{r}\nmask = pb.logcounts$POP.EL3SD == \"EUR\"\ntable(pb.logcounts$Cohort[mask])\n\n\ncor.test(pb.logcounts$TPS.All[mask], pb.logcounts$PRS[mask], method = \"pearson\")\n\n\ncor.test(pb.logcounts$A29.signature[mask], pb.logcounts$TPS.All[mask], method = \"pearson\")\n\n\n```\n```{r}\ndata()\n\n```\n\n\n\n```{r}\narch.annot = annotate.archetypes.using.labels(t(ACTIONet_summary$H_unified), ACTIONet_summary$metadata$Labels)\n\narch.labels = paste(\"A\", 1:ncol(ACTIONet_summary$H_unified), \"-\", arch.annot$Label, sep = \"\")\narch.labels[c(7, 11, 17, 29)] = paste(\"A\", c(7, 11, 17, 29), \"-\", c(\"Ex-NRGN\", \"Ex-SZ\", \"Ex-SZTR\", \"In-SZ\"), sep = \"\")\n\narch.order = c(setdiff(order(match(arch.annot$Label, names(colors))), c(11, 17, 29)), c(11, 17, 29))\n\n```\n\n```{r}\ncelltype.spec = readRDS(\"~/results/datasets/celltype_gene_specificity.rds\")\n\ncommon.genes = intersect(rownames(celltype.spec), rownames(bulk.profile.orth))\n\ncc.celltypes = cor(bulk.profile.orth[common.genes, ], celltype.spec[common.genes, ])\nrownames(cc.celltypes) = bulk$SampleID\n\ndf = as.data.frame(cc.celltypes)\ndf$Phenotype = bulk$Dx\ndf$ID = bulk$SampleID\nsaveRDS(df, file.path(dataset.path, \"celltypes_vs_bulk_cor.rds\"))\n\n\n\n\nsample.sets = split(bulk$SampleID, bulk$Dx)\npvals.celltypes=apply(cc.celltypes, 2, function(x) {\n gsea.out = fgsea(sample.sets, x, eps = 0)\n return(gsea.out$pval)\n})\n# pvals.corrected = -log10(p.adjust(pvals, \"fdr\"))\n# Enrichment = t(matrix(pvals.corrected, nrow = 2))\nEnrichment = t(-log10(apply(pvals.celltypes, 2, function(p) p.adjust(p, \"fdr\"))))\ncolnames(Enrichment) = names(sample.sets)\nEnrichment[Enrichment < -log10(0.05)] = 0\n\nHeatmap(Enrichment)\n\n```\n\n```{r}\narch.spec = readRDS(\"~/results/datasets/archetype_gene_specificity.rds\")\n\n\ncommon.genes = intersect(rownames(arch.spec), rownames(bulk.profile.orth))\n\ncc = cor(bulk.profile.orth[common.genes, ], arch.spec[common.genes, ])\nrownames(cc) = bulk$SampleID\n\nsample.sets = split(bulk$SampleID, bulk$Dx)\npvals=apply(cc, 2, function(x) {\n gsea.out = fgsea(sample.sets, x, eps = 0)\n return(gsea.out$pval)\n})\n# pvals.corrected = -log10(p.adjust(pvals, \"fdr\"))\n# Enrichment = t(matrix(pvals.corrected, nrow = 2))\nEnrichment = t(-log10(apply(pvals, 2, function(p) p.adjust(p, \"fdr\"))))\nrownames(Enrichment) = arch.labels\ncolnames(Enrichment) = names(sample.sets)\nEnrichment[Enrichment < -log10(0.05)] = 0\n\ndf = as.data.frame(cc[, arch.order])\ncolnames(df) = arch.labels[arch.order]\ndf$Phenotype = bulk$Dx\ndf$ID = bulk$SampleID\nsaveRDS(df, file.path(dataset.path, \"cellstates_vs_bulk_cor.rds\"))\n\n\n# PurPal = colorRampPalette(RColorBrewer::brewer.pal(11, \"Purples\"))(200)\n\npdf(file.path(figures.path, \"Archs_vs_bulk_fgsea_states.pdf\"), width = 3.5, height = 2)\nHeatmap(Enrichment[arch.order[c(1, 29:31)], ], cluster_rows = F, cluster_columns = F, rect_gp = gpar(col = \"black\"), row_names_side = \"left\", row_names_gp = gpar(col = colors[arch.annot$Label[arch.order]]), name = \"Enrichment\", col = PurPal)\ndev.off()\n\n\n```\n\n\n\n```{r}\nrequire(openxlsx)\n\nPEC_modules = readLines(con <- file(\"~/PEC_modules/INT-09_WGCNA_modules_hgnc_ids.csv\"))\n\n\nmod.names = lapply(PEC_modules, function(x) str_split(x, \"\\t\")[[1]][1])\nPEC_modules.genes = lapply(PEC_modules, function(x) sort(unique(str_split(x, \"\\t\")[[1]][-1])))\nnames(PEC_modules.genes) = mod.names\n\nSZ.mods = c(\"module_3628\", \"module_3636\", \"module_3711\", \"module_3251\", \"module_1749\", \"module_2752\", \"module_3001\", \"module_3009\", \"module_3172\", \"module_3332\", \"module_3333\", \"module_3464\", \"module_3614\", \"module_725\", \"module_738\", \"module_1685\", \"module_1755\", \"module_2692\", \"module_3107\", \"module_3184\", \"module_3316\", \"module_3349\", \"module_3381\", \"module_3496\", \"module_3543\", \"module_3616\", \"module_3673\", \"module_3678\", \"module_3693\", \"module_3709\", \"module_3731\")\nPEC_modules.genes.SZ = PEC_modules.genes[SZ.mods]\n\n\narch.spec = ACTIONet_summary$unified_feature_specificity\nassociations = do.call(cbind, lapply(PEC_modules.genes, function(mod) as.numeric(rownames(arch.spec) %in% mod)))\ncolnames(associations) = mod.names\nrownames(associations) = rownames(arch.spec)\nPEC.mod.en = assess.geneset.enrichment.from.scores(arch.spec, associations)\nPEC.mod.logPvals = PEC.mod.en$logPvals\ncolnames(PEC.mod.logPvals) = colnames(arch.spec)\nrownames(PEC.mod.logPvals) = mod.names\n \n# plot.top.k.features(PEC.mod.logPvals)\n\n\n\npdf(file.path(figures.path, \"Archs_vs_PEC_SZ_modules_cellstates.pdf\"), width = 10, height = 2)\nHeatmap(X[29:31, ], cluster_rows = F, cluster_columns = F, rect_gp = gpar(col = \"black\"), row_names_side = \"left\", row_names_gp = gpar(col = colors[arch.annot$Label[arch.order[29:31]]]), name = \"Enrichment\", col = blues9)\ndev.off()\n\n\n```\n```{r}\nMod.vs.DE.up = assess.genesets(Up.genes, PEC_modules.genes[SZ.mods], nrow(pb.logcounts), correct = \"local\")\nMod.vs.DE.down = assess.genesets(Down.genes, PEC_modules.genes[SZ.mods], nrow(pb.logcounts), correct = \"local\")\n\n\n# Mod.vs.DE.up[Mod.vs.DE.up < -log10(0.05)] = 0\n# Y = Mod.vs.DE.up\n# Rd.pal = circlize::colorRamp2(seq(0, quantile(Y, 0.99), length.out = 8), c(\"#ffffff\", pals::brewer.reds(7)))\n\nMod.vs.DE.down[Mod.vs.DE.down < -log10(0.05)] = 0\nX = Mod.vs.DE.down\nBu.pal = circlize::colorRamp2(seq(0, quantile(X, 0.99), length.out = 8), c(\"#ffffff\", pals::brewer.blues(7)))\n\n\n\npdf(file.path(figures.path, \"DE_Down_vs_PEC_SZ_modules.pdf\"), width = 9)\nHeatmap(X, cluster_rows = F, rect_gp = gpar(col = \"black\"), name = \"Down\", row_names_side = \"left\", row_names_gp = gpar(col = colors), col = Bu.pal)\ndev.off()\n\n\n\n\n```\n\n\n\n## Celltype enrichment \n```{r}\nLabels = as.character(ACTIONet_summary$metadata$Labels)\n\nLabels[grep(\"^In\", Labels)] = \"In\"\nLabels[grep(\"^Ex\", Labels)] = \"Ex\"\nLabels[!grepl(\"^Ex|^In\", Labels)] = \"Glial\"\n\n# Arch.vs.celltype.df = data.frame(A7 = ACTIONet_summary$H_unified[, 7], A11 = ACTIONet_summary$H_unified[, 11], A17 = ACTIONet_summary$H_unified[, 17], A29 = ACTIONet_summary$H_unified[, 29], Celltype = Labels)\n# \nArch.vs.celltype.df = data.frame(A11 = ACTIONet_summary$H_unified[, 11], A29 = ACTIONet_summary$H_unified[, 29], Celltype = Labels)\n\nArch.vs.celltype.df = Arch.vs.celltype.df[(Arch.vs.celltype.df$Celltype != \"Glial\") & (apply(cbind(ACTIONet_summary$H_unified[, 11], ACTIONet_summary$H_unified[, 29]), 1, max) > 0.5), ]\n\n\n\n# \n# df = reshape2::melt(Arch.vs.celltype.df)\n# colnames(df) = c(\"Celltype\", \"Archetype\", \"Score\")\n# \n# ggviolin(df, \"Archetype\", \"Score\", fill = \"Celltype\",\n# palette = c(\"#4daf4a\", \"#e41a1c\"),\n# add = \"boxplot\", add.params = list(fill = \"white\"))\n\n\n\nrequire(ggstatsplot)\ngg = ggstatsplot::ggbetweenstats(\n data = Arch.vs.celltype.df,\n x = Celltype,\n y = A11,\n xlab = \"Celltype\",\n ylab = \"A11\",\n pairwise.display = \"significant\", # display only significant pairwise comparisons\n p.adjust.method = \"fdr\", # adjust p-values for multiple tests using this method\n ggtheme = ggthemes::theme_tufte(),\n ) + scale_color_manual(values = c(\"#4daf4a\", \"#e41a1c\"))\n\n\npdf(file.path(figures.path, \"A11_vs_celltype.pdf\"))\nplot(gg)\ndev.off()\n\ngg = ggstatsplot::ggbetweenstats(\n data = Arch.vs.celltype.df,\n x = Celltype,\n y = A29,\n xlab = \"Celltype\",\n ylab = \"A29\",\n pairwise.display = \"significant\", # display only significant pairwise comparisons\n p.adjust.method = \"fdr\", # adjust p-values for multiple tests using this method\n ggtheme = ggthemes::theme_tufte(),\n ) + scale_color_manual(values = c(\"#4daf4a\", \"#e41a1c\"))\n\n\npdf(file.path(figures.path, \"A29_vs_celltype.pdf\"))\nplot(gg)\ndev.off()\n\n```\n# Co-association of A11/A29\n```{r}\nsample.df = data.frame(Label = pb.logcounts$ID, Phenotype = pb.logcounts$Phenotype, A11 = scale(pb.logcounts$A11.signature), A29 = scale(pb.logcounts$A29.signature))\n# sample.df = reshape2::melt(sample.df)\n\n# colnames(sample.df)[[3]] = \"Archetype\"\n \n\ngg = ggscatter(sample.df, x = \"A11\", y = \"A29\", \n color = \"Phenotype\",\n palette = c(\"CON\" = \"lightgray\", \"SZ\" = \"red\"),\n label = \"Label\", repel = TRUE,\n add = \"reg.line\", # Add regression line\n conf.int = TRUE, # Add confidence interval\n add.params = list(color = \"blue\",\n fill = \"lightgray\")\n )+ stat_cor(method = \"pearson\", label.x = -0.8)# +xlim(c(-2, 2)) + ylim(c(-2, 2))\n\npdf(file.path(figures.path, \"A11_vs_A29_sample_assignments.pdf\"), width = 6, height = 6)\nprint(gg)\ndev.off()\n\noutlier.samples = c(\"SZ7\", \"SZ31\", \"SZ44\", \"SZ33\")\n\n```\n\n\n# Compute pattern-specificity\n```{r}\nace = readr::read_rds(\"~/results/ACTIONet_reunified.rds\")\n\n```\n\n```{r}\n\nmask = grepl(\"^Ex\", ace$Labels) & !(grepl(\"^NRGN\", ace$Labels))\nS.Ex = logcounts(ace)[, mask]\nsubH = t(as.matrix(colMaps(ace)$H_unified[mask, c(7, 11, 17, 29)]))\n\narch.spec.Ex = compute_archetype_feature_specificity(S.Ex, H = subH)\n\nU.Ex = arch.spec.Ex$upper_significance\nrownames(U.Ex) = rownames(ace)\ncolnames(U.Ex) = paste(\"A\", c(7, 11, 17, 29), sep = \"\")\nreadr::write_rds(U.Ex, file.path(dataset.path, \"Cellstates_vs_Ex_gene_spec.rds\"))\n\n\n\nmask = grepl(\"^In\", ace$Labels)\nS.In = logcounts(ace)[, mask]\nsubH = t(as.matrix(colMaps(ace)$H_unified[mask, c(7, 11, 17, 29)]))\n\narch.spec.In = compute_archetype_feature_specificity(S.In, H = subH)\n\nU.In = arch.spec.In$upper_significance\nrownames(U.In) = rownames(ace)\ncolnames(U.In) = paste(\"A\", c(7, 11, 17, 29), sep = \"\")\nreadr::write_rds(U.In, file.path(dataset.path, \"Cellstates_vs_In_gene_spec.rds\"))\n\n\n\n\nmask = grepl(\"^In|^Ex\", ace$Labels)\nS.Neuro = logcounts(ace)[, mask]\nsubH = t(as.matrix(colMaps(ace)$H_unified[mask, c(7, 11, 17, 29)]))\n\narch.spec.Neuro = compute_archetype_feature_specificity(S.Neuro, H = subH)\n\nU.Neuro = arch.spec.Neuro$upper_significance\nrownames(U.Neuro) = rownames(ace)\ncolnames(U.Neuro) = paste(\"A\", c(7, 11, 17, 29), sep = \"\")\nreadr::write_rds(U.Neuro, file.path(dataset.path, \"Cellstates_vs_Neuro_gene_spec.rds\"))\n\n\n\nU = cbind(U.Neuro, U.Ex, U.In)\ncolnames(U) = c(paste(\"Neu_A\", c(7, 11, 17, 29), sep = \"\"), paste(\"Ex_A\", c(7, 11, 17, 29), sep = \"\"), paste(\"In_A\", c(7, 11, 17, 29), sep = \"\"))\nidx = grep(\"^MT-|^RPL|^RPS\", rownames(U))\nU = U[-idx, ]\n\nreadr::write_rds(U, file.path(dataset.path, \"Cellstates_vs_InEx_gene_spec_filtered.rds\"))\n\n\n```\n\n```{r}\nU=readr::read_rds(file.path(dataset.path, \"Cellstates_vs_InEx_gene_spec_filtered.rds\"))\nwrite.table(U, file.path(tables.path, \"cellstates_DE.tsv\"), sep = \"\\t\", row.names = T, col.names = T, quote = F)\n\ncelltype.spec=readr::read_rds(\"~/results/datasets/celltype_gene_specificity.rds\")\nwrite.table(celltype.spec, file.path(tables.path, \"celltype_gene_specificity.tsv\"), sep = \"\\t\", row.names = T, col.names = T, quote = F)\n\narch.spec=readr::read_rds(\"~/results/datasets/archetype_gene_specificity.rds\")\nwrite.table(arch.spec, file.path(tables.path, \"archetype_gene_specificity.tsv\"), sep = \"\\t\", row.names = T, col.names = T, quote = F)\n\n\n\n\n```\n\n```{r}\ndata(\"gProfilerDB_human\")\ncellstate.enrichment = assess.geneset.enrichment.from.scores(U, gProfilerDB_human$SYMBOL$`GO:BP`)$logPvals\ncolnames(cellstate.enrichment) = colnames(U)\n\n\nreadr::write_rds(cellstate.enrichment, file.path(dataset.path, \"Cellstates_vs_InEx_gene_spec_filtered_enrichment.rds\"))\n\npdf(file.path(figures.path, \"Cellstate_enrichment.pdf\"), height = 9)\nplot.top.k.features(cellstate.enrichment, 5)\ndev.off()\n\npdf(file.path(figures.path, \"Cellstate_enrichment_doubleNorm.pdf\"), height = 9)\nplot.top.k.features(doubleNorm(cellstate.enrichment), 5)\ndev.off()\n\n\nnerurodev.gene.counts = sort(table(unlist(apply(gProfilerDB_human$SYMBOL$`GO:BP`[, c(\"generation of neurons\", \"neurogenesis\", \"neuron differentiation\", \"nervous system development\")], 2, function(x) rownames(gProfilerDB_human$SYMBOL$`GO:BP`)[x > 0]))), decreasing = T)\n\nneurodev.genes = sort(unique(names(nerurodev.gene.counts)[nerurodev.gene.counts == 4]))\n\ngsea.results = apply(U, 2, function(x) {\n fgsea.out = fgsea(list(nerurodev = neurodev.genes), x)\n})\n\ngene.counts = sort(table(unlist(lapply(gsea.results[c(2, 4, 6, 8)], function(x) x$leadingEdge))), decreasing = T)\n\nselected.genes = sort(unique(names(gene.counts)[gene.counts == 4]))\n\n# [1] \"ABI2\" \"ACAP3\" \"ACSL4\" \"ACTB\" \"ADGRB1\" \"ADGRB3\" \"ADNP\" \"AHI1\" \"ALCAM\" \"ANK3\" \"APBB2\" \n# [12] \"APP\" \"ARHGAP35\" \"ARHGAP44\" \"ARID1B\" \"ASAP1\" \"ATL1\" \"ATP2B2\" \"ATP8A2\" \"AUTS2\" \"BEND6\" \"BMPR2\" \n# [23] \"BRAF\" \"BRINP2\" \"BRINP3\" \"BSG\" \"BTBD8\" \"CACNA1A\" \"CAMK1D\" \"CAMK2B\" \"CAMSAP2\" \"CBFA2T2\" \"CCDC88A\" \n# [34] \"CDH2\" \"CDKL5\" \"CEND1\" \"CEP290\" \"CHD5\" \"CHL1\" \"CHN1\" \"CNTN1\" \"CNTN4\" \"CNTNAP2\" \"CPEB3\" \n# [45] \"CSMD3\" \"CSNK1E\" \"CTNNA2\" \"CTNND2\" \"CUX1\" \"CUX2\" \"CYFIP2\" \"DAB1\" \"DCC\" \"DCLK1\" \"DCLK2\" \n# [56] \"DHFR\" \"DLG4\" \"DMD\" \"DNM3\" \"DNMT3A\" \"DOK6\" \"DSCAML1\" \"DYNC2H1\" \"EFNA5\" \"ELAVL4\" \"EPB41L3\" \n# [67] \"EPHA6\" \"ERBB4\" \"EVL\" \"EXT1\" \"FAIM2\" \"FARP1\" \"FLRT2\" \"FSTL4\" \"GABRB1\" \"GABRB2\" \"GABRB3\" \n# [78] \"GAK\" \"GDI1\" \"GOLGA4\" \"GPM6A\" \"GRIN1\" \"GRIP1\" \"GSK3B\" \"HCN1\" \"HECW1\" \"HECW2\" \"HERC1\" \n# [89] \"HMGB1\" \"HPRT1\" \"HSP90AA1\" \"HSP90AB1\" \"IL1RAPL1\" \"INPP5F\" \"ITSN1\" \"JAK2\" \"KALRN\" \"KDM4C\" \"KIF5A\" \n# [100] \"KIF5C\" \"KIRREL3\" \"KNDC1\" \"LINGO1\" \"LRRC4C\" \"MACF1\" \"MAGI2\" \"MAP1A\" \"MAP1B\" \"MAP2\" \"MAP3K13\" \n# [111] \"MAPK1\" \"MAPK8IP2\" \"MAPK8IP3\" \"MAPT\" \"MARK1\" \"MDGA2\" \"MEF2A\" \"MEF2C\" \"MIB1\" \"MTR\" \"MYCBP2\" \n# [122] \"MYH10\" \"MYO9A\" \"MYT1L\" \"NCAM1\" \"NCDN\" \"NCKAP1\" \"NCOA1\" \"NDRG4\" \"NEFM\" \"NEGR1\" \"NFE2L2\" \n# [133] \"NIN\" \"NLGN1\" \"NLGN4X\" \"NRCAM\" \"NRXN1\" \"NRXN3\" \"NTM\" \"NTRK2\" \"NTRK3\" \"OPA1\" \"OPCML\" \n# [144] \"PAK3\" \"PBX1\" \"PCDH15\" \"PHACTR1\" \"PIK3CA\" \"PIK3CB\" \"PLXNA4\" \"PPP1R9A\" \"PPP3CA\" \"PRKCA\" \"PRKD1\" \n# [155] \"PRKG1\" \"PTPN9\" \"PTPRD\" \"PTPRG\" \"PTPRO\" \"PTPRS\" \"RAB10\" \"RAP1GAP2\" \"RAPGEF2\" \"RARB\" \"RB1\" \n# [166] \"RBFOX2\" \"RERE\" \"RIMS1\" \"RIMS2\" \"RNF157\" \"ROBO1\" \"ROBO2\" \"RORA\" \"RTN4\" \"RTN4RL1\" \"RUFY3\" \n# [177] \"SARM1\" \"SCLT1\" \"SERPINI1\" \"SH3GL2\" \"SH3KBP1\" \"SHANK2\" \"SHTN1\" \"SIPA1L1\" \"SLC4A10\" \"SLITRK5\" \"SNAP25\" \n# [188] \"SNPH\" \"SOS1\" \"SPOCK1\" \"SPTAN1\" \"SPTBN1\" \"SPTBN4\" \"SRCIN1\" \"SRRM4\" \"STMN2\" \"STXBP1\" \"SUFU\" \n# [199] \"SYN1\" \"SYT1\" \"TCF12\" \"TCF4\" \"TENM2\" \"TENM3\" \"TENM4\" \"THOC2\" \"THRB\" \"TIAM1\" \"TMEFF2\" \n# [210] \"TMEM108\" \"TNIK\" \"TNR\" \"TRAK2\" \"TRIO\" \"TRIP11\" \"UCHL1\" \"UNC5C\" \"UNC5D\" \"USP33\" \"WDPCP\" \n# [221] \"WNK1\" \"YWHAG\" \"ZC4H2\" \"ZEB1\" \"ZEB2\" \"ZMYND8\" \"ZNF804A\" \"ZSWIM5\" \n\n\n```\n\n\n```{r}\ncc = cor(U, -DE.sc[-idx, ])\ncc[cc < 0.1] = 0\nHeatmap(cc)\n\n```\n\n\n```{r}\n\nmask = ACTIONet_summary$metadata$assigned_archetype %in% c(7, 11, 17, 29)\n\ncell.df = data.frame(Phenotype = ACTIONet_summary$metadata$Phenotype[mask], Celltype = ACTIONet_summary$metadata$Labels[mask], A7 = scale(ACTIONet_summary$H_unified[mask, 7]), A11 = scale(ACTIONet_summary$H_unified[mask, 11]), A17 = scale(ACTIONet_summary$H_unified[mask, 17]), A29 = scale(ACTIONet_summary$H_unified[mask, 29]))\n\n# cell.df = cell.df[grepl(\"^In|^Ex\", cell.df$Celltype)&!grepl(\"NRGN\", cell.df$Celltype), ]\ncell.df = cell.df[grepl(\"^In|^Ex\", cell.df$Celltype), ]\n\ncell.df2 = reshape2::melt(cell.df)\ncolnames(cell.df2)[[3]] = \"Archetype\"\ncell.df2$Celltype = factor(cell.df2$Celltype, names(colors))\n\n\n\ngg = ggbarplot(cell.df2, \"Archetype\", \"value\", fill = \"Celltype\", palette = colors, position = position_dodge(), add = \"mean_se\") + ylab(\"Archetype score (scaled)\")\n\npdf(file.path(figures.path, \"Cellstates_vs_celltypes_neuro_plusNRGN.pdf\"), width = 12, height = 5)\nplot(gg)\ndev.off()\n\n\nsub.cell.df2 = cell.df2[cell.df2$Archetype == \"A17\", ]\nIDX = split(sub.cell.df2$value, sub.cell.df2$Celltype)\n\ncls = scales::col_numeric(pals::brewer.rdbu(9), domain = NULL)(sapply(IDX, mean))\nnames(cls) = names(IDX)\nsub.cell.df2$color = cls[sub.cell.df2$Celltype]\n\nsub.cell.df2$Celltype = factor(sub.cell.df2$Celltype, names(IDX)[order(sapply(IDX, mean), decreasing = T)])\n\ngg = ggbarplot(sub.cell.df2, \"Celltype\", \"value\", fill = \"Celltype\", palette = colors, position = position_dodge(), add = \"mean_se\") + ylab(\"Archetype score (scaled)\") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1, color=colors))\n\npdf(file.path(figures.path, \"Cellstates_vs_celltypes_neuro_plusNRGN_SZTR_only_small.pdf\"), width = 5, height = 5)\nplot(gg)\ndev.off()\n\n\n\n```\n\n\n```{r}\n# X = assays(pb.logcounts)[[\"Ex-L45_MET\"]][selected.genes, ]\n# \n# X.orth = orthoProject(X, Matrix::rowMeans(X))\n# X.orth[is.na(X.orth)] = 0\n# Heatmap(X.orth)\n\n\noverlap.genes = lapply(DE.new$Down.genes, function(gs) intersect(selected.genes, gs))\nx = sort(table(unlist(overlap.genes)), decreasing = T)\nx[1:30]\n\n```\n\n\n```{r}\nbulk = readr::read_rds(\"~/results/input/MPP_bulk_expression_SZandCON.rds\")\nbulk.profile = assays(bulk)$voom\nbulk.profile.orth = orthoProject(bulk.profile, Matrix::rowMeans(bulk.profile))\n\n```\n\n\n```{r}\nidx = grep(\"^MT-|^RPL|^RPS|^PSM|^EIF|^MRP\", rownames(U))\ncellstate.panel = log1p(U[-idx, ])\n\n\ncommon.genes = intersect(rownames(cellstate.panel), rownames(bulk.profile.orth))\n\nSZ.pred = -cor(bulk.profile.orth[common.genes, ], cellstate.panel[common.genes, ], method = \"spearman\")\nrownames(SZ.pred) = bulk$SampleID\n\nCC = cor(t(bulk.profile.orth[common.genes, ]), SZ.pred, method = \"spearman\")\nscores = cbind(exp(3*CC), exp(-3*CC))\ncolnames(scores) = c(paste(\"Up_\", colnames(CC), sep = \"\"), paste(\"Down_\", colnames(CC), sep = \"\"))\nrownames(scores) = common.genes\n\nEn = assess.geneset.enrichment.from.scores(scores, gProfilerDB_human$SYMBOL$`GO:BP`)\nlogPvals = En$logPvals\ncolnames(logPvals) = colnames(scores)\n\nplot.top.k.features((logPvals))\n\n\n\n```\n```{r}\nX = assays(pb.logcounts)[[\"Ex-L23\"]]\nX.orth = orthoProject(X, fast_row_sums(X))\nsubX = X.orth[, c(\"SZ7\", \"SZ31\", \"SZ44\", \"SZ33\")]\n\n```\n\n```{r}\n\n# bulk.profile = assays(bulk)$voom\n# bulk.profile = orthoProject(bulk.profile, Matrix::rowMeans(bulk.profile))\n\nidx = grep(\"^MT-|^RPL|^RPS\", rownames(U.Neuro))\ncellstate.panel = U.Neuro[-idx, ]\n\n\ncommon.genes = intersect(rownames(cellstate.panel), rownames(bulk.profile))\n\nSZ.pred = -cor(bulk.profile[common.genes, ], cellstate.panel[common.genes, ], method = \"spearman\")\nrownames(SZ.pred) = bulk$SampleID\n\narch.df = data.frame(Id = bulk$SampleID, Phenotype = bulk$Dx, A11 = SZ.pred[, \"A11\"], A29 = SZ.pred[, \"A29\"])\n\n\n\n\n\n\n\n\n\n```\n\n\n```{r}\nrequire(ggpubr)\nLl = c(\"SZ\", \"CON\")\narch.df = data.frame(Id = bulk$SampleID, Phenotype = bulk$Dx, A11 = SZ.pred[, \"A11\"], A29 = SZ.pred[, \"A29\"], A7 = SZ.pred[, \"A7\"], Label = \"\")\narch.df$Phenotype = factor(Ll[as.numeric(arch.df$Phenotype == \"SCZ\")+1], Ll)\n\ngg = ggscatter(arch.df, x = \"A11\", y = \"A29\", \n color = \"Phenotype\",\n palette = c(\"CON\" = \"black\", \"SZ\" = \"red\"),\n label = \"Label\", repel = TRUE,\n add = \"reg.line\", # Add regression line\n conf.int = TRUE, # Add confidence interval\n add.params = list(color = \"blue\",\n fill = \"lightgray\")\n ) + stat_cor(method = \"pearson\")# +xlim(c(-2, 2)) + ylim(c(-2, 2))\n\n# pdf(file.path(figures.path, \"Supp\", \"TPS_vs_SZTR.pdf\"), width = 6, height = 6)\nprint(gg)\n# dev.off()\n\n```\n\n\n```{r}\narch.df$pred = scale(arch.df$A29)\n# arch.df$pred = scale(runif(length(arch.df$A11)))\n\ndata = bulk.profile[common.genes, ]\n# plot(density(data[, 4]))\n# data = normalizeQuantiles(data)\nmod = model.matrix( ~0 + pred, arch.df)\nfit = lmFit(data, mod)\nfit<-eBayes(fit)\ntbl = limma::topTable(\n fit = fit,\n coef=1,\n number = Inf,\n adjust.method = \"BH\",\n sort.by = \"t\"\n)\n\ngp = gProfileR::gprofiler(query = rownames(tbl), ordered_query = T) \n\n \nrequire(EnhancedVolcano)\nEnhancedVolcano(tbl , x = \"logFC\", y = \"adj.P.Val\", lab = rownames(tbl))\n \n```\n\n```{r}\nSZ.associations = as(cbind(as.numeric(bulk$Dx == \"SCZ\"), as.numeric(bulk$Dx == \"Control\")), \"sparseMatrix\")\ncolnames(SZ.associations) = c(\"SZ\", \"CON\")\n\nscores = exp(-3*SZ.pred)\nrownames(SZ.associations) = colnames(scores) = bulk$SampleID\n\nXX = t(assess.geneset.enrichment.from.scores(t(scores), SZ.associations)$logPvals)\nrownames(XX) = colnames(panel)\n# Heatmap(XX)\n\n```\n\n```{r}\n\n\nDx = split(bulk$SampleID, bulk$Dx)\n\n# Pvals = apply(SZ.pred, 2, function(x) {\n# out = fgsea(Dx, x)\n# pvals = out$pval\n# names(pvals) = names(Dx)\n# return(pvals)\n# })\n\nl = as.numeric(bulk$Dx == \"SCZ\")\nmhg.Pvals.CON = apply(SZ.pred, 2, function(x) {\n perm = order(x, decreasing = T)\n x = l[perm]\n mhg.out = mhg::mhg_test(x, length(x), sum(x), length(x), 1, upper_bound = F, tol = 1e-300) \n return(mhg.out$pvalue)\n})\n\nmhg.Pvals.SZ = apply(SZ.pred, 2, function(x) {\n perm = order(x, decreasing = F)\n x = l[perm]\n mhg.out = mhg::mhg_test(x, length(x), sum(x), length(x), 1, upper_bound = F, tol = 1e-300) \n return(mhg.out$pvalue)\n})\n\n\nEn = -log10(matrix(p.adjust(c(mhg.Pvals.SZ, mhg.Pvals.CON), \"fdr\"), ncol = 2))\nrownames(En) = colnames(cellstate.panel)\ncolnames(En) = c(\"SZ\", \"CON\")\nEn = round(En, 2)\n\n\n\nSZ.pred\n\n# \n# x = SZ.pred[, \"A29\"]\n# perm = order(x, decreasing = F)\n# x = l[perm]\n# mhg.out = mhg::mhg_test(x, length(x), sum(x), 100, 1, upper_bound = F, tol = 1e-300) \n# plot(-log10(mhg.out$mhg))\n\n\n\n\n# SZ.associations = as(cbind(as.numeric(bulk$Dx == \"SCZ\"), as.numeric(bulk$Dx == \"Control\")), \"sparseMatrix\")\n# colnames(SZ.associations) = c(\"SZ\", \"CON\")\n# \n# scores = exp(-3*SZ.pred)\n# rownames(SZ.associations) = colnames(scores) = bulk$SampleID\n\n\n\n\n# XX = t(assess.geneset.enrichment.from.scores(t(scores), SZ.associations)$logPvals)\n# rownames(XX) = colnames(cellstate.panel)\n\n```\n\n```{r}\nUp.DE.enrichment = annotate.archetypes.using.markers(ACTIONet_summary$unified_feature_specificity, DE.new$Up.genes)\n\nY = t(Up.DE.enrichment$Enrichment)\ncolnames(Y) = paste(\"A\", 1:ncol(X), sep = \"\")\nRd.pal = circlize::colorRamp2(seq(0, quantile(Y, 0.99), length.out = 8), c(\"#ffffff\", pals::brewer.reds(7)))\n\n\nDown.DE.enrichment = annotate.archetypes.using.markers(ACTIONet_summary$unified_feature_specificity, DE.new$Down.genes)\n\nX = t(Down.DE.enrichment$Enrichment)\nBu.pal = circlize::colorRamp2(seq(0, quantile(X, 0.99), length.out = 8), c(\"#ffffff\", pals::brewer.blues(7)))\n\ncolnames(X) = paste(\"A\", 1:ncol(X), sep = \"\")\n\n# arch.perm = order(apply(rbind(X, Y), 2, mean), decreasing = T)\n# \n# Heatmap(t(Y[, arch.perm]), rect_gp = gpar(col = \"black\"), col = Rd.pal, cluster_rows = F, cluster_columns = F, column_names_gp = gpar(col = colors[rownames(Y)]), name = \"Up\", column_title = \"Up\") + Heatmap(t(X[, arch.perm]), rect_gp = gpar(col = \"black\"), col = Bu.pal, cluster_columns = F, column_names_gp = gpar(col = colors[rownames(X)]), name = \"Down\", column_title = \"Down\")\n\n# arch.perm = order(apply(rbind(X), 2, mean), decreasing = T)\narch.perm = order(apply(rbind(X, Y), 2, mean), decreasing = T)\n\npdf(file.path(figures.path, \"arch_gene_spec_vs_DE_up.pdf\"), width = 5, height = 8)\nHeatmap(t(Y[, arch.perm]), cluster_rows = F, rect_gp = gpar(col = \"black\"), col = Rd.pal, cluster_columns = F, column_names_gp = gpar(col = colors[rownames(X)]), name = \"Up\", column_title = \"Up\", row_names_side = \"left\")\ndev.off()\n\n\npdf(file.path(figures.path, \"arch_gene_spec_vs_DE_down.pdf\"), width = 5, height = 8)\nHeatmap(t(X[, arch.perm]), cluster_rows = F, rect_gp = gpar(col = \"black\"), col = Bu.pal, cluster_columns = F, column_names_gp = gpar(col = colors[rownames(X)]), name = \"Down\", column_title = \"Down\", row_names_side = \"left\")\ndev.off()\n\n```\n```{r, eval = F}\n\nDE.down.vs.arch.fgsea = apply(ACTIONet_summary$unified_feature_specificity, 2, function(x) {\n fgsea.out = fgsea(DE.new$Down.genes, x, eps = 1e-100)\n \n v = fgsea.out$pval\n names(v) = fgsea.out$pathway\n return(v)\n})\n\nDE.down.vs.arch.fgsea.enrichment = -log10(DE.down.vs.arch.fgsea)\nHeatmap(DE.down.vs.arch.fgsea.enrichment)\n\n```\n\n## Enrichment\n```{r}\narchs = c(29,11, 17, 7)\n\narch.enrichment.phenotype = presto::wilcoxauc(t(ACTIONet_summary$H_unified), ACTIONet_summary$metadata$Phenotype)\narch.enrichment.phenotype = matrix(arch.enrichment.phenotype$auc-0.5, nrow=ncol(ACTIONet_summary$H_unified))\nrownames(arch.enrichment.phenotype) = paste(\"A\", 1:nrow(arch.enrichment.phenotype), sep = \"\")\ncolnames(arch.enrichment.phenotype) = levels(ACTIONet_summary$metadata$Phenotype)\n\narch.enrichment.ind = presto::wilcoxauc(t(ACTIONet_summary$H_unified), ACTIONet_summary$metadata$Individual)\narch.enrichment.ind = matrix(arch.enrichment.ind$auc-0.5, nrow=ncol(ACTIONet_summary$H_unified))\nrownames(arch.enrichment.ind) = paste(\"A\", 1:nrow(arch.enrichment.ind), sep = \"\")\n\narch.enrichment.celltype = presto::wilcoxauc(t(ACTIONet_summary$H_unified), ACTIONet_summary$metadata$Labels)\nrn = unique(arch.enrichment.celltype$group)\narch.enrichment.celltype = matrix(arch.enrichment.celltype$auc-0.5, nrow=ncol(ACTIONet_summary$H_unified))\nrownames(arch.enrichment.celltype) = paste(\"A\", 1:nrow(arch.enrichment.celltype), sep = \"\")\ncolnames(arch.enrichment.celltype) = rn\n\n\nha_ct = columnAnnotation(Celltype = factor(names(DE.new$Up.genes), names(DE.new$Up.genes)), col = list(Celltype = colors[names(DE.new$Up.genes)]))\n\nxx = t(scale(t(arch.enrichment.ind[archs, ])))\ncolnames(xx) = c()\n\nyy = t(scale(t(arch.enrichment.celltype[archs, names(DE.new$Up.genes)])))\ncolnames(yy) = c()\n\nzz = as.matrix(scale(arch.enrichment.phenotype[archs, 2]))\n\nsample_perm = order(apply(xx[1:2, ], 2, max), decreasing = T)\nha_pheno = columnAnnotation(Phenotype = pb.logcounts$Phenotype[sample_perm], col = list(Phenotype = c(\"CON\" = \"gray\", \"SZ\" = \"red\")))\n\npdf(file.path(figures.path, \"Cellstate_heatmaps.pdf\"), width = 32, height = 4)\nHeatmap(zz, cluster_rows = F, row_names_side = \"left\", name = \"Pheno\", column_title = \"Pheno\", show_column_dend = F, rect_gp = gpar(col = \"black\"))+ Heatmap(yy, name = \"Celltype\", cluster_columns = F, row_names_side = \"left\", top_annotation = ha_ct, rect_gp = gpar(col = \"black\")) + Heatmap(xx[, sample_perm], cluster_rows = F, name = \"Samples\", column_title = \"Samples\", show_column_dend = F, top_annotation = ha_pheno) \ndev.off()\n\n\n```\n\n" }, { "alpha_fraction": 0.5959183573722839, "alphanum_fraction": 0.6413265466690063, "avg_line_length": 26.20833396911621, "blob_id": "5dfd2c09bff3978dbff88e7cf245c00ed4803041", "content_id": "fc2a538143afc8f2e99534456a5ad803020e4e96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1960, "license_type": "no_license", "max_line_length": 75, "num_lines": 72, "path": "/old/filter_ad.py", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "import scrublet as scr\nimport scanpy as sc\nimport anndata as ad\nimport numpy as np\nfrom scipy.sparse import csr_matrix\n\naces = []\nc1 = c2 = c3 = 0\nfor i in range(8):\n print(i)\n fname = \"input_sce_Batch%d.h5ad\" % (i + 1)\n adata = ad.read_h5ad(fname)\n c1 += sum(adata.obs.Phenotype != \"BD\")\n # Calculate QC metrics\n adata.var[\"mt\"] = adata.var_names.str.startswith(\n \"MT-\"\n ) # annotate the group of mitochondrial genes as 'mt'\n sc.pp.calculate_qc_metrics(\n adata, qc_vars=[\"mt\"], percent_top=None, log1p=False, inplace=True,\n )\n adata = adata[\n (1000 <= adata.obs.n_genes_by_counts)\n & (adata.obs.pct_counts_mt <= 10)\n & (adata.obs.total_counts <= 50000),\n ]\n c2 += sum(adata.obs.Phenotype != \"BD\")\n # Remove doublets\n counts_matrix = adata.X\n scrub = scr.Scrublet(counts_matrix)\n doublet_scores, predicted_doublets = scrub.scrub_doublets()\n adata.obs[\"scrublet_doublet_scores\"] = doublet_scores\n adata.obs[\"scrublet_is_doublet\"] = predicted_doublets\n adata = adata[\n adata.obs[\"scrublet_is_doublet\"] == False,\n ]\n c3 += sum(adata.obs.Phenotype != \"BD\")\n aces.append(adata)\n# adata.write(\"input_sce_Batch%d_annotated.h5ad\" % (i + 1))\n\nprint(c1) # 560,020\nprint(c2) # 462,229\nprint(c3) # 454,622\n\nmerged_ace = ad.concat(aces)\nmerged_ace.obs_names_make_unique() # (643988, 33538)\n\n\nsc.pp.filter_genes(\n merged_ace,\n min_counts=None,\n min_cells=round(0.001 * merged_ace.shape[0]),\n max_counts=None,\n max_cells=None,\n inplace=True,\n copy=False,\n) # (643988, 24888)\n\nmerged_ace.X = csr_matrix(merged_ace.X)\n\n\"\"\"\nsc.pp.normalize_total(merged_ace)\nsc.pp.log1p(merged_ace)\n\nsc.pp.highly_variable_genes(merged_ace)\n\"\"\"\n\nmerged_ace.write_h5ad(\"Ruzika_doublet_removed_all_counts.h5ad\")\n\nSZ_ace = merged_ace[\n merged_ace.obs.Phenotype != \"BD\",\n] # (454622, 24888)\nSZ_ace.write_h5ad(\"Ruzika_doublet_removed_SZplusCON_counts.h5ad\")\n\n" }, { "alpha_fraction": 0.6100733280181885, "alphanum_fraction": 0.650986909866333, "avg_line_length": 28.972789764404297, "blob_id": "f395830ef14ca25874f096e58b097e09ff55c6d8", "content_id": "a476878e4abfbd9c94911c22ed91a453aff6ffaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 13223, "license_type": "no_license", "max_line_length": 251, "num_lines": 441, "path": "/ancient/Fig4_Cellstates_CMC.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"Assess significance and relevance of cell states/archetypes\"\noutput: html_notebook\n---\n\n# Setup\n```{r include=FALSE}\nrequire(ACTIONet)\nrequire(stringr)\nrequire(ComplexHeatmap)\n\nrequire(muscat)\nrequire(edgeR)\nrequire(limma)\n\ndataset.path = \"~/results/datasets/\"\nresults.path = \"~/results\"\nfigures.folder = \"~/results/figures\"\ninput.folder = \"~/results/input\"\n\n\n```\n\n\nMain archetypes to analyze are A7 (NRGN), A11 (Ex-SZ), A17 (SZTR), and A29 (In-SZ)\n\n# Show markers\n## A11 and A29 are Mt-reach but also neuro-specific\n# Plot projection of archetypes on the ACTIONet ()\n```{r}\npb.logcounts = readr::read_rds(file.path(dataset.path, \"PB_sce_final.rds\"))\n\nACTIONet_summary = readr::read_rds(file.path(dataset.path, \"ACTIONet_summary_filtered_individuals.rds\"))\n\ncelltype.gene.spec = readr::read_rds(file.path(dataset.path, \"celltype_gene_specificity.rds\"))\narchetype.gene.spec = readr::read_rds(file.path(dataset.path, \"archetype_gene_specificity.rds\"))\n\ncolor.df = readRDS(file.path(dataset.path, \"celltype_colors.rds\"))\n\n\n\n\ncolors = color.df$color\nnames(colors) = color.df$celltype\n```\n\n\n\n\n```{r}\nvobj = readRDS(\"~/results/input/vobj.lst.RDS\")\nvobj.meta = readRDS(\"~/results/input/METADATA.RDS\")\n\n\n\nace.MPP = SingleCellExperiment(assays = list(voom = vobj$`MSSM-Penn-Pitt`$E))\nlibrary(org.Hs.eg.db)\ngg = as.character(sapply(rownames(ace.MPP), function(str) str_split(str, fixed(\".\"))[[1]][[1]]))\nsuppressWarnings(ids <- AnnotationDbi::mapIds(org.Hs.eg.db, keys = gg, keytype = \"ENSEMBL\", column = \"SYMBOL\", multiVals = \"first\"))\nmask = !is.na(ids)\nace.MPP = ace.MPP[mask, ]\nrownames(ace.MPP) = ids[mask]\nidx = match(colnames(ace.MPP), vobj.meta$SampleID)\n\ncolData(ace.MPP) = DataFrame(vobj.meta[idx, ])\n\n\nreadr::write_rds(ace.MPP, \"~/results/input/MPP_bulk_expression_SZandCON.rds\")\n\n\n\nace.HBCC = SingleCellExperiment(assays = list(voom = vobj$`NIMH-HBCC`$E))\nlibrary(org.Hs.eg.db)\ngg = as.character(sapply(rownames(ace.HBCC), function(str) str_split(str, fixed(\".\"))[[1]][[1]]))\nsuppressWarnings(ids <- AnnotationDbi::mapIds(org.Hs.eg.db, keys = gg, keytype = \"ENSEMBL\", column = \"SYMBOL\", multiVals = \"first\"))\nmask = !is.na(ids)\nace.HBCC = ace.HBCC[mask, ]\nrownames(ace.HBCC) = ids[mask]\nidx = match(colnames(ace.HBCC), vobj.meta$SampleID)\n\ncolData(ace.HBCC) = DataFrame(vobj.meta[idx, ])\nreadr::write_rds(ace.HBCC, \"~/results/input/HBCC_bulk_expression_SZandCON.rds\")\n\n\n\n\n```\n\n\n```{r}\nace.bulk = ace.MPP\n\nbulk.voom = assays(ace.bulk)$voom\narch.gene.spec = ACTIONet_summary$unified_feature_specificity\n\narch.genes = rownames(arch.gene.spec) # [which(apply(scale(as.matrix(arch.gene.spec[, c(7, 11, 17, 29)])), 1, max) > 3)]\n#arch.genes = arch.genes [-grep(\"^RPL|^RPS|^MT-|^MT[:.:]\", arch.genes)]\n\ncg = intersect(rownames(bulk.voom), arch.genes)\nsubArch = log1p(arch.gene.spec[cg, ])\nsubBulk = bulk.voom[cg, ]\n\n```\n\n```{r}\narch.genes = rownames(arch.gene.spec) # [which(apply(scale(as.matrix(arch.gene.spec[, c(7, 11, 17, 29)])), 1, max) > 3)]\n\n\nZ = scale(subArch)\nmarkers.genes = as.list(as.data.frame(apply(Z, 2, function(z) rownames(Z)[order(z, decreasing = T)[1:500]])))\n\n\nsubBulk.orth = orthoProject(subBulk, fast_row_sums(subBulk))\nX = -subBulk.orth\nX[X < 0] = 0\n\nEn = annotate.profile.using.markers(t(X), markers.genes)\nHeatmap(En$Enrichment)\n\n```\n\n\n\n```{r}\n\n\nsubBulk.orth = orthoProject(subBulk, fast_row_sums(subBulk))\n\nSZ.samples = list(SZ = ace.bulk$SampleID[which(ace.bulk$Dx == \"SCZ\")])\nrequire(fgsea)\n\nArch.cor = -cor(subBulk.orth, subArch, method = \"pearson\")\narch.enrichment = -log10(p.adjust(apply(Arch.cor, 2, function(x) {\n gsea.out = fgsea(SZ.samples, x)\n gsea.out$padj\n # perm = order(x, decreasing = T)\n # l = SZ.mask[perm]\n # mhg.out = mhg::mhg_test(l, length(l), sum(l), length(l)/4, 1, upper_bound = F, tol = 1e-300)\n # mhg.out$pvalue\n}), \"fdr\"))\n\nsort(round(arch.enrichment, 1), decreasing = T)\n\n\n# cor(Arch.cor[, \"A11\"], Arch.cor[, \"A29\"], method = \"spearman\")\n# \n# x = -(Arch.cor[, \"A11\"] + Arch.cor[, \"A29\"]) / 2\n# gsea.out = fgsea(SZ.samples, x)\n# plotEnrichment(SZ.samples$SZ, x)\n# print(gsea.out)\n\n\n# \n# \n# \n# x = Arch.cor[, \"A29\"]\n# fgsea::plotEnrichment(SZ.samples[[1]], x)\n# \n# df = data.frame(A29 = scale(Arch.cor[, \"A29\"]), A11 = scale(Arch.cor[, \"A11\"]), Phenotype = PEC.sce.matched$diagnosis, Sample = rownames(Arch.cor), x = PEC.sce.matched$ethnicity, PEC.sce.matched$ageDeath, PEC.sce.matched$sex, PEC.sce.matched$smoker)\n# df$combined = (df$A29 + df$A11)/2\n# \n# ggscatter(df, x = \"A11\", y = \"A29\",\n# add = \"reg.line\", # Add regression line\n# conf.int = TRUE, # Add confidence interval\n# color = \"Phenotype\", \n# palette = c(\"gray\", \"red\"),\n# add.params = list(color = \"blue\",\n# fill = \"lightgray\")\n# ) \n# \n# +\n# stat_cor(method = \"pearson\", label.x = 3, label.y = 30) # Add correlation coefficient\n# \n# \n\n\n\n\n```\n\n\n```{r}\nsample.meta = as.data.frame(colData(pb.logcounts))\nsample.meta$scores = scale(sample.meta$A11.signature) + scale(sample.meta$A29.signature)\n\nEn = annotate.archetypes.using.labels(t(ACTIONet_summary$H_unified), ACTIONet_summary$metadata$Phenotype)\nHeatmap(En$Enrichment)\n\n\n\nHeatmap(sample.meta$Phenotype[order(sample.meta$scores, decreasing = T)], cluster_rows = F)\n\n```\n\n```{r}\n\narch.sig.avg = as.matrix(sample.meta[, 33:36])\nmed.mat = as.matrix(sample.meta[, 17:22])\n\nArch.vs.Med.enrichment = apply(arch.sig.avg, 2, function(sig) {\n perm = order(sig, decreasing = T)\n X = med.mat[perm, ]\n logPvals = apply(X, 2, function(x) {\n l = as.numeric(x != 0)\n mhg.out = mhg::mhg_test(l, length(l), sum(l), length(l), 1, upper_bound = F, tol = 1e-100)\n -log10(mhg.out$pvalue)\n })\n return(logPvals)\n})\nHeatmap(Arch.vs.Med.enrichment)\n\n(apply(arch.sig.avg, 2, function(x) cor(x, sample.meta$Age, method = \"spearman\")))\n\napply(arch.sig.avg, 2, function(x) cor.test(x, as.numeric(factor(sample.meta$Phenotype)), method = \"spearman\", use = \"complete.obs\")$p.value)\n\n\n```\n\n\n# Load PEC data\n```{r}\nPEC.expr.table = read.table(file.path(input.folder, \"DER-01_PEC_Gene_expression_matrix_normalized.txt\"), header = T)\nrownames(PEC.expr.table) = PEC.expr.table$gene_id\n\nPEC.expr.mat = as.matrix(PEC.expr.table[, -1])\n\n\nlibrary(org.Hs.eg.db)\ngg = as.character(sapply(PEC.expr.table$gene_id, function(str) str_split(str, fixed(\".\"))[[1]][[1]]))\nsuppressWarnings(ids <- AnnotationDbi::mapIds(org.Hs.eg.db, keys = gg, keytype = \"ENSEMBL\", column = \"SYMBOL\", multiVals = \"first\"))\nmask = !is.na(ids)\n\nPEC.expr.mat = PEC.expr.mat[mask, ]\nrownames(PEC.expr.mat) = ids[mask]\n\n\n\n\nPEC.expr.table.TPM = read.table(file.path(input.folder, \"DER-02_PEC_Gene_expression_matrix_TPM.txt\"), header = T)\nrownames(PEC.expr.table.TPM) = PEC.expr.table.TPM$GeneName\n\nPEC.expr.mat.TPM = as.matrix(PEC.expr.table.TPM[, -1])\n\n\nlibrary(org.Hs.eg.db)\nmask = !is.na(ids)\nsuppressWarnings(ids <- AnnotationDbi::mapIds(org.Hs.eg.db, keys = PEC.expr.table.TPM$GeneName, keytype = \"ENSEMBL\", column = \"SYMBOL\", multiVals = \"first\"))\n\nPEC.expr.mat.TPM = PEC.expr.mat.TPM[mask, ]\nrownames(PEC.expr.mat.TPM) = ids[mask]\n\n\n\n\n\ngg = sort(unique(intersect(rownames(PEC.expr.mat.TPM), rownames(PEC.expr.mat))))\ncc = sort(unique(intersect(colnames(PEC.expr.mat), colnames(PEC.expr.mat.TPM))))\n\nPEC.sce = SingleCellExperiment(assays = list(normexpr = PEC.expr.mat[gg, cc], TPM = PEC.expr.mat.TPM[gg, cc]))\n\n\nmeta.PEC.full = read.table(\"~/results/input/Job-138522884223735377851224577.tsv\", header = T, sep = \"\\t\")\n\n\nmeta.PEC = read.table(\"~/results/input/Job-138522891409304015015695443.tsv\", header = T, sep = \"\\t\")\nmask = meta.PEC$diagnosis %in% c(\"Control\", \"Schizophrenia\")\nmeta.PEC = meta.PEC[mask, ]\n\ncommon.samples = sort(unique(intersect((meta.PEC$individualID), (cc))))\n\nmeta.PEC.matched = meta.PEC[match(common.samples, meta.PEC$individualID), ]\nPEC.sce.matched = PEC.sce[, match(common.samples, colnames(PEC.sce))]\ncolData(PEC.sce.matched) = DataFrame(meta.PEC.matched)\ncolnames(PEC.sce.matched) = PEC.sce.matched$individualID\n\nreadr::write_rds(PEC.sce.matched, \"~/results/input/PEC_bulk_expression_SZandCON.rds\")\n\n```\n\n\n# A11 and A19 specific\n```{r}\n# 0 1 \n# 452 367\nSZ.mask = as.numeric(PEC.sce.matched$diagnosis == \"Schizophrenia\")\n\n\nX = assays(PEC.sce.matched)$normexpr\narch.gene.spec = ACTIONet_summary$unified_feature_specificity\n\ncg = intersect(rownames(X), rownames(arch.gene.spec))\nsubX = X[cg, ]\nsubArch = arch.gene.spec[cg, ]\n\nArch.cor = cor(subX, subArch)\n\narch.enrichment = apply(Arch.cor, 2, function(x) {\n perm = order(x, decreasing = T)\n l = SZ.mask[perm]\n mhg.out = mhg::mhg_test(l, length(l), sum(l), length(l), 1, upper_bound = F, tol = 1e-300)\n -log10(mhg.out$pvalue)\n})\nsort(round(arch.enrichment, 1), decreasing = T)\n# A30 A6 A26 A22 A19 A2 A29 A11 A15 A21 A16 A24 A7 A28 A1 A4 A12 A17 A27 A3 A5 A8 A9 A10 A13 A14 A18 A20 A23 A25 A31 \n# 8.0 6.0 3.2 1.8 1.7 1.6 1.6 1.1 0.8 0.7 0.6 0.5 0.3 0.3 0.2 0.1 0.1 0.1 0.1 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0\n\n\nArch.cor = cor(subX, subArch, method = \"spearman\")\narch.enrichment = apply(Arch.cor, 2, function(x) {\n perm = order(x, decreasing = F)\n l = SZ.mask[perm]\n mhg.out = mhg::mhg_test(l, length(l), sum(l), length(l), 1, upper_bound = F, tol = 1e-300)\n -log10(mhg.out$pvalue)\n})\nsort(round(arch.enrichment, 1), decreasing = T)\n# A30 A6 A22 A19 A2 A29 A26 A11 A15 A13 A21 A4 A16 A1 A14 A12 A24 A27 A28 A5 A7 A9 A18 A20 A3 A8 A10 A17 A23 A25 A31 \n# 8.5 8.4 4.0 2.6 2.1 2.1 1.5 1.4 1.2 1.0 1.0 0.8 0.6 0.3 0.3 0.2 0.2 0.2 0.2 0.1 0.1 0.1 0.1 0.1 0.0 0.0 0.0 0.0 0.0 0.0 0.0\n\nsubX.orth = orthoProject(subX, fast_row_sums(subX))\nArch.cor = cor(subX.orth, subArch, method = \"spearman\")\narch.enrichment = apply(Arch.cor, 2, function(x) {\n perm = order(x, decreasing = F)\n l = SZ.mask[perm]\n mhg.out = mhg::mhg_test(l, length(l), sum(l), length(l), 1, upper_bound = F, tol = 1e-300)\n -log10(mhg.out$pvalue)\n})\nsort(round(arch.enrichment, 1), decreasing = T)\n\n\n\n\n\n\n\n```\n\n\n\n```{r}\nX = assays(PEC.sce.matched)$normexpr\n# arch.genes = rownames(arch.gene.spec)[which(apply(as.matrix(arch.gene.spec[, c(11, 29)]), 1, max) > 100)]\narch.genes = rownames(arch.gene.spec)[which(apply(scale(as.matrix(arch.gene.spec[, c(7, 11, 17, 29)])), 1, max) > 3)]\narch.genes = arch.genes[-grep(\"^RPL|^RPS|^MT-|^MT[:.:]\", arch.genes)]\n\n\ncg = intersect(rownames(X), arch.genes)\nsubArch = (arch.gene.spec[cg, c(7, 11, 17, 29)])\nsubX = X[cg, ]\n# subX = log1p(subX)\n\n# X = assays(PEC.sce.matched)$normexpr\n# cg = intersect(rownames(X), rownames(arch.gene.spec))\n# subX = X[cg, ]\n\n\n# Arch.cor = -cor(subX, subArch, method = \"pearson\")\n# arch.enrichment = apply(Arch.cor, 2, function(x) {\n# perm = order(x, decreasing = T)\n# l = SZ.mask[perm]\n# mhg.out = mhg::mhg_test(l, length(l), sum(l), 1000, 1, upper_bound = F, tol = 1e-300)\n# -log10(mhg.out$pvalue)\n# })\n# sort(round(arch.enrichment, 1), decreasing = T)\n# \n# \nsubX.orth = orthoProject(subX, fast_row_sums(subX))\n\nSZ.samples = list(SZ = PEC.sce.matched$individualID[which(SZ.mask == 1)])\nrequire(fgsea)\n\nArch.cor = cor(subX.orth, subArch, method = \"spearman\")\narch.enrichment = apply(Arch.cor, 2, function(x) {\n gsea.out = fgsea(SZ.samples, x)\n -log10(gsea.out$padj)\n # perm = order(x, decreasing = T)\n # l = SZ.mask[perm]\n # mhg.out = mhg::mhg_test(l, length(l), sum(l), length(l)/4, 1, upper_bound = F, tol = 1e-300)\n # -log10(mhg.out$pvalue)\n})\nsort(round(arch.enrichment, 1), decreasing = T)\n\n```\n\n```{r}\nx = Arch.cor[, \"A29\"]\nfgsea::plotEnrichment(SZ.samples[[1]], x)\n\ndf = data.frame(A29 = scale(Arch.cor[, \"A29\"]), A11 = scale(Arch.cor[, \"A11\"]), Phenotype = PEC.sce.matched$diagnosis, Sample = rownames(Arch.cor), x = PEC.sce.matched$ethnicity, PEC.sce.matched$ageDeath, PEC.sce.matched$sex, PEC.sce.matched$smoker)\ndf$combined = (df$A29 + df$A11)/2\n\nggscatter(df, x = \"A11\", y = \"A29\",\n add = \"reg.line\", # Add regression line\n conf.int = TRUE, # Add confidence interval\n color = \"Phenotype\", \n palette = c(\"gray\", \"red\"),\n add.params = list(color = \"blue\",\n fill = \"lightgray\")\n ) \n\n+\n stat_cor(method = \"pearson\", label.x = 3, label.y = 30) # Add correlation coefficient\n\n\n\nArch.cor = cor(subX.orth, subArch, method = \"spearman\")\narch.enrichment = apply(Arch.cor, 2, function(x) {\n x = exp(df$A11)\n names(x) = df$Sample\n fgsea::plotEnrichment(SZ.samples[[1]], x)\n\n # gsea.out = fgsea(SZ.samples, x)\n # -log10(gsea.out$padj)\n perm = order(x, decreasing = T)\n l = SZ.mask[perm]\n mhg.out = mhg::mhg_test(l, length(l), sum(l), length(l)/4, 1, upper_bound = F, tol = 1e-300)\n -log10(mhg.out$pvalue)\n})\nsort(round(arch.enrichment, 1), decreasing = T)\n\n\n\n\n# 0.9115914\n# cor(Arch.cor[, \"A11\"], Arch.cor[, \"A29\"], method = \"spearman\")\n\nfgsea::plotEnrichment(SZ.samples[[1]], x)\n\n\nscores = exp(Arch.cor*5)\n\nX = sapply(sort(unique(PEC.sce.matched$a)), function(x) as.numeric(PEC.sce.matched$ethnicity == x))\nrownames(X) = colnames(PEC.sce.matched)\ngender.enrichment = assess.geneset.enrichment.from.scores(scores, X)\n\ncolnames(gender.enrichment$logPvals) = colnames(scores)\n\nHeatmap(gender.enrichment$logPvals)\n\n\n\n```\n\n\n\n\n\n" }, { "alpha_fraction": 0.6500456929206848, "alphanum_fraction": 0.683076798915863, "avg_line_length": 38.68619155883789, "blob_id": "7f986b48884afcf42a5e9d8e9e753fc453a57139", "content_id": "8fb8d778eb6baf56a9d84c507e396d345aef59a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 28458, "license_type": "no_license", "max_line_length": 359, "num_lines": 717, "path": "/ancient/Fig1_Annotate.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"Annotate and verify cell type annotations\"\noutput: html_notebook\n---\n\n# Setup\n```{r include=FALSE}\nrequire(ACTIONet)\nrequire(stringr)\nrequire(ComplexHeatmap)\n\ndataset.path = \"~/results/datasets/\"\nresults.path = \"~/results\"\nfigures.path = \"~/results/figures\"\n\n\n```\n\n# Load summary data\n```{r}\npb.logcounts = readr::read_rds(file.path(dataset.path, \"PB_sce_final.rds\"))\n\nACTIONet_summary = readr::read_rds(file.path(dataset.path, \"ACTIONet_summary_filtered_individuals.rds\"))\n\ncelltype.gene.spec = readr::read_rds(file.path(dataset.path, \"celltype_gene_specificity.rds\"))\narchetype.gene.spec = readr::read_rds(file.path(dataset.path, \"archetype_gene_specificity.rds\"))\n\ncolor.df = readRDS(file.path(dataset.path, \"celltype_colors.rds\"))\n\n\n\n\ncolors = color.df$color\nnames(colors) = color.df$celltype\n\n```\n\n\n# Garbage!\n```{r}\nace = readr::read_rds(\"~/results/ACTIONet_reunified.rds\")\n\nace = rerun.archetype.aggregation(ace)\n\nmeta = readRDS(\"~/PFC_v3/SZ_cell_meta.rds\")\n\n\ncolors = readRDS(\"~/results/celltype_colors.rds\")\n\nll = c(\"Ex-NRGN\", \"Ex-L2\", \"Ex-L23\", \"Ex-L3\", \"Ex-L4_MYLK\", \"Ex-L45_MET\", \"Ex-L45_LRRK1\", \"Ex-L5b_VEN\", \"Ex-L5b_HTR2C\", \"Ex-L56\", \"Ex-L56_CC_NTNG2\", \"Ex-L6_CC_SEMA3A\", \"Ex-L6b_SEMA3D\", \"Ex-L6b_SEMA3E\", \"In-Rosehip_CHST9\", \"In-Rosehip_TRPC3\", \"In-Reelin\", \"In-VIP\", \"In-PV_Chandelier\", \"In-PV_Basket\", \"In-SST\", \"Oli\", \"OPC\", \"Ast\", \"Mic\", \"Endo\", \"Pericytes\")\n\n\nll.old = c(\"Ex-NRGN\", \"Ex-L2\", \"Ex-L23\", \"Ex-L3\", \"Ex-L4_MYLK\", \"Ex-L45\", \"Ex-L45_LRRK1\", \"Ex-L5b\", \"Ex-L5b_HTR2C\", \"Ex-L5\", \"Ex-CC_THEMIS_NTNG2\", \"Ex-CC_THEMIS\", \"Ex-L6_SEMA3D\", \"Ex-L6\", \"In-Rosehip_CHST9\", \"In-Rosehip_TRPC3\", \"In-Reelin\", \"In-VIP\", \"In-PV_Chandelier\", \"In-PV_Basket\", \"In-SST\", \"Oli\", \"OPC\", \"Ast\", \"Mic\", \"Endothelial cells\", \"Pericytes\")\n\nnames(colors)[[23]] = \"Endothelial cells\"\n\ncl = as.character(colors[ll.old])\n# cl[1:14] = pals::brewer.greens(16*3)[seq(3*3, 16*3, 3)]\ncl[1:14] = rev(pals::kovesi.linear_green_5_95_c69(17)[c(1, 4, 5:17)])\ncl[15:21] = pals::brewer.reds(9)[2:8]\nnew.colors = cl\nnames(new.colors) = ll\n\nLabels = factor(ll[match(ace$Labels.final, ll.old)], ll)\n\n\n\n\n\n# color.df = readRDS(\"~/results/datasets/celltype_colors.rds\")\n\n# ace$Labels = Labels\n\n# df = data.frame(celltype = ll, old.celltype = ll.old, color = cl)\n# readr::write_rds(df, file = \"~/results/datasets/celltype_colors.rds\")\n\nX = data.frame(colData(ace))[, c(1:7, 14, 20)]\n\nACTIONet_summary = list(metadata = X, ACTIONet2D = ace$ACTIONet2D, ACTIONet3D = ace$ACTIONet3D, H_unified = colMaps(ace)$H_unified, unified_feature_specificity = ace$unified_feature_specificity)\nACTIONet_summary$metadata$umi_count = meta$umis\nACTIONet_summary$metadata$gene_counts = meta$genes\nACTIONet_summary$metadata$mito_perc = meta$mito_perc\nACTIONet_summary$metadata$Labels = Labels\nACTIONet_summary$metadata$Batch = pb.logcounts$Batch[ACTIONet_summary$metadata$Individual]\nACTIONet_summary$metadata$Gender = pb.logcounts$Gender[ACTIONet_summary$metadata$Individual]\nACTIONet_summary$metadata$Age = pb.logcounts$Age[ACTIONet_summary$metadata$Individual]\nACTIONet_summary$metadata$PMI = pb.logcounts$PMI[ACTIONet_summary$metadata$Individual]\n\n\nACTIONet_summary$metadata$dataset[ACTIONet_summary$metadata$dataset == \"DS1\"] = \"McLean\"\nACTIONet_summary$metadata$dataset[ACTIONet_summary$metadata$dataset == \"DS2\"] = \"MtSinai\"\nACTIONet_summary$metadata$assigned_archetype = ace$assigned_archetype\n\nACTIONet_summary$metadata$Individual = pb.logcounts$ID[match(ACTIONet_summary$metadata$Individual, pb.logcounts$Internal_ID)]\n\nreadr::write_rds(ACTIONet_summary, \"~/results/datasets/ACTIONet_summary.rds\")\n\nna.mask = is.na(ACTIONet_summary$metadata$Individual)\nACTIONet_summary$metadata = ACTIONet_summary$metadata[!na.mask, ]\nACTIONet_summary$ACTIONet2D = ACTIONet_summary$ACTIONet2D[!na.mask, ]\nACTIONet_summary$ACTIONet3D = ACTIONet_summary$ACTIONet3D[!na.mask, ]\nACTIONet_summary$H_unified = ACTIONet_summary$H_unified[!na.mask, ]\n\nreadr::write_rds(ACTIONet_summary, \"~/results/datasets/ACTIONet_summary_filtered_individuals.rds\")\n\n\n\n```\n\n```{r}\nACTIONet_summary = readr::read_rds(\"~/results/datasets/ACTIONet_summary.rds\")\n\n```\n\n# Plot main ACTIONet\n## Celltypes\n```{r}\n# annotated\ngg1 = my.plot.ACTIONet(ACTIONet_summary$ACTIONet2D, ACTIONet_summary$metadata$Labels, palette = new.colors, text_size = 2, use_repel = T)\n\npng(file.path(figures.path, \"ACTIONet_annotated.png\"), width = 1600, height = 1200, res = 150)\nplot(gg1)\ndev.off()\n\ngg2 = my.plot.ACTIONet(ACTIONet_summary$ACTIONet2D, ACTIONet_summary$metadata$Labels, palette = new.colors, text_size = 2, use_repel = T, add_text_labels = F)\n\npng(file.path(figures.path, \"ACTIONet_annotated_no_labels.png\"), width = 1600, height = 1200, res = 150)\nplot(gg2)\ndev.off()\n\n```\n\n\n## Supps\n### # Phenotype\n```{r}\ngg2 = my.plot.ACTIONet(ACTIONet_summary$ACTIONet2D, ACTIONet_summary$metadata$Phenotype, palette = c(\"#cccccc\", \"#888888\"), text_size = 2, use_repel = T, add_text_labels = F, point_size = 0.5)\n\npng(file.path(figures.path, \"ACTIONet_phenotype_annotated_no_labels.png\"), width = 1600, height = 1200, res = 150)\nplot(gg2)\ndev.off()\n```\n\n### Batch\n```{r}\ngg2 = my.plot.ACTIONet(ACTIONet_summary$ACTIONet2D, ACTIONet_summary$metadata$Batch, text_size = 2, use_repel = T, add_text_labels = F, point_size = 0.5)\n\npng(file.path(figures.path, \"ACTIONet_batch_annotated_no_labels.png\"), width = 1600, height = 1200, res = 150)\nplot(gg2)\ndev.off()\n```\n\n### Gender\n```{r}\ngg2 = my.plot.ACTIONet(ACTIONet_summary$ACTIONet2D, ACTIONet_summary$metadata$Gender, text_size = 2, use_repel = T, add_text_labels = F, point_size = 0.5, palette = c(\"pink\", \"#91bfdb\"))\n\npng(file.path(figures.path, \"ACTIONet_gender_annotated_no_labels.png\"), width = 1600, height = 1200, res = 150)\nplot(gg2)\ndev.off()\n```\n\n## Archetype\n```{r}\ngg2 = my.plot.ACTIONet(ACTIONet_summary$ACTIONet2D, ACTIONet_summary$metadata$assigned_archetype, text_size = 2, use_repel = T, add_text_labels = F, point_size = 0.5, palette = as.character(pals::polychrome(31)))\n\npng(file.path(figures.path, \"ACTIONet_archetypes_annotated_no_labels.png\"), width = 1600, height = 1200, res = 150)\nplot(gg2)\ndev.off()\n```\n## Archetype\n```{r}\ngg2 = plot.ACTIONet(ACTIONet_summary$ACTIONet2D, ACTIONet_summary$metadata$dataset, text_size = 2, use_repel = T, add_text_labels = F, point_size = 0.5, palette = c(\"#f1a340\", \"#998ec3\"))\n\npng(file.path(figures.path, \"ACTIONet_datasets_annotated_no_labels.png\"), width = 1600, height = 1200, res = 150)\nplot(gg2)\ndev.off()\n\n```\n\n```{r}\nct.vs.ds = table(interaction(ACTIONet_summary$metadata$Labels, ACTIONet_summary$metadata$dataset))\ncc = matrix(as.numeric(ct.vs.ds), ncol = 2)\ncs = fast_column_sums(cc)\ncc = 100*scale(cc, center = F, scale = cs)\nrownames(cc) = levels(ACTIONet_summary$metadata$Labels)\nHeatmap(log2(cc[, 1]/cc[, 2]))\n\n```\n\n\n## Plot ACTIONet plots per dataset\n### McLean dataset\n```{r}\nmask = ACTIONet_summary$metadata$dataset == \"McLean\"\nDS1.coors = ACTIONet_summary$ACTIONet2D[mask, ]\nDS1.labels = ACTIONet_summary$metadata$Labels[mask]\n\ngg3 = my.plot.ACTIONet(DS1.coors, DS1.labels, palette = new.colors, text_size = 2, use_repel = T)\n\npng(file.path(figures.path, \"ACTIONet_annotated_DS1.png\"), width = 1600, height = 1200, res = 150)\nplot(gg3)\ndev.off()\n\ngg4 = my.plot.ACTIONet(DS1.coors, DS1.labels, palette = new.colors, text_size = 2, use_repel = T, add_text_labels = F)\n\npng(file.path(figures.path, \"ACTIONet_annotated_no_labels_DS1.png\"), width = 1600, height = 1200, res = 150)\nplot(gg4)\ndev.off()\n\n```\n\n### MtSinai dataset\n```{r}\nmask = ACTIONet_summary$metadata$dataset == \"MtSinai\"\nDS2.coors = ACTIONet_summary$ACTIONet2D[mask, ]\nDS2.labels = ACTIONet_summary$metadata$Labels[mask]\n\ngg5 = my.plot.ACTIONet(DS1.coors, DS1.labels, palette = new.colors, text_size = 2, use_repel = T)\n\npng(file.path(figures.path, \"ACTIONet_annotated_DS2.png\"), width = 1600, height = 1200, res = 150)\nplot(gg5)\ndev.off()\n\ngg6 = my.plot.ACTIONet(DS1.coors, DS1.labels, palette = new.colors, text_size = 2, use_repel = T, add_text_labels = F)\n\npng(file.path(figures.path, \"ACTIONet_annotated_no_labels_DS2.png\"), width = 1600, height = 1200, res = 150)\nplot(gg6)\ndev.off()\n\n```\n\n\n# Plot cell type fraction stats\n```{r}\nrequire(ggpubr)\n\nncells = sapply(int_colData(pb.logcounts)$n_cells, as.numeric)\nrownames(ncells) = names(assays(pb.logcounts))\n\ncs = Matrix::colSums(ncells)\nncells.freq = 100*scale(ncells, center = F, scale = cs)\n# Ex.perc = (fast_column_sums(ncells.freq[grepl(\"^Ex\", rownames(ncells.freq)) & !grepl(\"^Ex-NRGN\", rownames(ncells.freq)), ]))\nEx.perc = (fast_column_sums(ncells.freq[grepl(\"^Ex\", rownames(ncells.freq)), ]))\n\ndf = data.frame(sample = colnames(ncells), perc = Ex.perc)\ngg = ggdensity(df, x = \"perc\", fill = \"lightgray\",\n add = \"mean\", rug = TRUE)\npdf(file.path(figures.path, \"Ex_perc_density.pdf\"), height = 4, width = 5)\nprint(gg)\ndev.off()\n\n\nncells.freq = ncells.freq[, order(Ex.perc, decreasing = T)]\nEx.perc = (fast_column_sums(ncells.freq[grepl(\"^Ex\", rownames(ncells.freq)) & !grepl(\"^Ex-NRGN\", rownames(ncells.freq)), ]))\n\n# SZ15 0.2570694\n# SZ3 2.8237585\n# SZ24 3.7128713\n# SZ29 7.5571178\n\n# mask = (fast_column_sums(ncells) > 1000) # (Ex.perc > 5) & (Ex.perc < 80) & (fast_column_sums(ncells) > 500)\n# 14 samples with less than 500 cells: CON32 CON43 CON47 CON50 SZ24 SZ25 SZ28 SZ31 SZ33 SZ34 SZ40 SZ41 SZ55 SZ60\n# 1 Sample with more than 80% Ex: CON1\n# 4 samples with less than 10% Ex: SZ37 SZ63 SZ64 SZ65\n\n\n# > sort(colnames(ncells.freq)[fast_column_sums(ncells) < 500])\n# [1] \"CON15\" \"CON17\" \"CON24\" \"CON35\" \"CON50\" \"CON55\" \"CON61\" \"CON67\" \"SZ39\" \"SZ45\" \"SZ48\" \"SZ58\" \"SZ6\" \"SZ61\" \n# > sort(colnames(ncells.freq)[Ex.perc > 80])\n# [1] \"SZ33\"\n# > sort(colnames(ncells.freq)[Ex.perc < 10])\n# [1] \"SZ15\" \"SZ24\" \"SZ29\" \"SZ3\" \n\nmask = (Ex.perc >= 10) & (Ex.perc <= 80) & (fast_column_sums(ncells) >= 500)\n# mask = !(colnames(ncells.freq) %in% c(\"SZ15\"))\nncells.freq = ncells.freq[, mask]\n\n# \n# \n# X = ncells.freq[, pb.logcounts$Cohort[match(colnames(ncells.freq), pb.logcounts$ID)] == \"McLean\"]\n# df = reshape2::melt(X)\n# colnames(df)=c(\"celltype\", \"sample\", \"freq\")\n# \n# df$celltype = factor(df$celltype, names(colors))\n# # df$sample = droplevels(factor(df$sample, colnames(ncells.freq)[sample.perm]))\n# \n# gg.ds1 = ggbarplot(df, \"sample\", \"freq\",\n# fill = \"celltype\", color = \"black\", palette = colors[levels(df$celltype)], xlab = \"Individual\", ylab = \"Percentage\") + theme(axis.text.x = element_text(face=\"bold\", size=0, angle=90), axis.text.y = element_text(face=\"bold\", size=12, angle=0), axis.title = element_text(face=\"bold\", size=18, angle=0))\n# \n# \n# pdf(file.path(figures.path, 'celltype_perc_McLean.pdf'), width = 10, height = 6)\n# print(gg.ds1)\n# dev.off()\n# \n# \n# \n# X = ncells.freq[, pb.logcounts$Cohort[match(colnames(ncells.freq), pb.logcounts$ID)] != \"McLean\"]\n# df = reshape2::melt(X)\n# colnames(df)=c(\"celltype\", \"sample\", \"freq\")\n# \n# df$celltype = factor(df$celltype, names(colors))\n# # df$sample = droplevels(factor(df$sample, colnames(ncells.freq)[sample.perm]))\n# \n# gg.ds2 = ggbarplot(df, \"sample\", \"freq\",\n# fill = \"celltype\", color = \"black\", palette = colors[levels(df$celltype)], xlab = \"Individual\", ylab = \"Percentage\") + theme(axis.text.x = element_text(face=\"bold\", size=0, angle=90), axis.text.y = element_text(face=\"bold\", size=12, angle=0), axis.title = element_text(face=\"bold\", size=18, angle=0))\n# \n# \n# pdf(file.path(figures.path, 'celltype_perc_MtSinai.pdf'), width = 10, height = 6)\n# print(gg.ds2)\n# dev.off()\n# \n# \n# pdf(file.path(figures.path, 'celltype_perc_combined.pdf'), width = 18, height = 6)\n# gridExtra::grid.arrange(gg.ds1, gg.ds2, nrow = 1)\n# dev.off()\n# \n# \n# \n# \n# df$celltype = factor(df$celltype, names(colors))\n# # df$sample = droplevels(factor(df$sample, colnames(ncells.freq)[sample.perm]))\n# \n# gg.ds2 = ggbarplot(df, \"sample\", \"freq\",\n# fill = \"celltype\", color = \"black\", palette = colors[levels(df$celltype)], xlab = \"Individual\", ylab = \"Percentage\") + theme(axis.text.x = element_text(face=\"bold\", size=0, angle=90), axis.text.y = element_text(face=\"bold\", size=12, angle=0), axis.title = element_text(face=\"bold\", size=18, angle=0))\n# \n# \n\n\n\n\nX = ncells.freq\ndf = reshape2::melt(X)\ncolnames(df)=c(\"celltype\", \"sample\", \"freq\")\n\ndf$celltype = factor(df$celltype, names(colors))\n\ngg.combined = ggbarplot(df, \"sample\", \"freq\",\n fill = \"celltype\", color = \"black\", palette = colors[levels(df$celltype)], xlab = \"Individual\", ylab = \"Percentage\") + theme(axis.text.x = element_text(face=\"bold\", size=8, angle=90,hjust=0.95,vjust=0.2), axis.text.y = element_text(face=\"bold\", size=12, angle=0), axis.title = element_text(face=\"bold\", size=18, angle=0))\n\npdf(file.path(figures.path, 'celltype_perc_joint.pdf'), width = 16, height = 6)\nprint(gg.combined)\ndev.off()\n\n\n\n\n\nX = ncells.freq[, pb.logcounts$Phenotype[match(colnames(ncells.freq), pb.logcounts$ID)] == \"CON\"]\ndf = reshape2::melt(X)\ncolnames(df)=c(\"celltype\", \"sample\", \"freq\")\n\ndf$celltype = factor(df$celltype, names(colors))\n\ngg.combined = ggbarplot(df, \"sample\", \"freq\",\n fill = \"celltype\", color = \"black\", palette = colors[levels(df$celltype)], xlab = \"Individual\", ylab = \"Percentage\") + theme(axis.text.x = element_text(face=\"bold\", size=8, angle=90,hjust=0.95,vjust=0.2), axis.text.y = element_text(face=\"bold\", size=12, angle=0), axis.title = element_text(face=\"bold\", size=18, angle=0))\n\npdf(file.path(figures.path, 'celltype_perc_CON.pdf'), width = 12, height = 6)\nprint(gg.combined)\ndev.off()\n\n\n\nX = ncells.freq[, pb.logcounts$Phenotype[match(colnames(ncells.freq), pb.logcounts$ID)] == \"SZ\"]\ndf = reshape2::melt(X)\ncolnames(df)=c(\"celltype\", \"sample\", \"freq\")\n\ndf$celltype = factor(df$celltype, names(colors))\n\ngg.combined = ggbarplot(df, \"sample\", \"freq\",\n fill = \"celltype\", color = \"black\", palette = colors[levels(df$celltype)], xlab = \"Individual\", ylab = \"Percentage\") + theme(axis.text.x = element_text(face=\"bold\", size=8, angle=90,hjust=0.95,vjust=0.2), axis.text.y = element_text(face=\"bold\", size=12, angle=0), axis.title = element_text(face=\"bold\", size=18, angle=0))\n\npdf(file.path(figures.path, 'celltype_perc_SZ.pdf'), width = 12, height = 6)\nprint(gg.combined)\ndev.off()\n\n\n\n\n```\n\n# Plot cell type fraction stats per phenotype\n```{r}\nX.CON = apply(metadata(pb.logcounts)$n_cells[, pb.logcounts$Phenotype == \"CON\"], 2, as.numeric)\nX.SZ = apply(metadata(pb.logcounts)$n_cells[, pb.logcounts$Phenotype == \"SZ\"], 2, as.numeric)\nrownames(X.CON) = rownames(X.SZ) = names(assays(pb.logcounts))\n\n# X.CON = apply(X.CON, 2, function(x) 100*x/sum(x))\n# X.SZ = apply(X.SZ, 2, function(x) 100*x/sum(x))\n# mu1 = apply(X.CON, 1, mean)\n# mu2 = apply(X.SZ, 1, mean)\n# sigmasq1 = apply(X.CON, 1, var)\n# sigmasq2 = apply(X.SZ, 1, var)\n# n1 = ncol(X.CON)\n# n2 = ncol(X.SZ)\n\nwilcox.out = presto::wilcoxauc(cbind(X.CON, X.SZ), c(rep(\"CON\", ncol(X.CON)), rep(\"SZ\", ncol(X.SZ))))\nwilcox.out = wilcox.out[wilcox.out$group == \"SZ\", ]\n\n\nPerc = t(apply(cbind(Matrix::rowMeans(X.CON), Matrix::rowMeans(X.SZ)), 1, function(x) 100*x / sum(x)))\ncolnames(Perc) = c(\"CON\", \"SZ\")\nPerc = Perc[order(Perc[, 1] - Perc[, 2], decreasing = T), ]\n# df = Perc[wilcox.out$feature[order(-log10(wilcox.out$pval)*sign(wilcox.out$logFC))], ]\ndf = reshape2::melt(Perc)\ncolnames(df) = c(\"Celltype\", \"Phenotype\", \"Perc\")\ndf$Celltype = factor(df$Celltype, names(colors))\n\ngg = ggbarplot(df, \"Celltype\", \"Perc\", fill = \"Phenotype\", palette = c(\"#cccccc\", \"#888888\"))+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1, colour = colors)) + xlab(\"Celltype\") + ylab(\"Percentage\")\n\npdf(file.path(figures.path, \"Celltype_perc_per_phenotype.pdf\"), height = 5, width = 8)\nprint(gg)\ndev.off()\n\n\n\n\n```\n\n\n\n# Plot gene/umi statistics\n## Per cell type\n```{r}\numis = ACTIONet_summary$metadata$umi_count\nmito.perc = ACTIONet_summary$metadata$mito_perc\ngenes = ACTIONet_summary$metadata$gene_counts\ndataset = ACTIONet_summary$metadata$dataset\nindiv = ACTIONet_summary$metadata$Individual\ncelltype = ACTIONet_summary$metadata$Labels\ndf = data.frame(celltype = celltype, umis = umis, genes = genes, mito = mito.perc, dataset = dataset, individual = indiv) \n\ndf = df[df$individual %in% colnames(pb.logcounts)[mask == T], ]\n\ndf$celltype = factor(df$celltype, names(colors))\n\nrequire(ggpubr)\ngg.umis.1 = ggviolin(df[df$dataset == \"McLean\", ], \"celltype\", \"umis\", fill = \"celltype\", palette = colors,\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Celltype\") + ylab(\"UMIs\")+ theme(legend.position = \"none\")\n\npng(file.path(figures.path, \"McLean_UMIs.png\"), width = 1200, height = 600, res = 150)\nprint(gg.umis.1)\ndev.off()\n\ngg.umis.2 = ggviolin(df[df$dataset == \"MtSinai\", ], \"celltype\", \"umis\", fill = \"celltype\", palette = colors,\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Celltype\") + ylab(\"UMIs\")+ theme(legend.position = \"none\")\n\npng(file.path(figures.path, \"MtSinai_UMIs.png\"), width = 1200, height = 600, res = 150)\nprint(gg.umis.2)\ndev.off()\n\n\nrequire(ggpubr)\ngg.genes.1 = ggviolin(df[df$dataset == \"McLean\", ], \"celltype\", \"genes\", fill = \"celltype\", palette = colors,\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Celltype\") + ylab(\"genes\")+ theme(legend.position = \"none\")\n\npng(file.path(figures.path, \"McLean_genes.png\"), width = 1200, height = 600, res = 150)\nprint(gg.genes.1)\ndev.off()\n\ngg.genes.2 = ggviolin(df[df$dataset == \"MtSinai\", ], \"celltype\", \"genes\", fill = \"celltype\", palette = colors,\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Celltype\") + ylab(\"genes\")+ theme(legend.position = \"none\")\n\npng(file.path(figures.path, \"MtSinai_genes.png\"), width = 1200, height = 600, res = 150)\nprint(gg.genes.2)\ndev.off()\n\nrequire(ggpubr)\ngg.mito.1 = ggviolin(df[df$dataset == \"McLean\", ], \"celltype\", \"mito\", fill = \"celltype\", palette = colors,\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Celltype\") + ylab(\"mito\") + ylim(c(0, 10))+ theme(legend.position = \"none\")\n\npng(file.path(figures.path,\"McLean_mito.png\"), width = 1200, height = 600, res = 150)\nprint(gg.mito.1)\ndev.off()\n\ngg.mito.2 = ggviolin(df[df$dataset == \"MtSinai\", ], \"celltype\", \"mito\", fill = \"celltype\", palette = colors,\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Celltype\") + ylab(\"mito\") + ylim(c(0, 10))+ theme(legend.position = \"none\")\n\npng(file.path(figures.path, \"MtSinai_mito.png\"), width = 1200, height = 600, res = 150)\nprint(gg.mito.2)\ndev.off()\n\n```\n\n## Per sample\n```{r}\ndf$individual = factor(as.character(df$individual), as.character(pb.logcounts$ID[order(pb.logcounts$umis, decreasing = T)]))\n\nrequire(ggpubr)\ngg.umis.1 = ggviolin(df[df$dataset == \"McLean\", ], \"individual\", \"umis\", fill = \"individual\", add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Individual\") + ylab(\"UMIs\")+ theme(legend.position = \"none\")\n\n\npng(file.path(figures.path, \"McLean_UMIs_per_sample.png\"), width = 1200, height = 500, res = 150)\nprint(gg.umis.1)\ndev.off()\n\ngg.umis.2 = ggviolin(df[df$dataset == \"MtSinai\", ], \"individual\", \"umis\", fill = \"individual\",\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Celltype\") + ylab(\"UMIs\")+ theme(legend.position = \"none\")\n\npng(file.path(figures.path, \"MtSinai_UMIs_per_sample.png\"), width = 2100, height = 500, res = 150)\nprint(gg.umis.2)\ndev.off()\n\n\n\ndf$individual = factor(as.character(df$individual), as.character(pb.logcounts$ID[order(pb.logcounts$genes, decreasing = T)]))\n\nrequire(ggpubr)\ngg.genes.1 = ggviolin(df[df$dataset == \"McLean\", ], \"individual\", \"genes\", fill = \"individual\",\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Celltype\") + ylab(\"genes\")+ theme(legend.position = \"none\")\n\npng(file.path(figures.path, \"McLean_genes_per_sample.png\"), width = 1200, height = 500, res = 150)\nprint(gg.genes.1)\ndev.off()\n\ngg.genes.2 = ggviolin(df[df$dataset == \"MtSinai\", ], \"individual\", \"genes\", fill = \"individual\",\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Celltype\") + ylab(\"genes\")+ theme(legend.position = \"none\")\n\npng(file.path(figures.path, \"MtSinai_genes_per_sample.png\"), width = 2100, height = 500, res = 150)\nprint(gg.genes.2)\ndev.off()\n\ndf$individual = factor(as.character(df$individual), as.character(pb.logcounts$ID[order(pb.logcounts$mito_perc, decreasing = T)]))\n\nrequire(ggpubr)\ngg.mito.1 = ggviolin(df[df$dataset == \"McLean\", ], \"individual\", \"mito\", fill = \"individual\",\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Celltype\") + ylab(\"mito\")+ theme(legend.position = \"none\") + ylim(c(0, 10))\n\npng(file.path(figures.path,\"McLean_mito_per_sample.png\"), width = 1200, height = 500, res = 150)\nprint(gg.mito.1)\ndev.off()\n\ngg.mito.2 = ggviolin(df[df$dataset == \"MtSinai\", ], \"individual\", \"mito\", fill = \"individual\",\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Celltype\") + ylab(\"mito\")+ theme(legend.position = \"none\") + ylim(c(0, 10))\n\npng(file.path(figures.path, \"MtSinai_mito_per_sample.png\"), width = 2100, height = 500, res = 150)\nprint(gg.mito.2)\ndev.off()\n\n```\n\n\n# Plot mappings of cell type annotations to other annotations\n## Load markers\n```{r}\ndata(\"curatedMarkers_human\")\nLayers = readRDS(\"~/results/input/Yao_layer_marker.RDS\")\nrdbu_fun = circlize::colorRamp2(c(-3, -1, 0, 1, 3), rev(pals::brewer.rdbu(9)[seq(1, 9, by = 2)]))\n```\n\n## Annotate\n```{r}\n# rownames(celltype.gene.spec)\n# ct.layer.annot.1 = annotate.profile.using.markers(celltype.gene.spec, Layers)\n\n\nX = as(do.call(cbind, lapply(Layers, function(gs) as.numeric(rownames(pb.logcounts) %in% gs))), \"dgCMatrix\")\nrownames(X) = rownames(pb.logcounts)\nLayer.annot = assess.geneset.enrichment.from.scores(celltype.gene.spec, X)\n\nZ = scale(t(Layer.annot$logPvals))\nrownames(Z) = colnames(celltype.gene.spec)\n# Z = scale(ct.layer.annot$Enrichment)\ncolnames(Z) = c(paste(\"L\", c(1:6), sep = \"\"), \"WM\")\n\npdf(file.path(figures.path, \"celltype_annotation_layers_v2.pdf\"), width = 4)\nHeatmap(Z, cluster_rows = F, cluster_columns = F, rect_gp = gpar(col = \"black\"), row_names_side = \"left\", row_names_gp = gpar(col = colors), col = rdbu_fun, name = \"Layer\", column_title = \"Layer (Maynard et al.)\")\ndev.off()\n\n\n# ct.mohammadi.annot = annotate.clusters.using.markers(ace, curatedMarkers_human$Brain$PFC$Mohammadi2020$marker.genes, specificity.slot.name = \"Celltypes\")\n\n# Z = scale(ct.mohammadi.annot$Enrichment)\nX = as(do.call(cbind, lapply(curatedMarkers_human$Brain$PFC$Mohammadi2020$marker.genes, function(gs) as.numeric(rownames(pb.logcounts) %in% gs))), \"dgCMatrix\")\nrownames(X) = rownames(pb.logcounts)\nCelltype.annot = assess.geneset.enrichment.from.scores(celltype.gene.spec, X)\n\nZ = scale(t(Celltype.annot$logPvals))\nrownames(Z) = colnames(celltype.gene.spec)\n\n\nM = as(t(MWM_hungarian(ct.mohammadi.annot$Enrichment)), \"dgTMatrix\")\n\n\npdf(file.path(figures.path, \"celltype_annotation_mohammadi_markers_v2.pdf\"), width = 6)\nHeatmap(Z[, M@i+1], cluster_rows = F, cluster_columns = F, rect_gp = gpar(col = \"black\"), row_names_side = \"left\", row_names_gp = gpar(col = colors), col = rdbu_fun, name = \"Celltypes\", column_title = \"Celltypes (Mohammadi et al.)\")\ndev.off()\n\n\n\nct.Velmeshev.annot = annotate.clusters.using.markers(ace, curatedMarkers_human$Brain$PFC$Velmeshev2019$marker.genes, specificity.slot.name = \"Celltypes\")\n\nZ = scale(ct.Velmeshev.annot$Enrichment)\n\nM = as(t(MWM_hungarian(ct.Velmeshev.annot$Enrichment)), \"dgTMatrix\")\n\n\npdf(file.path(figures.path, \"celltype_annotation_velmeshev_markers.pdf\"), width = 8)\nHeatmap(Z[, M@i+1], cluster_rows = F, cluster_columns = F, rect_gp = gpar(col = \"black\"), row_names_side = \"left\", row_names_gp = gpar(col = colors), col = rdbu_fun, name = \"Celltypes\", column_title = \"Celltypes (Velmeshev et al.)\")\ndev.off()\n\n\nct.Mathys.annot = annotate.clusters.using.markers(ace, curatedMarkers_human$Brain$PFC$MathysDavila2019$marker.genes, specificity.slot.name = \"Celltypes\")\n\nZ = scale(ct.Mathys.annot$Enrichment)\n\nM = as(t(MWM_hungarian(ct.Mathys.annot$Enrichment)), \"dgTMatrix\")\n\n\npdf(file.path(figures.path, \"celltype_annotation_mathys_markers.pdf\"), width = 8)\nHeatmap(Z[, M@i+1], cluster_rows = F, cluster_columns = F, rect_gp = gpar(col = \"black\"), row_names_side = \"left\", row_names_gp = gpar(col = colors), col = rdbu_fun, name = \"Celltypes\", column_title = \"Celltypes (Mathys and Davilla et al.)\")\ndev.off()\n\n\n\nct.Wang.annot = annotate.clusters.using.markers(ace, curatedMarkers_human$Brain$PFC$Wang2018$marker.genes, specificity.slot.name = \"Celltypes\")\n\nZ = scale(ct.Wang.annot$Enrichment)\n\nM = as(t(MWM_hungarian(ct.Wang.annot$Enrichment)), \"dgTMatrix\")\n\n\npdf(file.path(figures.path, \"celltype_annotation_wang_markers.pdf\"), width = 8)\nHeatmap(Z[, M@i+1], cluster_rows = F, cluster_columns = F, rect_gp = gpar(col = \"black\"), row_names_side = \"left\", row_names_gp = gpar(col = colors), col = rdbu_fun, name = \"Celltypes\", column_title = \"Celltypes (Wang et al.)\")\ndev.off()\n\n\nct.He.annot = annotate.clusters.using.markers(ace, curatedMarkers_human$Brain$Layers$marker.genes, specificity.slot.name = \"Celltypes\")\n\nZ = scale(ct.He.annot$Enrichment)\n\n\n\npdf(file.path(figures.path, \"celltype_annotation_He_markers.pdf\"), width = 4)\nHeatmap(Z, cluster_rows = F, cluster_columns = F, rect_gp = gpar(col = \"black\"), row_names_side = \"left\", row_names_gp = gpar(col = colors), col = rdbu_fun, name = \"Layers\", column_title = \"Layers (He et al.)\")\ndev.off()\n\n\n\n\n\n\n\n\n# X = as(do.call(cbind, lapply(Layers, function(gs) as.numeric(rownames(pb.logcounts) %in% gs))), \"dgCMatrix\")\n# rownames(X) = rownames(pb.logcounts)\n# Layer.annot = assess.geneset.enrichment.from.scores(ace$Celltypes_feature_specificity, X)\n# \n# Annot = t(Layer.annot$logPvals)\n# rownames(Annot) = colnames(ace$Celltypes_feature_specificity)\n# \n# Heatmap(scale(Annot[, -1]), cluster_rows = F, cluster_columns = F, rect_gp = gpar(col = \"black\"))\n\n```\n## Archetypes\n```{r}\nct.arch.annot = annotate.archetypes.using.labels(t(ACTIONet_summary$H_unified), ACTIONet_summary$metadata$Labels)\n\nperm = order(ct.arch.annot$Confidence, decreasing = T)\nselected.cols = match(colnames(ct.arch.annot$Enrichment), ct.arch.annot$Label[perm])\nselected.cols = selected.cols[!is.na(selected.cols)]\nX = t(ct.arch.annot$Enrichment[perm, ])\nX = X[, selected.cols]\nZ = scale(X)\n\ncolnames(Z) = sapply(colnames(Z), function(str) str_split(str, \"-\")[[1]][[1]])\n\npdf(file.path(figures.path, \"celltype_annotation_vs_archetypes_v3.pdf\"), width = 7)\nHeatmap(Z, cluster_rows = F, cluster_columns = F, rect_gp = gpar(col = \"black\"), row_names_side = \"left\", row_names_gp = gpar(col = colors), col = rdbu_fun, name = \"Archetypes\", column_title = \"Archetypes\")\ndev.off()\n\n```\n# Plot cell states\n```{r}\ncellstates = c(7, 11, 17, 29)\ncellstate.titles = c(\"A7-NRGN\", \"A11-Ex-SZ\", \"A17-SZTR\", \"A29-In-SZ\")\nsubH = ACTIONet_summary$H_unified[, cellstates]\n\nggs = lapply(1:length(cellstates), function(i) {\n gg = plot.ACTIONet.gradient(ACTIONet_summary$ACTIONet2D, subH[, i], alpha_val = 0, point_size = 0.5, grad_palette = \"magma\") + ggtitle(cellstate.titles[[i]])\n \n return(gg)\n})\n\n\npng(file.path(figures.path, \"ACTIONet_cellstates.png\"), width = 800*3, height = 600*3, res = 150)\ndo.call(gridExtra::grid.arrange, c(lapply(ggs, ggplotify::as.grob), nrow = 2))\ndev.off()\n\nsapply(1:4, function(i) {\n png(file.path(figures.path, sprintf(\"ACTIONet_cellstates_%s.png\", cellstate.titles[[i]])), width = 1600, height = 1200, res = 150)\n plot(ggs[[i]])\n dev.off()\n})\n\n```\n\n# Plot cell types\n```{r}\nidx = setdiff(1:ncol(ACTIONet_summary$H_unified), cellstates)\nsubH = ACTIONet_summary$H_unified[, -cellstates]\nLl = ct.arch.annot$Label[-cellstates]\nperm = order(match(Ll, names(colors)))\nsubH = subH[, perm]\nLl = Ll[perm]\nidx = idx[perm]\n\nggs.archs.celltypes = lapply(1:length(Ll), function(i) {\n gg = plot.ACTIONet.gradient(ACTIONet_summary$ACTIONet2D, subH[, i], alpha_val = 0, point_size = 0.5, grad_palette = \"magma\") + ggtitle(sprintf(\"A%d-%s\", idx[[i]], Ll[[i]])) + theme(plot.title = element_text(color = colors[[Ll[[i]]]]))\n return(gg)\n})\n\n\npng(file.path(figures.path, \"ACTIONet_archetypes_nonstate.png\"), width = 800*7, height = 600*4, res = 150)\ndo.call(gridExtra::grid.arrange, c(lapply(ggs.archs.celltypes, ggplotify::as.grob), nrow = 4))\ndev.off()\n \n```\n\n\n\n" }, { "alpha_fraction": 0.6364190578460693, "alphanum_fraction": 0.6580266952514648, "avg_line_length": 29.963714599609375, "blob_id": "6c4152af66af61da9daa28983b7b24fd42e00581", "content_id": "544b4cf061d0adff5d84beb989243b88a56b483a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 21335, "license_type": "no_license", "max_line_length": 507, "num_lines": 689, "path": "/old/AnalyzeDE_ChEA.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"Analyze DE genes\"\nsubtitle: \"Step 3: Postprocessing the alignment of DE results across datasets\"\n\noutput: html_notebook\n---\n\n# Setup\n```{r include=FALSE}\nrequire(ACTIONet)\nrequire(stringr)\nrequire(ComplexHeatmap)\n\n\nresults.path = \"~/results\"\ninput.path = \"~/results/input\"\ndataset.path = \"~/results/datasets\"\ntables.path = \"~/results/tables\"\nfigures.path = \"~/results/figures\"\n\n```\n\n\n## Enrichment function\n```{r}\nassess.genesets <-function (arch.gs, terms.gs, N, min.pval = 1e-100, correct = \"none\"){\n shared = t(sapply(terms.gs, function(gs1) {\n sapply(arch.gs, function(gs2) {\n nn = intersect(gs1, gs2)\n })\n }))\n colnames(shared) = names(arch.gs)\n GS.sizes = sapply(terms.gs, length)\n logPvals.out = sapply(1:ncol(shared), function(i) {\n gg = shared[, i]\n x = as.numeric(sapply(gg, length))\n n.sample = length(arch.gs[[i]])\n n.success = as.numeric(GS.sizes)\n v = rep(1, length(x))\n min.overlap = n.success * n.sample/N\n idx = which(x >= min.overlap)\n if (length(idx) == 0) \n return(v)\n v[idx] = (phyper(x[idx]-1, n.sample, N-n.sample, n.success[idx], lower.tail = F))\n # v[idx] = HGT_tail(population.size = N, success.count = n.success[idx], \n # sample.size = n.sample, observed.success = x[idx])\n return(v)\n })\n if(correct == \"global\") {\n logPvals.out = matrix(p.adjust(logPvals.out, \"fdr\"), nrow = nrow(logPvals.out))\n } else if(correct == \"local\") {\n logPvals.out = apply(logPvals.out, 2, function(x) p.adjust(x, \"fdr\"))\n }\n rownames(logPvals.out) = names(terms.gs)\n colnames(logPvals.out) = names(arch.gs)\n return(-log10(Matrix::t(logPvals.out)))\n}\n```\n\n# Load primary datasets\n```{r, eval = T}\nACTIONet_summary = readr::read_rds(file.path(dataset.path, \"ACTIONet_summary_filtered_individuals.rds\"))\npb.logcounts = readr::read_rds(file.path(dataset.path, \"PB_mean_logcounts_final.RDS\"))\n\ncolor.df = readRDS(file.path(dataset.path, \"celltype_colors.rds\"))\ncolors = color.df$color\nnames(colors) = color.df$celltype\n\n```\n\n\n# Load DE results\n```{r, eval = T}\nfiltered.tables = readr::read_rds(file.path(dataset.path, \"Cohort_specific_DE_results_filtered.rds\"))\ncombined.analysis.tables = readr::read_rds(file.path(dataset.path, \"meta_analysis_results.rds\"))\n\nDE.new = readRDS(file.path(dataset.path, \"DE_genes_pseudobulk.rds\"))\nUp.genes = DE.new$Up.genes\nDown.genes = DE.new$Down.genes\nDE.sc = DE.new$DE.sc\n\n```\n\n\n\n\n## Use ChEA3 REST API\n```{r}\n\nif(file.exists(file.path(dataset.path, \"ChEA_DE_TF_enrichment_min30genes.RDS\"))) {\n ChEA.analysis = readRDS(file.path(dataset.path, \"ChEA_DE_TF_enrichment_min30genes.RDS\"))\n} else {\n ChEA3.Up = lapply(Up.genes, function(genes) {\n if(length(genes) > 30)\n queryChEA3(genes)\n })\n \n ChEA3.Down = lapply(Down.genes, function(genes) {\n if(length(genes) > 30)\n queryChEA3(genes)\n })\n \n \n names(ChEA3.Up) = paste(\"Up\", names(Up.genes), sep = \"_\")\n names(ChEA3.Down) = paste(\"Down\", names(Down.genes), sep = \"_\")\n \n ChEA.analysis = c(ChEA3.Up, ChEA3.Down)\n saveRDS(ChEA.analysis, file = file.path(dataset.path, \"ChEA_DE_TF_enrichment_min30genes.RDS\"))\n}\n\n \nChEA3.Up = ChEA.analysis[grep(\"Up\", names(ChEA.analysis))]\nChEA3.Down = ChEA.analysis[grep(\"Down\", names(ChEA.analysis))]\n\nnames(ChEA3.Up) = names(ChEA3.Down) = names(Up.genes)\n\n```\n\n\n## Load significant variants and mapped genes\n```{r}\nPGC3.loci = read.table(file.path(input.path, \"PGC3_SZ_significant_loci.csv\"), sep = \"\\t\", header = T)\n\nassociated.genes = PGC3.loci$ENSEMBL.genes..all..clear.names.\n\n\nPGC3.all.genes.raw = sort(unique(unlist(sapply(PGC3.loci$ENSEMBL.genes..all..clear.names., function(str) {\n if(str == \"-\") {\n return(\"-\")\n }\n gs = str_split(str, \",\")[[1]]\n \n return(gs)\n}))))\n\nPGC3.all.genes = intersect(PGC3.all.genes.raw, rownames(pb.logcounts))\n\n\n\n```\n\n# Export TF ChEA scores as excel tables\n```{r}\nlibrary(openxlsx)\nUp.wb <- createWorkbook()\nfor(i in 1:length(ChEA3.Up)) {\n res = ChEA3.Up[[i]]\n if(is.null(res)) {\n next\n }\n \n X = res$`Integrated--topRank`\n \n X$Score = -log10(as.numeric(X$Score))\n X$Rank = as.numeric(X$Rank)\n X = X[, -c(1, 2, 5)]\n X$inPGC3 = as.numeric(X$TF %in% PGC3.all.genes)\n \n n = names(ChEA3.Up)[[i]] \n\n addWorksheet(wb=Up.wb, sheetName = n)\n writeData(Up.wb, sheet = n, X) \n\n}\n\nsaveWorkbook(Up.wb, file.path(tables.path, \"TFs_ChEA_scores_Up.xlsx\"), overwrite = TRUE)\n\n\nlibrary(openxlsx)\nDown.wb <- createWorkbook()\nfor(i in 1:length(ChEA3.Down)) {\n res = ChEA3.Down[[i]]\n if(is.null(res)) {\n next\n }\n \n X = res$`Integrated--topRank`\n \n X$Score = -log10(as.numeric(X$Score))\n X$Rank = as.numeric(X$Rank)\n X = X[, -c(1, 2, 5)]\n \n X$inPGC3 = as.numeric(X$TF %in% PGC3.all.genes)\n\n n = names(ChEA3.Down)[[i]]\n \n addWorksheet(wb=Down.wb, sheetName = n)\n writeData(Down.wb, sheet = n, X) \n\n}\n\nsaveWorkbook(Down.wb, file.path(tables.path, \"TFs_ChEA_scores_Down.xlsx\"), overwrite = TRUE)\n\n\n```\n\n# Construct ChEA score matrix for up- and down-regulated genes\n```{r}\nTFs = sort(unique(ChEA.analysis[[1]]$`Integrated--meanRank`$TF))\n\n\nTF.up = matrix(0, nrow = length(TFs), length(ChEA3.Up))\nrownames(TF.up) = TFs\ncolnames(TF.up) = names(ChEA3.Up)\nfor(i in 1:length(ChEA3.Up)) {\n res = ChEA3.Up[[i]]\n if(is.null(res)) {\n next\n }\n \n X = res$`Integrated--topRank`\n \n TF.up[match(X$TF, TFs), i] = -log10(as.numeric(X$Score))\n}\n\nTF.down = matrix(0, nrow = length(TFs), length(ChEA3.Down))\nrownames(TF.down) = TFs\ncolnames(TF.down) = names(ChEA3.Down)\nfor(i in 1:length(ChEA3.Down)) {\n res = ChEA3.Down[[i]]\n if(is.null(res)) {\n next\n }\n \n X = res$`Integrated--topRank`\n \n TF.down[match(X$TF, TFs), i] = -log10(as.numeric(X$Score))\n}\n\n# Only neuronal\nTF.mean.scores = apply(cbind(TF.down[, 1:17], TF.up[, 1:17]), 1, mean)\nnames(TF.mean.scores) = rownames(TF.down)\n\n\nTF.up = TF.up[, fast_column_sums(TF.up) != 0]\nTF.down = TF.down[, fast_column_sums(TF.down) != 0]\n\n```\n\n\n\n\n```{r}\nFunCat = readRDS(\"~/FunCat.rds\")\nFunCat.genes = split(FunCat$FunCat2Gene$Gene, factor(FunCat$FunCat2Gene$Category, unique(FunCat$FunCat2Gene$Category)))[-15]\nnames(FunCat.genes) = FunCat$FunCat2Class$Category\n\nFunCat.annotation = FunCat$FunCat2Class$Classification\n\nFunCatPal = ggpubr::get_palette(\"npg\", length(unique(FunCat.annotation)))\nnames(FunCatPal) = unique(FunCat.annotation)\n\n```\n\n# Construct TF modules\n## Filter PB samples\n```{r}\nncells = sapply(int_colData(pb.logcounts)$n_cells, as.numeric)\nrownames(ncells) = names(assays(pb.logcounts))\n\ncs = Matrix::colSums(ncells)\nncells.freq = 100*scale(ncells, center = F, scale = cs)\nEx.perc = (fast_column_sums(ncells.freq[grepl(\"^Ex\", rownames(ncells.freq)) & !grepl(\"^Ex-NRGN\", rownames(ncells.freq)), ]))\n\nmask = (Ex.perc >= 10) & (Ex.perc <= 80)\n\npb.logcounts.filtered = pb.logcounts [, mask]\n\n```\n\n## Compute TF-TF expression correlation within each cell type\n```{r}\ncts = names(assays(pb.logcounts.filtered))\n# cts = names(DE.new$Up.genes)\n# #cts = names(assays(pb.logcounts.filtered))\n# cts = cts[grep(\"^Ex|^In\", cts)]\n \nsubTFs = intersect(TFs, rownames(pb.logcounts))\nPB.assays.norm = lapply(cts, function(nn) {\n print(nn)\n E = assays(pb.logcounts.filtered)[[nn]]\n cs = Matrix::colSums(E)\n mask = (cs > 0)\n E = E[, mask]\n E = median(cs[mask])*scale(E, center = F, scale = cs[mask])\n\n # CC = cor(Matrix::t(E[subTFs, ]), use = \"p\")\n # CC[is.na(CC)] = 0\n\n return(E[subTFs, ])\n})\nnames(PB.assays.norm) = cts\n\n```\n\n# Convert to WGCNA compatible format\n```{r}\nnSets = length(cts)\nmultiExpr = vector(mode = \"list\", length = nSets)\nfor(i in 1:length(cts)) {\n multiExpr[[i]] = list(data = as.data.frame(t(PB.logcounts.combined[[i]])))\n # rownames(multiExpr[[i]]$data) = subTFs\n \n}\n\n```\n\n\n\n# Run WGCNA\n## Calculation of network adjacencies\n```{r}\nnGenes = length(subTFs)\nnSets = length(cts)\n\n# Initialize an appropriate array to hold the adjacencies\nadjacencies = array(0, dim = c(nSets, nGenes, nGenes));\n# Calculate adjacencies in each individual data set\nfor (set in 1:nSets) {\n adj = abs(cor(multiExpr[[set]]$data, use = \"p\"))^6\n # adj = ((1+cor(multiExpr[[set]]$data, use = \"p\"))/2)^12\n adj[is.na(adj)] = 0\n adjacencies[set, , ] = adj\n}\n\n```\n\n\n\n\n\n```{r}\nadj = adjacencies[8, , ]\nrownames(adj) = colnames(adj) = subTFs\ndiag(adj) = 0\nadj = doubleNorm(adj)\ncl = cluster.graph(adj, 5)\n\n\ncc = table(cl)\nTF.mods = split(rownames(adj), cl)\nTF.mods = TF.mods[as.numeric(names(cc)[cc>=10])]\nTF.mods = lapply(TF.mods, function(gs) sort(gs))\n\nperm = order(sapply(TF.mods, function(gs) mean(TF.mean.scores[gs])), decreasing = T)\nTF.mods = TF.mods[perm]\n\nnames(TF.mods) = 1:length(TF.mods)\n\nprint(length(TF.mods))\nprint(TF.mods[[1]])\n\n```\n\n\n## Calculation of Topological Overlap\n```{r}\n# Initialize an appropriate array to hold the TOMs\nTOM = array(0, dim = c(nSets, nGenes, nGenes));\n# Calculate TOMs in each individual data set\nfor (set in 1:nSets)\n TOM[set, , ] = TOMsimilarity(adjacencies[set, , ]);\n\n\n```\n\n## Calculation of consensus Topological Overlap\n```{r}\n# selected.cts = names(DE.new$Up.genes)\nscaleP = 0.95\nselected.cts = names(DE.new$Up.genes)\nindices = match(selected.cts, cts)\n\nscaleQuant = sapply(1:length(indices), function(i) quantile(as.numeric(TOM[indices[[i]], ,]), probs = scaleP, type = 8))\n\nindices = indices[order(scaleQuant, decreasing = T)]\nkappa = as.numeric(log(scaleQuant[1])/log(scaleQuant))\n\nconsensusTOM = matrix(1, nGenes, nGenes)\nconsensusTOM = TOM[indices[[1]], ,]\n\nfor(i in 2:length(indices)) {\n curTOM = TOM[indices[[i]], ,]\n scaledTOM = curTOM^kappa[i]\n # consensusTOM = consensusTOM * (scaledTOM)\n consensusTOM = consensusTOM + (scaledTOM)\n # consensusTOM = pmin(consensusTOM, scaledTOM)\n \n}\n# consensusTOM = consensusTOM^(1/length(indices))\n consensusTOM = consensusTOM *(1/length(indices))\n\n rownames(consensusTOM) = colnames(consensusTOM) = subTFs\n \n```\n\n```{r}\nreadr::write_rds(consensusTOM, file = file.path(dataset.path, \"WGCNA_consensusTOM.rds\"))\n\n```\n\n\n```{r}\n# Clustering\nconsTree = hclust(as.dist(1-consensusTOM), method = \"average\");\n# We like large modules, so we set the minimum module size relatively high:\nminModuleSize = 20;\n# Module identification using dynamic tree cut:\nunmergedLabels = cutreeDynamic(dendro = consTree, distM = 1- consensusTOM, method = \"hybrid\", deepSplit = 1, cutHeight = 0.99, minClusterSize = minModuleSize, pamRespectsDendro = TRUE );\n\nunmergedColors = labels2colors(unmergedLabels)\n\nsort(table(unmergedColors))\n\n```\n\n\n```{r}\nsizeGrWindow(8,6)\npdf(file.path(figures.path, \"Supp\", \"WGCNA_DynTreeCut.pdf\"), width = 8, height = 4)\nplotDendroAndColors(consTree, unmergedColors, \"Dynamic Tree Cut\", dendroLabels = FALSE, hang = 0.03, addGuide = TRUE, guideHang = 0.05)\ndev.off()\n\n```\n\n\n\n\n\n\n```{r}\n# Calculate module eigengenes\nunmergedMEs = multiSetMEs(multiExpr, colors = NULL, universalColors = unmergedColors)\n# Calculate consensus dissimilarity of consensus module eigengenes\nconsMEDiss = consensusMEDissimilarity(unmergedMEs);\n# Cluster consensus modules\nconsMETree = hclust(as.dist(consMEDiss), method = \"average\");\n# Plot the result\nsizeGrWindow(7,6)\npar(mfrow = c(1,1))\n\npdf(file.path(figures.path, \"Supp\", \"WGCNA_TFmod_clusters.pdf\"))\nplot(consMETree, main = \"Consensus clustering of consensus module eigengenes\", xlab = \"\", sub = \"\")\ndev.off()\n\n\n\n```\n\n\n```{r}\n# merge = mergeCloseModules(multiExpr, unmergedLabels, cutHeight = 0.25, verbose = 3)\n# \n# # Numeric module labels\n# moduleLabels = merge$colors;\n# # Convert labels to colors\n# moduleColors = labels2colors(moduleLabels)\n# # Eigengenes of the new merged modules:\n# consMEs = merge$newMEs;\n# \n# \n# sizeGrWindow(9,6)\n# plotDendroAndColors(consTree, cbind(unmergedColors, moduleColors),\n# c(\"Unmerged\", \"Merged\"),\n# dendroLabels = FALSE, hang = 0.03,\n# addGuide = TRUE, guideHang = 0.05)\n# \n# readr::write_rds(list(consMEs = consMEs, moduleColors = moduleColors, moduleLabels = moduleLabels, consTree = consTree), file = file.path(dataset.path, \"WGCNA_modules.rds\"))\n\n```\n\n\n\n```{r}\nTF.mean.scores = apply(cbind(TF.down, TF.up), 1, mean)\nnames(TF.mean.scores) = rownames(TF.down)\n\nff = factor(unmergedColors)\nTF.mods = split(subTFs, ff)\nperm = order(sapply(TF.mods, function(gs) mean(TF.mean.scores[gs])), decreasing = T)\nsorted.TFmods = levels(ff)[perm]\nTF.mods = TF.mods[sorted.TFmods]\nTF.mods = TF.mods[-which(sorted.TFmods == \"grey\")]\nTF.mods = lapply(TF.mods, function(gs) gs[order(TF.mean.scores[gs], decreasing = T)])\n\n\nTF.df = data.frame(TFs = subTFs, modules = unmergedLabels, colors = factor(unmergedColors, rev(sorted.TFmods)), GWAS.linked.PGC3 = as.numeric(subTFs %in% PGC3.all.genes), ChEA.aggregate.association = TF.mean.scores[subTFs])\n\nTF.df = TF.df[TF.df$modules != 0, ]\nTF.df = TF.df[order(TF.df$colors, TF.df$ChEA.aggregate.association, decreasing = T), ]\n\nTF.df$modules = paste(\"M\", match(TF.df$modules, unique(TF.df$modules)), sep = \"\")\n\nTF.df = droplevels(TF.df)\n\nwrite.table(TF.df, file.path(tables.path, \"TF_modules_WGCNA.tsv\"), sep = \"\\t\", row.names = F, col.names = T, quote = F)\n\n```\n\n\n```{r}\nTF.df = read.table(file.path(tables.path, \"TF_modules_WGCNA.tsv\"), sep = \"\\t\", header = T)\n\n```\n\n\n```{r}\nTF.mods = split(TF.df$TFs, factor(TF.df$colors, unique(TF.df$colors)))\n\ndf.up = reshape2::melt(cbind(TF.df[, c(1, 3)], data.frame(TF.up[TF.df$TFs, ])))\ndf.down = reshape2::melt(cbind(TF.df[, c(1, 3)], data.frame(TF.down[TF.df$TFs, ])))\ndf.down$value = df.down$value\ndf.up$Direction = \"Up\"\ndf.down$Direction = \"Down\"\ndf.combined = rbind(df.up, df.down)\ndf.combined$colors = factor(df.combined$colors, unique(TF.df$colors))\n \npdf(file.path(figures.path, \"ChEA_aggr_scores_per_module_barplot.pdf\"), height = 4)\nggbarplot(df.combined, \"colors\", \"value\", fill = \"Direction\", palette = c(\"#3288bd\", \"#d53e4f\"), add = \"mean_se\") + ylab(\"ChEA Score (combined)\") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1, color = unique(TF.df$colors))) + xlab(\"TF Modules (sorted)\")\ndev.off()\n\n\n\n```\n\n\n```{r}\n\nsorted.TFs = unlist(TF.mods)\nChEA.up.per.TF = as.matrix(apply(TF.up[sorted.TFs, ], 1, mean))\nChEA.down.per.TF = as.matrix(apply(TF.up[sorted.TFs, ], 1, mean))\n\n# Heatmap(ChEA.down.per.TF, cluster_rows = F)\n# \n\nww = consensusTOM[sorted.TFs, sorted.TFs]\ndiag(ww) = NA\n\nMPal = names(TF.mods)\nnames(MPal) = MPal\nha_row = rowAnnotation(Module = factor(unlist(lapply(1:length(TF.mods), function(i) rep(names(TF.mods)[[i]], length(TF.mods[[i]])))), names(TF.mods)), col = list(Module = MPal))\n\nha_row = rowAnnotation(Module = factor(unlist(lapply(1:length(TF.mods), function(i) rep(names(TF.mods)[[i]], length(TF.mods[[i]])))), names(TF.mods)), col = list(Module = MPal))\n\nX = ChEA.up.per.TF\nY = ChEA.down.per.TF\nrownames(ww) = colnames(ww) = c()\ncolnames(X) = colnames(Y) = c()\n\nPal = as.character(pals::brewer.ylorrd(11))\n\npdf(file.path(figures.path, \"TF_modules_unlabeled_colored.pdf\"), width = 7, height = 7)\nHeatmap(ww, row_names_side = \"left\", name = \"ConsensusTOM\", col = Pal, column_title = \"TF-TF expression correlation\", column_title_gp = gpar(fontsize = 21), cluster_rows = F, cluster_columns = F, left_annotation = ha_row)\ndev.off()\n\n\npdf(file.path(figures.path, \"TF_modules_unlabeled_uncolored.pdf\"), width = 5.5, height = 5)\nHeatmap(ww, row_names_side = \"left\", name = \"ConsensusTOM\", col = Pal, column_title = \"TF-TF expression correlation\", column_title_gp = gpar(fontsize = 12), cluster_rows = F, cluster_columns = F)\ndev.off()\n\n\n```\n\n```{r}\npurpleMod = TF.mods[[1]]\nmask = purpleMod %in% PGC3.all.genes\nTF.colors = rep(\"black\", length(sorted.TFs))\nTF.colors[mask] = \"red\"\n\n\nX.U = TF.up[purpleMod,]\nredCol_fun = circlize::colorRamp2(c(0, exp(quantile(log(X.U), seq(0.25, 0.95, length.out = 12)))), c(\"#ffffff\", pals::brewer.reds(12)))\n\nX.D = TF.down[purpleMod,]\nblueCol_fun = circlize::colorRamp2(c(0, exp(quantile(log(X.D), seq(0.25, 0.95, length.out = 12)))), c(\"#ffffff\", pals::brewer.blues(12)))\n\n# row.names(X.U) = rownames(X.D) = annots\n# CC = (cor(t(X.U)) + cor(t(X.D))) / 2\n# CC[is.na(CC)] = 0\n# perm = get_order(seriate)\n\npdf(file.path(figures.path, \"TF_module_purple_ChEA_scores.pdf\"), width = 8, height = 8)\nHeatmap(X.U, rect_gp = gpar(col = \"black\"), name = \"Up\", column_title = \"Up\", cluster_rows = F, cluster_columns = F, col = redCol_fun, row_names_side = \"left\", column_names_gp = gpar(fontsize = 14, fontface=\"bold\", col = colors[colnames(X.U)]), row_names_gp = gpar(fontsize = 14, fontface=\"bold\", col = TF.colors), column_title_gp = gpar(fontsize = 18, fontface=\"bold\"), row_title_gp = gpar(fontsize = 18, fontface=\"bold\"), row_names_max_width = unit(150, \"cm\"), column_names_max_height = unit(150, \"cm\"))+\nHeatmap(X.D, rect_gp = gpar(col = \"black\"), name = \"Down\", cluster_rows = F, cluster_columns = F, col = blueCol_fun, row_names_side = \"left\", column_title = \"Down\", column_names_gp = gpar(fontsize = 14, fontface=\"bold\", col = colors[colnames(X.D)]), row_names_gp = gpar(fontsize = 14, fontface=\"bold\"), column_title_gp = gpar(fontsize = 18, fontface=\"bold\"), row_title_gp = gpar(fontsize = 18, fontface=\"bold\"), row_names_max_width = unit(150, \"cm\"), column_names_max_height = unit(150, \"cm\"))\ndev.off()\n\n```\n\n\n\n\n\n# Overlap with ME37\n```{r}\nDev.modules = read.table('~/Mingfeng_Li_modules.csv', sep = '\\t', as.is = T, header = T)\n\nSATB2.module = TF.mods$purple\n\nrequire(stringr)\nDev.modules.genes = lapply(Dev.modules$X, function(mod) {\n mod = str_split(mod, \",\")[[1]]\n intersect(as.character(sapply(mod, function(g) str_split(g, fixed(\"|\"))[[1]][[2]])), TFs)\n})\nnames(Dev.modules.genes) = Dev.modules$Module\n\n\nphyper(length(intersect(Dev.modules.genes$ME37, SATB2.module)), length(SATB2.module), length(TFs)- length(SATB2.module), length(Dev.modules.genes$ME37), lower.tail = F) # 4.493923e-06\n\n\n\n\n\nS1 = setdiff(SATB2.module, Dev.modules.genes$ME37) # c(\"ETV5\", \"LHX2\", \"HIF1A\", \"RELA\", \"NFE2L1\", \"MYT1L\", \"ZNF365\", \"SMAD4\", \"ADNP\", \"NCOA1\", \"ZNF609\", \"NFE2L2\", \"ZEB1\", \"RARB\")\nS2 = setdiff(Dev.modules.genes$ME37, SATB2.module) # c(\"HIVEP1\", \"ZNF184\", \"NR4A3\", \"TSHZ3\", \"PRDM8\", \"FEZF2\", \"NEUROD6\", \"BHLHE22\", \"SATB1\", \"ZNF277\", \"MAFB\")\nS3 = intersect(Dev.modules.genes$ME37, SATB2.module) # c(\"NR4A2\", \"MEF2C\", \"SATB2\", \"SOX5\", \"EMX1\", \"TBR1\", \"NEUROD2\", \"TCF4\")\n\nS = c(\"MEF2C\" = length(S1), \"ME37\" = length(S2), \"MEF2C&ME37\" = length(S3))\nGS = list(\"MEF2C\" = (S1), \"ME37\" = (S2), \"MEF2C&ME37\" = (S3))\ndd = reshape2::melt(GS)\n\nwrite.table(dd, file = file.path(tables.path, \"TFMod_vs_ME37_overlap.txt\"), sep = '\\t', row.names = F, col.names = F, quote = F)\n\nrequire(eulerr)\npdf(file.path(figures.path, \"Supp\", \"SATB2_vs_ME37_Venn.pdf\"))\nplot(euler(S), quantities = T)\ndev.off()\n\n```\n\n## Analyze TGs with CUTTag\n```{r}\nCUTTag = readr::read_rds(\"~/CUTTag_linked_GRs_reproducible_linked_genes.rds\")\nCUTTag = CUTTag[-2]\n\nCUTTAG.vs.DE.up = assess.genesets(Up.genes, CUTTag, nrow(pb.logcounts), correct = \"local\")\nCUTTAG.vs.DE.down = assess.genesets(Down.genes, CUTTag, nrow(pb.logcounts), correct = \"local\")\n\n\nX.U = (CUTTAG.vs.DE.up)\nX.D = (CUTTAG.vs.DE.down)\ncolnames(X.U) = colnames(X.D) = names(CUTTag)\nX.U = X.U[, -3]\nX.D = X.D[, -3]\n\nredCol_fun = circlize::colorRamp2(c(0, exp(quantile(log(X.U)[X.U > -log10(0.05)], seq(0.05, 0.99, length.out = 12)))), c(\"#ffffff\", pals::brewer.reds(12)))\n\nblueCol_fun = circlize::colorRamp2(c(0, exp(quantile(log(X.D)[X.D > -log10(0.05)], seq(0.05, 0.99, length.out = 12)))), c(\"#ffffff\", pals::brewer.blues(12)))\n\n\npdf(file.path(figures.path, \"CUTTag_vs_DE_genes.pdf\"), width = 4, height = 6)\npar(mar=c(0,150,0,0))\nHeatmap(X.U, rect_gp = gpar(col = \"black\"), name = \"Up\", column_title = \"Up\", cluster_rows = F, cluster_columns = F, col = redCol_fun, row_names_side = \"left\", column_names_gp = gpar(fontsize = 14, fontface=\"bold\"), row_names_gp = gpar(fontsize = 14, fontface=\"bold\", col = colors), column_title_gp = gpar(fontsize = 12, fontface=\"bold\"), row_title_gp = gpar(fontsize = 12, fontface=\"bold\"), row_names_max_width = unit(150, \"cm\"), column_names_max_height = unit(150, \"cm\"))+\nHeatmap(X.D, rect_gp = gpar(col = \"black\"), name = \"Down\", cluster_rows = F, cluster_columns = F, col = blueCol_fun, row_names_side = \"left\", column_title = \"Down\", column_names_gp = gpar(fontsize = 14, fontface=\"bold\"), row_names_gp = gpar(fontsize = 14, fontface=\"bold\"), column_title_gp = gpar(fontsize = 12, fontface=\"bold\"), row_title_gp = gpar(fontsize = 12, fontface=\"bold\"), row_names_max_width = unit(150, \"cm\"), column_names_max_height = unit(150, \"cm\"))\ndev.off()\n\n\n```\n\n```{r}\nTGs = do.call(rbind, lapply(1:length(ChEA.analysis), function(i) {\n print(i)\n DF = ChEA.analysis[[i]]$`Integrated--topRank`\n if(is.null(DF))\n df = data.frame(TFs = c(\"SATB2\", \"MEF2C\", \"TCF4\", \"SOX5\"), genes = rep(\"\", ))\n else\n df = data.frame(TFs = c(\"SATB2\", \"MEF2C\", \"TCF4\", \"SOX5\"), genes = DF$Overlapping_Genes[match(c(\"SATB2\", \"MEF2C\", \"TCF4\", \"SOX5\"), DF$TF)])\n df$Id = paste(df$TFs, names(ChEA.analysis)[[i]], sep = \"_\")\n # df$enrichment=TF.pvals.enrichment[[i]]\n \n return(df)\n}))\n\nall.DE = sort(unique(union(unlist(DE.new$Up.genes), unlist(DE.new$Down.genes))))\n\nCUTTag.DE = lapply(CUTTag, function(x) intersect(x, all.DE))\n\nTGs.gs = as.list(TGs$genes)\nnames(TGs.gs) = TGs$Id\nTG.enrichment = assess.genesets(TGs.gs, CUTTag.DE, length(all.DE), correct = F)\n\n# pdf(\"~/PFC_v3/figures/CUTTag_enrichment.pdf\", height = 21)\n# Heatmap(TG.enrichment, rect_gp = gpar(col = \"black\"))\n# dev.off()\n\n\n\n\n\n```\n\n" }, { "alpha_fraction": 0.6818437576293945, "alphanum_fraction": 0.6857784986495972, "avg_line_length": 19.882352828979492, "blob_id": "852a15e60c284d44ed984a1880061bc8342ef6fa", "content_id": "999802bfc2eefc451acc0a7b179ad9f4b1194b45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 1779, "license_type": "no_license", "max_line_length": 99, "num_lines": 85, "path": "/RunDE_computePB.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"Perform DE analysis\"\nsubtitle: \"Step 1: Compute pseudobulk (PB) profiles\"\nauthor: \"Shahin Mohammadi\"\ndate: \"Run on `r Sys.time()`\"\ndocumentclass: article\noutput:\n html_document:\n toc: true\n toc_float: true\n---\n\n```{r setup, include=FALSE}\nsuppressPackageStartupMessages({\nlibrary(ACTIONet)\nlibrary(data.table)\nlibrary(ggplot2)\nlibrary(ggrepel)\nlibrary(cowplot)\nlibrary(corrplot)\nlibrary(muscat)\nlibrary(synapser)\nlibrary(synExtra)\nsynLogin(rememberMe = TRUE)\nsource(\"functions.R\")\n})\n\nknitr::opts_chunk$set(\n\teval = FALSE,\n\terror = FALSE,\n\tmessage = FALSE,\n\twarning = FALSE,\n\tcache = TRUE,\n\tdev = c(\"png\", \"pdf\"),\n\tinclude = FALSE,\n\ttidy = FALSE\n)\n\n\n```\n\n\n\n```{r}\ndataset.path = \"~/results/datasets/\"\nfigures.path = \"~/results/figures\"\ntables.path = \"~/results/tables\"\ninput.path = \"~/results/input\"\n\n\nindividual_metadata = loadDataset(\"individual_metadata\", dataset.path = dataset.path)\n\nace = loadDataset(\"combinedCells_ACTIONet\", dataset.path = dataset.path)\nsce = as(ace, \"SingleCellExperiment\")\n\n```\n\n# Use muscat to compute PB profiles\n```{r}\nsce$cluster_id = ace$Celltype\nsce$group_id = ace$Phenotype\nsce$sample_id = ace$ID\n\nlibrary(muscat)\nsce$id <- paste0(sce$Phenotype, sce$sample_id)\n(sce <- prepSCE(sce,\n kid = \"cluster_id\", # subpopulation assignments\n gid = \"group_id\", # group IDs (ctrl/stim)\n sid = \"sample_id\", # sample IDs (ctrl/stim.1234)\n drop = TRUE)) # drop all other colData columns\n\nsystem.time( {pb.logcounts <- aggregateData(sce,\n assay = \"logcounts\", fun = \"mean\",\n by = c(\"cluster_id\", \"sample_id\"))} )\n\ncolData(pb.logcounts) = cbind(colData(pb.logcounts), individual_metadata[colnames(pb.logcounts), ])\n\n```\n\n\n```{r}\n\nstoreDataset(pb.logcounts, name = \"pseudobulk_mean_logcounts\", dataset.path = dataset.path)\n\n```\n\n\n\n\n" }, { "alpha_fraction": 0.6669291853904724, "alphanum_fraction": 0.6877030730247498, "avg_line_length": 28.26512908935547, "blob_id": "b115ab1da7c18fe096995e9d13863bf6b698fef5", "content_id": "68ce1d6810daf694df5d99fc33935019702f82d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 10157, "license_type": "no_license", "max_line_length": 371, "num_lines": 347, "path": "/ancient/Fig2_Run_compute_PB.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"Perform DE analysis\"\noutput: html_notebook\n---\n\n# Setup\n```{r include=FALSE}\nrequire(ACTIONet)\nrequire(stringr)\nrequire(ComplexHeatmap)\n\nrequire(muscat)\nrequire(edgeR)\nrequire(limma)\n\ndataset.path = \"~/results/datasets/\"\nresults.path = \"~/results\"\nfigures.folder = \"~/results/figures\"\n\n\n```\n\n```{r}\nace = readr::read_rds(\"~/results/ACTIONet_reunified.rds\")\nsce = as(ace, \"SingleCellExperiment\")\n\n```\n\n```{r}\npb.logcounts.old = readr::read_rds(file.path(dataset.path, \"PB_sce_final.rds\"))\n\n```\n\n\n```{r}\n\n```\n\n\n```{r}\nACTIONet_summary = readr::read_rds(\"~/results/datasets/ACTIONet_summary.rds\")\n\nll = levels(ACTIONet_summary$metadata$Labels)\nll = c(ll[1:25], \"Vasc\")\nLabels = as.character(ACTIONet_summary$metadata$Labels)\n\nLabels[Labels %in% c(\"Endo\", \"Pericytes\")] = \"Vasc\"\n\nSST.cells = which(ACTIONet_summary$metadata$Labels == \"In-SST\")\nSST.subtypes = apply(ACTIONet_summary$H_unified[SST.cells, c(16, 21, 25)], 1, which.max)\nSST.l = c(\"In-SST_STK32A\", \"In-SST_CALB1\", \"In-SST_MEPE\")\nSST.subtypes = SST.l[SST.subtypes]\nLabels[SST.cells] = SST.subtypes\nLabels.f=factor(Labels, c(ll[1:20], SST.l, ll[22:26]))\n\nplot.ACTIONet(ace, Labels.f)\n\n```\n\n```{r}\nX = ACTIONet_summary$unified_feature_specificity[, c(16, 21, 25)]\nplot.top.k.features(doubleNorm(X), 10)\n\nHeatmap(X[c(\"TH\", \"TAC1\", \"TAC3\", \"STK32A\", \"CALB1\", \"NOS1\", \"CALB2\", \"CUX2\"), ])\n\n```\n\n\n```{r}\nvisualize.markers(ace, c(\"SST\", \"PVALB\", \"LYPD6\", \"LYPD6B\", \"MEPE\", \"CUX2\", \"CALB1\", \"STK32A\"))\n\n```\n```{r}\nexpr = impute.genes.using.ACTIONet(ace, c(\"CALB1\", \"CUX2\"), alpha_val = 0.99)\nidx = which(ace$Labels.final == \"In-SST\")\ndata = as.data.frame(scale(expr[idx, ]))\nmask = (df$CALB1 > 1) & (df$CUX2 > 1)\nSST_martin = as.numeric(1:ncol(ace) %in% idx[mask])\nplot.ACTIONet(ace, SST_martin)\n\n\n\nggplot(data, aes(x=CALB1, y=CUX2) ) +\n stat_density_2d(aes(fill = ..density..), geom = \"raster\", contour = FALSE) +\n scale_fill_distiller(palette=4, direction=-1) +\n scale_x_continuous(expand = c(0, 0)) +\n scale_y_continuous(expand = c(0, 0)) +\n theme(\n legend.position='none'\n )\n\n```\n```{r}\n\nplot.ACTIONet(ace, as.numeric(mask))\n```\n\n```{r}\n\n```\n\n\n```{r}\n\n```\n\n```{r}\nsce$cluster_id = Labels.f\nsce$group_id = ACTIONet_summary$metadata$Phenotype\nsce$sample_id = ACTIONet_summary$metadata$Individual\n\nlibrary(muscat)\nsce$id <- paste0(sce$Phenotype, sce$sample_id)\n(sce <- prepSCE(sce,\n kid = \"cluster_id\", # subpopulation assignments\n gid = \"group_id\", # group IDs (ctrl/stim)\n sid = \"sample_id\", # sample IDs (ctrl/stim.1234)\n drop = TRUE)) # drop all other colData columns\n\npb.logcounts <- aggregateData(sce,\n assay = \"logcounts\", fun = \"mean\",\n by = c(\"cluster_id\", \"sample_id\"))\n\nreadr::write_rds(pb.logcounts, file = \"~/results/PB_mean_logcounts_renormalized_with_subtypes.RDS\")\n\n```\n\n```{r}\npb.logcounts.old = readr::read_rds(file.path(dataset.path, \"PB_sce_final.rds\"))\npb.logcounts.old = readr::read_rds(file.path(dataset.path, \"PB_sce_final.rds\"))\n\n\nmetas = readr::read_rds(\"~/results/datasets/meta_data_final.rds\")\n\n\nmetas2 =data.frame(colData(pb.logcounts.old))\n\nreadr::write_rds(pb.logcounts, file = \"~/results/PB_mean_logcounts_renormalized_with_subtypes_annotated.RDS\")\n\n\n```\n\n```{r}\nACTIONet_summary = readr::read_rds(file.path(dataset.path, \"ACTIONet_summary_filtered_individuals.rds\"))\n\npb.logcounts = readr::read_rds(file.path(dataset.path, \"PB_sce_final.rds\"))\n\ncolor.df = readRDS(file.path(dataset.path, \"celltype_colors.rds\"))\n\ncolors = color.df$color\nnames(colors) = color.df$celltype\n\n# int_colData(pb.logcounts)$n_cells = t(metadata(pb.logcounts)$n_cells)\n# metadata(pb.logcounts) = metadata(pb.logcounts)[c(1:2)]\n# ncells = t(apply(int_colData(pb.logcounts)$n_cells, 2, as.numeric))\n\nncells = apply(metadata(pb.logcounts)$n_cells, 2, as.numeric)\n\n\n\n\n\n```\n\n# Prefilter outlier samples wrt ExNero %, or samples that have less than 500 cells (pruning from 140 -> 121 samples)\n```{r}\nrownames(ncells) = names(assays(pb.logcounts))\ncs = Matrix::colSums(ncells)\nncells.freq = 100*scale(ncells, center = F, scale = cs)\nEx.perc = (fast_column_sums(ncells.freq[grepl(\"^Ex\", rownames(ncells.freq)) & !grepl(\"^Ex-NRGN\", rownames(ncells.freq)), ]))\n\nncells.freq = ncells.freq[, order(Ex.perc, decreasing = T)]\nEx.perc = (fast_column_sums(ncells.freq[grepl(\"^Ex\", rownames(ncells.freq)) & !grepl(\"^Ex-NRGN\", rownames(ncells.freq)), ]))\n\n\nmask = (Ex.perc > 10) & (Ex.perc < 80) & (fast_column_sums(ncells) > 500)\n\n# Samples that are depleted in Ex.perc:: \n# # SZ15 0.2570694\n# # SZ3 2.8237585\n# # SZ24 3.7128713\n# # SZ29 7.5571178\n\npb.logcounts.filtered = pb.logcounts[, mask]\nmetadata(pb.logcounts.filtered)$n_cells = metadata(pb.logcounts.filtered)$n_cells[, mask]\n\n\n```\n\n# Performing cohort-specific DE\n```{r}\nform = ~ Phenotype + Batch + Gender + Age + PMI + Benzodiazepines + Anticonvulsants + AntipsychTyp + AntipsychAtyp + Antidepress\n\nresDE = lapply( levels(pb.logcounts.filtered$Cohort), function(chrt){\n\n\tkeep.ids = colnames(pb.logcounts.filtered)[pb.logcounts.filtered$Cohort == chrt]\n\n\tpb.logcounts.filtered_sub = pb.logcounts.filtered[,keep.ids]\n\tmetadata(pb.logcounts.filtered_sub)$n_cells = metadata(pb.logcounts.filtered_sub)$n_cells[,keep.ids]\n\n\tdesign.mat <- model.matrix(form, data = droplevels(colData(pb.logcounts.filtered_sub)))\n\n\tcolnames(design.mat)[1] = c(\"Intercept\")\n\n\tcontrast.mat <- makeContrasts(contrasts = \"PhenotypeSZ\", levels = design.mat)\n\n\tpbDS(pb.logcounts.filtered_sub, method = \"limma-trend\", min_cells = 5, design = design.mat, contrast = contrast.mat, filter = \"gene\")\n})\nnames(resDE) = levels(colData(pb.logcounts.filtered)$Cohort)\n\nreadr::write_rds(resDE, file.path(dataset.path, \"Cohort_specific_DE_results.rds\"))\n\n\n\n```\n\n# Read bulk DE\n```{r}\nCMC.DE = read.table(\"~/results/input/CMC_MSSM-Penn-Pitt_DLPFC_mRNA_IlluminaHiSeq2500_gene-adjustedSVA-differentialExpression-includeAncestry-DxSCZ-DE.tsv\", header = T)\nPEC.DE = read.table(\"~/results/input/Full_DE_table.csv\", header = T)\n\ncommon.genes = intersect(rownames(pb.logcounts), intersect(CMC.DE$MAPPED_genes, PEC.DE$gene_name))\n\nCMC.tstat = CMC.DE$t[match(common.genes, CMC.DE$MAPPED_genes)]\nPEC.tstat = PEC.DE$SCZ.t.value[match(common.genes, PEC.DE$gene_name)]\n\nnames(PEC.tstat) = names(CMC.tstat) = common.genes\npval = cor.test(CMC.tstat, PEC.tstat, method = \"spearman\")$p.value\n\nMcLean.PEC.cor.pvals = sapply(resDE$McLean$table$PhenotypeSZ, function(DF) {\n tstats = DF$t\n names(tstats) = DF$gene\n cg = intersect(common.genes, DF$gene)\n x = -log10(cor.test(tstats[cg], PEC.tstat[cg], method = \"spearman\")$p.value)\n \n return(x)\n})\n\n\nMtSinai.PEC.cor.pvals = sapply(resDE$MtSinai$table$PhenotypeSZ, function(DF) {\n tstats = DF$t\n names(tstats) = DF$gene\n cg = intersect(common.genes, DF$gene)\n x = -log10(cor.test(tstats[cg], PEC.tstat[cg], method = \"spearman\")$p.value)\n \n return(x)\n})\n\n\nMcLean.CMC.cor.pvals = sapply(resDE$McLean$table$PhenotypeSZ, function(DF) {\n tstats = DF$t\n names(tstats) = DF$gene\n cg = intersect(common.genes, DF$gene)\n x = -log10(cor.test(tstats[cg], CMC.tstat[cg], method = \"spearman\")$p.value)\n \n return(x)\n})\n\n\nMtSinai.CMC.cor.pvals = sapply(resDE$MtSinai$table$PhenotypeSZ, function(DF) {\n tstats = DF$t\n names(tstats) = DF$gene\n cg = intersect(common.genes, DF$gene)\n x = -log10(cor.test(tstats[cg], CMC.tstat[cg], method = \"spearman\")$p.value)\n \n return(x)\n})\n\ndf = data.frame(Celltypes = names(resDE$MtSinai$table$PhenotypeSZ), McLean.PEC = McLean.PEC.cor.pvals[names(resDE$MtSinai$table$PhenotypeSZ)], MtSinai.PEC = MtSinai.PEC.cor.pvals[names(resDE$MtSinai$table$PhenotypeSZ)], McLean.CMC = McLean.CMC.cor.pvals[names(resDE$MtSinai$table$PhenotypeSZ)], MtSinai.CMC = MtSinai.CMC.cor.pvals[names(resDE$MtSinai$table$PhenotypeSZ)])\ndf$Combined = combine.logPvals(t(as.matrix(df[, -1])))\ndf = df[order(df$Combined, decreasing = T), ]\n\ndf2 = reshape2::melt(df)\ncolnames(df2) = c(\"Celltype\", \"Test\", \"Enrichment\")\ndf2$Test = factor(as.character(df2$Test), c(\"Combined\", \"McLean.PEC\", \"MtSinai.PEC\", \"McLean.CMC\", \"MtSinai.CMC\"))\ndf2$Celltype = factor(df2$Celltype, df$Celltypes[order(df$Combined, decreasing = T)])\n\nrequire(ggpubr)\ngg =ggbarplot(df2, \"Celltype\", \"Enrichment\", fill = \"Test\", color = \"black\", palette = rev(pals::brewer.paired(5)),\n position = position_dodge(0.9), xlab = \"Celltype\", ylab = \"Enrichment\")+ theme(axis.text.x = element_text(face=\"bold\", size=8, angle=90,hjust=0.95,vjust=0.2, color = colors[levels(df2$Celltype)]), axis.text.y = element_text(face=\"bold\", size=12, angle=0), axis.title = element_text(face=\"bold\", size=18, angle=0))\n\npdf(file.path(figures.folder, \"DE_vs_bulk_v0.pdf\"))\nplot(gg)\ndev.off()\n\n\n\n\n```\n\n```{r}\nX = log1p(ACTIONet_summary$unified_feature_specificity[common.genes, ])\narch.SZ.CC = cor(X, abs(cbind(CMC.tstat, PEC.tstat)), method = \"pearson\")\n\n```\n\n# Prefiltering individual DE results before combining them\nOnly keep genes that have 1) consistent direction of dysregulation across both datasets, and 2) at least 1 sd away from zero on the logFC scale\n\n```{r}\ncelltypes = intersect(names(resDE$McLean$table$PhenotypeSZ), names(resDE$MtSinai$table$PhenotypeSZ))\n\nfiltered.tables = lapply(celltypes, function(celltype) {\n tbl1 = resDE[[1]]$table$PhenotypeSZ[[celltype]]\n tbl2 = resDE[[2]]$table$PhenotypeSZ[[celltype]]\n \n genes = intersect(tbl1$gene[1 <= abs(tbl1$logFC/sd(tbl1$logFC))], tbl2$gene[1 <= abs(tbl2$logFC / sd(tbl2$logFC))])\n \n tbl1 = tbl1[match(genes, tbl1$gene), ]\n tbl2 = tbl2[match(genes, tbl2$gene), ]\n \n mask = sign(tbl1$logFC)*sign(tbl2$logFC) > 0\n tbl1 = tbl1[mask, ]\n tbl2 = tbl2[mask, ]\n \n tbls = list(McClean = tbl1, MtSinai = tbl2) \n tbls = lapply( tbls, function(tab){\n tab$se = tab$logFC / tab$t\n tab\n })\n \n return(tbls)\n})\nnames(filtered.tables) = celltypes\n\nreadr::write_rds(filtered.tables, file.path(dataset.path, \"individual_diff_results_filtered.rds\"))\n\n```\n\n\n\n```{r}\n# filtered.tables.old = readRDS(\"~/PFC_v3/individual_diff_results_filtered.rds\")\n# \n# i = 1\nX1 = filtered.tables.old$`Ex-CC_THEMIS`\nX2 = filtered.tables$`Ex-L6_CC_SEMA3A`\n\n\ncor(X1$McClean$t, X2$McClean$t)\n\nresDE.old = readr::read_rds(\"~/PFC_v3/filtered_resDE.rds\")\n\n\nresDE.old$McLean$table$PhenotypeSZ$`Ex-CC_THEMIS`$t\n\n```\n\n\n" }, { "alpha_fraction": 0.6619834303855896, "alphanum_fraction": 0.6796778440475464, "avg_line_length": 38.81732940673828, "blob_id": "09b83c874c2bdd1a4bc91af5b68e1deb035041ad", "content_id": "9c05122a2ecf25bea15867af5de40415c3292c95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 17011, "license_type": "no_license", "max_line_length": 323, "num_lines": 427, "path": "/Annotation.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"Cell annotation and visualization\"\nsubtitle: ''\nauthor: \"Shahin Mohammadi\"\ndate: \"Run on `r Sys.time()`\"\ndocumentclass: article\noutput:\n html_document:\n toc: true\n toc_float: true\n---\n\n```{r setup, include=FALSE}\nsuppressPackageStartupMessages({\nlibrary(ACTIONet)\nlibrary(data.table)\nlibrary(ggplot2)\nlibrary(ggrepel)\nlibrary(cowplot)\nlibrary(corrplot)\nlibrary(muscat)\nlibrary(synapser)\nlibrary(synExtra)\nsynLogin(rememberMe = TRUE)\nsource(\"functions.R\")\n})\n\nknitr::opts_chunk$set(\n\teval = FALSE,\n\terror = FALSE,\n\tmessage = FALSE,\n\twarning = FALSE,\n\tcache = TRUE,\n\tdev = c(\"png\", \"pdf\"),\n\tinclude = FALSE,\n\ttidy = FALSE\n)\n\n\n```\n\n\n```{r}\n# devtools::load_all(\"~/ACTIONet/\")\ninstall.packages(\"~/ACTIONet/\", repos = NULL)\n\n```\n\n\n```{r}\ndataset.path = \"~/results/datasets/\"\nfigures.path = \"~/results/figures\"\ntables.path = \"~/results/tables\"\ninput.path = \"~/results/input\"\n\ncolors = loadDataset(\"celltype_colors\", dataset.path = dataset.path)\nACTIONet_summary = loadDataset(\"ACTIONet_summary\", dataset.path = dataset.path)\n\n```\n\n\n\n\n# Plot main ACTIONet\n## Celltypes\n```{r}\ngg = plot.ACTIONet(ACTIONet_summary$ACTIONet2D, ACTIONet_summary$metadata$Labels, palette = colors, text_size = 2, use_repel = T)\n\nstoreFigure(gg, name = \"ACTIONet_annotated\", extension = \"png\", figures.path = figures.path, width = 8, height = 6)\n\n```\n\n## Supps\n### Phenotype\n```{r}\ngg = plot.ACTIONet(ACTIONet_summary$ACTIONet2D, ACTIONet_summary$metadata$Phenotype, palette = c(\"#cccccc\", \"#888888\"), text_size = 2, use_repel = T, add_text_labels = F, point_size = 0.5)\n\nstoreFigure(gg, name = \"ACTIONet_phenotype_annotated_no_labels\", extension = \"png\", figures.path = figures.path, width = 8, height = 6)\n\n```\n\n### Batch\n```{r}\ngg = plot.ACTIONet(ACTIONet_summary$ACTIONet2D, ACTIONet_summary$metadata$Batch, text_size = 2, use_repel = T, add_text_labels = F, point_size = 0.5)\n\nstoreFigure(gg, name = \"ACTIONet_batch_annotated_no_labels\", extension = \"png\", figures.path = figures.path, width = 8, height = 6)\n\n```\n\n### Gender\n```{r}\nmask = !is.na(ACTIONet_summary$metadata$Gender)\ngg = plot.ACTIONet(ACTIONet_summary$ACTIONet2D[mask, ], ACTIONet_summary$metadata$Gender[mask], text_size = 2, use_repel = T, add_text_labels = F, point_size = 0.5, palette = c(\"pink\", \"#91bfdb\"))\n\nstoreFigure(gg, name = \"ACTIONet_gender_annotated_no_labels\", extension = \"png\", figures.path = figures.path, width = 8, height = 6)\n\n```\n\n### Archetype\n```{r}\ngg = plot.ACTIONet(ACTIONet_summary$ACTIONet2D, ACTIONet_summary$metadata$assigned_archetype, text_size = 2, use_repel = T, add_text_labels = F, point_size = 0.5, palette = as.character(pals::polychrome(31)))\n\nstoreFigure(gg, name = \"ACTIONet_archetypes_annotated_no_labels\", extension = \"png\", figures.path = figures.path, width = 8, height = 6)\n\n```\n\n### Dataset\n```{r}\ngg = plot.ACTIONet(ACTIONet_summary$ACTIONet2D, ACTIONet_summary$metadata$dataset, text_size = 2, use_repel = T, add_text_labels = F, point_size = 0.5, palette = c(\"#f1a340\", \"#998ec3\"))\n\n\nstoreFigure(gg, name = \"ACTIONet_datasets_annotated_no_labels\", extension = \"png\", figures.path = figures.path, width = 8, height = 6)\n\n```\n\n\n## Plot ACTIONet plots per dataset\n### McLean dataset\n```{r}\nmask = ACTIONet_summary$metadata$dataset == \"McLean\"\nDS1.coors = ACTIONet_summary$ACTIONet2D[mask, ]\nDS1.labels = ACTIONet_summary$metadata$Labels[mask]\n\ngg = plot.ACTIONet(DS1.coors, DS1.labels, palette = colors, text_size = 2, use_repel = T)\n\nstoreFigure(gg, name = \"ACTIONet_annotated_DS1\", extension = \"png\", figures.path = figures.path, width = 8, height = 6)\n\n```\n\n\n### MtSinai dataset\n```{r}\nmask = ACTIONet_summary$metadata$dataset == \"MtSinai\"\nDS2.coors = ACTIONet_summary$ACTIONet2D[mask, ]\nDS2.labels = ACTIONet_summary$metadata$Labels[mask]\n\ngg = plot.ACTIONet(DS1.coors, DS1.labels, palette = colors, text_size = 2, use_repel = T)\n\nstoreFigure(gg, name = \"ACTIONet_annotated_DS2\", extension = \"png\", figures.path = figures.path, width = 8, height = 6)\n\n```\n\n\n# Plot cell type fraction stats\n## Identify and filter outlier samples (based on the % of Ex cells)\nIn total, 5 samples are filtered, all of which are SZ (SZ33, SZ24, SZ29, SZ3, and SZ15)\n\n```{r}\nrequire(ggpubr)\n\nncells = apply(table(ACTIONet_summary$metadata$Labels, ACTIONet_summary$metadata$Individual), 2, as.numeric)\nrownames(ncells) = levels(ACTIONet_summary$metadata$Labels)\n\ncs = Matrix::colSums(ncells)\nncells.freq = 100*scale(ncells, center = F, scale = cs)\nEx.perc = (fast_column_sums(ncells.freq[grepl(\"^Ex\", rownames(ncells.freq)), ]))\n\ndf = data.frame(sample = colnames(ncells), perc = Ex.perc)\ngg = ggdensity(df, x = \"perc\", fill = \"lightgray\",\n add = \"mean\", rug = TRUE) + xlim(c(0, 100))\n\nstoreFigure(gg, name = \"Ex_perc_density\", extension = \"png\", figures.path = figures.path, width = 8, height = 6)\n\nncells.freq = ncells.freq[, order(Ex.perc, decreasing = T)]\nEx.perc = (fast_column_sums(ncells.freq[grepl(\"^Ex\", rownames(ncells.freq)) & !grepl(\"^Ex-NRGN\", rownames(ncells.freq)), ]))\n\nmask = (Ex.perc >= 10) & (Ex.perc <= 80) \nfiltered.samples = colnames(ncells.freq)[which(!mask)]\nncells.freq = ncells.freq[, mask]\n\n\n```\n\n\n## Plot cell type fractions for the rest of samples\n```{r}\nX = ncells.freq\ndf = reshape2::melt(X)\ncolnames(df)=c(\"celltype\", \"sample\", \"freq\")\n\ndf$celltype = factor(df$celltype, names(colors))\n\ngg = ggbarplot(df, \"sample\", \"freq\",\n fill = \"celltype\", color = \"black\", palette = colors[levels(df$celltype)], xlab = \"Individual\", ylab = \"Percentage\") + theme(axis.text.x = element_text(face=\"bold\", size=8, angle=90,hjust=0.95,vjust=0.2), axis.text.y = element_text(face=\"bold\", size=12, angle=0), axis.title = element_text(face=\"bold\", size=18, angle=0))\n\nstoreFigure(gg, name = \"celltype_perc_joint\", extension = \"png\", figures.path = figures.path, width = 8, height = 6)\n\n```\n\n## Plot cell type fraction stats per phenotype\n```{r}\nn_cells = table(ACTIONet_summary$metadata$Labels, ACTIONet_summary$metadata$Individual)\n\nX.CON = apply(n_cells[, grep(\"CON\", colnames(n_cells))], 2, as.numeric)\nX.SZ = apply(n_cells[, grep(\"SZ\", colnames(n_cells))], 2, as.numeric)\nrownames(X.CON) = rownames(X.SZ) = levels(ACTIONet_summary$metadata$Labels)\n\n\nPerc = t(apply(cbind(Matrix::rowMeans(X.CON), Matrix::rowMeans(X.SZ)), 1, function(x) 100*x / sum(x)))\ncolnames(Perc) = c(\"CON\", \"SZ\")\nPerc = Perc[order(Perc[, 1] - Perc[, 2], decreasing = T), ]\n\ndf = reshape2::melt(Perc)\ncolnames(df) = c(\"Celltype\", \"Phenotype\", \"Perc\")\ndf$Celltype = factor(df$Celltype, names(colors))\n\ngg = ggbarplot(df, \"Celltype\", \"Perc\", fill = \"Phenotype\", palette = c(\"#cccccc\", \"#888888\"))+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1, colour = colors)) + xlab(\"Celltype\") + ylab(\"Percentage\")\n\nstoreFigure(gg, name = \"Celltype_perc_per_phenotype\", extension = \"png\", figures.path = figures.path, width = 8, height = 6)\n\n```\n\n\n\n# Plot gene/umi statistics\n## Per cell type\n```{r}\numis = ACTIONet_summary$metadata$umi_count\nmito.perc = ACTIONet_summary$metadata$mito_perc\ngenes = ACTIONet_summary$metadata$gene_counts\ndataset = ACTIONet_summary$metadata$dataset\nindiv = ACTIONet_summary$metadata$Individual\ncelltype = ACTIONet_summary$metadata$Labels\ndf = data.frame(celltype = celltype, umis = umis, genes = genes, mito = mito.perc, dataset = dataset, individual = indiv) \n\ndf$celltype = factor(df$celltype, names(colors))\n\n```\n\n### McLean\n```{r}\nrequire(ggpubr)\ngg = ggviolin(df[df$dataset == \"McLean\", ], \"celltype\", \"umis\", fill = \"celltype\", palette = colors,\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Celltype\") + ylab(\"UMIs\")+ theme(legend.position = \"none\")\nstoreFigure(gg, name = \"McLean_umis\", extension = \"png\", figures.path = figures.path, width = 8, height = 6)\n\n\nrequire(ggpubr)\ngg = ggviolin(df[df$dataset == \"McLean\", ], \"celltype\", \"genes\", fill = \"celltype\", palette = colors,\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Celltype\") + ylab(\"genes\")+ theme(legend.position = \"none\")\nstoreFigure(gg, name = \"McLean_genes\", extension = \"png\", figures.path = figures.path, width = 8, height = 6)\n\n\ngg = ggviolin(df[df$dataset == \"McLean\", ], \"celltype\", \"mito\", fill = \"celltype\", palette = colors,\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Celltype\") + ylab(\"mito\") + ylim(c(0, 10))+ theme(legend.position = \"none\")\nstoreFigure(gg, name = \"McLean_mito\", extension = \"png\", figures.path = figures.path, width = 8, height = 6)\n\n```\n\n### MtSinai\n```{r}\ngg = ggviolin(df[df$dataset == \"MtSinai\", ], \"celltype\", \"umis\", fill = \"celltype\", palette = colors,\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Celltype\") + ylab(\"UMIs\")+ theme(legend.position = \"none\")\nstoreFigure(gg, name = \"MtSinai_umis\", extension = \"png\", figures.path = figures.path, width = 8, height = 6)\n\n\ngg = ggviolin(df[df$dataset == \"MtSinai\", ], \"celltype\", \"genes\", fill = \"celltype\", palette = colors,\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Celltype\") + ylab(\"genes\")+ theme(legend.position = \"none\")\nstoreFigure(gg, name = \"MtSinai_genes\", extension = \"png\", figures.path = figures.path, width = 8, height = 6)\n\n\ngg = ggviolin(df[df$dataset == \"MtSinai\", ], \"celltype\", \"mito\", fill = \"celltype\", palette = colors,\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Celltype\") + ylab(\"mito\") + ylim(c(0, 10))+ theme(legend.position = \"none\")\nstoreFigure(gg, name = \"MtSinai_mito\", extension = \"png\", figures.path = figures.path, width = 8, height = 6)\n\n\n```\n\n## Per sample\n```{r}\numis.per.ind = split(ACTIONet_summary$metadata$umi_count, ACTIONet_summary$metadata$Individual)\nmean.umis = sapply(umis.per.ind, mean)\n\ndf$individual = factor(as.character(df$individual), names(mean.umis)[order(mean.umis, decreasing = T)])\n\n```\n\n### McLean\n```{r}\nrequire(ggpubr)\ngg = ggviolin(df[df$dataset == \"McLean\", ], \"individual\", \"umis\", fill = \"individual\",\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"individual\") + ylab(\"UMIs\")+ theme(legend.position = \"none\")\nstoreFigure(gg, name = \"McLean_umis_per_sample\", extension = \"png\", figures.path = figures.path, width = 11, height = 6)\n\n\nrequire(ggpubr)\ngg = ggviolin(df[df$dataset == \"McLean\", ], \"individual\", \"genes\", fill = \"individual\",\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"individual\") + ylab(\"genes\")+ theme(legend.position = \"none\")\nstoreFigure(gg, name = \"McLean_genes_per_sample\", extension = \"png\", figures.path = figures.path, width = 11, height = 6)\n\n\ngg = ggviolin(df[df$dataset == \"McLean\", ], \"individual\", \"mito\", fill = \"individual\",\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"individual\") + ylab(\"mito\") + ylim(c(0, 10))+ theme(legend.position = \"none\")\nstoreFigure(gg, name = \"McLean_mito_per_sample\", extension = \"png\", figures.path = figures.path, width = 11, height = 6)\n\n```\n\n### MtSinai\n```{r}\ngg = ggviolin(df[df$dataset == \"MtSinai\", ], \"individual\", \"umis\", fill = \"individual\",\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"individual\") + ylab(\"UMIs\")+ theme(legend.position = \"none\")\nstoreFigure(gg, name = \"MtSinai_umis_per_sample\", extension = \"png\", figures.path = figures.path, width = 18, height = 6)\n\n\ngg = ggviolin(df[df$dataset == \"MtSinai\", ], \"individual\", \"genes\", fill = \"individual\",\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"individual\") + ylab(\"genes\")+ theme(legend.position = \"none\")\nstoreFigure(gg, name = \"MtSinai_genes_per_sample\", extension = \"png\", figures.path = figures.path, width = 18, height = 6)\n\n\ngg = ggviolin(df[df$dataset == \"MtSinai\", ], \"individual\", \"mito\", fill = \"individual\",\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"individual\") + ylab(\"mito\") + ylim(c(0, 10))+ theme(legend.position = \"none\")\nstoreFigure(gg, name = \"MtSinai_mito_per_sample\", extension = \"png\", figures.path = figures.path, width = 18, height = 6)\n\n\n```\n\n\n\n\n\n\n\n# Plot mappings of cell type annotations to other annotations\n## Load markers\n```{r}\ndata(\"curatedMarkers_human\")\nLayer.markers = loadInputDataset(\"Maynard_layer_marker\", \"rds\")\nLayer.markers = Layer.markers[c(2:7, 1)]\nVelmeshev.markers = loadInputDataset(\"Velmeshev\", \"tsv\")\nVelmeshev.markers = split(Velmeshev.markers$`Gene name`, Velmeshev.markers$`Cell type`)\nMohammadi.markers = curatedMarkers_human$Brain$PFC$Mohammadi2020$marker.genes\n\ncelltype.gene.spec = loadDataset(\"celltype_gene_specificity\")\n\nrdbu_fun = circlize::colorRamp2(c(-3, -1, 0, 1, 3), rev(pals::brewer.rdbu(9)[seq(1, 9, by = 2)]))\n\n```\n\n## Annotate\n### Layers (Maynard et al., 2021)\n```{r}\nX = as(do.call(cbind, lapply(Layer.markers, function(gs) as.numeric(rownames(celltype.gene.spec) %in% gs))), \"dgCMatrix\")\nrownames(X) = rownames(celltype.gene.spec)\nLayer.annot = assess.geneset.enrichment.from.scores(celltype.gene.spec, X)\n\nZ = scale(t(Layer.annot$logPvals))\nrownames(Z) = colnames(celltype.gene.spec)\ncolnames(Z) = c(paste(\"L\", c(1:6), sep = \"\"), \"WM\")\n\nht = Heatmap(Z, cluster_rows = F, cluster_columns = F, rect_gp = gpar(col = \"black\"), row_names_side = \"left\", row_names_gp = gpar(col = colors), col = rdbu_fun, name = \"Layer\", column_title = \"Layer (Maynard et al.)\")\n\nstoreFigure(ht, name = \"Layer_annotation_Maynard\", extension = \"pdf\", figures.path = figures.path, width = 4, height = 8)\n\n\n```\n\n### Cell types (Mohammadi et al., 2019)\n```{r}\nX = as(do.call(cbind, lapply(curatedMarkers_human$Brain$PFC$Mohammadi2020$marker.genes, function(gs) as.numeric(rownames(celltype.gene.spec) %in% gs))), \"dgCMatrix\")\nrownames(X) = rownames(celltype.gene.spec)\nCelltype.annot = assess.geneset.enrichment.from.scores(celltype.gene.spec, X)\n\nZ = scale(t(Celltype.annot$logPvals))\nrownames(Z) = colnames(celltype.gene.spec)\n\nM = as(t(MWM_hungarian(t(Celltype.annot$logPvals))), \"dgTMatrix\")\n\nht = Heatmap(Z[, M@i+1], cluster_rows = F, cluster_columns = F, rect_gp = gpar(col = \"black\"), row_names_side = \"left\", row_names_gp = gpar(col = colors), col = rdbu_fun, name = \"Celltypes\", column_title = \"Celltypes (Mohammadi et al.)\")\n\nstoreFigure(ht, name = \"celltype_annotation_mohammadi_markers\", extension = \"pdf\", figures.path = figures.path, width = 6, height = 8)\n\n```\n\n### Cell types (Velmeshev et al., 2019)\n```{r}\nX = as(do.call(cbind, lapply(curatedMarkers_human$Brain$PFC$Velmeshev2019$marker.genes, function(gs) as.numeric(rownames(celltype.gene.spec) %in% gs))), \"dgCMatrix\")\nrownames(X) = rownames(celltype.gene.spec)\nCelltype.annot = assess.geneset.enrichment.from.scores(celltype.gene.spec, X)\n\n\nZ = scale(t(Celltype.annot$logPvals))\nrownames(Z) = colnames(celltype.gene.spec)\n\nM = as(t(MWM_hungarian(t(Celltype.annot$logPvals))), \"dgTMatrix\")\n\n\nht = Heatmap(Z[, M@i+1], cluster_rows = F, cluster_columns = F, rect_gp = gpar(col = \"black\"), row_names_side = \"left\", row_names_gp = gpar(col = colors), col = rdbu_fun, name = \"Celltypes\", column_title = \"Celltypes (Velmeshev et al.)\")\n\nstoreFigure(ht, name = \"celltype_annotation_velmeshev_markers\", extension = \"pdf\", figures.path = figures.path, width = 6, height = 8)\n\n```\n### Cell types (Mathys et al., 2019)\n```{r}\nX = as(do.call(cbind, lapply(curatedMarkers_human$Brain$PFC$MathysDavila2019$marker.genes, function(gs) as.numeric(rownames(celltype.gene.spec) %in% gs))), \"dgCMatrix\")\nrownames(X) = rownames(celltype.gene.spec)\nCelltype.annot = assess.geneset.enrichment.from.scores(celltype.gene.spec, X)\n\n\n\nZ = scale(t(Celltype.annot$logPvals))\nrownames(Z) = colnames(celltype.gene.spec)\n\n\nM = as(t(MWM_hungarian(t(Celltype.annot$logPvals))), \"dgTMatrix\")\n\nht = Heatmap(Z[, M@i+1], cluster_rows = F, cluster_columns = F, rect_gp = gpar(col = \"black\"), row_names_side = \"left\", row_names_gp = gpar(col = colors), col = rdbu_fun, name = \"Celltypes\", column_title = \"Celltypes (Mathys and Davilla et al.)\")\n\nstoreFigure(ht, name = \"celltype_annotation_mathys_markers\", extension = \"pdf\", figures.path = figures.path, width = 10, height = 8)\n\n```\n\n## Bulk Layers (He et al., 2017)\n```{r}\nX = as(do.call(cbind, lapply(curatedMarkers_human$Brain$Layers$marker.genes, function(gs) as.numeric(rownames(celltype.gene.spec) %in% gs))), \"dgCMatrix\")\nrownames(X) = rownames(celltype.gene.spec)\nCelltype.annot = assess.geneset.enrichment.from.scores(celltype.gene.spec, X)\n\n\n\nZ = scale(t(Celltype.annot$logPvals))\nrownames(Z) = colnames(celltype.gene.spec)\n\nht = Heatmap(Z, cluster_rows = F, cluster_columns = F, rect_gp = gpar(col = \"black\"), row_names_side = \"left\", row_names_gp = gpar(col = colors), col = rdbu_fun, name = \"Layers\", column_title = \"Layers (He et al.)\")\n\nstoreFigure(ht, name = \"Layer_annotation_He_markers\", extension = \"pdf\", figures.path = figures.path, width = 4, height = 8)\n\n```\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6070707440376282, "alphanum_fraction": 0.6340187191963196, "avg_line_length": 35.438438415527344, "blob_id": "329ffd2473b77d39aff07ebbc6200c3fd3e5baa0", "content_id": "936184a6dc09eea587c2cf91ba3e878c0435642c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 24269, "license_type": "no_license", "max_line_length": 421, "num_lines": 666, "path": "/old/CellStates_A11A29.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"Fig3: H-MAGMA analysis\"\noutput: html_notebook\n---\n# Setup\n```{r include=FALSE}\nlibrary(org.Hs.eg.db)\nrequire(ACTIONet)\nrequire(stringr)\nrequire(ComplexHeatmap)\n\n\nresults.path = \"~/results\"\ninput.path = \"~/results/input\"\ndataset.path = \"~/results/datasets\"\ntables.path = \"~/results/tables\"\nfigures.path = \"~/results/figures\"\n\n\n```\n\n## Enrichment function\n```{r}\nassess.genesets <-function (arch.gs, terms.gs, N, min.pval = 1e-100, correct = \"none\"){\n shared = t(sapply(terms.gs, function(gs1) {\n sapply(arch.gs, function(gs2) {\n nn = intersect(gs1, gs2)\n })\n }))\n colnames(shared) = names(arch.gs)\n GS.sizes = sapply(terms.gs, length)\n logPvals.out = sapply(1:ncol(shared), function(i) {\n gg = shared[, i]\n x = as.numeric(sapply(gg, length))\n n.sample = length(arch.gs[[i]])\n n.success = as.numeric(GS.sizes)\n v = rep(1, length(x))\n min.overlap = n.success * n.sample/N\n idx = which(x >= min.overlap)\n if (length(idx) == 0) \n return(v)\n v[idx] = (phyper(x[idx]-1, n.sample, N-n.sample, n.success[idx], lower.tail = F))\n # v[idx] = HGT_tail(population.size = N, success.count = n.success[idx], \n # sample.size = n.sample, observed.success = x[idx])\n return(v)\n })\n if(correct == \"global\") {\n logPvals.out = matrix(p.adjust(logPvals.out, \"fdr\"), nrow = nrow(logPvals.out))\n } else if(correct == \"local\") {\n logPvals.out = apply(logPvals.out, 2, function(x) p.adjust(x, \"fdr\"))\n }\n rownames(logPvals.out) = names(terms.gs)\n colnames(logPvals.out) = names(arch.gs)\n return(-log10(Matrix::t(logPvals.out)))\n}\n```\n\n# Load primary datasets\n```{r, eval = T}\nACTIONet_summary = readr::read_rds(file.path(dataset.path, \"ACTIONet_summary_filtered_individuals.rds\"))\npb.logcounts = readr::read_rds(file.path(dataset.path, \"PB_mean_logcounts_final.RDS\"))\n\ncolor.df = readRDS(file.path(dataset.path, \"celltype_colors.rds\"))\ncolors = color.df$color\nnames(colors) = color.df$celltype\n\n```\n\n\n# Load DE results\n```{r, eval = T}\nresDE = readr::read_rds(file.path(dataset.path, \"Cohort_specific_DE_results.rds\"))\nfiltered.tables = readr::read_rds(file.path(dataset.path, \"Cohort_specific_DE_results_filtered.rds\"))\ncombined.analysis.tables = readr::read_rds(file.path(dataset.path, \"meta_analysis_results.rds\"))\n\nDE.new = readRDS(file.path(dataset.path, \"DE_genes_pseudobulk.rds\"))\nUp.genes = DE.new$Up.genes\nDown.genes = DE.new$Down.genes\nDE.sc = DE.new$DE.sc\n\n```\n\n\n```{r}\nassess.geneset.enrichment.from.archetypes <- function (ace, associations, min.counts = 0, specificity.slot = \"unified_feature_specificity\") \n{\n if(is.matrix(ace) | is.sparseMatrix(ace)) {\n scores = as.matrix(ace)\n } else {\n scores = rowMaps(ace)[[specificity.slot]]\n }\n if (max(scores) > 100) {\n scores = log1p(scores)\n }\n if (is.list(associations)) {\n associations = sapply(associations, function(gs) as.numeric(rownames(scores) %in% \n gs))\n rownames(associations) = rownames(scores)\n }\n common.features = intersect(rownames(associations), rownames(scores))\n rows = match(common.features, rownames(associations))\n associations = as(associations[rows, ], \"dgCMatrix\")\n scores = scores[common.features, ]\n enrichment.out = assess_enrichment(scores, associations)\n rownames(enrichment.out$logPvals) = colnames(associations)\n rownames(enrichment.out$thresholds) = colnames(associations)\n enrichment.out$scores = scores\n return(enrichment.out)\n}\n\nannotate.archetypes.using.markers <- function (ace, markers, features_use = NULL, significance_slot = \"unified_feature_specificity\") \n{\n features_use = ACTIONet:::.preprocess_annotation_features(ace, features_use)\n marker_mat = ACTIONet:::.preprocess_annotation_markers(markers, features_use)\n marker_stats = Matrix::t(assess.geneset.enrichment.from.archetypes(ace, \n marker_mat, specificity.slot = significance_slot)$logPvals)\n colnames(marker_stats) = colnames(marker_mat)\n marker_stats[!is.finite(marker_stats)] = 0\n annots = colnames(marker_mat)[apply(marker_stats, 1, which.max)]\n conf = apply(marker_stats, 1, max)\n out = list(Label = annots, Confidence = conf, Enrichment = marker_stats)\n return(out)\n}\n```\n\n\n\n\n\n\n## Celltype enrichment \n```{r}\nLabels = as.character(ACTIONet_summary$metadata$Labels)\n\nLabels[grep(\"^In\", Labels)] = \"In\"\nLabels[grep(\"^Ex\", Labels)] = \"Ex\"\nLabels[!grepl(\"^Ex|^In\", Labels)] = \"Glial\"\n\n# Arch.vs.celltype.df = data.frame(A7 = ACTIONet_summary$H_unified[, 7], A11 = ACTIONet_summary$H_unified[, 11], A17 = ACTIONet_summary$H_unified[, 17], A29 = ACTIONet_summary$H_unified[, 29], Celltype = Labels)\n# \nArch.vs.celltype.df = data.frame(A11 = ACTIONet_summary$H_unified[, 11], A29 = ACTIONet_summary$H_unified[, 29], Celltype = Labels)\n\nArch.vs.celltype.df = Arch.vs.celltype.df[(Arch.vs.celltype.df$Celltype != \"Glial\") & (apply(cbind(ACTIONet_summary$H_unified[, 11], ACTIONet_summary$H_unified[, 29]), 1, max) > 0.5), ]\n\n\n\n# \n# df = reshape2::melt(Arch.vs.celltype.df)\n# colnames(df) = c(\"Celltype\", \"Archetype\", \"Score\")\n# \n# ggviolin(df, \"Archetype\", \"Score\", fill = \"Celltype\",\n# palette = c(\"#4daf4a\", \"#e41a1c\"),\n# add = \"boxplot\", add.params = list(fill = \"white\"))\n\n\n\nrequire(ggstatsplot)\ngg = ggstatsplot::ggbetweenstats(\n data = Arch.vs.celltype.df,\n x = Celltype,\n y = A11,\n xlab = \"Celltype\",\n ylab = \"A11\",\n pairwise.display = \"significant\", # display only significant pairwise comparisons\n p.adjust.method = \"fdr\", # adjust p-values for multiple tests using this method\n ggtheme = ggthemes::theme_tufte(),\n ) + scale_color_manual(values = c(\"#4daf4a\", \"#e41a1c\"))\n\n\npdf(file.path(figures.path, \"A11_vs_celltype.pdf\"))\nplot(gg)\ndev.off()\n\ngg = ggstatsplot::ggbetweenstats(\n data = Arch.vs.celltype.df,\n x = Celltype,\n y = A29,\n xlab = \"Celltype\",\n ylab = \"A29\",\n pairwise.display = \"significant\", # display only significant pairwise comparisons\n p.adjust.method = \"fdr\", # adjust p-values for multiple tests using this method\n ggtheme = ggthemes::theme_tufte(),\n ) + scale_color_manual(values = c(\"#4daf4a\", \"#e41a1c\"))\n\n\npdf(file.path(figures.path, \"A29_vs_celltype.pdf\"))\nplot(gg)\ndev.off()\n\n```\n# Co-association of A11/A29\n```{r}\nsample.df = data.frame(Label = pb.logcounts$ID, Phenotype = pb.logcounts$Phenotype, A11 = scale(pb.logcounts$A11.signature), A29 = scale(pb.logcounts$A29.signature))\n# sample.df = reshape2::melt(sample.df)\n\n# colnames(sample.df)[[3]] = \"Archetype\"\n \n\ngg = ggscatter(sample.df, x = \"A11\", y = \"A29\", \n color = \"Phenotype\",\n palette = c(\"CON\" = \"lightgray\", \"SZ\" = \"red\"),\n label = \"Label\", repel = TRUE,\n add = \"reg.line\", # Add regression line\n conf.int = TRUE, # Add confidence interval\n add.params = list(color = \"blue\",\n fill = \"lightgray\")\n )+ stat_cor(method = \"pearson\", label.x = -0.8)# +xlim(c(-2, 2)) + ylim(c(-2, 2))\n\npdf(file.path(figures.path, \"A11_vs_A29_sample_assignments.pdf\"), width = 6, height = 6)\nprint(gg)\ndev.off()\n\noutlier.samples = c(\"SZ7\", \"SZ31\", \"SZ44\", \"SZ33\")\n\n```\n\n\n# Compute pattern-specificity\n```{r}\nace = readr::read_rds(\"~/results/ACTIONet_reunified.rds\")\n\n```\n\n```{r}\n\nmask = grepl(\"^Ex\", ace$Labels) & !(grepl(\"^NRGN\", ace$Labels))\nS.Ex = logcounts(ace)[, mask]\nsubH = t(as.matrix(colMaps(ace)$H_unified[mask, c(7, 11, 17, 29)]))\n\narch.spec.Ex = compute_archetype_feature_specificity(S.Ex, H = subH)\n\nU.Ex = arch.spec.Ex$upper_significance\nrownames(U.Ex) = rownames(ace)\ncolnames(U.Ex) = paste(\"A\", c(7, 11, 17, 29), sep = \"\")\nreadr::write_rds(U.Ex, file.path(dataset.path, \"Cellstates_vs_Ex_gene_spec.rds\"))\n\n\n\nmask = grepl(\"^In\", ace$Labels)\nS.In = logcounts(ace)[, mask]\nsubH = t(as.matrix(colMaps(ace)$H_unified[mask, c(7, 11, 17, 29)]))\n\narch.spec.In = compute_archetype_feature_specificity(S.In, H = subH)\n\nU.In = arch.spec.In$upper_significance\nrownames(U.In) = rownames(ace)\ncolnames(U.In) = paste(\"A\", c(7, 11, 17, 29), sep = \"\")\nreadr::write_rds(U.In, file.path(dataset.path, \"Cellstates_vs_In_gene_spec.rds\"))\n\n\n\n\nmask = grepl(\"^In|^Ex\", ace$Labels)\nS.Neuro = logcounts(ace)[, mask]\nsubH = t(as.matrix(colMaps(ace)$H_unified[mask, c(7, 11, 17, 29)]))\n\narch.spec.Neuro = compute_archetype_feature_specificity(S.Neuro, H = subH)\n\nU.Neuro = arch.spec.Neuro$upper_significance\nrownames(U.Neuro) = rownames(ace)\ncolnames(U.Neuro) = paste(\"A\", c(7, 11, 17, 29), sep = \"\")\nreadr::write_rds(U.Neuro, file.path(dataset.path, \"Cellstates_vs_Neuro_gene_spec.rds\"))\n\n\n\nU = cbind(U.Neuro, U.Ex, U.In)\ncolnames(U) = c(paste(\"Neu_A\", c(7, 11, 17, 29), sep = \"\"), paste(\"Ex_A\", c(7, 11, 17, 29), sep = \"\"), paste(\"In_A\", c(7, 11, 17, 29), sep = \"\"))\nidx = grep(\"^MT-|^RPL|^RPS\", rownames(U))\nU = U[-idx, ]\n\nreadr::write_rds(U, file.path(dataset.path, \"Cellstates_vs_InEx_gene_spec_filtered.rds\"))\n\n\n```\n\n```{r}\nU=readr::read_rds(file.path(dataset.path, \"Cellstates_vs_InEx_gene_spec_filtered.rds\"))\nwrite.table(U, file.path(tables.path, \"cellstates_DE.tsv\"), sep = \"\\t\", row.names = T, col.names = T, quote = F)\n\ncelltype.spec=readr::read_rds(\"~/results/datasets/celltype_gene_specificity.rds\")\nwrite.table(celltype.spec, file.path(tables.path, \"celltype_gene_specificity.tsv\"), sep = \"\\t\", row.names = T, col.names = T, quote = F)\n\narch.spec=readr::read_rds(\"~/results/datasets/archetype_gene_specificity.rds\")\nwrite.table(arch.spec, file.path(tables.path, \"archetype_gene_specificity.tsv\"), sep = \"\\t\", row.names = T, col.names = T, quote = F)\n\n\n\n\n```\n\n```{r}\ndata(\"gProfilerDB_human\")\ncellstate.enrichment = assess.geneset.enrichment.from.scores(U, gProfilerDB_human$SYMBOL$`GO:BP`)$logPvals\ncolnames(cellstate.enrichment) = colnames(U)\n\n\nreadr::write_rds(cellstate.enrichment, file.path(dataset.path, \"Cellstates_vs_InEx_gene_spec_filtered_enrichment.rds\"))\n\npdf(file.path(figures.path, \"Cellstate_enrichment.pdf\"), height = 9)\nplot.top.k.features(cellstate.enrichment, 5)\ndev.off()\n\npdf(file.path(figures.path, \"Cellstate_enrichment_doubleNorm.pdf\"), height = 9)\nplot.top.k.features(doubleNorm(cellstate.enrichment), 5)\ndev.off()\n\n\nnerurodev.gene.counts = sort(table(unlist(apply(gProfilerDB_human$SYMBOL$`GO:BP`[, c(\"generation of neurons\", \"neurogenesis\", \"neuron differentiation\", \"nervous system development\")], 2, function(x) rownames(gProfilerDB_human$SYMBOL$`GO:BP`)[x > 0]))), decreasing = T)\n\nneurodev.genes = sort(unique(names(nerurodev.gene.counts)[nerurodev.gene.counts == 4]))\n\ngsea.results = apply(U, 2, function(x) {\n fgsea.out = fgsea(list(nerurodev = neurodev.genes), x)\n})\n\ngene.counts = sort(table(unlist(lapply(gsea.results[c(2, 4, 6, 8)], function(x) x$leadingEdge))), decreasing = T)\n\nselected.genes = sort(unique(names(gene.counts)[gene.counts == 4]))\n\n# [1] \"ABI2\" \"ACAP3\" \"ACSL4\" \"ACTB\" \"ADGRB1\" \"ADGRB3\" \"ADNP\" \"AHI1\" \"ALCAM\" \"ANK3\" \"APBB2\" \n# [12] \"APP\" \"ARHGAP35\" \"ARHGAP44\" \"ARID1B\" \"ASAP1\" \"ATL1\" \"ATP2B2\" \"ATP8A2\" \"AUTS2\" \"BEND6\" \"BMPR2\" \n# [23] \"BRAF\" \"BRINP2\" \"BRINP3\" \"BSG\" \"BTBD8\" \"CACNA1A\" \"CAMK1D\" \"CAMK2B\" \"CAMSAP2\" \"CBFA2T2\" \"CCDC88A\" \n# [34] \"CDH2\" \"CDKL5\" \"CEND1\" \"CEP290\" \"CHD5\" \"CHL1\" \"CHN1\" \"CNTN1\" \"CNTN4\" \"CNTNAP2\" \"CPEB3\" \n# [45] \"CSMD3\" \"CSNK1E\" \"CTNNA2\" \"CTNND2\" \"CUX1\" \"CUX2\" \"CYFIP2\" \"DAB1\" \"DCC\" \"DCLK1\" \"DCLK2\" \n# [56] \"DHFR\" \"DLG4\" \"DMD\" \"DNM3\" \"DNMT3A\" \"DOK6\" \"DSCAML1\" \"DYNC2H1\" \"EFNA5\" \"ELAVL4\" \"EPB41L3\" \n# [67] \"EPHA6\" \"ERBB4\" \"EVL\" \"EXT1\" \"FAIM2\" \"FARP1\" \"FLRT2\" \"FSTL4\" \"GABRB1\" \"GABRB2\" \"GABRB3\" \n# [78] \"GAK\" \"GDI1\" \"GOLGA4\" \"GPM6A\" \"GRIN1\" \"GRIP1\" \"GSK3B\" \"HCN1\" \"HECW1\" \"HECW2\" \"HERC1\" \n# [89] \"HMGB1\" \"HPRT1\" \"HSP90AA1\" \"HSP90AB1\" \"IL1RAPL1\" \"INPP5F\" \"ITSN1\" \"JAK2\" \"KALRN\" \"KDM4C\" \"KIF5A\" \n# [100] \"KIF5C\" \"KIRREL3\" \"KNDC1\" \"LINGO1\" \"LRRC4C\" \"MACF1\" \"MAGI2\" \"MAP1A\" \"MAP1B\" \"MAP2\" \"MAP3K13\" \n# [111] \"MAPK1\" \"MAPK8IP2\" \"MAPK8IP3\" \"MAPT\" \"MARK1\" \"MDGA2\" \"MEF2A\" \"MEF2C\" \"MIB1\" \"MTR\" \"MYCBP2\" \n# [122] \"MYH10\" \"MYO9A\" \"MYT1L\" \"NCAM1\" \"NCDN\" \"NCKAP1\" \"NCOA1\" \"NDRG4\" \"NEFM\" \"NEGR1\" \"NFE2L2\" \n# [133] \"NIN\" \"NLGN1\" \"NLGN4X\" \"NRCAM\" \"NRXN1\" \"NRXN3\" \"NTM\" \"NTRK2\" \"NTRK3\" \"OPA1\" \"OPCML\" \n# [144] \"PAK3\" \"PBX1\" \"PCDH15\" \"PHACTR1\" \"PIK3CA\" \"PIK3CB\" \"PLXNA4\" \"PPP1R9A\" \"PPP3CA\" \"PRKCA\" \"PRKD1\" \n# [155] \"PRKG1\" \"PTPN9\" \"PTPRD\" \"PTPRG\" \"PTPRO\" \"PTPRS\" \"RAB10\" \"RAP1GAP2\" \"RAPGEF2\" \"RARB\" \"RB1\" \n# [166] \"RBFOX2\" \"RERE\" \"RIMS1\" \"RIMS2\" \"RNF157\" \"ROBO1\" \"ROBO2\" \"RORA\" \"RTN4\" \"RTN4RL1\" \"RUFY3\" \n# [177] \"SARM1\" \"SCLT1\" \"SERPINI1\" \"SH3GL2\" \"SH3KBP1\" \"SHANK2\" \"SHTN1\" \"SIPA1L1\" \"SLC4A10\" \"SLITRK5\" \"SNAP25\" \n# [188] \"SNPH\" \"SOS1\" \"SPOCK1\" \"SPTAN1\" \"SPTBN1\" \"SPTBN4\" \"SRCIN1\" \"SRRM4\" \"STMN2\" \"STXBP1\" \"SUFU\" \n# [199] \"SYN1\" \"SYT1\" \"TCF12\" \"TCF4\" \"TENM2\" \"TENM3\" \"TENM4\" \"THOC2\" \"THRB\" \"TIAM1\" \"TMEFF2\" \n# [210] \"TMEM108\" \"TNIK\" \"TNR\" \"TRAK2\" \"TRIO\" \"TRIP11\" \"UCHL1\" \"UNC5C\" \"UNC5D\" \"USP33\" \"WDPCP\" \n# [221] \"WNK1\" \"YWHAG\" \"ZC4H2\" \"ZEB1\" \"ZEB2\" \"ZMYND8\" \"ZNF804A\" \"ZSWIM5\" \n\n\n```\n\n\n```{r}\ncc = cor(U, -DE.sc[-idx, ])\ncc[cc < 0.1] = 0\nHeatmap(cc)\n\n```\n\n\n```{r}\n\nmask = ACTIONet_summary$metadata$assigned_archetype %in% c(7, 11, 17, 29)\n\ncell.df = data.frame(Phenotype = ACTIONet_summary$metadata$Phenotype[mask], Celltype = ACTIONet_summary$metadata$Labels[mask], A7 = scale(ACTIONet_summary$H_unified[mask, 7]), A11 = scale(ACTIONet_summary$H_unified[mask, 11]), A17 = scale(ACTIONet_summary$H_unified[mask, 17]), A29 = scale(ACTIONet_summary$H_unified[mask, 29]))\n\n# cell.df = cell.df[grepl(\"^In|^Ex\", cell.df$Celltype)&!grepl(\"NRGN\", cell.df$Celltype), ]\ncell.df = cell.df[grepl(\"^In|^Ex\", cell.df$Celltype), ]\n\ncell.df2 = reshape2::melt(cell.df)\ncolnames(cell.df2)[[3]] = \"Archetype\"\ncell.df2$Celltype = factor(cell.df2$Celltype, names(colors))\n\ngg = ggbarplot(cell.df2, \"Archetype\", \"value\", fill = \"Celltype\", palette = colors, position = position_dodge(), add = \"mean_se\") + ylab(\"Archetype score (scaled)\")\n\npdf(file.path(figures.path, \"Cellstates_vs_celltypes_neuro_plusNRGN.pdf\"), width = 12, height = 5)\nplot(gg)\ndev.off()\n\n\n```\n\n\n```{r}\n# X = assays(pb.logcounts)[[\"Ex-L45_MET\"]][selected.genes, ]\n# \n# X.orth = orthoProject(X, Matrix::rowMeans(X))\n# X.orth[is.na(X.orth)] = 0\n# Heatmap(X.orth)\n\n\noverlap.genes = lapply(DE.new$Down.genes, function(gs) intersect(selected.genes, gs))\nx = sort(table(unlist(overlap.genes)), decreasing = T)\nx[1:30]\n\n```\n\n\n```{r}\nbulk = readr::read_rds(\"~/results/input/MPP_bulk_expression_SZandCON.rds\")\nbulk.profile = assays(bulk)$voom\nbulk.profile.orth = orthoProject(bulk.profile, Matrix::rowMeans(bulk.profile))\n\n```\n\n\n```{r}\nidx = grep(\"^MT-|^RPL|^RPS|^PSM|^EIF|^MRP\", rownames(U))\ncellstate.panel = log1p(U[-idx, ])\n\n\ncommon.genes = intersect(rownames(cellstate.panel), rownames(bulk.profile.orth))\n\nSZ.pred = -cor(bulk.profile.orth[common.genes, ], cellstate.panel[common.genes, ], method = \"spearman\")\nrownames(SZ.pred) = bulk$SampleID\n\nCC = cor(t(bulk.profile.orth[common.genes, ]), SZ.pred, method = \"spearman\")\nscores = cbind(exp(3*CC), exp(-3*CC))\ncolnames(scores) = c(paste(\"Up_\", colnames(CC), sep = \"\"), paste(\"Down_\", colnames(CC), sep = \"\"))\nrownames(scores) = common.genes\n\nEn = assess.geneset.enrichment.from.scores(scores, gProfilerDB_human$SYMBOL$`GO:BP`)\nlogPvals = En$logPvals\ncolnames(logPvals) = colnames(scores)\n\nplot.top.k.features((logPvals))\n\n\n\n```\n```{r}\nX = assays(pb.logcounts)[[\"Ex-L23\"]]\nX.orth = orthoProject(X, fast_row_sums(X))\nsubX = X.orth[, c(\"SZ7\", \"SZ31\", \"SZ44\", \"SZ33\")]\n\n```\n\n```{r}\n\n# bulk.profile = assays(bulk)$voom\n# bulk.profile = orthoProject(bulk.profile, Matrix::rowMeans(bulk.profile))\n\nidx = grep(\"^MT-|^RPL|^RPS\", rownames(U.Neuro))\ncellstate.panel = U.Neuro[-idx, ]\n\n\ncommon.genes = intersect(rownames(cellstate.panel), rownames(bulk.profile))\n\nSZ.pred = -cor(bulk.profile[common.genes, ], cellstate.panel[common.genes, ], method = \"spearman\")\nrownames(SZ.pred) = bulk$SampleID\n\narch.df = data.frame(Id = bulk$SampleID, Phenotype = bulk$Dx, A11 = SZ.pred[, \"A11\"], A29 = SZ.pred[, \"A29\"])\n\n\n\n\n\n\n\n\n\n```\n\n\n```{r}\nrequire(ggpubr)\nLl = c(\"SZ\", \"CON\")\narch.df = data.frame(Id = bulk$SampleID, Phenotype = bulk$Dx, A11 = SZ.pred[, \"A11\"], A29 = SZ.pred[, \"A29\"], A7 = SZ.pred[, \"A7\"], Label = \"\")\narch.df$Phenotype = factor(Ll[as.numeric(arch.df$Phenotype == \"SCZ\")+1], Ll)\n\ngg = ggscatter(arch.df, x = \"A11\", y = \"A29\", \n color = \"Phenotype\",\n palette = c(\"CON\" = \"black\", \"SZ\" = \"red\"),\n label = \"Label\", repel = TRUE,\n add = \"reg.line\", # Add regression line\n conf.int = TRUE, # Add confidence interval\n add.params = list(color = \"blue\",\n fill = \"lightgray\")\n ) + stat_cor(method = \"pearson\")# +xlim(c(-2, 2)) + ylim(c(-2, 2))\n\n# pdf(file.path(figures.path, \"Supp\", \"TPS_vs_SZTR.pdf\"), width = 6, height = 6)\nprint(gg)\n# dev.off()\n\n```\n\n\n```{r}\narch.df$pred = scale(arch.df$A29)\n# arch.df$pred = scale(runif(length(arch.df$A11)))\n\ndata = bulk.profile[common.genes, ]\n# plot(density(data[, 4]))\n# data = normalizeQuantiles(data)\nmod = model.matrix( ~0 + pred, arch.df)\nfit = lmFit(data, mod)\nfit<-eBayes(fit)\ntbl = limma::topTable(\n fit = fit,\n coef=1,\n number = Inf,\n adjust.method = \"BH\",\n sort.by = \"t\"\n)\n\ngp = gProfileR::gprofiler(query = rownames(tbl), ordered_query = T) \n\n \nrequire(EnhancedVolcano)\nEnhancedVolcano(tbl , x = \"logFC\", y = \"adj.P.Val\", lab = rownames(tbl))\n \n```\n\n```{r}\nSZ.associations = as(cbind(as.numeric(bulk$Dx == \"SCZ\"), as.numeric(bulk$Dx == \"Control\")), \"sparseMatrix\")\ncolnames(SZ.associations) = c(\"SZ\", \"CON\")\n\nscores = exp(-3*SZ.pred)\nrownames(SZ.associations) = colnames(scores) = bulk$SampleID\n\nXX = t(assess.geneset.enrichment.from.scores(t(scores), SZ.associations)$logPvals)\nrownames(XX) = colnames(panel)\n# Heatmap(XX)\n\n```\n\n```{r}\n\n\nDx = split(bulk$SampleID, bulk$Dx)\n\n# Pvals = apply(SZ.pred, 2, function(x) {\n# out = fgsea(Dx, x)\n# pvals = out$pval\n# names(pvals) = names(Dx)\n# return(pvals)\n# })\n\nl = as.numeric(bulk$Dx == \"SCZ\")\nmhg.Pvals.CON = apply(SZ.pred, 2, function(x) {\n perm = order(x, decreasing = T)\n x = l[perm]\n mhg.out = mhg::mhg_test(x, length(x), sum(x), length(x), 1, upper_bound = F, tol = 1e-300) \n return(mhg.out$pvalue)\n})\n\nmhg.Pvals.SZ = apply(SZ.pred, 2, function(x) {\n perm = order(x, decreasing = F)\n x = l[perm]\n mhg.out = mhg::mhg_test(x, length(x), sum(x), length(x), 1, upper_bound = F, tol = 1e-300) \n return(mhg.out$pvalue)\n})\n\n\nEn = -log10(matrix(p.adjust(c(mhg.Pvals.SZ, mhg.Pvals.CON), \"fdr\"), ncol = 2))\nrownames(En) = colnames(cellstate.panel)\ncolnames(En) = c(\"SZ\", \"CON\")\nEn = round(En, 2)\n\n\n\nSZ.pred\n\n# \n# x = SZ.pred[, \"A29\"]\n# perm = order(x, decreasing = F)\n# x = l[perm]\n# mhg.out = mhg::mhg_test(x, length(x), sum(x), 100, 1, upper_bound = F, tol = 1e-300) \n# plot(-log10(mhg.out$mhg))\n\n\n\n\n# SZ.associations = as(cbind(as.numeric(bulk$Dx == \"SCZ\"), as.numeric(bulk$Dx == \"Control\")), \"sparseMatrix\")\n# colnames(SZ.associations) = c(\"SZ\", \"CON\")\n# \n# scores = exp(-3*SZ.pred)\n# rownames(SZ.associations) = colnames(scores) = bulk$SampleID\n\n\n\n\n# XX = t(assess.geneset.enrichment.from.scores(t(scores), SZ.associations)$logPvals)\n# rownames(XX) = colnames(cellstate.panel)\n\n```\n\n```{r}\nUp.DE.enrichment = annotate.archetypes.using.markers(ACTIONet_summary$unified_feature_specificity, DE.new$Up.genes)\n\nY = t(Up.DE.enrichment$Enrichment)\ncolnames(Y) = paste(\"A\", 1:ncol(X), sep = \"\")\nRd.pal = circlize::colorRamp2(seq(0, quantile(Y, 0.99), length.out = 8), c(\"#ffffff\", pals::brewer.reds(7)))\n\n\nDown.DE.enrichment = annotate.archetypes.using.markers(ACTIONet_summary$unified_feature_specificity, DE.new$Down.genes)\n\nX = t(Down.DE.enrichment$Enrichment)\nBu.pal = circlize::colorRamp2(seq(0, quantile(X, 0.99), length.out = 8), c(\"#ffffff\", pals::brewer.blues(7)))\n\ncolnames(X) = paste(\"A\", 1:ncol(X), sep = \"\")\n\n# arch.perm = order(apply(rbind(X, Y), 2, mean), decreasing = T)\n# \n# Heatmap(t(Y[, arch.perm]), rect_gp = gpar(col = \"black\"), col = Rd.pal, cluster_rows = F, cluster_columns = F, column_names_gp = gpar(col = colors[rownames(Y)]), name = \"Up\", column_title = \"Up\") + Heatmap(t(X[, arch.perm]), rect_gp = gpar(col = \"black\"), col = Bu.pal, cluster_columns = F, column_names_gp = gpar(col = colors[rownames(X)]), name = \"Down\", column_title = \"Down\")\n\n# arch.perm = order(apply(rbind(X), 2, mean), decreasing = T)\narch.perm = order(apply(rbind(X, Y), 2, mean), decreasing = T)\n\npdf(file.path(figures.path, \"arch_gene_spec_vs_DE_up.pdf\"), width = 5, height = 8)\nHeatmap(t(Y[, arch.perm]), cluster_rows = F, rect_gp = gpar(col = \"black\"), col = Rd.pal, cluster_columns = F, column_names_gp = gpar(col = colors[rownames(X)]), name = \"Up\", column_title = \"Up\", row_names_side = \"left\")\ndev.off()\n\n\npdf(file.path(figures.path, \"arch_gene_spec_vs_DE_down.pdf\"), width = 5, height = 8)\nHeatmap(t(X[, arch.perm]), cluster_rows = F, rect_gp = gpar(col = \"black\"), col = Bu.pal, cluster_columns = F, column_names_gp = gpar(col = colors[rownames(X)]), name = \"Down\", column_title = \"Down\", row_names_side = \"left\")\ndev.off()\n\n```\n```{r, eval = F}\n\nDE.down.vs.arch.fgsea = apply(ACTIONet_summary$unified_feature_specificity, 2, function(x) {\n fgsea.out = fgsea(DE.new$Down.genes, x, eps = 1e-100)\n \n v = fgsea.out$pval\n names(v) = fgsea.out$pathway\n return(v)\n})\n\nDE.down.vs.arch.fgsea.enrichment = -log10(DE.down.vs.arch.fgsea)\nHeatmap(DE.down.vs.arch.fgsea.enrichment)\n\n```\n\n## Enrichment\n```{r}\narchs = c(29,11, 17, 7)\n\narch.enrichment.phenotype = presto::wilcoxauc(t(ACTIONet_summary$H_unified), ACTIONet_summary$metadata$Phenotype)\narch.enrichment.phenotype = matrix(arch.enrichment.phenotype$auc-0.5, nrow=ncol(ACTIONet_summary$H_unified))\nrownames(arch.enrichment.phenotype) = paste(\"A\", 1:nrow(arch.enrichment.phenotype), sep = \"\")\ncolnames(arch.enrichment.phenotype) = levels(ACTIONet_summary$metadata$Phenotype)\n\narch.enrichment.ind = presto::wilcoxauc(t(ACTIONet_summary$H_unified), ACTIONet_summary$metadata$Individual)\narch.enrichment.ind = matrix(arch.enrichment.ind$auc-0.5, nrow=ncol(ACTIONet_summary$H_unified))\nrownames(arch.enrichment.ind) = paste(\"A\", 1:nrow(arch.enrichment.ind), sep = \"\")\n\narch.enrichment.celltype = presto::wilcoxauc(t(ACTIONet_summary$H_unified), ACTIONet_summary$metadata$Labels)\nrn = unique(arch.enrichment.celltype$group)\narch.enrichment.celltype = matrix(arch.enrichment.celltype$auc-0.5, nrow=ncol(ACTIONet_summary$H_unified))\nrownames(arch.enrichment.celltype) = paste(\"A\", 1:nrow(arch.enrichment.celltype), sep = \"\")\ncolnames(arch.enrichment.celltype) = rn\n\n\nha_ct = columnAnnotation(Celltype = factor(names(DE.new$Up.genes), names(DE.new$Up.genes)), col = list(Celltype = colors[names(DE.new$Up.genes)]))\n\nxx = t(scale(t(arch.enrichment.ind[archs, ])))\ncolnames(xx) = c()\n\nyy = t(scale(t(arch.enrichment.celltype[archs, names(DE.new$Up.genes)])))\ncolnames(yy) = c()\n\nzz = as.matrix(scale(arch.enrichment.phenotype[archs, 2]))\n\nsample_perm = order(apply(xx[1:2, ], 2, max), decreasing = T)\nha_pheno = columnAnnotation(Phenotype = pb.logcounts$Phenotype[sample_perm], col = list(Phenotype = c(\"CON\" = \"gray\", \"SZ\" = \"red\")))\n\npdf(file.path(figures.path, \"Cellstate_heatmaps.pdf\"), width = 32, height = 4)\nHeatmap(zz, cluster_rows = F, row_names_side = \"left\", name = \"Pheno\", column_title = \"Pheno\", show_column_dend = F, rect_gp = gpar(col = \"black\"))+ Heatmap(yy, name = \"Celltype\", cluster_columns = F, row_names_side = \"left\", top_annotation = ha_ct, rect_gp = gpar(col = \"black\")) + Heatmap(xx[, sample_perm], cluster_rows = F, name = \"Samples\", column_title = \"Samples\", show_column_dend = F, top_annotation = ha_pheno) \ndev.off()\n\n\n```\n\n" }, { "alpha_fraction": 0.6124095916748047, "alphanum_fraction": 0.645770788192749, "avg_line_length": 28.754026412963867, "blob_id": "b143ad5c26c0f2901060d8c9622a9139d0e4d203", "content_id": "6ac3827dcf804d21a8efcbad169bedfd68eaa467", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 20323, "license_type": "no_license", "max_line_length": 474, "num_lines": 683, "path": "/old/Archetype_preliminary.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"R Notebook\"\noutput: html_notebook\n---\n\n# Setup\n```{r include=FALSE}\nrequire(ACTIONet)\nrequire(stringr)\nrequire(ComplexHeatmap)\n\n\nresults.path = \"~/results\"\ninput.path = \"~/results/input\"\ndataset.path = \"~/results/datasets\"\ntables.path = \"~/results/tables\"\nfigures.path = \"~/results/figures\"\n\n\n```\n\n## Enrichment function\n```{r}\nassess.genesets <-function (arch.gs, terms.gs, N, min.pval = 1e-100, correct = \"none\"){\n shared = t(sapply(terms.gs, function(gs1) {\n sapply(arch.gs, function(gs2) {\n nn = intersect(gs1, gs2)\n })\n }))\n colnames(shared) = names(arch.gs)\n GS.sizes = sapply(terms.gs, length)\n logPvals.out = sapply(1:ncol(shared), function(i) {\n gg = shared[, i]\n x = as.numeric(sapply(gg, length))\n n.sample = length(arch.gs[[i]])\n n.success = as.numeric(GS.sizes)\n v = rep(1, length(x))\n min.overlap = n.success * n.sample/N\n idx = which(x >= min.overlap)\n if (length(idx) == 0) \n return(v)\n v[idx] = (phyper(x[idx]-1, n.sample, N-n.sample, n.success[idx], lower.tail = F))\n # v[idx] = HGT_tail(population.size = N, success.count = n.success[idx], \n # sample.size = n.sample, observed.success = x[idx])\n return(v)\n })\n if(correct == \"global\") {\n logPvals.out = matrix(p.adjust(logPvals.out, \"fdr\"), nrow = nrow(logPvals.out))\n } else if(correct == \"local\") {\n logPvals.out = apply(logPvals.out, 2, function(x) p.adjust(x, \"fdr\"))\n }\n rownames(logPvals.out) = names(terms.gs)\n colnames(logPvals.out) = names(arch.gs)\n return(-log10(Matrix::t(logPvals.out)))\n}\n```\n\n# Load primary datasets\n```{r, eval = T}\nACTIONet_summary = readr::read_rds(file.path(dataset.path, \"ACTIONet_summary_filtered_individuals.rds\"))\npb.logcounts = readr::read_rds(file.path(dataset.path, \"PB_mean_logcounts_final.RDS\"))\n\ncolor.df = readRDS(file.path(dataset.path, \"celltype_colors.rds\"))\ncolors = color.df$color\nnames(colors) = color.df$celltype\n\n\n\npng(\"~/Liver_atlas.png\", width = 800, height = 600)\nplot.ACTIONet(ace3, ace3$Manual_Annotation)\ndev.off()\n\n\n```\n\n\n\n\n# Load DE results\n```{r, eval = T}\nresDE = readr::read_rds(file.path(dataset.path, \"Cohort_specific_DE_results.rds\"))\nfiltered.tables = readr::read_rds(file.path(dataset.path, \"Cohort_specific_DE_results_filtered.rds\"))\ncombined.analysis.tables = readr::read_rds(file.path(dataset.path, \"meta_analysis_results.rds\"))\n\nDE.new = readRDS(file.path(dataset.path, \"DE_genes_pseudobulk.rds\"))\nUp.genes = DE.new$Up.genes\nDown.genes = DE.new$Down.genes\nDE.sc = DE.new$DE.sc\n\n\n```\n\n## Annotate archetypes based on cell types\n```{r}\narch.annot = annotate.archetypes.using.labels(t(ACTIONet_summary$H_unified), ACTIONet_summary$metadata$Labels)\n\narch.labels = paste(\"A\", 1:ncol(ACTIONet_summary$H_unified), \"-\", arch.annot$Label, sep = \"\")\narch.labels[c(7, 11, 17, 29)] = paste(\"A\", c(7, 11, 17, 29), \"-\", c(\"Ex-NRGN\", \"Ex-SZ\", \"Ex-SZTR\", \"In-SZ\"), sep = \"\")\n\narch.order = c(setdiff(order(match(arch.annot$Label, names(colors))), c(11, 17, 29)), c(11, 17, 29))\n\n```\n\n## Archetypes\n```{r}\nrdbu_fun = circlize::colorRamp2(c(-3, -1, 0, 1, 3), rev(pals::brewer.rdbu(9)[seq(1, 9, by = 2)]))\nZ = scale(t(arch.annot$Enrichment[arch.order, ]))\ncolnames(Z) = arch.labels[arch.order]\n\npdf(file.path(figures.path, \"archetypes\", \"celltype_annotation_vs_archetypes_v3.pdf\"), width = 8)\nHeatmap(Z, cluster_rows = F, cluster_columns = F, rect_gp = gpar(col = \"black\"), row_names_side = \"left\", row_names_gp = gpar(col = colors), col = rdbu_fun, name = \"Archetypes\", column_title = \"Archetypes\")\ndev.off()\n\n```\n# Plot cell states\n```{r}\ncellstates = c(7, 11, 17, 29)\ncellstate.titles = c(\"Ex-NRGN\", \"Ex-SZ\", \"Ex-SZTR\", \"In-SZ\")\nsubH = ACTIONet_summary$H_unified[, cellstates]\n\nggs = lapply(1:length(cellstates), function(i) {\n gg = plot.ACTIONet.gradient(ACTIONet_summary$ACTIONet2D, subH[, i], alpha_val = 0, point_size = 0.5, grad_palette = \"magma\") + ggtitle(cellstate.titles[[i]])\n \n return(gg)\n})\n\npng(file.path(figures.path, \"archetypes\", \"ACTIONet_cellstates_noNRGN.png\"), width = 600*3, height = 600, res = 150)\ndo.call(gridExtra::grid.arrange, c(lapply(ggs[-1], ggplotify::as.grob), nrow = 1))\ndev.off()\n\npng(file.path(figures.path, \"archetypes\", \"ACTIONet_cellstates.png\"), width = 800*3, height = 600*3, res = 150)\ndo.call(gridExtra::grid.arrange, c(lapply(ggs, ggplotify::as.grob), nrow = 2))\ndev.off()\n\nsapply(1:4, function(i) {\n png(file.path(figures.path, \"archetypes\", sprintf(\"ACTIONet_cellstates_%s.png\", cellstate.titles[[i]])), width = 1600, height = 1200, res = 150)\n plot(ggs[[i]])\n dev.off()\n})\n\n```\n\n# Plot cell types\n```{r}\n# cellstats = c(11, 17, 29)\n# idx = setdiff(1:ncol(ACTIONet_summary$H_unified), cellstates)\n# subH = ACTIONet_summary$H_unified[, -cellstates]\n# Ll = ct.arch.annot$Label[-cellstates]\n# perm = order(match(Ll, names(colors)))\n# subH = subH[, perm]\n# Ll = Ll[perm]\n# idx = idx[perm]\n\n\nidx = setdiff(order(match(arch.annot$Label, names(colors))), c(11, 17, 29))\nsubH = ACTIONet_summary$H_unified[, idx]\n\n\nggs.archs.celltypes = lapply(1:ncol(subH), function(i) {\n gg = plot.ACTIONet.gradient(ACTIONet_summary$ACTIONet2D, subH[, i], alpha_val = 0, point_size = 0.5, grad_palette = \"magma\") + ggtitle(arch.labels[[arch.order[[i]]]]) + theme(plot.title = element_text(color = colors[[arch.annot$Label[arch.order[[i]]]]]))\n return(gg)\n})\n\n\npng(file.path(figures.path, \"archetypes\", \"ACTIONet_archetypes_nonstate.png\"), width = 800*7, height = 600*4, res = 150)\ndo.call(gridExtra::grid.arrange, c(lapply(ggs.archs.celltypes, ggplotify::as.grob), nrow = 4))\ndev.off()\n \n```\n\n```{r}\n# data(\"gProfilerDB_human\")\n\nX = gProfilerDB_human$SYMBOL$`GO:BP`\ncs = fast_column_sums(X)\nX = X[, (cs > 10) & (cs < 2000)]\nY = (ACTIONet_summary$unified_feature_specificity[, c(17, 11, 29)])\narch.BP.enrichment = assess.geneset.enrichment.from.scores(Y, X)$logPvals\n\ncolnames(arch.BP.enrichment) = c(\"Ex-SZTR\", \"Ex-SZ\", \"In-SZ\")\nselected.rows = sort(unique(unlist(as.list(apply(arch.BP.enrichment, 2, function(x) order(x, decreasing = T)[1:5])))))\nHeatmap(scale(arch.BP.enrichment)[selected.rows, ])\n\n# plot.top.k.features(arch.BP.enrichment)\n\n\n\n```\n\n\n\n\n```{r}\nrequire(openxlsx)\n\nPEC_modules = readLines(con <- file(\"~/PEC_modules/INT-09_WGCNA_modules_hgnc_ids.csv\"))\n\n\nmod.names = lapply(PEC_modules, function(x) str_split(x, \"\\t\")[[1]][1])\nPEC_modules.genes = lapply(PEC_modules, function(x) sort(unique(str_split(x, \"\\t\")[[1]][-1])))\nnames(PEC_modules.genes) = mod.names\n\nSZ.mods = c(\"module_3628\", \"module_3636\", \"module_3711\", \"module_3251\", \"module_1749\", \"module_2752\", \"module_3001\", \"module_3009\", \"module_3172\", \"module_3332\", \"module_3333\", \"module_3464\", \"module_3614\", \"module_725\", \"module_738\", \"module_1685\", \"module_1755\", \"module_2692\", \"module_3107\", \"module_3184\", \"module_3316\", \"module_3349\", \"module_3381\", \"module_3496\", \"module_3543\", \"module_3616\", \"module_3673\", \"module_3678\", \"module_3693\", \"module_3709\", \"module_3731\")\nPEC_modules.genes.SZ = PEC_modules.genes[SZ.mods]\n\n\narch.spec = ACTIONet_summary$unified_feature_specificity\nassociations = do.call(cbind, lapply(PEC_modules.genes, function(mod) as.numeric(rownames(arch.spec) %in% mod)))\ncolnames(associations) = mod.names\nrownames(associations) = rownames(arch.spec)\nPEC.mod.en = assess.geneset.enrichment.from.scores(arch.spec, associations)\nPEC.mod.logPvals = PEC.mod.en$logPvals\ncolnames(PEC.mod.logPvals) = colnames(arch.spec)\nrownames(PEC.mod.logPvals) = mod.names\n \n# plot.top.k.features(PEC.mod.logPvals)\n\n\narch.annot = annotate.archetypes.using.labels(t(ACTIONet_summary$H_unified), ACTIONet_summary$metadata$Labels)\n\narch.labels = paste(\"A\", 1:ncol(ACTIONet_summary$H_unified), \"-\", arch.annot$Label, sep = \"\")\narch.labels[c(7, 11, 17, 29)] = paste(\"A\", c(7, 11, 17, 29), \"-\", c(\"Ex-NRGN\", \"Ex-SZ\", \"Ex-SZTR\", \"In-SZ\"), sep = \"\")\n\narch.order = c(setdiff(order(match(arch.annot$Label, names(colors))), c(7, 11, 17, 29)), c(7, 11, 17, 29))\n\nX = PEC.mod.logPvals[SZ.mods, arch.order]\ncolnames(X) = arch.labels[arch.order]\nHeatmap(X, cluster_columns = F)\n\n```\n\n\n```{r}\nassociations = do.call(cbind, lapply(DE.new$Down.genes, function(mod) as.numeric(rownames(arch.spec) %in% mod)))\ncolnames(associations) = names(DE.new$Down.genes)\nrownames(associations) = rownames(arch.spec)\nPEC.mod.en = assess.geneset.enrichment.from.scores(arch.spec, associations)\nPEC.mod.logPvals = PEC.mod.en$logPvals\ncolnames(PEC.mod.logPvals) = colnames(arch.spec)\nrownames(PEC.mod.logPvals) = names(DE.new$Down.genes)\n \n# plot.top.k.features(PEC.mod.logPvals)\n\n\narch.annot = annotate.archetypes.using.labels(t(ACTIONet_summary$H_unified), ACTIONet_summary$metadata$Labels)\n\narch.labels = paste(\"A\", 1:ncol(ACTIONet_summary$H_unified), \"-\", arch.annot$Label, sep = \"\")\narch.labels[c(7, 11, 17, 29)] = paste(\"A\", c(7, 11, 17, 29), \"-\", c(\"Ex-NRGN\", \"Ex-SZ\", \"Ex-SZTR\", \"In-SZ\"), sep = \"\")\n\narch.order = c(setdiff(order(match(arch.annot$Label, names(colors))), c(7, 11, 17, 29)), c(7, 11, 17, 29))\n\nX = PEC.mod.logPvals[, arch.order]\ncolnames(X) = arch.labels[arch.order]\nHeatmap(X, cluster_columns = F)\n\n\n\n```\n\n\n```{r}\ndf = data.frame(Gene = rownames(arch.spec), A11 = (arch.spec[, 11]), A29 = (arch.spec[, 29]))\n# mask = (df$A11 > 3) & (df$A29 > 3)\n# df = df[mask, ]\n# df$A11 = (df$A11 - median(df$A11)) / mad(df$A11)\n# df$A29 = (df$A29 - median(df$A29)) / mad(df$A29)\ndf$A11 = scale(df$A11)\ndf$A29 = scale(df$A29)\ndf$Label = \"\"\nmask = (df$A11 > 3) & (df$A29 > 3)\ndf$Label[mask] = df$Gene[mask]\n\nggscatter(df, \"A11\", \"A29\", repel = T, label = \"Label\")\n\n\n```\n\n\n```{r}\nbulk = readr::read_rds(\"~/results/input/MPP_bulk_expression_SZandCON.rds\")\nbulk.profile = assays(bulk)$voom\nbulk.profile.orth = orthoProject(bulk.profile, Matrix::rowMeans(bulk.profile))\n\n```\n\n```{r}\ntbl1 = read.csv(\"~/results/input/Prioritised_PGC3_SZ_Genes.csv\", sep = \"\\t\")\nPGC3.prioritized.genes = sort(unique(tbl1$Symbol.ID[tbl1$Prioritised == 1]))\n\ntbl2 = read.csv(\"~/results/input/INT-17_SCZ_High_Confidence_Gene_List.csv\", sep = \",\")\nPEC_HighConf.genes = sort(unique(tbl2$sczgenenames))\n\n\nA11 = scale(arch.spec[, 11])\nA29 = scale(arch.spec[, 29])\nmask = (A11 > 4) & (A29 > 4)\narch.genes = rownames(arch.spec)[mask]\n\npred.genes = list(arch.genes = arch.genes, PEC_HighConf.genes = PEC_HighConf.genes, PGC3.prioritized.genes = PGC3.prioritized.genes)\npred.genes = lapply(pred.genes, function(gs) intersect(gs, rownames(bulk)))\n\n```\n\n\n```{r}\nhot1 <- function (x, y = NULL, mu = 0, paired = FALSE, step_size = 0, \n skip_check = FALSE) {\n nx <- dim(x)[1]\n ny <- dim(y)[1]\n stat <- fdahotelling:::stat_hotelling_impl(x = x, y = y, mu = mu, paired = paired, \n step_size = step_size)\n df1 <- min(nx + ny - 2, p)\n df2 <- abs(nx + ny - 2 - p) + 1\n pvalue <- 1 - stats::pf(stat, df1, df2)\n dplyr::data_frame(statName = names(stat), statVal = stat, \n pValue = pvalue, df1 = df1, df2 = df2)\n}\n\n```\n\n\n```{r}\nlibrary(Hotelling)\n\ngs = pred.genes$arch.genes\ncommon.genes = intersect(rownames(bulk.profile.orth), gs)\n# Z = apply(t(bulk.profile[gs[1:10], ]) , 2, RNOmni::RankNorm)\nX = t(bulk.profile.orth[gs, ])\nX1 = X[bulk$Dx == \"SCZ\", ]\nX2 = X[bulk$Dx != \"SCZ\", ]\n\nstat <- fdahotelling:::stat_hotelling_impl(x = X1, y = X2, mu = 0, paired = F, step_size = 0)\nrand.stats = sapply(1:100, function(i) {\n rand.samples = sample(1:nrow(bulk.profile.orth), length(gs))\n randX = t(bulk.profile.orth[rand.samples, ])\n randX1 = randX[bulk$Dx == \"SCZ\", ]\n randX2 = randX[bulk$Dx != \"SCZ\", ]\n rand.stat <- fdahotelling:::stat_hotelling_impl(x = randX1, y = randX2, mu = 0, paired = F, step_size = 0)\n \n return(rand.stat)\n})\n\nz = (stat - mean(rand.stats) ) / sd(rand.stats)\n\n# require(DescTools)\n# out = DescTools::HotellingsT2Test(X1, X2, test = \"chi\")\n\n\n\n\n```\n\n\n```{r}\n\nstat <- hot1(x = X1, y = X2, mu = 0, step_size = 0)\n\n# x = Hotelling::hotelling.test(X1, X2)\n# \n# \n# N = nx + ny\n# print(stat$statVal*(N - p - 1)/((N-2)*p))\n# print(x)\n\n```\n\n```{r}\n\n\n\nfdahotelling::test_twosample\n\n\n\n\n\n# X1 = x\n# X2 = y\n# \n\nout = fdahotelling::test_twosample(x, y)\n\nstat <- out$statVal\nnx = nrow(x)\nny = nrow(y)\np = ncol(x)\ndf1 <- min(nx + ny - 2, p)\ndf2 <- abs(nx + ny - 2 - p) + 1\npvalue <- 1 - stats::pf(stat, df1, df2)\n\ndplyr::data_frame(statName = names(stat), statVal = stat, \n pValue = pvalue) \n\n\nstat = Hotelling::hotelling.test(x, y, perm = F)\nprint(stat)\n\n\n# pred.scores = cor(bulk.profile[common.genes, ], xx, method = \"pearson\")\n\n\n\nHot <- function(X1, X2) {\n p = ncol(X1)\n n1 = nrow(X1)\n n2 = nrow(X2)\n \n X1.mean = Matrix::colMeans(X1)\n X2.mean = Matrix::colMeans(X2)\n Delta.means = X1.mean - X2.mean\n \n Delta1 = apply(X1, 1, function(x) x - X1.mean)\n Delta2 = apply(X2, 1, function(x) x - X2.mean)\n Sigma1 = (Delta1 %*% t(Delta1)) / (n1-1)\n Sigma2 = (Delta2 %*% t(Delta2)) / (n2-1)\n Sigma = (n1 - 1) * Sigma1 + (n2 - 1) * Sigma2 / (((1 / n1) + (1 / n2) )*(n1+n2-2))\n \n HT = t(Delta.means) %*% Sigma %*% Delta.means\n \n require(fdahotelling)\n out = fdahotelling::test_twosample(X1, X2, B = 0)\n \n \n\n \n # x = Hotelling::hotelling.stat(X1, X2)\n \n \n # fdahotelling:::parametric_test\n \n parametric_test\n print(x2)\n\n x2 = hotelling.stat(X1, X2)\n print(x2)\n \n}\n\nx\n\n```\n\n\n```{r}\ncommon.genes = intersect(rownames(bulk.profile.orth), rownames(U))\nxx = arch.spec[common.genes, ]\npred.scores = cor(bulk.profile[common.genes, ], xx, method = \"pearson\")\n\nsc = apply(pred.scores, 2, function(x) 1 / (1 + exp(-scale(x))))\n# sc = apply(pred.scores, 2, function(x) 1 + x)\nrownames(sc) = bulk$SampleID\n\n\nxx = split(bulk$SampleID, bulk$Dx)\nassociations = do.call(cbind, lapply(xx, function(mod) as.numeric(bulk$SampleID %in% mod)))\ncolnames(associations) = names(xx)\nrownames(associations) = bulk$SampleID\n\nPEC.mod.logPvals = t(assess.geneset.enrichment.from.scores(sc, associations)$logPvals)\nrownames(PEC.mod.logPvals) = 1:nrow(PEC.mod.logPvals)\nHeatmap(PEC.mod.logPvals)\n\n```\n\n\n```{r}\n# scores = exp(bulk.profile.orth/10)\nscores = 1 / (1 + exp(-bulk.profile.orth))\n# scores[scores < 0] = 0\nassociations = do.call(cbind, lapply(pred.genes, function(gs) as.numeric(rownames(scores) %in% gs)))\ncolnames(associations) = names(pred.genes)\nrownames(associations) = rownames(scores)\npred.scores = t(assess.geneset.enrichment.from.scores(scores, associations)$logPvals)\ncolnames(pred.scores) = colnames(associations)\nrownames(pred.scores) = colnames(scores)\n\n\ncommon.genes = intersect(rownames(bulk.profile.orth), rownames(U))\nxx = (arch.spec[common.genes, c(29, 11)])\n# xx = cbind(sqrt(xx[, 1] * xx[, 2]), xx)\npred.scores = cor(bulk.profile[common.genes, ], xx, method = \"pearson\")\n\n\n# pred.scores = sapply(pred.genes, function(gs) stats = scale(Matrix::colMeans(bulk.profile.orth[gs, ])))\n\ndf = as.data.frame(scale(pred.scores))\nrownames(df) = bulk$SampleID\ndf$phenotype = bulk$Dx\n\nSZ.samples = list(SZ = bulk$SampleID[which(bulk$Dx == \"SCZ\")])\nv = df[, 1]\nnames(v) = rownames(df)\nx = fgsea::fgsea(SZ.samples, v)\n\n# fgsea::plotEnrichment(SZ.samples$SZ, v)\n\nprint(-log10(x$pval))\n\n# df2 = reshape2::melt(df)\n# colnames(df2) = c(\"phenotype\", \"method\", \"z\")\n\n# ggbarplot(df2, x = \"method\", y = \"z\", color = \"phenotype\",\n# add = \"mean_se\", palette = c(\"#00AFBB\", \"#E7B800\"),\n# position = position_dodge())\n\n\n\n```\n\n```{r}\n# arch.genes, PEC_HighConf.genes, PGC3.prioritized.genes)\n\n# zz = sapply(pred.genes, function(gs) stats = scale(Matrix::colMeans(bulk.profile.orth[gs, ])))\n\nll = lapply(pred.genes, function(gs) {\n l = as.numeric(rownames(bulk.profile.orth) %in% gs)\n logPvals=-log10(p.adjust(apply(bulk.profile.orth, 2, function(x) {\n perm = order(x, decreasing = T)\n mhg.out = mhg::mhg_test(l[perm], length(l), sum(l), length(l)/4, 5, upper_bound = F, tol = 1e-300)\n mhg.out$pvalue\n }), method = \"fdr\"))\n})\nX = do.call(cbind, ll)\n\ndf = as.data.frame(zz)\ndf$phenotype = bulk$Dx\ndf2 = reshape2::melt(df)\ncolnames(df2) = c(\"phenotype\", \"method\", \"z\")\n\n# ggbarplot(df2, x = \"method\", y = \"z\", color = \"phenotype\",\n# add = \"mean_se\", palette = c(\"#00AFBB\", \"#E7B800\"),\n# position = position_dodge())\n# \n# \n# \n# ggbarplot(df, x = \"phenotype\", y = \"arch.genes\", fill = \"phenotype\", palette = c(\"#666666\", \"#cccccc\"),\n# add = \"mean_se\", label = TRUE, lab.vjust = -1.6)\n\n\nperfs = apply(pred.scores, 2, function(x) PRROC::roc.curve(1 / (1 + exp(-scale(x))), weights.class0 = as.numeric(bulk$Dx == \"SCZ\"), curve = T))\nplot_roc(perfs, as.character(pals::brewer.dark2(3)))\n# prefs = apply(zz, 2, function(pred) PRROC::roc.curve(pred, weights.class0 = as.numeric(bulk$Dx == \"SCZ\"), curve = T, sorted = T))\n\nperfs = apply(pred.scores, 2, function(pred) PRROC::pr.curve(pred, weights.class0 = as.numeric(bulk$Dx == \"SCZ\"), curve = T))\nplot_prc(perfs)\n\n# \n# x = sapply(istel.perfs, function(x) x$auc)\n# cor(Cat.AC.z, x[names(Cat.AC.z)])\n# cor(C1.line.z[names(Cat.AC.z)], Cat.AC.z)\n# \n# CPal = as.character(pals::brewer.spectral(length(sorted.istels)))\n# AUCs = sapply(istel.perfs, function(x) x$auc)\n# perm = order(AUCs, decreasing = T)\n# gp = plot_roc(istel.perfs[perm], CPal)\n\n\n\n```\n\n\n```{r}\nlibrary(fda)\nlibrary(fdahotelling)\n\nSZ.mask = bulk$Dx == \"SCZ\"\nx = t(bulk.profile[pred.genes$arch.genes, SZ.mask])\ny = t(bulk.profile[pred.genes$arch.genes, !SZ.mask])\n\nout = fdahotelling::test_twosample(x, y, B = 0)\n\n# Hotelling \n# 750.1352 \n# out$statVal\n\nx = t(bulk.profile[pred.genes$PEC_HighConf.genes, SZ.mask])\ny = t(bulk.profile[pred.genes$PEC_HighConf.genes, !SZ.mask])\n\nout = fdahotelling::test_twosample(x, y, B = 0, verbose = T)\n\n\n\n```\n\n\n```{r}\nl = as.numeric(rownames(bulk.profile.orth) %in% pred.genes$arch.genes)\n\n# logPvals=-log10(p.adjust(apply(bulk.profile.orth, 2, function(x) {\n# perm = order(x, decreasing = T)\n# mhg.out = mhg::mhg_test(l[perm], length(l), sum(l), length(l), 5, upper_bound = F, tol = 1e-300)\n# mhg.out$pvalue\n# }), method = \"fdr\"))\n\ndf3 = data.frame(scores = logPvals, phenotype = bulk$Dx)\nggbarplot(df3, x = \"phenotype\", y = \"scores\", fill = \"phenotype\", palette = c(\"#666666\", \"#cccccc\"),\n add = \"mean_se\", label = TRUE, lab.vjust = -1.6) + geom_hline(yintercept = -log10(0.05), linetype=\"dashed\", \n color = \"red\", size=1)\n\n```\n\n\n\n```{r}\nLabels = sort(unique(ace.istel$Label))\nistel.perfs = vector(\"list\", length(Labels))\nnames(istel.perfs) = Labels\n\n\nfor(label in Labels) {\n print(label)\n mask.test = ace.istel$Label == label\n \n xgbpred <- predict(PCA.model.full, istel.data.reduced[mask.test, ])\n \n istel.perfs[[label]] = PRROC::roc.curve(xgbpred, weights.class0 = istel.data.labels[mask.test], curve = T)\n}\n\nx = sapply(istel.perfs, function(x) x$auc)\ncor(Cat.AC.z, x[names(Cat.AC.z)])\ncor(C1.line.z[names(Cat.AC.z)], Cat.AC.z)\n\nCPal = as.character(pals::brewer.spectral(length(sorted.istels)))\nAUCs = sapply(istel.perfs, function(x) x$auc)\nperm = order(AUCs, decreasing = T)\ngp = plot_roc(istel.perfs[perm], CPal)\n\n# L = c(istel.perfs, list(LX2 = lx2.perfs))\n# CPal = as.character(c(CPal.istel[rownames(X)[order(X[, 4])]], \"LX2\" = \"#aaaaaa\"))\n# perm = order(sapply(L, function(x) x$auc), decreasing = T)\n# gp = plot_roc(L[perm], CPal[perm])\n\n\n# sort(sapply(L, function(x) x$auc))\n\npdf(\"~/figures/TGFb_ROC_pStel_vs_iStel.pdf\", width = 12)\nprint(gp)\ndev.off()\n```\n\n\n```{r}\ngs = df$Label[df$Label != \"\"]\ngs = gs[-grep(\"MT-\", gs)]\n\n\n\n\n# SZ.genes = readr::read_rds(file.path(input.path, \"SCZ_associated_genesets.rds\"))\n# \n# gs = SZ.genes$\n\nl = as.numeric(rownames(bulk.profile.orth) %in% gs)\n\nlogPvals=-log10(p.adjust(apply(bulk.profile.orth, 2, function(x) {\n perm = order(x, decreasing = T)\n mhg.out = mhg::mhg_test(l[perm], length(l), sum(l), length(l), 5, upper_bound = F, tol = 1e-300)\n mhg.out$pvalue\n}), method = \"fdr\"))\n\ndf3 = data.frame(scores = logPvals, phenotype = bulk$Dx)\nggbarplot(df3, x = \"phenotype\", y = \"scores\", fill = \"phenotype\", palette = c(\"#666666\", \"#cccccc\"),\n add = \"mean_se\", label = TRUE, lab.vjust = -1.6) + geom_hline(yintercept = -log10(0.05), linetype=\"dashed\", \n color = \"red\", size=1)\n\nll = c(\"CON\", \"SZ\")\nisSZ.pred = ll[as.numeric(logPvals > -log10(0.05))+1]\ntable(isSZ.pred, bulk$Dx)\n\nsum((isSZ.pred == \"SZ\") & (bulk$Dx == \"SCZ\")) / sum((bulk$Dx == \"SCZ\"))\n\n ## AUC curve ...\n\n```\n\n\n\n```{r}\nplot.ACTIONet.gradient(ACTIONet_summary$ACTIONet2D, ACTIONet_summary$H_unified[, 30], alpha = 0)\nplot.ACTIONet.gradient(ACTIONet_summary$ACTIONet2D, ACTIONet_summary$H_unified[, 6], alpha = 0)\n\n\n```\n\n" }, { "alpha_fraction": 0.658115565776825, "alphanum_fraction": 0.6693047881126404, "avg_line_length": 36.7706184387207, "blob_id": "aad8300d094d6cad8a8b6b4fdf483f44f6b6b7d5", "content_id": "944164a606d7e0d23860293a1ea91dcd5b1bbd6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 14657, "license_type": "no_license", "max_line_length": 205, "num_lines": 388, "path": "/ancient/Fig2_Run_DE_v2.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"Perform DE analysis\"\noutput: html_notebook\n---\n\n# Setup\n```{r include=FALSE}\nrequire(ACTIONet)\nrequire(stringr)\nrequire(ComplexHeatmap)\n\nrequire(muscat)\nrequire(edgeR)\nrequire(limma)\n\ndataset.path = \"~/results/datasets/\"\nresults.path = \"~/results\"\nfigures.folder = \"~/results/figures\"\n\n\n```\n\n\n\n\n\n```{r}\nACTIONet_summary = readr::read_rds(file.path(dataset.path, \"ACTIONet_summary_filtered_individuals.rds\"))\n\npb.logcounts = readr::read_rds(file.path(dataset.path, \"PB_mean_logcounts_final.RDS\"))\n\ncolor.df = readRDS(file.path(dataset.path, \"celltype_colors.rds\"))\n\n# color.df[c(22:24), ] = color.df[c(24, 23, 22), ]\n\ncolors = color.df$color\nnames(colors) = color.df$celltype\n\n\nncells = sapply(int_colData(pb.logcounts)$n_cells, as.numeric)\nrownames(ncells) = names(assays(pb.logcounts))\n\n```\n\n\n\n\n\n\n# Prefilter outlier samples wrt ExNero %, or samples that have less than 500 cells (pruning from 140 -> 121 samples)\n```{r}\ncs = Matrix::colSums(ncells)\nncells.freq = 100*scale(ncells, center = F, scale = cs)\nEx.perc = (fast_column_sums(ncells.freq[grepl(\"^Ex\", rownames(ncells.freq)) & !grepl(\"^Ex-NRGN\", rownames(ncells.freq)), ]))\n\n# mask = !(pb.logcounts$ID %in% c(\"SZ15\"))\nmask = (Ex.perc >= 10) & (Ex.perc <= 80) #& (fast_column_sums(ncells) >= 500)\n# mask = (Ex.perc >= 1) & (fast_column_sums(ncells) >= 500)\n# mask = (Ex.perc >= 1)\npb.logcounts.filtered = pb.logcounts [, mask]\n\n\nff = interaction(ACTIONet_summary$metadata$Individual, ACTIONet_summary$metadata$Labels)\numi.tbl = split(ACTIONet_summary$metadata$umi_count, ff)\nmean.celltype.umi = sapply(umi.tbl, function(x) {\n if(length(x) == 0) {\n return(0)\n } else {\n return(mean(x))\n }\n})\nmean.celltype.umi.mat = matrix(mean.celltype.umi, nrow = length(levels(ACTIONet_summary$metadata$Individual)))\n\n\n```\n\n# Performing cohort-specific DE\n```{r}\n# int_colData(pb.logcounts.filtered)$n_cells = t(metadata(pb.logcounts.filtered)$n_cells)\n# metadata(pb.logcounts.filtered) = metadata(pb.logcounts.filtered)[c(1:2)]\n\n# [1] \"Cohort\" \"ID\" \"Internal_ID\" \"CMC_ID\" \"Phenotype\" \"Batch\" \"HTO\" \n# [8] \"Gender\" \"Age\" \"PMI\" \"EUR_Ancestry\" \"EAS_Ancestry\" \"AMR_Ancestry\" \"SAS_Ancestry\" \n# [15] \"AFR_Ancestry\" \"Benzodiazepines\" \"Anticonvulsants\" \"AntipsychTyp\" \"AntipsychAtyp\" \"Antidepress\" \"Lithium\" \n# [22] \"MedPC1\" \"MedPC2\" \"MedPC3\" \"MedPC4\" \"MedPC5\" \"MedPC6\" \"Cells\" \n# [29] \"Density\" \"SZTR.mean\" \"A7.signature\" \"A11.signature\" \"A17.signature\" \"A29.signature\" \"PRS\" \n# [36] \"POP.EL3SD\" \"genes\" \"umis\" \"mito_perc\" \"TPS.Ex\" \"TPS.Neuro\" \"TPS.All\" \n# form = ~ Phenotype + Batch + Gender + Age + PMI + Benzodiazepines + Anticonvulsants + AntipsychTyp + AntipsychAtyp + Antidepress\n# form = ~ Phenotype + Batch + Gender + Age + PMI + Benzodiazepines + Anticonvulsants + AntipsychTyp + AntipsychAtyp + Antidepress + EUR_Ancestry + EAS_Ancestry + AMR_Ancestry + SAS_Ancestry + AFR_Ancestry\n\n# pb.logcounts.filtered$logumis = log1p(pb.logcounts.filtered$umis)\n\npb.logcounts.filtered$SampleQuality = scale(log1p(pb.logcounts.filtered$umis))\nform = ~ Phenotype + Batch + PMI + Gender + Age + Benzodiazepines + Anticonvulsants + AntipsychTyp + AntipsychAtyp + Antidepress + SampleQuality\n\nresDE = lapply( levels(pb.logcounts.filtered$Cohort), function(chrt){\n\n\tkeep.ids = colnames(pb.logcounts.filtered)[pb.logcounts.filtered$Cohort == chrt]\n\n\tpb.logcounts.filtered_sub = pb.logcounts.filtered[,keep.ids]\n\t# metadata(pb.logcounts.filtered_sub)$n_cells = metadata(pb.logcounts.filtered_sub)$n_cells[,keep.ids]\n sample.metadata = droplevels(data.frame(colData(pb.logcounts.filtered_sub)))\n\tdesign.mat <- model.matrix(form, data = sample.metadata)\n\n# # sample.quality.mat = apply(mean.celltype.umi.mat[pb.logcounts.filtered_sub$ID, ], 2, function(x) log2(x / mean(x)))\n# # \tsample.quality.mat[sample.quality.mat == -Inf] = min(sample.quality.mat[!is.infinite(sample.quality.mat)])\n# sample.quality.mat = log1p(apply(mean.celltype.umi.mat[pb.logcounts.filtered_sub$ID, ], 2, function(x) x))\n# \n# \n# \tsample.quality.mat[sample.quality.mat == 0] = NA\n# sample.quality.mat.z = apply(sample.quality.mat, 2, function(x) x / sum(x, na.rm = T))\n# \n# sample.quality = as.numeric(scale(apply(sample.quality.mat.z, 1, function(x) mean(x, na.rm = T)\t)))\n\n# \n# \n# \tsample.quality.mat[sample.quality.mat == 0] = NA\n# sample.quality.mat.z = apply(sample.quality.mat, 2, function(x) (x - median(x, na.rm = T))/mad(x, na.rm = T))\n# \tsample.quality.mat.z[sample.quality.mat.z < -3] = -3\n# \tsample.quality.mat.z[sample.quality.mat.z > 3] = 3\n# \n# # sample.quality.mat = apply(sample.quality.mat, 2, function(x) x / sum(x))\n# \n# \n# design.mat = cbind(design.mat, sample.quality)\n# colnames(design.mat)[[ncol(design.mat)]] = \"SampleQuality\"\n\t\n\n\t# colnames(design.mat) = c(\"Intercept\", \"PhenotypeSZ\", paste(\"V\", 3:ncol(design.mat), sep = \"\"))\n\tcolnames(design.mat)[1] = c(\"Intercept\")\n\n\tcontrast.mat <- makeContrasts(contrasts = \"PhenotypeSZ\", levels = design.mat)\n\n\tdf = pbDS(pb.logcounts.filtered_sub, method = \"limma-trend\", min_cells = 5, design = design.mat, contrast = contrast.mat, filter = \"both\")\n\t\n})\nnames(resDE) = levels(colData(pb.logcounts.filtered)$Cohort)\n\nreadr::write_rds(resDE, file.path(dataset.path, \"Cohort_specific_DE_results_final_with_logumi_baseline_full_filter_extended_cell_filtering.rds\"))\n\n# resDE = readr::read_rds(\"~/PFC_v3/\")\n# lst_meta = readr::read_rds(\"~/PFC_v3/filtered_resDE.rds\")\n\n\n```\n\n\n## Export as excel tables\n```{r}\nfor(ds in 1:2) {\n\n library(openxlsx)\n Up.wb <- createWorkbook()\n for(i in 1:length(resDE[[ds]]$table$PhenotypeSZ)) {\n res = resDE[[ds]]$table$PhenotypeSZ[[i]]\n res = res[res$logFC > 0, ]\n res = cbind(data.frame(Gene = rownames(res)), res)\n res = res[order(res$t, decreasing = T), ]\n \n n = names(resDE[[ds]]$table$PhenotypeSZ)[[i]] #str_replace(arch.names[arch.order[i]], \"/\", \"-\")\n \n addWorksheet(wb=Up.wb, sheetName = n)\n writeData(Up.wb, sheet = n, res) \n \n }\n saveWorkbook(Up.wb, sprintf(file.path(dataset.path, \"DE_genes_up_%s_with_logumi_baseline_full_filter_extended_cell_filtering_fullset.xlsx\"), names(resDE)[[ds]]), overwrite = TRUE)\n \n \n library(openxlsx)\n Down.wb <- createWorkbook()\n for(i in 1:length(resDE[[ds]]$table$PhenotypeSZ)) {\n res = resDE[[ds]]$table$PhenotypeSZ[[i]]\n res = res[res$logFC < 0, ]\n res = cbind(data.frame(Gene = rownames(res)), res)\n res = res[order(res$t, decreasing = F), ]\n \n n = names(resDE[[ds]]$table$PhenotypeSZ)[[i]] #str_replace(arch.names[arch.order[i]], \"/\", \"-\")\n \n addWorksheet(wb=Down.wb, sheetName = n)\n writeData(Down.wb, sheet = n, res) \n \n }\n saveWorkbook(Down.wb, sprintf(file.path(dataset.path, \"DE_genes_down_%s_with_logumi_baseline_full_filter_extended_cell_filtering_fullset.xlsx\"), names(resDE)[[ds]]), overwrite = TRUE)\n}\n\n```\n\n\n\n# Prefiltering individual DE results before combining them\nOnly keep genes that have 1) consistent direction of dysregulation across both datasets, and 2) at least 1 sd away from zero on the logFC scale\n\n```{r}\ncelltypes = intersect(names(resDE$McLean$table$PhenotypeSZ), names(resDE$MtSinai$table$PhenotypeSZ))\n\nfiltered.tables = lapply(celltypes, function(celltype) {\n tbl1 = resDE[[1]]$table$PhenotypeSZ[[celltype]]\n tbl2 = resDE[[2]]$table$PhenotypeSZ[[celltype]]\n \n genes = intersect(tbl1$gene[1 <= abs(tbl1$logFC/sd(tbl1$logFC))], tbl2$gene[1 <= abs(tbl2$logFC / sd(tbl2$logFC))])\n # genes = intersect(tbl1$gene, tbl2$gene)\n \n tbl1 = tbl1[match(genes, tbl1$gene), ]\n tbl2 = tbl2[match(genes, tbl2$gene), ]\n \n mask = sign(tbl1$logFC)*sign(tbl2$logFC) > 0\n tbl1 = tbl1[mask, ]\n tbl2 = tbl2[mask, ]\n \n tbls = list(McClean = tbl1, MtSinai = tbl2) \n tbls = lapply( tbls, function(tab){\n tab$se = tab$logFC / tab$t\n tab\n })\n \n return(tbls)\n})\nnames(filtered.tables) = celltypes\n\nreadr::write_rds(filtered.tables, file.path(dataset.path, \"individual_diff_results_filtered_full_with_logumi_baseline_full_filter_extended_cell_filtering.rds\"))\n\n```\n\n## Export as excel tables\n```{r}\nfor(ds in 1:2) {\n\n library(openxlsx)\n Up.wb <- createWorkbook()\n for(i in 1:length(filtered.tables)) {\n res = filtered.tables[[i]][[ds]]\n res = res[res$logFC > 0, ]\n res = cbind(data.frame(Gene = rownames(res)), res)\n res = res[order(res$t, decreasing = T), ]\n \n n = names(filtered.tables)[[i]] #str_replace(arch.names[arch.order[i]], \"/\", \"-\")\n \n addWorksheet(wb=Up.wb, sheetName = n)\n writeData(Up.wb, sheet = n, res) \n \n }\n saveWorkbook(Up.wb, sprintf(file.path(dataset.path, \"DE_genes_up_%s_with_logumi_baseline_full_filter_extended_cell_filtering.xlsx\"), names(filtered.tables[[i]])[[ds]]), overwrite = TRUE)\n \n \n library(openxlsx)\n Down.wb <- createWorkbook()\n for(i in 1:length(filtered.tables)) {\n res = filtered.tables[[i]][[ds]]\n res = res[res$logFC < 0, ]\n res = cbind(data.frame(Gene = rownames(res)), res)\n res = res[order(res$t, decreasing = F), ]\n \n n = names(filtered.tables)[[i]] #str_replace(arch.names[arch.order[i]], \"/\", \"-\")\n \n addWorksheet(wb=Down.wb, sheetName = n)\n writeData(Down.wb, sheet = n, res) \n \n }\n saveWorkbook(Down.wb, sprintf(file.path(dataset.path, \"DE_genes_down_%s_with_logumi_baseline_full_filter_extended_cell_filtering.xlsx\"), names(filtered.tables[[i]])[[ds]]), overwrite = TRUE)\n}\n\n```\n\n\n```{r}\ncombined.analysis.tables = lapply(names(filtered.tables), function(celltype) {\n print(celltype)\n tbls = filtered.tables[[celltype]]\n \n gene.tbls = lapply(1:nrow(tbls[[1]]), function(i) {\n dfs = lapply(1:length(tbls), function(k) tbls[[k]][i, ])\n df = do.call(\"rbind\", dfs)\n })\n names(gene.tbls) = tbls[[1]]$gene\n \n combined.analysis.tbl = do.call(rbind, lapply(names(gene.tbls), function(gene){\n x = suppressWarnings(metafor::rma(yi=logFC, sei=se, data = gene.tbls[[gene]], method=\"FE\"))\n combined.tbl = data.frame( gene = gene, \n logFC = x$beta,\n se = x$se,\n tstat = x$zval,\n P.Value = x$pval)\n return(combined.tbl)\n }))\n rownames(combined.analysis.tbl) = names(gene.tbls)\n \n combined.analysis.tbl = combined.analysis.tbl[order(combined.analysis.tbl$P.Value), ]\n \n return(combined.analysis.tbl)\n})\nnames(combined.analysis.tables) = names(filtered.tables)\n\nDF = do.call(rbind, combined.analysis.tables)\nDF$adj.P.Val = p.adjust(DF$P.Value, \"fdr\")\nff = factor(unlist(lapply(names(combined.analysis.tables), function(celltype) rep(celltype, nrow(combined.analysis.tables[[celltype]])))), names(filtered.tables))\ncombined.analysis.tables = split(DF, ff)\n\nreadr::write_rds(combined.analysis.tables, file.path(dataset.path, \"meta_analysis_diff_results_full_with_logumi_baseline_full_filter_extended_cell_filtering.rds\"))\n\n```\n\n\n\n```{r eval=FALSE, include=FALSE}\nresDE = readr::read_rds(file.path(dataset.path, \"filtered_resDE_with_logumi_baseline_full_filter_extended_cell_filtering.rds\"))\n\nfiltered.tables = readr::read_rds(file.path(dataset.path, \"individual_diff_results_filtered_full_with_logumi_baseline_full_filter_extended_cell_filtering.rds\"))\n\ncombined.analysis.tables = readr::read_rds(file.path(dataset.path, \"meta_analysis_diff_results_with_logumi_baseline_full_filter_extended_cell_filtering.rds\"))\n\n```\n\n```{r}\n library(openxlsx)\n Up.wb <- createWorkbook()\n for(i in 1:length(combined.analysis.tables)) {\n res = combined.analysis.tables[[i]]\n res = res[(res$logFC > 0.1) & (res$P.Value <= 0.05), ]\n res = res[order(res$t, decreasing = T), ]\n \n n = names(combined.analysis.tables)[[i]] #str_replace(arch.names[arch.order[i]], \"/\", \"-\")\n \n addWorksheet(wb=Up.wb, sheetName = n)\n writeData(Up.wb, sheet = n, res) \n \n }\n saveWorkbook(Up.wb, sprintf(file.path(dataset.path, \"DE_genes_up_%s_with_logumi_baseline_full_filter_extended_cell_filtering.xlsx\"), \"combined\"), overwrite = TRUE)\n \n \n library(openxlsx)\n Down.wb <- createWorkbook()\n for(i in 1:length(combined.analysis.tables)) {\n res = combined.analysis.tables[[i]]\n res = res[(res$logFC < -0.1) & (res$P.Value <= 0.05), ]\n res = res[order(res$t, decreasing = F), ]\n \n n = names(combined.analysis.tables)[[i]] #str_replace(arch.names[arch.order[i]], \"/\", \"-\")\n \n addWorksheet(wb=Down.wb, sheetName = n)\n writeData(Down.wb, sheet = n, res) \n \n }\n saveWorkbook(Down.wb, sprintf(file.path(dataset.path, \"DE_genes_down_%s_with_logumi_baseline_full_filter_extended_cell_filtering.xlsx\"), \"combined\"), overwrite = TRUE)\n```\n\n\n```{r}\nDE.sc = matrix(0, nrow(pb.logcounts), length(combined.analysis.tables))\ntstats = matrix(0, nrow(pb.logcounts), length(combined.analysis.tables))\nlogFC = matrix(0, nrow(pb.logcounts), length(combined.analysis.tables))\nlogPvals = matrix(0, nrow(pb.logcounts), length(combined.analysis.tables))\nrownames(DE.sc) = rownames(tstats) = rownames(logFC) = rownames(logPvals) = rownames(pb.logcounts)\ncolnames(DE.sc) = colnames(tstats) = colnames(logFC) = colnames(logPvals) = names(combined.analysis.tables)\n\nlimma_trend_mean.scores = matrix(0, nrow(pb.logcounts), length(combined.analysis.tables))\nUp.genes = vector(\"list\", length(combined.analysis.tables))\nDown.genes = vector(\"list\", length(combined.analysis.tables))\nrownames(limma_trend_mean.scores) = rownames(pb.logcounts)\nnames(Up.genes) = names(Down.genes) = colnames(limma_trend_mean.scores) = names(combined.analysis.tables)\nfor(i in 1:length(combined.analysis.tables)) {\n\tprint(i)\n\t\n\ttbl = combined.analysis.tables[[i]]\n\n\ttstats[tbl$gene, names(combined.analysis.tables)[[i]]] = tbl$tstat\n\tlogFC[tbl$gene, names(combined.analysis.tables)[[i]]] = tbl$logFC\n\tlogPvals[tbl$gene, names(combined.analysis.tables)[[i]]] = -log10(tbl$adj.P.Val)\n\t\n\tDE.sc[tbl$gene, names(combined.analysis.tables)[[i]]] = tbl$tstat\n\t\n}\nlimma_trend_mean.scores[is.na(limma_trend_mean.scores)] = 0\n\n\nUp.genes = lapply(combined.analysis.tables, function(combined.analysis.tbl) {\n combined.analysis.tbl$gene[(combined.analysis.tbl$logFC > 0.1) & (combined.analysis.tbl$adj.P.Val < 0.05)]\n})\nDown.genes = lapply(combined.analysis.tables, function(combined.analysis.tbl) {\n combined.analysis.tbl$gene[(combined.analysis.tbl$logFC < -0.1) & (combined.analysis.tbl$adj.P.Val < 0.05)]\n})\n\nDE.new = list(DE.sc = DE.sc, tstats = tstats, logFC = logFC, logPvals = logPvals, Up.genes = Up.genes, Down.genes = Down.genes)\n\nsaveRDS(DE.new, file.path(dataset.path, \"DE_genes_pseudobulk_final_with_logumi_baseline_full_filter_extended_cell_filtering.rds\"))\n\n\n\n```\n\n\n" }, { "alpha_fraction": 0.6470255255699158, "alphanum_fraction": 0.6731733083724976, "avg_line_length": 37.89937210083008, "blob_id": "c6d9a95e2518704513278357051423cb3fba8f37", "content_id": "0573529178fb9e78eb3fe7a43c0fe11511f628be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 24744, "license_type": "no_license", "max_line_length": 323, "num_lines": 636, "path": "/old/Annotation.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"Annotate and verify cell type annotations\"\noutput: html_notebook\n---\n# Setup\n```{r include=FALSE}\nrequire(ACTIONet)\nrequire(stringr)\nrequire(ComplexHeatmap)\n\n\ndataset.path = \"~/results/datasets/\"\nresults.path = \"~/results\"\nfigures.path = \"~/results/figures\"\ninput.path = \"~/results/input\"\n\n\n```\n\n\n## Enrichment function\n```{r}\nassess.genesets <-function (arch.gs, terms.gs, N, min.pval = 1e-100, correct = \"none\"){\n shared = t(sapply(terms.gs, function(gs1) {\n sapply(arch.gs, function(gs2) {\n nn = intersect(gs1, gs2)\n })\n }))\n colnames(shared) = names(arch.gs)\n GS.sizes = sapply(terms.gs, length)\n logPvals.out = sapply(1:ncol(shared), function(i) {\n gg = shared[, i]\n x = as.numeric(sapply(gg, length))\n n.sample = length(arch.gs[[i]])\n n.success = as.numeric(GS.sizes)\n v = rep(1, length(x))\n min.overlap = n.success * n.sample/N\n idx = which(x >= min.overlap)\n if (length(idx) == 0) \n return(v)\n v[idx] = (phyper(x[idx]-1, n.sample, N-n.sample, n.success[idx], lower.tail = F))\n # v[idx] = HGT_tail(population.size = N, success.count = n.success[idx], \n # sample.size = n.sample, observed.success = x[idx])\n return(v)\n })\n if(correct == \"global\") {\n logPvals.out = matrix(p.adjust(logPvals.out, \"fdr\"), nrow = nrow(logPvals.out))\n } else if(correct == \"local\") {\n logPvals.out = apply(logPvals.out, 2, function(x) p.adjust(x, \"fdr\"))\n }\n rownames(logPvals.out) = names(terms.gs)\n colnames(logPvals.out) = names(arch.gs)\n return(-log10(Matrix::t(logPvals.out)))\n}\n\n\nassess.geneset.enrichment.from.archetypes <- function (ace, associations, min.counts = 0, specificity.slot = \"unified_feature_specificity\") \n{\n if(is.matrix(ace) | is.sparseMatrix(ace)) {\n scores = as.matrix(ace)\n } else {\n scores = rowMaps(ace)[[specificity.slot]] \n }\n if (max(scores) > 100) {\n scores = log1p(scores)\n }\n if (is.list(associations)) {\n associations = sapply(associations, function(gs) as.numeric(rownames(scores) %in% \n gs))\n rownames(associations) = rownames(scores)\n }\n common.features = intersect(rownames(associations), rownames(scores))\n rows = match(common.features, rownames(associations))\n associations = as(associations[rows, ], \"dgCMatrix\")\n scores = scores[common.features, ]\n enrichment.out = assess_enrichment(scores, associations)\n rownames(enrichment.out$logPvals) = colnames(associations)\n rownames(enrichment.out$thresholds) = colnames(associations)\n enrichment.out$scores = scores\n return(enrichment.out)\n}\n\nannotate_H_with_markers <- function (ace, markers, features_use = NULL, significance_slot = \"unified_feature_specificity\") \n{\n features_use = ACTIONet:::.preprocess_annotation_features(ace, features_use)\n marker_mat = ACTIONet:::.preprocess_annotation_markers(markers, features_use)\n marker_stats = Matrix::t(assess.geneset.enrichment.from.archetypes(ace, \n marker_mat)$logPvals)\n colnames(marker_stats) = colnames(marker_mat)\n marker_stats[!is.finite(marker_stats)] = 0\n annots = colnames(marker_mat)[apply(marker_stats, 1, which.max)]\n conf = apply(marker_stats, 1, max)\n out = list(Label = annots, Confidence = conf, Enrichment = marker_stats)\n return(out)\n}\n\n\n```\n\n\n# Load primary datasets\n```{r, eval = T}\nACTIONet_summary = readr::read_rds(file.path(dataset.path, \"ACTIONet_summary_filtered_individuals.rds\"))\n\npb.logcounts = readr::read_rds(file.path(dataset.path, \"PB_mean_logcounts_final.RDS\"))\n\ncolor.df = readRDS(file.path(dataset.path, \"celltype_colors.rds\"))\n\ncolors = color.df$color\nnames(colors) = color.df$celltype\n\nstoreDataset(colors, \"celltype_colors\", \"celltype_colors\", dataset.path = dataset.path)\n\n```\n\n\n\n# Plot main ACTIONet\n## Celltypes\n```{r}\n# annotated\ngg1 = plot.ACTIONet(ACTIONet_summary$ACTIONet2D, ACTIONet_summary$metadata$Labels, palette = colors, text_size = 2, use_repel = T)\n\npng(file.path(figures.path, \"ACTIONet\", \"ACTIONet_annotated.png\"), width = 1600, height = 1200, res = 150)\nplot(gg1)\ndev.off()\n\ngg2 = plot.ACTIONet(ACTIONet_summary$ACTIONet2D, ACTIONet_summary$metadata$Labels, palette = colors, text_size = 2, use_repel = T, add_text_labels = F)\n\npng(file.path(figures.path, \"ACTIONet\", \"ACTIONet_annotated_no_labels.png\"), width = 1600, height = 1200, res = 150)\nplot(gg2)\ndev.off()\n\n```\n\n\n## Supps\n### # Phenotype\n```{r}\ngg2 = plot.ACTIONet(ACTIONet_summary$ACTIONet2D, ACTIONet_summary$metadata$Phenotype, palette = c(\"#cccccc\", \"#888888\"), text_size = 2, use_repel = T, add_text_labels = F, point_size = 0.5)\n\npng(file.path(figures.path, \"ACTIONet\", \"ACTIONet_phenotype_annotated_no_labels.png\"), width = 1600, height = 1200, res = 150)\nplot(gg2)\ndev.off()\n```\n\n### Batch\n```{r}\ngg2 = plot.ACTIONet(ACTIONet_summary$ACTIONet2D, ACTIONet_summary$metadata$Batch, text_size = 2, use_repel = T, add_text_labels = F, point_size = 0.5)\n\npng(file.path(figures.path, \"ACTIONet\", \"ACTIONet_batch_annotated_no_labels.png\"), width = 1600, height = 1200, res = 150)\nplot(gg2)\ndev.off()\n```\n\n### Gender\n```{r}\nmask = !is.na(ACTIONet_summary$metadata$Gender)\ngg2 = plot.ACTIONet(ACTIONet_summary$ACTIONet2D[mask, ], ACTIONet_summary$metadata$Gender[mask], text_size = 2, use_repel = T, add_text_labels = F, point_size = 0.5, palette = c(\"pink\", \"#91bfdb\"))\n\npng(file.path(figures.path, \"ACTIONet\", \"ACTIONet_gender_annotated_no_labels.png\"), width = 1600, height = 1200, res = 150)\nplot(gg2)\ndev.off()\n```\n\n## Archetype\n```{r}\ngg2 = plot.ACTIONet(ACTIONet_summary$ACTIONet2D, ACTIONet_summary$metadata$assigned_archetype, text_size = 2, use_repel = T, add_text_labels = F, point_size = 0.5, palette = as.character(pals::polychrome(31)))\n\npng(file.path(figures.path, \"ACTIONet\", \"ACTIONet_archetypes_annotated_no_labels.png\"), width = 1600, height = 1200, res = 150)\nplot(gg2)\ndev.off()\n```\n## Archetype\n```{r}\ngg2 = plot.ACTIONet(ACTIONet_summary$ACTIONet2D, ACTIONet_summary$metadata$dataset, text_size = 2, use_repel = T, add_text_labels = F, point_size = 0.5, palette = c(\"#f1a340\", \"#998ec3\"))\n\npng(file.path(figures.path, \"ACTIONet\", \"ACTIONet_datasets_annotated_no_labels.png\"), width = 1600, height = 1200, res = 150)\nplot(gg2)\ndev.off()\n\n```\n\n\n## Plot ACTIONet plots per dataset\n### McLean dataset\n```{r}\nmask = ACTIONet_summary$metadata$dataset == \"McLean\"\nDS1.coors = ACTIONet_summary$ACTIONet2D[mask, ]\nDS1.labels = ACTIONet_summary$metadata$Labels[mask]\n\ngg3 = plot.ACTIONet(DS1.coors, DS1.labels, palette = colors, text_size = 2, use_repel = T)\n\npng(file.path(figures.path, \"ACTIONet\", \"ACTIONet_annotated_DS1.png\"), width = 1600, height = 1200, res = 150)\nplot(gg3)\ndev.off()\n\ngg4 = plot.ACTIONet(DS1.coors, DS1.labels, palette = colors, text_size = 2, use_repel = T, add_text_labels = F)\n\npng(file.path(figures.path, \"ACTIONet\", \"ACTIONet_annotated_no_labels_DS1.png\"), width = 1600, height = 1200, res = 150)\nplot(gg4)\ndev.off()\n\n```\n\n### MtSinai dataset\n```{r}\nmask = ACTIONet_summary$metadata$dataset == \"MtSinai\"\nDS2.coors = ACTIONet_summary$ACTIONet2D[mask, ]\nDS2.labels = ACTIONet_summary$metadata$Labels[mask]\n\ngg5 = plot.ACTIONet(DS1.coors, DS1.labels, palette = colors, text_size = 2, use_repel = T)\n\npng(file.path(figures.path, \"ACTIONet\", \"ACTIONet_annotated_DS2.png\"), width = 1600, height = 1200, res = 150)\nplot(gg5)\ndev.off()\n\ngg6 = plot.ACTIONet(DS1.coors, DS1.labels, palette = colors, text_size = 2, use_repel = T, add_text_labels = F)\n\npng(file.path(figures.path, \"ACTIONet\", \"ACTIONet_annotated_no_labels_DS2.png\"), width = 1600, height = 1200, res = 150)\nplot(gg6)\ndev.off()\n\n```\n\n\n\n\n# Plot cell type fraction stats\n```{r}\nrequire(ggpubr)\n\nncells = sapply(int_colData(pb.logcounts)$n_cells, as.numeric)\nrownames(ncells) = names(assays(pb.logcounts))\n\ncs = Matrix::colSums(ncells)\nncells.freq = 100*scale(ncells, center = F, scale = cs)\n# Ex.perc = (fast_column_sums(ncells.freq[grepl(\"^Ex\", rownames(ncells.freq)) & !grepl(\"^Ex-NRGN\", rownames(ncells.freq)), ]))\nEx.perc = (fast_column_sums(ncells.freq[grepl(\"^Ex\", rownames(ncells.freq)), ]))\n\ndf = data.frame(sample = colnames(ncells), perc = Ex.perc)\ngg = ggdensity(df, x = \"perc\", fill = \"lightgray\",\n add = \"mean\", rug = TRUE)\npdf(file.path(figures.path, \"Ex_perc_density.pdf\"), height = 4, width = 5)\nprint(gg)\ndev.off()\n\n\nncells.freq = ncells.freq[, order(Ex.perc, decreasing = T)]\nEx.perc = (fast_column_sums(ncells.freq[grepl(\"^Ex\", rownames(ncells.freq)) & !grepl(\"^Ex-NRGN\", rownames(ncells.freq)), ]))\n\nmask = (Ex.perc >= 10) & (Ex.perc <= 80) \nncells.freq = ncells.freq[, mask]\n\n# \n# \n# X = ncells.freq[, pb.logcounts$Cohort[match(colnames(ncells.freq), pb.logcounts$ID)] == \"McLean\"]\n# df = reshape2::melt(X)\n# colnames(df)=c(\"celltype\", \"sample\", \"freq\")\n# \n# df$celltype = factor(df$celltype, names(colors))\n# # df$sample = droplevels(factor(df$sample, colnames(ncells.freq)[sample.perm]))\n# \n# gg.ds1 = ggbarplot(df, \"sample\", \"freq\",\n# fill = \"celltype\", color = \"black\", palette = colors[levels(df$celltype)], xlab = \"Individual\", ylab = \"Percentage\") + theme(axis.text.x = element_text(face=\"bold\", size=0, angle=90), axis.text.y = element_text(face=\"bold\", size=12, angle=0), axis.title = element_text(face=\"bold\", size=18, angle=0))\n# \n# \n# pdf(file.path(figures.path, 'celltype_perc_McLean.pdf'), width = 10, height = 6)\n# print(gg.ds1)\n# dev.off()\n# \n# \n# \n# X = ncells.freq[, pb.logcounts$Cohort[match(colnames(ncells.freq), pb.logcounts$ID)] != \"McLean\"]\n# df = reshape2::melt(X)\n# colnames(df)=c(\"celltype\", \"sample\", \"freq\")\n# \n# df$celltype = factor(df$celltype, names(colors))\n# # df$sample = droplevels(factor(df$sample, colnames(ncells.freq)[sample.perm]))\n# \n# gg.ds2 = ggbarplot(df, \"sample\", \"freq\",\n# fill = \"celltype\", color = \"black\", palette = colors[levels(df$celltype)], xlab = \"Individual\", ylab = \"Percentage\") + theme(axis.text.x = element_text(face=\"bold\", size=0, angle=90), axis.text.y = element_text(face=\"bold\", size=12, angle=0), axis.title = element_text(face=\"bold\", size=18, angle=0))\n# \n# \n# pdf(file.path(figures.path, 'celltype_perc_MtSinai.pdf'), width = 10, height = 6)\n# print(gg.ds2)\n# dev.off()\n# \n# \n# pdf(file.path(figures.path, 'celltype_perc_combined.pdf'), width = 18, height = 6)\n# gridExtra::grid.arrange(gg.ds1, gg.ds2, nrow = 1)\n# dev.off()\n# \n# \n# \n# \n# df$celltype = factor(df$celltype, names(colors))\n# # df$sample = droplevels(factor(df$sample, colnames(ncells.freq)[sample.perm]))\n# \n# gg.ds2 = ggbarplot(df, \"sample\", \"freq\",\n# fill = \"celltype\", color = \"black\", palette = colors[levels(df$celltype)], xlab = \"Individual\", ylab = \"Percentage\") + theme(axis.text.x = element_text(face=\"bold\", size=0, angle=90), axis.text.y = element_text(face=\"bold\", size=12, angle=0), axis.title = element_text(face=\"bold\", size=18, angle=0))\n# \n# \n\n\n\n\nX = ncells.freq\ndf = reshape2::melt(X)\ncolnames(df)=c(\"celltype\", \"sample\", \"freq\")\n\ndf$celltype = factor(df$celltype, names(colors))\n\ngg.combined = ggbarplot(df, \"sample\", \"freq\",\n fill = \"celltype\", color = \"black\", palette = colors[levels(df$celltype)], xlab = \"Individual\", ylab = \"Percentage\") + theme(axis.text.x = element_text(face=\"bold\", size=8, angle=90,hjust=0.95,vjust=0.2), axis.text.y = element_text(face=\"bold\", size=12, angle=0), axis.title = element_text(face=\"bold\", size=18, angle=0))\n\npdf(file.path(figures.path, 'celltype_perc_joint.pdf'), width = 16, height = 6)\nprint(gg.combined)\ndev.off()\n\n\n\n\n\nX = ncells.freq[, pb.logcounts$Phenotype[match(colnames(ncells.freq), pb.logcounts$ID)] == \"CON\"]\ndf = reshape2::melt(X)\ncolnames(df)=c(\"celltype\", \"sample\", \"freq\")\n\ndf$celltype = factor(df$celltype, names(colors))\n\ngg.combined = ggbarplot(df, \"sample\", \"freq\",\n fill = \"celltype\", color = \"black\", palette = colors[levels(df$celltype)], xlab = \"Individual\", ylab = \"Percentage\") + theme(axis.text.x = element_text(face=\"bold\", size=8, angle=90,hjust=0.95,vjust=0.2), axis.text.y = element_text(face=\"bold\", size=12, angle=0), axis.title = element_text(face=\"bold\", size=18, angle=0))\n\npdf(file.path(figures.path, 'celltype_perc_CON.pdf'), width = 12, height = 6)\nprint(gg.combined)\ndev.off()\n\n\n\nX = ncells.freq[, pb.logcounts$Phenotype[match(colnames(ncells.freq), pb.logcounts$ID)] == \"SZ\"]\ndf = reshape2::melt(X)\ncolnames(df)=c(\"celltype\", \"sample\", \"freq\")\n\ndf$celltype = factor(df$celltype, names(colors))\n\ngg.combined = ggbarplot(df, \"sample\", \"freq\",\n fill = \"celltype\", color = \"black\", palette = colors[levels(df$celltype)], xlab = \"Individual\", ylab = \"Percentage\") + theme(axis.text.x = element_text(face=\"bold\", size=8, angle=90,hjust=0.95,vjust=0.2), axis.text.y = element_text(face=\"bold\", size=12, angle=0), axis.title = element_text(face=\"bold\", size=18, angle=0))\n\npdf(file.path(figures.path, 'celltype_perc_SZ.pdf'), width = 12, height = 6)\nprint(gg.combined)\ndev.off()\n\n\n\n\n```\n\n# Plot cell type fraction stats per phenotype\n```{r}\nn_cells = table(ACTIONet_summary$metadata$Labels, ACTIONet_summary$metadata$Individual)\n\nX.CON = apply(n_cells[, pb.logcounts$Phenotype == \"CON\"], 2, as.numeric)\nX.SZ = apply(n_cells[, pb.logcounts$Phenotype == \"SZ\"], 2, as.numeric)\nrownames(X.CON) = rownames(X.SZ) = names(assays(pb.logcounts))\n\n\n# wilcox.out = presto::wilcoxauc(cbind(X.CON, X.SZ), c(rep(\"CON\", ncol(X.CON)), rep(\"SZ\", ncol(X.SZ))))\n# wilcox.out = wilcox.out[wilcox.out$group == \"SZ\", ]\n\n\nPerc = t(apply(cbind(Matrix::rowMeans(X.CON), Matrix::rowMeans(X.SZ)), 1, function(x) 100*x / sum(x)))\ncolnames(Perc) = c(\"CON\", \"SZ\")\nPerc = Perc[order(Perc[, 1] - Perc[, 2], decreasing = T), ]\n# df = Perc[wilcox.out$feature[order(-log10(wilcox.out$pval)*sign(wilcox.out$logFC))], ]\ndf = reshape2::melt(Perc)\ncolnames(df) = c(\"Celltype\", \"Phenotype\", \"Perc\")\ndf$Celltype = factor(df$Celltype, names(colors))\n\ngg = ggbarplot(df, \"Celltype\", \"Perc\", fill = \"Phenotype\", palette = c(\"#cccccc\", \"#888888\"))+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1, colour = colors)) + xlab(\"Celltype\") + ylab(\"Percentage\")\n\npdf(file.path(figures.path, \"Celltype_perc_per_phenotype.pdf\"), height = 5, width = 8)\nprint(gg)\ndev.off()\n\n\n\n\n```\n\n\n\n# Plot gene/umi statistics\n## Per cell type\n```{r}\numis = ACTIONet_summary$metadata$umi_count\nmito.perc = ACTIONet_summary$metadata$mito_perc\ngenes = ACTIONet_summary$metadata$gene_counts\ndataset = ACTIONet_summary$metadata$dataset\nindiv = ACTIONet_summary$metadata$Individual\ncelltype = ACTIONet_summary$metadata$Labels\ndf = data.frame(celltype = celltype, umis = umis, genes = genes, mito = mito.perc, dataset = dataset, individual = indiv) \n\ndf = df[df$individual %in% colnames(pb.logcounts)[mask == T], ]\n\ndf$celltype = factor(df$celltype, names(colors))\n\nrequire(ggpubr)\ngg.umis.1 = ggviolin(df[df$dataset == \"McLean\", ], \"celltype\", \"umis\", fill = \"celltype\", palette = colors,\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Celltype\") + ylab(\"UMIs\")+ theme(legend.position = \"none\")\n\npng(file.path(figures.path, \"McLean_UMIs.png\"), width = 1200, height = 600, res = 150)\nprint(gg.umis.1)\ndev.off()\n\ngg.umis.2 = ggviolin(df[df$dataset == \"MtSinai\", ], \"celltype\", \"umis\", fill = \"celltype\", palette = colors,\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Celltype\") + ylab(\"UMIs\")+ theme(legend.position = \"none\")\n\npng(file.path(figures.path, \"MtSinai_UMIs.png\"), width = 1200, height = 600, res = 150)\nprint(gg.umis.2)\ndev.off()\n\n\nrequire(ggpubr)\ngg.genes.1 = ggviolin(df[df$dataset == \"McLean\", ], \"celltype\", \"genes\", fill = \"celltype\", palette = colors,\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Celltype\") + ylab(\"genes\")+ theme(legend.position = \"none\")\n\npng(file.path(figures.path, \"McLean_genes.png\"), width = 1200, height = 600, res = 150)\nprint(gg.genes.1)\ndev.off()\n\ngg.genes.2 = ggviolin(df[df$dataset == \"MtSinai\", ], \"celltype\", \"genes\", fill = \"celltype\", palette = colors,\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Celltype\") + ylab(\"genes\")+ theme(legend.position = \"none\")\n\npng(file.path(figures.path, \"MtSinai_genes.png\"), width = 1200, height = 600, res = 150)\nprint(gg.genes.2)\ndev.off()\n\nrequire(ggpubr)\ngg.mito.1 = ggviolin(df[df$dataset == \"McLean\", ], \"celltype\", \"mito\", fill = \"celltype\", palette = colors,\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Celltype\") + ylab(\"mito\") + ylim(c(0, 10))+ theme(legend.position = \"none\")\n\npng(file.path(figures.path,\"McLean_mito.png\"), width = 1200, height = 600, res = 150)\nprint(gg.mito.1)\ndev.off()\n\ngg.mito.2 = ggviolin(df[df$dataset == \"MtSinai\", ], \"celltype\", \"mito\", fill = \"celltype\", palette = colors,\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Celltype\") + ylab(\"mito\") + ylim(c(0, 10))+ theme(legend.position = \"none\")\n\npng(file.path(figures.path, \"MtSinai_mito.png\"), width = 1200, height = 600, res = 150)\nprint(gg.mito.2)\ndev.off()\n\n```\n\n## Per sample\n```{r}\ndf$individual = factor(as.character(df$individual), as.character(pb.logcounts$ID[order(pb.logcounts$umis, decreasing = T)]))\n\nrequire(ggpubr)\ngg.umis.1 = ggviolin(df[df$dataset == \"McLean\", ], \"individual\", \"umis\", fill = \"individual\", add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Individual\") + ylab(\"UMIs\")+ theme(legend.position = \"none\")\n\n\npng(file.path(figures.path, \"McLean_UMIs_per_sample.png\"), width = 1200, height = 500, res = 150)\nprint(gg.umis.1)\ndev.off()\n\ngg.umis.2 = ggviolin(df[df$dataset == \"MtSinai\", ], \"individual\", \"umis\", fill = \"individual\",\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Celltype\") + ylab(\"UMIs\")+ theme(legend.position = \"none\")\n\npng(file.path(figures.path, \"MtSinai_UMIs_per_sample.png\"), width = 2100, height = 500, res = 150)\nprint(gg.umis.2)\ndev.off()\n\n\n\ndf$individual = factor(as.character(df$individual), as.character(pb.logcounts$ID[order(pb.logcounts$genes, decreasing = T)]))\n\nrequire(ggpubr)\ngg.genes.1 = ggviolin(df[df$dataset == \"McLean\", ], \"individual\", \"genes\", fill = \"individual\",\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Celltype\") + ylab(\"genes\")+ theme(legend.position = \"none\")\n\npng(file.path(figures.path, \"McLean_genes_per_sample.png\"), width = 1200, height = 500, res = 150)\nprint(gg.genes.1)\ndev.off()\n\ngg.genes.2 = ggviolin(df[df$dataset == \"MtSinai\", ], \"individual\", \"genes\", fill = \"individual\",\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Celltype\") + ylab(\"genes\")+ theme(legend.position = \"none\")\n\npng(file.path(figures.path, \"MtSinai_genes_per_sample.png\"), width = 2100, height = 500, res = 150)\nprint(gg.genes.2)\ndev.off()\n\ndf$individual = factor(as.character(df$individual), as.character(pb.logcounts$ID[order(pb.logcounts$mito_perc, decreasing = T)]))\n\nrequire(ggpubr)\ngg.mito.1 = ggviolin(df[df$dataset == \"McLean\", ], \"individual\", \"mito\", fill = \"individual\",\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Celltype\") + ylab(\"mito\")+ theme(legend.position = \"none\") + ylim(c(0, 10))\n\npng(file.path(figures.path,\"McLean_mito_per_sample.png\"), width = 1200, height = 500, res = 150)\nprint(gg.mito.1)\ndev.off()\n\ngg.mito.2 = ggviolin(df[df$dataset == \"MtSinai\", ], \"individual\", \"mito\", fill = \"individual\",\n add = \"boxplot\")+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + xlab(\"Celltype\") + ylab(\"mito\")+ theme(legend.position = \"none\") + ylim(c(0, 10))\n\npng(file.path(figures.path, \"MtSinai_mito_per_sample.png\"), width = 2100, height = 500, res = 150)\nprint(gg.mito.2)\ndev.off()\n\n```\n\n\n# Plot mappings of cell type annotations to other annotations\n## Load markers\n```{r}\ndata(\"curatedMarkers_human\")\nLayers = readRDS(\"~/results/input/Yao_layer_marker.RDS\")\nrdbu_fun = circlize::colorRamp2(c(-3, -1, 0, 1, 3), rev(pals::brewer.rdbu(9)[seq(1, 9, by = 2)]))\n\ncelltype.gene.spec = readRDS(file.path(dataset.path, \"celltype_gene_specificity.rds\"))\n\n```\n\n## Annotate\n### Layers (Maynard et al., 2021)\n```{r}\nX = as(do.call(cbind, lapply(Layers[c(2:7, 1)], function(gs) as.numeric(rownames(pb.logcounts) %in% gs))), \"dgCMatrix\")\nrownames(X) = rownames(pb.logcounts)\nLayer.annot = assess.geneset.enrichment.from.scores(celltype.gene.spec, X)\n\nZ = scale(t(Layer.annot$logPvals))\nrownames(Z) = colnames(celltype.gene.spec)\n# Z = scale(ct.layer.annot$Enrichment)\ncolnames(Z) = c(paste(\"L\", c(1:6), sep = \"\"), \"WM\")\n\npdf(file.path(figures.path, \"annotations\", \"Layer_annotation_Maynard.pdf\"), width = 4)\nHeatmap(Z, cluster_rows = F, cluster_columns = F, rect_gp = gpar(col = \"black\"), row_names_side = \"left\", row_names_gp = gpar(col = colors), col = rdbu_fun, name = \"Layer\", column_title = \"Layer (Maynard et al.)\")\ndev.off()\n```\n\n### Cell types (Mohammadi et al., 2019)\n```{r}\n\nX = as(do.call(cbind, lapply(curatedMarkers_human$Brain$PFC$Mohammadi2020$marker.genes, function(gs) as.numeric(rownames(pb.logcounts) %in% gs))), \"dgCMatrix\")\nrownames(X) = rownames(pb.logcounts)\nCelltype.annot = assess.geneset.enrichment.from.scores(celltype.gene.spec, X)\n\nZ = scale(t(Celltype.annot$logPvals))\nrownames(Z) = colnames(celltype.gene.spec)\n\n\nM = as(t(MWM_hungarian(t(Celltype.annot$logPvals))), \"dgTMatrix\")\n\npdf(file.path(figures.path, \"annotations\", \"celltype_annotation_mohammadi_markers.pdf\"), width = 6)\nHeatmap(Z[, M@i+1], cluster_rows = F, cluster_columns = F, rect_gp = gpar(col = \"black\"), row_names_side = \"left\", row_names_gp = gpar(col = colors), col = rdbu_fun, name = \"Celltypes\", column_title = \"Celltypes (Mohammadi et al.)\")\ndev.off()\n\n```\n\n### Cell types (Velmeshev et al., 2019)\n```{r}\nX = as(do.call(cbind, lapply(curatedMarkers_human$Brain$PFC$Velmeshev2019$marker.genes, function(gs) as.numeric(rownames(pb.logcounts) %in% gs))), \"dgCMatrix\")\nrownames(X) = rownames(pb.logcounts)\nCelltype.annot = assess.geneset.enrichment.from.scores(celltype.gene.spec, X)\n\n\n\nZ = scale(t(Celltype.annot$logPvals))\nrownames(Z) = colnames(celltype.gene.spec)\n\n\nM = as(t(MWM_hungarian(t(Celltype.annot$logPvals))), \"dgTMatrix\")\n\n\npdf(file.path(figures.path, \"annotations\", \"celltype_annotation_velmeshev_markers.pdf\"), width = 8)\nHeatmap(Z[, M@i+1], cluster_rows = F, cluster_columns = F, rect_gp = gpar(col = \"black\"), row_names_side = \"left\", row_names_gp = gpar(col = colors), col = rdbu_fun, name = \"Celltypes\", column_title = \"Celltypes (Velmeshev et al.)\")\ndev.off()\n```\n### Cell types (Mathys et al., 2019)\n```{r}\nX = as(do.call(cbind, lapply(curatedMarkers_human$Brain$PFC$MathysDavila2019$marker.genes, function(gs) as.numeric(rownames(pb.logcounts) %in% gs))), \"dgCMatrix\")\nrownames(X) = rownames(pb.logcounts)\nCelltype.annot = assess.geneset.enrichment.from.scores(celltype.gene.spec, X)\n\n\n\nZ = scale(t(Celltype.annot$logPvals))\nrownames(Z) = colnames(celltype.gene.spec)\n\n\nM = as(t(MWM_hungarian(t(Celltype.annot$logPvals))), \"dgTMatrix\")\n\n\npdf(file.path(figures.path, \"annotations\", \"celltype_annotation_mathys_markers.pdf\"), width = 8)\nHeatmap(Z[, M@i+1], cluster_rows = F, cluster_columns = F, rect_gp = gpar(col = \"black\"), row_names_side = \"left\", row_names_gp = gpar(col = colors), col = rdbu_fun, name = \"Celltypes\", column_title = \"Celltypes (Mathys and Davilla et al.)\")\ndev.off()\n\n```\n## Bulk Layers (He et al., 2017)\n```{r}\nX = as(do.call(cbind, lapply(curatedMarkers_human$Brain$Layers$marker.genes, function(gs) as.numeric(rownames(pb.logcounts) %in% gs))), \"dgCMatrix\")\nrownames(X) = rownames(pb.logcounts)\nCelltype.annot = assess.geneset.enrichment.from.scores(celltype.gene.spec, X)\n\n\n\nZ = scale(t(Celltype.annot$logPvals))\nrownames(Z) = colnames(celltype.gene.spec)\n\n\npdf(file.path(figures.path, \"annotations\", \"Layer_annotation_He_markers.pdf\"), width = 4)\nHeatmap(Z, cluster_rows = F, cluster_columns = F, rect_gp = gpar(col = \"black\"), row_names_side = \"left\", row_names_gp = gpar(col = colors), col = rdbu_fun, name = \"Layers\", column_title = \"Layers (He et al.)\")\ndev.off()\n```\n\n\n```{r}\nLabels.idx = split(1:nrow(ACTIONet_summary$metadata), ACTIONet_summary$metadata$Labels)\nInd.idx = split(1:nrow(ACTIONet_summary$metadata), ACTIONet_summary$metadata$Individual)\n\n\nEn = assess.genesets(Ind.idx, Labels.idx, nrow(ACTIONet_summary$metadata), correct = \"local\")\nEn[is.na(En)] = 0\nEn[is.infinite(En)] = max(En[!is.infinite((En))])\n\nX = En\nX[X < -log10(0.05)] = 0\n\n\npdf(file.path(figures.path, \"Sample_vs_celltype_enrichment_heatmap.pdf\"), width = 7, height = 28)\nHeatmap(X, rect_gp = gpar(col = \"black\"), col = blues9)\ndev.off()\n\n\n\n```\n\n\n\n\n" }, { "alpha_fraction": 0.6639304757118225, "alphanum_fraction": 0.6716561913490295, "avg_line_length": 27.383562088012695, "blob_id": "a90437311eaf2148785acf987aa1eddf19c65591", "content_id": "a0c9ad8413396426b3dac8516ec898bf1c6c5021", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 2071, "license_type": "no_license", "max_line_length": 147, "num_lines": 73, "path": "/old/export_ACTIONet.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"R Notebook\"\noutput: html_notebook\n---\n\n\n```{r}\n CD = as.data.frame(colData(ace.filtered))\n \n\n\n Celltypes = factor(color.df$celltype[match(ace.filtered$Labels.final, color.df$old.celltype)], color.df$celltype)\n Colors = colors[Celltypes]\n \n idx = match(ace.filtered$Individual, pb.logcounts$Internal_ID)\n ind.meta = as.data.frame(colData(pb.logcounts))[, -c(23:36, 39:45)]\n ind.cells = ind.meta[idx, ]\n ind.cells$Celltype = Celltypes\n ind.cells$Color = Colors\n \n S = counts(ace.filtered)\n umis = fast_column_sums(S)\n mt.idx = grep(\"MT-|MT[:.:]\", rownames(ace.filtered))\n mt.sum = fast_column_sums(S[mt.idx, ])\n mt.perc = 100*mt.sum/umis\n S@x = rep(1, length(S@x))\n genes = fast_column_sums(S)\n \n ind.cells$umis = umis\n ind.cells$genes = genes\n ind.cells$mito.perc = mt.perc\n \n \n ind.cells = cbind(ind.cells, CD[, c(\"assigned_archetype\", \"node_centrality\")])\n ind.cells = ind.cells[, -1]\n \n ind.cells = cbind(CD[, c(\"Id\", \"sizeFactors\")], ind.cells)\n ace = ace.filtered\n rownames(ind.cells) = colnames(ace)\n\n readr::write_rds(ind.cells, \"~/results/cell_meta.rds\")\n \n colData(ace) = DataFrame(ind.cells)\n sce = revert_ace_as_sce(ace) \n se = as(sce, \"SummarizedExperiment\")\n se.ace = as(se, \"ACTIONetExperiment\")\n \n readr::write_rds(se, \"~/results/combinedCells.rds\")\n readr::write_rds(ace, \"~/results/combinedCells_ACTIONet.rds\")\n ACE2AnnData(se.ace, \"~/results/combinedCells.h5ad\")\n \n \n\n\tfolder = Syn.datasets$properties$id\n\tOBJ = File(\"~/results/datasets/ACTIONet_summary_filtered_individuals.rds\", name = \"Summarized fields from the ACTIONet object\", parentId = folder)\n\tsynStore(OBJ)\t\n\t\n\tOBJ = File(\"~/results/combinedCells_ACTIONet.rds\", name = \"Combined cells (ACTIONet)\", parentId = folder)\n\tsynStore(OBJ)\n \n\tOBJ = File(\"~/results/combinedCells.rds\", name = \"Combined cells (SummarizedExperiment)\", parentId = folder)\n\tsynStore(OBJ)\n\n\tOBJ = File(\"~/results/combinedCells.h5ad\", name = \"Combined cells (AnnData)\", parentId = folder)\n\tsynStore(OBJ)\n\t \n \n \n\n \n sce = revert_ace_as_sce(ace.filtered)\n\n```" }, { "alpha_fraction": 0.6273576617240906, "alphanum_fraction": 0.6487219929695129, "avg_line_length": 32.291080474853516, "blob_id": "798f794316f4ed29cf8691d60607183efa72738d", "content_id": "9a505c1dc049fe33aca924396d1e4072d2e02bd9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 28368, "license_type": "no_license", "max_line_length": 710, "num_lines": 852, "path": "/ancient/Fig2_ChEA.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"ChEA Analyze of DE genes\"\noutput: html_notebook\n---\n\n# Setup\n```{r include=FALSE}\nrequire(ACTIONet)\nrequire(stringr)\nrequire(ComplexHeatmap)\n\n\ndataset.path = \"~/results/datasets/\"\nresults.path = \"~/results\"\nfigures.folder = \"~/results/figures\"\ninput.folder = \"~/results/input\"\n\n\n```\n\n\n## Enrichment function\n```{r}\nassess.genesets <-function (arch.gs, terms.gs, N, min.pval = 1e-100, correct = \"none\"){\n shared = t(sapply(terms.gs, function(gs1) {\n sapply(arch.gs, function(gs2) {\n nn = intersect(gs1, gs2)\n })\n }))\n colnames(shared) = names(arch.gs)\n GS.sizes = sapply(terms.gs, length)\n logPvals.out = sapply(1:ncol(shared), function(i) {\n gg = shared[, i]\n x = as.numeric(sapply(gg, length))\n n.sample = length(arch.gs[[i]])\n n.success = as.numeric(GS.sizes)\n v = rep(1, length(x))\n min.overlap = n.success * n.sample/N\n idx = which(x >= min.overlap)\n if (length(idx) == 0) \n return(v)\n v[idx] = (phyper(x[idx]-1, n.sample, N-n.sample, n.success[idx], lower.tail = F))\n # v[idx] = HGT_tail(population.size = N, success.count = n.success[idx], \n # sample.size = n.sample, observed.success = x[idx])\n return(v)\n })\n if(correct == \"global\") {\n logPvals.out = matrix(p.adjust(logPvals.out, \"fdr\"), nrow = nrow(logPvals.out))\n } else if(correct == \"local\") {\n logPvals.out = apply(logPvals.out, 2, function(x) p.adjust(x, \"fdr\"))\n }\n rownames(logPvals.out) = names(terms.gs)\n colnames(logPvals.out) = names(arch.gs)\n return(-log10(Matrix::t(logPvals.out)))\n}\n```\n\n# Load primary datasets\n```{r, eval = T}\nACTIONet_summary = readr::read_rds(file.path(dataset.path, \"ACTIONet_summary_filtered_individuals.rds\"))\n\npb.logcounts = readr::read_rds(file.path(dataset.path, \"PB_mean_logcounts_final.RDS\"))\n\ncolor.df = readRDS(file.path(dataset.path, \"celltype_colors.rds\"))\n\ncolors = color.df$color\nnames(colors) = color.df$celltype\n\n```\n\n# Load DE results\n```{r, eval = F}\nresDE = readr::read_rds(file.path(dataset.path, \"Cohort_specific_DE_results_final_with_logumi_baseline_full_filter_extended_cell_filtering.rds\"))\n\nfiltered.tables = readr::read_rds(file.path(dataset.path, \"individual_diff_results_filtered_full_with_logumi_baseline_full_filter_extended_cell_filtering.rds\"))\n\nDE.new = readRDS(file.path(dataset.path, \"DE_genes_pseudobulk_final_with_logumi_baseline_full_filter_extended_cell_filtering.rds\"))\n\nUp.genes = DE.new$Up.genes\nDown.genes = DE.new$Down.genes\n\n```\n\n\n\n\n## Use ChEA3 REST API\n```{r}\nlibrary(httr)\nlibrary(jsonlite)\n\nqueryChEA3 <- function(genes, url = \"https://maayanlab.cloud/chea3/api/enrich/\") {\n\n encode = \"json\"\n payload = list(query_name = \"myQuery\", gene_set = genes)\n \n #POST to ChEA3 server\n response = POST(url = url, body = payload, encode = encode)\n json = content(response, \"text\")\n \n #results as list of R dataframes\n results = fromJSON(json)\n}\n\n\nChEA3.Up = lapply(Up.genes, function(genes) {\n if(length(genes) > 10)\n queryChEA3(genes)\n})\n\nChEA3.Down = lapply(Down.genes, function(genes) {\n if(length(genes) > 10)\n queryChEA3(genes)\n})\n\n\nnames(ChEA3.Up) = paste(\"Up\", names(Up.genes), sep = \"_\")\nnames(ChEA3.Down) = paste(\"Down\", names(Down.genes), sep = \"_\")\n\nChEA.analysis = c(ChEA3.Up, ChEA3.Down)\nsaveRDS(ChEA.analysis, file = file.path(dataset.path, \"ChEA_DE_TF_enrichment_meta_filtered_with_logumi_baseline_full_filter_extended_cell_filtering.RDS\"))\n# \n# X = readRDS(\"~/PFC_v3/ChEA_DE_TF_enrichment_meta_filtered.RDS\")\n\n\n\n```\n\n\n```{r}\nChEA.analysis = readRDS(file.path(dataset.path, \"ChEA_DE_TF_enrichment_meta_filtered_with_logumi_baseline_full_filter_extended_cell_filtering.RDS\"))\n\nChEA3.Up = ChEA.analysis[grep(\"Up\", names(ChEA.analysis))]\nChEA3.Down = ChEA.analysis[grep(\"Down\", names(ChEA.analysis))]\n\nnames(ChEA3.Up) = names(ChEA3.Down) = names(Up.genes)\n\n\n```\n\n\n## Export as excel tables\n```{r}\nlibrary(openxlsx)\nUp.wb <- createWorkbook()\nfor(i in 1:length(ChEA3.Up)) {\n res = ChEA.analysis[[i]]\n if(is.null(res)) {\n next\n }\n \n X = res$`Integrated--topRank`\n \n X$Score = -log10(as.numeric(X$Score))\n X$Rank = as.numeric(X$Rank)\n X = X[, -c(1, 2, 5)]\n \n # X$hasGWAS = as.numeric(X$TF %in% SZ.genes$`GWAS (Pardiñas)`)\n # X$hasDenovo = as.numeric(X$TF %in% SZ.genes$`De Novo`)\n # \n \n n = names(ChEA3.Up)[[i]] #str_replace(arch.names[arch.order[i]], \"/\", \"-\")\n\n addWorksheet(wb=Up.wb, sheetName = n)\n writeData(Up.wb, sheet = n, X) \n\n}\n\nsaveWorkbook(Up.wb, file.path(dataset.path, \"Enriched_TFs_Up_topRank_meta_filtered_with_logumi_baseline_full_filter_extended_cell_filtering.xlsx\"), overwrite = TRUE)\n\n\nlibrary(openxlsx)\nDown.wb <- createWorkbook()\nfor(i in (length(ChEA3.Up)+1):(length(ChEA3.Up)+length(ChEA3.Down))) {\n res = ChEA.analysis[[i]]\n if(is.null(res)) {\n next\n }\n \n X = res$`Integrated--topRank`\n \n X$Score = -log10(as.numeric(X$Score))\n X$Rank = as.numeric(X$Rank)\n X = X[, -c(1, 2, 5)]\n \n # X$hasGWAS = as.numeric(X$TF %in% SZ.genes$`GWAS (Pardiñas)`)\n # X$hasDenovo = as.numeric(X$TF %in% SZ.genes$`De Novo`)\n # \n \n n = names(ChEA3.Down)[[i-length(ChEA3.Up)]] #str_replace(arch.names[arch.order[i]], \"/\", \"-\")\n \n addWorksheet(wb=Down.wb, sheetName = n)\n writeData(Down.wb, sheet = n, X) \n\n}\n\nsaveWorkbook(Down.wb, file.path(dataset.path, \"Enriched_TFs_Down_topRank_meta_filtered_with_logumi_baseline_full_filter_extended_cell_filtering.xlsx\"), overwrite = TRUE)\n\n\n```\n\n\n```{r}\nTFs = sort(unique(ChEA.analysis$Up_Ast$`Integrated--topRank`$TF))\n\n\nTF.up = matrix(0, nrow = length(TFs), length(ChEA3.Up))\nrownames(TF.up) = TFs\ncolnames(TF.up) = names(ChEA3.Up)\nfor(i in 1:length(ChEA3.Up)) {\n res = ChEA.analysis[[i]]\n if(is.null(res)) {\n next\n }\n \n X = res$`Integrated--topRank`\n \n TF.up[match(X$TF, TFs), i] = -log10(as.numeric(X$Score))\n}\n\n\n\n\nTF.down = matrix(0, nrow = length(TFs), length(ChEA3.Down))\nrownames(TF.down) = TFs\ncolnames(TF.down) = names(ChEA3.Down)\nfor(i in (length(ChEA3.Up)+1):(length(ChEA3.Up)+length(ChEA3.Down))) {\n res = ChEA.analysis[[i]]\n if(is.null(res)) {\n next\n }\n \n X = res$`Integrated--topRank`\n \n TF.down[match(X$TF, TFs), i-length(ChEA3.Up)-1] = -log10(as.numeric(X$Score))\n}\n\nTFs = sort(unique(ChEA.analysis$Up_Ast$`Integrated--topRank`$TF))\n\nTF.mean.scores = apply(cbind(TF.down[, 1:17], TF.up[, 1:17]), 1, mean)\nnames(TF.mean.scores) = rownames(TF.down)\n\n\n```\n\n\n\n## Load significant variants and mapped genes\n```{r}\nPGC3.loci = read.table(file.path(input.folder, \"PGC3_SZ_significant_loci.csv\"), sep = \"\\t\", header = T)\n\nassociated.genes = PGC3.loci$ENSEMBL.genes..all..clear.names.\n\n\nPGC3.all.genes.raw = sort(unique(unlist(sapply(PGC3.loci$ENSEMBL.genes..all..clear.names., function(str) {\n if(str == \"-\") {\n return(\"-\")\n }\n gs = str_split(str, \",\")[[1]]\n \n return(gs)\n}))))\n\nPGC3.all.genes = intersect(PGC3.all.genes.raw, rownames(pb.logcounts))\n\n\n\n```\n\n\n```{r}\nFunCat = readRDS(\"~/FunCat.rds\")\nFunCat.genes = split(FunCat$FunCat2Gene$Gene, factor(FunCat$FunCat2Gene$Category, unique(FunCat$FunCat2Gene$Category)))[-15]\nnames(FunCat.genes) = FunCat$FunCat2Class$Category\n\nFunCat.annotation = FunCat$FunCat2Class$Classification\n\nFunCatPal = ggpubr::get_palette(\"npg\", length(unique(FunCat.annotation)))\nnames(FunCatPal) = unique(FunCat.annotation)\n\n```\n\n\n```{r}\nncells = sapply(int_colData(pb.logcounts)$n_cells, as.numeric)\nrownames(ncells) = names(assays(pb.logcounts))\n\ncs = Matrix::colSums(ncells)\nncells.freq = 100*scale(ncells, center = F, scale = cs)\nEx.perc = (fast_column_sums(ncells.freq[grepl(\"^Ex\", rownames(ncells.freq)) & !grepl(\"^Ex-NRGN\", rownames(ncells.freq)), ]))\n\nmask = (Ex.perc >= 10) & (Ex.perc <= 80) #& (fast_column_sums(ncells) >= 500)\n\n\n# mask = !(pb.logcounts$ID %in% c(\"SZ15\"))\n# Samples that are depleted in Ex.perc:: \n# # SZ15 0.2570694\n# # SZ3 2.8237585\n# # SZ24 3.7128713\n# # SZ29 7.5571178\n\npb.logcounts.filtered = pb.logcounts [, mask]\n# metadata(pb.logcounts.filtered)$n_cells = metadata(pb.logcounts.filtered)$n_cells[, mask]\n```\n\n```{r}\n# cts = names(assays(pb.logcounts.filtered))\ncts = names(DE.new$Up.genes)\n# #cts = names(assays(pb.logcounts.filtered))\ncts = cts[grep(\"^Ex|^In\", cts)]\n \nsubTFs = intersect(TFs, rownames(pb.logcounts))\nPB.logcounts.combined = lapply(cts, function(nn) {\n print(nn)\n E = assays(pb.logcounts.filtered)[[nn]]\n cs = Matrix::colSums(E)\n mask = (cs > 0)\n E = E[, mask]\n E = median(cs[mask])*scale(E, center = F, scale = cs[mask])\n # E.orth = orthoProject(E, Matrix::rowMeans(E))\n \n CC = cor(Matrix::t(E[subTFs, ]), use = \"p\")\n CC[is.na(CC)] = 0\n\n return(CC)\n})\nCC.mean = Reduce(\"+\", PB.logcounts.combined) / length(PB.logcounts.combined)\n\n```\n\n\n\n```{r}\nadj = CC.mean\n# data(\"PCNet\")\n# adj[adj < 0] = 0\n# common.genes = intersect(rownames(PCNet), rownames(adj))\n# adj = adj[common.genes, common.genes] * PCNet[common.genes, common.genes]\n# adj = EnhAdj(adj)\n# rownames(adj) = colnames(adj) = common.genes\n\ncl = cluster.graph(adj, 0.1)\ncc = table(cl)\nTF.mods = split(rownames(adj), cl)\nTF.mods = TF.mods[as.numeric(names(cc)[cc>=5])]\nTF.mods = lapply(TF.mods, function(gs) sort(gs))\n\nperm = order(sapply(TF.mods, function(gs) mean(TF.mean.scores[gs])), decreasing = T)\nTF.mods = TF.mods[perm]\n\nnames(TF.mods) = 1:length(TF.mods)\n\n# data(\"gProfilerDB_human\")\n# BP = gProfilerDB_human$SYMBOL$`GO:BP`\n# cs = fast_column_sums(BP)\n# BP = BP[, (cs >= 10) & (cs <= 1000)]\n# BP.gs = apply(BP, 2, function(x) rownames(BP)[x > 0])\n\nFunCat.TFs = lapply(FunCat.genes, function(gs) intersect(TFs, gs))\nTF.enrichment = assess.genesets(FunCat.TFs, TF.mods, length(TFs), \"local\")\nTF.enrichment = TF.enrichment[, fast_column_sums(TF.enrichment) > 1]\n# Heatmap((TF.enrichment))\n\nHeatmap(doubleNorm(TF.enrichment))\n\n```\n\n```{r}\n\n\n\n\n\n\n# sorted.TFs = unlist(lapply(TF.mods, function(x) x[order(TF.mean.scores[x], decreasing = T]))\n\n\n# sorted.TFs = unlist(lapply(TF.mods[1:5], function(x) x[order(TF.mean.scores[x], decreasing = T)]))\n# \n# mask = sorted.TFs %in% PGC3.all.genes\n# TF.colors = rep(\"black\", length(sorted.TFs))\n# TF.colors[mask] = \"red\"\n# \n# ww = CC.mean[sorted.TFs, sorted.TFs]\n# diag(ww) = NA\n# MPal = pals::brewer.dark2(5)\n# names(MPal) = paste(\"M\", 1:5, sep = \"\")\n# ha_row = rowAnnotation(Module = factor(unlist(lapply(1:5, function(i) paste(\"M\", rep(i, length(TF.mods[[i]])), sep = \"\"))), paste(\"M\", 1:5, sep = \"\")), col = list(Module = MPal))\n# pdf(file.path(figures.folder, \"TF_modules_top5_tmp.pdf\"), width = 18, height = 12)\n# Heatmap(ww, row_names_side = \"left\", name = \"Correlation\", row_names_gp = gpar(col = TF.colors), column_title = \"TF-TF expression correlation\", column_title_gp = gpar(fontsize = 21), cluster_rows = F, cluster_columns = F, left_annotation = ha_row) + Heatmap(TF.up[sorted.TFs, ], rect_gp = gpar(col = \"black\"), cluster_columns = F, column_title = \"Up\", column_title_gp = gpar(fontsize = 21), column_names_gp = gpar(col = colors[colnames(TF.up)]), name = \"Up\") + Heatmap(TF.down[sorted.TFs, ], rect_gp = gpar(col = \"black\"), cluster_columns = F, column_title = \"Down\", column_title_gp = gpar(fontsize = 21), column_names_gp = gpar(col = colors[colnames(TF.down)]), name = \"Down\", row_names_side = \"left\")\n# dev.off()\n\n\nsorted.TFs = unlist(lapply(TF.mods, function(x) x[order(TF.mean.scores[x], decreasing = T)]))\n\nmask = sorted.TFs %in% PGC3.all.genes\nTF.colors = rep(\"black\", length(sorted.TFs))\nTF.colors[mask] = \"red\"\n\nww = CC.mean[sorted.TFs, sorted.TFs]\ndiag(ww) = NA\nMPal = pals::polychrome(length(TF.mods))\nnames(MPal) = paste(\"M\", 1:length(TF.mods), sep = \"\")\nha_row = rowAnnotation(Module = factor(unlist(lapply(1:length(TF.mods), function(i) paste(\"M\", rep(i, length(TF.mods[[i]])), sep = \"\"))), paste(\"M\", 1:length(TF.mods), sep = \"\")), col = list(Module = MPal))\npdf(file.path(figures.folder, \"TF_modules_all_tmp.pdf\"), width = 42, height = 36)\nHeatmap(ww, row_names_side = \"left\", name = \"Correlation\", row_names_gp = gpar(col = TF.colors), column_title = \"TF-TF expression correlation\", column_title_gp = gpar(fontsize = 21), cluster_rows = F, cluster_columns = F, left_annotation = ha_row) + Heatmap(TF.up[sorted.TFs, ], rect_gp = gpar(col = \"black\"), cluster_columns = F, column_title = \"Up\", column_title_gp = gpar(fontsize = 21), column_names_gp = gpar(col = colors[colnames(TF.up)]), name = \"Up\") + Heatmap(TF.down[sorted.TFs, ], rect_gp = gpar(col = \"black\"), cluster_columns = F, column_title = \"Down\", column_title_gp = gpar(fontsize = 21), column_names_gp = gpar(col = colors[colnames(TF.down)]), name = \"Down\", row_names_side = \"left\")\ndev.off()\n\n\n\n\n```\n\n\n\n\n\n```{r}\nsorted.TFs = unlist(lapply(TF.mods[1:5], function(x) x[order(TF.mean.scores[x], decreasing = T)]))\n\nmask = sorted.TFs %in% PGC3.all.genes\nTF.colors = rep(\"black\", length(sorted.TFs))\nTF.colors[mask] = \"red\"\n\nww = CC.mean[sorted.TFs, sorted.TFs]\ndiag(ww) = NA\nMPal = pals::brewer.dark2(5)\nnames(MPal) = paste(\"M\", 1:5, sep = \"\")\nha_row = rowAnnotation(Module = factor(unlist(lapply(1:5, function(i) paste(\"M\", rep(i, length(TF.mods[[i]])), sep = \"\"))), paste(\"M\", 1:5, sep = \"\")), col = list(Module = MPal))\npdf(file.path(figures.folder, \"TF_modules_top5_neuro.pdf\"), width = 18, height = 12)\nHeatmap(ww, row_names_side = \"left\", name = \"Correlation\", row_names_gp = gpar(col = TF.colors), column_title = \"TF-TF expression correlation\", column_title_gp = gpar(fontsize = 21), cluster_rows = F, cluster_columns = F, left_annotation = ha_row) + Heatmap(TF.up[sorted.TFs, 1:17], rect_gp = gpar(col = \"black\"), cluster_columns = F, column_title = \"Up\", column_title_gp = gpar(fontsize = 21), column_names_gp = gpar(col = colors[colnames(TF.up)]), name = \"Up\") + Heatmap(TF.down[sorted.TFs, 1:17], rect_gp = gpar(col = \"black\"), cluster_columns = F, column_title = \"Down\", column_title_gp = gpar(fontsize = 21), column_names_gp = gpar(col = colors[colnames(TF.down)]), name = \"Down\", row_names_side = \"left\")\ndev.off()\n\n\nsorted.TFs = unlist(lapply(TF.mods, function(x) x[order(TF.mean.scores[x], decreasing = T)]))\n\nmask = sorted.TFs %in% PGC3.all.genes\nTF.colors = rep(\"black\", length(sorted.TFs))\nTF.colors[mask] = \"red\"\n\nww = CC.mean[sorted.TFs, sorted.TFs]\ndiag(ww) = NA\nMPal = pals::polychrome(length(TF.mods))\nnames(MPal) = paste(\"M\", 1:length(TF.mods), sep = \"\")\nha_row = rowAnnotation(Module = factor(unlist(lapply(1:length(TF.mods), function(i) paste(\"M\", rep(i, length(TF.mods[[i]])), sep = \"\"))), paste(\"M\", 1:length(TF.mods), sep = \"\")), col = list(Module = MPal))\npdf(file.path(figures.folder, \"TF_modules_all_neuro.pdf\"), width = 42, height = 36)\nHeatmap(ww, row_names_side = \"left\", name = \"Correlation\", row_names_gp = gpar(col = TF.colors), column_title = \"TF-TF expression correlation\", column_title_gp = gpar(fontsize = 21), cluster_rows = F, cluster_columns = F, left_annotation = ha_row) + Heatmap(TF.up[sorted.TFs, 1:17], rect_gp = gpar(col = \"black\"), cluster_columns = F, column_title = \"Up\", column_title_gp = gpar(fontsize = 21), column_names_gp = gpar(col = colors[colnames(TF.up)]), name = \"Up\") + Heatmap(TF.down[sorted.TFs, 1:17], rect_gp = gpar(col = \"black\"), cluster_columns = F, column_title = \"Down\", column_title_gp = gpar(fontsize = 21), column_names_gp = gpar(col = colors[colnames(TF.down)]), name = \"Down\", row_names_side = \"left\")\ndev.off()\n\n```\n\n\n```{r}\n\n\nsub.W = CC.mean[TF.mods[[1]], TF.mods[[1]]]\ndiag(sub.W) = NA\nHeatmap(sub.W, col = blues9)\n\nHeatmap(as.matrix(TF.mean.scores[TF.mods[[1]]]), name = \"Max ChEA score\") + Heatmap(TF.up[TF.mods[[1]], ], rect_gp = gpar(col = \"black\"), cluster_columns = F, column_title = \"Up\", column_names_gp = gpar(col = colors[colnames(TF.up)]), name = \"Up\") + Heatmap(TF.down[TF.mods[[1]], ], rect_gp = gpar(col = \"black\"), cluster_columns = F, column_title = \"Down\", column_names_gp = gpar(col = colors[colnames(TF.down)]), name = \"Down\") + Heatmap(sub.W, cluster_columns = F, cluster_rows = F)\n\n\nD = (1 - CC.mean)/2\nrequire(NetLibR)\npc.out = PCSF(as(D, \"sparseMatrix\"), TF.mean.scores, kappa = 1e-5)\nx = pc.out + t(pc.out)\ngg = graph_from_adjacency_matrix(x, mode = \"undirected\", weighted = T)\ncomponents(gg) \n\n\nW = abs(CC.mean)^6\n\n\ncl = cluster.graph(W)\ncc = table(cl)\nTF.mods = split(rownames(CC.mean), cl)\nTF.mods = TF.mods[as.numeric(names(cc)[cc>=5])]\nTF.mods[[1]]\n\nrownames(CC.mean)\n\n\npdf(\"~/results/figures/TFs_avg.pdf\", width = 21, height = 21)\n# Heatmap(abs(CC.mean)^6, rect_gp = gpar(col = \"black\"))\nHeatmap(CC.mean[neurodev.top.TFs, neurodev.top.TFs], rect_gp = gpar(col = \"black\"))\ndev.off()\n\nW = abs(CC.mean)^6\n\npdf(\"~/results/figures/TFs_avg_full_ortho.pdf\", width = 21, height = 21)\nHeatmap(CC.mean, show_row_dend = F, show_column_dend = F, show_row_names = F, show_column_names = F)\ndev.off()\n\n\n\n\n\nCC.mean[is.na(CC.mean)] = 0\ncl = cluster.graph(CC.mean)\nIDX = split(rownames(CC.mean), cl)\n\n\nPB.logcounts.combined = do.call(cbind, lapply(cts, function(nn) {\n E = assays(pb.logcounts.filtered)[[nn]]\n cs = Matrix::colSums(E)\n mask = (cs > 0)\n E = E[, mask]\n E = median(cs[mask])*scale(E, center = F, scale = cs[mask])\n}))\nPB.logcounts.combined[is.na(PB.logcounts.combined)] = 0\n\nlibrary(preprocessCore)\n# PB.logcounts.combined <- normalize.quantiles(PB.logcounts.combined, copy = TRUE)\nrownames(PB.logcounts.combined) = rownames(pb.logcounts.filtered)\n\n# CC = cor(Matrix::t(PB.logcounts.combined[neurodev.top.TFs, ]), use = \"p\")\nCC = abs(cor(Matrix::t(PB.logcounts.combined[neurodev.top.TFs, ]), use = \"p\"))^6\n# CC = EnhAdj(CC)\n# CC = EnhAdj(CC)\n# CC[abs(CC) < 0.5] = 0\n\ncl = cluster.graph(CC, resolution_parameter = 0.1)\nRegulons = sapply(split(neurodev.top.TFs, cl)[1:5], sort)\nprint(Regulons)\n\nperm = get_order(seriate(as.dist(1-CC/(max(abs(CC)))), \"OLO\"))\ndiag(CC) = NA\n\npdf(\"~/PFC_v3/figures/regulons.pdf\", width = 12, height = 12)\nHeatmap(CC[perm, perm], cluster_rows = F, cluster_columns = F)\ndev.off()\n\n\nSATB2.module = Regulons[[1]]\n\n```\n\n\n\n```{r}\n\n\nTGs.up = vector(\"list\", length(TFs))\nnames(TGs.up) = TFs\n\nfor(i in 1:length(ChEA3.Up)) {\n res = ChEA.analysis[[i]]\n if(is.null(res)) {\n next\n }\n \n X = res$`Integrated--topRank`\n for(j in 1:nrow(X)) {\n TGs.up[[X$TF[[j]]]] = union(TGs.up[[X$TF[[j]]]], str_split(X$Overlapping_Genes[[j]], \",\")[[1]])\n }\n}\n\ngg = sapply(TGs.up, length)\nTGs.up = TGs.up[scale(gg) > 1]\nadj = assess.genesets(TGs.up, TGs.up, length(TFs))\ncl = cluster.graph(adj, 2)\ncc = table(cl)\nlapply(as.numeric(names(cc)[cc > 5]), function(i) sort(rownames(adj)[cl == i]))\n\nTF.down = matrix(0, nrow = length(TFs), length(ChEA3.Down))\nrownames(TF.down) = TFs\ncolnames(TF.down) = names(ChEA3.Down)\nfor(i in (length(ChEA3.Up)+1):(length(ChEA3.Up)+length(ChEA3.Down))) {\n res = ChEA.analysis[[i]]\n if(is.null(res)) {\n next\n }\n \n X = res$`Integrated--topRank`\n \n TF.down[match(X$TF, TFs), i-length(ChEA3.Up)-1] = -log10(as.numeric(X$Score))\n}\n```\n\n\n\n```{r}\n# GWAS.TFs = intersect(SZ.genes$`GWAS (Pardiñas)`, rownames(TF.down))\nGWAS.TFs = intersect(PGC3.all.genes, rownames(TF.down))\n\nXd = TF.down[GWAS.TFs, grep(\"Ex\", colnames(TF.down))]\nXd[Xd < 2] = 0\nXd = Xd[fast_row_sums(Xd) > 0, ]\n\n# Xd = (max(TF.down) - t(TF.down[GWAS.TFs, ]+1)) / (max(TF.down) - min(TF.down))\n# Xd = Xd[grep(\"Ex\", rownames(Xd)), ]\n# pdf(\"~/PFC_v3/TF_GWAS_down_PGC3.pdf\", width = 10, height = 4)\nHeatmap(Xd, rect_gp = gpar(col = \"black\"), name = \"Enrichment\")\n# dev.off()\n\n\nXu = TF.up[GWAS.TFs, grep(\"Ex\", colnames(TF.up))]\nXu[Xu < 2] = 0\nXu = Xu[fast_row_sums(Xu) > 0, ]\n# Xu = (max(TF.up) - t(TF.up[GWAS.TFs, ]+1)) / (max(TF.up) - min(TF.up))\n# Xu = Xu[grep(\"Ex\", rownames(Xd)), ]\n# pdf(\"~/PFC_v3/TF_GWAS_up_PGC3.pdf\", width = 10, height = 4)\nHeatmap(Xu, rect_gp = gpar(col = \"black\"), name = \"Enrichment\")\n# dev.off()\n\n\nselected.TFs = sort(unique(union(rownames(Xu), rownames(Xd))))\n\n\n```\n\n\n```{r}\nset.seed(0)\nGWAS.TFs = sort(unique(intersect(all.TFs, PGC3.all.genes)))\n# GWAS.TFs = intersect(all.TFs, PGC3.all.genes)\n\nTF.pvals = sapply(ChEA.analysis, function(tbl) {\n if(is.null(tbl)) {\n return(1)\n }\n TFs = tbl$`Integrated--topRank`$TF\n # scores = -log10((as.numeric(tbl$`Integrated--topRank`$Score)))\n # names(scores) = TFs\n # \n # res = fgsea::fgsea(list(PGC3 = GWAS.TFs), scores)\n # res$pval\n \n l = as.numeric(TFs %in% GWAS.TFs)\n if(sum(l) < 5)\n return (1)\n mhg.out = mhg::mhg_test(l, length(l), sum(l), length(l)/4, 10, upper_bound = F, tol = 1e-300)\n mhg.out$pvalue\n})\nTF.pvals.corrected = p.adjust(TF.pvals, method = \"fdr\")\nTF.pvals.enrichment = -log10(TF.pvals.corrected)\nsort(TF.pvals.enrichment)\n\n\n\nselected.TFs = sapply(ChEA.analysis, function(tbl) {\n if(is.null(tbl))\n return (NULL)\n TFs = tbl$`Integrated--topRank`$TF\n l = as.numeric(TFs %in% GWAS.TFs)\n mhg.out = mhg::mhg_test(l, length(l), sum(l), length(l)/4, 10, upper_bound = F, tol = 1e-300)\n TFs[1:mhg.out$threshold]\n\n \n # TFs = tbl$`Integrated--topRank`$TF\n # scores = -log10((as.numeric(tbl$`Integrated--topRank`$Score)))\n # names(scores) = TFs\n # \n # res = fgsea::fgsea(list(PGC3 = GWAS.TFs), scores)\n # res$leadingEdge[[1]]\n})\n\nsig.selected.TFs = selected.TFs[TF.pvals.corrected < 0.01]\n\n```\n\n\n```{r}\n\n\ndf = data.frame(Celltype = c(colnames(DE.sc), colnames(DE.sc)), Enrichment = TF.pvals.enrichment, Direction = c(rep(\"Up\", 20), rep(\"Down\", 20)))\ndf$Enrichment[21:40] = -df$Enrichment[21:40]\n\nperm = order(pmax(TF.pvals.enrichment[1:20], TF.pvals.enrichment[21:40]), decreasing = F)\ndf$Celltype = factor(df$Celltype, df$Celltype[perm])\n\npdf(\"~/PFC_v3/figures/TF_GWAS_enrichment.pdf\", width = 8, height = 5)\nggplot(data = df, aes(x = Celltype, y = Enrichment, fill = Direction)) + geom_bar(stat = \"identity\")+\n coord_flip()+ylab(\"Sorted Celltypes\")+\nlabs(y = \"Enrichment\", x = \"Sorted Celltypes\")+\n theme_minimal()+\n guides(fill = FALSE)+ scale_fill_manual(values=c(\"#3288bd\", \"#d53e4f\")) + theme(axis.text.y = element_text(face=\"bold\", color=celltype.colors[levels(df$Celltype)], size=12, angle=0), axis.text.x = element_text(face=\"bold\", color=\"black\", size=12, angle=0), axis.title = element_text(face=\"bold\", size=14, angle=0))\ndev.off()\n\n\n\n\n\n\n```\n\n```{r}\n# Top.Up.TFs.top50 = as.list(as.data.frame(apply(TF.up, 2, function(x) rownames(TF.up)[order(x, decreasing = T)[1:50]])))\n# Top.Down.TFs.top50 = as.list(as.data.frame(apply(TF.down, 2, function(x) rownames(TF.up)[order(x, decreasing = T)[1:50]])))\n\n# Top.Up.TFs.top50 = apply(TF.up, 2, function(x) rownames(TF.up)[x > -log10(0.05)])\n# Top.Down.TFs.top50 = apply(TF.down, 2, function(x) rownames(TF.down)[x > -log10(0.05)])\n\n\nTop.Up.TFs = sig.selected.TFs[grep(\"Up\", names(sig.selected.TFs))]\nnames(Top.Up.TFs)=sapply(names(Top.Up.TFs), function(x) substr(x, 4, str_length(x)))\n\nTop.Down.TFs = sig.selected.TFs[grep(\"Down\", names(sig.selected.TFs))]\nnames(Top.Down.TFs)=sapply(names(Top.Down.TFs), function(x) substr(x, 6, str_length(x)))\n\nFunCat.TFs = lapply(FunCat.genes, function(x) intersect(x, all.TFs))\nfun.Cat.TFs.up = assess.genesets(FunCat.TFs, Top.Up.TFs, length(all.TFs), correct = T)\nfun.Cat.TFs.down = assess.genesets(FunCat.TFs, Top.Down.TFs, length(all.TFs), correct = T)\n\n\n\n\n# fun.Cat.TFs.up = assess.genesets(FunCat.genes, Top.Up.TFs.top50, nrow(pb.logcounts))\n# fun.Cat.TFs.down = assess.genesets(FunCat.genes, Top.Down.TFs.top50, nrow(pb.logcounts))\n\nha_rows = rowAnnotation(df = list(\"Class\" = FunCat.annotation), col = list(\"Class\" = FunCatPal), annotation_legend_param = list(\"Class\"=list(title_gp = gpar(fontsize = 0), labels_gp = gpar(fontsize = 10))))\n\n\nX.U = (fun.Cat.TFs.up)\n# redCol_fun = circlize::colorRamp2(c(quantile(X.U, 0.25), quantile(X.U, 0.5), quantile(X.U, 0.85), quantile(X.U, 0.99)), c(\"#ffffff\", \"#fee5d9\", \"#ef3b2c\", \"#99000d\"))\nX.U[X.U < -log10(0.05)] = 0\nredCol_fun = circlize::colorRamp2(seq(-log10(0.05), quantile(X.U, 0.95), length.out = 8), (c(\"#ffffff\", pals::brewer.reds(7))))\n\n\n\n\n\nX.D = (fun.Cat.TFs.down)\n# blueCol_fun = circlize::colorRamp2(c(quantile(X.D, 0.25), quantile(X.U, 0.5), quantile(X.D, 0.85), quantile(X.D, 0.99)), c( \"#ffffff\", \"#9ecae1\", \"#2171b5\", \"#08306b\"))\nX.D[X.D < -log10(0.05)] = 0\n\nblueCol_fun = circlize::colorRamp2(seq(-log10(0.05), quantile(X.D, 0.95), length.out = 8), (c(\"#ffffff\", pals::brewer.blues(7))))\n\n# pals::brewer.reds()\n\n\npdf(\"~/PFC_v3/figures/TFs_FunCat_enrichment_meta_filtered_selected.pdf\", width = 8, height = 7)\npar(mar=c(0,150,0,0))\nHeatmap(X.U, rect_gp = gpar(col = \"black\"), name = \"Up\", column_title = \"Up\", cluster_rows = F, cluster_columns = F, col = redCol_fun, row_names_side = \"left\", column_names_gp = gpar(fontsize = 14, fontface=\"bold\", col = colors[colnames(X.U)]), row_names_gp = gpar(fontsize = 14, fontface=\"bold\", col = FunCatPal[FunCat.annotation]), column_title_gp = gpar(fontsize = 18, fontface=\"bold\"), row_title_gp = gpar(fontsize = 18, fontface=\"bold\"), row_names_max_width = unit(150, \"cm\"), column_names_max_height = unit(150, \"cm\"))+\nHeatmap(X.D, rect_gp = gpar(col = \"black\"), name = \"Down\", cluster_rows = F, cluster_columns = F, col = blueCol_fun, row_names_side = \"left\", column_title = \"Down\", column_names_gp = gpar(fontsize = 14, fontface=\"bold\", col = colors[colnames(X.D)]), row_names_gp = gpar(fontsize = 14, fontface=\"bold\", col = FunCatPal[FunCat.annotation]), column_title_gp = gpar(fontsize = 18, fontface=\"bold\"), row_title_gp = gpar(fontsize = 18, fontface=\"bold\"), right_annotation = ha_rows, row_names_max_width = unit(150, \"cm\"), column_names_max_height = unit(150, \"cm\"))\ndev.off()\n\n\n\n```\n\n\n```{r}\n# tbl = ChEA.analysis$`Up_Ex-L2`\n# topTFs = sapply(1:40, function(i) {\n# tbl = ChEA.analysis[[i]]\n# if(is.null(tbl)) {\n# return(1)\n# }\n# \n# tbl.top = tbl$`Integrated--topRank`\n# tbl.top$TF[as.numeric(tbl.top$Score) < 1e-3]\n# })\n# sort(unique(unlist(topTFs)))\n# \n```\n\n```{r}\ntbl = ChEA.analysis$`Up_Ex-L2`$`Integrated--topRank`\n\n\n\nTF.pvals = sapply(ChEA.analysis, function(tbl) {\n if(is.null(tbl)) {\n return(1)\n }\n TFs = tbl$`Integrated--topRank`$TF\n # scores = -log10((as.numeric(tbl$`Integrated--topRank`$Score)))\n # names(scores) = TFs\n # \n # res = fgsea::fgsea(list(PGC3 = GWAS.TFs), scores)\n # res$pval\n \n l = as.numeric(TFs %in% GWAS.TFs)\n if(sum(l) < 5)\n return (1)\n mhg.out = mhg::mhg_test(l, length(l), sum(l), length(l)/4, 10, upper_bound = F, tol = 1e-300)\n mhg.out$pvalue\n})\nTF.pvals.corrected = p.adjust(TF.pvals, method = \"fdr\")\nTF.pvals.enrichment = -log10(TF.pvals.corrected)\nsort(TF.pvals.enrichment)\n```\n\n\n```{r}\nset.seed(0)\n\nTF.pvals = sapply(ChEA.analysis, function(tbl) {\n if(is.null(tbl)) {\n return(1)\n }\n TFs = tbl$`Integrated--topRank`$TF\n # scores = -log10((as.numeric(tbl$`Integrated--topRank`$Score)))\n # names(scores) = TFs\n # \n # res = fgsea::fgsea(list(PGC3 = GWAS.TFs), scores)\n # res$pval\n \n l = as.numeric(TFs %in% GWAS.TFs)\n if(sum(l) < 5)\n return (1)\n mhg.out = mhg::mhg_test(l, length(l), sum(l), length(l)/4, 10, upper_bound = F, tol = 1e-300)\n mhg.out$pvalue\n})\nTF.pvals.corrected = p.adjust(TF.pvals, method = \"fdr\")\nTF.pvals.enrichment = -log10(TF.pvals.corrected)\nsort(TF.pvals.enrichment)\n\n\n\nselected.TFs = sapply(ChEA.analysis, function(tbl) {\n if(is.null(tbl))\n return (NULL)\n TFs = tbl$`Integrated--topRank`$TF\n l = as.numeric(TFs %in% GWAS.TFs)\n mhg.out = mhg::mhg_test(l, length(l), sum(l), length(l)/4, 10, upper_bound = F, tol = 1e-300)\n TFs[1:mhg.out$threshold]\n\n \n # TFs = tbl$`Integrated--topRank`$TF\n # scores = -log10((as.numeric(tbl$`Integrated--topRank`$Score)))\n # names(scores) = TFs\n # \n # res = fgsea::fgsea(list(PGC3 = GWAS.TFs), scores)\n # res$leadingEdge[[1]]\n})\n\nsig.selected.TFs = selected.TFs[TF.pvals.corrected < 0.01]\n\n```\n\n\n\n```{r}\n# Top.Up.TFs = sig.selected.TFs[grep(\"Up\", names(sig.selected.TFs))]\n# names(Top.Up.TFs)=sapply(names(Top.Up.TFs), function(x) substr(x, 4, str_length(x)))\n# \n# Top.Down.TFs = sig.selected.TFs[grep(\"Down\", names(sig.selected.TFs))]\n# names(Top.Down.TFs)=sapply(names(Top.Down.TFs), function(x) substr(x, 6, str_length(x)))\n\n# FunCat.TFs = lapply(FunCat.genes, function(x) intersect(x, all.TFs))\n# fun.Cat.TFs.up = assess.genesets(FunCat.TFs, Top.Up.TFs, length(all.TFs), correct = T)\n# fun.Cat.TFs.down = assess.genesets(FunCat.TFs, Top.Down.TFs, length(all.TFs), correct = T)\n# \n# \n# \n# neurodev.top.TFs = sort(unique(intersect(rownames(pb.logcounts), intersect(FunCat.genes$neurodevelopment, union(sort(unique(unlist(Top.Up.TFs))), sort(unique(unlist(Top.Down.TFs))))))))\n\nneurodev.top.TFs = intersect(sort(unique(intersect(TFs, FunCat.genes$neurodevelopment))), rownames(pb.logcounts))\n\n```\n\n" }, { "alpha_fraction": 0.6520640850067139, "alphanum_fraction": 0.6733710169792175, "avg_line_length": 46.13203430175781, "blob_id": "957aec539ddc7274ec56f5886bf20488eec2141a", "content_id": "921922789f3b0e89480fc34505ec76106b4dd8d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 21777, "license_type": "no_license", "max_line_length": 912, "num_lines": 462, "path": "/old/GWAS_comprison_with_bulkRNA.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"Constructing panels for the PGC3 GWAS Manhattan plot\"\noutput: html_notebook\n---\n\n# Setup\n```{r include=FALSE}\nrequire(ACTIONet)\nrequire(stringr)\nrequire(ComplexHeatmap)\n\n\nresults.path = \"~/results\"\ninput.path = \"~/results/input\"\ndataset.path = \"~/results/datasets\"\ntables.path = \"~/results/tables\"\nfigures.path = \"~/results/figures/PGC3/\"\n\nsource(\"manhattan.R\")\n\n```\n\n\n## Enrichment function\n```{r}\nassess.genesets <-function (arch.gs, terms.gs, N, min.pval = 1e-100, correct = \"none\"){\n shared = t(sapply(terms.gs, function(gs1) {\n sapply(arch.gs, function(gs2) {\n nn = intersect(gs1, gs2)\n })\n }))\n colnames(shared) = names(arch.gs)\n GS.sizes = sapply(terms.gs, length)\n logPvals.out = sapply(1:ncol(shared), function(i) {\n gg = shared[, i]\n x = as.numeric(sapply(gg, length))\n n.sample = length(arch.gs[[i]])\n n.success = as.numeric(GS.sizes)\n v = rep(1, length(x))\n min.overlap = n.success * n.sample/N\n idx = which(x >= min.overlap)\n if (length(idx) == 0) \n return(v)\n v[idx] = (phyper(x[idx]-1, n.sample, N-n.sample, n.success[idx], lower.tail = F))\n # v[idx] = HGT_tail(population.size = N, success.count = n.success[idx], \n # sample.size = n.sample, observed.success = x[idx])\n return(v)\n })\n if(correct == \"global\") {\n logPvals.out = matrix(p.adjust(logPvals.out, \"fdr\"), nrow = nrow(logPvals.out))\n } else if(correct == \"local\") {\n logPvals.out = apply(logPvals.out, 2, function(x) p.adjust(x, \"fdr\"))\n }\n rownames(logPvals.out) = names(terms.gs)\n colnames(logPvals.out) = names(arch.gs)\n return(-log10(Matrix::t(logPvals.out)))\n}\n```\n\n# Load primary datasets\n```{r, eval = T}\nACTIONet_summary = readr::read_rds(file.path(dataset.path, \"ACTIONet_summary_filtered_individuals.rds\"))\npb.logcounts = readr::read_rds(file.path(dataset.path, \"PB_mean_logcounts_final.RDS\"))\n\ncolor.df = readRDS(file.path(dataset.path, \"celltype_colors.rds\"))\ncolors = color.df$color\nnames(colors) = color.df$celltype\n\n```\n\n\n# Load DE results\n```{r, eval = T}\nrdbu_fun = circlize::colorRamp2(c(-3, log10(0.05), 0, -log10(0.05), 3), rev(pals::brewer.rdbu(9)[seq(1, 9, by = 2)]))\n\n\nbulk.DE = read.csv(\"~/results/input/PEC_DE_table.csv\", sep = \"\\t\")\nDE.genes = readr::read_rds(\"~/results/input/SCZ_associated_genesets.rds\")\nbulkDE.genes = intersect(bulk.DE$gene_name, sort(unique(union(DE.genes$`DE.Up (PEC)`, DE.genes$`DE.Down (PEC)`))))\nbulk.scores = -log10(bulk.DE$SCZ.p.value[match(bulkDE.genes, bulk.DE$gene_name)])\nnames(bulk.scores) = bulkDE.genes\n\n\n```\n\n\n## Load significant variants and mapped genes\n```{r}\nPGC3.finemapped.genes.tbl = read.table(file.path(input.path, \"Prioritised_PGC3_SZ_Genes.csv\"), sep = \"\\t\", header = T)\nPGC3.loci = read.table(file.path(input.path, \"PGC3_SZ_significant_loci.csv\"), sep = \"\\t\", header = T)\n\nassociated.genes = PGC3.loci$ENSEMBL.genes..all..clear.names.\n\n\nPGC3.all.genes.raw = sort(unique(unlist(sapply(PGC3.loci$ENSEMBL.genes..all..clear.names., function(str) {\n if(str == \"-\") {\n return(\"-\")\n }\n gs = str_split(str, \",\")[[1]]\n \n return(gs)\n}))))\n\nPGC3.all.genes = intersect(PGC3.all.genes.raw, rownames(DE.scores))\n\n\n \nPGC3.loci$bulk.selected.genes = sapply(PGC3.loci$ENSEMBL.genes..all..clear.names., function(str) {\n if(str == \"-\") {\n return(\"-\")\n }\n gs = intersect(str_split(str, \",\")[[1]], names(bulk.scores))\n if(length(gs) == 0)\n return(\"-\")\n else \n ss = bulk.scores[gs]\n if(sum(abs(ss)) == 0)\n return(\"-\")\n else\n return(gs[which.max(ss)])\n})\n\n\nPGC3.loci.finemapped = PGC3.loci[PGC3.loci$top.index %in% PGC3.finemapped.genes.tbl$Index.SNP, ]\n\nPGC3.loci.finemapped$finemapped.gene = PGC3.finemapped.genes.tbl$Symbol.ID[match(PGC3.loci.finemapped$top.index, PGC3.finemapped.genes.tbl$Index.SNP)]\n\n\nPGC3.loci.finemapped.filtered = PGC3.loci.finemapped[PGC3.loci.finemapped$selected.genes != \"-\", ]\nPGC3.loci.finemapped.filtered$match.finemapping = PGC3.loci.finemapped.filtered$selected.genes == PGC3.loci.finemapped.filtered$finemapped.gene\n\n```\n\n\n\n\n```{r}\nprint(sum(PGC3.loci$selected.genes != \"-\")) # 132 -> 103 had finemaps\n\nproximal.genes = as.numeric(sapply(PGC3.loci.finemapped.filtered$ENSEMBL.genes..all..clear.names., function(str) length(str_split(str, \",\")[[1]])))\nsuccess.p = 1/proximal.genes\nis.success = as.numeric(PGC3.loci.finemapped.filtered$match.finemapping) # 25/103 success\n# bino.logpvals = -log10(pbinom(0, size = 1, prob = success.p, lower.tail = F))\n\nrequire(poibin)\npbino.pval = 1-ppoibin(sum(is.success), success.p, method = \"DFT-CF\",wts=NULL) # p-value: 1.765768e-05\n\nprint(length(proximal.genes))\nprint(sum(is.success))\nprint(pbino.pval)\n# GRIN2A and CACNA1C (almost are the only choices)\n# CLU: is linked to many genes, but is selected in L23\n\n\n# pdf(file.path(figures.path, \"GWAS_panels\", \"SNP_number_linked_genes.pdf\"), height = 42, width = 2.5)\n# Heatmap(as.matrix(proximal.genes), cluster_rows = F, name = \"enrichment\", col = viridis::magma(100))\n# dev.off()\n\n\n\n```\n\n\n## Visualize the heatmap of DE for variants-associated genes\n```{r}\n\nX = DE.scores[PGC3.loci.finemapped.filtered$selected.genes[PGC3.loci.finemapped.filtered$match.finemapping == T], ]\nX = X[rowSums(X !=0)>0, ]\n\npdf(file.path(figures.path, \"PGC3_top_matched_genes_finemapped.pdf\"), height = 12, width = 6)\nHeatmap(X[, sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]], rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_rows = T, cluster_columns = F, col = rdbu_fun, name = \"Neuro (Ex)\", column_title = \"Neuro (Ex)\") + Heatmap(X[, sorted.celltypes[grepl(\"^In\", sorted.celltypes)]], rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^In\", sorted.celltypes)]]), cluster_columns = F, col = rdbu_fun, name = \"Neuro (In)\", column_title = \"Neuro (In)\") + Heatmap(X[, sorted.celltypes[!grepl(\"^Ex|^In\", sorted.celltypes)]], rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[!grepl(\"^In|^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_columns = F, col = rdbu_fun, name = \"Glial\", column_title = \"Glial\")\ndev.off()\n\n\n# pdf(file.path(figures.path,\"GWAS_panels\", \"PGC3_top_matched_genes_finemapped_genome_order.pdf\"), height = 12, width = 6)\n# Heatmap(X[, sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]], rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_rows = F, cluster_columns = F, col = rdbu_fun, name = \"Neuro (Ex)\", column_title = \"Neuro (Ex)\") + Heatmap(X[, sorted.celltypes[grepl(\"^In\", sorted.celltypes)]], rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^In\", sorted.celltypes)]]), cluster_columns = F, col = rdbu_fun, name = \"Neuro (In)\", column_title = \"Neuro (In)\") + Heatmap(X[, sorted.celltypes[!grepl(\"^Ex|^In\", sorted.celltypes)]], rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[!grepl(\"^In|^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_columns = F, col = rdbu_fun, name = \"Glial\", column_title = \"Glial\")\n# dev.off()\n\n\n\nX = DE.scores[PGC3.loci.finemapped.filtered$selected.genes, ]\nX = X[rowSums(X !=0)>0, ]\n\npdf(file.path(figures.path, \"PGC3_top_matched_genes.pdf\"), height = 18, width = 6)\nHeatmap(X[, sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]], rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_rows = T, cluster_columns = F, col = rdbu_fun, name = \"Neuro (Ex)\", column_title = \"Neuro (Ex)\") + Heatmap(X[, sorted.celltypes[grepl(\"^In\", sorted.celltypes)]], rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^In\", sorted.celltypes)]]), cluster_columns = F, col = rdbu_fun, name = \"Neuro (In)\", column_title = \"Neuro (In)\") + Heatmap(X[, sorted.celltypes[!grepl(\"^Ex|^In\", sorted.celltypes)]], rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[!grepl(\"^In|^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_columns = F, col = rdbu_fun, name = \"Glial\", column_title = \"Glial\")\ndev.off()\n\npdf(file.path(figures.path, \"GWAS_panels\", \"PGC3_top_matched_genes_genome_order.pdf\"), height = 24, width = 6)\nHeatmap(X[, sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]], rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_rows = F, cluster_columns = F, col = rdbu_fun, name = \"Neuro (Ex)\", column_title = \"Neuro (Ex)\") + Heatmap(X[, sorted.celltypes[grepl(\"^In\", sorted.celltypes)]], rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^In\", sorted.celltypes)]]), cluster_columns = F, col = rdbu_fun, name = \"Neuro (In)\", column_title = \"Neuro (In)\") + Heatmap(X[, sorted.celltypes[!grepl(\"^Ex|^In\", sorted.celltypes)]], rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[!grepl(\"^In|^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_columns = F, col = rdbu_fun, name = \"Glial\", column_title = \"Glial\")\ndev.off()\n\npdf(file.path(figures.path, \"GWAS_panels\", \"PGC3_top_matched_genes_genome_order_neuro.pdf\"), height = 24, width = 5)\nHeatmap(X[, sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]], rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_rows = F, cluster_columns = F, col = rdbu_fun, name = \"Neuro (Ex)\", column_title = \"Neuro (Ex)\") + Heatmap(X[, sorted.celltypes[grepl(\"^In\", sorted.celltypes)]], rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^In\", sorted.celltypes)]]), cluster_columns = F, col = rdbu_fun, name = \"Neuro (In)\", column_title = \"Neuro (In)\")\ndev.off()\n\n\n```\n\n# Export individual columns \n```{r}\nX = as.matrix(assigned.genes2celltype.df$score[match(PGC3.loci.finemapped.filtered$selected.genes, assigned.genes2celltype.df$gene)])\npdf(file.path(figures.path, \"GWAS_panels\", \"PGC3_mapped_ordered_genes_topMap_notlabeled.pdf\"), height = 42, width = 1.5)\nHeatmap(X, rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_rows = F, cluster_columns = F, col = rdbu_fun, name = \"Enrichment\")\ndev.off()\n\nrownames(X) = PGC3.loci.finemapped.filtered$selected.genes\npdf(file.path(figures.path, \"GWAS_panels\", \"PGC3_mapped_ordered_genes_topMap_labeled.pdf\"), height = 42, width = 2.35)\nHeatmap(X, rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_rows = F, cluster_columns = F, col = rdbu_fun, name = \"Enrichment\", row_names_side = \"left\")\ndev.off()\n\n\n\nX = as.matrix(factor(assigned.genes2celltype.df$celltype[match(PGC3.loci.finemapped.filtered$selected.genes, assigned.genes2celltype.df$gene)], levels = names(colors)))\nX[assigned.genes2celltype.df$score[match(PGC3.loci.finemapped.filtered$selected.genes, assigned.genes2celltype.df$gene)] == 0, 1] = NA\npdf(file.path(figures.path, \"GWAS_panels\", \"PGC3_mapped_ordered_genes_topMap_celltype.pdf\"), height = 42, width = 2.2)\nHeatmap(X, rect_gp = gpar(col = \"black\"), cluster_rows = F, cluster_columns = F, col = colors, name = \"Celltype\", na_col = \"black\")\ndev.off()\n\nrownames(X) = as.character(assigned.genes2celltype.df$celltype[match(PGC3.loci.finemapped.filtered$selected.genes, assigned.genes2celltype.df$gene)])\nrownames(X)[assigned.genes2celltype.df$score[match(PGC3.loci.finemapped.filtered$selected.genes, assigned.genes2celltype.df$gene)] == 0] = NA\npdf(file.path(figures.path, \"GWAS_panels\", \"PGC3_mapped_ordered_genes_topMap_celltype_withlabels.pdf\"), height = 42, width = 3.8)\nHeatmap(X, rect_gp = gpar(col = \"black\"), cluster_rows = F, cluster_columns = F, col = colors, name = \"Celltype\", row_names_side = \"left\", na_col = \"black\")\ndev.off()\n\n\n```\n\n\n# Plot Manhattan\n```{r}\nSCZ.GWAS = read.csv(file.path(input.path, 'PGC3_SCZ_wave3_public.v2.tsv'), sep = \"\\t\")\nval = as.numeric(SCZ.GWAS$CHR)\nSCZ.GWAS=SCZ.GWAS[!is.na(val), ]\nSCZ.GWAS$CHR = val[!is.na(val)]\n\nSCZ.GWAS.annotated = SCZ.GWAS\n\nidx = match(PGC3.loci.finemapped.filtered$top.index, SCZ.GWAS.annotated$SNP)\n\nSCZ.GWAS.annotated$Labels = \"\"\nSCZ.GWAS.annotated$Labels.col = \"#ffffff\"\n\n\nSCZ.GWAS.annotated$Labels[idx] = paste(\"(\", SCZ.GWAS.annotated$SNP[idx], \")-(\", PGC3.loci.finemapped.filtered$selected.genes, \")-(\", assigned.genes2celltype.df$celltype[match(PGC3.loci.finemapped.filtered$selected.genes, assigned.genes2celltype.df$gene)], \")-(\", assigned.genes2celltype.df$dir[match(PGC3.loci.finemapped.filtered$selected.genes, assigned.genes2celltype.df$gene)], \")\", sep = \"\")\nSCZ.GWAS.annotated$Labels.col[idx] = colors[assigned.genes2celltype.df$celltype[match(PGC3.loci.finemapped.filtered$selected.genes, assigned.genes2celltype.df$gene)]]\n\n\n\n# iii = which(SCZ.GWAS.annotated$Labels != \"\")\n\n```\n\n## Compute Manhattan\n```{r}\nDd = manhattan.compute(SCZ.GWAS.annotated, cex = 0.15, cex.axis = 0.5, suggestiveline = F, ylim = c(0, -log10(min(sig.SCZ.GWAS$P))), annotateLabels = T)\n\n```\n\n```{r}\nDd$Point.col = \"#000000\"\n\n```\n\n\n```{r}\n# png(file.path(figures.path, \"GWAS_panels\", \"SCZ_Manh_v4.png\"), width = 12, height = 6)\npng(file.path(figures.path, \"SCZ_Manh_v4.png\"), width = 2400, height = 1200, res = 300)\nmanhattan.plot(Dd, cex = 0.15, cex.axis = 0.5, suggestiveline = F, ylim = c(0, -log10(min(SCZ.GWAS$P))), annotateLabels = NULL, precolor = F)\ndev.off()\n\n```\n\n## Plot Manhattan without Labels\n```{r}\n\niii = c(which(Dd$Labels != \"\"), which.max(Dd$pos))\nXd = Dd[iii, ]\n\npdf(file.path(figures.path, \"GWAS_panels\", \"SCZ_Manh_sig_aligned_v4.pdf\"), width = 12, height = 6)\n# png(\"~/PFC_v3/figures/SCZ_Manh_sig_aligned_annotatede.png\", width = 2400, height = 1200, res = 300)\nmanhattan.plot(Xd, cex = 0.15, cex.axis = 0.5, suggestiveline = F, ylim = c(0, -log10(min(SCZ.GWAS$P))), annotateLabels = NULL)\ndev.off()\n\n\n# pdf(file.path(figures.path, \"GWAS_panels\", \"SCZ_Manh_sigOnly_aligned_v4.pdf\"), width = 12, height = 6)\n# # png(\"SCZ_Manh_all_aligned.png\", width = 2400, height = 1200, res = 300)\n# manhattan.plot(X, cex = 0.15, cex.axis = 0.5, suggestiveline = F, ylim = c(0, -log10(min(SCZ.GWAS$P))), annotateLabels = NULL)\n# dev.off()\n\n```\n\n## Plot Manhattan with Labels\n```{r}\niii = c(which(Dd$Labels != \"\"), which.max(Dd$pos))\nXd = Dd[iii, ]\n\ngg = as.character(sapply(Xd$Labels[-nrow(Xd)], function(str) {\n x = str_split(str, \"-\")[[1]][[2]]\n gg = substr(x, 2, str_length(x)-1)\n}))\n\nx = assigned.genes2celltype.df$score[match(gg, assigned.genes2celltype.df$gene)]\n\n\nrdbu_fun = circlize::colorRamp2(c(-3, -1.96, 0, 1.96, 3), rev(pals::brewer.rdbu(9)[seq(1, 9, by = 2)]))\n# \n# \n# NA_col = \"#eeeeee\"\n# grad_palette = (grDevices::colorRampPalette(rev(RColorBrewer::brewer.pal(n = 7, name = \"RdBu\"))))(100)\n# col_func = (scales::col_bin(palette = grad_palette, domain = NULL, na.color = NA_col, bins = 7))\n\nXd$Point.col = c(rdbu_fun(x), \"#000000\")\n\nXd$FullLabels = Xd$Labels\nXd$Labels = c(gg, \"\")\n\n\n\n\npdf(file.path(figures.path, \"GWAS_panels\", \"SCZ_Manh_sig_aligned_v4.pdf\"), width = 12, height = 6)\nmanhattan.plot(Xd, cex = 0.15, cex.axis = 0.5, suggestiveline = F, ylim = c(0, -log10(min(SCZ.GWAS$P))), annotateLabels = NULL, precolor = T)\ndev.off()\n\npdf(file.path(figures.path, \"GWAS_panels\", \"SCZ_Manh_sig_aligned_labels_v4.pdf\"), width = 12, height = 6)\nmanhattan.plot(Xd, cex = 0.15, cex.axis = 0.5, suggestiveline = F, ylim = c(0, -log10(min(SCZ.GWAS$P))), annotateLabels = T, precolor = T)\ndev.off()\n\n```\n\n```{r}\ntbl = cbind(Xd[1:97, ], assigned.genes2celltype.df[match(Xd$Labels[1:97], assigned.genes2celltype.df$gene), ], PGC3.loci.finemapped.filtered)\n\n\n\n\nwrite.table(tbl, \"~/results/figures/PGC3/SNP_to_gene_assignments_sig_v3.tsv\", sep = \"\\t\", row.names = F, col.names = T, quote = F)\n\n```\n\n```{r}\ntbl = read.table(\"~/magma/hmagma/hmagmaAdultBrain__sz3/hmagmaAdultBrain__sz3.genes.out\", header = T)\nsuppressWarnings(ids <- AnnotationDbi::mapIds(org.Hs.eg.db, keys = tbl$GENE, keytype = \"ENSEMBL\", column = \"SYMBOL\", multiVals = \"first\"))\nids[is.na(ids)] = \"\"\n\nscores = rep(0, nrow(PGC3.loci.finemapped.filtered))\nii = match(PGC3.loci.finemapped.filtered$selected.genes, ids)\nscores[!is.na(ii)] = -log10(tbl$P[ii[!is.na(ii)]])\n\n\nPurPal = colorRampPalette(RColorBrewer::brewer.pal(9, \"Purples\"))(200)\n\nX = as.matrix(scores)\npdf(file.path(figures.path, \"GWAS_panels\", \"HMAGMA_scores.pdf\"), height = 42, width = 1.5)\nHeatmap(X, rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_rows = F, cluster_columns = F, col = PurPal, name = \"Enrichment\", show_row_names = F)\ndev.off()\n\nrownames(X) = PGC3.loci.finemapped.filtered$selected.genes\npdf(file.path(figures.path, \"GWAS_panels\", \"HMAGMA_scores_labeled.pdf\"), height = 42, width = 2.5)\nHeatmap(X, rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_rows = F, cluster_columns = F, col = PurPal, name = \"Enrichment\", row_names_side = \"left\")\ndev.off()\n\n\n```\n\n\n\n```{r}\n# tbl = read.table(\"~/magma/hmagma/hmagmaAdultBrain__sz3/hmagmaAdultBrain__sz3.genes.out\", header = T)\n# suppressWarnings(ids <- AnnotationDbi::mapIds(org.Hs.eg.db, keys = tbl$GENE, keytype = \"ENSEMBL\", column = \"SYMBOL\", multiVals = \"first\"))\n# ids[is.na(ids)] = \"\"\n\nrr = match(PGC3.loci.finemapped.filtered$top.index, SCZ.GWAS$SNP)\nscores = round(-log10(SCZ.GWAS$P[rr]), 1)\nnames(scores) = PGC3.loci.finemapped.filtered$top.index\n\n\n\n\n# scores = rep(0, nrow(PGC3.loci.finemapped.filtered))\n# ii = match(PGC3.loci.finemapped.filtered$selected.genes, ids)\n# scores[!is.na(ii)] = -log10(tbl$P[ii[!is.na(ii)]])\n\n\npdf(file.path(figures.path, \"GWAS_panels\", \"SNP_scores_labeled_v3.pdf\"), height = 42, width = 2.5)\nHeatmap(as.matrix(scores), cluster_rows = F, name = \"enrichment\", col = PurPal,\n cell_fun = function(j, i, x, y, width, height, fill) {\n grid.text(sprintf(\"%.1f\", as.matrix(scores)[i, j]), x, y, gp = gpar(fontsize = 10))\n})\ndev.off()\n\n\n\nmask = as.numeric(PGC3.loci.finemapped.filtered$match.finemapping)\nnames(mask) = PGC3.loci.finemapped.filtered$finemapped.gene\n\npdf(file.path(figures.path, \"GWAS_panels\", \"finemapped_genes.pdf\"), height = 42, width = 2.8)\nHeatmap(as.matrix(mask), cluster_rows = F, rect_gp = gpar(col = \"black\"), col = c(\"white\", \"gray\"), name = \"Fine-mapped\")\ndev.off()\n\n\n\n\n# PGC3.loci.finemapped.filtered$top.P[[15]] = sprintf('%e', 0.000000015)\n\n# scores = sapply(PGC3.loci.finemapped.filtered$top.P, function(x) {\n# #x = round(-log10(as.numeric(x)))\n# #if(is.na(x))\n# x = as.numeric(str_split(x, \"-\")[[1]][[2]])\n# # x[!is.na(x)]\n# })\n\n# names(scores) = PGC3.loci.finemapped.filtered$top.index\n\nPurPal = colorRampPalette(RColorBrewer::brewer.pal(9, \"Purples\"))(200)\n\nX = as.matrix(scores)\npdf(file.path(figures.path, \"GWAS_panels\", \"SNP_scores.pdf\"), height = 42, width = 1.5)\nHeatmap(X, rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_rows = F, cluster_columns = F, col = PurPal, name = \"Enrichment\", show_row_names = F)\ndev.off()\n\npdf(file.path(figures.path, \"GWAS_panels\", \"SNP_scores_labeled.pdf\"), height = 42, width = 2.5)\nHeatmap(X, rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_rows = F, cluster_columns = F, col = PurPal, name = \"Enrichment\", row_names_side = \"left\")\ndev.off()\n\n```\n\n\n```{r}\nSCZ.GWAS.annotated.ext = SCZ.GWAS\n\nidx = match(PGC3.loci.finemapped$top.index, SCZ.GWAS.annotated.ext$SNP)\nmask = (!is.na(idx)) & (PGC3.loci.finemapped$selected.genes == \"-\")\nDF = PGC3.loci.finemapped[mask, ]\nidx = idx[mask]\n\n\nSCZ.GWAS.annotated.ext$Labels = \"\"\nSCZ.GWAS.annotated.ext$Labels.col = \"#ffffff\"\n\n\nSCZ.GWAS.annotated.ext$Labels[idx] = DF$finemapped.gene # paste(\"(\", SCZ.GWAS.annotated$SNP[idx], \")-(\", PGC3.loci.finemapped.filtered$selected.genes, \")-(\", assigned.genes2celltype.df$celltype[match(PGC3.loci.finemapped.filtered$selected.genes, assigned.genes2celltype.df$gene)], \")-(\", assigned.genes2celltype.df$dir[match(PGC3.loci.finemapped.filtered$selected.genes, assigned.genes2celltype.df$gene)], \")\", sep = \"\")\nSCZ.GWAS.annotated.ext$Labels.col[idx] = colors[assigned.genes2celltype.df$celltype[match(DF$selected.genes, assigned.genes2celltype.df$gene)]]\n\nDd.ext = manhattan.compute(SCZ.GWAS.annotated.ext, cex = 0.15, cex.axis = 0.5, suggestiveline = F, ylim = c(0, -log10(min(sig.SCZ.GWAS$P))), annotateLabels = T)\n\n\n\niii = c(which(Dd.ext$Labels != \"\"), which.max(Dd.ext$pos))\nXd = Dd.ext[iii, ]\n\nXd$Point.col = \"#000000\"\n\n\npdf(file.path(figures.path, \"GWAS_panels\", \"SCZ_Manh_sig_aligned.pdf\"), width = 12, height = 6)\nmanhattan.plot(Xd, cex = 0.15, cex.axis = 0.5, suggestiveline = F, ylim = c(0, -log10(min(SCZ.GWAS$P))), annotateLabels = NULL)\ndev.off()\n\npdf(file.path(figures.path, \"GWAS_panels\", \"SCZ_Manh_sig_aligned_labels_finemapped.pdf\"), width = 12, height = 6)\nmanhattan.plot(Xd, cex = 0.15, cex.axis = 0.5, suggestiveline = F, ylim = c(0, -log10(min(SCZ.GWAS$P))), annotateLabels = T)\ndev.off()\n\n```\n\n\n" }, { "alpha_fraction": 0.6717498898506165, "alphanum_fraction": 0.6800419092178345, "avg_line_length": 31.9874210357666, "blob_id": "c06c3fc6c96aba56904bb15d86931d7b07b4824c", "content_id": "adaa6887459e5d7f76a5fdd060cffd112a226bed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 10492, "license_type": "no_license", "max_line_length": 162, "num_lines": 318, "path": "/old/RunDE_performMetaAnalysis.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"Perform DE analysis\"\nsubtitle: \"Step 2: Limma-trend on PB(s) followed by meta-analysis\"\noutput: html_notebook\n---\n\n# Setup\n```{r include=FALSE}\nrequire(ACTIONet)\nrequire(stringr)\nrequire(ComplexHeatmap)\nrequire(openxlsx)\n\nrequire(muscat)\nrequire(edgeR)\nrequire(limma)\n\nresults.path = \"~/results\"\ninput.path = \"~/results/input\"\ndataset.path = \"~/results/datasets\"\ntables.path = \"~/results/tables\"\nfigures.path = \"~/results/figures\"\n\n\ndev_threshold = 1 # logFC needs to be 1 std away from 0 (in both datasets) prior to metanalysis\n\n# Thresholds on the FDR-corrected meta-analysis results\npval_threshold = 0.05\nlogFC_threshold = 0.1\n\n```\n\n\n\n\n# Load datasets\n```{r}\nACTIONet_summary = readr::read_rds(file.path(dataset.path, \"ACTIONet_summary_filtered_individuals.rds\"))\npb.logcounts = readr::read_rds(file.path(dataset.path, \"PB_mean_logcounts.RDS\"))\n\nncells = sapply(int_colData(pb.logcounts)$n_cells, as.numeric)\nrownames(ncells) = names(assays(pb.logcounts))\n\n```\n\n\n\n# Prefilter outlier samples using % of excitatory neurons\nSZ33 is removed due to having > 80% ExNeu, and samples SZ3, SZ15, SZ24, SZ29 are removed due to having less than 10% ExNeu\n```{r}\ncs = Matrix::colSums(ncells)\nncells.freq = 100*scale(ncells, center = F, scale = cs)\nEx.perc = (fast_column_sums(ncells.freq[grepl(\"^Ex\", rownames(ncells.freq)) & !grepl(\"^Ex-NRGN\", rownames(ncells.freq)), ]))\n\nmask = (Ex.perc >= 10) & (Ex.perc <= 80) \npb.logcounts.filtered = pb.logcounts [, mask]\n\n```\n\n\n\n# Performing cohort-specific DE\n```{r}\npb.logcounts.filtered$SampleQuality = scale(log1p(pb.logcounts.filtered$umis))\nform = ~ Phenotype + Batch + PMI + Gender + Age + Benzodiazepines + Anticonvulsants + AntipsychTyp + AntipsychAtyp + Antidepress + SampleQuality\n\nresDE = lapply( levels(pb.logcounts.filtered$Cohort), function(chrt){\n\n\tkeep.ids = colnames(pb.logcounts.filtered)[pb.logcounts.filtered$Cohort == chrt]\n\n\tpb.logcounts.filtered_sub = pb.logcounts.filtered[,keep.ids]\n sample.metadata = droplevels(data.frame(colData(pb.logcounts.filtered_sub)))\n\tdesign.mat <- model.matrix(form, data = sample.metadata)\n\tcolnames(design.mat)[1] = c(\"Intercept\")\n\n\tcontrast.mat <- makeContrasts(contrasts = \"PhenotypeSZ\", levels = design.mat)\n\n\tdf = pbDS(pb.logcounts.filtered_sub, method = \"limma-trend\", min_cells = 5, design = design.mat, contrast = contrast.mat, filter = \"both\")\n\t\n})\nnames(resDE) = levels(colData(pb.logcounts.filtered)$Cohort)\n\nreadr::write_rds(resDE, file.path(dataset.path, \"Cohort_specific_DE_results.rds\"))\n\n```\n\n\n## Export as excel tables\n```{r}\nfor(ds in 1:length(resDE)) {\n print(names(resDE)[[ds]])\n \n Up.wb <- createWorkbook()\n for(i in 1:length(resDE[[ds]]$table$PhenotypeSZ)) {\n res = resDE[[ds]]$table$PhenotypeSZ[[i]]\n res = res[res$logFC > 0, ]\n res = cbind(data.frame(Gene = rownames(res)), res)\n res = res[order(res$t, decreasing = T), ]\n \n n = names(resDE[[ds]]$table$PhenotypeSZ)[[i]]\n \n addWorksheet(wb=Up.wb, sheetName = n)\n writeData(Up.wb, sheet = n, res) \n }\n saveWorkbook(Up.wb, sprintf(file.path(tables.path, \"DE_genes_up_%s_complete_set.xlsx\"), names(resDE)[[ds]]), overwrite = TRUE)\n \n \n Down.wb <- createWorkbook()\n for(i in 1:length(resDE[[ds]]$table$PhenotypeSZ)) {\n res = resDE[[ds]]$table$PhenotypeSZ[[i]]\n res = res[res$logFC < 0, ]\n res = cbind(data.frame(Gene = rownames(res)), res)\n res = res[order(res$t, decreasing = F), ]\n \n n = names(resDE[[ds]]$table$PhenotypeSZ)[[i]] \n \n addWorksheet(wb=Down.wb, sheetName = n)\n writeData(Down.wb, sheet = n, res) \n \n }\n saveWorkbook(Down.wb, sprintf(file.path(tables.path, \"DE_genes_down_%s_complete_set.xlsx\"), names(resDE)[[ds]]), overwrite = TRUE)\n}\n\n```\n\n\n\n# Prefiltering individual DE results before combining them\nOnly keep genes that have 1) consistent direction of dysregulation across both datasets, and 2) at least 1 std away from zero on the logFC scale\n\n```{r}\ncommon.celltypes = intersect(names(resDE$McLean$table$PhenotypeSZ), names(resDE$MtSinai$table$PhenotypeSZ))\n\nfiltered.tables = lapply(common.celltypes, function(celltype) {\n tbl1 = resDE[[1]]$table$PhenotypeSZ[[celltype]]\n tbl2 = resDE[[2]]$table$PhenotypeSZ[[celltype]]\n \n genes = intersect(tbl1$gene[dev_threshold <= abs(tbl1$logFC/sd(tbl1$logFC))], tbl2$gene[dev_threshold <= abs(tbl2$logFC / sd(tbl2$logFC))])\n\n tbl1 = tbl1[match(genes, tbl1$gene), ]\n tbl2 = tbl2[match(genes, tbl2$gene), ]\n \n mask = sign(tbl1$logFC)*sign(tbl2$logFC) > 0\n tbl1 = tbl1[mask, ]\n tbl2 = tbl2[mask, ]\n \n tbls = list(McClean = tbl1, MtSinai = tbl2) \n tbls = lapply( tbls, function(tab){\n tab$se = tab$logFC / tab$t\n tab\n })\n \n return(tbls)\n})\nnames(filtered.tables) = common.celltypes\n\nreadr::write_rds(filtered.tables, file.path(dataset.path, \"Cohort_specific_DE_results_filtered.rds\"))\n\n```\n\n## Export as excel tables\n```{r}\nfor(ds in 1:length(filtered.tables[[1]])) {\n Up.wb <- createWorkbook()\n for(i in 1:length(filtered.tables)) {\n res = filtered.tables[[i]][[ds]]\n res = res[res$logFC > 0, ]\n res = cbind(data.frame(Gene = rownames(res)), res)\n res = res[order(res$t, decreasing = T), ]\n \n n = names(filtered.tables)[[i]]\n \n addWorksheet(wb=Up.wb, sheetName = n)\n writeData(Up.wb, sheet = n, res) \n \n }\n saveWorkbook(Up.wb, sprintf(file.path(tables.path, \"DE_genes_up_%s_filtered.xlsx\"), names(filtered.tables[[i]])[[ds]]), overwrite = TRUE)\n \n \n Down.wb <- createWorkbook()\n for(i in 1:length(filtered.tables)) {\n res = filtered.tables[[i]][[ds]]\n res = res[res$logFC < 0, ]\n res = cbind(data.frame(Gene = rownames(res)), res)\n res = res[order(res$t, decreasing = F), ]\n \n n = names(filtered.tables)[[i]]\n \n addWorksheet(wb=Down.wb, sheetName = n)\n writeData(Down.wb, sheet = n, res) \n \n }\n saveWorkbook(Down.wb, sprintf(file.path(tables.path, \"DE_genes_down_%s_filtered.xlsx\"), names(filtered.tables[[i]])[[ds]]), overwrite = TRUE)\n}\n\n```\n\n# Perform meta-analysis via Linear (Mixed-Effects) Models (RMA)\n```{r}\ncombined.analysis.tables = lapply(names(filtered.tables), function(celltype) {\n print(celltype)\n tbls = filtered.tables[[celltype]]\n \n gene.tbls = lapply(1:nrow(tbls[[1]]), function(i) {\n dfs = lapply(1:length(tbls), function(k) tbls[[k]][i, ])\n df = do.call(\"rbind\", dfs)\n })\n names(gene.tbls) = tbls[[1]]$gene\n \n combined.analysis.tbl = do.call(rbind, lapply(names(gene.tbls), function(gene){\n x = suppressWarnings(metafor::rma(yi=logFC, sei=se, data = gene.tbls[[gene]], method=\"FE\"))\n combined.tbl = data.frame( gene = gene, \n logFC = x$beta,\n se = x$se,\n tstat = x$zval,\n P.Value = x$pval)\n return(combined.tbl)\n }))\n rownames(combined.analysis.tbl) = names(gene.tbls)\n \n combined.analysis.tbl = combined.analysis.tbl[order(combined.analysis.tbl$P.Value), ]\n \n return(combined.analysis.tbl)\n})\nnames(combined.analysis.tables) = names(filtered.tables)\n\nDF = do.call(rbind, combined.analysis.tables)\nDF$adj.P.Val = p.adjust(DF$P.Value, \"fdr\")\nff = factor(unlist(lapply(names(combined.analysis.tables), function(celltype) rep(celltype, nrow(combined.analysis.tables[[celltype]])))), names(filtered.tables))\ncombined.analysis.tables = split(DF, ff)\n\nreadr::write_rds(combined.analysis.tables, file.path(dataset.path, \"meta_analysis_results.rds\"))\n\n```\n\n\n# Export final tables\n```{r}\n Up.wb <- createWorkbook()\n for(i in 1:length(combined.analysis.tables)) {\n res = combined.analysis.tables[[i]]\n res = res[(res$logFC > logFC_threshold) & (res$P.Value <= pval_threshold), ]\n res = res[order(res$t, decreasing = T), ]\n res$isSig = res$adj.P.Val <= pval_threshold\n \n \n n = names(combined.analysis.tables)[[i]] \n \n addWorksheet(wb=Up.wb, sheetName = n)\n writeData(Up.wb, sheet = n, res) \n \n }\n saveWorkbook(Up.wb, file.path(tables.path, \"DE_genes_up_combined.xlsx\"), overwrite = TRUE)\n \n \n Down.wb <- createWorkbook()\n for(i in 1:length(combined.analysis.tables)) {\n res = combined.analysis.tables[[i]]\n res = res[(res$logFC < -logFC_threshold) & (res$P.Value <= pval_threshold), ]\n res = res[order(res$t, decreasing = F), ]\n res$isSig = res$adj.P.Val <= pval_threshold\n \n n = names(combined.analysis.tables)[[i]] \n \n addWorksheet(wb=Down.wb, sheetName = n)\n writeData(Down.wb, sheet = n, res) \n \n }\n saveWorkbook(Down.wb, file.path(tables.path, \"DE_genes_down_combined.xlsx\"), overwrite = TRUE)\n \n```\n\n\n# Summarize and simplify DE results\n```{r}\nDE.sc = matrix(0, nrow(pb.logcounts), length(combined.analysis.tables))\ntstats = matrix(0, nrow(pb.logcounts), length(combined.analysis.tables))\nlogFC = matrix(0, nrow(pb.logcounts), length(combined.analysis.tables))\nlogPvals = matrix(0, nrow(pb.logcounts), length(combined.analysis.tables))\nrownames(DE.sc) = rownames(tstats) = rownames(logFC) = rownames(logPvals) = rownames(pb.logcounts)\ncolnames(DE.sc) = colnames(tstats) = colnames(logFC) = colnames(logPvals) = names(combined.analysis.tables)\n\nlimma_trend_mean.scores = matrix(0, nrow(pb.logcounts), length(combined.analysis.tables))\nUp.genes = vector(\"list\", length(combined.analysis.tables))\nDown.genes = vector(\"list\", length(combined.analysis.tables))\nrownames(limma_trend_mean.scores) = rownames(pb.logcounts)\nnames(Up.genes) = names(Down.genes) = colnames(limma_trend_mean.scores) = names(combined.analysis.tables)\nfor(i in 1:length(combined.analysis.tables)) {\n\tprint(i)\n\t\n\ttbl = combined.analysis.tables[[i]]\n\n\ttstats[tbl$gene, names(combined.analysis.tables)[[i]]] = tbl$tstat\n\tlogFC[tbl$gene, names(combined.analysis.tables)[[i]]] = tbl$logFC\n\tlogPvals[tbl$gene, names(combined.analysis.tables)[[i]]] = -log10(tbl$adj.P.Val)\n\t\n\tx = tbl$tstat\n\tx[abs(tbl$logFC) < logFC_threshold] = 0\n\tDE.sc[tbl$gene, names(combined.analysis.tables)[[i]]] = x\n\t\n}\nlimma_trend_mean.scores[is.na(limma_trend_mean.scores)] = 0\n\n\nUp.genes = lapply(combined.analysis.tables, function(combined.analysis.tbl) {\n combined.analysis.tbl$gene[(combined.analysis.tbl$logFC > logFC_threshold) & (combined.analysis.tbl$adj.P.Val < pval_threshold)]\n})\nDown.genes = lapply(combined.analysis.tables, function(combined.analysis.tbl) {\n combined.analysis.tbl$gene[(combined.analysis.tbl$logFC < -logFC_threshold) & (combined.analysis.tbl$adj.P.Val < pval_threshold)]\n})\n\nDE.new = list(DE.sc = DE.sc, tstats = tstats, logFC = logFC, logPvals = logPvals, Up.genes = Up.genes, Down.genes = Down.genes)\n\nsaveRDS(DE.new, file.path(dataset.path, \"DE_genes_pseudobulk.rds\"))\n\n\n\n```\n\n\n" }, { "alpha_fraction": 0.6926187872886658, "alphanum_fraction": 0.7007077932357788, "avg_line_length": 23.407407760620117, "blob_id": "a915b7435dc03b685d3d65aa8f2acd87ab1e1ad6", "content_id": "75f6fff37d53ab903b96d55583065853c20f22c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 1978, "license_type": "no_license", "max_line_length": 104, "num_lines": 81, "path": "/old/RunDE_computePB.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"Perform DE analysis\"\nsubtitle: \"Step 1: Compute pseudobulk (PB) profiles\"\noutput: html_notebook\n---\n\n# Setup\n```{r include=FALSE}\nrequire(ACTIONet)\nrequire(stringr)\nrequire(ComplexHeatmap)\nrequire(muscat)\n\n\ndataset.path = \"~/results/datasets/\"\nresults.path = \"~/results\"\nfigures.folder = \"~/results/figures\"\n\n\n```\n\n# Read ACTIONet and convert to an SCE object\n```{r}\nace = readr::read_rds(\"~/results/ACTIONet_reunified.rds\")\nsce = as(ace, \"SingleCellExperiment\")\n\n```\n\n# Read metadata\n```{r}\nsample.metadata = readr::read_rds(file.path(dataset.path, \"sample_metadata.rds\"))\nACTIONet_summary = readr::read_rds(file.path(dataset.path, \"ACTIONet_summary.rds\"))\n\n```\n\n\n\n\n\n```{r}\nACTIONet_summary = readr::read_rds(file.path(dataset.path, \"ACTIONet_summary_filtered_individuals.rds\"))\n\npb.logcounts = readr::read_rds(file.path(dataset.path, \"PB_mean_logcounts_final.RDS\"))\n\ncolor.df = readRDS(file.path(dataset.path, \"celltype_colors.rds\"))\n\n# color.df[c(22:24), ] = color.df[c(24, 23, 22), ]\n\ncolors = color.df$color\nnames(colors) = color.df$celltype\n\n\nncells = sapply(int_colData(pb.logcounts)$n_cells, as.numeric)\nrownames(ncells) = names(assays(pb.logcounts))\n\n```\n\n\n# Use muscat to compute PB profiles\n```{r}\nsce$cluster_id = ACTIONet_summary$metadata$Labels\nsce$group_id = ACTIONet_summary$metadata$Phenotype\nsce$sample_id = ACTIONet_summary$metadata$Individual\n\nlibrary(muscat)\nsce$id <- paste0(sce$Phenotype, sce$sample_id)\n(sce <- prepSCE(sce,\n kid = \"cluster_id\", # subpopulation assignments\n gid = \"group_id\", # group IDs (ctrl/stim)\n sid = \"sample_id\", # sample IDs (ctrl/stim.1234)\n drop = TRUE)) # drop all other colData columns\n\npb.logcounts <- aggregateData(sce,\n assay = \"logcounts\", fun = \"mean\",\n by = c(\"cluster_id\", \"sample_id\"))\n\n\ncolData(pb.logcounts) = cbind(colData(pb.logcounts), sample.metadata[colnames(pb.logcounts), ])\nreadr::write_rds(pb.logcounts, file = file.path(dataset.path, \"PB_mean_logcounts_final.RDS\"))\n\n```\n\n" }, { "alpha_fraction": 0.6554704904556274, "alphanum_fraction": 0.6725117564201355, "avg_line_length": 35.468467712402344, "blob_id": "8b4f8d74b38c0191c2e51c96bb6695623fd71ee7", "content_id": "f08377e16a3f75cf302e567ba6b88a70488fd76d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 8098, "license_type": "no_license", "max_line_length": 328, "num_lines": 222, "path": "/old/RunDE_postQC.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"Analyze DE genes\"\nsubtitle: \"Step 3: Postprocessing the alignment of DE results across datasets\"\n\noutput: html_notebook\n---\n\nAnalyze individual DE results for consistency and alignment\n\n\n# Setup\n```{r include=FALSE}\nrequire(ACTIONet)\nrequire(stringr)\nrequire(ComplexHeatmap)\n\n\nresults.path = \"~/results\"\ninput.path = \"~/results/input\"\ndataset.path = \"~/results/datasets\"\ntables.path = \"~/results/tables\"\nfigures.path = \"~/results/figures\"\n\n\n```\n\n\n## Enrichment function\n```{r}\nassess.genesets <-function (arch.gs, terms.gs, N, min.pval = 1e-100, correct = \"none\"){\n shared = t(sapply(terms.gs, function(gs1) {\n sapply(arch.gs, function(gs2) {\n nn = intersect(gs1, gs2)\n })\n }))\n colnames(shared) = names(arch.gs)\n GS.sizes = sapply(terms.gs, length)\n logPvals.out = sapply(1:ncol(shared), function(i) {\n gg = shared[, i]\n x = as.numeric(sapply(gg, length))\n n.sample = length(arch.gs[[i]])\n n.success = as.numeric(GS.sizes)\n v = rep(1, length(x))\n min.overlap = n.success * n.sample/N\n idx = which(x >= min.overlap)\n if (length(idx) == 0) \n return(v)\n v[idx] = (phyper(x[idx]-1, n.sample, N-n.sample, n.success[idx], lower.tail = F))\n # v[idx] = HGT_tail(population.size = N, success.count = n.success[idx], \n # sample.size = n.sample, observed.success = x[idx])\n return(v)\n })\n if(correct == \"global\") {\n logPvals.out = matrix(p.adjust(logPvals.out, \"fdr\"), nrow = nrow(logPvals.out))\n } else if(correct == \"local\") {\n logPvals.out = apply(logPvals.out, 2, function(x) p.adjust(x, \"fdr\"))\n }\n rownames(logPvals.out) = names(terms.gs)\n colnames(logPvals.out) = names(arch.gs)\n return(-log10(Matrix::t(logPvals.out)))\n}\n```\n\n# Load primary datasets\n```{r, eval = T}\nACTIONet_summary = readr::read_rds(file.path(dataset.path, \"ACTIONet_summary_filtered_individuals.rds\"))\npb.logcounts = readr::read_rds(file.path(dataset.path, \"PB_mean_logcounts_final.RDS\"))\n\ncolor.df = readRDS(file.path(dataset.path, \"celltype_colors.rds\"))\ncolors = color.df$color\nnames(colors) = color.df$celltype\n\n```\n\n# Load DE results\n```{r, eval = T}\nresDE = readr::read_rds(file.path(dataset.path, \"Cohort_specific_DE_results.rds\"))\nfiltered.tables = readr::read_rds(file.path(dataset.path, \"Cohort_specific_DE_results_filtered.rds\"))\ncombined.analysis.tables = readr::read_rds(file.path(dataset.path, \"meta_analysis_results.rds\"))\n\nDE.new = readRDS(file.path(dataset.path, \"DE_genes_pseudobulk.rds\"))\nUp.genes = DE.new$Up.genes\nDown.genes = DE.new$Down.genes\nDE.sc = DE.new$DE.sc\nordered.celltypes = rownames(X)[order(apply(X, 1, sum), decreasing = T)]\n\n```\n\n\n\n# Compute Storey's pi1 per dataset\n```{r}\ntstat.overlap = sapply(common.celltypes, function(celltype) {\n df1 = resDE$McLean$table$PhenotypeSZ[[celltype]]\n df2 = resDE$MtSinai$table$PhenotypeSZ[[celltype]]\n common.genes = intersect(df1$gene, df2$gene)\n t1 = df1$t[match(common.genes, df1$gene)] \n t2 = df2$t[match(common.genes, df2$gene)] \n \n tt = cor.test(t1, t2)\n \n return(tt$statistic)\n})\ntstat.overlap[tstat.overlap < 0] = 0\nnames(tstat.overlap) = common.celltypes\n\nX = cbind(sapply(DE.new$Up.genes, length),sapply(DE.new$Down.genes, length))\nordered.celltypes = rownames(X)[order(apply(X, 1, sum), decreasing = T)]\n\nrequire(corrplot)\nPurPal = colorRampPalette(RColorBrewer::brewer.pal(9, \"Purples\"))(200)\npdf(file.path(figures.path, \"Supp\", \"Cohort_overlap.pdf\"), width =3, height = 7)\ncorrplot(as.matrix(tstat.overlap[ordered.celltypes]), is.corr = F, method = \"pie\", col = PurPal, cl.length = 5, outline = T, tl.col = \"black\", p.mat = as.matrix(p.adjust(pnorm(tstat.overlap[ordered.celltypes], lower.tail = F), \"fdr\")), insig = \"blank\", sig.level = 0.05)\ndev.off()\n\n\nlibrary(qvalue)\nMcLean.Pi1 = sapply(resDE$McLean$table$PhenotypeSZ, function(df) {\n pvals = df$p_val\n pi1 = 1 - qvalue(pvals)$pi0\n})\n\nMtSinai.Pi1 = sapply(resDE$MtSinai$table$PhenotypeSZ, function(df) {\n pvals = df$p_val\n pi1 = 1 - qvalue(pvals)$pi0\n})\ndf = data.frame(Celltype = union(names(resDE$MtSinai$table$PhenotypeSZ), names(resDE$McLean$table$PhenotypeSZ)))\nrownames(df) = df$Celltype\ndf$McLean = McLean.Pi1[df$Celltype]\ndf$MtSinai = 0\ndf[names(MtSinai.Pi1), \"MtSinai\"] = -MtSinai.Pi1\ndf = df[rev(ordered.celltypes), ]\ndf$Celltype = factor(df$Celltype, rev(ordered.celltypes))\ndf2 = reshape2::melt(df)\ncolnames(df2) = c(\"Celltype\", \"Dataset\", \"Pi1\")\n\ngg = ggplot(data = df2, aes(x = Celltype, y = Pi1, fill = Dataset)) + geom_bar(stat = \"identity\")+\n coord_flip()+ylab(\"Sorted Celltypes\")+\nlabs(y = \"Storey's Pi1\", x = \"Sorted Celltypes\")+\n theme_minimal()+\n guides(fill = FALSE)+ scale_fill_manual(values=c(\"#666666\", \"#cccccc\")) + theme(axis.text.y = element_text(face=\"bold\", color=colors[levels(df$Celltype)], size=12, angle=0), axis.text.x = element_text(face=\"bold\", color=\"black\", size=12, angle=0), axis.title = element_text(face=\"bold\", size=14, angle=0)) + ylim(c(-0.4, 0.4))\n\npdf(file.path(figures.path, \"Supp\", \"Cohort_specific_Pi1.pdf\"))\nplot(gg)\ndev.off()\n\n\n```\n\n# Overlap with bulk (PEC)\n```{r}\nPEC.DE = read.table(file.path(input.path, \"PEC_DE_table.csv\"), header = T)\ncommon.genes = intersect(rownames(pb.logcounts), PEC.DE$gene_name)\nPEC.tstat = PEC.DE$SCZ.t.value[match(common.genes, PEC.DE$gene_name)]\nnames(PEC.tstat) = common.genes\n\nMcLean.PEC.cor.pvals = sapply(resDE$McLean$table$PhenotypeSZ, function(DF) {\n tstats = DF$t\n names(tstats) = DF$gene\n cg = intersect(common.genes, DF$gene)\n x = -log10(cor.test(tstats[cg], PEC.tstat[cg], method = \"spearman\")$p.value)\n \n return(x)\n})\n\n\nMtSinai.PEC.cor.pvals = sapply(resDE$MtSinai$table$PhenotypeSZ, function(DF) {\n tstats = DF$t\n names(tstats) = DF$gene\n cg = intersect(common.genes, DF$gene)\n x = -log10(cor.test(tstats[cg], PEC.tstat[cg], method = \"spearman\")$p.value)\n \n return(x)\n})\n\nPEC.overlap.df = data.frame(Celltypes = names(resDE$MtSinai$table$PhenotypeSZ), McLean.PEC = McLean.PEC.cor.pvals[names(resDE$MtSinai$table$PhenotypeSZ)], MtSinai.PEC = -MtSinai.PEC.cor.pvals[names(resDE$MtSinai$table$PhenotypeSZ)])\ndf2 = reshape2::melt(PEC.overlap.df)\ncolnames(df2) = c(\"Celltype\", \"Dataset\", \"Enrichment\")\ndf2$Dataset = factor(as.character(df2$Dataset), c(\"McLean.PEC\", \"MtSinai.PEC\"))\ndf2$Celltype = factor(df2$Celltype, rev(ordered.celltypes))\n\n\n\ngg = ggplot(data = df2, aes(x = Celltype, y = Enrichment, fill = Dataset)) + geom_bar(stat = \"identity\")+\n coord_flip()+ylab(\"Sorted Celltypes\")+\nlabs(y = \"Bulk Enrichment\", x = \"Sorted Celltypes\")+\n theme_minimal()+\n guides(fill = FALSE)+ scale_fill_manual(values=c(\"#666666\", \"#cccccc\")) + theme(axis.text.y = element_text(face=\"bold\", color=colors[levels(df$Celltype)], size=12, angle=0), axis.text.x = element_text(face=\"bold\", color=\"black\", size=12, angle=0), axis.title = element_text(face=\"bold\", size=14, angle=0))\n\npdf(file.path(figures.path, \"Supp\", \"Cohort_specific_overlap_with_PEC_bulk.pdf\"))\nplot(gg)\ndev.off()\n\n# require(ggpubr)\n# gg =ggbarplot(df2, \"Celltype\", \"Enrichment\", fill = \"Dataset\", color = \"black\", palette = c(\"#666666\", \"#cccccc\"),\n# position = position_dodge(0.9), xlab = \"Celltype\", ylab = \"Enrichment\")+ theme(axis.text.x = element_text(face=\"bold\", size=8, angle=90,hjust=0.95,vjust=0.2, color = colors[levels(df2$Celltype)]), axis.text.y = element_text(face=\"bold\", size=12, angle=0), axis.title = element_text(face=\"bold\", size=18, angle=0))\n# \n# pdf(file.path(figures.path, \"Supp\", \"Cohort_specific_overlap_with_PEC_bulk.pdf\"))\n# plot(gg)\n# dev.off()\n\n```\n\n\n```{r}\nPyschDEGs = read.csv(file.path(input.path, \"RhesusAntipsychoticDEGs.csv\"), sep=\",\")\n\nDE = c(DE.new$Up.genes, DE.new$Down.genes)\nnames(DE) = c(paste(\"Up\", names(DE.new$Up.genes), sep = \"_\"), paste(\"Down\", names(DE.new$Down.genes), sep = \"_\"))\n\n\nset.seed(0)\nPyschDEGs.gsea = apply(PyschDEGs[, 3:5], 2, function(x) {\n names(v) = PyschDEGs$hsapiens_homolog_associated_gene_name\n DE.enrich = fgsea::fgsea(DE, v, eps = 0)\n})\n\n\nreadr::write_rds(PyschDEGs.gsea, file.path(dataset.path, \"RhesusAntipsychoticDEGs_vs_DEGs_fgsea.rds\"))\n\n\n```\n\n\n" }, { "alpha_fraction": 0.6599690914154053, "alphanum_fraction": 0.6742658615112305, "avg_line_length": 33.9594612121582, "blob_id": "42c5e0db4f1899725ad638e3cb3e5244732bbed2", "content_id": "22f90c7b1e766c57961a2e5ac7f2f40cb59358d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 2588, "license_type": "no_license", "max_line_length": 150, "num_lines": 74, "path": "/ancient/Supp_L45_vs_Psych.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"Identify genes that are shared across SZ+BD in a cell type-specific manner\"\noutput: html_notebook\n---\n\n```{r}\nL45_LRRK1.DE.genes = sort(unique(union(DE.new$Up.genes$`Ex-L45_LRRK1`, DE.new$Down.genes$`Ex-L45_LRRK1`)))\n\nrequire(fgsea)\n\nrequire(stringr)\n# SZ.hmagma.tbl = read.csv(\"~/magma/hmagma/hmagmaAdultBrain__sz3/hmagmaAdultBrain__sz3.genes.out\", sep = \" \")\nSZ.hmagma.lines = readLines(file(\"~/magma/hmagma/hmagmaAdultBrain__sz3/hmagmaAdultBrain__sz3.genes.out\", \"r\", blocking = T))\nSZ.hmagma.lines = str_split(SZ.hmagma.lines, \"\\n\")\nSZ.enrichment = sapply(SZ.hmagma.lines[-1], function(x) {\n parts = str_split(x, \" \")[[1]]\n parts = parts[parts != \"\"]\n v = -log10(as.numeric(parts[length(parts)]))\n names(v) = parts[[1]]\n return(v)\n})\n\nsuppressWarnings(ids <- AnnotationDbi::mapIds(org.Hs.eg.db, keys = names(SZ.enrichment), keytype = \"ENSEMBL\", column = \"SYMBOL\", multiVals = \"first\"))\nmask = !is.na(ids)\nSZ.enrichment = SZ.enrichment[!is.na(ids)]\nnames(SZ.enrichment) = ids[!is.na(ids)]\n\n\n\nBD.hmagma.lines = readLines(file(\"~/magma/hmagma/hmagmaAdultBrain__bip2/hmagmaAdultBrain__bip2.genes.out\", \"r\", blocking = T))\nBD.hmagma.lines = str_split(BD.hmagma.lines, \"\\n\")\nBD.enrichment = sapply(BD.hmagma.lines[-1], function(x) {\n parts = str_split(x, \" \")[[1]]\n parts = parts[parts != \"\"]\n v = -log10(as.numeric(parts[length(parts)]))\n names(v) = parts[[1]]\n return(v)\n})\n\nlibrary(org.Hs.eg.db)\nsuppressWarnings(ids <- AnnotationDbi::mapIds(org.Hs.eg.db, keys = names(BD.enrichment), keytype = \"ENSEMBL\", column = \"SYMBOL\", multiVals = \"first\"))\nmask = !is.na(ids)\nBD.enrichment = BD.enrichment[!is.na(ids)]\nnames(BD.enrichment) = ids[!is.na(ids)]\n\n\ncommon.genes = intersect(rownames(DE.sc), intersect(names(BD.enrichment), names(SZ.enrichment)))\n\nEn.df = data.frame(gene = common.genes, DE = DE.sc[common.genes, \"Ex-L45_LRRK1\"], BD = BD.enrichment[common.genes], SZ = SZ.enrichment[common.genes])\nEn.df$absDE = abs(En.df$DE)\nEn.df$joint = combine.logPvals(t(cbind(En.df$SZ, En.df$BD)))\n\nDE.genes = list(L45_LRRK1 = L45_LRRK1.DE.genes)\n\n# v.SZ = En.df$SZ\n# names(v.SZ) = En.df$gene\n# sz.enrichment = fgsea::fgsea(DE.genes, v.SZ, scoreType = \"pos\")\n# SZ.vs.DE.top = sz.enrichment$leadingEdge[[1]]\n# \n# \n# v.BD = En.df$BD\n# names(v.BD) = En.df$gene\n# bd.enrichment = fgsea::fgsea(DE.genes, v.BD, scoreType = \"pos\")\n# BD.vs.DE.top = bd.enrichment$leadingEdge[[1]]\n\n\nv.SZ = En.df$joint\nnames(v.SZ) = En.df$gene\nsz.enrichment = fgsea::fgsea(DE.genes, v.SZ, scoreType = \"pos\")\nSZ.vs.DE.top = sz.enrichment$leadingEdge[[1]]\n\n# intersect(BD.vs.DE.top, SZ.vs.DE.top)\n\n```\n\n" }, { "alpha_fraction": 0.6318651437759399, "alphanum_fraction": 0.6468732953071594, "avg_line_length": 33.05185317993164, "blob_id": "9fd07bfb52d9114eaa7c58f5bfd127ac22267ff9", "content_id": "3e73b40dc00dce3ab1c8cb457a8008d3ad79e431", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 9195, "license_type": "no_license", "max_line_length": 265, "num_lines": 270, "path": "/old/GWAS_HMAGMA.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"H-MAGMA analysis\"\noutput: html_notebook\n---\n\n# Setup\n```{r include=FALSE}\nlibrary(org.Hs.eg.db)\nrequire(ACTIONet)\nrequire(stringr)\nrequire(ComplexHeatmap)\n\n\nresults.path = \"~/results\"\ninput.path = \"~/results/input\"\ndataset.path = \"~/results/datasets\"\ntables.path = \"~/results/tables\"\nfigures.path = \"~/results/figures\"\nMAGMA.path = \"~/magma\"\n\n\n```\n\n## Enrichment function\n```{r}\nassess.genesets <-function (arch.gs, terms.gs, N, min.pval = 1e-100, correct = \"none\"){\n shared = t(sapply(terms.gs, function(gs1) {\n sapply(arch.gs, function(gs2) {\n nn = intersect(gs1, gs2)\n })\n }))\n colnames(shared) = names(arch.gs)\n GS.sizes = sapply(terms.gs, length)\n logPvals.out = sapply(1:ncol(shared), function(i) {\n gg = shared[, i]\n x = as.numeric(sapply(gg, length))\n n.sample = length(arch.gs[[i]])\n n.success = as.numeric(GS.sizes)\n v = rep(1, length(x))\n min.overlap = n.success * n.sample/N\n idx = which(x >= min.overlap)\n if (length(idx) == 0) \n return(v)\n v[idx] = (phyper(x[idx]-1, n.sample, N-n.sample, n.success[idx], lower.tail = F))\n # v[idx] = HGT_tail(population.size = N, success.count = n.success[idx], \n # sample.size = n.sample, observed.success = x[idx])\n return(v)\n })\n if(correct == \"global\") {\n logPvals.out = matrix(p.adjust(logPvals.out, \"fdr\"), nrow = nrow(logPvals.out))\n } else if(correct == \"local\") {\n logPvals.out = apply(logPvals.out, 2, function(x) p.adjust(x, \"fdr\"))\n }\n rownames(logPvals.out) = names(terms.gs)\n colnames(logPvals.out) = names(arch.gs)\n return(-log10(Matrix::t(logPvals.out)))\n}\n```\n\n# Load primary datasets\n```{r, eval = T}\nACTIONet_summary = readr::read_rds(file.path(dataset.path, \"ACTIONet_summary_filtered_individuals.rds\"))\npb.logcounts = readr::read_rds(file.path(dataset.path, \"PB_mean_logcounts_final.RDS\"))\n\ncolor.df = readRDS(file.path(dataset.path, \"celltype_colors.rds\"))\ncolors = color.df$color\nnames(colors) = color.df$celltype\n\n```\n\n\n# Load DE results\n```{r, eval = T}\nresDE = readr::read_rds(file.path(dataset.path, \"Cohort_specific_DE_results.rds\"))\nfiltered.tables = readr::read_rds(file.path(dataset.path, \"Cohort_specific_DE_results_filtered.rds\"))\ncombined.analysis.tables = readr::read_rds(file.path(dataset.path, \"meta_analysis_results.rds\"))\n\nDE.new = readRDS(file.path(dataset.path, \"DE_genes_pseudobulk.rds\"))\nUp.genes = DE.new$Up.genes\nDown.genes = DE.new$Down.genes\nDE.sc = DE.new$DE.sc\nordered.celltypes = rownames(X)[order(apply(X, 1, sum), decreasing = T)]\n\n```\n\n\n\n# Convert DE genes to ENSG and export\n```{r}\nrequire(org.Hs.eg.db)\n\nsuppressWarnings(ids <- AnnotationDbi::mapIds(org.Hs.eg.db, keys = row.names(DE.new$DE.sc), keytype = \"SYMBOL\", column = \"ENSEMBL\", multiVals = \"first\"))\nids[is.na(ids)] = \"\"\n\nUp.genes.ENSG = sapply(Up.genes, function(gs) {\n setdiff(sort(unique(ids[match(gs, rownames(pb.logcounts))])), \"\")\n})\nUp.genes.ENSG.df = reshape2::melt(Up.genes.ENSG)\nUp.genes.ENSG.df = Up.genes.ENSG.df[, c(2, 1)]\nUp.genes.ENSG.df$L1 = factor(Up.genes.ENSG.df$L1, names(Up.genes))\nUp.genes.ENSG.df = Up.genes.ENSG.df[order(Up.genes.ENSG.df$L1), ]\nwrite.table(Up.genes.ENSG.df, file.path(MAGMA.path, \"genesets\", \"Up_genes_ENSG.tsv\"), sep = \"\\t\", col.names = F, row.names = F, quote = F)\n\nDown.genes.ENSG = sapply(Down.genes, function(gs) {\n setdiff(sort(unique(ids[match(gs, rownames(pb.logcounts))])), \"\")\n})\nDown.genes.ENSG.df = reshape2::melt(Down.genes.ENSG)\nDown.genes.ENSG.df = Down.genes.ENSG.df[, c(2, 1)]\nDown.genes.ENSG.df$L1 = factor(Down.genes.ENSG.df$L1, names(Down.genes))\nDown.genes.ENSG.df = Down.genes.ENSG.df[order(Down.genes.ENSG.df$L1), ]\n\nwrite.table(Down.genes.ENSG.df, file.path(MAGMA.path, \"genesets\", \"Down_genes_ENSG.tsv\"), sep = \"\\t\", col.names = F, row.names = F, quote = F)\n\n\nUpAndDown.genes.ENSG.df = rbind(Up.genes.ENSG.df, Down.genes.ENSG.df)\nUpAndDown.genes.ENSG.df$L1 = factor(UpAndDown.genes.ENSG.df$L1, names(Up.genes))\nUpAndDown.genes.ENSG.df = UpAndDown.genes.ENSG.df[order(UpAndDown.genes.ENSG.df$L1), ]\n\nwrite.table(UpAndDown.genes.ENSG.df, file.path(MAGMA.path, \"genesets\", \"UpAndDown_genes_ENSG.tsv\"), sep = \"\\t\", col.names = F, row.names = F, quote = F)\n\n\n```\n\n\n\n\n\n# Run H-MAGMA\nWe run HMAGMA using **for f in `ls hmagma/`; do (./magma --gene-results ./hmagma/$f/$f.genes.raw --set-annot genesets/UpAndDown_genes_ENSG.tsv col=2,1 --out $f\\_UpAndDown &); done`**, from inside the magma folder, where hmagma are prestored the gene models scores.\n\n# Load H-MAGMA results\n\n```{r}\ndl = list.dirs(file.path(MAGMA.path, \"psych_arch/\"), full.names = F, recursive = F)\n\nHMAGMA.Pvals = vector(\"list\", 1)\nnames(HMAGMA.Pvals) = c(\"UpAndDown\")\nfor (d in names(HMAGMA.Pvals)) {\n HMAGMA.Pvals[[d]] = matrix(1, nrow = 20, ncol = length(dl))\n colnames(HMAGMA.Pvals[[d]]) = dl\n rownames(HMAGMA.Pvals[[d]]) = names(Up.genes)\n for(cond in dl) {\n print(cond)\n file.name = sprintf(\"%s/out/%s_%s.gsa.out\", MAGMA.path, cond, d)\n lines = readLines(con <- file(file.name))\n lines = str_split(lines, \"\\n\")[-c(1:5)]\n \n pvals = sapply(lines, function(ll) {\n parts = str_split(ll, \" \")\n as.numeric(parts[[1]][length(parts[[1]])])\n })\n \n names(pvals) = sapply(lines, function(ll) {\n parts = str_split(ll, \" \")\n parts[[1]][[1]]\n })\n\n HMAGMA.Pvals[[d]][names(pvals), cond] = pvals \n }\n}\n\n\nreadr::write_rds(HMAGMA.Pvals, file.path(dataset.path, \"HMAGMA_results_raw.rds\"))\n\n\n```\n\n# Or load preprocessed results\n```{r}\nHMAGMA.Pvals = readr::read_rds(file.path(dataset.path, \"HMAGMA_results_raw.rds\"))\n\nDF = HMAGMA.Pvals[[1]]\n\n\nstoreDataset(DF, \"HMAGMA_results\", dataset.path = dataset.path)\n\n```\n\n\n\n## Export selected results\n```{r}\n\n selected.traits = c(\"hmagmaAdultBrain__sz3\", \"hmagmaAdultBrain__bip2\", \"hmagmaAdultBrain__asd\", \"hmagmaAdultBrain__adhd\", \"hmagmaAdultBrain__mdd_without_23andMe\", \"hmagmaAdultBrain__alz2noapoe\")\n\ntrait.labels = c(\"Schizophrenia (SZ)\", \"Bipolar (BP)\",\"Autism (ASD)\", \"ADHD\", \"Depression (MDD)\", \"Alzheimer (AD)\")\n\nX = HMAGMA.Pvals$UpAndDown[, selected.traits]\ncts = intersect(color.df$celltype, rownames(X))\nX = X[cts, ]\nX = matrix(p.adjust(as.numeric(X), \"fdr\"), nrow = length(cts))\nrownames(X) = cts\n# X = apply(X, 2, function(p) p.adjust(p, \"fdr\"))\nrownames(X) = intersect(names(colors), rownames(X))\nX = -log10(X)\nX[X < -log10(0.05)] = 0\ncolnames(X) = trait.labels\nrownames(X) = cts\n\nPurPal = colorRampPalette(RColorBrewer::brewer.pal(9, \"Purples\"))(200)\nPurPal = c(rep(PurPal[1], length(PurPal)*(sum(X < 1) / length(X))), PurPal)\n\nrequire(corrplot)\npdf(file.path(figures.path, \"HMAGMA_adultBrain.pdf\"), width =7, height = 7)\ncorrplot(X, is.corr = F, method = \"pie\", col = PurPal, cl.lim = c(0, 4), cl.length = 5, outline = T, sig.level = 0.05, p.mat = 10^(-X), insig = \"blank\", tl.col = \"black\")\ndev.off()\n\nX = X[grep(\"^In|^Ex\", rownames(X)), ]\nrequire(corrplot)\npdf(file.path(figures.path, \"HMAGMA_adultBrain_neuro.pdf\"), width =7, height = 7)\ncorrplot(X, is.corr = F, method = \"pie\", col = PurPal, cl.lim = c(0, 4), cl.length = 5, outline = T, sig.level = 0.05, p.mat = 10^(-X), insig = \"blank\", tl.col = \"black\")\ndev.off()\n\n```\n\n# Plot \"volcanos\"\n## Load H-MAGMA gene p-values\n```{r}\ntbl = read.table(\"~/magma/hmagma/hmagmaAdultBrain__sz3/hmagmaAdultBrain__sz3.genes.out\", header = T)\nsuppressWarnings(ids <- AnnotationDbi::mapIds(org.Hs.eg.db, keys = tbl$GENE, keytype = \"ENSEMBL\", column = \"SYMBOL\", multiVals = \"first\"))\nids[is.na(ids)] = \"\"\n\nscores = rep(0, nrow(pb.logcounts))\nii = match(rownames(pb.logcounts), ids)\nscores[!is.na(ii)] = -log10(tbl$P[ii[!is.na(ii)]])\nnames(scores) = rownames(pb.logcounts)\n\nsort(scores, decreasing = T)[1:30]\n\n```\n\n```{r}\nselected.cts = c(\"Ex-L45_LRRK1\", \"In-PV_Basket\", \"Oli\")\nidx = match(selected.cts, colnames(DE.new$DE.sc))\n\nt.threshold = 3\nmagma.pval.threshold = 0.05\n\nGrobs = vector(\"list\", length(idx))\nfor(i in 1:length(idx)) {\n k = idx[[i]]\n df = data.frame(\"log2FoldChange\" = DE.new$DE.sc[, k], \"pvalue\" = 10^(-scores))\n rownames(df) = rownames(DE.new$DE.sc)\n df = df[df$log2FoldChange != 0, ]\n \n keyvals <- rep('#cccccc', nrow(df))\n names(keyvals) <- rep('None', nrow(df))\n \n keyvals[which( (df$log2FoldChange > t.threshold) & (df$pvalue < magma.pval.threshold) )] <- '#ca0020'\n names(keyvals)[which( (df$log2FoldChange > t.threshold) & (df$pvalue < magma.pval.threshold) )] <- rep('Up', sum(keyvals == '#ca0020'))\n \n keyvals[which( (df$log2FoldChange < -t.threshold) & (df$pvalue < magma.pval.threshold) )] <- '#0571b0'\n names(keyvals)[which( (df$log2FoldChange < -t.threshold) & (df$pvalue < magma.pval.threshold) )] <- rep('Down', sum(keyvals == '#0571b0'))\n \n \n \n Grobs[[i]] = EnhancedVolcano(df,\n lab = rownames(df),\n x = 'log2FoldChange',\n y = 'pvalue', pCutoff = magma.pval.threshold, FCcutoff = t.threshold, xlim = c(-4, 4), ylim = c(0, 20), title = \"H-MAGMA pvals-vs-DE tstats\", subtitle = colnames(DE.new$logFC)[[k]], colCustom = keyvals, labCol = 'black',\n labFace = 'bold', caption = \"\")\n} \n\npdf(file.path(figures.path, \"HMAGMA_vs_DE.pdf\"), width = 8*3, height = 8*1)\ngridExtra::grid.arrange( grobs = Grobs, nrow = 1)\ndev.off()\n\n\n\n```\n\n" }, { "alpha_fraction": 0.6392350792884827, "alphanum_fraction": 0.6469703316688538, "avg_line_length": 32.48201370239258, "blob_id": "b20fa895e04be566d7adcd016726c782b673051a", "content_id": "81a9a553ba02f98aedd2a0b46808686367d84971", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 4654, "license_type": "no_license", "max_line_length": 123, "num_lines": 139, "path": "/functions.R", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "synapse.project.id = \"syn22755334\"\nsynapse.results.folder = \"syn25910026\"\n\nSyn.datasets <- Folder(name = \"datasets\", parentId = synapse.results.folder)\nSyn.tables <- Folder(name = \"tables\", parentId = synapse.results.folder)\nSyn.figures <- Folder(name = \"figures\", parentId = synapse.results.folder)\nSyn.input <- Folder(name = \"input\", parentId = synapse.project.id)\n\n# Functions to Pull/Push objects from/to Synapse\nstoreDataset = function( obj, name, description = NULL, dataset.path = \"results/datasets\"){\n file_name = paste0(name, \".rds\")\n file_path = file.path(dataset.path, file_name)\n readr::write_rds( obj, file=file_path)\n \n Syn.datasets <- synStore(Syn.datasets)\n folder = Syn.datasets$properties$id\n if(is.null(description)) {\n description = file_name\n }\t\n OBJ = File(file_path, name = description, parentId = folder)\n \n suppressWarnings( {suppressMessages( {out = synStore(OBJ)} )} )\t\n}\n\n# Store Table\nstoreTable = function( DFs, name, description = NULL, tables.path = \"results/tables\"){\n if(is.null(names(DFs))) {\n names(DFs) = paste(\"Table\", 1:length(DFs), sep = \"\")\n }\n wb <- openxlsx::createWorkbook()\n for(i in 1:length(DFs)) {\n n = names(DFs)[[i]] \n openxlsx::addWorksheet(wb=wb, sheetName = n)\n openxlsx::writeData(wb, sheet = n, DFs[[i]]) \n }\n file_name = paste0(name, \".xlsx\")\n file_path = file.path(tables.path, file_name)\n openxlsx::saveWorkbook(wb, file_path, overwrite = TRUE)\n \n Syn.tables <- synStore(Syn.tables)\n folder = Syn.tables$properties$id\n if(is.null(description)) {\n description = file_name\n }\n OBJ = File(path = file_path, name = description, parentId = folder)\n \n suppressWarnings( {suppressMessages( {out = synStore(OBJ)} )} )\t\n}\n\n# Store figure\nstoreFigure = function( gg, name, extension, description = NULL, width = 10, height = 8, figures.path = \"results/figures\"){\n if(extension == \"png\") {\n file_name = paste0(name, \".png\")\n file_path = file.path(figures.path, file_name)\n png(file_path, width = width, height = height, units = \"in\", res = 300)\n } else if(extension == \"pdf\") {\n file_name = paste0(name, \".pdf\")\n file_path = file.path(figures.path, file_name)\n pdf(file_path, width = width, height = height)\n }\n print(gg)\n dev.off()\n \n Syn.figures <- synStore(Syn.figures)\n folder = Syn.figures$properties$id\n if(is.null(description)) {\n description = file_name\n } \n OBJ = File(path = file_path, name = description, parentId = folder)\n \n suppressWarnings( {suppressMessages( {out = synStore(OBJ)} )} )\n}\n\n# Load a dataset, either locally or fetch from Synapse\nloadDataset = function( name, dataset.path = \"results/datasets\" ){\n file_name = paste0(name, \".rds\")\n file_path = file.path(dataset.path, file_name)\n if(!file.exists(file_path)) {\n Syn.datasets <- synStore(Syn.datasets)\n folder = Syn.datasets$properties$id\n \n syn.files = synChildren(folder)\n mask = names(syn.files) == file_name\n if(sum(mask) == 0) {\n warning(sprintf(\"Did not find file %s\", file_name))\n return()\n } else {\n syn.id = as.character(syn.files[which(mask == T)[[1]]])\n entity <- synGet(syn.id, downloadLocation = dataset.path) \t\n }\n }\n obj = readr::read_rds( file_path )\n \n return(obj)\n}\n\n# Load an \"input\" dataset, either locally or fetch from Synapse\nloadInputDataset = function( name, extension, input.path = \"input\" ){\n file_name = paste(name, extension, sep = \".\")\n file_path = file.path(dataset.path, file_name)\n if(!file.exists(file_path)) {\n Syn.input <- synStore(Syn.input)\n folder = Syn.input$properties$id\n \n syn.files = synChildren(folder)\n mask = names(syn.files) == file_name\n if(sum(mask) == 0) {\n warning(sprintf(\"Did not find file %s\", file_name))\n return()\n } else {\n syn.id = as.character(syn.files[which(mask == T)[[1]]])\n entity <- synGet(syn.id, downloadLocation = dataset.path) \t\n }\n }\n if(extension == \"csv\") {\n obj = readr::read_csv(file_path, col_types=readr::cols()) \n } else if(extension == \"tsv\" | extension == \"tab\" | extension == \"txt\") {\n obj = readr::read_tsv(file_path, col_types=readr::cols()) \n } else if(extension == \"rds\" | extension == \"RDS\") {\n obj = readr::read_rds(file_path)\n }\n \n return(obj)\n}\n\nqueryChEA3 <- function(genes, url = \"https://maayanlab.cloud/chea3/api/enrich/\") {\n library(httr)\n library(jsonlite)\n \n encode = \"json\"\n payload = list(query_name = \"myQuery\", gene_set = genes)\n \n #POST to ChEA3 server\n response = POST(url = url, body = payload, encode = encode)\n json = content(response, \"text\")\n \n #results as list of R dataframes\n results = fromJSON(json)\n}\n" }, { "alpha_fraction": 0.6628392934799194, "alphanum_fraction": 0.6829990744590759, "avg_line_length": 47.33503723144531, "blob_id": "081cc7c0a907b5bac0b55c43f74a095abec76ff5", "content_id": "55a6ea2e67880a083dd727a38d8a90b525473235", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 18899, "license_type": "no_license", "max_line_length": 912, "num_lines": 391, "path": "/ancient/Fig3_GWAS_Manhattan_panels.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"Fig3: H-MAGMA analysis\"\noutput: html_notebook\n---\n\n# Setup\n```{r include=FALSE}\nlibrary(org.Hs.eg.db)\n\nsource(\"manhattan.R\")\n\ninput.path = \"~/results/input/\"\ndataset.path = \"~/results/datasets/\"\nresults.path = \"~/results\"\nfigures.folder = \"~/results/figures\"\n\nexport.path = \"~/magma/genesets\"\nMAGMA.path = \"~/magma/\"\n\n```\n\n# Load DE genes\n```{r include=FALSE}\ncolors = readRDS(file.path(dataset.path, \"celltype_colors.rds\"))\nDE.new = readRDS(file.path(dataset.path, \"DE_genes_pseudobulk_final.rds\"))\n\nUp.genes = DE.new$Up.genes\nDown.genes = DE.new$Down.genes\nDE.scores = sign(DE.new$logFC) * (DE.new$logPvals) # tstats\nDE.scores.sig = DE.scores\nDE.scores.sig[(abs(DE.new$logFC) < 0.1) | (DE.new$logPvals < -log10(0.05))] = 0\n\nrdbu_fun = circlize::colorRamp2(c(-3, log10(0.05), 0, -log10(0.05), 3), rev(pals::brewer.rdbu(9)[seq(1, 9, by = 2)]))\nsorted.celltypes = intersect(names(colors), colnames(DE.sc))\n\n\n```\n\n# Map DE genes to the most dysregulated cell types\n\n```{r}\ntop.scores = apply(DE.scores.sig, 1, function(x) {x[which.max(abs(x))]})\ntop.scores = apply(DE.scores.sig, 1, function(x) {x[which.max(abs(x))]})\n\n\ntop.celltype = apply(DE.scores.sig, 1, function(x) {colnames(DE.scores.sig)[which.max(abs(x))]})\nassigned.genes2celltype.df = data.frame(gene = rownames(DE.scores.sig), celltype = top.celltype, score = top.scores)\nassigned.genes2celltype.df$dir = \".\"\nassigned.genes2celltype.df$dir[assigned.genes2celltype.df$score > 0] = \"Up\"\nassigned.genes2celltype.df$dir[assigned.genes2celltype.df$score < 0] = \"Down\"\n\n```\n\n\n## Load significant variants and mapped genes\n```{r}\nPGC3.finemapped.genes.tbl = read.table(file.path(input.path, \"Prioritised_PGC3_SZ_Genes.csv\"), sep = \"\\t\", header = T)\nPGC3.loci = read.table(file.path(input.path, \"PGC3_SZ_significant_loci.csv\"), sep = \"\\t\", header = T)\n\nassociated.genes = PGC3.loci$ENSEMBL.genes..all..clear.names.\n\n\nPGC3.all.genes.raw = sort(unique(unlist(sapply(PGC3.loci$ENSEMBL.genes..all..clear.names., function(str) {\n if(str == \"-\") {\n return(\"-\")\n }\n gs = str_split(str, \",\")[[1]]\n \n return(gs)\n}))))\n\nPGC3.all.genes = intersect(PGC3.all.genes.raw, rownames(DE.scores))\n\n\n \nPGC3.loci$selected.genes = sapply(PGC3.loci$ENSEMBL.genes..all..clear.names., function(str) {\n if(str == \"-\") {\n return(\"-\")\n }\n gs = intersect(str_split(str, \",\")[[1]], assigned.genes2celltype.df$gene)\n if(length(gs) == 0)\n return(\"-\")\n else \n ss = abs(assigned.genes2celltype.df$score[match(gs, assigned.genes2celltype.df$gene)])\n if(sum(abs(ss)) == 0)\n return(\"-\")\n else\n return(gs[which.max(ss)])\n})\n\n\nPGC3.loci.finemapped = PGC3.loci[PGC3.loci$top.index %in% PGC3.finemapped.genes.tbl$Index.SNP, ]\n\nPGC3.loci.finemapped$finemapped.gene = PGC3.finemapped.genes.tbl$Symbol.ID[match(PGC3.loci.finemapped$top.index, PGC3.finemapped.genes.tbl$Index.SNP)]\n```\n\n\n## Visualize the heatmap of DE for variants-associated genes\n```{r}\nPGC3.loci.finemapped.filtered = PGC3.loci.finemapped[PGC3.loci.finemapped$selected.genes != \"-\", ]\nPGC3.loci.finemapped.filtered$match.finemapping = PGC3.loci.finemapped.filtered$selected.genes == PGC3.loci.finemapped.filtered$finemapped.gene\n\nX = DE.scores[PGC3.loci.finemapped.filtered$selected.genes[PGC3.loci.finemapped.filtered$match.finemapping == T], ]\nX = X[rowSums(X !=0)>0, ]\n\npdf(file.path(figures.folder, \"PGC3_top_matched_genes_finemapped.pdf\"), height = 12, width = 6)\nHeatmap(X[, sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]], rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_rows = T, cluster_columns = F, col = rdbu_fun, name = \"Neuro (Ex)\", column_title = \"Neuro (Ex)\") + Heatmap(X[, sorted.celltypes[grepl(\"^In\", sorted.celltypes)]], rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^In\", sorted.celltypes)]]), cluster_columns = F, col = rdbu_fun, name = \"Neuro (In)\", column_title = \"Neuro (In)\") + Heatmap(X[, sorted.celltypes[!grepl(\"^Ex|^In\", sorted.celltypes)]], rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[!grepl(\"^In|^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_columns = F, col = rdbu_fun, name = \"Glial\", column_title = \"Glial\")\ndev.off()\n\n\n# pdf(file.path(figures.folder,\"GWAS_panels\", \"PGC3_top_matched_genes_finemapped_genome_order.pdf\"), height = 12, width = 6)\n# Heatmap(X[, sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]], rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_rows = F, cluster_columns = F, col = rdbu_fun, name = \"Neuro (Ex)\", column_title = \"Neuro (Ex)\") + Heatmap(X[, sorted.celltypes[grepl(\"^In\", sorted.celltypes)]], rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^In\", sorted.celltypes)]]), cluster_columns = F, col = rdbu_fun, name = \"Neuro (In)\", column_title = \"Neuro (In)\") + Heatmap(X[, sorted.celltypes[!grepl(\"^Ex|^In\", sorted.celltypes)]], rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[!grepl(\"^In|^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_columns = F, col = rdbu_fun, name = \"Glial\", column_title = \"Glial\")\n# dev.off()\n\n\n\nX = DE.scores[PGC3.loci.finemapped.filtered$selected.genes, ]\nX = X[rowSums(X !=0)>0, ]\n\npdf(file.path(figures.folder, \"PGC3_top_matched_genes.pdf\"), height = 18, width = 6)\nHeatmap(X[, sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]], rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_rows = T, cluster_columns = F, col = rdbu_fun, name = \"Neuro (Ex)\", column_title = \"Neuro (Ex)\") + Heatmap(X[, sorted.celltypes[grepl(\"^In\", sorted.celltypes)]], rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^In\", sorted.celltypes)]]), cluster_columns = F, col = rdbu_fun, name = \"Neuro (In)\", column_title = \"Neuro (In)\") + Heatmap(X[, sorted.celltypes[!grepl(\"^Ex|^In\", sorted.celltypes)]], rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[!grepl(\"^In|^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_columns = F, col = rdbu_fun, name = \"Glial\", column_title = \"Glial\")\ndev.off()\n\npdf(file.path(figures.folder, \"GWAS_panels\", \"PGC3_top_matched_genes_genome_order.pdf\"), height = 18, width = 6)\nHeatmap(X[, sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]], rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_rows = F, cluster_columns = F, col = rdbu_fun, name = \"Neuro (Ex)\", column_title = \"Neuro (Ex)\") + Heatmap(X[, sorted.celltypes[grepl(\"^In\", sorted.celltypes)]], rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^In\", sorted.celltypes)]]), cluster_columns = F, col = rdbu_fun, name = \"Neuro (In)\", column_title = \"Neuro (In)\") + Heatmap(X[, sorted.celltypes[!grepl(\"^Ex|^In\", sorted.celltypes)]], rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[!grepl(\"^In|^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_columns = F, col = rdbu_fun, name = \"Glial\", column_title = \"Glial\")\ndev.off()\n\n```\n\n# Export individual columns \n```{r}\nX = as.matrix(assigned.genes2celltype.df$score[match(PGC3.loci.finemapped.filtered$selected.genes, assigned.genes2celltype.df$gene)])\npdf(file.path(figures.folder, \"GWAS_panels\", \"PGC3_mapped_ordered_genes_topMap_notlabeled.pdf\"), height = 42, width = 1.5)\nHeatmap(X, rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_rows = F, cluster_columns = F, col = rdbu_fun, name = \"Enrichment\")\ndev.off()\n\nrownames(X) = PGC3.loci.finemapped.filtered$selected.genes\npdf(file.path(figures.folder, \"GWAS_panels\", \"PGC3_mapped_ordered_genes_topMap_labeled.pdf\"), height = 42, width = 2.5)\nHeatmap(X, rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_rows = F, cluster_columns = F, col = rdbu_fun, name = \"Enrichment\", row_names_side = \"left\")\ndev.off()\n\n\n\nX = as.matrix(factor(assigned.genes2celltype.df$celltype[match(PGC3.loci.finemapped.filtered$selected.genes, assigned.genes2celltype.df$gene)], levels = names(colors)))\nX[assigned.genes2celltype.df$score[match(PGC3.loci.finemapped.filtered$selected.genes, assigned.genes2celltype.df$gene)] == 0, 1] = NA\npdf(file.path(figures.folder, \"GWAS_panels\", \"PGC3_mapped_ordered_genes_topMap_celltype.pdf\"), height = 42, width = 2.5)\nHeatmap(X, rect_gp = gpar(col = \"black\"), cluster_rows = F, cluster_columns = F, col = colors, name = \"Celltype\", na_col = \"black\")\ndev.off()\n\nrownames(X) = as.character(assigned.genes2celltype.df$celltype[match(PGC3.loci.finemapped.filtered$selected.genes, assigned.genes2celltype.df$gene)])\nrownames(X)[assigned.genes2celltype.df$score[match(PGC3.loci.finemapped.filtered$selected.genes, assigned.genes2celltype.df$gene)] == 0] = NA\npdf(file.path(figures.folder, \"GWAS_panels\", \"PGC3_mapped_ordered_genes_topMap_celltype_withlabels.pdf\"), height = 42, width = 4.5)\nHeatmap(X, rect_gp = gpar(col = \"black\"), cluster_rows = F, cluster_columns = F, col = colors, name = \"Celltype\", row_names_side = \"left\", na_col = \"black\")\ndev.off()\n\n\n```\n\n\n# Plot Manhattan\n```{r}\nSCZ.GWAS = read.csv(file.path(input.path, 'PGC3_SCZ_wave3_public.v2.tsv'), sep = \"\\t\")\nval = as.numeric(SCZ.GWAS$CHR)\nSCZ.GWAS=SCZ.GWAS[!is.na(val), ]\nSCZ.GWAS$CHR = val[!is.na(val)]\n\nSCZ.GWAS.annotated = SCZ.GWAS\n\nidx = match(PGC3.loci.finemapped.filtered$top.index, SCZ.GWAS.annotated$SNP)\n\nSCZ.GWAS.annotated$Labels = \"\"\nSCZ.GWAS.annotated$Labels.col = \"#ffffff\"\n\n\nSCZ.GWAS.annotated$Labels[idx] = paste(\"(\", SCZ.GWAS.annotated$SNP[idx], \")-(\", PGC3.loci.finemapped.filtered$selected.genes, \")-(\", assigned.genes2celltype.df$celltype[match(PGC3.loci.finemapped.filtered$selected.genes, assigned.genes2celltype.df$gene)], \")-(\", assigned.genes2celltype.df$dir[match(PGC3.loci.finemapped.filtered$selected.genes, assigned.genes2celltype.df$gene)], \")\", sep = \"\")\nSCZ.GWAS.annotated$Labels.col[idx] = colors[assigned.genes2celltype.df$celltype[match(PGC3.loci.finemapped.filtered$selected.genes, assigned.genes2celltype.df$gene)]]\n\n\n\n# iii = which(SCZ.GWAS.annotated$Labels != \"\")\n\n```\n\n## Compute Manhattan\n```{r}\nDd = manhattan.compute(SCZ.GWAS.annotated, cex = 0.15, cex.axis = 0.5, suggestiveline = F, ylim = c(0, -log10(min(sig.SCZ.GWAS$P))), annotateLabels = T)\n\n```\n\n## Plot Manhattan without Labels\n```{r}\n\niii = c(which(Dd$Labels != \"\"), which.max(Dd$pos))\nXd = Dd[iii, ]\n\npdf(\"~/PFC_v3/figures/SCZ_Manh_sig_aligned.pdf\", width = 12, height = 6)\n# png(\"~/PFC_v3/figures/SCZ_Manh_sig_aligned_annotatede.png\", width = 2400, height = 1200, res = 300)\nmanhattan.plot(Xd, cex = 0.15, cex.axis = 0.5, suggestiveline = F, ylim = c(0, -log10(min(SCZ.GWAS$P))), annotateLabels = NULL)\ndev.off()\n\n\npdf(\"SCZ_Manh_sigOnly_aligned_v3.pdf\", width = 12, height = 6)\n# png(\"SCZ_Manh_all_aligned.png\", width = 2400, height = 1200, res = 300)\nmanhattan.plot(X, cex = 0.15, cex.axis = 0.5, suggestiveline = F, ylim = c(0, -log10(min(SCZ.GWAS$P))), annotateLabels = NULL)\ndev.off()\n\n```\n\n## Plot Manhattan with Labels\n```{r}\niii = c(which(Dd$Labels != \"\"), which.max(Dd$pos))\nXd = Dd[iii, ]\n\ngg = as.character(sapply(Xd$Labels[-nrow(Xd)], function(str) {\n x = str_split(str, \"-\")[[1]][[2]]\n gg = substr(x, 2, str_length(x)-1)\n}))\n\nx = assigned.genes2celltype.df$score[match(gg, assigned.genes2celltype.df$gene)]\n\n\nNA_col = \"#eeeeee\"\ngrad_palette = (grDevices::colorRampPalette(rev(RColorBrewer::brewer.pal(n = 7, name = \"RdBu\"))))(100)\ncol_func = (scales::col_bin(palette = grad_palette, domain = NULL, na.color = NA_col, bins = 7))\nXd$Point.col = plot_fill_col = c(col_func(x), \"#000000\")\n\nXd$FullLabels = Xd$Labels\nXd$Labels = c(gg, \"\")\n\n\n\n\npdf(file.path(figures.folder, \"GWAS_panels\", \"SCZ_Manh_sig_aligned.pdf\"), width = 12, height = 6)\nmanhattan.plot(Xd, cex = 0.15, cex.axis = 0.5, suggestiveline = F, ylim = c(0, -log10(min(SCZ.GWAS$P))), annotateLabels = NULL)\ndev.off()\n\npdf(file.path(figures.folder, \"GWAS_panels\", \"SCZ_Manh_sig_aligned_labels.pdf\"), width = 12, height = 6)\nmanhattan.plot(Xd, cex = 0.15, cex.axis = 0.5, suggestiveline = F, ylim = c(0, -log10(min(SCZ.GWAS$P))), annotateLabels = T)\ndev.off()\n\n```\n\n```{r}\ntbl = read.table(\"~/magma/hmagma/hmagmaAdultBrain__sz3/hmagmaAdultBrain__sz3.genes.out\", header = T)\nsuppressWarnings(ids <- AnnotationDbi::mapIds(org.Hs.eg.db, keys = tbl$GENE, keytype = \"ENSEMBL\", column = \"SYMBOL\", multiVals = \"first\"))\nids[is.na(ids)] = \"\"\n\nscores = rep(0, nrow(PGC3.loci.finemapped.filtered))\nii = match(PGC3.loci.finemapped.filtered$selected.genes, ids)\nscores[!is.na(ii)] = -log10(tbl$P[ii[!is.na(ii)]])\n\n\nPurPal = colorRampPalette(RColorBrewer::brewer.pal(9, \"Purples\"))(200)\n\nX = as.matrix(scores)\npdf(file.path(figures.folder, \"GWAS_panels\", \"HMAGMA_scores.pdf\"), height = 42, width = 1.5)\nHeatmap(X, rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_rows = F, cluster_columns = F, col = PurPal, name = \"Enrichment\", show_row_names = F)\ndev.off()\n\nrownames(X) = PGC3.loci.finemapped.filtered$selected.genes\npdf(file.path(figures.folder, \"GWAS_panels\", \"HMAGMA_scores_labeled.pdf\"), height = 42, width = 2.5)\nHeatmap(X, rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_rows = F, cluster_columns = F, col = PurPal, name = \"Enrichment\", row_names_side = \"left\")\ndev.off()\n\n\n```\n\n```{r}\nABC = read.table(file.path(input.path, \"AllPredictions.AvgHiC.ABC0.015.minus150.ForABCPaperV3.txt\"), header = T, sep = \"\\t\")\n\nABC.celltypes = sort(unique(ABC$CellType))\n\n```\n\n\n```{r}\nCOLOC = read.table(file.path(input.path, \"coloc_result_for_meta-eQTL_SCZ3-GWAS.txt\"), header = T, sep = \"\\t\")\n\n\ngg = sapply(COLOC$Gene_eQTLorder.Trait, function(x) str_split(x, \"_\")[[1]][[1]])\n\nposter = sapply(PGC3.loci.finemapped.filtered$ENSEMBL.genes..all..ENSEMBL.IDs., function(x) {\n idx = match(str_split(x, \",\")[[1]], gg)\n if(sum(!is.na(idx)) == 0)\n return(NA)\n else\n max(COLOC$H4_PP[idx[!is.na(idx)]])\n})\nnames(poster) = PGC3.loci.finemapped.filtered$selected.genes\n\n\n```\n\n\n\n```{r}\n# tbl = read.table(\"~/magma/hmagma/hmagmaAdultBrain__sz3/hmagmaAdultBrain__sz3.genes.out\", header = T)\n# suppressWarnings(ids <- AnnotationDbi::mapIds(org.Hs.eg.db, keys = tbl$GENE, keytype = \"ENSEMBL\", column = \"SYMBOL\", multiVals = \"first\"))\n# ids[is.na(ids)] = \"\"\n\nrr = match(PGC3.loci.finemapped.filtered$top.index, SCZ.GWAS$SNP)\nscores = round(-log10(SCZ.GWAS$P[rr]), 1)\nnames(scores) = PGC3.loci.finemapped.filtered$top.index\n\n\n\n\n# scores = rep(0, nrow(PGC3.loci.finemapped.filtered))\n# ii = match(PGC3.loci.finemapped.filtered$selected.genes, ids)\n# scores[!is.na(ii)] = -log10(tbl$P[ii[!is.na(ii)]])\n\n\npdf(file.path(figures.folder, \"GWAS_panels\", \"SNP_scores_labeled_v3.pdf\"), height = 42, width = 2.5)\nHeatmap(as.matrix(scores), cluster_rows = F, name = \"enrichment\", col = PurPal,\n cell_fun = function(j, i, x, y, width, height, fill) {\n grid.text(sprintf(\"%.1f\", as.matrix(scores)[i, j]), x, y, gp = gpar(fontsize = 10))\n})\ndev.off()\n\n\n\nmask = as.numeric(PGC3.loci.finemapped.filtered$match.finemapping)\nnames(mask) = PGC3.loci.finemapped.filtered$finemapped.gene\n\npdf(file.path(figures.folder, \"GWAS_panels\", \"finemapped_genes.pdf\"), height = 42, width = 2.8)\nHeatmap(as.matrix(mask), cluster_rows = F, rect_gp = gpar(col = \"black\"), col = c(\"white\", \"gray\"), name = \"Fine-mapped\")\ndev.off()\n\n\n\n\n# PGC3.loci.finemapped.filtered$top.P[[15]] = sprintf('%e', 0.000000015)\n\nscores = sapply(PGC3.loci.finemapped.filtered$top.P, function(x) {\n #x = round(-log10(as.numeric(x)))\n #if(is.na(x))\n x = as.numeric(str_split(x, \"-\")[[1]][[2]])\n # x[!is.na(x)]\n})\n\nnames(scores) = PGC3.loci.finemapped.filtered$top.index\n\nPurPal = colorRampPalette(RColorBrewer::brewer.pal(9, \"Purples\"))(200)\n\nX = as.matrix(scores)\npdf(file.path(figures.folder, \"GWAS_panels\", \"SNP_scores.pdf\"), height = 42, width = 1.5)\nHeatmap(X, rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_rows = F, cluster_columns = F, col = PurPal, name = \"Enrichment\", show_row_names = F)\ndev.off()\n\npdf(file.path(figures.folder, \"GWAS_panels\", \"SNP_scores_labeled.pdf\"), height = 42, width = 2.5)\nHeatmap(X, rect_gp = gpar(col = \"black\"), column_names_gp = gpar(col = colors[sorted.celltypes[grepl(\"^Ex\", sorted.celltypes)]]), show_column_dend = F, show_row_dend = F, cluster_rows = F, cluster_columns = F, col = PurPal, name = \"Enrichment\", row_names_side = \"left\")\ndev.off()\n\n```\n\n\n```{r}\nSCZ.GWAS.annotated.ext = SCZ.GWAS\n\nidx = match(PGC3.loci.finemapped$top.index, SCZ.GWAS.annotated.ext$SNP)\nmask = (!is.na(idx)) & (PGC3.loci.finemapped$selected.genes == \"-\")\nDF = PGC3.loci.finemapped[mask, ]\nidx = idx[mask]\n\n\nSCZ.GWAS.annotated.ext$Labels = \"\"\nSCZ.GWAS.annotated.ext$Labels.col = \"#ffffff\"\n\n\nSCZ.GWAS.annotated.ext$Labels[idx] = DF$finemapped.gene # paste(\"(\", SCZ.GWAS.annotated$SNP[idx], \")-(\", PGC3.loci.finemapped.filtered$selected.genes, \")-(\", assigned.genes2celltype.df$celltype[match(PGC3.loci.finemapped.filtered$selected.genes, assigned.genes2celltype.df$gene)], \")-(\", assigned.genes2celltype.df$dir[match(PGC3.loci.finemapped.filtered$selected.genes, assigned.genes2celltype.df$gene)], \")\", sep = \"\")\nSCZ.GWAS.annotated.ext$Labels.col[idx] = colors[assigned.genes2celltype.df$celltype[match(DF$selected.genes, assigned.genes2celltype.df$gene)]]\n\nDd.ext = manhattan.compute(SCZ.GWAS.annotated.ext, cex = 0.15, cex.axis = 0.5, suggestiveline = F, ylim = c(0, -log10(min(sig.SCZ.GWAS$P))), annotateLabels = T)\n\n\n\niii = c(which(Dd.ext$Labels != \"\"), which.max(Dd.ext$pos))\nXd = Dd.ext[iii, ]\n\nXd$Point.col = \"#000000\"\n\n\npdf(file.path(figures.folder, \"GWAS_panels\", \"SCZ_Manh_sig_aligned.pdf\"), width = 12, height = 6)\nmanhattan.plot(Xd, cex = 0.15, cex.axis = 0.5, suggestiveline = F, ylim = c(0, -log10(min(SCZ.GWAS$P))), annotateLabels = NULL)\ndev.off()\n\npdf(file.path(figures.folder, \"GWAS_panels\", \"SCZ_Manh_sig_aligned_labels_finemapped.pdf\"), width = 12, height = 6)\nmanhattan.plot(Xd, cex = 0.15, cex.axis = 0.5, suggestiveline = F, ylim = c(0, -log10(min(SCZ.GWAS$P))), annotateLabels = T)\ndev.off()\n\n```\n" }, { "alpha_fraction": 0.6757559180259705, "alphanum_fraction": 0.6876318454742432, "avg_line_length": 31.721227645874023, "blob_id": "7427b633170d9af3deb7b97ca44461d1932ca04b", "content_id": "cd677a75e0d7025d8710f1452f0af59ebff76d57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 12799, "license_type": "no_license", "max_line_length": 328, "num_lines": 391, "path": "/RunDE_performMetaAnalysis.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"Perform DE analysis\"\nsubtitle: \"Step 1: Compute pseudobulk (PB) profiles\"\nauthor: \"Shahin Mohammadi\"\ndate: \"Run on `r Sys.time()`\"\ndocumentclass: article\noutput:\n html_document:\n toc: true\n toc_float: true\n---\n\n```{r setup, include=FALSE}\nsuppressPackageStartupMessages({\nlibrary(ACTIONet)\nlibrary(data.table)\nlibrary(ggplot2)\nlibrary(ggrepel)\nlibrary(cowplot)\nlibrary(corrplot)\nlibrary(limma)\nlibrary(muscat)\nlibrary(metafor)\nlibrary(ggcorrplot)\nlibrary(synapser)\nlibrary(synExtra)\nsynLogin(rememberMe = TRUE)\nsource(\"functions.R\")\n})\n\nknitr::opts_chunk$set(\n\teval = FALSE,\n\terror = FALSE,\n\tmessage = FALSE,\n\twarning = FALSE,\n\tcache = TRUE,\n\tdev = c(\"png\", \"pdf\"),\n\tinclude = FALSE,\n\ttidy = FALSE\n)\n\n\n```\n\n\n# Setup environment\n```{r}\ndataset.path = \"~/results/datasets/\"\nfigures.path = \"~/results/figures\"\ntables.path = \"~/results/tables\"\ninput.path = \"~/results/input\"\n\ndev_threshold = 1 # logFC needs to be 1 std away from 0 (in both datasets) prior to metanalysis\n\n# Thresholds on the FDR-corrected meta-analysis results\npval_threshold = 0.05\nlogFC_threshold = 0.1\n\n# Load pseudobulk samples\npb.sce = loadDataset(\"pseudobulk_mean_logcounts\", dataset.path = dataset.path)\nACTIONet_summary = loadDataset(\"ACTIONet_summary\", dataset.path = dataset.path)\ncolors = loadDataset(\"celltype_colors\", dataset.path = dataset.path)\n\n\n```\n\n\n# Prefilter outlier samples using % of excitatory neurons\nSZ33 is removed due to having > 80% ExNeu, and samples SZ3, SZ15, SZ24, SZ29 are removed due to having less than 10% ExNeu\n```{r}\nncells = apply(table(ACTIONet_summary$metadata$Labels, ACTIONet_summary$metadata$Individual), 2, as.numeric)\nrownames(ncells) = levels(ACTIONet_summary$metadata$Labels)\n\ncs = Matrix::colSums(ncells)\nncells.freq = 100*scale(ncells, center = F, scale = cs)\nEx.perc = (fast_column_sums(ncells.freq[grepl(\"^Ex\", rownames(ncells.freq)) & !grepl(\"^Ex-NRGN\", rownames(ncells.freq)), ]))\n\nmask = (Ex.perc >= 10) & (Ex.perc <= 80) \npb.sce.filtered = pb.sce[, mask]\n\n```\n\n\n\n\n# Performing cohort-specific DE\n```{r}\npb.sce.filtered$SampleQuality = scale(log1p(pb.sce.filtered$umis))\nform = ~ Phenotype + Batch + PMI + Gender + Age + Benzodiazepines + Anticonvulsants + AntipsychTyp + AntipsychAtyp + Antidepress + SampleQuality\n\nresDE = lapply( levels(pb.sce.filtered$Cohort), function(chrt){\n\n\tkeep.ids = colnames(pb.sce.filtered)[pb.sce.filtered$Cohort == chrt]\n\n\tpb.sce.filtered_sub = pb.sce.filtered[,keep.ids]\n sample.metadata = droplevels(data.frame(colData(pb.sce.filtered_sub)))\n\tdesign.mat <- model.matrix(form, data = sample.metadata)\n\tcolnames(design.mat)[1] = c(\"Intercept\")\n\n\tcontrast.mat <- makeContrasts(contrasts = \"PhenotypeSZ\", levels = design.mat)\n\n\tdf = pbDS(pb.sce.filtered_sub, method = \"limma-trend\", min_cells = 5, design = design.mat, contrast = contrast.mat, filter = \"both\")\n\t\n})\nnames(resDE) = levels(colData(pb.sce.filtered)$Cohort)\n\n```\n\n```{r}\nstoreDataset(resDE, name = \"Cohort_specific_DE_results\", dataset.path = dataset.path)\n\n```\n\n\n# Export unfiltered cohort-specific tables\n```{r}\nfor(ds in 1:length(resDE)) {\n print(names(resDE)[[ds]])\n \n Up.DFs = lapply(1:length(resDE[[ds]]$table$PhenotypeSZ), function(i) {\n res = resDE[[ds]]$table$PhenotypeSZ[[i]]\n res = res[res$logFC > 0, ]\n res = cbind(data.frame(Gene = rownames(res)), res)\n res = res[order(res$t, decreasing = T), ]\n return(res) \n })\n names(Up.DFs) = names(resDE[[ds]]$table$PhenotypeSZ)\n storeTable(Up.DFs, name = sprintf(\"DE_genes_up_%s_complete_set\", names(resDE)[[ds]]), tables.path = tables.path)\n\n Down.DFs = lapply(1:length(resDE[[ds]]$table$PhenotypeSZ), function(i) {\n res = resDE[[ds]]$table$PhenotypeSZ[[i]]\n res = res[res$logFC < 0, ]\n res = cbind(data.frame(Gene = rownames(res)), res)\n res = res[order(res$t, decreasing = F), ]\n })\n names(Down.DFs) = names(resDE[[ds]]$table$PhenotypeSZ)\n storeTable(Down.DFs, name = sprintf(\"DE_genes_down_%s_complete_set\", names(resDE)[[ds]]), tables.path = tables.path)\n}\n\n```\n\n\n\n\n\n\n# Compute Storey's pi1 per dataset\n```{r}\ntstat.overlap = sapply(common.celltypes, function(celltype) {\n df1 = resDE$McLean$table$PhenotypeSZ[[celltype]]\n df2 = resDE$MtSinai$table$PhenotypeSZ[[celltype]]\n common.genes = intersect(df1$gene, df2$gene)\n t1 = df1$t[match(common.genes, df1$gene)] \n t2 = df2$t[match(common.genes, df2$gene)] \n \n tt = cor.test(t1, t2)\n \n return(tt$statistic)\n})\ntstat.overlap[tstat.overlap < 0] = 0\nnames(tstat.overlap) = common.celltypes\n\nX = cbind(sapply(DE.new$Up.genes, length),sapply(DE.new$Down.genes, length))\nordered.celltypes = rownames(X)[order(apply(X, 1, sum), decreasing = T)]\n\nPurPal = colorRampPalette(RColorBrewer::brewer.pal(9, \"Purples\"))(200)\nht = Heatmap(as.matrix(tstat.overlap[ordered.celltypes]), col = PurPal, cluster_rows = F, cluster_columns = F, rect_gp = gpar(col = \"black\"), row_names_gp = gpar(col = colors[ordered.celltypes]), name = \"-log10(pval(correlation))\")\n\nstoreFigure(ht, name = \"Cohort_overlap\", extension = \"pdf\", figures.path = figures.path, width = 4)\n\n```\n\n\n# Plot Storey's Pi1 for each dataset\n```{r}\nlibrary(qvalue)\nMcLean.Pi1 = sapply(resDE$McLean$table$PhenotypeSZ, function(df) {\n pvals = df$p_val\n pi1 = 1 - qvalue(pvals)$pi0\n})\n\nMtSinai.Pi1 = sapply(resDE$MtSinai$table$PhenotypeSZ, function(df) {\n pvals = df$p_val\n pi1 = 1 - qvalue(pvals)$pi0\n})\ndf = data.frame(Celltype = union(names(resDE$MtSinai$table$PhenotypeSZ), names(resDE$McLean$table$PhenotypeSZ)))\nrownames(df) = df$Celltype\ndf$McLean = McLean.Pi1[df$Celltype]\ndf$MtSinai = 0\ndf[names(MtSinai.Pi1), \"MtSinai\"] = -MtSinai.Pi1\ndf = df[rev(ordered.celltypes), ]\ndf$Celltype = factor(df$Celltype, rev(ordered.celltypes))\ndf2 = reshape2::melt(df)\ncolnames(df2) = c(\"Celltype\", \"Dataset\", \"Pi1\")\n\ngg = ggplot(data = df2, aes(x = Celltype, y = Pi1, fill = Dataset)) + geom_bar(stat = \"identity\")+\n coord_flip()+ylab(\"Sorted Celltypes\")+\nlabs(y = \"Storey's Pi1\", x = \"Sorted Celltypes\")+\n theme_minimal()+\n guides(fill = FALSE)+ scale_fill_manual(values=c(\"#666666\", \"#cccccc\")) + theme(axis.text.y = element_text(face=\"bold\", color=colors[levels(df$Celltype)], size=12, angle=0), axis.text.x = element_text(face=\"bold\", color=\"black\", size=12, angle=0), axis.title = element_text(face=\"bold\", size=14, angle=0)) + ylim(c(-0.4, 0.4))\n\nstoreFigure(gg, name = \"Cohort_specific_Pi1\", extension = \"pdf\", figures.path = figures.path)\n\n\n```\n\n\n\n\n# Prefiltering individual DE results before combining them\nOnly keep genes that have 1) consistent direction of dysregulation across both datasets, and 2) at least 1 std away from zero on the logFC scale\n\n```{r}\ncommon.celltypes = intersect(names(resDE$McLean$table$PhenotypeSZ), names(resDE$MtSinai$table$PhenotypeSZ))\n\nfiltered.tables = lapply(common.celltypes, function(celltype) {\n tbl1 = resDE[[1]]$table$PhenotypeSZ[[celltype]]\n tbl2 = resDE[[2]]$table$PhenotypeSZ[[celltype]]\n \n genes = intersect(tbl1$gene[dev_threshold <= abs(tbl1$logFC/sd(tbl1$logFC))], tbl2$gene[dev_threshold <= abs(tbl2$logFC / sd(tbl2$logFC))])\n\n tbl1 = tbl1[match(genes, tbl1$gene), ]\n tbl2 = tbl2[match(genes, tbl2$gene), ]\n \n mask = sign(tbl1$logFC)*sign(tbl2$logFC) > 0\n tbl1 = tbl1[mask, ]\n tbl2 = tbl2[mask, ]\n \n tbls = list(McClean = tbl1, MtSinai = tbl2) \n tbls = lapply( tbls, function(tab){\n tab$se = tab$logFC / tab$t\n tab\n })\n \n return(tbls)\n})\nnames(filtered.tables) = common.celltypes\n\n```\n\n# Store filtered results\n```{r}\nstoreDataset(filtered.tables, \"Cohort_specific_DE_results_filtered\", dataset.path = dataset.path)\n\n```\n\n## Export as excel tables\n```{r}\nfor(ds in 1:length(filtered.tables[[1]])) {\n Up.DFs = lapply(1:length(filtered.tables), function(i) {\n res = filtered.tables[[i]][[ds]]\n res = res[res$logFC > 0, ]\n res = cbind(data.frame(Gene = rownames(res)), res)\n res = res[order(res$t, decreasing = T), ]\n })\n names(Up.DFs) = names(filtered.tables)\n storeTable(Up.DFs, name = sprintf(\"DE_genes_up_%s_filtered\", names(filtered.tables)[[ds]]), tables.path = tables.path)\n\n \n Down.DFs = lapply(1:length(filtered.tables), function(i) {\n res = filtered.tables[[i]][[ds]]\n res = res[res$logFC < 0, ]\n res = cbind(data.frame(Gene = rownames(res)), res)\n res = res[order(res$t, decreasing = F), ]\n })\n names(Down.DFs) = names(filtered.tables)\n storeTable(Down.DFs, name = sprintf(\"DE_genes_down_%s_filtered\", names(filtered.tables)[[ds]]), tables.path = tables.path)\n \n}\n\n```\n\n# Perform meta-analysis via Linear (Mixed-Effects) Models (RMA)\n```{r}\ncombined.analysis.tables = lapply(names(filtered.tables), function(celltype) {\n print(celltype)\n tbls = filtered.tables[[celltype]]\n \n gene.tbls = lapply(1:nrow(tbls[[1]]), function(i) {\n dfs = lapply(1:length(tbls), function(k) tbls[[k]][i, ])\n df = do.call(\"rbind\", dfs)\n })\n names(gene.tbls) = tbls[[1]]$gene\n \n combined.analysis.tbl = do.call(rbind, lapply(names(gene.tbls), function(gene){\n x = suppressWarnings(metafor::rma(yi=logFC, sei=se, data = gene.tbls[[gene]], method=\"FE\"))\n combined.tbl = data.frame( gene = gene, \n logFC = x$beta,\n se = x$se,\n tstat = x$zval,\n P.Value = x$pval)\n return(combined.tbl)\n }))\n rownames(combined.analysis.tbl) = names(gene.tbls)\n \n combined.analysis.tbl = combined.analysis.tbl[order(combined.analysis.tbl$P.Value), ]\n \n return(combined.analysis.tbl)\n})\nnames(combined.analysis.tables) = names(filtered.tables)\n\nDF = do.call(rbind, combined.analysis.tables)\nDF$adj.P.Val = p.adjust(DF$P.Value, \"fdr\")\nff = factor(unlist(lapply(names(combined.analysis.tables), function(celltype) rep(celltype, nrow(combined.analysis.tables[[celltype]])))), names(filtered.tables))\ncombined.analysis.tables = split(DF, ff)\n\n```\n\n# Export meta-analysis results\n```{r}\nstoreDataset(combined.analysis.tables, \"meta_analysis_results\", dataset.path = dataset.path)\n\n\n```\n\n\n\n# Export final tables\n```{r}\n Up.DFs = lapply(1:length(combined.analysis.tables), function(i) {\n res = combined.analysis.tables[[i]]\n res = res[(res$logFC > logFC_threshold) & (res$P.Value <= pval_threshold), ]\n res = res[order(res$t, decreasing = T), ]\n res$isSig = res$adj.P.Val <= pval_threshold\n \n })\n names(Up.DFs) = names(combined.analysis.tables)\n storeTable(Up.DFs, name = \"DE_genes_up_combined\", tables.path = tables.path)\n\n \n Down.DFs = lapply(1:length(combined.analysis.tables), function(i) {\n res = combined.analysis.tables[[i]]\n res = res[(res$logFC < -logFC_threshold) & (res$P.Value <= pval_threshold), ]\n res = res[order(res$t, decreasing = F), ]\n res$isSig = res$adj.P.Val <= pval_threshold\n \n })\n names(Down.DFs) = names(combined.analysis.tables)\n \n storeTable(Down.DFs, name = \"DE_genes_down_combined\", tables.path = tables.path)\n \n```\n\n\n# Summarize and simplify DE results\n```{r}\nDE.sc = matrix(0, nrow(pb.sce), length(combined.analysis.tables))\ntstats = matrix(0, nrow(pb.sce), length(combined.analysis.tables))\nlogFC = matrix(0, nrow(pb.sce), length(combined.analysis.tables))\nlogPvals = matrix(0, nrow(pb.sce), length(combined.analysis.tables))\nrownames(DE.sc) = rownames(tstats) = rownames(logFC) = rownames(logPvals) = rownames(pb.sce)\ncolnames(DE.sc) = colnames(tstats) = colnames(logFC) = colnames(logPvals) = names(combined.analysis.tables)\n\nlimma_trend_mean.scores = matrix(0, nrow(pb.sce), length(combined.analysis.tables))\nUp.genes = vector(\"list\", length(combined.analysis.tables))\nDown.genes = vector(\"list\", length(combined.analysis.tables))\nrownames(limma_trend_mean.scores) = rownames(pb.sce)\nnames(Up.genes) = names(Down.genes) = colnames(limma_trend_mean.scores) = names(combined.analysis.tables)\nfor(i in 1:length(combined.analysis.tables)) {\n\tprint(i)\n\t\n\ttbl = combined.analysis.tables[[i]]\n\n\ttstats[tbl$gene, names(combined.analysis.tables)[[i]]] = tbl$tstat\n\tlogFC[tbl$gene, names(combined.analysis.tables)[[i]]] = tbl$logFC\n\tlogPvals[tbl$gene, names(combined.analysis.tables)[[i]]] = -log10(tbl$adj.P.Val)\n\t\n\tx = tbl$tstat\n\tx[abs(tbl$logFC) < logFC_threshold] = 0\n\tDE.sc[tbl$gene, names(combined.analysis.tables)[[i]]] = x\n\t\n}\nlimma_trend_mean.scores[is.na(limma_trend_mean.scores)] = 0\n\n\nUp.genes = lapply(combined.analysis.tables, function(combined.analysis.tbl) {\n combined.analysis.tbl$gene[(combined.analysis.tbl$logFC > logFC_threshold) & (combined.analysis.tbl$adj.P.Val < pval_threshold)]\n})\nDown.genes = lapply(combined.analysis.tables, function(combined.analysis.tbl) {\n combined.analysis.tbl$gene[(combined.analysis.tbl$logFC < -logFC_threshold) & (combined.analysis.tbl$adj.P.Val < pval_threshold)]\n})\n\nDE.new = list(DE.sc = DE.sc, tstats = tstats, logFC = logFC, logPvals = logPvals, Up.genes = Up.genes, Down.genes = Down.genes)\n\n\n```\n# Store final results\n```{r}\nstoreDataset(DE.new, \"DE_genes_pseudobulk\", dataset.path = dataset.path)\n\n```\n\n\n\n\n\n" }, { "alpha_fraction": 0.6647570133209229, "alphanum_fraction": 0.6892600655555725, "avg_line_length": 36.24164581298828, "blob_id": "04fae66117dddd96b5952f47421043805e50f5cf", "content_id": "1b0b133f6ea76a710556c5f5f05c5a8a9a89d0ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 14488, "license_type": "no_license", "max_line_length": 691, "num_lines": 389, "path": "/old/run_ACTIONet_per_dataset.Rmd", "repo_name": "shmohammadi86/snSZ_backup", "src_encoding": "UTF-8", "text": "---\ntitle: \"Compute ACTIONet per dataset\"\noutput: html_notebook\n---\n\n# Setup\n```{r include=FALSE}\n\nrequire(ACTIONet)\nrequire(stringr)\nrequire(ComplexHeatmap)\n\n\ndataset.path = \"~/results/datasets/\"\nresults.path = \"~/results\"\nfigures.folder = \"~/results/figures\"\n\n\n```\n\n# Read ACTIONet and convert to an SCE object\n```{r}\nace = readr::read_rds(\"~/results/ACTIONet_reunified.rds\")\nsce = as(ace, \"SingleCellExperiment\")\n\nACTIONet_summary = readr::read_rds(file.path(dataset.path, \"ACTIONet_summary.rds\"))\n\nACTIONet_summary.filtered = readr::read_rds(file.path(dataset.path, \"ACTIONet_summary_filtered_individuals.rds\"))\n\npb.logcounts = readr::read_rds(file.path(dataset.path, \"PB_mean_logcounts_final.RDS\"))\n\ncolor.df = readRDS(file.path(dataset.path, \"celltype_colors.rds\"))\n\n```\n\n```{r}\nnrow(ACTIONet_summary$metadata)\nnrow(ACTIONet_summary.filtered$metadata)\n\n\nlength(table(ACTIONet_summary$metadata$Individual))\nlength(table(ACTIONet_summary.filtered$metadata$Individual))\n\n\nidx = match(ACTIONet_summary.filtered$metadata$Id, ACTIONet_summary$metadata$Id)\nfilter.idx = setdiff(1:ncol(ace), idx)\n\nace.filtered = ace[, idx]\n\n\nace.McLean = ace.filtered[, ace.filtered$dataset == \"DS1\"]\nace.MtSinai = ace.filtered[, ace.filtered$dataset == \"DS2\"]\n\n\n# ncol(ace)\n# \n# \n# length(table(ACTIONet_summary$metadata$Individual))\n# \n# length(table(ACTIONet_summary$metadata$Individual))\n\n```\n\n```{r}\nace.McLean = run.ACTIONet(ace.McLean, k_max = 40, thread_no = 42)\nace.MtSinai = run.ACTIONet(ace.MtSinai, k_max = 40, thread_no = 42)\n\nreadr::write_rds(ace.filtered, \"~/results/ACTIONet_filtered_final.rds\")\nreadr::write_rds(ace.McLean, \"~/results/ACTIONet_McLean_final.rds\")\nreadr::write_rds(ace.MtSinai, \"~/results/ACTIONet_MtSinai_final.rds\")\n\n\n```\n```{r}\nspecs = list(Combined = ace.filtered$unified_feature_specificity, McLean = ace.McLean$unified_feature_specificity, MtSinai = ace.MtSinai$unified_feature_specificity)\n\nreadr::write_rds(specs, \"~/archetypes_gene_specs_individual_ACTIONets.rds\")\n\n\ncolors = color.df$color\nnames(colors) = color.df$celltype\n# plot.ACTIONet(ace.McLean, ace.McLean$Labels.final, palette = colors)\n\n```\n```{r}\narch.annot.McLean = annotate.archetypes.using.labels(ace.McLean, ace.McLean$Celltype)\narch.annot.MtSinai = annotate.archetypes.using.labels(ace.MtSinai, ace.MtSinai$Celltype)\narch.annot.Combined = annotate.archetypes.using.labels(ace.filtered, ace.filtered$Celltype)\n\n# kk1 = match(arch.annot.Combined$Label, color.df$old.celltype)\n# kk2 = match(arch.annot.McLean$Label, color.df$old.celltype)\n# kk3 = match(arch.annot.MtSinai$Label, color.df$old.celltype)\n\n\n```\n\n\n```{r}\nrequire(seriation)\nCC1 = cor(specs$Combined, specs$McLean)\nCC2 = cor(specs$Combined, specs$MtSinai)\nrownames(CC1) = rownames(CC2) = paste(\"A\", 1:nrow(CC1), \"-\", color.df$celltype[kk1], sep = \"\")\ncolnames(CC1) = paste(\"A\", 1:ncol(CC1), \"-\", color.df$celltype[kk2], sep = \"\")\ncolnames(CC2) = paste(\"A\", 1:ncol(CC2), \"-\", color.df$celltype[kk3], sep = \"\")\n\nM1 = as(MWM_hungarian(1+t(CC1)), \"dgTMatrix\")\nM2 = as(MWM_hungarian(1+t(CC2)), \"dgTMatrix\")\n\njj1 = M1@i+1\njj2 = M2@i+1\n\nRdBu.pal = circlize::colorRamp2(seq(-0.75, 0.75, length.out = 7), rev(pals::brewer.rdbu(7)))\n\ncolors = color.df$color\nnames(colors) = color.df$celltype\ncc = colors[color.df$celltype[kk1]]\ncc1 = colors[color.df$celltype[kk2]]\ncc2 = colors[color.df$celltype[kk3]]\n\n# perm = get_order(seriate(as.dist(1-((cor(t(CC1)) + cor(t(CC2)))/2)), \"OLO\"))\nperm = c(setdiff(order(kk1), c(7, 11, 17, 29)), c(7, 17, 11, 29))\nX1 = CC1[perm, jj1[perm]]\nX2 = CC2[perm, jj2[perm]]\npdf(\"~/results/figures/archetype_mapping.pdf\", width = 14, height = 8)\nHeatmap(X1, cluster_columns = F, cluster_rows = F, row_title = \"Combined\", column_title = \"McLean\", rect_gp = gpar(col = \"black\"), name = \"Correlation\", row_names_side = \"left\", col = RdBu.pal, row_names_gp = gpar(col = cc[perm]), column_names_gp = gpar(col = cc1[jj1[perm]])) + Heatmap(X2, cluster_columns = F, cluster_rows = F, row_title = \"Combined\", column_title = \"MtSinai\", rect_gp = gpar(col = \"black\"), name = \"Correlation\", row_names_side = \"left\", col = RdBu.pal, column_names_gp = gpar(col = cc2[jj2[perm]]))\ndev.off()\n\n\n\n\n\n\n```\n\n```{r}\nspec.full.McLean = compute_archetype_feature_specificity(logcounts(ace.McLean), as.matrix(t(colMaps(ace.McLean)$H_stacked)))\nspec.full.MtSinai = compute_archetype_feature_specificity(logcounts(ace.MtSinai), as.matrix(t(colMaps(ace.MtSinai)$H_stacked)))\n\nace.filtered$Celltype = color.df$celltype[match(ace.filtered$Labels.final, color.df$old.celltype)]\nace.McLean$Celltype = color.df$celltype[match(ace.McLean$Labels.final, color.df$old.celltype)]\nace.MtSinai$Celltype = color.df$celltype[match(ace.MtSinai$Labels.final, color.df$old.celltype)]\n\narch.annot.McLean.full = annotate.archetypes.using.labels(ace.McLean, ace.McLean$Celltype, archetype.slot = \"H_stacked\")\n# arch.annot.Combined.full = annotate.archetypes.using.labels(ace.filtered, ace.filtered$Celltype, archetype.slot = \"H_stacked\")\narch.annot.MtSinai.full = annotate.archetypes.using.labels(ace.MtSinai, ace.MtSinai$Celltype, archetype.slot = \"H_stacked\")\n\n\n\n\n\n```\n\n```{r}\nrequire(seriation)\nCC1 = cor(specs$Combined, spec.full.McLean$upper_significance)\nCC2 = cor(specs$Combined, spec.full.MtSinai$upper_significance)\nrownames(CC1) = rownames(CC2) = paste(\"A\", 1:nrow(CC1), \"-\", color.df$celltype[kk1], sep = \"\")\ncolnames(CC1) = paste(\"A\", 1:ncol(CC1), \"-\", arch.annot.McLean.full$Label, sep = \"\")\ncolnames(CC2) = paste(\"A\", 1:ncol(CC2), \"-\", arch.annot.MtSinai.full$Label, sep = \"\")\n\nM1 = as(MWM_hungarian(1+t(CC1)), \"dgTMatrix\")\nM2 = as(MWM_hungarian(1+t(CC2)), \"dgTMatrix\")\n\njj1 = M1@i+1\njj2 = M2@i+1\n\nRdBu.pal = circlize::colorRamp2(seq(-0.75, 0.75, length.out = 7), rev(pals::brewer.rdbu(7)))\n\ncolors = color.df$color\nnames(colors) = color.df$celltype\ncc = colors[color.df$celltype[kk1]]\ncc1 = colors[arch.annot.McLean.full$Label]\ncc2 = colors[arch.annot.MtSinai.full$Label]\n\n# perm = get_order(seriate(as.dist(1-((cor(t(CC1)) + cor(t(CC2)))/2)), \"OLO\"))\nperm = c(setdiff(order(kk1), c(7, 11, 17, 29)), c(7, 17, 11, 29))\nX1 = CC1[perm, jj1[perm]]\nX2 = CC2[perm, jj2[perm]]\npdf(\"~/results/figures/archetype_mapping_full.pdf\", width = 14, height = 8)\nHeatmap(X1, cluster_columns = F, cluster_rows = F, row_title = \"Combined\", column_title = \"McLean\", rect_gp = gpar(col = \"black\"), name = \"Correlation\", row_names_side = \"left\", col = RdBu.pal, row_names_gp = gpar(col = cc[perm]), column_names_gp = gpar(col = cc1[jj1[perm]])) + Heatmap(X2, cluster_columns = F, cluster_rows = F, row_title = \"Combined\", column_title = \"MtSinai\", rect_gp = gpar(col = \"black\"), name = \"Correlation\", row_names_side = \"left\", col = RdBu.pal, column_names_gp = gpar(col = cc2[jj2[perm]]))\ndev.off()\n\n\n```\n\n```{r}\n\n\n\nunified_archetypes = list(Combined = list(archetype_footprint = ace.filtered$archetype_footprint, unified_feature_specificity = ace.filtered$unified_feature_specificity, annotations = arch.annot.Combined$Enrichment, labels = arch.annot.Combined$Label), McLean = list(archetype_footprint = ace.McLean$archetype_footprint, unified_feature_specificity = ace.McLean$unified_feature_specificity, annotations = arch.annot.McLean$Enrichment, labels = arch.annot.McLean$Label), MtSinai = list(archetype_footprint = ace.MtSinai$archetype_footprint, unified_feature_specificity = ace.MtSinai$unified_feature_specificity, annotations = arch.annot.MtSinai$Enrichment, labels = arch.annot.MtSinai$Label))\n\nreadr::write_rds(unified_archetypes, \"~/results/unified_archetypes_plus_individual_ACTIONets.rds\")\n\n\n\nfull_archetypes = list(McLean = list(H_stacked = colMaps(ace.McLean)$H_stacked, profile = spec.full.McLean$archetypes, specificity = spec.full.McLean$upper_significance, annotations = arch.annot.McLean.full$Enrichment, labels = arch.annot.McLean.full$Label), MtSinai = list(H_stacked = colMaps(ace.MtSinai)$H_stacked, profile = spec.full.MtSinai$archetypes, specificity = spec.full.MtSinai$upper_significance, annotations = arch.annot.MtSinai.full$Enrichment, labels = arch.annot.MtSinai.full$Label))\n\nreadr::write_rds(full_archetypes, \"~/results/Full_archetypes_individual_ACTIONets.rds\")\n\n\n\n\n```\n\n```{r}\nDE.new = readRDS(\"~/results/datasets/DE_genes_pseudobulk.rds\")\n\nUp.genes = DE.new$Up.genes\nDown.genes = DE.new$Down.genes\nDE.scores = sign(DE.new$logFC) * (DE.new$logPvals) # tstats\nDE.scores.sig = DE.scores\nDE.scores.sig[(abs(DE.new$logFC) < 0.1) | (DE.new$logPvals < -log10(0.05))] = 0\n\n```\n\n\n```{r}\nMcLean.enrichment = assess.geneset.enrichment.from.scores(scores = ace.McLean$unified_feature_specificity, DE.new$Down.genes)\nX1 = McLean.enrichment$logPvals\ncolnames(X1) = colnames(CC1)\n\nMcLean.enrichment = assess.geneset.enrichment.from.scores(scores = ace.MtSinai$unified_feature_specificity, DE.new$Down.genes)\nX2 = McLean.enrichment$logPvals\ncolnames(X2) = colnames(CC2)\n\n\npdf(\"~/results/figures/individual_archetypes_vs_DE_genes.pdf\", width = 14, height = 6)\nHeatmap(X1, show_column_dend = F, show_row_dend = F, cluster_rows = F, row_names_side = \"left\", row_names_gp = gpar(col = colors), rect_gp = gpar(col = \"black\"), name = \"Enrichment\") + Heatmap(X2, show_column_dend = F, show_row_dend = F, cluster_rows = F, row_names_side = \"left\", row_names_gp = gpar(col = colors), rect_gp = gpar(col = \"black\"), name = \"Enrichment\") \ndev.off()\n\n\n\n\n```\n\n\n```{r}\n\nDE = c(DE.new$Up.genes, DE.new$Down.genes)\nnames(DE) = c(paste(\"Up\", names(DE.new$Up.genes), sep = \"_\"), paste(\"Down\", names(DE.new$Down.genes), sep = \"_\"))\n\n\n\nset.seed(0)\nSZTR.McLean = ace.McLean$unified_feature_specificity[, 18]\nDE.enrich.McLean = fgsea::fgsea(DE, SZTR.McLean)\nsaveRDS(DE.enrich.McLean, \"~/results/datasets/McLean_SZTR_vs_DE.rds\")\n\n\nSZTR.MtSinai = ace.McLean$unified_feature_specificity[, 30]\nDE.enrich.MtSinai = fgsea::fgsea(DE, SZTR.MtSinai)\nsaveRDS(DE.enrich.MtSinai, \"~/results/datasets/MtSinai_SZTR_vs_DE.rds\")\n\n\n# data: log1p(SZTR.McLean) and log1p(SZTR.MtSinai)\n# t = 42.507, df = 17656, p-value < 2.2e-16\n# alternative hypothesis: true correlation is not equal to 0\n# 95 percent confidence interval:\n# 0.2912497 0.3180110\n# sample estimates:\n# cor \n# 0.3046904 \n# stats$p.value == 0\nstats = cor.test(log1p(SZTR.McLean), log1p(SZTR.MtSinai))\n\n\n\n```\n\n\n```{r}\nCommon.genes = lapply(1:nrow(DE.enrich.McLean), function(i) {\n sort(unique(intersect(DE.enrich.McLean$leadingEdge[[i]], DE.enrich.MtSinai$leadingEdge[[i]])))\n})\n\nnames(Common.genes) = DE.enrich.McLean$pathway\n\nreadr::write_rds(Common.genes, \"~/results/SZTR_common_genes_across_datasets.rds\")\n\n\n\n\n```\n\n\n```{r}\nx1 = annotate.archetypes.using.labels(ace.McLean, ace.McLean$Phenotype)\nx2 = annotate.archetypes.using.labels(ace.MtSinai, ace.MtSinai$Phenotype)\n\n# Heatmap(x1$Enrichment)\n# Heatmap(x2$Enrichment)\n\n```\n```{r}\n# order(SZTR.McLean, decreasing = T)[1:20], order(SZTR.McLean, decreasing = T)[1:20]\n\nintersect(names(sort(SZTR.McLean, decreasing = T)[1:20]), names(sort(SZTR.MtSinai, decreasing = T)[1:20]))\n\n\n# Z = scale(cbind(SZTR.McLean, SZTR.MtSinai))\n\n```\n\n\n\n```{r}\nxx = scale(sapply(split(ace.McLean$archetype_footprint[, 18], droplevels(ace.McLean$Individual)), mean))\nii = match(rownames(xx), pb.logcounts$Internal_ID)\ndf1 = data.frame(TPS = pb.logcounts$TPS[ii], SZTR = xx, Phenotype = pb.logcounts$Phenotype[ii])\ncor(df1$TPS, df1$SZTR) # -0.7134271\ncor.test(df1$TPS, df1$SZTR) # t = -6.9052, df = 46, p-value = 1.264e-08\n\n\nrequire(ggpubr)\ngg = ggscatter(df1, x = \"TPS\", y = \"SZTR\", \n color = \"Phenotype\",\n palette = c(\"CON\" = \"lightgray\", \"SZ\" = \"red\"),\n add = \"reg.line\", # Add regression line\n conf.int = TRUE, # Add confidence interval\n add.params = list(color = \"blue\",\n fill = \"lightgray\")\n ) + geom_vline(xintercept = -1, linetype = \"dashed\", color=\"gray\") + geom_vline(xintercept = 1, linetype = \"dashed\", color=\"gray\")+\n stat_cor(method = \"pearson\")# +xlim(c(-2, 2)) + ylim(c(-2, 2))\n\npdf(\"~/results/figures/McLean_SZTR_vs_TPS_scatter.pdf\")\nplot(gg)\ndev.off()\n\n\n\n\nxx2 = scale(sapply(split(ace.MtSinai$archetype_footprint[, 30], droplevels(ace.MtSinai$Individual)), mean))\nii2 = match(rownames(xx2), pb.logcounts$Internal_ID)\n\ndf2 = data.frame(TPS = pb.logcounts$TPS[ii2], SZTR = xx2, Phenotype = pb.logcounts$Phenotype[ii2])\ncor(df2$TPS, df2$SZTR) # -0.7134271\ncor.test(df2$TPS, df2$SZTR) # t = -6.9052, df = 46, p-value = 1.264e-08\n\n\nrequire(ggpubr)\ngg = ggscatter(df2, x = \"TPS\", y = \"SZTR\", \n color = \"Phenotype\",\n palette = c(\"CON\" = \"lightgray\", \"SZ\" = \"red\"),\n add = \"reg.line\", # Add regression line\n conf.int = TRUE, # Add confidence interval\n add.params = list(color = \"blue\",\n fill = \"lightgray\")\n ) + geom_vline(xintercept = -1, linetype = \"dashed\", color=\"gray\") + geom_vline(xintercept = 1, linetype = \"dashed\", color=\"gray\")+\n stat_cor(method = \"pearson\")# +xlim(c(-2, 2)) + ylim(c(-2, 2))\n\npdf(\"~/results/figures/MtSinai_SZTR_vs_TPS_scatter.pdf\")\nplot(gg)\ndev.off()\n\n\n```\n\n\n\n```{r}\nx = readr::read_rds(\"~/results/datasets/SZTR_vs_DE_shared_genes_gProfiler_filtered.rds\")\n\n```\n\n\n```{r}\n\ngs = list(shared = shared.genes)\n\nset.seed(0)\nshared.enrich.DS1 = fgsea::fgsea(gs, SZTR.McLean) # 0.001113701, 133 genes\nshared.enrich.DS2 = fgsea::fgsea(gs, SZTR.MtSinai) # 5.173198e-09, 117 genes\n\nSZTR.genes = list(Joint = shared.genes, McLean = shared.enrich.DS1$leadingEdge[[1]], MtSinai = shared.enrich.DS2$leadingEdge[[1]])\n\n\ndf = data.frame(genes = SZTR.genes$Joint, McLean = SZTR.genes$Joint %in% SZTR.genes$McLean, MtSinai = SZTR.genes$Joint %in% SZTR.genes$MtSinai)\ndf$Both = df$McLean & df$MtSinai\nwrite.table(df, file.path(tables.path, \"Shared_SZTR_genes_vs_individual_ds.tsv\"), sep = \"\\t\", row.names = F, col.names = T, quote = F)\n\n\n\n\ngg = list(Joint = setdiff(SZTR.genes$Joint, union(SZTR.genes$McLean, SZTR.genes$MtSinai)), McLean = setdiff(SZTR.genes$McLean, union(SZTR.genes$MtSinai, SZTR.genes$Joint)), MtSinai = setdiff(SZTR.genes$MtSinai, union(SZTR.genes$McLean, SZTR.genes$Joint)), \"Joint&McLean\" = setdiff(union(SZTR.genes$Joint, SZTR.genes$McLean), SZTR.genes$MtSinai), \"Joint&MtSinai\" = setdiff(union(SZTR.genes$Joint, SZTR.genes$MtSinai), SZTR.genes$McLean), \"McLean&MtSinai\" = setdiff(union(SZTR.genes$MtSinai, SZTR.genes$McLean), SZTR.genes$Joint), \"Joint&McLean&MtSinai\" = intersect(SZTR.genes$Joint, intersect(SZTR.genes$McLean, SZTR.genes$MtSinai)))\n\n\n\n\n```\n\n" } ]
36
anbergem/rema-parser
https://github.com/anbergem/rema-parser
01bc8522396bf8a9822f5241a5989598c35da3c6
ab4887c37c7811f26677ea8965d5a5b1a4d5ec59
1016062a125eba3a35ca1669ba25e925c2453287
refs/heads/master
2023-04-12T11:12:56.853070
2021-04-26T18:37:45
2021-04-26T18:37:58
361,851,811
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7593516111373901, "alphanum_fraction": 0.7668328881263733, "avg_line_length": 49, "blob_id": "d4108df0dbb45cee19c4ec5091b5a8ee975669b9", "content_id": "53627f71cb635284669215cc1d4b5ed1f5e19993", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 806, "license_type": "no_license", "max_line_length": 164, "num_lines": 16, "path": "/README.md", "repo_name": "anbergem/rema-parser", "src_encoding": "UTF-8", "text": "# rema-parser\n\nThe norwegian grocery store Rema 1000 offers to export a detailed transaction history to a JSON file. This is done through their app \"Æ\", through `Profile` - \n`Vilkår og samtykke` - `Se dine data` - `Få tilsendt data i maskinlesbart format`. The file acts as input to the script\n\nThe simple script organises the transaction by week, month and year, and plots the top n (default 20) products for the each month and year. The detailed transaction\nhistory is only available if your payment information is confirmed in their app, \"Æ\". It becomes available for purchases made subsequent to confirming the payment \ninformation.\n\n# Installation\nInstall [poetry](https://python-poetry.org) then run \n\n```bash\npoetry install\npoetry run python main.py <filename> [--n <plot top n products>]\n```\n\n\n" }, { "alpha_fraction": 0.63825523853302, "alphanum_fraction": 0.6502774357795715, "avg_line_length": 36.94736862182617, "blob_id": "0d42e523c32474d618bd1da0025e8802ab51dded", "content_id": "3cb706743be5439a223d22736c7a4a3233aeaf13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6489, "license_type": "no_license", "max_line_length": 117, "num_lines": 171, "path": "/main.py", "repo_name": "anbergem/rema-parser", "src_encoding": "UTF-8", "text": "import dataclasses\nimport datetime\nimport json\nfrom collections import defaultdict\nfrom types import SimpleNamespace\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom dateutil import relativedelta\n\n\ndef difference_in_months(from_date: datetime.datetime, to_date: datetime.datetime):\n if from_date > to_date:\n from_date, to_date = to_date, from_date\n if from_date.year == to_date.year:\n return to_date.month - from_date.month\n\n # If there are any full years between, add 12 months for each year\n result = (to_date.year - from_date.year - 1) * 12\n # Add months for first year\n result += 12 - from_date.month\n # Add months for last year\n result += to_date.month\n\n return result\n\n\ndef group_transactions(transactions):\n first_date = datetime.datetime.fromtimestamp(transactions[0].PurchaseDate // 1000)\n last_date = datetime.datetime.fromtimestamp(transactions[-1].PurchaseDate // 1000)\n\n first_week_start = first_date - datetime.timedelta(days=first_date.weekday())\n last_week_start = last_date - datetime.timedelta(days=last_date.weekday())\n\n first_month_start = first_date - datetime.timedelta(days=first_date.day - 1)\n\n first_year_start = first_date.replace(month=1, day=1, hour=0, minute=0, second=0)\n\n num_weeks = (last_week_start - first_week_start).days // 7 + 1\n num_months = difference_in_months(first_date, last_date) + 1\n num_years = last_date.year - first_date.year + 1\n\n weekly_dates = np.array(\n [(first_week_start + datetime.timedelta(weeks=i)).replace(hour=0, minute=0, second=0) for i in\n range(num_weeks)],\n dtype=datetime.datetime)\n monthly_dates = np.array(\n [(first_month_start + relativedelta.relativedelta(months=i)).replace(hour=0, minute=0, second=0) for i in\n range(num_months)],\n dtype=datetime.datetime)\n yearly_dates = np.array([first_year_start + relativedelta.relativedelta(years=i) for i in range(num_years)],\n dtype=datetime.datetime)\n\n weeks = defaultdict(list)\n months = defaultdict(list)\n years = defaultdict(list)\n\n for transaction in transactions:\n date = datetime.datetime.fromtimestamp(transaction.PurchaseDate // 1000)\n week_index = ((date - datetime.timedelta(days=date.weekday())) - first_week_start).days // 7\n\n month_index = difference_in_months(first_date, date)\n\n year_index = date.year - first_year_start.year\n\n weeks[weekly_dates[week_index]] += [transaction]\n months[monthly_dates[month_index]] += [transaction]\n years[yearly_dates[year_index]] += [transaction]\n\n return weeks, months, years\n\n\ndef plot(weekly_dates, weekly_amounts, monthly_dates, monthly_amounts):\n fig, ax = plt.subplots(2, 1)\n ax[0].step(weekly_dates, weekly_amounts, \".-\", where=\"post\")\n ax[0].set_title(\"Per week\")\n ax[1].step(monthly_dates, monthly_amounts, \".-\", where=\"post\")\n ax[1].set_title(\"Per month\")\n fig.suptitle(\"Spendings at Rema 1000 - from Æ\")\n plt.grid(True)\n plt.show()\n\n\[email protected](eq=True, frozen=True)\nclass Product:\n code: int\n text: str = dataclasses.field(compare=False)\n description: str = dataclasses.field(compare=False)\n group_code: int = dataclasses.field(compare=False)\n group_description: str = dataclasses.field(compare=False)\n volume: float = dataclasses.field(compare=False)\n amount: float = dataclasses.field(compare=False)\n\n @staticmethod\n def from_receipt(receipt):\n return Product(receipt.ProductCode if receipt.ProductCode is not None else 0,\n receipt.Prodtxt1 if receipt.Prodtxt1 is not None else \"Unknown\",\n receipt.ProductDescription if receipt.ProductDescription is not None else \"Unknown\",\n receipt.ProductGroupCode if receipt.ProductGroupCode is not None else \"Unknown\",\n receipt.ProductGroupDescription if receipt.ProductGroupDescription is not None else \"Unknown\",\n receipt.Volume,\n receipt.Amount)\n\n\ndef process_receipts(transactions):\n items = defaultdict(lambda: {'count': 0, 'total': 0})\n for transaction in transactions:\n for receipt in transaction.Receipt:\n product = Product.from_receipt(receipt)\n items[product]['total'] += receipt.Amount\n items[product]['count'] += 1\n return items\n\n\ndef plot_top_n_products(title, products, n):\n if (len(products) < 2):\n print(f\"{title} has unknown products worth kr {[v for v in products.values()][0]['total']:.2f} ,-\")\n return\n keys = []\n values = []\n total = sum(map(lambda x: x['total'], (v for v in products.values())))\n unknown = 0\n for key, value in sorted(products.items(), key=lambda x: x[1]['total'], reverse=True):\n if key.code != 0:\n keys.append(key)\n values.append(value)\n else:\n unknown = value['total']\n\n _slice = slice(0, n, None)\n fig, ax = plt.subplots(1, 1)\n fig.suptitle(f\"{title} - kr {total:.2f},-\")\n if unknown > 0:\n ax.set_title(f\"Ukjent: kr {unknown:.2f},-\")\n bottom = list(map(lambda x: x.text, keys[_slice]))\n width = list(map(lambda x: x['total'], values[_slice]))\n ax.barh(bottom, width, color='lightblue')\n plt.subplots_adjust(left=0.4)\n for i, (k, v) in enumerate(zip(keys[_slice], values[_slice])):\n ax.text(2, i, f\"{k.amount:<7.2f} * {v['count']:>2.0f} = {v['total']:.2f}\", va='center', color='black',\n alpha=0.7)\n\n\ndef plot_top_n_periodically(title_generator, periods, n):\n for period, transactions in periods.items():\n products = process_receipts(transactions)\n plot_top_n_products(title_generator(period), products, n)\n\n\ndef main(filename, n):\n with open(filename) as json_file:\n # Parse JSON into an object with attributes corresponding to dict keys.\n x = json.load(json_file, object_hook=lambda d: SimpleNamespace(**d))\n\n weeks, months, years = group_transactions(x.TransactionsInfo.Transactions)\n\n plot_top_n_periodically(lambda x: x.strftime(\"%B %Y\"), months, n)\n plot_top_n_periodically(lambda x: x.strftime(\"%Y\"), years, n)\n\n plt.show()\n\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"filename\", type=str)\n parser.add_argument(\"--n\", type=int, default=20)\n\n args = parser.parse_args()\n\n main(args.filename, args.n)" } ]
2
alexknight/pyfire
https://github.com/alexknight/pyfire
b4421166458c7f321c9cd40a2d479da63804956c
8fc4bbc83452ddd8812238c73565dd1cf2e161f6
a25814b7bb8717cf6870722989d5f10b31fb1462
refs/heads/master
2016-09-08T02:32:52.170494
2015-04-10T13:24:49
2015-04-10T13:24:49
33,672,884
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7281553149223328, "alphanum_fraction": 0.7281553149223328, "avg_line_length": 33.5, "blob_id": "d3ae1fd19c2d696c9cb207efe282db53d833c05c", "content_id": "abe01827462aef2692a365530e01b6030e30371b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 374, "license_type": "no_license", "max_line_length": 89, "num_lines": 6, "path": "/pyfire/templates/about.html", "repo_name": "alexknight/pyfire", "src_encoding": "UTF-8", "text": "{% extends 'base.html' %}\n{% block content %}\n<p>关于本人:本人Alex,求一份深圳地区python测试开发的岗位.</p><br />\n<p>开设此网目的:Python工程师在国内远不算如火如荼,关于资料,培训,以及招聘信息怎么也不能算多,这个站点的初衷是为了让更多的人更好的学习python.</p><br />\n\n{% endblock content %}" }, { "alpha_fraction": 0.746391773223877, "alphanum_fraction": 0.7587628960609436, "avg_line_length": 36.30769348144531, "blob_id": "8d24eb6c93569be0f3d15557ab88c08134f494c6", "content_id": "1a3de4ea2c962dced99f2daf160d82b858b37807", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 485, "license_type": "no_license", "max_line_length": 89, "num_lines": 13, "path": "/pyfire/views.py", "repo_name": "alexknight/pyfire", "src_encoding": "UTF-8", "text": "from django.shortcuts import render_to_response,get_object_or_404\nfrom .models import article\n# Create your views here.\ndef subject(request):\n\tarticles=article.objects.filter(published_data__isnull=False).order_by('published_data')\n\treturn render_to_response('subject.html',{'articles':articles})\n\ndef detail(request,pk):\n\tpost = get_object_or_404(article, pk=pk)\n\treturn render_to_response('detail.html',{'post':post})\n\ndef about(request):\n\treturn render_to_response('about.html',{})\n" }, { "alpha_fraction": 0.6136363744735718, "alphanum_fraction": 0.6227272748947144, "avg_line_length": 23.55555534362793, "blob_id": "50e27cb825702b9d30d7b86e67fe063163298dc3", "content_id": "33b50d159a80cc433190b096b206fc851daca8ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 220, "license_type": "no_license", "max_line_length": 51, "num_lines": 9, "path": "/pyfire/urls.py", "repo_name": "alexknight/pyfire", "src_encoding": "UTF-8", "text": "from django.conf.urls import patterns, include, url\nfrom . import views\n\nurlpatterns = patterns('',\n url(r'^$', views.subject),\n url(r'^detail/(?P<pk>[0-9]+)/$', views.detail),\n url(r'^about/$', views.about),\n\n)" }, { "alpha_fraction": 0.45614033937454224, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 13.25, "blob_id": "154081e0536f7acb839ac380cf79155463ce4db6", "content_id": "bde7e43fa135b35c91119a10df52b1da48215d5d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 57, "license_type": "no_license", "max_line_length": 15, "num_lines": 4, "path": "/requirements.txt", "repo_name": "alexknight/pyfire", "src_encoding": "UTF-8", "text": "Django==1.7\nargparse==1.2.1\nuWSGI==2.0.10\nwsgiref==0.1.2\n" } ]
4
hdinsight/hdinsight-helper-tools
https://github.com/hdinsight/hdinsight-helper-tools
843f825706867da80ada7a5ce5b1f8ebb064197e
e5eabc2b1b3f472285f1043f959c317ade66e38e
1a9e32c0d012ff101c91a489f6d0ec5c5d82e586
refs/heads/master
2021-07-04T02:02:01.973805
2016-03-22T18:07:12
2016-03-22T18:07:12
54,663,322
1
1
null
2016-03-24T18:03:53
2016-08-01T22:01:58
2021-04-20T08:41:29
C#
[ { "alpha_fraction": 0.6566368937492371, "alphanum_fraction": 0.6605547666549683, "avg_line_length": 40.70588302612305, "blob_id": "8d515da2bdb6d107733c7477787541643cb52069", "content_id": "3be3a5ccbe7fba5b01a024aaa65a9b3515c68a24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6383, "license_type": "no_license", "max_line_length": 178, "num_lines": 153, "path": "/src/StormLogsDownloader/StormLogsDownloader.py", "repo_name": "hdinsight/hdinsight-helper-tools", "src_encoding": "UTF-8", "text": "import logging, requests, sys, os, zipfile, gzip, time\nfrom requests.auth import HTTPBasicAuth\nfrom datetime import datetime\n\nlogger = logging.getLogger(__name__)\n\ndef initialize_logger():\n logger = logging.getLogger()\n logger.setLevel(logging.DEBUG)\n\n # create console handler and set level to info\n handler = logging.StreamHandler()\n formatter = logging.Formatter('%(asctime)s [%(levelname)s] - %(message)s')\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n\n logdir = os.path.dirname(__file__) + '/logs'\n if not os.path.exists(logdir):\n os.makedirs(logdir)\n\n # create error file handler and set level to error\n handler = logging.FileHandler(os.path.join(logdir + '/' + os.path.basename(__file__) + datetime.now().strftime('%Y%m%d%H%M%S') + '.log'), 'w', encoding=None, delay='true')\n formatter = logging.Formatter('%(asctime)s [%(levelname)s] - %(message)s')\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n\ndef main(clusterUrl, clusterUsername, clusterPassword, topologyName, downloadOlderLogs):\n basicAuth = HTTPBasicAuth(clusterUsername, clusterPassword)\n start_time = time.time()\n logger.info('Getting topology summary from cluster: ' + clusterUrl + ' for topology: ' + topologyName)\n topologiesRequest = requests.get(clusterUrl + '/' + 'stormui/api/v1/topology/summary', auth=basicAuth)\n topologiesResponse = topologiesRequest.json()\n logger.info(topologiesResponse)\n\n topologies = topologiesResponse['topologies']\n\n topologyFilter = [i for i, xs in enumerate(topologies) if (topologies[i]['name'] == topologyName)]\n\n if len(topologyFilter) == 0:\n logger.error('Topology not found. Name: ' + topologyName)\n logger.info('Currently running topologies: ')\n for topology in topologies:\n logger.info(topology['name'])\n sys.exit(1)\n else:\n topologyId = topologies[topologyFilter[0]]['id']\n logger.info('Topology found with id: ' + topologyId)\n\n topologyUrl = clusterUrl + '/' + 'stormui/api/v1/topology/' + topologyId\n\n topologyRequest = requests.get(topologyUrl, auth=basicAuth)\n topologySummary = topologyRequest.json()\n logger.info('Topology summary: ' + str(topologySummary))\n\n components = list()\n\n for spout in topologySummary['spouts']:\n components.append(spout['spoutId'])\n\n for bolt in topologySummary['bolts']:\n components.append(bolt['boltId'])\n\n logger.info('Topology: ' + topologyId + ' - Component list: ' + str(components))\n\n logLinks = dict()\n for component in components:\n componentSummary = get_topology_component(topologyUrl, basicAuth, component)\n for executor in componentSummary['executorStats']:\n workerLogLink = clusterUrl + executor['workerLogLink'].replace('log?file=', 'download/')\n if not logLinks.has_key(workerLogLink):\n logLinks[workerLogLink] = executor['host']\n supervisorLogLink = workerLogLink[:workerLogLink.rfind('/')] + '/supervisor.log'\n if not logLinks.has_key(supervisorLogLink):\n logLinks[supervisorLogLink] = executor['host']\n logger.info('Log links: ' + str(logLinks))\n\n if(not downloadOlderLogs):\n logger.info('DownloadOlderLogs set to False will skip downloading older logs')\n for logLink in logLinks.iterkeys():\n logger.info(logLink)\n logFile = download_file(logLink, basicAuth, os.path.join(topologyId, logLinks[logLink]))\n # Do a best effort to download older logs\n if(downloadOlderLogs):\n try_download_olderLogs(logLink, basicAuth, os.path.join(topologyId, logLinks[logLink]))\n\n logs_time = time.time() - start_time\n logger.info('Time taken to download logs: %s secs' % str(logs_time))\n\n zip(topologyId, topologyId)\n zip_time = time.time() - start_time - logs_time\n logger.info('Time taken to zip logs: %s secs' % str(zip_time))\n\n total_time = time.time() - start_time\n logger.info('Total time taken: %s secs' % str(total_time))\n\n sys.exit(0)\n\ndef get_topology_component(topologyUrl, basicAuth, component):\n componentRequest = requests.get(topologyUrl + '/component/' + component, auth=basicAuth)\n componentSummary = componentRequest.json()\n logger.info('Component \\'' + component + '\\' summary: ' + str(componentSummary))\n return componentSummary\n\ndef try_download_olderLogs(url, basicAuth, dir):\n logger.info('Attempting to download older logs using ' + url + ' to ' + dir)\n # With current logback configuration we expect 10 copies with file format 'xyz.log.1'\n for num in range(1,10):\n logUrl = url + '.' + str(num)\n logger.info(logUrl)\n try:\n logFile = download_file(logUrl, basicAuth, dir)\n except Exception, e:\n logger.error('Unable to download more logs: ' + str(e))\n return\n\ndef download_file(url, basicAuth, dir):\n logger.info('Downloading ' + url + ' to ' + dir)\n\n if not os.path.exists(dir):\n os.makedirs(dir)\n\n local_filename = os.path.join(dir, url.split('/')[-1])\n # NOTE the stream=True parameter\n r = requests.get(url, auth=basicAuth, stream=True)\n\n with open(local_filename, 'wb') as f:\n for chunk in r.iter_content(chunk_size=4096):\n if chunk: # filter out keep-alive new chunks\n f.write(chunk)\n f.flush()\n logger.info('Download complete - ' + local_filename)\n return local_filename\n\ndef zip(src, dst):\n dstfile = \"%s.zip\" % (dst)\n logger.info('Creating a zip archive of ' + src)\n zf = zipfile.ZipFile(dstfile, \"w\", zipfile.ZIP_DEFLATED)\n for dirname, subdirs, files in os.walk(src):\n zf.write(dirname)\n for filename in files:\n zf.write(os.path.join(dirname, filename))\n zf.close()\n logger.info('Zip archive created successfully at: ' + dstfile)\n\nif __name__ == '__main__':\n initialize_logger()\n if(len(sys.argv) < 5):\n logger.error('Missing parameters. Syntax: StormLogsDownloader.py \"<CLUSTER_URL>\" \"<CLUSTER_USER>\" \"<CLUSTER_PASSWORD>\" \"<TOPOLOGY_NAME>\" [OPTIONAL]<DOWNLOAD_OLDER_LOGS>')\n sys.exit(-1)\n downloadOlderLogs = True\n if (len(sys.argv) >= 6 and str(sys.argv[5]).upper() == 'FALSE'):\n downloadOlderLogs = False\n main(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], downloadOlderLogs)\n" }, { "alpha_fraction": 0.7644996643066406, "alphanum_fraction": 0.7705544829368591, "avg_line_length": 63.06122589111328, "blob_id": "44ea90801a460b121e5592dc5c37cb2fa8ef7876", "content_id": "40f3e7baf8398fa627b327fe3b7d1fd823c13b85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3138, "license_type": "no_license", "max_line_length": 194, "num_lines": 49, "path": "/src/StormLogsDownloader/README.md", "repo_name": "hdinsight/hdinsight-helper-tools", "src_encoding": "UTF-8", "text": "# Apache Storm Logs Downloader for Azure HDInsight\nThis python script allows you to download all the topology logs from a Azure HDInsight Apache Storm cluster.\n\nThe script relies on STORM UI REST APIs to retreive the worker log links and then downloads them one by one from each node for that topology.\nIt also downloads the supervisor logs from all those workers.\n\n## Pre-Requisites\n* [Python 2.7+](https://www.python.org/)\n* [Python requests](https://pypi.python.org/pypi/requests) package - ```pip install requests```\n* [OPTIONAL] [Python Tools for Visual Studio](http://microsoft.github.io/PTVS/)\n\n## Usage\n* Run the script by providing your cluster url, user name, password and the topology name for which you want to download the logs\n * You need to provide your cluster http username and password that you provided at cluster create time for the basic auth to work\n```\npython StormLogsDownloader.py \"<CLUSTER_URL>\" \"<CLUSTER_USER>\" \"<CLUSTER_PASSWORD>\" \"<TOPOLOGY_NAME>\" [OPTIONAL]<DOWNLOAD_OLDER_LOGS>\n```\n* Or you can use the provided Visual Studio solution file to run via 'F5' (You will need PTVS)\n* The logs for this script are created under the ```logs``` directory which you can use to create issues or ask support for\n* If the logs are too big or it is taking too long to download all older copies, you can choose to skip downloading older logs by passing ```False``` to the final 'DOWNLOAD_OLDER_LOGS' argument.\n\n## Compatibility Notes\nThis package is fully compatible with Azure HDInsight Apache Storm cluster for both Windows and Linux flavors.\n\n### Running this script on Windows 10?\nInstalling Python on Windows 10 may not add it to your system path.\nYou will need to create a system variable called as PYTHON_HOME with a path like ```c:\\python27``` and then add PYTHON_HOME to your system path.\n\n## HDInsight Storm Logs URI format\nOn a Windows cluster the supervisors are registered with nimbus using their host names, however on a linux cluster they currently show up as ip addresses.\n\n* Nimbus log on Headnode - CLUSTER_URL/stormui/hn/log?file=nimbus.log\n* Supervisor log on Workernode - CLUSTER_URL/stormui/wn0/log?file=supervisor.log\n * Linux - CLUSTER_URL/stormui/10.0.0.X/log?file=supervisor.log\n* Worker log on Workernode - CLUSTER_URL/stormui/wn0/log?file=worker-port.log\n * Linux - CLUSTER_URL/stormui/10.0.0.X/log?file=worker-port.log\n\n## References\n* [STORM UI REST API](https://github.com/apache/storm/blob/master/STORM-UI-REST-API.md)\n* [Python Tools for Visual Studio](http://microsoft.github.io/PTVS/)\n\n## TODO (Future extensibility)\n* Add Nimbus log downloading\n * An issue on Windows clusters prevents the links from working, it will be soon live in production.\n * The limitation of not having logview service running on headnode prevents to download Nimbus logs on Linux clusters.\n* Add a flag to download logs of every topology\n * This is easily extensible as we have to just loop over the topologies summary to run the log downloader on topology ids.\n* Parallelize log downloading to reduce time to download for a long running topology\n* Add more retry-ability (use retrying package perhaps)" }, { "alpha_fraction": 0.5330213904380798, "alphanum_fraction": 0.5386363863945007, "avg_line_length": 34.45023727416992, "blob_id": "d23205840ea67cd37ee349b6576bfd95ea54ef19", "content_id": "f09123012d6b079df190d17f8a3f0375f56b1d1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 7482, "license_type": "no_license", "max_line_length": 166, "num_lines": 211, "path": "/src/HDInsightClusterLogsDownloader/HDInsightClusterLogsWriter.cs", "repo_name": "hdinsight/hdinsight-helper-tools", "src_encoding": "UTF-8", "text": "using log4net;\nusing OfficeOpenXml;\nusing OfficeOpenXml.Drawing.Chart;\nusing OfficeOpenXml.Style;\nusing OfficeOpenXml.Table.PivotTable;\nusing System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\n\nnamespace HDInsightClusterLogsDownloader\n{\n public class PivotField\n {\n public string FieldName;\n public string DisplayName;\n\n public PivotField()\n {\n }\n\n public PivotField(string fieldName, string displayName = null)\n {\n this.FieldName = fieldName;\n\n if (string.IsNullOrWhiteSpace(displayName))\n {\n this.DisplayName = fieldName;\n }\n else\n {\n this.DisplayName = displayName;\n }\n }\n }\n\n public class PivotDataField : PivotField\n {\n public DataFieldFunctions Function;\n\n public PivotDataField(string fieldName, string displayName = null, DataFieldFunctions funtion = DataFieldFunctions.Average)\n {\n this.FieldName = fieldName;\n\n if (string.IsNullOrWhiteSpace(displayName))\n {\n this.DisplayName = fieldName;\n }\n else\n {\n this.DisplayName = displayName;\n }\n\n this.Function = funtion;\n }\n }\n\n public class HDInsightClusterLogsWriter\n {\n private static readonly ILog Logger = LogManager.GetLogger(typeof(HDInsightClusterLogsDownloader));\n\n public static void Write(OperatingSystemType clusterOperatingSystemType, string filePath, List<Object> logEntities)\n {\n if (File.Exists(filePath))\n {\n File.Delete(filePath);\n }\n\n var excelPackageLogs = new ExcelPackage(new FileInfo(filePath));\n List<MemberInfo> columnInfoBuilds;\n\n var excelWorksheetHadoopServiceLogs = CreateExcelWorksheetForDataList(excelPackageLogs, \"HadoopServiceLog\", logEntities, out columnInfoBuilds);\n\n if (columnInfoBuilds != null && columnInfoBuilds.Count > 0)\n {\n CreateExcelPivotForWorksheet(excelPackageLogs, excelWorksheetHadoopServiceLogs, \"ComponentLogTypePivot\",\n new List<PivotField>() { new PivotField(\"Role\") },\n new List<PivotField>() { new PivotField(\"ComponentName\") },\n new List<PivotField>() { new PivotField(\"TraceLevel\") },\n new List<PivotDataField>() { new PivotDataField(\"Message\", \"Count\", DataFieldFunctions.Count) },\n logEntities.Count, columnInfoBuilds.Count\n );\n }\n excelPackageLogs.Save();\n }\n\n public static ExcelWorksheet CreateExcelWorksheetForDataList(ExcelPackage exPackage, string sheetName, List<Object> dataList, out List<MemberInfo> columnInfo)\n {\n var exWorksheet = exPackage.Workbook.Worksheets.Add(sheetName);\n int i = 1, j = 1;\n\n columnInfo = null;\n if (dataList.Count > 0)\n {\n var obj = dataList[0];\n\n columnInfo = (obj.GetType()).GetProperties(BindingFlags.Public | BindingFlags.Instance).Cast<MemberInfo>().ToList();\n\n foreach (var member in columnInfo)\n {\n exWorksheet.Cells[1, i].Value = member.Name;\n if (member.MemberType == MemberTypes.Property &&\n (((PropertyInfo)member).PropertyType == typeof(DateTime)) || (((PropertyInfo)member).PropertyType == typeof(DateTimeOffset)))\n {\n exWorksheet.Column(i).Style.Numberformat.Format = \"yyyy-MM-dd\";\n }\n i++;\n }\n\n i = 2;\n foreach (var data in dataList)\n {\n j = 1;\n foreach (var member in columnInfo)\n {\n exWorksheet.Cells[i, j++].Value = data.GetType().GetProperty(member.Name).GetValue(data);\n }\n i++;\n }\n exWorksheet.Cells[1, 1, i - 1, j - 1].AutoFilter = true;\n using (var range = exWorksheet.Cells[1, 1, 1, j - 1])\n {\n range.Style.Font.Bold = true;\n range.Style.Fill.PatternType = ExcelFillStyle.Solid;\n range.Style.Fill.BackgroundColor.SetColor(Color.DarkBlue);\n range.Style.Font.Color.SetColor(Color.White);\n range.AutoFitColumns();\n }\n }\n return exWorksheet;\n }\n\n public static void CreateExcelPivotForWorksheet(ExcelPackage exPackage, ExcelWorksheet exWorksheet, string name,\n List<PivotField> pageFields, List<PivotField> rowFields, List<PivotField> columnFields, List<PivotDataField> dataFields,\n int rowCount, int columnCount)\n {\n //Pivot PassRate\n var exPivotSheet = exPackage.Workbook.Worksheets.Add(name);\n\n //add 1 to rowCount as TopRow is ColumnNames\n var exPivotTable = exPivotSheet.PivotTables.Add(exPivotSheet.Cells[\"A3\"], exWorksheet.Cells[1, 1, rowCount + 1, columnCount], name);\n\n if (pageFields != null)\n {\n foreach (var field in pageFields)\n {\n exPivotTable.PageFields.Add(exPivotTable.Fields[field.FieldName]);\n }\n }\n\n if (rowFields != null)\n {\n foreach (var field in rowFields)\n {\n exPivotTable.RowFields.Add(exPivotTable.Fields[field.FieldName]);\n }\n }\n\n if (columnFields != null)\n {\n foreach (var field in columnFields)\n {\n exPivotTable.ColumnFields.Add(exPivotTable.Fields[field.FieldName]);\n }\n }\n\n if (dataFields != null)\n {\n var i = 0;\n foreach (var field in dataFields)\n {\n exPivotTable.DataFields.Add(exPivotTable.Fields[field.FieldName]);\n exPivotTable.DataFields[i++].Function = field.Function;\n }\n\n foreach (var df in exPivotTable.DataFields)\n {\n if (df.Function == DataFieldFunctions.Average)\n {\n df.Format = \"#.00\";\n }\n }\n }\n\n exPivotTable.DataOnRows = false;\n\n var chart = exPivotSheet.Drawings.AddChart(\"PC\" + name, eChartType.ColumnClustered, exPivotTable) as ExcelBarChart;\n\n if (dataFields.Count > 1)\n {\n chart.VaryColors = true;\n }\n\n chart.SetPosition(4, 0, 6, 0);\n chart.SetSize(640, 480);\n\n chart.Title.Text = name;\n chart.Title.Font.Size = 12;\n\n chart.XAxis.Title.Text = String.Join(\", \", rowFields.Select(f => f.DisplayName).ToList());\n chart.XAxis.Title.Font.Size = 10;\n\n chart.YAxis.Title.Text = String.Join(\", \", dataFields.Select(f => f.DisplayName).ToList());\n chart.YAxis.Title.Font.Size = 10;\n\n chart.DataLabel.ShowValue = true;\n }\n }\n}\n" }, { "alpha_fraction": 0.6158192157745361, "alphanum_fraction": 0.6255044341087341, "avg_line_length": 27.813953399658203, "blob_id": "61c115f0f32b041aa85c71880ab8e38b1d2b8448", "content_id": "8b64c42b5f5b8605607889a318cc0272b2fd3026", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1241, "license_type": "no_license", "max_line_length": 149, "num_lines": 43, "path": "/src/HDInsightClusterLogsDownloader/HadoopServiceLogEntity.cs", "repo_name": "hdinsight/hdinsight-helper-tools", "src_encoding": "UTF-8", "text": "using Microsoft.WindowsAzure.Storage.Table;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace HDInsightClusterLogsDownloader\n{\n public class HadoopServiceLogEntity : TableEntity\n {\n public string Tenant { get; set; }\n public string Role { get; set; }\n public string TraceLevel { get; set; }\n public string ComponentName { get; set; }\n public string Message { get; set; }\n\n public override string ToString()\n {\n return String.Format(\"{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}\", ETag, PartitionKey, RowKey, Timestamp, Role, TraceLevel, ComponentName, Message);\n }\n }\n\n public class WindowsHadoopServiceLogEntity : HadoopServiceLogEntity\n {\n public string RoleInstance { get; set; }\n\n public override string ToString()\n {\n return String.Format(\"{0}|{1}\", base.ToString(), RoleInstance);\n }\n }\n\n public class LinuxHadoopServiceLogEntity : HadoopServiceLogEntity\n {\n public string Host { get; set; }\n\n public override string ToString()\n {\n return String.Format(\"{0}|{1}\", base.ToString(), Host);\n }\n }\n}\n" }, { "alpha_fraction": 0.5160754919052124, "alphanum_fraction": 0.5177761316299438, "avg_line_length": 33.29999923706055, "blob_id": "c0a2b496b0df73c2276a20a99fe94e5cc8d1e42d", "content_id": "2cb1dc1b14977acd6475ad977270b1867581fde0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 24696, "license_type": "no_license", "max_line_length": 194, "num_lines": 720, "path": "/src/HDInsightManagementCLI/Config.cs", "repo_name": "hdinsight/hdinsight-helper-tools", "src_encoding": "UTF-8", "text": "using log4net;\nusing System;\nusing System.Collections.Generic;\nusing System.Configuration;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Text.RegularExpressions;\n\nnamespace HDInsightManagementCLI\n{\n public class AzureStorageConfig\n {\n public string Name { get; set; }\n public string Key { get; set; }\n public string Container { get; set; }\n }\n\n public class SqlAzureConfig\n {\n public string Server { get; set; }\n public string Database { get; set; }\n public string User { get; set; }\n public string Password { get; set; }\n public string Type { get; set; }\n }\n\n public class Config\n {\n private static readonly ILog Logger = LogManager.GetLogger(typeof(HDInsightManagementCLI));\n\n public enum ConfigName\n {\n AzureManagementUri,\n AzureResourceManagementUri,\n AzureResourceProviderNamespace,\n AzureActiveDirectoryUri,\n AzureActiveDirectoryRedirectUri,\n AzureActiveDirectoryTenantId,\n AzureActiveDirectoryClientId,\n SubscriptionId,\n ResourceGroupName,\n ClusterLocation,\n ClusterDnsName,\n ClusterSize,\n ClusterUsername,\n ClusterPassword,\n SshUsername,\n SshPassword,\n SshPublicKeyFilePath,\n HDInsightVersion,\n DefaultStorageAccountName,\n DefaultStorageAccountKey,\n DefaultStorageAccountContainer,\n AdditionalStorageAccountNames,\n AdditionalStorageAccountKeys,\n SqlAzureAsMetastore,\n SqlHiveMetastoreServer,\n SqlHiveMetastoreDatabase,\n SqlHiveMetastoreUser,\n SqlHiveMetastorePassword,\n SqlOozieMetastoreDatabase,\n SqlOozieMetastoreServer,\n SqlOozieMetastoreUser,\n SqlOozieMetastorePassword,\n OperationPollIntervalInSeconds,\n TimeoutPeriodInMinutes,\n DeleteCutoffPeriodInHours,\n CleanupOnError,\n SilentMode,\n AutoEnableRdp,\n RdpUsername,\n RdpPassword,\n RdpExpirationInDays,\n ClusterType,\n OperatingSystemType,\n HeadNodeSize,\n WorkerNodeSize,\n ZookeeperSize,\n VirtualNetworkId,\n SubnetName,\n }\n\n private readonly Dictionary<ConfigName, string> _overrides =\n new Dictionary<ConfigName, string>();\n\n public Config(string[] args)\n {\n var argsList = new List<string>(args);\n foreach (ConfigName config in System.Enum.GetValues(typeof(ConfigName)))\n {\n if (argsList.Count > 0)\n {\n string result;\n\n if (ApplicationUtilities.TryGetArgumentValue(argsList, string.Format(\"/{0}:\", config), out result))\n {\n _overrides.Add(config, result);\n }\n }\n else\n {\n break;\n }\n }\n\n //Ignore the first valid command\n if (argsList.Count - 1 != _overrides.Count)\n {\n Logger.InfoFormat(\"WARNING! Override parse count mismatch. Overrides Passed: {0}, Overrides Parsed: {1}\", argsList.Count - 1, _overrides.Count);\n }\n }\n\n public string AzureManagementUri\n {\n get { return GetConfigurationValue(ConfigName.AzureManagementUri); }\n }\n\n public string AzureResourceManagementUri\n {\n get { return GetConfigurationValue(ConfigName.AzureResourceManagementUri); }\n }\n\n public string AzureResourceProviderNamespace\n {\n get { return GetConfigurationValue(ConfigName.AzureResourceProviderNamespace); }\n }\n \n public string AzureActiveDirectoryUri\n {\n get { return GetConfigurationValue(ConfigName.AzureActiveDirectoryUri); }\n }\n\n public string AzureActiveDirectoryRedirectUri\n {\n get { return GetConfigurationValue(ConfigName.AzureActiveDirectoryRedirectUri); }\n }\n\n public string AzureActiveDirectoryTenantId\n {\n get { return GetConfigurationValue(ConfigName.AzureActiveDirectoryTenantId); }\n }\n\n public string AzureActiveDirectoryClientId\n {\n get { return GetConfigurationValue(ConfigName.AzureActiveDirectoryClientId); }\n }\n\n public string ClusterType\n {\n get\n {\n return GetConfigurationValue(ConfigName.ClusterType);\n }\n }\n\n public string OSType\n {\n get\n {\n return GetConfigurationValue(ConfigName.OperatingSystemType);\n }\n }\n\n private string _subscriptionId = null;\n [System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Design\", \"CA1065:DoNotRaiseExceptionsInUnexpectedLocations\")]\n public string SubscriptionId\n {\n get\n {\n if (_subscriptionId == null)\n {\n _subscriptionId = GetConfigurationValue(ConfigName.SubscriptionId);\n Guid guid;\n var result = Guid.TryParse(_subscriptionId, out guid);\n if (!result)\n {\n throw new ApplicationException(\n String.Format(\n \"SubscriptionId: '{0}' is not a valid value, please use a valid subscription id or a well formed guid\",\n _subscriptionId));\n }\n }\n return _subscriptionId;\n }\n }\n\n public string ClusterLocation\n {\n get { return GetConfigurationValue(ConfigName.ClusterLocation); }\n }\n\n private string _clusterDnsName = null;\n public string ClusterDnsName\n {\n get\n {\n if (_clusterDnsName == null)\n {\n _clusterDnsName = GetConfigurationValue(ConfigName.ClusterDnsName);\n }\n\n return _clusterDnsName;\n }\n set\n {\n _clusterDnsName = value;\n }\n }\n\n private string _resourceGroupName = null;\n public string ResourceGroupName\n {\n get\n {\n if (_resourceGroupName == null)\n {\n var result = TryGetConfigurationValue(ConfigName.ResourceGroupName, out _resourceGroupName);\n\n if(!result || String.IsNullOrWhiteSpace(_resourceGroupName))\n {\n _resourceGroupName = HDInsightManagementCLIHelpers.GetResourceGroupName(SubscriptionId, ClusterLocation);\n }\n }\n\n return _resourceGroupName;\n }\n set\n {\n _resourceGroupName = value;\n }\n }\n\n public string ClusterUsername\n {\n get\n {\n string returnValue = null;\n bool result = TryGetConfigurationValue(ConfigName.ClusterUsername, out returnValue);\n if (!result)\n {\n returnValue = \"admin\";\n }\n return returnValue;\n }\n }\n\n private string _clusterPassword = null;\n public string ClusterPassword\n {\n get\n {\n if (string.IsNullOrWhiteSpace(_clusterPassword))\n {\n bool result = TryGetConfigurationValue(ConfigName.ClusterPassword, out _clusterPassword);\n if (!result)\n {\n Logger.InfoFormat(\"Generating random cluster password of length 24 using System.Web.Security.Membership.GeneratePassword\");\n do\n {\n _clusterPassword = System.Web.Security.Membership.GeneratePassword(24, 2);\n }\n while (!Regex.IsMatch(_clusterPassword, HDInsightManagementCLIHelpers.HDInsightPasswordValidationRegex));\n Logger.InfoFormat(\"PLEASE NOTE: New cluster password: {0}\", _clusterPassword);\n Logger.InfoFormat(\"If the cluster was created previously you should use the previously generated password instead.\");\n SaveConfigurationValue(ConfigName.ClusterPassword, _clusterPassword);\n }\n }\n return _clusterPassword;\n }\n set\n {\n _clusterPassword = value;\n }\n }\n\n public string SshUsername\n {\n get\n {\n string returnValue = null;\n bool result = TryGetConfigurationValue(ConfigName.SshUsername, out returnValue);\n if (!result)\n {\n returnValue = \"ssh\" + ClusterUsername;\n }\n return returnValue;\n }\n }\n\n public string SshPassword\n {\n get\n {\n string returnValue = null;\n bool result = TryGetConfigurationValue(ConfigName.SshPassword, out returnValue);\n return returnValue;\n }\n }\n\n public string SshPublicKeyFilePath\n {\n get\n {\n string returnValue = null;\n bool result = TryGetConfigurationValue(ConfigName.SshPublicKeyFilePath, out returnValue);\n if(!result)\n {\n var keyPair = HDInsightManagementCLIHelpers.GenerateSshKeyPair(ClusterDnsName, ClusterPassword);\n Logger.InfoFormat(\"PLEASE NOTE: A new SSH key pair was generated. Public Key Path: {0}, Private Key Path: {1}, Passphrase: {2}\", keyPair.Key, keyPair.Value, ClusterPassword);\n Logger.InfoFormat(\"This new key path will saved in your application configuration, the passphrase is same as your cluster password.\");\n returnValue = keyPair.Key;\n SaveConfigurationValue(ConfigName.SshPublicKeyFilePath, returnValue);\n }\n return returnValue;\n }\n }\n\n public int ClusterSize\n {\n get\n {\n int defaultValue = 3;\n int returnValue = defaultValue;\n string outValue = null;\n bool result = TryGetConfigurationValue(ConfigName.ClusterSize, out outValue);\n if (result)\n {\n bool flag = int.TryParse(outValue, out returnValue);\n if (!flag)\n {\n returnValue = defaultValue;\n }\n }\n return returnValue;\n }\n }\n\n public string HDInsightVersion\n {\n get\n {\n string returnValue = null;\n bool result = TryGetConfigurationValue(ConfigName.HDInsightVersion, out returnValue);\n if (!result)\n {\n returnValue = \"default\";\n }\n return returnValue;\n }\n }\n\n private AzureStorageConfig _defaultStorageAccount;\n public AzureStorageConfig DefaultStorageAccount\n {\n get\n {\n if(_defaultStorageAccount == null)\n {\n _defaultStorageAccount = new AzureStorageConfig()\n {\n Name = GetConfigurationValue(ConfigName.DefaultStorageAccountName),\n Key = GetConfigurationValue(ConfigName.DefaultStorageAccountKey)\n };\n\n string container = null;\n var result = TryGetConfigurationValue(ConfigName.DefaultStorageAccountContainer, out container);\n if(result && !String.IsNullOrEmpty(container))\n {\n _defaultStorageAccount.Container = container;\n }\n }\n return _defaultStorageAccount;\n }\n set\n {\n _defaultStorageAccount = value;\n }\n }\n\n private List<AzureStorageConfig> _additionalStorageAccounts = null;\n [System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Design\", \"CA1065:DoNotRaiseExceptionsInUnexpectedLocations\")]\n public List<AzureStorageConfig> AdditionalStorageAccounts\n {\n get\n {\n if (_additionalStorageAccounts == null)\n {\n _additionalStorageAccounts = new List<AzureStorageConfig>();\n\n var additionalStorageAccountNames = GetConfigurationValue(ConfigName.AdditionalStorageAccountNames).Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);\n var additionalStorageAccountKeys = GetConfigurationValue(ConfigName.AdditionalStorageAccountKeys).Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);\n\n if (additionalStorageAccountNames.Count() != additionalStorageAccountKeys.Count())\n {\n throw new ApplicationException(\n String.Format(\"AdditionalStorageAccountNames.Count: {0} is not equal to AdditionalStorageAccountKeys.Count: {1}\",\n additionalStorageAccountNames.Count(), additionalStorageAccountKeys.Count()));\n }\n\n for (int i = 0; i < additionalStorageAccountNames.Count(); i++)\n {\n var additionalStorageAccount = new AzureStorageConfig()\n {\n Name = additionalStorageAccountNames[i],\n Key = additionalStorageAccountKeys[i]\n };\n\n _additionalStorageAccounts.Add(additionalStorageAccount);\n }\n }\n return _additionalStorageAccounts;\n }\n set\n {\n _additionalStorageAccounts = value;\n }\n }\n\n private List<SqlAzureConfig> _sqlAzureMetastores = null;\n public List<SqlAzureConfig> SqlAzureMetastores\n {\n get\n {\n if (_sqlAzureMetastores == null && SqlAzureAsMetastore)\n {\n _sqlAzureMetastores = new List<SqlAzureConfig>();\n\n var sqlHive = new SqlAzureConfig()\n {\n Server = GetConfigurationValue(ConfigName.SqlHiveMetastoreServer),\n Database = GetConfigurationValue(ConfigName.SqlHiveMetastoreDatabase),\n User = GetConfigurationValue(ConfigName.SqlHiveMetastoreUser),\n Password = GetConfigurationValue(ConfigName.SqlHiveMetastorePassword),\n Type = \"HiveMetastore\"\n };\n\n _sqlAzureMetastores.Add(sqlHive);\n\n var sqlOozie = new SqlAzureConfig()\n {\n Server = GetConfigurationValue(ConfigName.SqlOozieMetastoreServer),\n Database = GetConfigurationValue(ConfigName.SqlOozieMetastoreDatabase),\n User = GetConfigurationValue(ConfigName.SqlOozieMetastoreUser),\n Password = GetConfigurationValue(ConfigName.SqlOozieMetastorePassword),\n Type = \"OozieMetastore\"\n };\n\n _sqlAzureMetastores.Add(sqlOozie);\n }\n return _sqlAzureMetastores;\n }\n set\n {\n _sqlAzureMetastores = value;\n }\n }\n\n public string HeadNodeSize\n {\n get { return GetConfigurationValue(ConfigName.HeadNodeSize); }\n }\n\n public string WorkerNodeSize\n {\n get { return GetConfigurationValue(ConfigName.WorkerNodeSize); }\n }\n\n public string ZookeeperSize\n {\n get { return GetConfigurationValue(ConfigName.ZookeeperSize); }\n }\n\n public string VirtualNetworkId\n {\n get { return GetConfigurationValue(ConfigName.VirtualNetworkId); }\n }\n\n public string SubnetName\n {\n get { return GetConfigurationValue(ConfigName.SubnetName); }\n }\n\n public int OperationPollIntervalInSeconds\n {\n get\n {\n int defaultValue = 30;\n int returnValue = defaultValue;\n string outValue = null;\n bool result = TryGetConfigurationValue(ConfigName.OperationPollIntervalInSeconds, out outValue);\n if (result)\n {\n bool flag = int.TryParse(outValue, out returnValue);\n if (!flag)\n {\n returnValue = defaultValue;\n }\n }\n return returnValue;\n }\n }\n\n public int TimeoutPeriodInMinutes\n {\n get\n {\n int defaultValue = 60;\n int returnValue = defaultValue;\n string outValue = null;\n bool result = TryGetConfigurationValue(ConfigName.TimeoutPeriodInMinutes, out outValue);\n if (result)\n {\n bool flag = int.TryParse(outValue, out returnValue);\n if (!flag)\n returnValue = defaultValue;\n }\n return returnValue;\n }\n }\n\n int _deleteCutoffPeriodInHours = 24;\n public int DeleteCutoffPeriodInHours\n {\n get\n {\n string outValue;\n bool result = TryGetConfigurationValue(ConfigName.DeleteCutoffPeriodInHours, out outValue);\n if (result)\n {\n int returnValue;\n bool flag = int.TryParse(outValue, out returnValue);\n if (flag)\n _deleteCutoffPeriodInHours = returnValue;\n }\n return _deleteCutoffPeriodInHours;\n }\n set\n {\n _deleteCutoffPeriodInHours = value;\n }\n }\n\n public bool SqlAzureAsMetastore\n {\n get\n {\n string returnValue;\n bool result = TryGetConfigurationValue(ConfigName.SqlAzureAsMetastore, out returnValue);\n if (!result)\n {\n returnValue = \"false\";\n }\n return IsValueYesOrTrue(returnValue);\n }\n }\n\n public bool CleanupOnError\n {\n get\n {\n string returnValue;\n bool result = TryGetConfigurationValue(ConfigName.CleanupOnError, out returnValue);\n if (!result)\n {\n returnValue = \"false\";\n }\n return IsValueYesOrTrue(returnValue);\n }\n set\n {\n SetConfigurationValue(ConfigName.CleanupOnError, value.ToString());\n }\n }\n\n public bool SilentMode\n {\n get\n {\n string returnValue;\n bool result = TryGetConfigurationValue(ConfigName.SilentMode, out returnValue);\n if (!result)\n returnValue = \"false\";\n return IsValueYesOrTrue(returnValue);\n }\n }\n\n public string RdpUsername\n {\n get\n {\n string returnValue = null;\n bool result = TryGetConfigurationValue(ConfigName.RdpUsername, out returnValue);\n if (!result)\n {\n returnValue = \"rdp\" + ClusterUsername;\n }\n return returnValue;\n }\n }\n\n public string RdpPassword\n {\n get\n {\n string returnValue = null;\n bool result = TryGetConfigurationValue(ConfigName.RdpPassword, out returnValue);\n if (!result)\n {\n returnValue = ClusterPassword;\n SaveConfigurationValue(ConfigName.RdpPassword, returnValue);\n }\n return returnValue;\n }\n }\n\n public string RdpExpirationInDays\n {\n get { return GetConfigurationValue(ConfigName.RdpExpirationInDays); }\n }\n\n public bool AutoEnableRdp\n {\n get\n {\n string returnValue = null;\n bool result = TryGetConfigurationValue(ConfigName.AutoEnableRdp, out returnValue);\n if (!result)\n {\n returnValue = \"false\";\n }\n return IsValueYesOrTrue(returnValue);\n }\n }\n\n private bool IsValueYesOrTrue(string value)\n {\n if (String.Compare(value, \"y\", StringComparison.OrdinalIgnoreCase) == 0 || String.Compare(value, \"yes\", StringComparison.OrdinalIgnoreCase) == 0 ||\n String.Compare(value, \"true\", StringComparison.OrdinalIgnoreCase) == 0)\n {\n return true;\n }\n return false;\n }\n\n internal string GetConfigurationValue(ConfigName configName)\n {\n string returnValue = null;\n if (_overrides.ContainsKey(configName))\n {\n returnValue = _overrides[configName];\n }\n else\n {\n returnValue = ConfigurationManager.AppSettings[configName.ToString()];\n }\n\n if (String.IsNullOrEmpty(returnValue))\n {\n throw new ArgumentNullException(configName.ToString());\n }\n\n return returnValue;\n }\n\n internal bool TryGetConfigurationValue(ConfigName configName, out string configValue)\n {\n configValue = _overrides.ContainsKey(configName) ? _overrides[configName] : ConfigurationManager.AppSettings[configName.ToString()];\n\n return !String.IsNullOrEmpty(configValue);\n }\n\n private void SetConfigurationValue(ConfigName configName, string value)\n {\n if (_overrides.ContainsKey(configName))\n {\n _overrides[configName] = value;\n }\n else\n {\n _overrides.Add(configName, value);\n }\n }\n\n private void SaveConfigurationValue(ConfigName configName, string value)\n {\n Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);\n KeyValueConfigurationCollection settings = config.AppSettings.Settings;\n\n settings[configName.ToString()].Value = value;\n\n Logger.InfoFormat(\"Saving application configuration - Key: {0}, Value: {1}\", configName.ToString(), value);\n config.Save(ConfigurationSaveMode.Modified);\n \n ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);\n }\n\n public void PrintRunConfiguration()\n {\n if (this.SilentMode)\n {\n return;\n }\n\n var sb = new StringBuilder();\n\n sb.AppendLine(Environment.NewLine + \"====================Current Run Configuration====================\");\n foreach (ConfigName configPropertyName in Enum.GetValues(typeof(ConfigName)))\n {\n string configValue;\n this.TryGetConfigurationValue(configPropertyName, out configValue);\n if (!String.IsNullOrEmpty(configValue))\n {\n sb.AppendLine(String.Format(\"{0} : {1}\", configPropertyName, configValue));\n }\n }\n Logger.Info(sb.ToString());\n }\n }\n}\n" }, { "alpha_fraction": 0.7757611274719238, "alphanum_fraction": 0.8132318258285522, "avg_line_length": 62.25925827026367, "blob_id": "3ca2c835c8cb06c60082e5bcc06b78646c4f9d14", "content_id": "49158498fb7e64a976de3b130b53b7c7da1bb31d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1708, "license_type": "no_license", "max_line_length": 203, "num_lines": 27, "path": "/src/HDInsightClusterLogsDownloader/README.md", "repo_name": "hdinsight/hdinsight-helper-tools", "src_encoding": "UTF-8", "text": "# HDInsightClusterLogsDownloader\nA command line tool to download the hadoop and other components service logs of your Microsoft Azure HDInsight clusters.\nYou need to first use the [HDInsightManagementCLI](../HDInsightManagementCLI) to get the UserClusterTablePrefix for your cluster.\n\nAdd your storage account credentials into the App.config and provide the table name (e.g. ustormiaasprod219aug2015at204409001hadoopservicelog) or the table name prefix (e.g. ustormiaasprod219aug2015at20)\n\nOnce the tools runs it will create an excel workbook with all the logs and also pivot tables that show your TraceLevel splits.\n\nYou may extend or modify the tools to make your query granular or larger. \nSpecifying wide or large filter ranges will make the query take a long time to download.\nCurrently aborts at 100000 rows or 15 minutes - whichever is earlier to avoid out of memory issues.\n\nLogs from you **hadoopservicelog** table (below is a snapshot from a Linux Storm cluster):\n![Image of HadoopServiceLog workbook](images/HadoopServiceLog.png)\n\nThe excel workbook also contains the ability to create Pivot table to show components failing the most:\n![Image of PivotTableComponentErrorWarn workbook](images/PivotTableComponentErrorWarn.png)\n\n## References\n* https://social.msdn.microsoft.com/Forums/azure/en-US/8a1b48a3-2617-4a2c-980f-4022005a9afa/question-about-logging-in-storm-with-hdinsight?forum=hdinsight\n* http://blogs.msdn.com/b/brian_swan/archive/2014/01/06/accessing-hadoop-logs-in-hdinsight.aspx\n* https://github.com/hdinsight/hdinsight-storm-examples/issues/7\n\n## TODO (How you can help)\n* Switch to Dynamic table entities to support other tables\n* Augment parsing & checking\n* Query building helper\n" }, { "alpha_fraction": 0.7614893913269043, "alphanum_fraction": 0.7653951048851013, "avg_line_length": 54.25899124145508, "blob_id": "f783cdef21305f4510ff26edc3e835642c2b0a07", "content_id": "93427b4ce6c9353ba9b01b3dfbf6433b161a29cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7681, "license_type": "no_license", "max_line_length": 267, "num_lines": 139, "path": "/src/HDInsightManagementCLI/README.md", "repo_name": "hdinsight/hdinsight-helper-tools", "src_encoding": "UTF-8", "text": "# HDInsightManagementCLI\nThis is an **unofficial** tool created for managing (create, list and delete) your Microsoft Azure HDInsight clusters.\nIt is developed using the latest preview SDK that supports deploying both Windows and Linux clusters using Azure Resource Manager (ARM).\n\n**[Microsoft.Azure.Management.HDInsight NuGet](https://www.nuget.org/packages/Microsoft.Azure.Management.HDInsight) -** [![NuGet version](https://badge.fury.io/nu/Microsoft.Azure.Management.HDInsight.svg)](http://badge.fury.io/nu/Microsoft.Azure.Management.HDInsight)\n\n## Key points\n* HDInsight is moving to Azure Resource Manager.\n * The **Windows** clusters are still PaaS and are deployed RDFE way\n * The **Linux** clusters are in IaaS model and are deployed via Azure Resource Manager.\n* You will not be able to deploy **Storm** and **HBase** cluster types for **Linux** OS flavor from the old azure portal (RDFE based).\n * You will need to use the new preview portal to create any new cluster types in Linux.\n * Windows based clusters can be created using the new portal, old portal, new SDK and old SDK.\n* Certificate based credentials will no longer work if you are using the new SDK (ARM), you need to use Active Directory Token based credentials.\n ```csharp\n Logger.InfoFormat(\"Getting Azure ActiveDirectory Token from {0}\", config.AzureActiveDirectoryUri);\n AuthenticationContext ac = new AuthenticationContext(config.AzureActiveDirectoryUri + config.AzureActiveDirectoryTenantId, true);\n var token = ac.AcquireToken(config.AzureManagementUri, config.AzureActiveDirectoryClientId,\n new Uri(config.AzureActiveDirectoryRedirectUri), PromptBehavior.Auto);\n\n Logger.InfoFormat(\"Acquired Azure ActiveDirectory Token for User: {0} with Expiry: {1}\", token.UserInfo.GivenName, token.ExpiresOn);\n tokenCloudCredentials = new TokenCloudCredentials(config.SubscriptionId, token.AccessToken);\n\n Logger.InfoFormat(\"Connecting to AzureResourceManagementUri endpoint at {0}\", config.AzureResourceManagementUri);\n hdInsightManagementClient = new HDInsightManagementClient(tokenCloudCredentials, new Uri(config.AzureResourceManagementUri));\n ```\n Configurations:\n ```\n AzureManagementUri : https://management.core.windows.net/\n AzureResourceManagementUri : https://management.azure.com/\n AzureActiveDirectoryUri : https://login.windows.net/\n AzureActiveDirectoryRedirectUri : urn:ietf:wg:oauth:2.0:oob\n AzureActiveDirectoryTenantId : YOUR-TENANT-ID\n AzureActiveDirectoryClientId : 1950a258-227b-4e31-a9cf-717495945fc2\n ```\n* You need to call GetCapabilities to list any subscription properties. (You may pass any Azure location to get capabilities)\n\n## Change Impact\nThe new [HDInsight ARM SDK](https://www.nuget.org/packages/Microsoft.Azure.Management.HDInsight) is completely different than the [RDFE HDInsight SDK](Microsoft.WindowsAzure.Management.HDInsight). \nThe new SDK does not break existing scripts or clients as it is a separate NuGet package.\nYou will not automatically get this SDK if you update your current HDInsight SDKs. Instead, you will have to explicitly choose the NuGet packages for the new SDK.\n\nThere are two parts of this SDK: cluster CRUD (management) and job submission (data). The new changes do not impact job submission to templeton, hence the data SDK remains fairly same.\n\nOne can use the SDK by installing the appropriate NuGet package for the SDK:\n* RDFE data NuGet package: Microsoft.Hadoop.Client\n* ARM data NuGet package: Microsoft.Azure.Management.HDInsight.Job \n* RDFE management NuGet package: Microsoft.WindowsAzure.Management.HDInsight \n* ARM management NuGet package: Microsoft.Azure.Management.HDInsight \n\nWith the move to ARM, HDInsight has begun to use Hyak. \nHyak is a code generator written by the Azure SDK team that provides the ability to generate client SDK code for REST API endpoints in multiple programming languages.\n\nThe following operations are no longer be supported in the SDK:\n* ListAvailableLocations \n* ListAvailableVersions \n\nThis information is available via the GetCapabilities operation. \n\n## Usage\n```\n--------------------------------------------------\nMicrosoft HdInsight Management Tool Help\n--------------------------------------------------\nYou must provide one of the following as command line arg:\nc - creates a cluster\nd - deletes the cluster\nl - list all the clusters for the specified subscription\nls - list a specific cluster's details for the specified subscription and ClusterDnsName\nlsrc - resume cluster creation monitoring (helpful to resume if you get a timeout or lost track of the create)\nlsrd - resume cluster deletion monitoring (helpful to resume if you get a timeout or lost track of the delete)\ngsl - get supported locations for a subcription\ngc - gets subcription capabilities like supported regions, versions, os types etc\ndall - delete all the clusters based off on cutoff time. Cutoff time is overridable using DeleteCutoffPeriodInHours\nrdpon, rdponrdfe - enable rdp for a cluster. RdpUsername, RdpPassword, RdpExpirationInDays are specified using RdpUsername, RdpPassword, RdpExpirationInDays\nConfiguration Overrides - Command Line arguments for configuration take precedence over App.config\nSpecifying a configuration override in command line: /{ConfigurationName}:{ConfigurationValue}\nOptional/Additional parameters that override the configuration values can be specified in the App.config\nOverridable Configuration Names:\n AzureManagementUri\n AzureResourceManagementUri\n AzureActiveDirectoryUri\n AzureActiveDirectoryRedirectUri\n AzureActiveDirectoryTenantId\n AzureActiveDirectoryClientId\n AzureManagementCertificateName\n AzureManagementCertificatePassword\n SubscriptionId\n ResourceGroupName\n ClusterLocation\n ClusterDnsName\n ClusterSize\n ClusterUsername\n ClusterPassword\n SshUsername\n SshPassword\n SshPublicKeyFilePath\n HDInsightVersion\n WasbNames\n WasbKeys\n WasbContainers\n SqlAzureAsMetastore\n SqlHiveMetastoreServer\n SqlHiveMetastoreDatabase\n SqlHiveMetastoreUser\n SqlHiveMetastorePassword\n SqlOozieMetastoreDatabase\n SqlOozieMetastoreServer\n SqlOozieMetastoreUser\n SqlOozieMetastorePassword\n OperationPollIntervalInSeconds\n TimeoutPeriodInMinutes\n DeleteCutoffPeriodInHours\n CleanupOnError\n SilentMode\n BuildLabMode\n AutoEnableRdp\n RdpUsername\n RdpPassword\n RdpExpirationInDays\n ClusterType\n OperatingSystemType\n--------------------------------------------------\nExamples:\nHDInsightManagementCLI.exe c - Creates a cluster using the name specified in app.config or as command line overrides\nHDInsightManagementCLI.exe c /CleanupOnError:yes - Creates a cluster and cleans up if an error was encountered\nHDInsightManagementCLI.exe d - Deletes the cluster.\nHDInsightManagementCLI.exe l /SubscriptionId:<your-sub-id> - Gets the clusters for the specified subscription id\nHDInsightManagementCLI.exe gsl /SubscriptionId:<your-sub-id> - Gets the list of supported locations for the specified subscription id\nHDInsightManagementCLI.exe gc /SubscriptionId:<your-sub-id> - Gets the subscription capabilities\nHDInsightManagementCLI.exe rdpon - Enables RDP for cluster (windows only)\n```\n\n## TODO (How you can help)\n* Switch to a command line parser NuGet and customize that to use the App.config\n* Add more commands support based on APIs available\n* Add job submission support\n* Update CLI when password retrieval arrives\n* Upload the RDFE based CLI as well\n" }, { "alpha_fraction": 0.5466887354850769, "alphanum_fraction": 0.5568705797195435, "avg_line_length": 42.85877990722656, "blob_id": "8642a3a1b665d437e8e58379451bb7bf907f6e9b", "content_id": "01efe8c92cf38ba6f1323b41b4236fd9a3600514", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 11493, "license_type": "no_license", "max_line_length": 190, "num_lines": 262, "path": "/src/HDInsightClusterLogsDownloader/HDInsightClusterLogsDownloader.cs", "repo_name": "hdinsight/hdinsight-helper-tools", "src_encoding": "UTF-8", "text": "using log4net;\nusing Microsoft.WindowsAzure.Storage;\nusing Microsoft.WindowsAzure.Storage.Auth;\nusing Microsoft.WindowsAzure.Storage.Table;\nusing System;\nusing System.Collections.Generic;\nusing System.Configuration;\nusing System.Diagnostics;\nusing System.Linq;\n\nnamespace HDInsightClusterLogsDownloader\n{\n public enum OperatingSystemType\n {\n Linux,\n Windows\n }\n\n public class HDInsightClusterLogsDownloader\n {\n private static readonly ILog Logger = LogManager.GetLogger(typeof(HDInsightClusterLogsDownloader));\n\n public const int MAX_LOGS = 100000;\n public static TimeSpan timeout = TimeSpan.FromMinutes(15);\n\n static void Main(string[] args)\n {\n bool failure = false;\n try\n {\n string storageAccountName = GetConfig(\"StorageAccountName\");\n string storageAccountKey = GetConfig(\"StorageAccountKey\");\n string storageAccountEndpointSuffix = GetConfig(\"StorageAccountEndpointSuffix\");\n string storageAccountTableNamePrefix = GetConfig(\"storageAccountTableNamePrefix\", false);\n string storageAccountTableName = GetConfig(\"StorageAccountTableName\", false);\n\n var clusterOperatingSystemType = (OperatingSystemType)Enum.Parse(typeof(OperatingSystemType), GetConfig(\"ClusterOperatingSystemType\"));\n\n var credentials = new StorageCredentials(storageAccountName, storageAccountKey);\n var cloudStorageAccount = new CloudStorageAccount(credentials, storageAccountEndpointSuffix, true);\n var cloudTableClient = cloudStorageAccount.CreateCloudTableClient();\n\n CloudTable cloudTable = null;\n if (String.IsNullOrWhiteSpace(storageAccountTableName))\n {\n var cloudTables = cloudTableClient.ListTables(storageAccountTableNamePrefix).Where(t => t.Name.EndsWith(\"hadoopservicelog\", StringComparison.OrdinalIgnoreCase)).ToList();\n Logger.InfoFormat(\"Found '{0}' hadoopservicelog tables:\\r\\n{1}\", cloudTables.Count, \n String.Join(Environment.NewLine, cloudTables.Select(t => t.Name)));\n if (cloudTables.Count == 1)\n {\n storageAccountTableName = cloudTables.First().Name;\n }\n else\n {\n if (cloudTables.Count == 0)\n {\n Logger.Error(\"No tables found with this prefix, try a shorter prefix. Prefix: \" + storageAccountTableNamePrefix);\n }\n else\n {\n Logger.Error(\"More than one table found with same prefix, please pick one and use that name for config: StorageAccountTableName.\");\n }\n Environment.Exit(1);\n }\n }\n\n cloudTable = cloudTableClient.GetTableReference(storageAccountTableName);\n\n var dateTimeMin = DateTimeOffset.UtcNow.AddHours(-2);\n var dateTimeMax = dateTimeMin.AddMinutes(5);\n\n //var dateTimeMin = new DateTime(2015, 8, 19, 8, 55, 0, DateTimeKind.Utc);\n //var dateTimeMax = new DateTime(2015, 8, 19, 9, 10, 0, DateTimeKind.Utc);\n\n var stopwatch = Stopwatch.StartNew();\n GetLogs(clusterOperatingSystemType, cloudTable, dateTimeMin, dateTimeMax);\n\n Logger.InfoFormat(\"Done! Total Time Elapsed: {0} secs\", stopwatch.Elapsed.TotalSeconds);\n }\n catch(Exception ex)\n {\n Logger.Error(\"An error occurred while dowloading cluster logs. Details:\", ex);\n failure = true;\n }\n\n if(Debugger.IsAttached)\n {\n Logger.InfoFormat(\"Press a key to exit...\");\n Console.ReadKey();\n }\n\n if(failure)\n {\n Environment.Exit(-1);\n }\n }\n\n public static string GetConfig(string config, bool throwOnEmpty = true)\n {\n var value = ConfigurationManager.AppSettings.Get(config);\n if(throwOnEmpty && String.IsNullOrWhiteSpace(value))\n {\n throw new ArgumentNullException(config, \n String.Format(\"Please make sure you provide a valid value for key: {0} in App.config\", config));\n }\n Logger.InfoFormat(\"Config: {0}, Value: {1}\", config, value);\n return value;\n }\n\n public static void GetLogs(\n OperatingSystemType clusterOperatingSystemType, CloudTable cloudTable,\n DateTimeOffset dateTimeMin, DateTimeOffset dateTimeMax,\n string roleName = null, string roleInstance = null, string componentName = null,\n string endpointSuffix = \"core.windows.net\")\n {\n //string partitionKeyMin = string.Format(\"0000000000000000000___{0}\", new DateTime(dateTimeMin.Ticks, DateTimeKind.Unspecified).ToBinary().ToString(\"D19\"));\n //string partitionKeyMax = string.Format(\"0000000000000000100___{0}\", new DateTime(dateTimeMax.Ticks, DateTimeKind.Unspecified).ToBinary().ToString(\"D19\"));\n //Logger.InfoFormat(partitionKeyMin);\n //Logger.InfoFormat(partitionKeyMax); \n\n var filters = new List<FilterClause>()\n {\n //new FilterClause(\"PartitionKey\", \"gt\", partitionKeyMin),\n //new FilterClause(\"PartitionKey\", \"lt\", partitionKeyMax),\n new FilterClause(\"Timestamp\", QueryComparisons.GreaterThan, dateTimeMin), //2012-12-23T21:11:32.8339201Z\n new FilterClause(\"Timestamp\", QueryComparisons.LessThan, dateTimeMax)\n //new FilterClause(\"TraceLevel\", QueryComparisons.Equal, \"Error\"),\n //new FilterClause(\"Role\", QueryComparisons.Equal, \"workernode\")\n };\n\n if (!String.IsNullOrEmpty(roleName))\n {\n filters.Add(new FilterClause(\"Role\", \"eq\", roleName));\n }\n\n if (!String.IsNullOrEmpty(roleInstance))\n {\n if (clusterOperatingSystemType == OperatingSystemType.Linux)\n {\n filters.Add(new FilterClause(\"Host\", \"eq\", roleInstance));\n }\n else\n {\n filters.Add(new FilterClause(\"RoleInstance\", \"eq\", roleInstance));\n }\n }\n\n if (!String.IsNullOrEmpty(componentName))\n {\n filters.Add(new FilterClause(\"ComponentName\", \"eq\", componentName));\n }\n\n var query = BuildQuery<HadoopServiceLogEntity>(filters);\n\n Logger.InfoFormat(\"Query = {0}\", query.FilterString);\n\n var logList = RunQuery(clusterOperatingSystemType, cloudTable, query);\n\n HDInsightClusterLogsWriter.Write(clusterOperatingSystemType, cloudTable.Name + \".xlsx\", logList);\n\n Logger.InfoFormat(\"Done - {0}. Rows: {1}\", cloudTable.Name, logList.Count);\n }\n\n public static List<Object> RunQuery(OperatingSystemType clusterOperatingSystemType, CloudTable cloudTable, TableQuery<HadoopServiceLogEntity> query)\n {\n var stopwatch = Stopwatch.StartNew();\n List<Object> logList = new List<Object>();\n try\n {\n EntityResolver<HadoopServiceLogEntity> entityResolver = (pk, rk, ts, props, etag) =>\n {\n\n HadoopServiceLogEntity resolvedEntity = null;\n\n if (clusterOperatingSystemType == OperatingSystemType.Linux)\n {\n resolvedEntity = new LinuxHadoopServiceLogEntity();\n }\n else\n {\n resolvedEntity = new WindowsHadoopServiceLogEntity();\n }\n\n resolvedEntity.PartitionKey = pk;\n resolvedEntity.RowKey = rk;\n resolvedEntity.Timestamp = ts;\n resolvedEntity.ETag = etag;\n resolvedEntity.ReadEntity(props, null);\n\n return resolvedEntity;\n };\n\n TableQuerySegment<HadoopServiceLogEntity> currentSegment = null;\n while (currentSegment == null || currentSegment.ContinuationToken != null)\n {\n var task = cloudTable.ExecuteQuerySegmentedAsync(\n query,\n entityResolver,\n currentSegment != null ? currentSegment.ContinuationToken : null);\n\n task.Wait();\n\n currentSegment = task.Result;\n if (currentSegment != null)\n {\n logList.AddRange(currentSegment.Results as List<HadoopServiceLogEntity>);\n }\n\n Logger.InfoFormat(\"Rows Retreived: {0}, Time Elapsed: {1:0.00} secs\", \n logList.Count, stopwatch.Elapsed.TotalSeconds);\n if (logList.Count >= MAX_LOGS || stopwatch.Elapsed > timeout)\n {\n Logger.ErrorFormat(\"Your query result is either very large or taking too long, aborting the fetch. Rows: {0}\", logList.Count);\n Logger.Error(\"Try reducing the query window or add more filters. Your fetched results will still be available in a excel workbook.\");\n break;\n }\n }\n }\n catch (Exception ex)\n {\n Logger.InfoFormat(ex.ToString());\n throw;\n }\n\n return logList;\n }\n\n public static TableQuery<T> BuildQuery<T>(List<FilterClause> filterClauses)\n {\n var tableQuery = new TableQuery<T>();\n var filters = new List<string>();\n foreach (var filterClause in filterClauses)\n {\n if (filterClause.FilterValue is DateTimeOffset)\n {\n filters.Add(TableQuery.GenerateFilterConditionForDate(filterClause.FilterColumn, filterClause.FilterCondition, (DateTimeOffset)filterClause.FilterValue));\n }\n else\n {\n filters.Add(TableQuery.GenerateFilterCondition(filterClause.FilterColumn, filterClause.FilterCondition, filterClause.FilterValue.ToString()));\n }\n }\n var filterString = \"(\" + String.Join(\") \" + TableOperators.And + \" (\", filters) + \")\";\n return tableQuery.Where(filterString);\n }\n\n public class FilterClause\n {\n public string FilterColumn { get; set; }\n public string FilterCondition { get; set; }\n public object FilterValue { get; set; }\n\n public FilterClause(string filterColumn, string filterCondition, object filterValue)\n {\n this.FilterColumn = filterColumn;\n this.FilterCondition = filterCondition;\n this.FilterValue = filterValue;\n }\n }\n }\n\n}\n" }, { "alpha_fraction": 0.7090619802474976, "alphanum_fraction": 0.7117117047309875, "avg_line_length": 25.20833396911621, "blob_id": "6316f6eea113210491e5c6e79302105325f342b4", "content_id": "a42e7d04e230e417f76fa1c661fb9c15221c4b4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1889, "license_type": "no_license", "max_line_length": 127, "num_lines": 72, "path": "/src/HDInsightManagementCLI/ApplicationUtilities.cs", "repo_name": "hdinsight/hdinsight-helper-tools", "src_encoding": "UTF-8", "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace HDInsightManagementCLI\n{\n\tinternal class ApplicationUtilities\n\t{\n\t\tpublic static bool TryGetArgumentValue(IList<string> args, string argumentKey, out string value)\n\t\t{\t\n\t\t\tvalue = null;\n\n\t\t\tstring matchingArgument;\n\n\t\t\tif (TryFindMatchingArgument(args, argumentKey, out matchingArgument))\n\t\t\t{\n\t\t\t\tint nameStartIndex = matchingArgument.IndexOf(\":\", StringComparison.OrdinalIgnoreCase) + 1;\n\n\t\t\t\tvalue = matchingArgument.Substring(nameStartIndex, matchingArgument.Length - nameStartIndex).Trim();\n\n\t\t\t\tif (string.IsNullOrWhiteSpace(value))\n\t\t\t\t{\n\t\t\t\t\tvalue = null;\n\t\t\t\t\tthrow new ApplicationException(string.Format(\"A value was not provided for the argument {0} \", argumentKey));\n\t\t\t\t}\n\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tpublic static bool HasMatchingArgument(IList<string> args, string argumentKey)\n\t\t{\n\t\t\tstring arg;\n\t\t\treturn TryFindMatchingArgument(args, argumentKey, out arg);\n\t\t}\n\n\t\tprivate static bool TryFindMatchingArgument(IList<string> args, string argumentKey, out string arg)\n\t\t{\n\t\t\targ = null;\n\n\t\t\t//if the key ends with a colon (:) that means it has an associated value, otherwise there should be no additional characters\n\t\t\t//and the key is the entire argument\n\t\t\t//\n\t\t\t\n\t\t\tIEnumerable<string> matchingArgs;\n\t\t\tif(argumentKey.EndsWith(\":\", StringComparison.OrdinalIgnoreCase) )\n\t\t\t{\n\t\t\t\tmatchingArgs = args.Where(a => a.StartsWith(argumentKey, StringComparison.OrdinalIgnoreCase));\n\t\t\t}\n\t\t\telse \n\t\t\t{\n\t\t\t\tmatchingArgs = args.Where(a => a.Equals(argumentKey, StringComparison.OrdinalIgnoreCase));\n\t\t\t}\n\n\t\t\tif (matchingArgs.Count() > 1)\n\t\t\t{\n\t\t\t\tthrow new ApplicationException(string.Format(\"Multiple arguments of name {0} specified\", argumentKey));\n\t\t\t}\n\t\t\telse if (matchingArgs.Count() == 1)\n\t\t\t{\n\t\t\t\targ = matchingArgs.First();\n\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\treturn false;\n\t\t}\n\n\n\t}\n}\n" }, { "alpha_fraction": 0.5320366024971008, "alphanum_fraction": 0.5362899303436279, "avg_line_length": 49.256248474121094, "blob_id": "a4941aad5f832b29eba406281687ae2a3225abc3", "content_id": "4bd4aa7174531b94c190865c3aa189e69dfe2d91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 40204, "license_type": "no_license", "max_line_length": 228, "num_lines": 800, "path": "/src/HDInsightManagementCLI/HDInsightManagementCLI.cs", "repo_name": "hdinsight/hdinsight-helper-tools", "src_encoding": "UTF-8", "text": "using Hyak.Common;\nusing log4net;\nusing Microsoft.Azure;\nusing Microsoft.Azure.Management.HDInsight;\nusing Microsoft.Azure.Management.HDInsight.Models;\nusing Microsoft.Azure.Management.Resources;\nusing Microsoft.Azure.Management.Resources.Models;\nusing Microsoft.IdentityModel.Clients.ActiveDirectory;\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Security.Cryptography.X509Certificates;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace HDInsightManagementCLI\n{\n public static class HDInsightManagementCLI\n {\n private static readonly ILog Logger = LogManager.GetLogger(typeof(HDInsightManagementCLI));\n\n static Stopwatch totalStopWatch;\n\n static TimeSpan pollInterval;\n static TimeSpan timeout;\n\n static Config config = null;\n\n static TokenCloudCredentials tokenCloudCredentials;\n static HDInsightManagementClient hdInsightManagementClient;\n\n public static int Main(string[] args)\n {\n var command = string.Empty;\n try\n {\n if (args.Length == 0)\n {\n Console.Error.WriteLine(\"No input args, you should provide at least one arg\");\n ShowHelp();\n return 9999;\n }\n\n command = args[0];\n if ((command == \"help\") || (command == \"/?\"))\n {\n ShowHelp();\n return -2;\n }\n\n config = new Config(args);\n\n config.PrintRunConfiguration();\n\n if (!config.SilentMode)\n {\n Logger.InfoFormat(\"\\n========== Microsoft HDInsight Management Command Line Tool ==========\\n\");\n Logger.InfoFormat(\"Command: {0}\", command);\n\n Logger.InfoFormat(\"TimeoutPeriodInMinutes: {0}, OperationPollIntervalInSeconds: {1}. Overridable through command line or config file\\n\",\n config.TimeoutPeriodInMinutes, config.OperationPollIntervalInSeconds);\n }\n\n Logger.InfoFormat(\"Getting Azure ActiveDirectory Token from {0}\", config.AzureActiveDirectoryUri);\n\n AuthenticationResult token = null;\n AuthenticationContext ac = new AuthenticationContext(config.AzureActiveDirectoryUri + config.AzureActiveDirectoryTenantId, true);\n\n var promptBehavior = PromptBehavior.Auto;\n\n while (token == null)\n {\n try\n {\n Logger.DebugFormat(\"Acquring token from {0} with behavior: {1}\", config.AzureActiveDirectoryUri + config.AzureActiveDirectoryTenantId, promptBehavior);\n token = ac.AcquireToken(config.AzureManagementUri, config.AzureActiveDirectoryClientId,\n new Uri(config.AzureActiveDirectoryRedirectUri), promptBehavior);\n }\n catch(Exception ex)\n {\n Logger.ErrorFormat(\"An error occurred while acquiring token from Azure Active Directory, will retry. Exception:\\r\\n{0}\", ex.ToString());\n promptBehavior = PromptBehavior.RefreshSession;\n }\n }\n\n Logger.InfoFormat(\"Acquired Azure ActiveDirectory Token for User: {0} with Expiry: {1}\", token.UserInfo.GivenName, token.ExpiresOn);\n tokenCloudCredentials = new TokenCloudCredentials(config.SubscriptionId, token.AccessToken);\n\n Logger.InfoFormat(\"Connecting to AzureResourceManagementUri endpoint at {0}\", config.AzureResourceManagementUri);\n\n\n HttpClient azureResourceProviderHandlerHttpClient = null;\n if (!AzureResourceProviderHandler.HDInsightResourceProviderNamespace.Equals(config.AzureResourceProviderNamespace, StringComparison.OrdinalIgnoreCase))\n {\n azureResourceProviderHandlerHttpClient = new HttpClient(new AzureResourceProviderHandler(config.AzureResourceProviderNamespace));\n hdInsightManagementClient = new HDInsightManagementClient(tokenCloudCredentials,\n new Uri(config.AzureResourceManagementUri), azureResourceProviderHandlerHttpClient);\n }\n else\n {\n hdInsightManagementClient = new HDInsightManagementClient(tokenCloudCredentials, new Uri(config.AzureResourceManagementUri));\n }\n\n pollInterval = TimeSpan.FromSeconds(config.OperationPollIntervalInSeconds);\n timeout = TimeSpan.FromMinutes(config.TimeoutPeriodInMinutes);\n\n totalStopWatch = new Stopwatch();\n totalStopWatch.Start();\n\n switch (command)\n {\n case \"l\":\n case \"list\":\n {\n Logger.InfoFormat(\"SubscriptionId: {0} - Getting cluster information\", config.SubscriptionId);\n var clusters = hdInsightManagementClient.Clusters.List();\n int i = 1;\n foreach (var cluster in clusters)\n {\n Logger.InfoFormat(\"Cluster {0}: {1}\", i++, cluster.Name);\n Logger.InfoFormat(ClusterToString(cluster));\n }\n break;\n }\n case \"ls\":\n case \"listspecific\":\n {\n Logger.InfoFormat(\"Cluster: {0} - Getting details\", config.ClusterDnsName);\n var cluster = hdInsightManagementClient.Clusters.Get(config.ResourceGroupName, config.ClusterDnsName).Cluster;\n Logger.InfoFormat(ClusterToString(cluster));\n\n Logger.InfoFormat(\"Cluster Configurations:\\r\\n{0}\", GetClusterConfigurations());\n break;\n }\n case \"lsrc\":\n case \"listspecificresumecreate\":\n case \"lsrd\":\n case \"listspecificresumedelete\":\n {\n if (command.Contains(\"lsrc\") || command.Contains(\"create\"))\n {\n MonitorCreate(config.ResourceGroupName, config.ClusterDnsName);\n }\n else if (command.Contains(\"lsrd\") || command.Contains(\"delete\"))\n {\n MonitorDelete(config.ResourceGroupName, config.ClusterDnsName);\n }\n break;\n }\n case \"c\":\n case \"create\":\n {\n foreach (var asv in config.AdditionalStorageAccounts)\n {\n if (!asv.Name.EndsWith(\".net\", StringComparison.OrdinalIgnoreCase))\n Logger.InfoFormat(\"WARNING - ASV AccountName: {0} does not seem to have a valid FQDN. \" +\n \"Please ensure that you use the full blob endpoint url else your cluster creation will fail.\",\n asv.Name);\n }\n\n CreateResourceGroup(config.AzureResourceManagementUri, \n config.AzureResourceProviderNamespace, \n config.ResourceGroupName, config.ClusterLocation);\n\n Create(config.SubscriptionId, config.ResourceGroupName, config.ClusterDnsName, config.ClusterLocation, \n config.DefaultStorageAccount, config.ClusterSize, \n config.ClusterUsername, config.ClusterPassword, config.HDInsightVersion,\n config.ClusterType, config.OSType,\n config.AdditionalStorageAccounts, config.SqlAzureMetastores,\n config.VirtualNetworkId, config.SubnetName,\n config.HeadNodeSize, config.WorkerNodeSize, config.ZookeeperSize);\n\n break;\n }\n case \"rs\":\n case \"resize\":\n {\n Resize(config.ResourceGroupName, config.ClusterDnsName, config.ClusterSize);\n break;\n }\n case \"rdpon\":\n {\n EnableRdp(config.ClusterDnsName, config.ClusterLocation,\n config.RdpUsername, config.RdpPassword,\n DateTime.Now.AddDays(int.Parse(config.RdpExpirationInDays)));\n break;\n }\n case \"rdpoff\":\n {\n DisableRdp(config.ClusterDnsName, config.ClusterLocation);\n break;\n }\n case \"d\":\n case \"delete\":\n {\n Delete(config.ResourceGroupName, config.ClusterDnsName);\n break;\n }\n case \"derr\":\n case \"deleteerror\":\n {\n Logger.InfoFormat(\"SubId: {0} - Deleting all clusters in error or unknown state\", config.SubscriptionId);\n var clustersResponse = hdInsightManagementClient.Clusters.List();\n var errorClustersList = new List<Cluster>();\n foreach (var cluster in clustersResponse.Clusters)\n {\n Logger.InfoFormat(\"Found: {0}, State: {1}, CreatedDate: {2}\",\n cluster.Name, cluster.Properties.ClusterState, cluster.Properties.CreatedDate);\n if (cluster.Properties.ProvisioningState == HDInsightClusterProvisioningState.Failed ||\n cluster.Properties.ProvisioningState == HDInsightClusterProvisioningState.Canceled ||\n String.Compare(cluster.Properties.ClusterState, \"Error\", StringComparison.OrdinalIgnoreCase) == 0 ||\n String.Compare(cluster.Properties.ClusterState, \"Unknown\", StringComparison.OrdinalIgnoreCase) == 0)\n {\n errorClustersList.Add(cluster);\n }\n }\n\n Logger.InfoFormat(\"Clusters found: {0}, Clusters in Error/Unknown state: {1}\", clustersResponse.Clusters.Count, errorClustersList.Count);\n\n var deleteCount = 0;\n foreach (var errorCluster in errorClustersList)\n {\n Delete(config.ResourceGroupName, errorCluster.Name);\n deleteCount++;\n }\n\n Logger.InfoFormat(\"Clusters deleted: {0}\", deleteCount);\n\n break;\n }\n case \"dstale\":\n case \"deletestale\":\n case \"dall\":\n case \"deleteall\":\n case \"dallprefix\":\n case \"deleteallprefix\":\n {\n if (!ConfirmOperation(String.Format(\"SubId: {0} - Are you sure you want delete all the clusters (Clusters that were created more than {1} hours ago)? This operation cannot be undone.\",\n config.SubscriptionId, config.DeleteCutoffPeriodInHours)))\n {\n break;\n }\n\n var clustersResponse = hdInsightManagementClient.Clusters.List();\n var deleteClustersList = new List<Cluster>();\n\n var currTime = DateTime.UtcNow;\n var cutoffTime = DateTime.UtcNow.AddHours(-config.DeleteCutoffPeriodInHours);\n Logger.InfoFormat(\n Environment.NewLine + String.Format(\"Current UTC time: {0}, Cut-off time: {1}\", currTime.ToString(), cutoffTime.ToString()) +\n Environment.NewLine + String.Format(\"Total Clusters: {0}\", clustersResponse.Clusters.Count) +\n Environment.NewLine + \"Searching for Clusters...\");\n\n foreach (var cluster in clustersResponse)\n {\n if (cluster.Properties.CreatedDate < cutoffTime)\n {\n Logger.InfoFormat(\"Name: {0}, State: {1}, CreatedDate: {2}\",\n cluster.Name, cluster.Properties.ProvisioningState, cluster.Properties.CreatedDate);\n deleteClustersList.Add(cluster);\n }\n }\n\n Logger.InfoFormat(\"Clusters to be deleted: {0}\", deleteClustersList.Count);\n\n var deleteCount = 0;\n if (deleteClustersList.Count == 0 || !ConfirmOperation())\n {\n break;\n }\n else\n {\n foreach (var deleteCluster in deleteClustersList)\n {\n try\n {\n Delete(config.ResourceGroupName, deleteCluster.Name);\n deleteCount++;\n }\n catch (Exception ex)\n {\n Logger.InfoFormat(\"SubId: {0} - Cluster: {1} - Error encountered during Delete:\\r\\n{2}\",\n config.SubscriptionId, deleteCluster.Name, ex.ToString());\n }\n }\n }\n\n Logger.InfoFormat(\"Clusters deleted: {0}\", deleteCount);\n break;\n }\n case \"gsl\":\n case \"getsupportedlocations\":\n {\n GetSupportedLocations(config.ClusterLocation);\n break;\n }\n case \"gc\":\n case \"getcapabilties\":\n {\n GetCapabilities(config.SubscriptionId);\n break;\n }\n default:\n {\n Logger.InfoFormat(string.Format(\"Command '{0}' is incorrect.\", command));\n ShowHelp();\n throw new Exception();\n }\n }\n Logger.InfoFormat(\"Total time taken for this command ({0}): {1:0.00} secs\", command, totalStopWatch.Elapsed.TotalSeconds);\n totalStopWatch.Stop();\n }\n catch (Exception ex)\n {\n Logger.Error(String.Format(\"Command '{0}' failed. Error Information:\", command ?? \"null\") , ex);\n return -1;\n }\n finally\n {\n if (Debugger.IsAttached && !config.SilentMode)\n {\n Logger.Info(\"Press any key to exit...\");\n Console.ReadKey();\n }\n }\n\n return 0;\n }\n\n private static string GetClusterConfigurations(List<string> clusterConfigurationNames = null)\n {\n var sb = new StringBuilder();\n if (clusterConfigurationNames == null || clusterConfigurationNames.Count == 0)\n {\n clusterConfigurationNames = new List<string>() { \"core-site\" };\n //\"hdfs-site\", \"hive-site\", \"mapred-site\", \"oozie-site\", \"yarn-site\", \"hbase-site\", \"storm-site\"\n }\n\n foreach (var clusterConfigurationName in clusterConfigurationNames)\n {\n sb.AppendFormat(GetClusterConfiguration(clusterConfigurationName));\n }\n return sb.ToString();\n }\n\n private static string GetClusterConfiguration(string clusterConfigurationName)\n {\n var sb = new StringBuilder();\n var clusterConfigurations = hdInsightManagementClient.Clusters.GetClusterConfigurations(\n config.ResourceGroupName, config.ClusterDnsName, clusterConfigurationName);\n\n if (clusterConfigurations.Configuration.Count > 0)\n {\n sb.AppendFormat(\"\\t{0}:\\r\\n\\t\\t{1}\\r\\n\",\n clusterConfigurationName,\n String.Join(Environment.NewLine + \"\\t\\t\", clusterConfigurations.Configuration.Select(\n c => c.Key + \": \" + c.Value)));\n }\n return sb.ToString();\n }\n\n private static string ClusterToString(Cluster cluster)\n {\n var sb = new StringBuilder();\n sb.AppendFormat(\"\\r\\n\\tResourceGroup: {0}\\r\\n\", HDInsightManagementCLIHelpers.GetResourceGroupNameFromClusterId(cluster.Id));\n sb.AppendFormat(\"\\t{0}\\r\\n\", cluster.ToDisplayString().Replace(\"\\n\", \"\\n\\t\"));\n sb.AppendFormat(\"\\tUserClusterTablePrefix: {0}\\r\\n\", HDInsightManagementCLIHelpers.GetUserClusterTablePrefix(cluster));\n return sb.ToString();\n }\n\n private static void Resize(string resourceGroup, string ClusterDnsName, int newSize)\n {\n Logger.InfoFormat(\"Cluster: {0} - Getting cluster information\", ClusterDnsName);\n var clusterGetResponse = hdInsightManagementClient.Clusters.Get(resourceGroup, ClusterDnsName);\n Logger.InfoFormat(clusterGetResponse.ToDisplayString());\n Logger.InfoFormat(\"Resizing - Cluster: {0}, Location: {1}, NewSize: {2}\", ClusterDnsName, resourceGroup, newSize);\n var resizeResponse = hdInsightManagementClient.Clusters.Resize(resourceGroup, ClusterDnsName, newSize);\n Logger.InfoFormat(\"Resizing complete - Getting Updated Cluster Information:\");\n clusterGetResponse = hdInsightManagementClient.Clusters.Get(resourceGroup, ClusterDnsName);\n Logger.InfoFormat(clusterGetResponse.ToDisplayString());\n }\n\n private static void EnableRdp(string resourceGroup, string ClusterDnsName, string rdpUserName, string rdpPassword, DateTime rdpExpiry)\n {\n Logger.InfoFormat(\"Enabling Rdp - ResourceGroup: {0}, Cluster: {1}\", resourceGroup, ClusterDnsName);\n hdInsightManagementClient.Clusters.EnableRdp(resourceGroup, ClusterDnsName, rdpUserName, rdpPassword, rdpExpiry);\n HDInsightManagementCLIHelpers.CreateRdpFile(ClusterDnsName, rdpUserName, rdpPassword);\n }\n\n private static void DisableRdp(string resourceGroup, string ClusterDnsName)\n {\n Logger.InfoFormat(\"Disabling Rdp - ResourceGroup: {0}, Cluster: {1}\", resourceGroup, ClusterDnsName);\n var response = hdInsightManagementClient.Clusters.DisableRdp(resourceGroup, ClusterDnsName);\n }\n\n static bool ConfirmOperation(string message = null)\n {\n if (config.SilentMode)\n return true;\n\n if (message == null)\n message = String.Format(\"Do you wish to continue the current operaton?\");\n Console.Write(message + \" (yes/no): \");\n var input = Console.ReadLine();\n if (string.Compare(input, \"yes\", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(input, \"y\", StringComparison.OrdinalIgnoreCase) == 0)\n {\n return true;\n }\n else\n {\n Logger.InfoFormat(\"Operation aborted\");\n return false;\n }\n }\n\n static void GetSupportedLocations(string location)\n {\n Logger.InfoFormat(\"SubscriptionId: {0} - Getting Supported Locations\", hdInsightManagementClient.Credentials.SubscriptionId);\n\n var capabilities = hdInsightManagementClient.Clusters.GetCapabilities(location);\n\n Logger.InfoFormat(\"Regions:\\r\\n{0}\",\n String.Join(Environment.NewLine, capabilities.Regions.Select(c => c.Key + \":\" + Environment.NewLine + \"\\t\" +\n String.Join(Environment.NewLine + \"\\t\", c.Value.AvailableRegions))));\n }\n\n static void GetCapabilities(string location)\n {\n Logger.InfoFormat(\"SubscriptionId: {0} - Getting Subscription Properties\", hdInsightManagementClient.Credentials.SubscriptionId);\n\n var capabilities = hdInsightManagementClient.Clusters.GetCapabilities(location);\n\n Logger.InfoFormat(\"Features:\\r\\n\\t{0}\",\n String.Join(Environment.NewLine + \"\\t\", capabilities.Features));\n\n Logger.InfoFormat(\"QuotaCapability:\\r\\n\\t{0}\",\n String.Join(Environment.NewLine + \"\\t\", capabilities.QuotaCapability.RegionalQuotas.Select(q => q.ToDisplayString(false))));\n\n Logger.InfoFormat(\"Regions:\\r\\n\\t{0}\",\n String.Join(Environment.NewLine + \"\\t\", capabilities.Regions.Select(c => c.Key + \":\" + Environment.NewLine + \"\\t\\t\" +\n String.Join(Environment.NewLine + \"\\t\\t\", c.Value.AvailableRegions))));\n\n Logger.InfoFormat(\"Versions:\\r\\n\\t{0}\",\n String.Join(Environment.NewLine + \"\\t\", capabilities.Versions.Select(c => c.Key + \":\" + Environment.NewLine + \"\\t\\t\" +\n String.Join(Environment.NewLine + \"\\t\\t\",\n String.Join(Environment.NewLine + \"\\t\\t\", c.Value.AvailableVersions.Select(v => v.DisplayName))))));\n\n Logger.InfoFormat(\"VmSizes:\\r\\n\\t{0}\",\n String.Join(Environment.NewLine + \"\\t\", capabilities.VmSizes.Select(c => c.Key + \":\" + Environment.NewLine + \"\\t\\t\" +\n String.Join(Environment.NewLine + \"\\t\\t\", c.Value.AvailableVmSizes))));\n }\n\n static void CreateResourceGroup(string azureResourceManagementUri, string azureResourceProviderNamespace, string resourceGroupName, string location)\n {\n Logger.InfoFormat(\"Creating Resource Group and registering provider - \" + \n \"ARM Uri: {0}, ResourceProvider: {1}, ResourceGroupName: {2}, Location: {3}\",\n azureResourceManagementUri, azureResourceProviderNamespace, resourceGroupName, location);\n\n var resourceClient = new ResourceManagementClient(tokenCloudCredentials, new Uri(azureResourceManagementUri));\n resourceClient.ResourceGroups.CreateOrUpdate(\n resourceGroupName,\n new ResourceGroup\n {\n Location = location\n });\n\n resourceClient.Providers.Register(azureResourceProviderNamespace);\n }\n\n static void Create(string subscriptionId, string resourceGroupName, string clusterDnsName, string clusterLocation,\n AzureStorageConfig defaultStorageAccount, int clusterSize, string clusterUsername, string clusterPassword,\n string hdInsightVersion,\n string clusterType, string osType,\n List<AzureStorageConfig> additionalStorageAccounts,\n List<SqlAzureConfig> sqlAzureMetaStores,\n string virtualNetworkId = null, string subnetName = null,\n string headNodeSize = null, string workerNodeSize = null, string zookeeperSize = null)\n {\n Logger.InfoFormat(\"ResourceGroup: {0}, Cluster: {1} - Submitting a new cluster deployment request\", resourceGroupName, clusterDnsName);\n\n var clusterCreateParameters = new ClusterCreateParameters()\n {\n ClusterSizeInNodes = clusterSize,\n ClusterType = clusterType,\n DefaultStorageAccountName = defaultStorageAccount.Name,\n DefaultStorageAccountKey = defaultStorageAccount.Key,\n DefaultStorageContainer = defaultStorageAccount.Container,\n Location = clusterLocation,\n Password = clusterPassword,\n UserName = clusterUsername,\n Version = hdInsightVersion,\n OSType = (OSType)Enum.Parse(typeof(OSType), osType.ToString()),\n HeadNodeSize = headNodeSize,\n WorkerNodeSize = workerNodeSize,\n ZookeeperNodeSize = zookeeperSize\n };\n\n if (clusterCreateParameters.OSType == OSType.Linux)\n {\n clusterCreateParameters.SshUserName = config.SshUsername;\n if(!String.IsNullOrWhiteSpace(config.SshPassword))\n {\n clusterCreateParameters.SshPassword = config.SshPassword;\n }\n else if(File.Exists(config.SshPublicKeyFilePath))\n {\n var publicKey = File.ReadAllText(config.SshPublicKeyFilePath);\n Logger.Debug(\"SSH RSA Public Key: \" + Environment.NewLine + publicKey + Environment.NewLine);\n clusterCreateParameters.SshPublicKey = publicKey;\n }\n else if (String.IsNullOrWhiteSpace(config.SshPassword))\n {\n clusterCreateParameters.SshPassword = config.ClusterPassword;\n }\n }\n else\n {\n if (config.AutoEnableRdp)\n {\n clusterCreateParameters.RdpUsername = config.RdpUsername;\n clusterCreateParameters.RdpPassword = config.RdpPassword;\n clusterCreateParameters.RdpAccessExpiry = DateTime.Now.AddDays(int.Parse(config.RdpExpirationInDays));\n }\n }\n\n foreach (var additionalStorageAccount in additionalStorageAccounts)\n {\n clusterCreateParameters.AdditionalStorageAccounts.Add(additionalStorageAccount.Name, additionalStorageAccount.Key);\n }\n\n\n if (!String.IsNullOrEmpty(virtualNetworkId) && !String.IsNullOrEmpty(subnetName))\n {\n clusterCreateParameters.VirtualNetworkId = virtualNetworkId;\n clusterCreateParameters.SubnetName = subnetName;\n }\n\n if (sqlAzureMetaStores != null && sqlAzureMetaStores.Count > 0)\n {\n var hiveMetastore = sqlAzureMetaStores.FirstOrDefault(s => s.Type.Equals(\"HiveMetastore\"));\n if (hiveMetastore != null)\n {\n clusterCreateParameters.HiveMetastore =\n new Metastore(hiveMetastore.Server, hiveMetastore.Database, hiveMetastore.User, hiveMetastore.Password);\n }\n\n var oozieMetastore = sqlAzureMetaStores.FirstOrDefault(s => s.Type.Equals(\"OozieMetastore\"));\n if (oozieMetastore != null)\n {\n clusterCreateParameters.OozieMetastore =\n new Metastore(oozieMetastore.Server, oozieMetastore.Database, oozieMetastore.User, oozieMetastore.Password);\n }\n }\n\n var localStopWatch = Stopwatch.StartNew();\n\n var createTask = hdInsightManagementClient.Clusters.CreateAsync(resourceGroupName, clusterDnsName, clusterCreateParameters);\n Logger.InfoFormat(\"Cluster: {0} - Create cluster request submitted with task id: {1}, task status: {2}\",\n clusterDnsName, createTask.Id, createTask.Status);\n\n Thread.Sleep(pollInterval);\n\n var error = MonitorCreate(resourceGroupName, clusterDnsName, createTask);\n\n if (error)\n {\n if (config.CleanupOnError)\n {\n Logger.InfoFormat(\"{0} - {1}. Submitting a delete request for the failed cluster creation.\", Config.ConfigName.CleanupOnError.ToString(), config.CleanupOnError.ToString());\n Delete(resourceGroupName, clusterDnsName);\n }\n else\n {\n throw new ApplicationException(String.Format(\"Cluster: {0} - Creation unsuccessful\", clusterDnsName));\n }\n }\n else\n {\n if (config.AutoEnableRdp && clusterCreateParameters.OSType == OSType.Windows)\n {\n HDInsightManagementCLIHelpers.CreateRdpFile(clusterDnsName, config.RdpUsername, config.RdpPassword);\n }\n }\n }\n\n static bool MonitorCreate(string resourceGroupName, string ClusterDnsName, Task<ClusterGetResponse> createTask = null)\n {\n bool error = false;\n Cluster cluster = null;\n var localStopWatch = Stopwatch.StartNew();\n do\n {\n if (createTask != null)\n {\n Logger.InfoFormat(\"Cluster: {0} - Create Task Id: {1}, Task Status: {2}, Time: {3:0.00} secs\",\n ClusterDnsName, createTask.Id, createTask.Status, localStopWatch.Elapsed.TotalSeconds);\n\n if (createTask.IsFaulted || createTask.IsCanceled)\n {\n error = true;\n break;\n }\n }\n\n try\n {\n cluster = hdInsightManagementClient.Clusters.Get(resourceGroupName, ClusterDnsName).Cluster;\n }\n catch(CloudException ex)\n {\n if(!ex.Error.Code.Equals(\"ResourceNotFound\", StringComparison.OrdinalIgnoreCase))\n {\n throw;\n }\n }\n\n if (cluster != null)\n {\n Logger.InfoFormat(\"Cluster: {0} - State: {1}, Time: {2:0.00} secs, CRUD Time: {3:0.00} secs\",\n cluster.Name, cluster.Properties.ClusterState,\n localStopWatch.Elapsed.TotalSeconds,\n (DateTime.UtcNow - cluster.Properties.CreatedDate).TotalSeconds);\n\n if (cluster.Properties.ProvisioningState == HDInsightClusterProvisioningState.Failed ||\n cluster.Properties.ProvisioningState == HDInsightClusterProvisioningState.Canceled ||\n String.Compare(cluster.Properties.ClusterState, \"Error\", StringComparison.OrdinalIgnoreCase) == 0 ||\n String.Compare(cluster.Properties.ClusterState, \"Unknown\", StringComparison.OrdinalIgnoreCase) == 0)\n {\n error = true;\n break;\n }\n\n if (cluster.Properties.ProvisioningState == HDInsightClusterProvisioningState.Succeeded ||\n String.Compare(cluster.Properties.ClusterState, \"Running\", StringComparison.OrdinalIgnoreCase) == 0)\n {\n error = false;\n break;\n }\n }\n else\n {\n Logger.InfoFormat(\"Cluster: {0} - State: {1}, Time: {2:0.00} secs\",\n ClusterDnsName, \"ResourceNotFound\", localStopWatch.Elapsed.TotalSeconds);\n }\n\n if (timeout.TotalMinutes > 0)\n {\n var elapsedTime = localStopWatch.Elapsed;\n if (elapsedTime > timeout)\n {\n error = true;\n Logger.InfoFormat(\"Cluster: {0} - Operation timed out. Timeout: {1:0.00} mins, Elapsed Time: {2:0.00} mins. Cluster will be deleted if /CleanupOnError was set\",\n ClusterDnsName, timeout.TotalMinutes, elapsedTime.TotalMinutes);\n break;\n }\n }\n else\n {\n error = false;\n break;\n }\n\n Thread.Sleep(pollInterval);\n }\n while (!error);\n\n if (createTask != null)\n {\n Logger.InfoFormat(\"Task Result:\\r\\n{0}\", createTask.Result.ToDisplayString());\n }\n\n if (cluster != null)\n {\n Logger.InfoFormat(\"Cluster details:\" + Environment.NewLine + ClusterToString(cluster));\n }\n\n if(!error)\n {\n Logger.InfoFormat(\"Cluster: {0} - Created successfully and is ready to use\", cluster.Name);\n Logger.InfoFormat(\"Cluster ConnectivityEndpoints:\\r\\n{0}\",\n String.Join(Environment.NewLine, cluster.Properties.ConnectivityEndpoints.Select(c => c.ToDisplayString(false))));\n }\n return error;\n }\n\n static void Delete(string resourceGroupName, string clusterDnsName)\n {\n var localStopWatch = Stopwatch.StartNew();\n var deleteTask = hdInsightManagementClient.Clusters.DeleteAsync(resourceGroupName, clusterDnsName);\n Logger.InfoFormat(\"Cluster: {0} - Cluster delete request submitted with task id: {1}, status: {2}\",\n clusterDnsName, deleteTask.Id, deleteTask.Status);\n\n bool error = MonitorDelete(resourceGroupName, clusterDnsName);\n\n if (error)\n {\n throw new ApplicationException(String.Format(\"Cluster: {0} - Delete unsucessful\", clusterDnsName));\n }\n }\n\n static bool MonitorDelete(string resourceGroupName, string ClusterDnsName)\n {\n Cluster cluster = null;\n var localStopWatch = new Stopwatch();\n localStopWatch.Start();\n bool error = false;\n try\n {\n do\n {\n cluster = hdInsightManagementClient.Clusters.Get(resourceGroupName, ClusterDnsName).Cluster;\n\n if (cluster != null)\n {\n Logger.InfoFormat(\"Cluster: {0} - State: {1}, Time: {2:0.00} secs\",\n cluster.Name, cluster.Properties.ClusterState, localStopWatch.Elapsed.TotalSeconds);\n\n if (timeout.TotalMinutes > 0)\n {\n var elapsedTime = localStopWatch.Elapsed;\n if (elapsedTime > timeout)\n {\n error = true;\n Logger.InfoFormat(\"Cluster: {0} - Operation timed out. Timeout: {1:0.00} mins, Elapsed Time: {2:0.00} mins.\" + Environment.NewLine, ClusterDnsName, timeout.TotalMinutes, elapsedTime.TotalMinutes);\n break;\n }\n }\n }\n else\n {\n error = false;\n break;\n }\n Thread.Sleep(pollInterval);\n }\n while (!error);\n }\n catch (Exception ex)\n {\n Logger.InfoFormat(ex.ToString());\n if (ex is CloudException && ((CloudException)ex).Error.Code.Equals(\"ResourceNotFound\", StringComparison.OrdinalIgnoreCase))\n {\n Logger.InfoFormat(\"Cluster: {0} - Not found. Delete Successful.\", ClusterDnsName);\n }\n else\n {\n Logger.InfoFormat(\"Cluster: {0} - Delete Unsuccessful.\", ClusterDnsName);\n }\n }\n\n if (cluster != null)\n {\n Logger.InfoFormat(\"Cluster details:\" + Environment.NewLine + ClusterToString(cluster));\n }\n\n return error;\n }\n\n private static void ShowHelp()\n {\n var sb = new StringBuilder();\n sb.AppendLine(Environment.NewLine + \"-\".PadRight(50, '-'));\n sb.AppendLine(\"Microsoft HDInsight Management Tool Help\");\n sb.AppendLine(\"-\".PadRight(50, '-'));\n sb.AppendLine(\"You must provide one of the following as command line arg:\");\n sb.AppendLine(\"c - creates a cluster\");\n sb.AppendLine(\"d - deletes the cluster\");\n sb.AppendLine(\"l - list all the clusters for the specified subscription\");\n sb.AppendLine(\"ls - list a specific cluster's details for the specified subscription and ClusterDnsName\");\n sb.AppendLine(\"lsrc - resume cluster creation monitoring (helpful to resume if you get a timeout or lost track of the create)\");\n sb.AppendLine(\"lsrd - resume cluster deletion monitoring (helpful to resume if you get a timeout or lost track of the delete)\");\n sb.AppendLine(\"gsl - get supported locations for a subcription\");\n sb.AppendLine(\"gc - gets subcription capabilities like supported regions, versions, os types etc\");\n sb.AppendLine(String.Format(\"dall - delete all the clusters based off on cutoff time. \" + \n \"Cutoff time is overridable using {0}\", Config.ConfigName.DeleteCutoffPeriodInHours.ToString()));\n sb.AppendLine(String.Format(\"rdpon, rdponrdfe - enable rdp for a cluster. \" + \n \"RdpUsername, RdpPassword, RdpExpirationInDays are specified using {0}, {1}, {2}\", \n Config.ConfigName.RdpUsername, Config.ConfigName.RdpPassword, Config.ConfigName.RdpExpirationInDays));\n sb.AppendLine(\"Configuration Overrides - Command Line arguments for configuration take precedence over App.config\");\n sb.AppendLine(\"Specifying a configuration override in commandline: /{ConfigurationName}:{ConfigurationValue}\");\n sb.AppendLine(\"Optional/Additional parameters that override the configuration values can be specified in the App.config\");\n sb.AppendLine(\"Overridable Configuration Names:\");\n sb.AppendLine(\"\\t\" + string.Join(Environment.NewLine + \"\\t\", Enum.GetNames(typeof(Config.ConfigName))));\n sb.AppendLine(\"-\".PadRight(50, '-'));\n sb.AppendLine(\"Examples:\");\n sb.AppendLine(\"HDInsightManagementCLI.exe c - Creates a cluster using the name specified in app.config or as command line overrides\");\n sb.AppendLine(\"HDInsightManagementCLI.exe c /CleanupOnError:yes - Creates a cluster and cleans up if an error was encountered\");\n sb.AppendLine(\"HDInsightManagementCLI.exe d - Deletes the cluster.\");\n sb.AppendLine(\"HDInsightManagementCLI.exe l /SubscriptionId:<your-sub-id> - Gets the clusters for the specified subscription id\");\n sb.AppendLine(\"HDInsightManagementCLI.exe gsl /SubscriptionId:<your-sub-id> - Gets the list of supported locations for the specified subscription id\");\n sb.AppendLine(\"HDInsightManagementCLI.exe gc /SubscriptionId:<your-sub-id> - Gets the subscription capabilities\");\n sb.AppendLine(\"HDInsightManagementCLI.exe rdpon - Enables RDP for cluster (windows only)\");\n Logger.Info(sb.ToString());\n }\n }\n}" }, { "alpha_fraction": 0.5511241555213928, "alphanum_fraction": 0.5593352913856506, "avg_line_length": 41.272727966308594, "blob_id": "0f049c9aca3918f4853e89a2dc2b80e19742d403", "content_id": "3d068324e18856762c5cbe22f3246d566e1fe8cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 15347, "license_type": "no_license", "max_line_length": 206, "num_lines": 363, "path": "/src/HDInsightManagementCLI/HDInsightManagementCLIHelpers.cs", "repo_name": "hdinsight/hdinsight-helper-tools", "src_encoding": "UTF-8", "text": "using log4net;\nusing Microsoft.Azure.Management.HDInsight.Models;\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Linq.Expressions;\nusing System.Net.Http;\nusing System.Reflection;\nusing System.Security.Cryptography;\nusing System.Text;\nusing System.Text.RegularExpressions;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace HDInsightManagementCLI\n{\n public static class HDInsightManagementCLIHelpers\n {\n private static readonly ILog Logger = LogManager.GetLogger(typeof(HDInsightManagementCLIHelpers));\n /// <summary>\n /// Regex to validate cluster user password.\n /// Checks for following\n /// - Minimum of 10 characters\n /// - Atleast one upper case character\n /// - Atleast one lower case character\n /// - Atleast one number\n /// - Atleast one non whitespace special character\n /// DONT CHANGE this without corresponding change to the AUX code base.\n /// </summary>\n public const string HDInsightPasswordValidationRegex =\n @\"^.*(?=.{10,})(?=.*[a-z])(?=.*\\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9]).*$\";\n\n public static string GetResourceGroupNameFromClusterId(string clusterId)\n {\n var resourceGroupUriPortion = \"resourceGroups/\";\n var startIndex = clusterId.IndexOf(resourceGroupUriPortion, StringComparison.OrdinalIgnoreCase) + resourceGroupUriPortion.Length;\n var endIndex = clusterId.IndexOf(\"/\", startIndex, StringComparison.OrdinalIgnoreCase);\n\n return clusterId.Substring(startIndex, endIndex - startIndex);\n }\n\n public static string GetResourceGroupName(string subscriptionId, string location, string extensionPrefix = \"hdinsight\")\n {\n string hashedSubId = string.Empty;\n using (SHA256 sha256 = SHA256Managed.Create())\n {\n hashedSubId = Base32NoPaddingEncode(sha256.ComputeHash(UTF8Encoding.UTF8.GetBytes(subscriptionId)));\n }\n\n return string.Format(CultureInfo.InvariantCulture, \"{0}{1}-{2}\", extensionPrefix, hashedSubId, location.Replace(' ', '-'));\n }\n\n private static string Base32NoPaddingEncode(byte[] data)\n {\n const string Base32StandardAlphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567\";\n\n StringBuilder result = new StringBuilder(Math.Max((int)Math.Ceiling(data.Length * 8 / 5.0), 1));\n\n byte[] emptyBuffer = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };\n byte[] workingBuffer = new byte[8];\n\n // Process input 5 bytes at a time\n for (int i = 0; i < data.Length; i += 5)\n {\n int bytes = Math.Min(data.Length - i, 5);\n Array.Copy(emptyBuffer, workingBuffer, emptyBuffer.Length);\n Array.Copy(data, i, workingBuffer, workingBuffer.Length - (bytes + 1), bytes);\n Array.Reverse(workingBuffer);\n ulong val = BitConverter.ToUInt64(workingBuffer, 0);\n\n for (int bitOffset = ((bytes + 1) * 8) - 5; bitOffset > 3; bitOffset -= 5)\n {\n result.Append(Base32StandardAlphabet[(int)((val >> bitOffset) & 0x1f)]);\n }\n }\n\n return result.ToString();\n }\n\n public static void CreateRdpFile(string clusterDnsName, string rdpUsername, string rdpPassword)\n {\n Logger.InfoFormat(\"Creating RDP file...\");\n\n try\n {\n var roleName = \"IsotopeHeadNode\";\n var rdpFileName = clusterDnsName + String.Format(\"_{0}_IN_0.rdp\", roleName);\n var rdpFileContents = new StringBuilder();\n rdpFileContents.AppendLine(String.Format(\"full address:s:{0}.cloudapp.net\", clusterDnsName));\n rdpFileContents.AppendLine(String.Format(\"username:s:{0}\", rdpUsername));\n rdpFileContents.AppendLine(String.Format(\"LoadBalanceInfo:s:Cookie: mstshash={0}#{0}_IN_0\",\n roleName));\n rdpFileContents.AppendLine(String.Format(\"#RdpPassword={0}\", rdpPassword));\n File.WriteAllText(rdpFileName, rdpFileContents.ToString());\n\n Logger.InfoFormat(\"RDP file for Cluster: {0} is available at: {1} (password is available in the file contents).\", clusterDnsName, Path.Combine(Directory.GetCurrentDirectory(), rdpFileName));\n }\n catch (Exception)\n {\n Logger.InfoFormat(\"Unable to create rdp file for cluster: {0}\", clusterDnsName);\n throw;\n }\n }\n\n public static System.Reflection.PropertyInfo GetPropertyInfo<TObj, TProp>(\n this TObj obj,\n Expression<Func<TObj, TProp>> propertyAccessor)\n {\n var memberExpression = propertyAccessor.Body as MemberExpression;\n if (memberExpression != null)\n {\n var propertyInfo = memberExpression.Member as System.Reflection.PropertyInfo;\n if (propertyInfo != null)\n {\n return propertyInfo;\n }\n }\n throw new ArgumentException(\"propertyAccessor\");\n }\n\n public static string ToDisplayString<T>(this T item, bool multiline = true, bool ignoreInheritedProperties = false)\n {\n if (item == null)\n {\n return \"null\";\n }\n\n Type itemType = item.GetType();\n\n ICollection collection = item as ICollection;\n if (collection != null)\n {\n List<string> itemDisplayStrings = new List<string>();\n\n foreach (var obj in collection)\n {\n itemDisplayStrings.Add(ToDisplayString(obj, multiline, ignoreInheritedProperties));\n }\n\n return string.Join(multiline ? \",\" + Environment.NewLine : \", \", itemDisplayStrings);\n }\n else if (itemType.IsEnum)\n {\n if (itemType.GetCustomAttributes(typeof(FlagsAttribute), false).Any())\n {\n return string.Join(\" | \", Enum.GetValues(itemType).Cast<Enum>().Where((item as Enum).HasFlag));\n }\n else\n {\n return item.ToString();\n }\n }\n else if (itemType.GetMethod(\"ToString\", System.Type.EmptyTypes).DeclaringType.Equals(itemType))\n {\n try\n {\n return item.ToString();\n }\n catch (Exception e)\n {\n return string.Format(\"Error({0})\", e.Message);\n }\n }\n\n System.Reflection.BindingFlags bindingFlags =\n System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.ExactBinding | System.Reflection.BindingFlags.GetProperty;\n\n if (ignoreInheritedProperties)\n {\n bindingFlags |= System.Reflection.BindingFlags.DeclaredOnly;\n }\n\n return string.Join(\n multiline ? Environment.NewLine : \" \",\n itemType.GetProperties(bindingFlags)\n .Select(p =>\n {\n string displayString;\n try\n {\n if (p.GetIndexParameters().Length > 0)\n {\n displayString = \"Indexed Property (unavailable)\";\n }\n else\n {\n displayString = ToDisplayString(p.GetValue(item, null), multiline);\n }\n }\n catch (Exception e)\n {\n displayString = string.Format(\"Error({0})\", e.Message);\n }\n return string.Format(\"{0}: {1}\", p.Name, displayString);\n }));\n }\n\n public static KeyValuePair<string, string> GenerateSshKeyPair(string keyName, string keyPassword)\n {\n var privateKeyName = keyName + \".key\";\n if (File.Exists(privateKeyName))\n {\n throw new ApplicationException(\"A Private key already exists with same name, please move it before generating a new one. Name: \" + privateKeyName);\n }\n Logger.InfoFormat(\"Generating a new Ssh key pair. Name: {0}, Passphrase: {1}\", privateKeyName, keyPassword);\n try\n {\n RunExecutable(\"ssh-keygen.exe\", String.Format(\"-t rsa -C {0} -f {1} -N {2}\", keyName, privateKeyName, keyPassword));\n }\n catch (Exception)\n {\n Logger.Error(\"Failed to generate keys, please make sure you are running this executable from Git shell as it uses the ssh-keygen.exe provided by Git. \" +\n \"Alternatively you may place ssh-keygen.exe from PortableGit in the current execution directory.\" + \n Environment.NewLine);\n throw;\n }\n return new KeyValuePair<string, string>(privateKeyName + \".pub\", privateKeyName);\n }\n\n /// <summary>\n /// Blocking executable launch\n /// </summary>\n /// <param name=\"exePath\"></param>\n /// <param name=\"exeArgs\"></param>\n /// <param name=\"workingDir\"></param>\n public static void RunExecutable(string exePath, string exeArgs, string workingDir = null)\n {\n Logger.InfoFormat(\"Running executable - Path: {0}, Args: {1}, WorkingDir: {2}\",\n exePath, exeArgs, workingDir);\n\n ProcessStartInfo startInfo = new ProcessStartInfo();\n startInfo.CreateNoWindow = false;\n startInfo.UseShellExecute = false;\n startInfo.FileName = exePath;\n startInfo.WindowStyle = ProcessWindowStyle.Hidden;\n startInfo.Arguments = exeArgs;\n\n if (!String.IsNullOrWhiteSpace(workingDir))\n {\n startInfo.WorkingDirectory = workingDir;\n }\n\n try\n {\n using (Process exeProcess = Process.Start(startInfo))\n {\n exeProcess.WaitForExit();\n if (exeProcess.ExitCode != 0)\n {\n var message = String.Format(\"Executable returned non-zero exit code. Path: {0}, Code: {1}\",\n exePath, exeProcess.ExitCode);\n throw new ApplicationException(message);\n }\n }\n }\n catch (Exception ex)\n {\n var message = String.Format(\"Executable failed. Path: {0}, Args: {1}, WorkingDir: {2}\",\n exePath, exeArgs, workingDir);\n Logger.Error(message, ex);\n throw new ApplicationException(message, ex);\n }\n\n Logger.InfoFormat(\"Executable run successfully - Path: {0}, Args: {1}, WorkingDir: {2}\",\n exePath, exeArgs, workingDir);\n }\n\n /// <summary>\n /// Non blocking process launch\n /// </summary>\n /// <param name=\"exePath\"></param>\n /// <param name=\"exeArgs\"></param>\n /// <param name=\"workingDir\"></param>\n public static void LaunchProcess(string exePath, string exeArgs, string workingDir = null)\n {\n Logger.InfoFormat(\"Launch Process - Path: {0}, Args: {1}, WorkingDir: {2}\",\n exePath, exeArgs, workingDir);\n\n ProcessStartInfo startInfo = new ProcessStartInfo();\n startInfo.FileName = exePath;\n startInfo.Arguments = exeArgs;\n\n if (!String.IsNullOrWhiteSpace(workingDir))\n {\n startInfo.WorkingDirectory = workingDir;\n }\n\n try\n {\n Process exeProcess = Process.Start(startInfo);\n }\n catch (Exception ex)\n {\n var message = String.Format(\"Launch failed. Path: {0}, Args: {1}, WorkingDir: {2}\",\n exePath, exeArgs, workingDir);\n Logger.Error(message, ex);\n throw new ApplicationException(message, ex);\n }\n\n Logger.InfoFormat(\"Process launched successfully - Path: {0}, Args: {1}, WorkingDir: {2}\",\n exePath, exeArgs, workingDir);\n }\n\n public static string GetUserClusterTablePrefix(Cluster cluster)\n {\n Regex alphaNumRgx = new Regex(\"[^a-zA-Z0-9]\");\n string sanitizedClusterName = alphaNumRgx.Replace(cluster.Name, string.Empty);\n if (sanitizedClusterName.Length > 20)\n {\n sanitizedClusterName = sanitizedClusterName.Substring(0, 20);\n }\n return String.Format(\"u{0}{1}\", sanitizedClusterName, cluster.Properties.CreatedDate.AddMinutes(1).ToString(\"ddMMMyyyyATHH\")).ToLowerInvariant();\n }\n }\n\n public class AzureResourceProviderHandler : DelegatingHandler\n {\n private static readonly ILog Logger = LogManager.GetLogger(typeof(AzureResourceProviderHandler));\n\n public string AzureResourceProviderNamespace {get; set;}\n\n public const string HDInsightResourceProviderNamespace = \"Microsoft.HDInsight\";\n public AzureResourceProviderHandler(string resourceProviderNamespace)\n {\n this.AzureResourceProviderNamespace = resourceProviderNamespace;\n InnerHandler = new HttpClientHandler();\n Logger.InfoFormat(\"AzureResourceProviderHandler initialized with ResourceProviderNamespace: {0}\", this.AzureResourceProviderNamespace);\n }\n\n protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n {\n var originalRequestUri = request.RequestUri;\n\n Logger.InfoFormat(\"Request Uri: {0}\", originalRequestUri);\n\n var newRequestUri =\n new Uri(originalRequestUri.AbsoluteUri.Replace(\n string.Format(\"/{0}/\", HDInsightResourceProviderNamespace),\n string.Format(\"/{0}/\", AzureResourceProviderNamespace)));\n request.RequestUri = newRequestUri;\n\n Logger.InfoFormat(\"Request Uri (NEW): {0}\", newRequestUri);\n\n if (request.Content != null)\n {\n string s = request.Content.ReadAsStringAsync().Result;\n Logger.InfoFormat(\"Request Content:\\r\\n{0}\", s);\n }\n\n return base.SendAsync(request, cancellationToken).ContinueWith(task =>\n {\n var response = task.Result;\n Logger.InfoFormat(\"Response Status code: {0} \", response.StatusCode);\n Logger.InfoFormat(\"Response content: {0}\", response.Content.ReadAsStringAsync().Result);\n return response;\n });\n }\n }\n}\n" }, { "alpha_fraction": 0.793083906173706, "alphanum_fraction": 0.7976190447807312, "avg_line_length": 55.90322494506836, "blob_id": "98861808f4162ab250d19bee3383785f5303cd50", "content_id": "ac9f79dac36ab88bbef28d262ee20c5e52a9f728", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1764, "license_type": "no_license", "max_line_length": 284, "num_lines": 31, "path": "/README.md", "repo_name": "hdinsight/hdinsight-helper-tools", "src_encoding": "UTF-8", "text": "# hdinsight-helper-tools\nScripts and Tools to provide help, pointers and examples for developing with Microsoft HDInsight.\n\n## Build status\n\n[![Build status](https://ci.appveyor.com/api/projects/status/u59hingp65bdsayq?svg=true)](https://ci.appveyor.com/project/rtandonmsft/hdinsight-helper-tools)\n\n## Tools\n\n### HDInsightManagementCLI\nA command line tool to manage (create, list and delete) your Microsoft Azure HDInsight clusters. \nIt is developed using the latest preview SDK that supports deploying both Windows and Linux clusters using Azure Resource Manager.\n\nRead more at [HDInsightClusterLogsDownloader](src/HDInsightManagementCLI)\n\n**[Microsoft.Azure.Management.HDInsight NuGet](https://www.nuget.org/packages/Microsoft.Azure.Management.HDInsight) -** [![NuGet version](https://img.shields.io/nuget/vpre/Microsoft.Azure.Management.HDInsight.svg)](https://www.nuget.org/packages/Microsoft.Azure.Management.HDInsight/)\n\n### HDInsightClusterLogsDownloader\nA command line tool to download the hadoop and other components service logs of your Microsoft Azure HDInsight clusters.\nThese logs are in a table in your storage account that you provided while creating the cluster.\n\nRead more at [HDInsightClusterLogsDownloader](src/HDInsightClusterLogsDownloader)\n\n## Support\nThe tools are provided as-is. You can choose to use it, extend it or copy portions of it. Please log issues in this repository that you may hit, they will be addressed time-permitting.\n\n[![Follow @Ravi_sCythE](https://img.shields.io/badge/Twitter-Follow%20%40Ravi__sCythE-blue.svg)](https://twitter.com/intent/follow?screen_name=Ravi_sCythE)\n\n[![rtandonmsft](https://img.shields.io/badge/LinkedIn-rtandonmsft-blue.svg)](https://www.linkedin.com/in/rtandonmsft)\n\n*More tools coming soon...*\n" } ]
12
hackerbb/KBC-Game-using-python-
https://github.com/hackerbb/KBC-Game-using-python-
30e376aaae75b5306de179264cd519af764d254b
e49e2b29e735e997c7ac6fff26ecb0f448512f32
f28e3fe2de1c69cc4d2c99d790e3ca53e9c5dadd
refs/heads/main
2023-06-03T11:19:21.154641
2021-06-15T07:32:30
2021-06-15T07:32:30
377,074,742
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5311601161956787, "alphanum_fraction": 0.5608820915222168, "avg_line_length": 35.596492767333984, "blob_id": "8ee25c505682cec2b1f91c8087200809806d3203", "content_id": "e433a31ee1a775be2466673777ff04b98b6d6630", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2086, "license_type": "no_license", "max_line_length": 95, "num_lines": 57, "path": "/KBC-Game/kbc.py", "repo_name": "hackerbb/KBC-Game-using-python-", "src_encoding": "UTF-8", "text": "from questions import QUESTIONS\ndef isAnswerCorrect(question, answer):\n return True if question[\"answer\"]==answer else False #remove this\ndef lifeLine(ques):\n return ques['option1'],ques['option'+str(ques['answer'])]\ndef kbc():\n print(\"\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t WELCOME\\n\")\n noq=0\n moneywon=0\n lifeline_use=0\n while (noq<=15):\n noq+=1\n print(\"\\tQuestion \", noq,\" : \" ,QUESTIONS[noq-1][\"name\"],\" \")\n print(f'\\t\\tOptions:')\n print(f'\\t\\t\\tOption 1: {QUESTIONS[noq-1][\"option1\"]}')\n print(f'\\t\\t\\tOption 2: {QUESTIONS[noq-1][\"option2\"]}')\n print(f'\\t\\t\\tOption 3: {QUESTIONS[noq-1][\"option3\"]}')\n print(f'\\t\\t\\tOption 4: {QUESTIONS[noq-1][\"option4\"]}')\n ans = input('Your choice ( 1-4 ) : ')\n if ans==\"lifeline\" and lifeline_use==0:\n op1,op2=lifeLine(QUESTIONS[noq-1])\n print(f'\\t\\tOptions:')\n print(f'\\t\\t\\tOption 1: {op1}')\n c=QUESTIONS[noq-1]['answer']\n print(f'\\t\\t\\tOption {c} : {op2}')\n ans = input('Your choice ( 1-2 ) : ')\n lifeline_use =1\n if ans == \"lifeline\" and lifeline_use == 1:\n print(\"\\t\\t\\t\\t\\tSorry , you can use lifeline only one time\")\n noq-=1\n ans=0\n # check for the input validations\n if ans==\"quit\":\n break;\n a=isAnswerCorrect(QUESTIONS[noq - 1], int(ans))\n if a and ans!=0:\n moneywon+=QUESTIONS[noq-1]['money']\n # print the total money won.\n print(\"\\t\\t\\t\\t\\tTotal money won :\",moneywon)\n # See if the user has crossed a level, print that if yes\n if (noq - 5 == 0):\n print(\"LEVEL INCREASED,\", \"You are Now on level 1\")\n elif (noq - 11 == 0):\n print(\"\\t\\t\\t\\t\\tLEVEL INCREASED\", \"You are Now on level 2\")\n print('\\t\\t\\t\\t\\tCorrect !\\n')\n elif not a:\n if noq<=5:\n moneywon=0\n elif noq<=11:\n moneywon=10,000\n else:\n moneywon=320000\n print(\"\\t\\t\\t\\t\\tIncorrect ! \\n\\t\\t\\t\\t\\tCorect answer is \",QUESTIONS[noq-1][\"answer\"])\n break;\n\n print(\"\\t\\t\\t\\t\\tTotal money won :\",moneywon)\nkbc()\n" } ]
1
zhanglei1949/google-audio-recognition
https://github.com/zhanglei1949/google-audio-recognition
8919512f06228a93ad72afbef07a9d2aa8543276
99576a5ac1d4edff86d9697e8dbac4ecadbf8b67
3a421769c77f2d4a9dc82ebb0ce617dd478a3719
refs/heads/master
2021-09-03T13:42:07.219252
2018-01-09T13:38:13
2018-01-09T13:38:13
116,820,394
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7692307829856873, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 38, "blob_id": "6cee207955cefbed8564ebae66826b3fe0c80bfa", "content_id": "f76d5d4361d773558ccbffb00b09e86c00abf808", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 39, "license_type": "no_license", "max_line_length": 38, "num_lines": 1, "path": "/README.md", "repo_name": "zhanglei1949/google-audio-recognition", "src_encoding": "UTF-8", "text": "# Example file for google sr API usage\n" }, { "alpha_fraction": 0.7427536249160767, "alphanum_fraction": 0.7445651888847351, "avg_line_length": 29.66666603088379, "blob_id": "6bf55c45a8bb33857b453bc4ad4f827f0ef2693e", "content_id": "a6724669f9a3ff93e2b936e64c8c463b82ba104b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 552, "license_type": "no_license", "max_line_length": 108, "num_lines": 18, "path": "/test.py", "repo_name": "zhanglei1949/google-audio-recognition", "src_encoding": "UTF-8", "text": "import speech_recognition as sr\nimport wave\nimport argparse\nr = sr.Recognizer()\n\nparser = argparse.ArgumentParser(description=None)\nparser.add_argument('--in', type=str,dest=\"input\",required=True, help=\"the file you want to be recognized.\")\n#audio = wave.open(wave_file, 'r')\nargs = parser.parse_args()\nwith sr.AudioFile(args.input) as source:\n\taudio = r.record(source)\n\ntry:\n\tprint(\"Predicted: \"+ r.recognize_google(audio))\nexcept sr.UnknownValueError:\n\tprint(\"Could not understand\")\nexcept sr.RequestError as e:\n\tprint(\"Reuqest error {0}\".format(e))\n" } ]
2
yjhong89/ITS
https://github.com/yjhong89/ITS
4fce1d25b2653d5053ea4cd3780a6d94d3b849fd
d40980eeda1f7434026fb8b4d4f3d45fd4e84dbf
5211d426390b7ebb02c754d473d7aae219737b21
refs/heads/master
2021-09-01T13:54:35.215388
2017-12-27T09:30:55
2017-12-27T09:30:55
110,205,059
0
0
null
2017-11-10T05:04:21
2017-11-10T05:04:24
2017-12-15T06:04:11
Python
[ { "alpha_fraction": 0.5444400906562805, "alphanum_fraction": 0.5492976307868958, "avg_line_length": 35.61538314819336, "blob_id": "b3f9a8eec2d4f441876c46accd1184a99e65c2f5", "content_id": "d377329b653e56548f976fe28cef24a66f059020", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7617, "license_type": "no_license", "max_line_length": 170, "num_lines": 208, "path": "/DQN/agent.py", "repo_name": "yjhong89/ITS", "src_encoding": "UTF-8", "text": "import numpy as np\nimport tensorflow as tf\nfrom tqdm import tqdm\n\nimport os \nfrom logger import *\n\nfrom dqn import *\nfrom environment import *\nfrom replay_memory import *\n\nclass Agent(object):\n def __init__(self, args, sess):\n self.args = args\n self.sess = sess\n self.dqn = DQN(self.args, self.sess, self.memory, self.env)\n\n self.saver = tf.train.Saver()\n self.logger = Logger(os.path.join(self.args.dqn_log_dir, self.model_dir))\n\n print('Trainalbe_variables of DKVMNAgent')\n for i in tf.trainable_variables():\n if \"dkvmn\" not in i.op.name:\n print(i.op.name)\n #self.sess.run(tf.initialize_variables([i]))\n\n self.sess.run(tf.global_variables_initializer())\n\n self.dqn.update_target_network()\n\n\n def train(self):\n print('Agent is training')\n self.episode_count = 0\n best_reward = 0\n self.episode_reward = 0\n episode_rewards = []\n\n print('===== Start to make random memory =====')\n self.reset_episode()\n for self.step in tqdm(range(1, self.args.max_step+1), ncols=70, initial=0):\n action = self.select_action()\n\n next_state, reward, terminal = self.env.act(action)\n self.memory.add(action, reward, terminal, next_state)\n \n self.episode_reward += reward \n if terminal:\n self.episode_count += 1\n episode_rewards.append(self.episode_reward)\n if self.episode_reward > best_reward:\n best_reward = self.episode_reward\n self.logger.log_scalar(tag='reward', value=self.episode_reward, step=self.step)\n self.reset_episode()\n\n if self.step >= self.args.training_start_step:\n if self.step == self.args.training_start_step:\n print(\"===== Start to update the network =====\")\n\n if self.step % self.args.train_interval == 0:\n loss, _ = self.dqn.train_network()\n\n if self.step % self.args.copy_interval == 0:\n self.dqn.update_target_network()\n\n if self.step % self.args.save_interval == 0:\n self.save()\n\n if self.step % self.args.show_interval == 0:\n avg_r = np.mean(episode_rewards)\n max_r = np.max(episode_rewards)\n min_r = np.min(episode_rewards)\n if max_r > best_reward:\n best_reward = max_r\n print('\\n[recent %d episodes] avg_r: %.4f, max_r: %d, min_r: %d // Best: %d' % (len(episode_rewards), avg_r, max_r, min_r, best_reward))\n episode_rewards = []\n\n def play(self, num_episode=10, load=True):\n if load:\n if not self.load():\n exit()\n best_reward = 0\n for episode in range(num_episode):\n self.reset_episode()\n current_reward = 0\n\n terminal = False\n while not terminal:\n action = self.select_action()\n next_state, reward, terminal = self.env.act(action)\n self.process_state(next_state)\n\n current_reward += reward\n if terminal:\n break\n\n if current_reward > best_reward:\n best_reward = current_reward\n print('<%d> Current reward: %d' % (episode, current_reward))\n print('='*30)\n print('Best reward : %d' % (best_reward))\n\n\n def baseline(self, num_episode=1000, load=True):\n #if load:\n # if not self.load():\n # exit()\n self.episode_count = 1\n self.episode_reward = 0\n best_reward = 0\n for episode in range(num_episode):\n self.reset_episode()\n current_reward = 0\n\n terminal = False\n while not terminal:\n action, prob = self.env.baseline_act()\n print(action, prob)\n _, reward, terminal = self.env.act(action, prob[0])\n self.episode_reward += reward\n \n if terminal:\n self.episode_count += 1\n break\n\n if current_reward > best_reward:\n best_reward = current_reward\n print('<%d> Current reward: %d' % (episode, current_reward))\n print('='*30)\n print('Best reward : %d' % (best_reward))\n\n def select_action(self):\n if self.args.dqn_train:\n self.eps = np.max([self.args.eps_min, self.args.eps_init - (self.args.eps_init - self.args.eps_min)*(float(self.step)/float(self.args.max_exploration_step))])\n elif self.args.dqn_test:\n self.eps = self.args.eps_test\n\n if np.random.rand() < self.eps:\n action = self.env.random_action()\n print('\\nRandom action %d' % action)\n else:\n q = self.dqn.predict_Q_value(np.squeeze(self.env.value_matrix))[0]\n action = np.argmax(q)\n print('\\nQ value %s and action %d' % (q,action))\n return action \n\n def write_log(self, episode_count, episode_reward, case=None):\n logdir = './' + case + '_train.csv'\n if not os.path.exists(logdir):\n train_log = open(logdir, 'w')\n train_log.write('episode\\t, total reward\\n')\n else:\n train_log = open(logdir, 'a')\n train_log.write(str(episode_count) + '\\t' + str(episode_reward) +'\\n')\n \n @property\n def model_dir(self):\n return '{}_{}batch'.format(self.args.env_name, self.args.batch_size_dqn)\n \n \n def save(self):\n checkpoint_dir = os.path.join(self.args.dqn_checkpoint_dir, self.model_dir)\n if not os.path.exists(checkpoint_dir):\n os.mkdir(checkpoint_dir)\n self.saver.save(self.sess, os.path.join(checkpoint_dir, str(self.step)))\n print('*** Save at %d steps' % self.step)\n\n def load(self):\n print('Loading checkpoint ...')\n checkpoint_dir = os.path.join(self.args.dqn_checkpoint_dir, self.model_dir)\n checkpoint_state = tf.train.get_checkpoint_state(checkpoint_dir)\n if checkpoint_state and checkpoint_state.model_checkpoint_path:\n checkpoint_model = os.path.basename(checkpoint_state.model_checkpoint_path)\n self.saver.restore(self.sess, checkpoint_state.model_checkpoint_path)\n print('Success to laod %s' % checkpoint_model)\n return True\n else:\n print('Failed to find a checkpoint')\n return False\n\nclass SimpleAgent(Agent):\n def __init__(self, args, sess):\n self.env = SimpleEnvironment(args)\n self.memory = SimpleMemory(args, self.env.state_shape)\n super(SimpleAgent, self).__init__(args, sess)\n\n def reset_episode(self):\n self.state = self.env.new_episode()\n\n def process_state(self, next_state):\n self.state = next_state\n\n\nclass DKVMNAgent(Agent):\n def __init__(self, args, sess, dkvmn):\n print('Initializing AGENT')\n\n self.env = DKVMNEnvironment(args, sess, dkvmn)\n self.memory = DKVMNMemory(args, self.env.state_shape)\n super(DKVMNAgent, self).__init__(args, sess)\n dkvmn.load()\n\n def reset_episode(self):\n self.env.new_episode()\n self.write_log(self.episode_count, self.episode_reward, case=self.args.case)\n self.env.episode_step = 0\n print('Episode rewards :%3.4f' % self.episode_reward)\n self.episode_reward = 0\n\n" }, { "alpha_fraction": 0.6187499761581421, "alphanum_fraction": 0.6968749761581421, "avg_line_length": 31, "blob_id": "1dca9e772d86b1640c530e4012ca9448e013c1de", "content_id": "447bd2ba1edddaf189956d9f80d45f2887137242", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 320, "license_type": "no_license", "max_line_length": 73, "num_lines": 10, "path": "/DKVMN/README.md", "repo_name": "yjhong89/ITS", "src_encoding": "UTF-8", "text": "# DKVMN\nDynamic Key-Value Memory Networks for Knowledge Tracing\n\nReference\n---------\n> ##### Paper\n>> 1. Dynamic Key Valuy Memory Network : https://arxiv.org/abs/1611.08108\n>> 2. Deep Knowledge Tracing : https://arxiv.org/abs/1506.05908\n> ##### Code\n>> 1. https://github.com/jennyzhang0215/DKVMN (Implemented in MXNET)\n" }, { "alpha_fraction": 0.5894561409950256, "alphanum_fraction": 0.5993410348892212, "avg_line_length": 50.534149169921875, "blob_id": "ba1a11b9afd0158259a825d4491216c4a0484e39", "content_id": "05adeaf13eaeefd11d881ec8b8c298428c667b17", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 29439, "license_type": "no_license", "max_line_length": 324, "num_lines": 571, "path": "/DKVMN/model.py", "repo_name": "yjhong89/ITS", "src_encoding": "UTF-8", "text": "import numpy as np\nimport os, time\nimport tensorflow as tf\nimport operations\nimport shutil\nfrom memory import DKVMN\nfrom sklearn import metrics\n\n\n\nclass DKVMNModel():\n def __init__(self, args, sess, name='KT'):\n\n self.args = args\n self.name = name\n self.sess = sess\n #self.batch_size = args.batch_size\n\n tf.set_random_seed(224)\n\n self.init_model()\n self.init_total_prediction_probability()\n \n def sampling_a_given_q(self, q, value_matrix):\n q_embed = self.embedding_q(q)\n correlation_weight = self.memory.attention(q_embed)\n\n _, _, _, pred_prob = self.inference(q_embed, correlation_weight, value_matrix, reuse_flag = True)\n #pred_prob[tf.where(tf.less(pred_prob, 0.3))].assign(0.3)\n #idx = tf.gather_nd(pred_prob, tf.where(tf.less(pred_prob, 0.3)))\n #pred_prob = tf.assign(idx,tf.constant(0.3))\n pred_prob = tf.clip_by_value(pred_prob, 0.3, 1.0)\n\n #pred_prob = tf.minimum(pred_prob, 0.3)\n threshold = tf.random_uniform(pred_prob.shape)\n\n a = tf.cast(tf.less(threshold, pred_prob), tf.int32)\n qa = q + tf.multiply(a, self.args.n_questions)[0]\n\n return qa \n\n def inference(self, q_embed, correlation_weight, value_matrix, reuse_flag):\n read_content = self.memory.value.read(value_matrix, correlation_weight)\n\n ##### ADD new FC layer for q_embedding. There is an layer in MXnet implementation\n q_embed_content_logit = operations.linear(q_embed, 50, name='input_embed_content', reuse=reuse_flag)\n q_embed_content = tf.tanh(q_embed_content_logit)\n\n mastery_level_prior_difficulty = tf.concat([read_content, q_embed_content], 1)\n #mastery_level_prior_difficulty = tf.concat([read_content, q_embed], 1)\n\n # f_t\n summary_logit = operations.linear(mastery_level_prior_difficulty, self.args.final_fc_dim, name='Summary_Vector', reuse=reuse_flag)\n if self.args.summary_activation == 'tanh':\n summary_vector = tf.tanh(summary_logit)\n elif self.args.summary_activation == 'sigmoid':\n summary_vector = tf.sigmoid(summary_logit)\n elif self.args.summary_activation == 'relu':\n summary_vector = tf.nn.relu(summary_logit)\n\n #summary_vector = tf.sigmoid(operations.linear(mastery_level_prior_difficulty, self.args.final_fc_dim, name='Summary_Vector', reuse=reuse_flag))\n #summary_vector = tf.tanh(operations.linear(mastery_level_prior_difficulty, self.args.final_fc_dim, name='Summary_Vector', reuse=reuse_flag))\n # p_t\n pred_logits = operations.linear(summary_vector, 1, name='Prediction', reuse=reuse_flag)\n\n pred_prob = tf.sigmoid(pred_logits)\n\n return read_content, summary_vector, pred_logits, pred_prob\n\n def init_total_prediction_probability(self):\n self.total_q_data = tf.placeholder(tf.int32, [self.args.n_questions], name='total_q_data') \n self.total_value_matrix = tf.placeholder(tf.float32, [self.args.memory_size,self.args.memory_value_state_dim], name='total_value_matrix')\n\n total_q_data = tf.constant(np.arange(1,self.args.n_questions+1))\n q_embeds = self.embedding_q(total_q_data)\n correlation_weight = self.memory.attention(q_embeds)\n \n stacked_total_value_matrix = tf.tile(tf.expand_dims(self.total_value_matrix, 0), tf.stack([self.args.n_questions, 1, 1]))\n _, _, _, self.total_pred_probs = self.inference(q_embeds, correlation_weight, stacked_total_value_matrix, True)\n\n \n def init_memory(self):\n with tf.variable_scope('Memory'):\n init_memory_key = tf.get_variable('key', [self.args.memory_size, self.args.memory_key_state_dim], \\\n initializer=tf.random_normal_initializer(stddev=0.1))\n #initializer=tf.truncated_normal_initializer(stddev=0.1))\n self.init_memory_value = tf.get_variable('value', [self.args.memory_size,self.args.memory_value_state_dim], \\\n initializer=tf.random_normal_initializer(stddev=0.1))\n #initializer=tf.truncated_normal_initializer(stddev=0.1))\n #initializer=tf.random_uniform_initializer(minval=0.5, maxval=1.0))\n \n # Broadcast memory value tensor to match [batch size, memory size, memory state dim]\n # First expand dim at axis 0 so that makes 'batch size' axis and tile it along 'batch size' axis\n # tf.tile(inputs, multiples) : multiples length must be thes saame as the number of dimensions in input\n # tf.stack takes a list and convert each element to a tensor\n stacked_init_memory_value = tf.tile(tf.expand_dims(self.init_memory_value, 0), tf.stack([self.args.batch_size, 1, 1]))\n \n return DKVMN(self.args.memory_size, self.args.memory_key_state_dim, \\\n self.args.memory_value_state_dim, init_memory_key=init_memory_key, init_memory_value=stacked_init_memory_value, args=self.args, name='DKVMN')\n\n def init_embedding_mtx(self):\n # Embedding to [batch size, seq_len, memory_state_dim(d_k or d_v)]\n with tf.variable_scope('Embedding'):\n # A\n self.q_embed_mtx = tf.get_variable('q_embed', [self.args.n_questions+1, self.args.memory_key_state_dim],\\\n initializer=tf.random_normal_initializer(stddev=0.1))\n #initializer=tf.truncated_normal_initializer(stddev=0.1))\n # B\n self.qa_embed_mtx = tf.get_variable('qa_embed', [2*self.args.n_questions+1, self.args.memory_value_state_dim], initializer=tf.random_normal_initializer(stddev=0.1)) \n #self.qa_embed_mtx = tf.get_variable('qa_embed', [2*self.args.n_questions+1, self.args.memory_value_state_dim], initializer=tf.truncated_normal_initializer(stddev=0.1)) \n \n\n def embedding_q(self, q):\n return tf.nn.embedding_lookup(self.q_embed_mtx, q)\n\n def embedding_qa(self, qa):\n return tf.nn.embedding_lookup(self.qa_embed_mtx, qa)\n \n\n def calculate_knowledge_growth(self, value_matrix, correlation_weight, qa_embed, read_content, summary, pred_prob):\n if self.args.knowledge_growth == 'origin': \n return qa_embed\n \n elif self.args.knowledge_growth == 'value_matrix':\n value_matrix_reshaped = tf.reshape(value_matrix, [self.args.batch_size, -1])\n return tf.concat([value_matrix_reshaped, qa_embed], 1)\n\n elif self.args.knowledge_growth == 'read_content':\n read_content_reshaped = tf.reshape(read_content, [self.args.batch_size, -1])\n return tf.concat([read_content_reshaped, qa_embed], 1)\n\n elif self.args.knowledge_growth == 'summary':\n summary_reshaped = tf.reshape(summary, [self.args.batch_size, -1])\n return tf.concat([summary_reshaped, qa_embed], 1)\n \n elif self.args.knowledge_growth == 'pred_prob':\n pred_prob_reshaped = tf.reshape(pred_prob, [self.args.batch_size, -1])\n return tf.concat([pred_prob_reshaped, qa_embed], 1)\n\n def extract_a_from_qa(self, qa):\n return tf.cast(tf.greater(qa, tf.constant(self.args.n_questions)), tf.float32)\n\n def init_model(self):\n # 'seq_len' means question sequences\n self.q_data_seq = tf.placeholder(tf.int32, [self.args.batch_size, self.args.seq_len], name='q_data_seq') \n self.qa_data_seq = tf.placeholder(tf.int32, [self.args.batch_size, self.args.seq_len], name='qa_data')\n self.target_seq = tf.placeholder(tf.float32, [self.args.batch_size, self.args.seq_len], name='target')\n\n self.memory = self.init_memory()\n self.init_embedding_mtx()\n \n slice_q_data = tf.split(self.q_data_seq, self.args.seq_len, 1) \n slice_qa_data = tf.split(self.qa_data_seq, self.args.seq_len, 1) \n\n \n prediction = list()\n reuse_flag = False\n\n #self.prev_value_memory = self.memory.memory_value\n \n # Logics\n for i in range(self.args.seq_len):\n # To reuse linear vectors\n if i != 0:\n reuse_flag = True\n\n q = tf.squeeze(slice_q_data[i], 1)\n qa = tf.squeeze(slice_qa_data[i], 1)\n a = self.extract_a_from_qa(qa)\n\n q_embed = self.embedding_q(q)\n qa_embed = self.embedding_qa(qa)\n\n correlation_weight = self.memory.attention(q_embed)\n \n prev_read_content, prev_summary, prev_pred_logit, prev_pred_prob = self.inference(q_embed, correlation_weight, self.memory.memory_value, reuse_flag)\n prediction.append(prev_pred_logit)\n\n knowledge_growth = self.calculate_knowledge_growth(self.memory.memory_value, correlation_weight, qa_embed, prev_read_content, prev_summary, prev_pred_prob)\n self.memory.memory_value = self.memory.value.write_given_a(self.memory.memory_value, correlation_weight, knowledge_growth, a, reuse_flag)\n #self.memory.memory_value = self.memory.value.write(self.memory.memory_value, correlation_weight, qa_embed, knowledge_growth, reuse_flag)\n\n # reward \n #self.value_memory_difference = tf.reduce_sum(self.memory.memory_value - self.prev_value_memory)\n #self.next_state = self.memory.memory_value \n\n # 'prediction' : seq_len length list of [batch size ,1], make it [batch size, seq_len] tensor\n # tf.stack convert to [batch size, seq_len, 1]\n pred_logits = tf.reshape(tf.stack(prediction, axis=1), [self.args.batch_size, self.args.seq_len]) \n\n # Define loss : standard cross entropy loss, need to ignore '-1' label example\n # Make target/label 1-d array\n target_1d = tf.reshape(self.target_seq, [-1])\n pred_logits_1d = tf.reshape(pred_logits, [-1])\n index = tf.where(tf.not_equal(target_1d, tf.constant(-1., dtype=tf.float32)))\n # tf.gather(params, indices) : Gather slices from params according to indices\n filtered_target = tf.gather(target_1d, index)\n filtered_logits = tf.gather(pred_logits_1d, index)\n self.loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=filtered_logits, labels=filtered_target))\n #self.loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=filtered_logits, labels=filtered_target))\n self.pred = tf.sigmoid(pred_logits)\n\n # Optimizer : SGD + MOMENTUM with learning rate decay\n self.global_step = tf.Variable(0, trainable=False)\n self.lr = tf.placeholder(tf.float32, [], name='learning_rate')\n #self.lr_decay = tf.train.exponential_decay(self.args.initial_lr, global_step=global_step, decay_steps=10000, decay_rate=0.667, staircase=True)\n self.learning_rate = tf.train.exponential_decay(self.args.initial_lr, global_step=self.global_step, decay_steps=self.args.anneal_interval*(tf.shape(self.q_data_seq)[0] // self.args.batch_size), decay_rate=0.667, staircase=True)\n# self.learning_rate = tf.maximum(lr, self.args.lr_lowerbound)\n optimizer = tf.train.MomentumOptimizer(self.lr, self.args.momentum)\n #optimizer = tf.train.MomentumOptimizer(self.learning_rate, momentum)\n grads, vrbs = zip(*optimizer.compute_gradients(self.loss))\n ## grad, _ = tf.clip_by_global_norm(grads, self.args.maxgradnorm)\n self.grads = grads\n #print('\\nGrad')\n #print(len(grads))\n #for i in range(len(grads)):\n #print(tf.shape(grads[i][0]))\n #self.global_norm = tf.global_norm(grads)\n grad, self.global_norm = tf.clip_by_global_norm(grads, self.args.maxgradnorm)\n #grad, _ = tf.clip_by_global_norm(grads, self.args.maxgradnorm, use_norm = self.global_norm)\n \n self.train_op = optimizer.apply_gradients(list(zip(grad, vrbs)), global_step=self.global_step)\n# grad_clip = [(tf.clip_by_value(grad, -self.args.maxgradnorm, self.args.maxgradnorm), var) for grad, var in grads]\n self.tr_vrbs = tf.trainable_variables()\n for i in self.tr_vrbs:\n print(i.name)\n print(i.shape)\n\n self.saver = tf.train.Saver()\n print('Finish init_model')\n\n\n def train(self, train_q_data, train_qa_data, valid_q_data, valid_qa_data):\n #np.random.seed(224)\n # q_data, qa_data : [samples, seq_len]\n\n training_step = train_q_data.shape[0] // self.args.batch_size\n self.sess.run(tf.global_variables_initializer())\n '''\n value_mem = self.init_memory_value.eval()\n print(np.sum(value_mem))\n\n for i in self.tr_vrbs:\n print(i.name)\n print(i.shape)\n print(np.sum(i.eval()))\n '''\n \n if self.args.show:\n from utils import ProgressBar\n bar = ProgressBar(label, max=training_step)\n\n self.train_count = 0\n if self.args.init_from:\n if self.load():\n print('Checkpoint_loaded')\n else:\n print('No checkpoint')\n else:\n if os.path.exists(os.path.join(self.args.dkvmn_checkpoint_dir, self.model_dir)):\n try:\n shutil.rmtree(os.path.join(self.args.dkvmn_checkpoint_dir, self.model_dir))\n shutil.rmtree(os.path.join(self.args.dkvmn_log_dir, self.model_dir+'.csv'))\n except(FileNotFoundError, IOError) as e:\n print('[Delete Error] %s - %s' % (e.filename, e.strerror))\n \n best_valid_auc = 0\n #print(self.args.seq_len)\n\n # Training\n for epoch in range(0, self.args.num_epochs):\n shuffle_index = np.random.permutation(train_q_data.shape[0])\n q_data_shuffled = train_q_data[shuffle_index, :]\n qa_data_shuffled = train_qa_data[shuffle_index, :]\n\n if self.args.show:\n bar.next()\n\n pred_list = list()\n target_list = list() \n epoch_loss = 0\n learning_rate = tf.train.exponential_decay(self.args.initial_lr, global_step=self.global_step, decay_steps=self.args.anneal_interval*training_step, decay_rate=0.667, staircase=True)\n lr = learning_rate.eval()\n #print('LR %f' % lr )\n #print('Epoch %d starts with learning rate : %3.5f' % (epoch+1, self.sess.run(learning_rate)))\n for steps in range(training_step):\n # [batch size, seq_len]\n q_batch_seq = q_data_shuffled[steps*self.args.batch_size:(steps+1)*self.args.batch_size, :]\n qa_batch_seq = qa_data_shuffled[steps*self.args.batch_size:(steps+1)*self.args.batch_size, :]\n \n # qa : exercise index + answer(0 or 1)*exercies_number\n # right : 1, wrong : 0, padding : -1\n target = qa_batch_seq[:,:]\n # Make integer type to calculate target\n target = target.astype(np.int)\n target_batch = (target - 1) // self.args.n_questions \n target_batch = target_batch.astype(np.float)\n\n feed_dict = {self.q_data_seq:q_batch_seq, self.qa_data_seq:qa_batch_seq, self.target_seq:target_batch, self.lr:self.args.initial_lr}\n #self.lr:self.sess.run(learning_rate)\n #loss_, pred_, _, = self.sess.run([self.loss, self.pred, self.train_op], feed_dict=feed_dict)\n loss_, pred_, _, global_norm, grads, _lr = self.sess.run([self.loss, self.pred, self.train_op, self.global_norm, self.grads, self.learning_rate], feed_dict=feed_dict)\n #print('Global norm %f' % global_norm)\n #print(grads)\n #print('Legnth of global variables : %d' % len(grads))\n\n #print('LR %f %f' % (lr, _lr))\n #print(len(grads[0])) # 20\n #print(len(grads[0][0])) # 50\n\n #print(np.squre(grads[0]))\n '''\n globbal_norm = 0\n for i in range(len(grads)):\n print(i)\n print(np.sum(np.square(grads[i])))\n global_norm += np.sum(np.square(grads[i]))\n print(np.sqrt(global_norm))\n '''\n # Get right answer index\n # Make [batch size * seq_len, 1]\n right_target = np.asarray(target_batch).reshape(-1,1)\n right_pred = np.asarray(pred_).reshape(-1,1)\n # np.flatnonzero returns indices which is nonzero, convert it list \n right_index = np.flatnonzero(right_target != -1.).tolist()\n #print(len(right_index)/self.args.batch_size)\n # Number of 'training_step' elements list with [batch size * seq_len, ]\n pred_list.append(right_pred[right_index])\n target_list.append(right_target[right_index])\n\n epoch_loss += loss_\n #print('Epoch %d/%d, steps %d/%d, loss : %3.5f' % (epoch+1, self.args.num_epochs, steps+1, training_step, loss_))\n \n\n if self.args.show:\n bar.finish() \n \n all_pred = np.concatenate(pred_list, axis=0)\n all_target = np.concatenate(target_list, axis=0)\n\n # Compute metrics\n self.auc = metrics.roc_auc_score(all_target, all_pred)\n # Extract elements with boolean index\n # Make '1' for elements higher than 0.5\n # Make '0' for elements lower than 0.5\n all_pred[all_pred > 0.5] = 1.0\n all_pred[all_pred <= 0.5] = 0.0\n self.accuracy = metrics.accuracy_score(all_target, all_pred)\n\n epoch_loss = epoch_loss / training_step \n print('Epoch %d/%d, loss : %3.5f, auc : %3.5f, accuracy : %3.5f' % (epoch+1, self.args.num_epochs, epoch_loss, self.auc, self.accuracy))\n self.write_log(epoch=epoch+1, auc=self.auc, accuracy=self.accuracy, loss=epoch_loss, name='training_')\n\n valid_steps = valid_q_data.shape[0] // self.args.batch_size\n valid_pred_list = list()\n valid_target_list = list()\n for s in range(valid_steps):\n # Validation\n valid_q = valid_q_data[s*self.args.batch_size:(s+1)*self.args.batch_size, :]\n valid_qa = valid_qa_data[s*self.args.batch_size:(s+1)*self.args.batch_size, :]\n # right : 1, wrong : 0, padding : -1\n valid_target = (valid_qa - 1) // self.args.n_questions\n valid_feed_dict = {self.q_data_seq : valid_q, self.qa_data_seq : valid_qa, self.target_seq : valid_target}\n valid_loss, valid_pred = self.sess.run([self.loss, self.pred], feed_dict=valid_feed_dict)\n # Same with training set\n valid_right_target = np.asarray(valid_target).reshape(-1,)\n valid_right_pred = np.asarray(valid_pred).reshape(-1,)\n valid_right_index = np.flatnonzero(valid_right_target != -1).tolist() \n valid_target_list.append(valid_right_target[valid_right_index])\n valid_pred_list.append(valid_right_pred[valid_right_index])\n \n all_valid_pred = np.concatenate(valid_pred_list, axis=0)\n all_valid_target = np.concatenate(valid_target_list, axis=0)\n\n valid_auc = metrics.roc_auc_score(all_valid_target, all_valid_pred)\n # For validation accuracy\n all_valid_pred[all_valid_pred > 0.5] = 1.0\n all_valid_pred[all_valid_pred <= 0.5] = 0.0\n valid_accuracy = metrics.accuracy_score(all_valid_target, all_valid_pred)\n print('Epoch %d/%d, valid auc : %3.5f, valid accuracy : %3.5f' %(epoch+1, self.args.num_epochs, valid_auc, valid_accuracy))\n # Valid log\n self.write_log(epoch=epoch+1, auc=valid_auc, accuracy=valid_accuracy, loss=valid_loss, name='valid_')\n if valid_auc > best_valid_auc:\n print('%3.4f to %3.4f' % (best_valid_auc, valid_auc))\n best_valid_auc = valid_auc\n best_epoch = epoch + 1\n self.save(best_epoch)\n\n return best_epoch \n \n \n \n \n def test(self, test_q, test_qa):\n steps = test_q.shape[0] // self.args.batch_size\n self.sess.run(tf.global_variables_initializer())\n if self.load():\n print('CKPT Loaded')\n else:\n raise Exception('CKPT need')\n\n print('Initial value of probability')\n print(init_probability)\n\n pred_list = list()\n target_list = list()\n\n for s in range(steps):\n test_q_batch = test_q[s*self.args.batch_size:(s+1)*self.args.batch_size, :]\n test_qa_batch = test_qa[s*self.args.batch_size:(s+1)*self.args.batch_size, :]\n target = test_qa_batch[:,:]\n target = target.astype(np.int)\n target_batch = (target - 1) // self.args.n_questions \n target_batch = target_batch.astype(np.float)\n feed_dict = {self.q_data_seq:test_q_batch, self.qa_data_seq:test_qa_batch, self.target_seq:target_batch}\n loss_, pred_ = self.sess.run([self.loss, self.pred], feed_dict=feed_dict)\n # Get right answer index\n # Make [batch size * seq_len, 1]\n right_target = np.asarray(target_batch).reshape(-1,1)\n right_pred = np.asarray(pred_).reshape(-1,1)\n # np.flatnonzero returns indices which is nonzero, convert it list \n right_index = np.flatnonzero(right_target != -1.).tolist()\n # Number of 'training_step' elements list with [batch size * seq_len, ]\n pred_list.append(right_pred[right_index])\n target_list.append(right_target[right_index])\n\n all_pred = np.concatenate(pred_list, axis=0)\n all_target = np.concatenate(target_list, axis=0)\n\n test_auc = metrics.roc_auc_score(all_target, all_pred)\n # Compute metrics\n all_pred[all_pred > 0.5] = 1.0\n all_pred[all_pred <= 0.5] = 0.0\n # Extract elements with boolean index\n # Make '1' for elements higher than 0.5\n # Make '0' for elements lower than 0.5\n\n test_accuracy = metrics.accuracy_score(all_target, all_pred)\n\n print('Test auc : %3.4f, Test accuracy : %3.4f' % (test_auc, test_accuracy))\n self.write_log(epoch=1, auc=test_auc, accuracy=test_accuracy, loss=0, name='test_')\n\n log_file_name = 'test_all_%s.txt' % self.args.gpu_id \n log_file = open(log_file_name, 'a')\n log = 'Test auc : %3.4f, Test accuracy : %3.4f' % (test_auc, test_accuracy)\n log_file.write(self.model_dir + '\\n')\n log_file.write(log + '\\n') \n log_file.flush() \n \n\n########################################################## FOR Reinforcement Learning ##############################################################\n\n def init_step(self):\n # q : action for RL\n # value_matrix : state for RL\n self.q = tf.placeholder(tf.int32, [self.args.batch_size, self.args.seq_len], name='step_q') \n self.a = tf.placeholder(tf.int32, [self.args.batch_size, self.args.seq_len], name='step_a') \n self.value_matrix = tf.placeholder(tf.float32, [self.args.memory_size,self.args.memory_value_state_dim], name='step_value_matrix')\n\n slice_a = tf.split(self.a, self.args.seq_len, 1) \n a = tf.squeeze(slice_a[0], 1)\n \n slice_q = tf.split(self.q, self.args.seq_len, 1) \n q = tf.squeeze(slice_q[0], 1)\n q_embed = self.embedding_q(q)\n correlation_weight = self.memory.attention(q_embed)\n\n stacked_value_matrix = tf.tile(tf.expand_dims(self.value_matrix, 0), tf.stack([self.args.batch_size, 1, 1]))\n \n # -1 for sampling\n # 0, 1 for given answer\n self.qa = tf.cond(tf.squeeze(a) < 0, lambda: self.sampling_a_given_q(q, stacked_value_matrix), lambda: q + tf.multiply(a, self.args.n_questions))\n a = (self.qa-1) // self.args.n_questions\n qa_embed = self.embedding_qa(self.qa) \n\n ######### Before Step ##########\n prev_read_content, prev_summary, prev_pred_logits, prev_pred_prob = self.inference(q_embed, correlation_weight, stacked_value_matrix, reuse_flag = True)\n\n ######### STEP #####################\n knowledge_growth = self.calculate_knowledge_growth(stacked_value_matrix, correlation_weight, qa_embed, prev_read_content, prev_summary, prev_pred_prob)\n # TODO : refactor sampling_a_given_q to return a only for below function call\n self.stepped_value_matrix = tf.squeeze(self.memory.value.write_given_a(stacked_value_matrix, correlation_weight, knowledge_growth, a, True), axis=0)\n #self.stepped_value_matrix = tf.squeeze(self.memory.value.write(stacked_value_matrix, correlation_weight, qa_embed, knowledge_growth, True), axis=0)\n self.stepped_read_content, self.stepped_summary, self.stepped_pred_logits, self.stepped_pred_prob = self.inference(q_embed, correlation_weight, self.stepped_value_matrix, reuse_flag = True)\n\n ######### After Step #########\n self.value_matrix_difference = tf.squeeze(tf.reduce_sum(self.stepped_value_matrix - stacked_value_matrix))\n self.read_content_difference = tf.squeeze(tf.reduce_sum(self.stepped_read_content - prev_read_content))\n self.summary_difference = tf.squeeze(tf.reduce_sum(self.stepped_summary - prev_summary))\n self.pred_logit_difference = tf.squeeze(tf.reduce_sum(self.stepped_pred_logits - prev_pred_logits))\n self.pred_prob_difference = tf.squeeze(tf.reduce_sum(self.stepped_pred_prob - prev_pred_prob))\n\n def ideal_test(self):\n type_list = [0, 1]\n for t in type_list: \n self.ideal_test_given_type(t) \n \n\n def ideal_test_given_type(self, input_type): \n \n if self.load():\n print('CKPT Loaded')\n else:\n raise Exception('CKPT need')\n\n log_file_name = 'logs/'+self.model_dir\n if input_type == 0:\n log_file_name = log_file_name + '_neg.csv'\n elif input_type == 1:\n log_file_name = log_file_name + '_pos.csv' \n elif input_type == -1:\n log_file_name = log_file_name + '_rand.csv' \n\n log_file = open(log_file_name, 'w')\n value_matrix = self.sess.run(self.init_memory_value)\n for i in range(100):\n\n for q_idx in range(1, self.args.n_questions+1):\n q = np.expand_dims(np.expand_dims(q_idx, axis=0), axis=0) \n a = np.expand_dims(np.expand_dims(input_type, axis=0), axis=0) \n \n ops = [self.stepped_value_matrix, self.stepped_pred_prob, self.value_matrix_difference, self.read_content_difference, self.summary_difference, self.pred_logit_difference, self.pred_prob_difference]\n feed_dict = { self.q : q, self.a : a, self.value_matrix: value_matrix }\n\n value_matrix, pred_prob, value_matrix_diff, read_content_diff, summary_diff, pred_logit_diff, pred_prob_diff = np.squeeze(self.sess.run(ops, feed_dict=feed_dict))\n pred_prob = np.squeeze(np.squeeze(pred_prob))\n\n log = str(i)+','+ str(q_idx) +','+str(input_type)+','+str(np.sum(value_matrix))+','+str(pred_prob) + ','\n log = log + str(value_matrix_diff) + ',' + str(read_content_diff) + ',' + str(summary_diff) + ',' + str(pred_logit_diff) + ',' + str(pred_prob_diff) + '\\n' \n log_file.write(log) \n\n log_file.flush() \n\n @property\n def model_dir(self):\n return '{}Knowledge_{}_Summary_{}_Add_{}_Erase_{}_WriteType_{}_{}_lr{}_{}epochs'.format(self.args.prefix, self.args.knowledge_growth, self.args.summary_activation, self.args.add_signal_activation, self.args.erase_signal_activation, self.args.write_type, self.args.dataset, self.args.initial_lr, self.args.num_epochs)\n\n def load(self):\n #self.args.batch_size = 32\n checkpoint_dir = os.path.join(self.args.dkvmn_checkpoint_dir, self.model_dir)\n print(checkpoint_dir)\n ckpt = tf.train.get_checkpoint_state(checkpoint_dir)\n if ckpt and ckpt.model_checkpoint_path:\n ckpt_name = os.path.basename(ckpt.model_checkpoint_path)\n self.train_count = int(ckpt_name.split('-')[-1])\n self.saver.restore(self.sess, os.path.join(checkpoint_dir, ckpt_name))\n print('DKVMN ckpt loaded')\n return True\n else:\n print('DKVMN cktp not loaded')\n return False\n\n def save(self, global_step):\n model_name = 'DKVMN'\n checkpoint_dir = os.path.join(self.args.dkvmn_checkpoint_dir, self.model_dir)\n if not os.path.exists(checkpoint_dir):\n os.mkdir(checkpoint_dir)\n self.saver.save(self.sess, os.path.join(checkpoint_dir, model_name), global_step=global_step)\n print('Save checkpoint at %d' % (global_step+1))\n\n # Log file\n def write_log(self, auc, accuracy, loss, epoch, name='training_'):\n log_path = os.path.join(self.args.dkvmn_log_dir, name+self.model_dir+'.csv')\n if not os.path.exists(log_path):\n self.log_file = open(log_path, 'w')\n self.log_file.write('Epoch\\tAuc\\tAccuracy\\tloss\\n')\n else:\n self.log_file = open(log_path, 'a') \n \n self.log_file.write(str(epoch) + '\\t' + str(auc) + '\\t' + str(accuracy) + '\\t' + str(loss) + '\\n')\n self.log_file.flush() \n \n" }, { "alpha_fraction": 0.6314732432365417, "alphanum_fraction": 0.6401785612106323, "avg_line_length": 39.727272033691406, "blob_id": "8304aa5d4cb3349b79d98ae87aa4b8a5264ffddd", "content_id": "bac14bc6e43eb517ebdd46e739b96090e9e00f0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4480, "license_type": "no_license", "max_line_length": 214, "num_lines": 110, "path": "/DQN/environment.py", "repo_name": "yjhong89/ITS", "src_encoding": "UTF-8", "text": "import gym\nimport tensorflow as tf\nimport numpy as np\nimport random\nimport copy\n\n#from model import *\n\nclass Environment(object):\n def __init__(self, args):\n self.args = args\n\n \nclass SimpleEnvironment(Environment):\n def __init__(self, args):\n super(SimpleEnvironment, self).__init__(args)\n self.env = gym.make(self.args.env_name)\n self.num_actions = self.env.action_space.n\n self.state_shape = list(self.env.observation_space.shape)\n\n def new_episode(self):\n return self.env.reset()\n\n def act(self, action):\n self.state, self.reward, self.terminal, _ = self.env.step(action)\n\n return self.state, self.reward, self.terminal\n\n def random_action(self):\n return self.env.action_space.sample()\n\nclass DKVMNEnvironment(Environment):\n def __init__(self, args, sess, dkvmn):\n super(DKVMNEnvironment, self).__init__(args)\n\n self.sess = sess\n print('Initializing ENVIRONMENT')\n self.env = dkvmn \n\n self.num_actions = self.args.n_questions\n self.initial_ckpt = np.copy(self.env.memory.memory_value)\n self.episode_step = 0\n\n self.value_matrix = self.sess.run(self.env.init_memory_value) \n self.state_shape = list(self.value_matrix.shape)\n \n\n def new_episode(self):\n print('NEW EPISODE')\n final_values_probs = self.sess.run(self.env.total_pred_probs, feed_dict={self.env.total_value_matrix: self.value_matrix})\n\n self.value_matrix = self.sess.run(self.env.init_memory_value)\n starting_values_probs = self.sess.run(self.env.total_pred_probs, feed_dict={self.env.total_value_matrix: self.value_matrix})\n\n #diff = final_values_probs - starting_values_probs\n for i, (s,f) in enumerate(zip(starting_values_probs, final_values_probs)):\n print(i, s, f, f-s)\n\n def check_terminal(self, total_pred_probs):\n return False\n\n def baseline_act(self):\n total_preds = self.sess.run(self.env.total_pred_probs, feed_dict={self.env.total_value_matrix:self.value_matrix})\n best_prob_index = np.argmax(total_preds)\n print('Action:%d, probL %3.4f' % (best_prob_index+1, total_preds[best_prob_index]))\n return best_prob_index+1, total_preds[best_prob_index]\n\n def act(self, action, case=None, prob=0):\n action = np.asarray(action+1, dtype=np.int32)\n action = np.expand_dims(np.expand_dims(action, axis=0), axis=0)\n\n # -1 for sampling \n # 0, 1 for input given\n # 0 : worst, 1 : best \n answer = np.asarray(-1, dtype=np.int32)\n answer = np.expand_dims(np.expand_dims(answer, axis=0), axis=0)\n\n prev_value_matrix = self.value_matrix\n\n #self.value_matrix, qa = self.sess.run([self.env.stepped_value_matrix, self.env.qa], feed_dict={self.env.q: action, self.env.a: answer, self.env.value_matrix: prev_value_matrix})\n ops = [self.env.stepped_value_matrix, self.env.value_matrix_difference, self.env.read_content_difference, self.env.summary_difference, self.env.qa, self.env.stepped_pred_prob, self.env.pred_prob_difference]\n self.value_matrix, val_diff, read_diff, summary_diff, qa, stepped_prob, prob_diff = self.sess.run(ops, feed_dict={self.env.q: action, self.env.a: answer, self.env.value_matrix: prev_value_matrix})\n \n if self.args.reward_type == 'value':\n self.reward = np.sum(val_diff)/100 \n elif self.args.reward_type == 'read':\n self.reward = np.sum(read_diff)/100\n elif self.args.reward_type == 'summary':\n self.reward = np.sum(summary_diff)/100\n\n ######## calculate probabilty for total problems\n #total_preds = self.sess.run(self.env.total_pred_probs, feed_dict={self.env.total_value_matrix: self.value_matrix})\n #print(total_preds)\n\n self.episode_step += 1\n\n total_pred_probs = self.sess.run(self.env.total_pred_probs, feed_dict={self.env.total_value_matrix: self.value_matrix})\n print('QA : %3d, Reward : %+5.4f, Prob : %1.4f, ProbDiff : %+1.4f' % (qa, self.reward, stepped_prob, prob_diff))\n if self.episode_step == self.args.episode_maxstep:\n terminal = True\n elif self.check_terminal(total_pred_probs) == True:\n terminal = True\n else:\n terminal = False\n\n\n return np.squeeze(self.value_matrix), self.reward, terminal\n\n def random_action(self):\n return random.randrange(0, self.num_actions)\n" }, { "alpha_fraction": 0.5232774615287781, "alphanum_fraction": 0.5465549230575562, "avg_line_length": 38.77777862548828, "blob_id": "90d71b077c4ba809e953045e65aba8fe6020c0e0", "content_id": "f12c1638418c8bddef7dd43a7b81e19bae7e704b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2148, "license_type": "no_license", "max_line_length": 197, "num_lines": 54, "path": "/run_improved_dkvmn.py", "repo_name": "yjhong89/ITS", "src_encoding": "UTF-8", "text": "import os \n\n# 'origin', 'value_matrix', 'read_content', 'summary', 'pred_prob'\nknowledge_growth_list = ['read_content']\n\n# 'sigmoid', 'tanh', 'relu'\nadd_signal_activation_list = ['sigmoid']\n\n# 'sigmoid', 'tanh', 'relu'\nerase_signal_activation_list = ['sigmoid']\n\n# 'sigmoid', 'tanh', 'relu'\nsummary_activation_list = ['sigmoid']\n\n# 'add_off_erase_off', 'add_off_erase_on', 'add_on_erase_off', 'add_on_erase_on'\nwrite_type_list = ['add_off_erase_on']\n\nlearning_rate_list = [0.6]\n#learning_rate_list = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n# 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0\n\nfor knowledge_growth in knowledge_growth_list:\n for add_signal_activation in add_signal_activation_list:\n for erase_signal_activation in erase_signal_activation_list:\n for write_type in write_type_list:\n for summary_activation in summary_activation_list:\n for learning_rate in learning_rate_list:\n\n args_list = []\n args_list.append('python main.py --dkvmn_train f --dkvmn_test f --dkvmn_ideal_test f --dqn_train t --dqn_test f --gpu_id 0 --dkvmn_checkpoint_dir DKVMN/100epoch_checkpoint')\n\n args_list.append('--dataset assist2009_updated')\n\n args_list.append('--knowledge_growth')\n args_list.append(knowledge_growth)\n\n args_list.append('--summary_activation')\n args_list.append(summary_activation)\n\n args_list.append('--add_signal_activation')\n args_list.append(add_signal_activation)\n\n args_list.append('--erase_signal_activation')\n args_list.append(erase_signal_activation)\n\n args_list.append('--write_type')\n args_list.append(write_type)\n\n args_list.append('--initial_lr')\n args_list.append(str(learning_rate))\n\n model = ' '.join(args_list)\n print(model)\n os.system(model)\n" } ]
5
huxiao-neu/Neu
https://github.com/huxiao-neu/Neu
3c767ec8167d7e328ae7642be810856bccfc5dde
6da2887def39e5c82d74ba3cc87ce071331c0744
a423c787a3915618b028733d7f0bdbb2b052b05e
refs/heads/master
2021-04-15T11:56:27.901762
2018-03-26T03:58:08
2018-03-26T03:58:08
126,306,899
0
0
null
2018-03-22T08:55:08
2018-03-22T00:59:40
2018-03-22T00:59:39
null
[ { "alpha_fraction": 0.6814814805984497, "alphanum_fraction": 0.6851851940155029, "avg_line_length": 22.18181800842285, "blob_id": "6ad3bcf4a144c29e81989af8cdc1250b8ed8d18d", "content_id": "67d8902c29e05d31bd54a4170f3f398b076517a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 270, "license_type": "no_license", "max_line_length": 36, "num_lines": 11, "path": "/__init__.py", "repo_name": "huxiao-neu/Neu", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\nfrom .SegModel import SegModel\r\nfrom .PosModel import PosModel\r\nfrom .NerModel import NerModel\r\nfrom .ParserModel import ParserModel\r\n\r\n\r\n# cut = SegModel().cut\r\n# pos = PosModel().pos\r\nner = NerModel().ner\r\n# parser = ParserModel().parser\r\n\r\n\r\n" }, { "alpha_fraction": 0.5550987124443054, "alphanum_fraction": 0.5912829041481018, "avg_line_length": 47.632652282714844, "blob_id": "d4872f326de86aba664e7c2e98543db9091519cd", "content_id": "59808cc59a4b8e501e54094f4d850add4595776c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2432, "license_type": "no_license", "max_line_length": 113, "num_lines": 49, "path": "/NerModel.py", "repo_name": "huxiao-neu/Neu", "src_encoding": "UTF-8", "text": "from .nn.op import lookup, LSTMlayer, CRFlayer, concat, Linear, LSTMcell, LSTMparam, LSTMstate\r\nfrom .util import ner_parameters\r\nimport numpy as np\r\n\r\nclass NerModel:\r\n def __init__(self):\r\n self.paras = ner_parameters(\"Neu/model/ner.model\")\r\n self.embedding = self.paras['embeddings']\r\n self.word2id = self.paras[\"word2id\"]\r\n self.id2tag = self.paras[\"id2tag\"]\r\n self.fWi = np.array(self.paras[\"fWi\"]).reshape((100,200))\r\n self.fbi = np.array(self.paras[\"fbi\"]).reshape((100))\r\n self.fWf = np.array(self.paras[\"fWf\"]).reshape((100,200))\r\n self.fbf = np.array(self.paras[\"fbf\"]).reshape((100))\r\n self.fWu = np.array(self.paras[\"fWu\"]).reshape((100,200))\r\n self.fbu = np.array(self.paras[\"fbu\"]).reshape((100))\r\n self.fWo = np.array(self.paras[\"fWo\"]).reshape((100,200))\r\n self.fbo = np.array(self.paras[\"fbo\"]).reshape((100))\r\n self.bWi = np.array(self.paras[\"bWi\"]).reshape((100,200))\r\n self.bbi = np.array(self.paras[\"bbi\"]).reshape((100))\r\n self.bWf = np.array(self.paras[\"bWf\"]).reshape((100,200))\r\n self.bbf = np.array(self.paras[\"bbf\"]).reshape((100))\r\n self.bWu = np.array(self.paras[\"bWu\"]).reshape((100,200))\r\n self.bbu = np.array(self.paras[\"bbu\"]).reshape((100))\r\n self.bWo = np.array(self.paras[\"bWo\"]).reshape((100,200))\r\n self.bbo = np.array(self.paras[\"bbo\"]).reshape((100))\r\n self.W_tag = np.array(self.paras[\"W_tag\"]).reshape((200, 7))\r\n self.b_tag = np.array(self.paras[\"b_tag\"]).reshape((7))\r\n self.trans = np.array(self.paras[\"transitions\"])\r\n\r\n def ner(self, word_list):\r\n ids = [self.word2id[word] for word in word_list]\r\n\r\n emb = lookup(self.embedding, ids) # (n, 100)\r\n forward = LSTMlayer(emb, self.fWi, self.fbi, self.fWf, self.fbf, self.fWu, self.fbu, self.fWo, self.fbo)\r\n # print(forward)\r\n\r\n emb.reverse()\r\n backward = LSTMlayer(emb, self.bWi, self.bbi, self.bWf, self.bbf, self.bWu, self.bbu, self.bWo, self.bbo)\r\n backward = np.flip(backward, 0)\r\n # print(backward)\r\n top_recur = concat(forward, backward, axis=1)\r\n tag_score = Linear(top_recur, self.W_tag, self.b_tag)\r\n # print(tag_score)\r\n tag_ids = CRFlayer(tag_score, self.trans)\r\n tag_list = [self.id2tag[id] for id in tag_ids]\r\n # print(tag_list)\r\n\r\n return tag_list\r\n" }, { "alpha_fraction": 0.7961538434028625, "alphanum_fraction": 0.8115384578704834, "avg_line_length": 20.66666603088379, "blob_id": "5491b3e23d6f8a77768334b8a2ba963d1909ed60", "content_id": "cd39c062aaf3b55b3a9efe694a68f3ca4a918b3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 494, "license_type": "no_license", "max_line_length": 64, "num_lines": 12, "path": "/README.md", "repo_name": "huxiao-neu/Neu", "src_encoding": "UTF-8", "text": "# Neu\n中文自然语言处理工具包--东北大学自然语言处理实验室(http://www.nlplab.com)\n\nNeu是东北大学自然语言处理实验室在2014开发的NiuParser的Python版本.\n\nNiuParser(http://www.niuparser.com), NiuParser支持所有的中文自然语言处理底层技术.\n\nNeu初步预计有四个模块,分别是分词,词性标注,实体识别,句法分析.\n\n安装方便,可直接pip安装,不依赖于繁多的包,敬请期待!\n\n有任何问题可联系[email protected], [email protected]\n" }, { "alpha_fraction": 0.44859811663627625, "alphanum_fraction": 0.44859811663627625, "avg_line_length": 15.5, "blob_id": "8daa2e04959014e44c225aae477c840acdc86424", "content_id": "05a322931644062d7b2b74a7019acb4656accc8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 107, "license_type": "no_license", "max_line_length": 23, "num_lines": 6, "path": "/SegModel.py", "repo_name": "huxiao-neu/Neu", "src_encoding": "UTF-8", "text": "\r\n\r\nclass SegModel():\r\n def __init__(self):\r\n pass\r\n\r\n def cut(self):\r\n print(\"cut le\")" } ]
4
NittaNonoka/e2MaskViewer
https://github.com/NittaNonoka/e2MaskViewer
3c1a6b35bd102edbe80dbcb60805758c646c622e
66825733d7c7311116783a3190444ec72ca7ade6
420db301678f7b0aff51ee673931e3afcb8e6a4d
refs/heads/develop
2023-01-05T01:22:05.943167
2020-11-04T05:25:22
2020-11-04T05:25:22
299,213,540
0
0
null
2020-09-28T06:42:21
2020-09-28T07:48:13
2020-09-28T07:50:01
Python
[ { "alpha_fraction": 0.49578651785850525, "alphanum_fraction": 0.5999744534492493, "avg_line_length": 37.39706039428711, "blob_id": "bbc65a3c93b3f873ca366776b6f7d88ad1dda1f0", "content_id": "6786c6f2902a6496c022855d14c4b161878ab039", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8110, "license_type": "no_license", "max_line_length": 107, "num_lines": 204, "path": "/viewer.py", "repo_name": "NittaNonoka/e2MaskViewer", "src_encoding": "UTF-8", "text": "# e2MaskZ\n# Arduinoで読み取ったセンサの値をシリアル通信によってPythonで可視化\nimport datetime\nimport serial\nimport numpy as np\nfrom time import time\nimport pygame \nfrom datetime import datetime \n\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\nRED = (255, 0, 0)\nBLUE = (0, 0, 255)\n\n#色を返す\ndef color(data_byte):\n sp = 1024/4\n if 0<data_byte<sp:\n return (0,0+data_byte,255)\n elif sp<=data_byte<sp*2:\n return(0,255,255-(data_byte-256))\n elif sp*2<=data_byte<sp*3:\n return(0+(data_byte-512),255,0)\n elif sp*3<=data_byte<sp*4:\n return (255,255-(data_byte-768),0)\n else:\n return(255,255,255)\n\nclass HMDSerialRead():\n\n def __init__(self, comnum, rate):\n self.com = comnum\n self.ser = serial.Serial(comnum, rate)\n self.values = [0 for i in range(20)] \n \n def UpdateSensorData(self):\n # When micro computer receives the \"b\", it sends back the sensor data.\n # This system receive the 24 bytes which include the sensor data and start stop character\n \n # self.ser.write(b\"b\")\n byteBuffer = self.ser.read_until(terminator=\"Z\".encode(\"utf-8\"))\n SensorList = byteBuffer\n \n # print(\"SensorList = \", SensorList)\n # print(byteBuffer)\n if(len(SensorList) == 27):\n # print(SensorList[0])\n self.values[0] = (((SensorList[1]) & 0xff) << 2) + (((SensorList[21]) & 0xc0) >> 6)\t \n self.values[1] = (((SensorList[2]) & 0xff) << 2) + (((SensorList[21]) & 0x30) >> 4)\n self.values[2] = (((SensorList[3]) & 0xff) << 2) + (((SensorList[21]) & 0x0c) >> 2)\n self.values[3] = (((SensorList[4]) & 0xff) << 2) + ((SensorList[21]) & 0x03)\n self.values[4] = (((SensorList[5]) & 0xff) << 2) + (((SensorList[22]) & 0xc0) >> 6)\t\n self.values[5] = (((SensorList[6]) & 0xff) << 2) + (((SensorList[22]) & 0x30) >> 4)\n self.values[6] = (((SensorList[7]) & 0xff) << 2) + (((SensorList[22]) & 0x0c) >> 2)\n self.values[7] = (((SensorList[8]) & 0xff) << 2) + ((SensorList[22]) & 0x03)\n self.values[8] = (((SensorList[9]) & 0xff) << 2) + (((SensorList[23]) & 0xc0) >> 6)\n self.values[9] = (((SensorList[10]) & 0xff) << 2) + (((SensorList[23]) & 0x30) >> 4)\n self.values[10] = (((SensorList[11]) & 0xff) << 2) + (((SensorList[23]) & 0x0c) >> 2)\n self.values[11] = (((SensorList[12]) & 0xff) << 2) + ((SensorList[23]) & 0x03)\n self.values[12] = (((SensorList[13]) & 0xff) << 2) + (((SensorList[24]) & 0xc0) >> 6)\n self.values[13] = (((SensorList[14]) & 0xff) << 2) + (((SensorList[24]) & 0x30) >> 4)\n self.values[14] = (((SensorList[15]) & 0xff) << 2) + (((SensorList[24])& 0x0c) >> 2)\n self.values[15] = (((SensorList[16]) & 0xff) << 2) + ((SensorList[24]) & 0x03)\n self.values[16] = (((SensorList[17]) & 0xff) << 2) + (((SensorList[25]) & 0xc0) >> 6)\n self.values[17] = (((SensorList[18]) & 0xff) << 2) + (((SensorList[25]) & 0x30) >> 4)\n self.values[18] = (((SensorList[19]) & 0xff) << 2) + (((SensorList[25]) & 0x0c) >> 2)\n self.values[19] = (((SensorList[20]) & 0xff) << 2) + ((SensorList[25]) & 0x03)\n # print(self.values)\n\n else:\n print(\"sensor data error\")\n\n def getSensorData(self):\n self.UpdateSensorData()\n return self.values \n\nclass SensorData:\n def __init__(self):\n self.commandType = -1\n self.strength = 0\n self.sensorValues = []\n \n def setSensorValues(self, sensorValues):\n self.sensorValues = sensorValues\n \n def getSensorValues(self):\n return self.sensorValues\n\n# Arduinoを繋げたCOMポートを開く \n# * ポート名は環境に合わせて適宜変えること\nser = HMDSerialRead(\"/dev/tty.usbserial-DN03ZVUJ\", 57600) # e2mask left\nser2 = HMDSerialRead(\"/dev/tty.usbserial-DN040KE7\", 57600) # e2mask right\n\n#ser = HMDSerialRead(\"/dev/tty.usbserial-DN0404LS\", 57600)\n# ser = HMDSerialRead(\"COM5\", 57600)\n\n\nsensorData = SensorData()\nsensorData2 = SensorData()\n# print(\"getSensorData = \", ser.getSensorData())\nsensorDataList = []\n\n#描画\npygame.init()\n\nWIDTH = 528\nHEIGHT = 639\n\nSCREEN = pygame.display.set_mode((WIDTH, HEIGHT))\n\npygame.display.set_caption('Viewer')\n\n#画像の挿入、1がセンサもついた画像、2が顔だけの画像\n# img1 = pygame.image.load(\"sensor.jpg\")\nimg2 = pygame.image.load(\"./test.jpg\")\n \n#SCREEN.blit(img1, (0, 0))\nSCREEN.blit(img2, (0, 0)) \n# SCREEN.fill(WHITE)\n\nis_running = True\n\nwhile is_running:\n # SensorData Update\n ser.UpdateSensorData()\n ser2.UpdateSensorData()\n sensorData.setSensorValues(ser.getSensorData())\n sensorData2.setSensorValues(ser2.getSensorData())\n data = sensorData.getSensorValues()+sensorData2.getSensorValues()\n # print(sensorData.getSensorValues())\n print(data)\n \n \n#right\n\n pygame.draw.rect(SCREEN,color(data[35]),(60,210,30,30))#ok\n pygame.draw.rect(SCREEN,color(data[37]),(125,210,30,30))#ok\n pygame.draw.rect(SCREEN,color(data[39]),(190,210,30,30))#ok\n\n\n pygame.draw.rect(SCREEN,color(data[31]),(50,320,30,30))#ok\n pygame.draw.rect(SCREEN,color(data[34]),(110,320,30,30))#ok\n pygame.draw.rect(SCREEN,color(data[25]),(170,320,30,30))#??\n \n pygame.draw.rect(SCREEN,color(data[26]),(35,370,30,30))#\n pygame.draw.rect(SCREEN,color(data[33]),(105,370,30,30))#ok\n pygame.draw.rect(SCREEN,color(data[28]),(170,370,30,30))#\n \n pygame.draw.rect(SCREEN,color(data[29]),(60,420,30,30))#ok\n pygame.draw.rect(SCREEN,color(data[38]),(110,420,30,30))#ok\n pygame.draw.rect(SCREEN,color(data[36]),(165,420,30,30))#ok\n \n pygame.draw.rect(SCREEN,color(data[22]),(80,470,30,30))#ok\n pygame.draw.rect(SCREEN,color(data[32]),(130,470,30,30))#ok\n pygame.draw.rect(SCREEN,color(data[34]),(180,470,30,30))#??\n \n pygame.draw.rect(SCREEN,color(data[28]),(100,520,30,30))#ok\n pygame.draw.rect(SCREEN,color(data[36]),(150,520,30,30))#?\n pygame.draw.rect(SCREEN,color(data[24]),(200,520,30,30))#ok\n\n pygame.draw.rect(SCREEN,color(data[27]),(130,570,30,30))#ok\n pygame.draw.rect(SCREEN,color(data[26]),(180,570,30,30))#ok\n\n#left\n# 2 0 反応なし\n pygame.draw.rect(SCREEN,color(data[14]),(330,210,30,30))#ok\n pygame.draw.rect(SCREEN,color(data[16]),(395,210,30,30))#ok\n pygame.draw.rect(SCREEN,color(data[17]),(460,210,30,30))#ok\n \n\n pygame.draw.rect(SCREEN,color(data[15]),(330,320,30,30))#ok\n pygame.draw.rect(SCREEN,color(data[13]),(390,320,30,30))#ok\n pygame.draw.rect(SCREEN,color(data[19]),(450,320,30,30))#ok\n \n pygame.draw.rect(SCREEN,color(data[8]),(340,370,30,30))#ok\n pygame.draw.rect(SCREEN,color(data[11]),(400,370,30,30))#ok\n pygame.draw.rect(SCREEN,color(data[18]),(460,370,30,30))#ok\n \n pygame.draw.rect(SCREEN,color(data[9]),(350,420,30,30))#ok\n pygame.draw.rect(SCREEN,color(data[10]),(400,420,30,30))#ok\n pygame.draw.rect(SCREEN,color(data[12]),(450,420,30,30))#ok\n \n pygame.draw.rect(SCREEN,color(data[1]),(340,470,30,30))#ok\n pygame.draw.rect(SCREEN,color(data[4]),(390,470,30,30))#ok\n pygame.draw.rect(SCREEN,color(data[7]),(440,470,30,30))#ok\n \n pygame.draw.rect(SCREEN,color(data[3]),(310,520,30,30))#ok\n pygame.draw.rect(SCREEN,color(data[0]),(360,520,30,30))#壊れてる?\n pygame.draw.rect(SCREEN,color(data[6]),(410,520,30,30))#ok\n\n pygame.draw.rect(SCREEN,color(data[5]),(330,570,30,30))#ok\n pygame.draw.rect(SCREEN,color(data[0]),(380,570,30,30))#壊れてる?\n\n pygame.display.flip()\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n is_running = False\n # elif event.type == pygame.MOUSEBUTTONDOWN:#右クリックするとスクリーンショットを保存する\n # if event.button == 1:\n # print(\"スクリーンショットを保存しました。\")\n # # pygame.image.save(SCREEN,\"screenshot%s.jpg\"%datetime.today().strftime(\"%Y%m%d-%H%M%S\"))\n \npygame.quit()" }, { "alpha_fraction": 0.38078629970550537, "alphanum_fraction": 0.48604947328567505, "avg_line_length": 32.553192138671875, "blob_id": "52019f5310c7c82c0471ce2c8f5a2356cb6e3868", "content_id": "d83a47f709d5cd5f5361473b6d1f40a0cb69ff4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3154, "license_type": "no_license", "max_line_length": 82, "num_lines": 94, "path": "/arduino_multiplexer_20/arduino_multiplexer_20.ino", "repo_name": "NittaNonoka/e2MaskViewer", "src_encoding": "UTF-8", "text": "#include <Arduino.h>\n\n/* application\nPIN\n D2 --- A\n D3 --- B\n D4 --- C\n A0 --- COM1 (0 - 7)\n A1 --- COM2 (8 - 15)\n A2 --- COM3 (16 - 23)\n*/\n\n#define PLOT_MODE\n\nint sensorValue[22];\nconst int numSns = 24;\nbyte BinaryData[27] = {65.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,90};\n\nvoid setup() {\n pinMode(2, OUTPUT);\n pinMode(3, OUTPUT);\n pinMode(4, OUTPUT);\n // overflow\n // analogReference(INTERNAL);\n Serial.begin(57600);\n}\n\nvoid loop() {\n int value = 0;\n// get\n for (int i = 0; i <7; i++) {\n digitalWrite(2, i % 2);\n digitalWrite(3, (i / 2) % 2);\n digitalWrite(4, (i / 4) % 2);\n // wait\n delay(1);\n\n sensorValue[i] = analogRead(A0);\n// delay(3);\n sensorValue[8 + i] = analogRead(A1);\n// delay(3);\n if(i!=6) sensorValue[16 + i] = analogRead(A2);\n }\n \n BinaryData[1] = ((sensorValue[0] >> 2) & 0xff);\n BinaryData[2] = ((sensorValue[1] >> 2) & 0xff);\n BinaryData[3] = ((sensorValue[2] >> 2) & 0xff);\n BinaryData[4] = ((sensorValue[3] >> 2) & 0xff);\n BinaryData[5] = ((sensorValue[4] >> 2) & 0xff);\n BinaryData[6] = ((sensorValue[5] >> 2) & 0xff);\n BinaryData[7] = ((sensorValue[6] >> 2) & 0xff);\n\n BinaryData[8] = ((sensorValue[8] >> 2) & 0xff);\n BinaryData[9] = ((sensorValue[9] >> 2) & 0xff);\n BinaryData[10] = ((sensorValue[10] >> 2) & 0xff);\n BinaryData[11] = ((sensorValue[11] >> 2) & 0xff);\n BinaryData[12] = ((sensorValue[12] >> 2) & 0xff);\n BinaryData[13] = ((sensorValue[13] >> 2) & 0xff);\n BinaryData[14] = ((sensorValue[14] >> 2) & 0xff);\n\n BinaryData[15] = ((sensorValue[16] >> 2) & 0xff);\n BinaryData[16] = ((sensorValue[17] >> 2) & 0xff);\n BinaryData[17] = ((sensorValue[18] >> 2) & 0xff);\n BinaryData[18] = ((sensorValue[19] >> 2) & 0xff);\n BinaryData[19] = ((sensorValue[20] >> 2) & 0xff);\n BinaryData[20] = ((sensorValue[21] >> 2) & 0xff);\n\n\n BinaryData[21] = (((sensorValue[0] & 0x03) << 0)\n + ((sensorValue[1] & 0x03) << 2)\n + ((sensorValue[2] & 0x03) << 4)\n + ((sensorValue[3] & 0x03) << 6));\n BinaryData[22] = (((sensorValue[4] & 0x03) << 0)\n + ((sensorValue[5] & 0x03) << 2)\n + ((sensorValue[6] & 0x03) << 4)\n + ((sensorValue[8] & 0x03) << 6));\n BinaryData[23] = (((sensorValue[9] & 0x03) << 0)\n + ((sensorValue[10] & 0x03) << 2)\n + ((sensorValue[11] & 0x03) << 4)\n + ((sensorValue[12] & 0x03) << 6));\n BinaryData[24] = (((sensorValue[13] & 0x03) << 0)\n + ((sensorValue[14] & 0x03) << 2)\n + ((sensorValue[16] & 0x03) << 4)\n + ((sensorValue[17] & 0x03) << 6));\n BinaryData[25] = (((sensorValue[18] & 0x03) << 0)\n + ((sensorValue[19] & 0x03) << 2)\n + ((sensorValue[20] & 0x03) << 4)\n + ((sensorValue[21] & 0x03) << 6));\n //Serial.write(((sensorValue[20] & 0x03) << 0)\n // + ((sensorValue[21] & 0x03) << 2)\n // + ((sensorValue[22] & 0x03) << 4)\n // + ((sensorValue[23] & 0x03) << 6));\n Serial.write(BinaryData, 27);\n}\n" }, { "alpha_fraction": 0.7380607724189758, "alphanum_fraction": 0.7959479093551636, "avg_line_length": 12.037735939025879, "blob_id": "06df5f319eef67d5241165e35d2c30dc400eb633", "content_id": "ecaac02f6b5bd75b76815ed0f02018cf1151ec9f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1129, "license_type": "no_license", "max_line_length": 115, "num_lines": 53, "path": "/README.md", "repo_name": "NittaNonoka/e2MaskViewer", "src_encoding": "UTF-8", "text": "# e2MaskViewer\n\nArduinoから読み取ったセンサのデータを可視化するviewer\n\n\n# DEMO\n\n画像は一例ですが、センサデータをマスクの位置と対応するように、ヒートマップなどで可視化するとわかりやすいかと思います\n\n![viewerイメージ](https://user-images.githubusercontent.com/40416853/94401996-64aa1880-01a6-11eb-88df-a83a020a282a.jpg)\n\n\n# Features\nどうして表情が変化したかの説明の役割\n\nセンサのいる要らないの判断ができる\n\n\n# Requirement\n\n必要な環境\n\n* Python3系\n* Arduino IDE\n\n# Installation\n\n### Pythonのライブラリインストール方法\n\n```bash\npip install [ライブラリ]\n```\n\n### ArduinoIDEのインストール\n\n以下よりダウンロードしてインストールする\n\nhttps://www.arduino.cc/en/Main/Software\n\n# Usage\n\n実行方法\n\n自分のPCにクローンして、実行する\n\nArduinoを繋ぐCOMポートの名称は適宜変えてください(viewer.py)\n```bash\ngit clone https://github.com/NittaNonoka/e2MaskViewer.git\npython viewer.py\n```\n\n# Note\nmasterブランチにはPushしないこと!\n" } ]
3
DipenMav/PythonMP3
https://github.com/DipenMav/PythonMP3
318e00a4b899cff01d5268f062ddefe8f12ea1ed
efaa9199198533a11cdbb0196f7acb157429b8bd
b3c8342238af45985698a42b1f909ee3245307f6
refs/heads/main
2023-06-29T14:55:51.960778
2021-07-28T17:12:06
2021-07-28T17:12:06
390,434,606
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6719729900360107, "alphanum_fraction": 0.6943238377571106, "avg_line_length": 29.57868003845215, "blob_id": "1b74c2fa1a38507d69a88a1ba98d7e5678dc387d", "content_id": "0b2c64bef01680c8ad2deefc4fcd51132625f3c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6219, "license_type": "no_license", "max_line_length": 146, "num_lines": 197, "path": "/mp3player.py", "repo_name": "DipenMav/PythonMP3", "src_encoding": "UTF-8", "text": "from tkinter import *\r\nimport pygame\r\nfrom tkinter import filedialog\r\nfrom PIL import ImageTk,Image\r\nroot=Tk()\r\nroot.geometry(\"500x400\")\r\nroot.title(\"MP3 Player\")\r\n#pygame\r\npygame.mixer.init()\r\n\r\n#frame\r\nframe=Frame(root,bg=\"blue\")\r\nframe.pack()\r\n\r\n#listbox\r\nsong_box=Listbox(frame,width=50,height=15,selectbackground=\"khaki1\",selectforeground=\"navy\")\r\nsong_box.pack(pady=10)\r\n\r\ndef resume_music():\r\n pygame.mixer.music.unpause()\r\n\r\ndef pause_music():\r\n pygame.mixer.music.pause()\r\n\r\ndef stop_music():\r\n pygame.mixer.music.stop()\r\n song_box.selection_clear(ACTIVE)\r\n\r\ndef play_music():\r\n get_song=song_box.get(ACTIVE)\r\n get_song=str.format(\"C:/Users/User/Desktop/songs/{}.mp3\".format(get_song))\r\n #get_song=f'C:/Users/User/Desktop/songs/{get_song}.mp3'\r\n print(get_song)\r\n pygame.mixer.music.load(get_song)\r\n pygame.mixer.music.play(loops=0) \r\n\r\ndef forward_song():\r\n \r\n current_song_tuple=song_box.curselection()\r\n #It is returning tuple not exact location\r\n print(current_song_tuple)\r\n \r\n # now to get exact location\r\n current_song=current_song_tuple[0]\r\n print(current_song)\r\n\r\n next_song=current_song+1\r\n print(next_song)\r\n get_song=song_box.get(next_song)\r\n print(get_song)\r\n get_song=str.format(\"C:/Users/User/Desktop/songs/{}.mp3\".format(get_song))\r\n #get_song=f'C:/Users/User/Desktop/songs/{get_song}.mp3'\r\n #print(get_song)\r\n pygame.mixer.music.load(get_song)\r\n pygame.mixer.music.play(loops=0)\r\n # clear selector and then move\r\n song_box.selection_clear(0,END)\r\n song_box.activate(next_song)\r\n # SET ACTIVE BAR\r\n song_box.selection_set(next_song,last=None)\r\n length=song_box.size()\r\n print(length)\r\n #if next_song ==length-1:\r\n # pygame.mixer.music.play(next_song)\r\n # song_box.selection_clear(0,END)\r\n #song_box.activate(0)\r\n #song_box.selection_set(0,last=None)\r\n \r\n \r\n\r\n\r\ndef previous_song():\r\n current_song_tuple=song_box.curselection()\r\n #It is returning tuple not exact location\r\n print(current_song_tuple)\r\n \r\n # now to get exact location\r\n current_song=current_song_tuple[0]\r\n print(current_song)\r\n\r\n previous_song=current_song-1\r\n \r\n get_song=song_box.get(previous_song)\r\n print(get_song)\r\n get_song=str.format(\"C:/Users/User/Desktop/songs/{}.mp3\".format(get_song))\r\n print(get_song)\r\n pygame.mixer.music.load(get_song)\r\n pygame.mixer.music.play(loops=0)\r\n # clear selector and then move\r\n song_box.selection_clear(0,END)\r\n song_box.activate(previous_song)\r\n # SET ACTIVE BAR\r\n song_box.selection_set(previous_song,last=None)\r\n print(previous_song)\r\n \r\n \r\n\r\n\r\ndef add_one_song():\r\n song=filedialog.askopenfilename(initialdir='desktop/songs/',title=\"Select a song\",filetypes=((\"mp3 files\",\"*.mp3\"),(\"all song\",\"*.*\")))\r\n song=song.replace(\"C:/Users/User/Desktop/songs/\",\"\")\r\n song=song.replace(\".mp3\",\"\")\r\n song_box.insert(END,song)\r\n\r\ndef add_many_songs():\r\n many_songs=filedialog.askopenfilenames(initialdir='desktop/songs/',title=\"Select a song\",filetypes=((\"mp3 files\",\"*.mp3\"),(\"all song\",\"*.*\")))\r\n for item in many_songs:\r\n item=item.replace(\"C:/Users/User/Desktop/songs/\",\"\")\r\n item=item.replace(\".mp3\",\"\")\r\n song_box.insert(END,item)\r\n\r\ndef delete_one_song():\r\n song_box.delete(ANCHOR)\r\n #song_box.delete(ACTIVE)\r\n pygame.mixer.music.stop()\r\n\r\ndef delete_all_song():\r\n song_box.delete(0,END)\r\n pygame.mixer.music.stop()\r\n\r\n# menubar\r\nmenu_bar=Menu(root)\r\nroot.config(menu=menu_bar)\r\nsong_menu=Menu(menu_bar)\r\nmenu_bar.add_cascade(label=\"Add Song\",menu=song_menu)\r\nsong_menu.add_command(label=\"Add one song\",command=add_one_song)\r\nsong_menu.add_command(label=\"Add Many song\",command=add_many_songs)\r\n\r\ndelete_menu=Menu(menu_bar)\r\nmenu_bar.add_cascade(label=\"Delete song\",menu=delete_menu)\r\ndelete_menu.add_command(label=\"Delete one song\",command=delete_one_song)\r\ndelete_menu.add_command(label=\"Delete All song\",command=delete_all_song)\r\n\r\n\r\n#resize img\r\n\r\nmusic_img=Image.open(\"desktop/music.png\")\r\nresize_music_img=music_img.resize((58,58),Image.ANTIALIAS)\r\nnew_music_img=ImageTk.PhotoImage(resize_music_img)\r\n\r\npause_img=Image.open(\"desktop/pause.png\")\r\nresize_pause_img=pause_img.resize((70,70),Image.ANTIALIAS)\r\nnew_pause_img=ImageTk.PhotoImage(resize_pause_img)\r\n\r\nresume_img=Image.open(\"desktop/play.png\")\r\nresize_resume_img=resume_img.resize((50,50),Image.ANTIALIAS)\r\nnew_resume_img=ImageTk.PhotoImage(resize_resume_img)\r\n\r\nstop_img=Image.open(\"desktop/stop.png\")\r\nresize_stop_img=stop_img.resize((50,50),Image.ANTIALIAS)\r\nnew_stop_img=ImageTk.PhotoImage(resize_stop_img)\r\n\r\nforward_img=Image.open(\"desktop/forwardbutton.png\")\r\nresize_forward_img=forward_img.resize((90,55),Image.ANTIALIAS)\r\nnew_forward_img=ImageTk.PhotoImage(resize_forward_img)\r\n\r\nprevious_img=Image.open(\"desktop/backbutton.png\")\r\nresize_previous_img=previous_img.resize((50,50),Image.ANTIALIAS)\r\nnew_previous_img=ImageTk.PhotoImage(resize_previous_img)\r\n\r\nstop_btn=Button(root,image=new_stop_img,borderwidth=0,command=stop_music)\r\nstop_btn.place(x=190,y=300)\r\n\r\nstop_label=Label(root,text=\"Stop\",fg=\"red\")\r\nstop_label.place(x=200,y=360)\r\n\r\nprevious_btn=Button(root,image=new_previous_img,borderwidth=0,command=previous_song)\r\nprevious_btn.place(x=30,y=300)\r\n\r\nprevious_label=Label(root,text=\"Previous Song\",fg=\"red\")\r\nprevious_label.place(x=10,y=360)\r\n\r\nforward_btn=Button(root,image=new_forward_img,borderwidth=0,command=forward_song)\r\nforward_btn.place(x=395,y=298)\r\n\r\nforward_label=Label(root,text=\"Next Song\",fg=\"red\")\r\nforward_label.place(x=410,y=360)\r\n\r\npause_btn=Button(root,image=new_pause_img,borderwidth=0,command=pause_music)\r\npause_btn.place(x=255,y=290)\r\n\r\npause_label=Label(root,text=\"Pause\",fg=\"red\",)\r\npause_label.place(x=270,y=360)\r\n\r\nmusic_btn=Button(root,image=new_music_img,borderwidth=0,command=play_music)\r\nmusic_btn.place(x=110,y=295)\r\n\r\nmusic_label=Label(root,text=\"Music\",fg=\"red\")\r\nmusic_label.place(x=120,y=360)\r\n\r\nresume_btn=Button(root,image=new_resume_img,borderwidth=0,command=resume_music)\r\nresume_btn.place(x=340,y=300)\r\n\r\nresume_label=Label(root,text=\"Resume\",fg=\"red\")\r\nresume_label.place(x=340,y=360)\r\n\r\nroot.mainloop()" } ]
1
topgambajrjdeveloper/trabajo-extra
https://github.com/topgambajrjdeveloper/trabajo-extra
68da1193b64544674a5ed8babc701076d6f73536
18ee5069d5a68bda1220250d144dd487f54167e5
9021a92a3bd319d379cbc380656a2615d4f3f56e
refs/heads/main
2023-04-13T02:36:44.683838
2021-05-03T09:44:13
2021-05-03T09:44:13
362,214,646
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4906103312969208, "alphanum_fraction": 0.5422534942626953, "avg_line_length": 28.413793563842773, "blob_id": "3b94a56ed8bc4dea464be1c4ca7f243606c6ea08", "content_id": "48a6bd844bea97766662fcd877e51085374aba84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 854, "license_type": "no_license", "max_line_length": 73, "num_lines": 29, "path": "/romano.py", "repo_name": "topgambajrjdeveloper/trabajo-extra", "src_encoding": "UTF-8", "text": "def romano_a_arabigo(romano):\n romanos = {'M': 1000, 'D':500, 'C':100, 'L':50, 'X':10, 'V':5, 'I':1}\n entero=0\n for i in range(len(romano)):\n if i > 0 and romanos[romano[i]] > romanos[romano[i-1]]:\n entero += romano[romano[i]]-2 * romanos[romano[i-1]]\n else:\n entero += romanos[romano[i]] \n\n print('Este es el número en romano:', entero)\n\n\ndef arabigo_a_romano(entero):\n numeros = [1000, 500, 100, 50, 10, 5, 1]\n numerales = ['M', 'D', 'C', 'L', 'X', 'V', 'I']\n\n numeral = ''\n i = 0\n\n while entero > 0:\n for _ in range(entero // numeros[i]):\n numeral += numerales[i]\n entero -= numeros[i]\n i += 1\n print('Este es el número en romano:', numeral)\n\n\narabigo_a_romano(1098) #Introduce aqui el entero\nromano_a_arabigo('CXXIII') #Introduce aqui el romano" }, { "alpha_fraction": 0.48815789818763733, "alphanum_fraction": 0.49166667461395264, "avg_line_length": 27.148147583007812, "blob_id": "5a3ac9bc2a69038329b344c99f095c17db4ad141", "content_id": "14a7068b00c4db5df7561f689a0fb2779142bf9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2292, "license_type": "no_license", "max_line_length": 145, "num_lines": 81, "path": "/silabeo.py", "repo_name": "topgambajrjdeveloper/trabajo-extra", "src_encoding": "UTF-8", "text": "def leer_frase():\n global txt\n txt = (input(\"Ingresa una texto: \")).lower()\n\n\ndictSilabas = {\n 'consonantes': [\n 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'll', 'm', 'n', 'ñ', 'p',\n 'q', 'r', 's', 't', 'v', 'w', 'x', 'z'\n ],\n 'vocales_abiertas': ['a', 'e', 'o', 'á', 'é', 'ó', 'ú'],\n 'vocales_cerradas': ['i', 'u', 'ü'],\n 'semivocles': ['y']\n}\n\n#diptongos = [(dictSilabas.vocales_abiertas + dictSilabas.vocales_cerradas),\n# (dictSilabas.vocales_abiertas + dictSilabas.vocales_cerradas),\n# (dictSilabas.vocales_abiertas + dictSilabas.vocales_cerradas)]\n#triptongos = dictSilabas.vocales_cerradas+dictSilabas.vocales_abiertas + dictSilabas.vocales_cerradas\npares_consonantes=[pares_consonantes=['bl', 'cl', 'fl', 'gl', 'kl', 'pl', 'tl', 'br', 'cr', 'dr', 'fr', 'gr', 'kr', 'pr', 'tr', 'ch', 'll', 'rr']\n]\n\n\ndef separar_silabas():\n part = txt.split('-')\n for i in dictSilabas:\n for j in part:\n if i.isalpha():\n print('Estas son las silabas en la frase: ', part)\n\n\ndef contar_vocales():\n vocal = ['a', 'e', 'o', 'á', 'é', 'ó', 'ú', 'i', 'u', 'ü']\n contador = 0\n for i in vocal:\n for j in txt:\n if (i == j):\n contador += 1\n print('El numero de vocales es: ', contador)\n\n\ndef contar_consonantes():\n consonantes = [\n 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'll', 'm', 'n', 'ñ', 'p',\n 'q', 'r', 's', 't', 'v', 'w', 'x', 'z'\n ]\n contador = 0\n for i in consonantes:\n for j in txt:\n if (i == j):\n contador += 1\n print(' El numero de consonantes es: ', contador)\n\n\ndef pares_consonantes():\n pares = [\n 'bl', 'cl', 'fl', 'gl', 'kl', 'pl', 'tl', 'br', 'cr', 'dr', 'fr', 'gr',\n 'kr', 'pr', 'tr', 'ch', 'll', 'rr'\n ]\n contador = 0\n for i in pares:\n for j in txt:\n if (i == j):\n contador += 1\n print(' El numero de pares es: ', contador)\n\n\ndef contar_letra_en_frase():\n contador = 0\n for i in txt:\n if (i.isalpha()):\n contador += 1\n print(' La cantidad de letras es: ', contador)\n\n\nleer_frase()\ncontar_letra_en_frase()\ncontar_consonantes()\npares_consonantes()\nseparar_silabas()\ncontar_vocales()\n" } ]
2
wanggn/tableau-1
https://github.com/wanggn/tableau-1
53ab147d96e27557d1a1d7a29cde83e6b0c9e091
be16a9e3642435d759f404920b14281f836f6b64
7195222c10c129873aa72c8834cc566879f4677a
refs/heads/master
2020-03-24T22:57:57.626127
2016-07-28T01:52:08
2016-07-28T01:52:08
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7048192620277405, "alphanum_fraction": 0.7108433842658997, "avg_line_length": 17.44444465637207, "blob_id": "ef88e754917ee3a56d47d9b7261ed9a82af8d62a", "content_id": "3a9baf9a77d91e77a3f63fceeeccd35a240018bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 166, "license_type": "no_license", "max_line_length": 50, "num_lines": 9, "path": "/conf/config.py", "repo_name": "wanggn/tableau-1", "src_encoding": "UTF-8", "text": "# coding=utf8\n\nimport logging\n\ntry:\n from local_config import *\n from db_config import *\nexcept ImportError:\n logging.warning(\"No local_config file found.\")\n" }, { "alpha_fraction": 0.4755353331565857, "alphanum_fraction": 0.4928436577320099, "avg_line_length": 38.782806396484375, "blob_id": "7e979461d0e0451ff4dbf3661b53e17baa9754c9", "content_id": "560a742a395125307eeaa0b8410d19a570c9f121", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9025, "license_type": "no_license", "max_line_length": 79, "num_lines": 221, "path": "/ylzh/ylzh.py", "repo_name": "wanggn/tableau-1", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\nimport json, md5, requests\r\nfrom conf import config\r\nfrom datetime import datetime\r\nfrom pony.orm import *\r\nfrom model.models import *\r\nfrom tool import utils\r\nfrom tool.utils import *\r\n\r\nclass Pylzh_Process(object):\r\n def __init__(self):\r\n self.request_model = utils.Request_Model()\r\n self.format_str = utils.Format_Str()\r\n\r\n def request_data(self, json_data):\r\n param_dict = json.loads(json_data)\r\n self.params = self.request_model.request_params(param_dict)\r\n url = config.DOMAIN+config.USER_DATA\r\n response = self.request_model.request_get(\r\n url,\r\n self.params\r\n )\r\n self.request_time = None\r\n self.parse_time = None\r\n try:\r\n request_start = datetime.now()\r\n request_end = datetime.now()\r\n all_data = json.loads(response.text)\r\n self.order_id = all_data.get('orderId', '')\r\n self.order_id = param_dict.get('orderId', '')\r\n self.cert_no = '51152119902022322'\r\n self.bank_card_no = '621123812839123912'\r\n self.name = u'张三'\r\n self.time_now = datetime.now()\r\n self.request_time = request_end - request_start\r\n print '$$$$',self.request_time\r\n except Exception, e:\r\n raise e\r\n data = all_data.get('data', {})\r\n result = data.get('result', {})\r\n quota = result.get('quota', {})\r\n if quota:\r\n try:\r\n parse_start = datetime.now()\r\n self.format_str.clean_na(quota)\r\n self.save_base_statistic_info(quota)\r\n self.save_month_consume(quota)\r\n self.save_live_city(quota)\r\n self.save_mcc_consume(quota)\r\n self.save_high_freq_mar(quota)\r\n self.save_top_money_mar(quota)\r\n self.save_consume_city_times(quota)\r\n parse_end = datetime.now()\r\n self.parse_time = parse_end - parse_start\r\n except Exception, e:\r\n raise e\r\n self.save_info(all_data)\r\n print self.parse_time\r\n return 'ylzh请求成功'\r\n\r\n @db_session\r\n def save_info(self, all_data):\r\n REQUEST_INFO(\r\n orderId = self.order_id, \r\n resCode = all_data.get('resCode', ''),\r\n resMsg = all_data.get('resMsg', ''),\r\n statCode = all_data.get('statCode', ''),\r\n statMsg = all_data.get('statMsg', ''),\r\n smartOrderId = all_data.get('smartOrderId', ''),\r\n sign = all_data.get('sign', ''),\r\n request_time = self.request_time,\r\n parse_time = self.parse_time,\r\n create_time = self.time_now,\r\n )\r\n\r\n @db_session\r\n def save_base_statistic_info(self, quota):\r\n BN_BASE_STATISTIC_INFO(\r\n orderId = self.order_id,\r\n cert_no = self.cert_no,\r\n bank_card_no = self.bank_card_no,\r\n name = self.name,\r\n card_type = quota.get('S0466', ''),\r\n card_grade = quota.get('S0467', ''),\r\n line_consume_amt = try_float(quota.get('S0057')),\r\n line_consume_times = try_int(quota.get('S0060', '')),\r\n lastest_consume_date = exact_to_day(quota.get('S0135', '')),\r\n dif_city_consume_1h = try_int(quota.get('S0305', '')),\r\n receive_to_transfer_per = percent_to_float(quota.get('S0314', '')),\r\n receive_to_draw_per = percent_to_float(quota.get('S0317', '')),\r\n fir_deal_date = exact_to_day(quota.get('S0506', '')),\r\n deal_days = try_int(quota.get('S0513','')),\r\n deal_grade_in_city = percent_to_float(quota.get('S0563', '')),\r\n work_consume_times_per = percent_to_float(quota.get('S0656', '')),\r\n create_time=self.time_now,\r\n )\r\n\r\n @db_session\r\n def save_month_consume(self, quota):\r\n work_consume_amt_dict = parse_to_dict(quota.get('S0520', ''))\r\n deal_consume_amt_dict = parse_to_dict(quota.get('S0534', ''))\r\n deal_consume_times_dict = parse_to_dict(quota.get('S0537', ''))\r\n deal_bank_amt_dict = parse_to_dict(quota.get('S0535', ''))\r\n deal_bank_times_dict = parse_to_dict(quota.get('S0538', ''))\r\n keys = work_consume_amt_dict.keys()\r\n keys.sort(reverse=True)\r\n for key in keys:\r\n work_consume_amt = work_consume_amt_dict.get(key)\r\n deal_consume_amt = deal_consume_amt_dict.get(key)\r\n deal_consume_times = deal_consume_times_dict.get(key)\r\n deal_bank_amt = deal_bank_amt_dict.get(key)\r\n deal_bank_times = deal_bank_times_dict.get(key)\r\n BN_MONTH_CONSUME(\r\n orderId = self.order_id,\r\n cert_no = self.cert_no,\r\n bank_card_no = self.bank_card_no,\r\n name = self.name,\r\n month = exact_to_month('20'+key),\r\n work_consume_amt = work_consume_amt,\r\n deal_consume_amt = deal_consume_amt,\r\n deal_consume_times = deal_consume_times,\r\n deal_bank_amt = deal_bank_amt,\r\n deal_bank_times = deal_bank_times,\r\n create_time = self.time_now,\r\n )\r\n\r\n @db_session\r\n def save_live_city(self, quota):\r\n citys = quota.get('S0503', '').split(';')\r\n BN_LIVE_CITY(\r\n orderId = self.order_id,\r\n cert_no = self.cert_no,\r\n bank_card_no = self.bank_card_no,\r\n name = self.name,\r\n province = citys[0],\r\n city1 = citys[1],\r\n city2 = citys[2],\r\n city3 = citys[3],\r\n city4 = citys[4],\r\n city5 = citys[5],\r\n create_time = self.time_now,\r\n )\r\n\r\n @db_session\r\n def save_mcc_consume(self, quota):\r\n night_consume_amt_dict = parse_to_dict(quota.get('S0640', ''))\r\n night_consume_times_dict = parse_to_dict(quota.get('S0641', ''))\r\n consume_amt_dict = parse_to_dict(quota.get('S0647', ''))\r\n consume_times_dict = parse_to_dict(quota.get('S0649', ''))\r\n mccs = []\r\n mccs.extend(night_consume_times_dict)\r\n mccs.extend(night_consume_times_dict)\r\n mccs.extend(consume_amt_dict)\r\n mccs.extend(consume_times_dict)\r\n mccs = list(set(mccs))\r\n for mcc in mccs:\r\n BN_MCC_CONSUME(\r\n orderId = self.order_id,\r\n cert_no = self.cert_no,\r\n bank_card_no = self.bank_card_no,\r\n name = self.name,\r\n mcc_code = mcc,\r\n night_consume_amt = night_consume_amt_dict.get(mcc),\r\n night_consume_times = night_consume_times_dict.get(mcc),\r\n consume_amt = consume_amt_dict.get(mcc),\r\n consume_times = consume_times_dict.get(mcc),\r\n create_time = self.time_now,\r\n )\r\n\r\n @db_session\r\n def save_high_freq_mar(self, quota):\r\n data = quota.get('S0149', '')\r\n if data:\r\n company_list = data.split(';')\r\n for em in company_list:\r\n result = re.search(r'([\\D\\d]*)_(\\d+%)', em)\r\n if result:\r\n company = result.group(1)\r\n percent = result.group(2)\r\n BN_HIGH_FREQ_MAR(\r\n orderId = self.order_id,\r\n cert_no = self.cert_no,\r\n bank_card_no = self.bank_card_no,\r\n name = self.name,\r\n mar_name = company,\r\n consume_per = percent_to_float(percent),\r\n create_time = self.time_now,\r\n )\r\n @db_session\r\n def save_top_money_mar(self, quota):\r\n data = quota.get('S0613', '')\r\n mars = data.split(';')\r\n for mar in mars:\r\n if mar:\r\n BN_TOP_MONEY_MAR(\r\n orderId = self.order_id,\r\n cert_no = self.cert_no,\r\n bank_card_no = self.bank_card_no,\r\n name = self.name,\r\n top5_consume_amt_mar = mar,\r\n create_time = self.time_now,\r\n )\r\n\r\n @db_session\r\n def save_consume_city_times(self, quota):\r\n data = quota.get('S0581', '')\r\n data_list = data.split(';')\r\n for em in data_list:\r\n result = re.search(r'(\\d+)_(\\d+)', em)\r\n if result:\r\n city_code = result.group(1)\r\n consume_times = result.group(2)\r\n BN_CONSUME_CITY_TIMES(\r\n orderId = self.order_id,\r\n cert_no = self.cert_no,\r\n bank_card_no = self.bank_card_no,\r\n name = self.name,\r\n city_code = city_code,\r\n consume_times = consume_times,\r\n create_time = self.time_now,\r\n )\r\n" }, { "alpha_fraction": 0.5182335376739502, "alphanum_fraction": 0.5245901346206665, "avg_line_length": 24.201753616333008, "blob_id": "7c7eb432a039cebcb4fc27dec35f28cd1dfad738", "content_id": "fe4980a80cdf6a61fac04d97389287c38da12777", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2989, "license_type": "no_license", "max_line_length": 69, "num_lines": 114, "path": "/tool/utils.py", "repo_name": "wanggn/tableau-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n# coding: utf-8\r\n\r\n\r\nimport json, md5, requests, datetime, re\r\nfrom conf import config\r\nfrom pony.orm import *\r\nfrom model.models import *\r\nfrom datetime import *\r\n\r\n\r\ndef try_int(data):\r\n try:\r\n data = int(data)\r\n except Exception, e:\r\n return None\r\n return data\r\n\r\ndef try_float(data):\r\n try:\r\n data = round(float(data), 2)\r\n except Exception, e:\r\n return None\r\n return data\r\n\r\ndef percent_to_float(data):\r\n try:\r\n data = round(float(data.strip('%'))/100, 3)\r\n except Exception, e:\r\n return None\r\n return data\r\n\r\ndef exact_to_day(time_str):\r\n try:\r\n new_time = datetime.strptime(time_str, \"%Y%m%d\")\r\n except Exception, e:\r\n return None\r\n return new_time\r\n \r\ndef exact_to_month(time_str):\r\n try:\r\n new_time = datetime.strptime(time_str, \"%Y%m\")\r\n except Exception, e:\r\n return None\r\n return new_time\r\n\r\ndef get_db():\r\n db.bind('mysql', host=config.MYSQL_HOST, user=config.MYSQL_USER, \r\n passwd=config.MYSQL_PASSWORD, db=config.DB_NAME\r\n )\r\n return db\r\n\r\ndef parse_to_dict(data, null=True):\r\n ret = {}\r\n try:\r\n data_list = data.split(';')\r\n except Exception, e:\r\n return {}\r\n for em in data_list:\r\n result = re.search(r'([\\D\\d]+)_([\\D\\d]*)', em)\r\n if result:\r\n key = result.group(1)\r\n value = result.group(2)\r\n if not value and null is True:\r\n value = None\r\n ret[key] = value\r\n return ret\r\n\r\n\r\nclass Request_Model(object):\r\n def request_params(self, param_dict):\r\n sign = self._parce_param(param_dict)\r\n param_dict['sign'] = sign\r\n return param_dict\r\n\r\n def _parce_param(self, param_dict):\r\n shabby_str = ''\r\n for key in sorted(param_dict.keys()):\r\n shabby_str += key.encode('utf8') + param_dict[key]\r\n shabby_str += config.PRIVATE_KEY\r\n return self._md5_encrypt(shabby_str)\r\n\r\n def _md5_encrypt(self, shabby_str):\r\n shabby_str=shabby_str.encode('utf8')\r\n md5_str = md5.new()\r\n md5_str.update(shabby_str)\r\n md5_str = md5_str.hexdigest()\r\n return md5_str.upper()\r\n\r\n def request_get(self, url, params):\r\n try:\r\n re = requests.get(url, params=params, verify=False)\r\n except Exception, e:\r\n raise e\r\n return re\r\n \r\n def request_post(self, url, data):\r\n r= requests.post(url, data=data)\r\n return r.url\r\n\r\n\r\nclass Format_Str(object):\r\n\r\n def clean_na(self, data):\r\n for key in data.keys():\r\n if data[key] == 'NA':\r\n data[key] = ''\r\n continue\r\n ems = data[key].split(';')\r\n for index in xrange(len(ems)):\r\n if ems[index] == 'NA':\r\n ems[index] = ''\r\n ems[index] = ems[index].replace('_NA', '_')\r\n data[key] = ';'.join(ems)\r\n\r\n" }, { "alpha_fraction": 0.6339285969734192, "alphanum_fraction": 0.6627303957939148, "avg_line_length": 29.173913955688477, "blob_id": "2cd39b7ea9496cc090c61bd1272e54ec9ffca7e5", "content_id": "9549d7495aac88352d97bf92f882dc6f921080b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3472, "license_type": "no_license", "max_line_length": 45, "num_lines": 115, "path": "/model/models.py", "repo_name": "wanggn/tableau-1", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom datetime import *\nfrom pony.orm import *\nfrom pony import orm\nfrom datetime import datetime\ndb = Database()\n\nclass REQUEST_INFO(db.Entity):\n orderId = Optional(str, 55)\n resCode = Optional(int)\n resMsg = Optional(str, 10)\n statCode = Optional(int)\n statMsg = Optional(str, 55)\n smartOrderId = Optional(str, 55)\n sign = Optional(str, 55)\n request_time = Optional(timedelta)\n parse_time = Optional(timedelta)\n create_time = Optional(datetime)\n update_time = Optional(datetime)\n\n\nclass BN_BASE_STATISTIC_INFO(db.Entity):\n orderId = Optional(str, 55)\n cert_no = Optional(str, 20)\n bank_card_no = Optional(str, 20)\n name = Optional(str, 20)\n card_type = Optional(str, 10)\n card_grade = Optional(str, 10)\n line_consume_amt = Optional(float)\n line_consume_times = Optional(int)\n lastest_consume_date = Optional(datetime)\n dif_city_consume_1h = Optional(int)\n receive_to_transfer_per = Optional(float)\n receive_to_draw_per = Optional(float)\n fir_deal_date = Optional(datetime)\n deal_days = Optional(int)\n deal_grade_in_city = Optional(float)\n work_consume_times_per = Optional(float)\n create_time = Optional(datetime)\n update_time = Optional(datetime)\n\nclass BN_MONTH_CONSUME(db.Entity):\n orderId = Optional(str, 55)\n cert_no = Optional(str, 20)\n bank_card_no = Optional(str, 20)\n name = Optional(str, 20)\n month = Optional(datetime)\n work_consume_amt = Optional(float)\n deal_consume_amt = Optional(float)\n deal_consume_times = Optional(int)\n deal_bank_amt = Optional(float)\n deal_bank_times = Optional(int)\n create_time = Optional(datetime)\n update_time = Optional(datetime)\n\n\nclass BN_LIVE_CITY(db.Entity):\n orderId = Optional(str, 55)\n cert_no = Optional(str, 20)\n bank_card_no = Optional(str, 20)\n name = Optional(str, 20)\n province = Optional(str, 20)\n city1 = Optional(str, 20)\n city2 = Optional(str, 20)\n city3 = Optional(str, 20)\n city4 = Optional(str, 20)\n city5 = Optional(str, 20)\n create_time = Optional(datetime)\n update_time = Optional(datetime)\n\n\nclass BN_MCC_CONSUME(db.Entity):\n orderId = Optional(str, 55)\n cert_no = Optional(str, 20)\n bank_card_no = Optional(str, 20)\n name = Optional(str, 20)\n mcc_code = Optional(str, 10)\n night_consume_amt = Optional(float)\n night_consume_times = Optional(int)\n consume_amt = Optional(float)\n consume_times = Optional(int)\n create_time = Optional(datetime)\n update_time = Optional(datetime)\n\n\nclass BN_HIGH_FREQ_MAR(db.Entity):\n orderId = Optional(str, 55)\n cert_no = Optional(str, 20)\n bank_card_no = Optional(str, 20)\n name = Optional(str, 20)\n mar_name = Optional(str, 255)\n consume_per = Optional(float)\n create_time = Optional(datetime)\n update_time = Optional(datetime)\n\n\nclass BN_TOP_MONEY_MAR(db.Entity):\n orderId = Optional(str, 55)\n cert_no = Optional(str, 20)\n bank_card_no = Optional(str, 20)\n name = Optional(str, 20)\n top5_consume_amt_mar = Optional(str, 255)\n create_time = Optional(datetime)\n update_time = Optional(datetime)\n\n\nclass BN_CONSUME_CITY_TIMES(db.Entity):\n orderId = Optional(str, 55)\n cert_no = Optional(str, 20)\n bank_card_no = Optional(str, 20)\n name = Optional(str, 20)\n city_code = Optional(str, 10)\n consume_times = Optional(int)\n create_time = Optional(datetime)\n update_time = Optional(datetime)\n\n\n" }, { "alpha_fraction": 0.617977499961853, "alphanum_fraction": 0.6292135119438171, "avg_line_length": 11.714285850524902, "blob_id": "ddd66c579671c961417c1a79d3b7cbb221223d13", "content_id": "dd7535f1c6f2f9866e11fdd984a8b1efec645562", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 89, "license_type": "no_license", "max_line_length": 30, "num_lines": 7, "path": "/queryapi/urls.py", "repo_name": "wanggn/tableau-1", "src_encoding": "UTF-8", "text": "# coding=utf-8\n\nfrom views import TestHandler\n\nURLS = [\n (r\"/test/$\", TestHandler),\n]\n" }, { "alpha_fraction": 0.7013888955116272, "alphanum_fraction": 0.7083333134651184, "avg_line_length": 17, "blob_id": "045725e888c16a5b8e659ae27c148b3858a94ebd", "content_id": "ac0277020afe89d7af8e6f6eba334d5391d8f8d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 144, "license_type": "no_license", "max_line_length": 38, "num_lines": 8, "path": "/queryapi/views.py", "repo_name": "wanggn/tableau-1", "src_encoding": "UTF-8", "text": "# coding=utf-8\n\nfrom tornado.web import RequestHandler\n\n\nclass TestHandler(RequestHandler):\n def get(self):\n self.write(\"hello word\")\n" }, { "alpha_fraction": 0.5081737637519836, "alphanum_fraction": 0.5161139369010925, "avg_line_length": 24.085365295410156, "blob_id": "d7756bc21e21dae9e0a8fd32aea53bedb46a02fb", "content_id": "a63913e42abfd567470e29d4802d48abca9e3dee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2141, "license_type": "no_license", "max_line_length": 62, "num_lines": 82, "path": "/tool/utils.py~", "repo_name": "wanggn/tableau-1", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n# coding: utf-8\r\n\r\n\r\nimport json, md5, requests, datetime\r\nfrom conf import config\r\nfrom pony.orm import *\r\nfrom datetime import *\r\n\r\n\r\ndef try_int(data):\r\n try:\r\n data = int(data)\r\n except Exception, e:\r\n return ''\r\n return data\r\n\r\ndef try_float(data):\r\n try:\r\n data = round(float(data), 2)\r\n except Exception, e:\r\n return ''\r\n return data\r\n\r\ndef percent_to_float(data):\r\n try:\r\n data = round(float(data.strip('%'))/100, 3)\r\n except Exception, e:\r\n return ''\r\n return data\r\n\r\ndef exact_to_day(time_str):\r\n try:\r\n new_time = datetime.strptime(time_str, \"%Y%m%d\")\r\n except Exception, e:\r\n return ''\r\n return new_time\r\n \r\ndef exact_to_month(time_str):\r\n try:\r\n new_time = datetime.strptime(time_str, \"%Y%m\")\r\n except Exception, e:\r\n return ''\r\n return new_time\r\n\r\nclass Build_Url(object):\r\n def request_url(self, param_dict):\r\n url = config.DOMAIN + config.USER_DATA\r\n for key, val in param_dict.items():\r\n url += key + '=' + val + '&'\r\n sign = self.parce_param(param_dict)\r\n url += 'sign' + '=' + sign\r\n return url\r\n\r\n def parce_param(self, param_dict):\r\n shabby_str = ''\r\n for key in sorted(param_dict.keys()):\r\n shabby_str += key.encode('utf8') + param_dict[key]\r\n shabby_str += config.PRIVATE_KEY\r\n return self.md5_encrypt(shabby_str)\r\n\r\n def md5_encrypt(self, shabby_str):\r\n shabby_str=shabby_str.encode('utf8')\r\n md5_str = md5.new()\r\n md5_str.update(shabby_str)\r\n md5_str = md5_str.hexdigest()\r\n return md5_str.upper()\r\n\r\n\r\nclass Format_Str(object):\r\n\r\n def clean_na(data):\r\n for key in data.keys():\r\n if data[key] == 'NA':\r\n data[key] = ''\r\n continue\r\n ems = data[key].split(';')\r\n for index in xrange(len(ems)):\r\n if ems[index] == 'NA':\r\n ems[index] = ''\r\n ems[index] = ems[index].replace('_NA', '_')\r\n data[key] = ';'.join(ems)\r\n\r\n" }, { "alpha_fraction": 0.474303662776947, "alphanum_fraction": 0.5096116065979004, "avg_line_length": 30.653846740722656, "blob_id": "aee63185438587e1f5cf70d99bf9719f6f0ea320", "content_id": "efb4f0541fa8b4a8d16b6b97dd4e9bcde32a7b89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2553, "license_type": "no_license", "max_line_length": 114, "num_lines": 78, "path": "/torn.py", "repo_name": "wanggn/tableau-1", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\r\nfrom tornado import (\r\n ioloop,\r\n web,\r\n httpserver\r\n )\r\nimport json, md5, requests, datetime, re\r\nfrom conf import config\r\nfrom pony.orm import *\r\nfrom model.models import *\r\nfrom ylzh.ylzh import Pylzh_Process\r\nfrom tornado.concurrent import run_on_executor\r\nfrom concurrent.futures import ThreadPoolExecutor\r\nimport tornado.httpserver\r\nfrom queryapi.urls import URLS as urls\r\nfrom tool.utils import get_db\r\n\r\nclass MainHandler(web.RequestHandler):\r\n executor = ThreadPoolExecutor(30)\r\n\r\n def initialize(self):\r\n self.ylzh_process = Pylzh_Process()\r\n \r\n @tornado.web.asynchronous\r\n @tornado.gen.coroutine\r\n def get(self):\r\n #ram_data = {\r\n # 'account': config.ACCOUNT,\r\n # 'orderId': 'byjr_8ad22395309a120530c6e12a20260',\r\n # 'card': '6222629530002562008',\r\n # 'identityCard': '410422199003197012',\r\n # 'identityType': '001',\r\n # 'index': 'all',\r\n # 'mobile': '18625708694',\r\n # 'name': 'du培源'\r\n #}\r\n #json_data = json.dumps(ram_data)\r\n #self.ylzh_proc(json_data)\r\n for line in open('data.txt', 'r'):\r\n if line.strip():\r\n srt = re.match(r'\"([\\D\\d]+)\"\\t\"([\\D\\d]+)\"\\t\"([\\D\\d]+)\"\\t\"([\\D\\d]+)\"\\t\"([\\D\\d]+)\"\\t', line.strip())\r\n try:\r\n ram_data = {\r\n 'account': config.ACCOUNT,\r\n 'orderId': 'byjr_'+srt.group(1),\r\n 'card': srt.group(2),\r\n 'index': 'all',\r\n 'identityCard': srt.group(4),\r\n 'identityType': '001',\r\n 'mobile': srt.group(5),\r\n 'name': srt.group(3),\r\n }\r\n except Exception, e:\r\n continue\r\n json_data = json.dumps(ram_data)\r\n self.ylzh_proc(json_data)\r\n \r\n \r\n @run_on_executor\r\n def ylzh_proc(self, json_data):\r\n res = self.ylzh_process.request_data(json_data)\r\n\r\n\t\t\t\r\nif __name__ == \"__main__\":\r\n settings = {\r\n 'debug': True\r\n }\r\n # URLS is belong to queryapi\r\n urls.append((r\"/\", MainHandler))\r\n app = web.Application(urls, **settings)\r\n db = get_db()\r\n db.generate_mapping(create_tables=True)\r\n app.listen(8888)\r\n ioloop.IOLoop.instance().start()\r\n server = httpserver.HTTPServer(app)\r\n server.bind(config.SERVER_PORT)\r\n server.start(config.SERVER_NUM)\r\n\r\n" } ]
8
dbddqy/machine_perception
https://github.com/dbddqy/machine_perception
93270c3b56092e20cd77197fb2aa6c7c2839119b
6864794806e42923b130052b03f800473f3752d9
621d7a83e3549b0570b2b7dde4ec6a985f1bd22c
refs/heads/master
2021-07-07T09:22:53.152889
2020-11-30T19:09:14
2020-11-30T19:09:14
212,831,797
2
0
null
2019-10-04T14:18:16
2019-10-04T20:21:55
2019-10-04T20:34:27
Python
[ { "alpha_fraction": 0.5982142686843872, "alphanum_fraction": 0.6105769276618958, "avg_line_length": 28.1200008392334, "blob_id": "4447af5d32714838a4d6b71187d50e73dadf8fdc", "content_id": "057ce7c75530c61fa825db05a15d77b05b6bd63a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1456, "license_type": "no_license", "max_line_length": 110, "num_lines": 50, "path": "/demo4.1_tracking/web/catkin_ws/src/web/src/f_scan.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "#include \"lib.h\"\n#include <std_msgs/Float32.h>\n\n#define F_STATE 4\n\nMat imgCallback;\nbool RECEIVED = false;\n\nstatic void ImageCallback(const sensor_msgs::CompressedImageConstPtr &msg) {\n try {\n cv_bridge::CvImagePtr cv_ptr_compressed = cv_bridge::toCvCopy(msg,sensor_msgs::image_encodings::BGR8);\n imgCallback = cv_ptr_compressed->image;\n RECEIVED = true;\n } catch (cv_bridge::Exception& e){ }\n}\n\nint main(int argc, char **argv) {\n // // window setting\n // namedWindow(\"imgCallback\", 0);\n // cvResizeWindow(\"imgCallback\", 960, 540);\n\n // ros init\n ros::init(argc, argv, \"f_scan\");\n ros::NodeHandle nh;\n\n // sub\n ros::Subscriber image_sub = nh.subscribe(\"rs_color/compressed\", 10, ImageCallback);\n \n // pub\n image_transport::ImageTransport it(nh);\n image_transport::Publisher pub = it.advertise(\"img\", 1);\n\n ros::Rate loop_rate(10);\n while (ros::ok()) {\n // check state\n if (!checkState(F_STATE)) { loop_rate.sleep(); continue; }\n // check if image received\n if (!RECEIVED) { ros::spinOnce(); loop_rate.sleep(); continue; }\n // INFO received\n ROS_INFO(\"cv_ptr_compressed: %d * %d \", imgCallback.cols, imgCallback.rows);\n\n // pub\n sensor_msgs::ImagePtr msg = cv_bridge::CvImage(std_msgs::Header(), \"bgr8\", imgCallback).toImageMsg();\n pub.publish(msg);\n\n ros::spinOnce();\n loop_rate.sleep();\n }\n return 0;\n}\n" }, { "alpha_fraction": 0.8015872836112976, "alphanum_fraction": 0.8015872836112976, "avg_line_length": 59, "blob_id": "42ac30723cfa0d4d8aa37f798bdb2d47981ada5c", "content_id": "c70a61d280f48a6c8e1f411fc21fc6db40871541", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 126, "license_type": "no_license", "max_line_length": 98, "num_lines": 2, "path": "/README.md", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "# machine_perception\r\nFilament fabrication process with a closed-loop control robotic system utilizing computer vision\r\n\r\n\r\n" }, { "alpha_fraction": 0.4621241092681885, "alphanum_fraction": 0.5481537580490112, "avg_line_length": 31.850000381469727, "blob_id": "6ff4b38d998db031adf2468bb4396ab4b7c98fee", "content_id": "b5e25d8f1085d449fe3b2af065ce2233a81a9d55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2627, "license_type": "no_license", "max_line_length": 101, "num_lines": 80, "path": "/demo4.1_tracking/web/catkin_ws/src/web/src/lib.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "#include \"lib.h\"\n\nCameraConfig::CameraConfig() {\n M = (Mat_<double>(3, 3)\n << 1382.23, 0., 953.567\n , 0., 1379.46, 532.635\n , 0., 0., 1.);\n distortion = (Mat_<double >(1, 5)\n << 0.0, 0.0, 0.0, 0.0, 0.0);\n MExt = (Mat_<double>(3, 4)\n << 1382.23, 0., 953.567, 0.\n , 0., 1379.46, 532.635, 0.\n , 0., 0., 1., 0.);\n MInv = M.inv();\n fx = 1382.23; fy = 1379.46; cx = 953.567; cy = 532.635;\n}\n\nbool checkState(int f_state) {\n int state;\n ros::param::get(\"f_state\", state);\n return (state == f_state);\n}\n\ndouble **readData(string path, int row, int col) {\n ifstream file;\n file.open(path, ios::in);\n double **data = new double*[row];\n for (int i = 0; i < row; ++i) {\n data[i] = new double[col];\n for (int j = 0; j < col; ++j)\n file >> data[i][j];\n }\n file.close();\n return data;\n}\n\nint findIndex(vector<int> indices, int index) {\n vector <int>::iterator iElement = find(indices.begin(), indices.end(), index);\n if( iElement != indices.end() ) {\n return distance(indices.begin(),iElement);\n } else {\n return -1;\n }\n}\n\nEigen::Vector4d getCorner(int index, double size) {\n switch (index) {\n case 0: return Eigen::Vector4d(-0.5*size, 0.5*size, 0.0, 1.0);\n case 1: return Eigen::Vector4d(0.5*size, 0.5*size, 0.0, 1.0);\n case 2: return Eigen::Vector4d(0.5*size, -0.5*size, 0.0, 1.0);\n case 3: return Eigen::Vector4d(-0.5*size, -0.5*size, 0.0, 1.0);\n }\n}\n\nMat readPose() {\n vector<double> data_c2w;\n ros::param::get(\"c2w\", data_c2w);\n Vec3d rvec(data_c2w[0], data_c2w[1], data_c2w[2]);\n Vec3d tvec(data_c2w[3], data_c2w[4], data_c2w[5]);\n Mat r, c2w;\n Rodrigues(rvec, r);\n hconcat(r, tvec*1000.0, c2w);\n Mat down = (Mat_<double>(1, 4) << 0., 0., 0., 1.);\n vconcat(c2w, down, c2w);\n return c2w;\n}\n\ndouble dis(Vec3d p1, Vec3d p2) {\n return sqrt((p1[0]-p2[0])*(p1[0]-p2[0])+(p1[1]-p2[1])*(p1[1]-p2[1])+(p1[2]-p2[2])*(p1[2]-p2[2]));\n}\n\ndouble distance2cylinder(double *cylinder_param, Vec3d pt, double start_param, double end_param) {\n Vec3d start(cylinder_param[1], cylinder_param[2], cylinder_param[3]);\n Vec3d dir(cylinder_param[4], cylinder_param[5], cylinder_param[6]);\n Vec3d p_start = start + start_param * dir;\n Vec3d p_end = start + end_param * dir;\n if ((pt-p_start).dot(dir) < 0) return 0; // 0: not in the segment\n if ((p_end-pt).dot(dir) < 0) return 0; // 0: not in the segment\n return sqrt((pt-p_start).dot(pt-p_start)-pow((pt-p_start).dot(dir), 2)) - cylinder_param[0];\n}" }, { "alpha_fraction": 0.4834710657596588, "alphanum_fraction": 0.5233175754547119, "avg_line_length": 37.4886360168457, "blob_id": "3c0ad4084b572653a4d9b48f9693825330371865", "content_id": "329b51cf3e8b815f3a77675abb0b6513f58838f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3388, "license_type": "no_license", "max_line_length": 113, "num_lines": 88, "path": "/demo2.2_detect_cylinder/detection_rgbd/lib/vision.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 31.01.20.\n//\n\n#include <vision.hpp>\n#include <opencv2/aruco.hpp>\n\nCameraConfig::CameraConfig() {\n M = (Mat_<double>(3, 3)\n << 1382.23, 0., 953.567\n , 0., 1379.46, 532.635\n , 0., 0., 1.);\n distortion = (Mat_<double>(1, 5)\n << 0.0, 0.0, 0.0, 0.0, 0.0);\n MInv = M.inv();\n fx = 1382.23; fy = 1379.46; cx = 953.567; cy = 532.635;\n}\n\nvoid detectAruco(Mat img, vector<pose> &poses, vector<vector<Point2f> > &markerCorners, vector<int> &markerIds) {\n vector<vector<cv::Point2f>> rejectedCandidates;\n cv::Ptr<cv::aruco::DetectorParameters> parameters = cv::aruco::DetectorParameters::create();\n cv::Ptr<cv::aruco::Dictionary> dictionary = cv::aruco::generateCustomDictionary(10, 6);\n\n cv::aruco::detectMarkers(img, dictionary, markerCorners, markerIds, parameters, rejectedCandidates);\n cv::aruco::drawDetectedMarkers(img, markerCorners, markerIds);\n// imshow(\"aruco\", img);\n if (markerIds.size() != 2) return;\n\n vector<cv::Vec3d> rvecs, tvecs;\n cv::aruco::estimatePoseSingleMarkers(markerCorners, 0.015, C.M, C.distortion, rvecs, tvecs);\n for (int i = 0; i < rvecs.size(); ++i) {\n auto rvec = rvecs[i];\n auto tvec = tvecs[i];\n// cv::aruco::drawAxis(img, C.M, C.distortion, rvec, tvec, 0.015);\n pose pose(tvec, rvec);\n poses.push_back(pose);\n }\n}\n\nvoid grow(cv::Mat& src, cv::Mat& mask, cv::Point seed, int threshold) {\n /* apply \"seed grow\" in a given seed\n * Params:\n * src: source image\n * dest: a matrix records which pixels are determined/undtermined/ignored\n * mask: a matrix records the region found in current \"seed grow\"\n */\n const cv::Point PointShift2D[4] =\n {\n cv::Point(1, 0),\n cv::Point(0, -1),\n cv::Point(-1, 0),\n cv::Point(0, 1),\n };\n\n stack<cv::Point> point_stack;\n point_stack.push(seed);\n\n while(!point_stack.empty()) {\n cv::Point center = point_stack.top();\n mask.at<uchar>(center) = 1;\n point_stack.pop();\n\n for (int i=0; i<4; ++i) {\n cv::Point estimating_point = center + PointShift2D[i];\n if (estimating_point.x < 0\n || estimating_point.x > src.cols-1\n || estimating_point.y < 0\n || estimating_point.y > src.rows-1) {\n // estimating_point should not out of the range in image\n continue;\n } else {\n int delta=0;\n if (src.type() == CV_16U)\n delta = (int)abs(src.at<uint16_t>(center) - src.at<uint16_t>(estimating_point));\n // delta = (R-R')^2 + (G-G')^2 + (B-B')^2\n else\n delta = int(pow(src.at<cv::Vec3b>(center)[0] - src.at<cv::Vec3b>(estimating_point)[0], 2)\n + pow(src.at<cv::Vec3b>(center)[1] - src.at<cv::Vec3b>(estimating_point)[1], 2)\n + pow(src.at<cv::Vec3b>(center)[2] - src.at<cv::Vec3b>(estimating_point)[2], 2));\n if (mask.at<uchar>(estimating_point) == 0\n && delta < threshold) {\n mask.at<uchar>(estimating_point) = 1;\n point_stack.push(estimating_point);\n }\n }\n }\n }\n}\n\n" }, { "alpha_fraction": 0.4629707932472229, "alphanum_fraction": 0.5526872873306274, "avg_line_length": 39.39316177368164, "blob_id": "c6c787f446f6fd6fe1037231489d599c35bf7499", "content_id": "f66d404754e67c33c7c2396716a3c9e6e568630e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4726, "license_type": "no_license", "max_line_length": 137, "num_lines": 117, "path": "/demo2.2_detect_cylinder/detection_2.0/combine_cloud.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 23.02.20.\n//\n\n#include <iostream>\n#include <fstream>\n#include <boost/format.hpp> // for formating strings\n\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n#include <pcl/filters/statistical_outlier_removal.h>\n#include <pcl/common/transforms.h>\n#include <pcl/registration/icp.h>\n\ntypedef pcl::PointXYZRGB PointC;\ntypedef pcl::PointXYZ PointG;\ntypedef pcl::PointCloud<PointC>::Ptr PointCloudC;\ntypedef pcl::PointCloud<PointG>::Ptr PointCloudG;\n\nusing namespace std;\n\npcl::PCDReader reader;\npcl::PCDWriter writer;\npcl::StatisticalOutlierRemoval<PointG> sor;\n\nconst int COUNT = 11;\n\nint main(int argc, char **argv) {\n // e2c transformation\n double t[3] = {-0.0153632, 0.042317, 0.139266};\n double r[9] = {-0.000174572, -1, -0.000177886, 0.999979, -0.000175714, 0.00644069, -0.00644072, -0.000176758, 0.999979};\n Eigen::Matrix4d e2c;\n e2c << r[0], r[3], r[6], t[0],\n r[1], r[4], r[7], t[1],\n r[2], r[5], r[8], t[2],\n 0.0, 0.0, 0.0, 1.0;\n // w2e transformation\n ifstream file;\n file.open(\"../test_data/data_4/robot_pose.txt\", ios::in); // KUKA X Y Z A B C (in mm, degree)\n vector<Eigen::Matrix4d> w2e;\n for (int i = 0; i < COUNT; ++i) {\n double data[6];\n for (auto& d : data)\n file >> d;\n Eigen::Quaterniond q = Eigen::AngleAxisd(data[3]*M_PI/180.0, Eigen::Vector3d::UnitZ())\n * Eigen::AngleAxisd(data[4]*M_PI/180.0, Eigen::Vector3d::UnitY())\n * Eigen::AngleAxisd(data[5]*M_PI/180.0, Eigen::Vector3d::UnitX());\n Eigen::Isometry3d T(q);\n T.pretranslate(Eigen::Vector3d(data[0]/1000.0, data[1]/1000.0, data[2]/1000.0));\n w2e.push_back(T.matrix());\n }\n file.close();\n // cylinder params\n// double cylinder[7] = {1.62165, -0.09601, 0.17847, 0.0, 1.0, 0.0, 0.0158};\n double cylinder[7] = {0.05423, -2.47415, 1.32664, 0.0, 1.0, 0.0, 0.0158}; // 2cut\n// double cylinder[7] = {1.68594, 0.5306, 0.24832, 0.55457148246, 0.83183737076, -0.02229482977, 0.018685}; //No.2\n// double cylinder[7] = {1.61857, 0.7942, 0.29441, 0.91515029888, -0.26184958961, -0.30648772059, 0.019085}; //No.3\n\n PointCloudG cloud_combined (new pcl::PointCloud<PointG>);\n for (int i = 0; i < COUNT; ++i) {\n PointCloudG cloud_c (new pcl::PointCloud<PointG>);\n boost::format fmt( \"../test_data/data_4/cloud_full0%d.pcd\" );\n reader.read ((fmt%i).str(), *cloud_c);\n\n double min_dis = 999999999.0;\n double max_dis = 0.0;\n PointCloudG cloud_cylinder (new pcl::PointCloud<PointG>);\n for (int j=0; j < cloud_c->points.size(); j++) {\n Eigen::Vector4d p_c;\n p_c << cloud_c->points[j].x, cloud_c->points[j].y, cloud_c->points[j].z, 1.0;\n Eigen::Vector4d p = w2e[i] * e2c * p_c;\n double dis = sqrt((p[0]-cylinder[0]) * (p[0]-cylinder[0])\n + (p[1]-cylinder[1]) * (p[1]-cylinder[1])\n + (p[2]-cylinder[2]) * (p[2]-cylinder[2])\n - pow((p[0]-cylinder[0])*cylinder[3] + (p[1]-cylinder[1])*cylinder[4] + (p[2]-cylinder[2])*cylinder[5], 2))\n - cylinder[6];\n if (dis < min_dis)\n min_dis = dis;\n if (dis > max_dis)\n max_dis = dis;\n if (abs(dis) < 0.5) {\n cloud_combined->points.push_back(cloud_c->points[j]);\n// PointG p2append;\n// p2append.x = p[0]; p2append.y = p[1]; p2append.z = p[2];\n// cloud_combined->points.push_back(p2append);\n }\n }\n cout << \"min: \" << min_dis << endl;\n cout << \"max: \" << max_dis << endl;\n }\n\n// cloud_merged = clouds[0];\n// pcl::IterativeClosestPoint<PointG, PointG> icp;\n// cout << \"cloud 0: \" << clouds[0]->points.size() << endl;\n// for (int i = 1; i < COUNT; ++i) {\n// cout << \"cloud \" << i << \": \" << clouds[i]->points.size() << endl;\n// icp.setInputSource(clouds[i]);\n// icp.setInputTarget(cloud_merged);\n// pcl::PointCloud<PointG> final;\n// icp.align(final);\n// *cloud_merged += final;\n// }\n// cout << icp.getFinalTransformation() << endl;\n\n // remove outliers\n// sor.setInputCloud (cloud_merged);\n// sor.setMeanK (5);\n// sor.setStddevMulThresh (0.5);\n// sor.filter (*cloud_merged);\n\n cloud_combined->width = cloud_combined->points.size();\n cloud_combined->height = 1;\n cloud_combined->resize(cloud_combined->width * cloud_combined->height);\n writer.write (\"../test_data/data_4/cloud_combined.pcd\", *cloud_combined, false);\n return 0;\n}\n" }, { "alpha_fraction": 0.6234042644500732, "alphanum_fraction": 0.6702127456665039, "avg_line_length": 17.799999237060547, "blob_id": "3dc01a06e0e7e6b37eda15948e82fab31d46066e", "content_id": "4043daf774611693d6c5f810968a5770c592d4a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 470, "license_type": "no_license", "max_line_length": 61, "num_lines": 25, "path": "/demo5.1_final/detection/lib/header/lib_rs.hpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 22.09.20.\n//\n\n#ifndef DETECTION_LIB_RS_HPP\n#define DETECTION_LIB_RS_HPP\n\n#include <librealsense2/rs.hpp>\n#include <librealsense2/rs_advanced_mode.hpp>\n\n#include <opencv2/opencv.hpp>\n\nclass D415 {\npublic:\n D415();\n ~D415();\n void receive_frame(cv::Mat & color, cv::Mat & depth);\n void print_intrinsics();\n\nprivate:\n rs2::pipeline pipe;\n rs2::align align_to_color = rs2::align(RS2_STREAM_COLOR);\n};\n\n#endif //DETECTION_LIB_RS_HPP\n" }, { "alpha_fraction": 0.7314049601554871, "alphanum_fraction": 0.7314049601554871, "avg_line_length": 11.684210777282715, "blob_id": "f6354f3c18475c1ca74a0d10189740a02e4c19b9", "content_id": "022884e786661bdd003003a0ea9dfff6a0be00b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 242, "license_type": "no_license", "max_line_length": 53, "num_lines": 19, "path": "/demo4.1_tracking/web/note.md", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "# Web Interface for Augmented Assembly\n\nRosbridge\n\n```\nroslaunch rosbridge_server rosbridge_websocket.launch\n```\n\nWeb video server\n\n```\nrosrun web_video_server web_video_server\n```\n\nWeb node for publishing /img topic\n\n```\nrosrun web web\n```\n\n" }, { "alpha_fraction": 0.521785318851471, "alphanum_fraction": 0.5536662936210632, "avg_line_length": 28.375, "blob_id": "bd059844f856e310b219f30fe3e2f9c792e48716", "content_id": "65a56eeaef6a5fab5bc8b64c70e070e96fc33462", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 941, "license_type": "no_license", "max_line_length": 125, "num_lines": 32, "path": "/demo2.2_detect_cylinder/detection_rgbd/src/takeFrameKinect.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 26.01.20.\n//\n\n#include <iostream>\n#include <boost/format.hpp> // for formating strings\n#include <kinect.hpp>\n\nusing namespace std;\nusing namespace cv;\n\nint main() {\n kinectInit();\n int count = 0;\n while (waitKey(1) != 27) {\n getFrame();\n imshow(\"bgrd\", *matBGRD);\n imshow(\"depth\", *matDepth / 4500.0f);\n if (waitKey(1) == 'q') {\n imwrite((boost::format(\"../../data/color/color_%d.png\")%count).str(), *matBGRD);\n Mat depth = matDepth->clone();\n Mat matDepth16 = Mat::zeros(depth.size(), CV_16UC1);\n depth.convertTo(matDepth16, CV_16UC1);\n imwrite((boost::format(\"../../data/depth/depth_%d.png\")%count).str(), matDepth16);\n\n pcl::io::savePCDFileBinary((boost::format(\"../../data/point_cloud/cloud_%d.pcd\")%count).str(), *getPointCloud());\n count += 1;\n }\n }\n kinectClose();\n return 0;\n}\n\n" }, { "alpha_fraction": 0.6954314708709717, "alphanum_fraction": 0.7258883118629456, "avg_line_length": 13.071428298950195, "blob_id": "220250d1aa95b6bda0e39479e6821e9152a08079", "content_id": "1003d1fe799a930de49188efcf704e95b0a27b66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 197, "license_type": "no_license", "max_line_length": 35, "num_lines": 14, "path": "/demo5.1_final/detection/lib/header/lib_geometry.hpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 23.09.20.\n//\n\n#ifndef DETECTION_LIB_GEOMETRY_HPP\n#define DETECTION_LIB_GEOMETRY_HPP\n\n#include <Eigen/Geometry>\n\nnamespace geometry {\n\n}\n\n#endif //DETECTION_LIB_GEOMETRY_HPP\n" }, { "alpha_fraction": 0.7789473533630371, "alphanum_fraction": 0.800000011920929, "avg_line_length": 46.5, "blob_id": "1d29143a42a557a23d939d0cbec1dfe2acd624b5", "content_id": "5bdc7bff7d788484d2add230141d2abde64b7b4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 95, "license_type": "no_license", "max_line_length": 59, "num_lines": 2, "path": "/demo3.1_validate_in_process_scan/README.md", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "# demo3.1_validate_in_process_scan\nCompare in-process scan with one-time scan in the beginning\n" }, { "alpha_fraction": 0.5028675198554993, "alphanum_fraction": 0.5463326573371887, "avg_line_length": 38.44047546386719, "blob_id": "339f6d69a1a3d14bc3ca2553156383ad0703fed0", "content_id": "c00c2868a144f2a1e3b483278301d89a2193c305", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3313, "license_type": "no_license", "max_line_length": 92, "num_lines": 84, "path": "/workshop/DNN_classification/main.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "from NeuralNetwork import *\nfrom matplotlib import pyplot as plt\n\n\ndef generate_data(n, p=0.8):\n # p: percentage of data for training\n x11 = np.random.multivariate_normal([4., 3.], [[4., 0.], [0., 1.]], int(0.5*n))\n x12 = np.random.multivariate_normal([2., -2.], [[1., 0.], [0., 2.]], int(0.25*n))\n x13 = np.random.multivariate_normal([7., -4.], [[1., 0.], [0., 1.]], int(0.25*n))\n x1 = np.vstack((x11, x12, x13))\n plt.scatter(x1.T[0], x1.T[1], color=\"red\")\n x2 = np.random.multivariate_normal([6., 0.], [[1.5, 0.5], [0.5, 1.5]], n)\n plt.scatter(x2.T[0], x2.T[1], color=\"blue\")\n # combine data\n x = np.vstack((x1, x2))\n y = np.asarray([[1., 0.]] * n + [[0., 1.]] * n)\n # shuffle data\n shuffle_idx = np.arange(0, n*2)\n np.random.shuffle(shuffle_idx)\n x_shuffled = x[shuffle_idx]\n y_shuffled = y[shuffle_idx]\n # split data into training and testing\n _x_train = x_shuffled[0:int(n * p)*2]\n _y_train = y_shuffled[0:int(n * p)*2]\n _x_test = x_shuffled[int(n * p)*2:n*2]\n _y_test = y_shuffled[int(n * p)*2:n*2]\n return _x_train, _y_train, _x_test, _y_test\n\n\ndef error_rate(_x, _y, _dnn):\n error_count = 0\n for i in range(len(_x)):\n if (_dnn.model(_x[i:i+1].T)[-1][0][0] > 0.5) and _y[i][0] == 0:\n error_count += 1\n if (_dnn.model(_x[i:i+1].T)[-1][0][0] < 0.5) and _y[i][0] == 1:\n error_count += 1\n return error_count / len(_x)\n\n\ndef train(_x, _y, _dnn, lr=1e-5, steps=1000):\n global x_test, y_test\n # using adagrad\n grad_w_sum_square, grad_b_sum_square = [], []\n for i in range(len(_dnn.Ws)):\n grad_w_sum_square.append(np.zeros(_dnn.Ws[i].shape))\n grad_b_sum_square.append(np.zeros(_dnn.Bs[i].shape))\n for step in range(steps):\n grad_w, grad_b = _dnn.gradient(_x, _y, d_loss_f=d_cross_entropy)\n for i in range(len(_dnn.Ws)):\n grad_w_sum_square[i] += grad_w[i] ** 2\n grad_b_sum_square[i] += grad_b[i] ** 2\n _dnn.Ws[i] -= grad_w[i] * lr / (np.sqrt(grad_w_sum_square[i])+1e-9)\n _dnn.Bs[i] -= grad_b[i] * lr / (np.sqrt(grad_b_sum_square[i])+1e-9)\n # print log\n if step % 100 == 0:\n print(\"step: %d, training error rate: %f, testing error rate: %f\"\n % (step, error_rate(_x, _y, _dnn), error_rate(x_test, y_test, _dnn)))\n\n\ndef plot_boundary(_dnn, _color):\n x_plot = np.arange(-2., 10., .1)\n y_plot = np.arange(-6., 6., .1)\n x_plot, y_plot = np.meshgrid(x_plot, y_plot)\n f = np.zeros(x_plot.shape)\n for i in range(x_plot.shape[0]):\n for j in range(x_plot.shape[1]):\n f[i][j] = _dnn.model(np.array([[x_plot[i][j]], [y_plot[i][j]]]))[-1][0][0] - 0.5\n plt.contour(x_plot, y_plot, f, 0, colors=_color)\n\n\nif __name__ == \"__main__\":\n x_train, y_train, x_test, y_test = generate_data(100)\n dnn = NeuralNetwork(2)\n for _ in range(2):\n dnn.add_dense_layer(100, activation=sigmoid, d_activation=d_sigmoid)\n dnn.add_dense_layer(2, activation=softmax, d_activation=d_softmax)\n # plot boundary before training\n plot_boundary(dnn, \"orange\")\n # training\n # print(dnn.model(x_train[6:7].T)[-1])\n train(x_train, y_train, dnn, lr=5e-4, steps=1000)\n # plot boundary after training\n plot_boundary(dnn, \"lightblue\")\n plt.show()\n" }, { "alpha_fraction": 0.7603978514671326, "alphanum_fraction": 0.7748643755912781, "avg_line_length": 27.35897445678711, "blob_id": "9ad5646296bf3a236f76799d29b7f9f94d487d45", "content_id": "08834b816c5b4391f3b5bc30e2946ae84eb4d7a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1106, "license_type": "no_license", "max_line_length": 58, "num_lines": 39, "path": "/demo2.2_detect_cylinder/detection_rgbd/CMakeLists.txt", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "project (cylinder_RGBD)\nset(CMAKE_CXX_FLAGS \"-std=c++14 -O3\")\ncmake_minimum_required(VERSION 3.15)\n\nlist(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake)\n\nfind_package(realsense2 REQUIRED)\n\nfind_package(OpenCV REQUIRED)\ninclude_directories(${OpenCV_INCLUDE_DIRS})\n\nfind_package(Eigen3 REQUIRED)\ninclude_directories(${Eigen3_INCLUDE_DIRS})\n\nfind_package(freenect2 REQUIRED)\ninclude_directories(${freenect2_INCLUDE_DIRS})\n\nfind_package(Ceres REQUIRED)\ninclude_directories(${CERES_INCLUDE_DIRS})\n\n#find_package( PCL REQUIRED COMPONENT common io )\n#include_directories( ${PCL_INCLUDE_DIRS} )\n#list(REMOVE_ITEM PCL_LIBRARIES \"vtkproj4\")\n#add_definitions( ${PCL_DEFINITIONS} )\n\nfind_package(PCL 1.2 REQUIRED)\n\ninclude_directories(${PCL_INCLUDE_DIRS})\nlink_directories(${PCL_LIBRARY_DIRS})\nadd_definitions(${PCL_DEFINITIONS})\n\nadd_subdirectory(lib)\nadd_subdirectory(src)\n\n#target_link_libraries(main ${OpenCV_LIBS})\n#target_link_libraries(main ${freenect2_LIBRARIES})\n#target_link_libraries(main Eigen3::Eigen)\n#target_link_libraries(main ${Pangolin_LIBRARIES})\n#target_link_libraries(main ${PCL_LIBRARIES})\n" }, { "alpha_fraction": 0.5205777883529663, "alphanum_fraction": 0.5557372570037842, "avg_line_length": 30.869565963745117, "blob_id": "da0c80718df718e6d859520bb45a2e1985d9b76f", "content_id": "734ea6246d842233284d3d30f587fb1a481367a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3669, "license_type": "no_license", "max_line_length": 98, "num_lines": 115, "path": "/workshop/pytorch/logistic_regression/logistic_regression_pytorch_2.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "import torch\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\ndef generate_data(n, p=0.8):\n # p: percentage of data for training\n x1 = np.random.multivariate_normal([4., 3.], [[4., 0.], [0., 1.]], n)\n plt.scatter(x1.T[0], x1.T[1], marker=\"^\", color=\"red\")\n x2 = np.random.multivariate_normal([6., 0.], [[1.5, 0.5], [0.5, 1.5]], n)\n plt.scatter(x2.T[0], x2.T[1], color=\"blue\")\n # combine data\n x = np.vstack((x1, x2))\n y = np.asarray([[1., 0.]] * n + [[0., 1.]] * n)\n # shuffle data\n shuffle_idx = np.arange(0, n*2)\n np.random.shuffle(shuffle_idx)\n x_shuffled = x[shuffle_idx]\n y_shuffled = y[shuffle_idx]\n # split data into training and testing\n _x_train = x_shuffled[0:int(n * p)*2]\n _y_train = y_shuffled[0:int(n * p)*2]\n _x_test = x_shuffled[int(n * p)*2:n*2]\n _y_test = y_shuffled[int(n * p)*2:n*2]\n # transform into torch.tensor\n _x_train = torch.from_numpy(_x_train)\n _y_train = torch.from_numpy(_y_train)\n _x_test = torch.from_numpy(_x_test)\n _y_test = torch.from_numpy(_y_test)\n _x_train = _x_train.type(torch.float32)\n _y_train = _y_train.type(torch.float32)\n _x_test = _x_test.type(torch.float32)\n _y_test = _y_test.type(torch.float32)\n return _x_train, _y_train, _x_test, _y_test\n\n\ndef error_rate(_x, _y, _model):\n _error_count = 0\n for i in range(_x.shape[0]):\n _y_label = _y[i]\n _y_pred = _model.forward(_x[i])\n if (_y_pred[0] > 0.5) and (_y_label[0] == 0):\n _error_count += 1\n if (_y_pred[1] > 0.5) and(_y_label[1] == 0):\n _error_count += 1\n _error_rate = _error_count / _x.shape[0]\n return _error_rate\n\n\ndef plot_boundary(_model, _color):\n x1_plot = np.arange(-2., 10., .1)\n x2_plot = np.arange(-6., 6., .1)\n x1_plot, x2_plot = np.meshgrid(x1_plot, x2_plot)\n f = np.zeros(x1_plot.shape)\n for i in range(x1_plot.shape[0]):\n for j in range(x1_plot.shape[1]):\n # f[i][j] = model(np.array([[x1_plot[i][j]], [x2_plot[i][j]]]), _theta)[3][0][0] - 0.5\n f[i][j] = model.forward(torch.tensor([x1_plot[i][j], x2_plot[i][j]]))[0] - 0.5\n\n plt.contour(x1_plot, x2_plot, f, 0, colors=_color)\n\n\nclass Model(torch.nn.Module):\n def __init__(self):\n super(Model, self).__init__()\n self.linear = torch.nn.Linear(2, 2)\n\n def forward(self, x):\n # y_pred = torch.sigmoid(self.linear(x))\n y_pred = torch.softmax(self.linear(x), dim=0)\n return y_pred\n\n\n def li(self, x):\n return self.linear(x)\n\n\n\nif __name__ == \"__main__\":\n # my model\n model = Model()\n\n # define criterion and optimizer\n criterion = torch.nn.BCELoss(reduction='mean')\n optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)\n\n # generate data\n x_train, y_train, x_test, y_test = generate_data(100)\n\n\n for epoch in range(5000):\n y_pred = model(x_train)\n\n loss = criterion(y_pred, y_train)\n if (epoch % 100 == 0):\n print(f'Epoch: {epoch} | Loss: {loss.item()}')\n print(\"training error rate %f \" % (error_rate(x_train, y_train, model)))\n print(\"testing error rate %f \" % (error_rate(x_test, y_test, model)))\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # visualize\n # x_boundary = [0., 10.]\n # y_boundary = [model.li(torch.tensor([0., 0.]))[0], model.li(torch.tensor([10., 10.]))[0]]\n #\n # plt.plot(x_boundary, y_boundary)\n\n plot_boundary(model, \"green\")\n plt.show()\n\n print(\"weight: \", model.linear.weight)\n print(\"bias: \", model.linear.bias)\n print(\"test result: \", model.forward(torch.tensor([1., 3.])))\n\n\n\n\n" }, { "alpha_fraction": 0.5381699800491333, "alphanum_fraction": 0.5814834833145142, "avg_line_length": 32.27927780151367, "blob_id": "6de981bfd02db5cb6a7311d478fff4fe486d8b41", "content_id": "3caf588e41ad2dfc1e60a381e3cc310178e8553e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3694, "license_type": "no_license", "max_line_length": 113, "num_lines": 111, "path": "/workshop/DNN_classification/torch_network/main.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "from torch_network.TorchNN import *\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport torch\n\n\ndef generate_data(n, p=0.8):\n # p: percentage of data for training\n x11 = np.random.multivariate_normal([4., 3.], [[4., 0.], [0., 1.]], int(0.5*n))\n x12 = np.random.multivariate_normal([2., -2.], [[1., 0.], [0., 2.]], int(0.25*n))\n x13 = np.random.multivariate_normal([7., -4.], [[1., 0.], [0., 1.]], int(0.25*n))\n x1 = np.vstack((x11, x12, x13))\n plt.scatter(x1.T[0], x1.T[1], color=\"red\")\n x2 = np.random.multivariate_normal([6., 0.], [[1.5, 0.5], [0.5, 1.5]], n)\n plt.scatter(x2.T[0], x2.T[1], color=\"blue\")\n # combine data\n x = np.vstack((x1, x2))\n y = np.asarray([[1., 0.]] * n + [[0., 1.]] * n)\n # shuffle data\n shuffle_idx = np.arange(0, n*2)\n np.random.shuffle(shuffle_idx)\n x_shuffled = x[shuffle_idx]\n y_shuffled = y[shuffle_idx]\n # split data into training and testing\n _x_train = x_shuffled[0:int(n * p)*2]\n _y_train = y_shuffled[0:int(n * p)*2]\n _x_test = x_shuffled[int(n * p)*2:n*2]\n _y_test = y_shuffled[int(n * p)*2:n*2]\n # make torch tensor\n _x_train = torch.tensor(_x_train.T, dtype=torch.float32)\n _y_train = torch.tensor(_y_train.T, dtype=torch.float32)\n _x_test = torch.tensor(_x_test.T, dtype=torch.float32)\n _y_test = torch.tensor(_y_test.T, dtype=torch.float32)\n return _x_train, _y_train, _x_test, _y_test\n\n\ndef error_rate(_x, _y, _dnn):\n y = _dnn.model(_x)\n error_count = 0\n for i in range(y.shape[1]):\n if (y[0, i].data.numpy() > 0.5) and _y[0, i].data.numpy() == 0:\n error_count += 1\n if (y[0, i].data.numpy() < 0.5) and _y[0, i].data.numpy() == 1:\n error_count += 1\n return error_count / _y.shape[1]\n\n\ndef plot_boundary(_dnn, _color):\n x_plot = np.arange(-2., 10., .2)\n y_plot = np.arange(-6., 6., .2)\n x_plot, y_plot = np.meshgrid(x_plot, y_plot)\n f = np.zeros(x_plot.shape)\n for i in range(x_plot.shape[0]):\n for j in range(x_plot.shape[1]):\n f[i][j] = _dnn.model(torch.tensor([[x_plot[i][j]], [y_plot[i][j]]], dtype=torch.float32))[0][0] - 0.5\n plt.contour(x_plot, y_plot, f, 0, colors=_color)\n\n\nx_train, y_train, x_test, y_test = generate_data(100)\n\nnn = TorchNN(2)\nnn.add_dense_layer(20)\nnn.add_dense_layer(20)\nnn.add_dense_layer(20)\n# nn.add_dense_layer(5)\n# nn.add_dense_layer(5)\n# nn.add_dense_layer(5)\n# nn.add_dense_layer(5)\n# nn.add_dense_layer(5)\n# nn.add_dense_layer(5)\n# nn.add_dense_layer(5)\n# nn.add_dense_layer(5)\nnn.add_dense_layer(2, activation=softmax)\n\n# print(x_train[:, :5])\n# print(nn.model(x_train[:, :5]))\n\n# loss = -torch.trace(torch.log(nn.model(x_train)).T.mm(y_train))\n# loss.backward()\n# nn.Ws[0] = torch.tensor([1])\n# loss.backward()\n# nn.Ws[0].data.zero_()\n# print(nn.Ws[0])\n# print(nn.Ws[0].grad)\n# nn.Ws[0].data.sub_(nn.Ws[0].grad.data*0.01)\n# print(nn.Ws[0])\n# loss = -torch.trace(torch.log(nn.model(x_train)).T.mm(y_train))\n# loss.backward()\n# print(\"______________\")\n# print(nn.Ws[0].grad)\n\nplot_boundary(nn, \"orange\")\n\nlr = 5e-4\n\nfor step in range(15000):\n loss = -torch.trace(torch.log(nn.model(x_train)).T.mm(y_train)) / x_train.shape[1]\n loss.backward()\n for tensor in nn.Ws:\n tensor.data.sub_(tensor.grad.data * lr)\n tensor.grad.data.zero_()\n for tensor in nn.Bs:\n tensor.data.sub_(tensor.grad.data * lr)\n tensor.grad.data.zero_()\n if step % 100 == 0:\n print(\"step: %d, training error rate: %f, testing error rate: %f\"\n % (step, error_rate(x_train, y_train, nn), error_rate(x_test, y_test, nn)))\n print(\"loss : %f\" % loss.data.numpy())\n\nplot_boundary(nn, \"lightblue\")\nplt.show()\n" }, { "alpha_fraction": 0.5135335326194763, "alphanum_fraction": 0.5502409934997559, "avg_line_length": 34.48684310913086, "blob_id": "3f810857045b22a8d7e7c6b7326a2dcdb292ce56", "content_id": "228b23d183060913686cb388b5afca750047105c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2697, "license_type": "no_license", "max_line_length": 118, "num_lines": 76, "path": "/workshop/Clustering/k_means.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "import numpy as np\nimport random\nfrom matplotlib import pyplot as plt\n\n\ndef generate_data(n, p=1.0):\n # p: percentage of data for training\n\n x11 = np.random.multivariate_normal([4., 3.], [[.08, 0.], [0., .05]], int(0.5*n))\n x12 = np.random.multivariate_normal([2., -2.], [[.05, 0.], [0., .1]], int(0.25*n))\n x13 = np.random.multivariate_normal([7., -4.], [[.1, 0.], [0., .05]], int(0.25*n))\n x1 = np.vstack((x11, x12, x13))\n # x1 = np.random.multivariate_normal([4., 3.], [[2., 0.], [0., .5]], n) # simple case\n\n plt.scatter(x1.T[0], x1.T[1], color=\"red\")\n x2 = np.random.multivariate_normal([6., 0.], [[.8, .05], [.05, .2]], n)\n plt.scatter(x2.T[0], x2.T[1], color=\"blue\")\n plt.show()\n # combine data\n x = np.vstack((x1, x2))\n y = np.asarray([[1.]] * n + [[-1.]] * n)\n # shuffle data\n shuffle_idx = np.arange(0, n*2)\n np.random.shuffle(shuffle_idx)\n x_shuffled = x[shuffle_idx]\n y_shuffled = y[shuffle_idx]\n # split data into training and testing\n _x_train = x_shuffled[0:int(n * p)*2]\n _y_train = y_shuffled[0:int(n * p)*2]\n _x_test = x_shuffled[int(n * p)*2:n*2]\n _y_test = y_shuffled[int(n * p)*2:n*2]\n return _x_train, _y_train, _x_test, _y_test\n\n\ndef distance(x1, x2):\n return np.sum((x1-x2)*(x1-x2))\n\n\nif __name__ == \"__main__\":\n n = 60\n x_train, y_train, x_test, y_test = generate_data(n)\n K = 4\n\n # initialization\n center_indices, cluster_indices = [], []\n for i in range(K):\n center_indices.append(random.randint(0, len(x_train)-1))\n cluster_indices.append([])\n\n flag = True\n while flag:\n # assigning label for all the samples\n for i in range(len(x_train)):\n sample = x_train[i]\n nearest_label = 0\n for label in range(K):\n center_index = center_indices[label]\n if distance(sample, x_train[center_index]) < distance(sample, x_train[center_indices[nearest_label]]):\n nearest_label = label\n cluster_indices[nearest_label].append(i)\n # computing the new center\n flag = False\n for i in range(K):\n pos_mean = np.mean(x_train[cluster_indices[i]], axis=0)\n nearest_index = 0\n for index in range(len(x_train)):\n if distance(pos_mean, x_train[index]) < distance(pos_mean, x_train[nearest_index]):\n nearest_index = index\n if center_indices[i] != nearest_index:\n flag = True\n center_indices[i] = nearest_index\n\n # plot data\n for i in range(K):\n plt.scatter(x_train[cluster_indices[i]].T[0], x_train[cluster_indices[i]].T[1])\n plt.show()\n" }, { "alpha_fraction": 0.46316850185394287, "alphanum_fraction": 0.5181634426116943, "avg_line_length": 29.492307662963867, "blob_id": "46f28946f9b17a61a52fff8971f29e655f736853", "content_id": "529cc2c1b59516c365da828147907c95c78dd5c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1998, "license_type": "no_license", "max_line_length": 88, "num_lines": 65, "path": "/workshop/SVM/hard_margin.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom cvxopt import solvers, matrix\nfrom matplotlib import pyplot as plt\n\n\ndef generate_data(n, p=1.0):\n # p: percentage of data for training\n\n # x11 = np.random.multivariate_normal([4., 3.], [[4., 0.], [0., 1.]], int(0.5*n))\n # x12 = np.random.multivariate_normal([2., -2.], [[1., 0.], [0., 2.]], int(0.25*n))\n # x13 = np.random.multivariate_normal([7., -4.], [[1., 0.], [0., 1.]], int(0.25*n))\n # x1 = np.vstack((x11, x12, x13))\n x1 = np.random.multivariate_normal([4., 3.], [[.4, 0.], [0., .1]], n) # simple case\n\n plt.scatter(x1.T[0], x1.T[1], color=\"red\")\n x2 = np.random.multivariate_normal([6., 0.], [[.15, .05], [.05, .15]], n)\n plt.scatter(x2.T[0], x2.T[1], color=\"blue\")\n # combine data\n x = np.vstack((x1, x2))\n y = np.asarray([[1.]] * n + [[-1.]] * n)\n # shuffle data\n shuffle_idx = np.arange(0, n*2)\n np.random.shuffle(shuffle_idx)\n x_shuffled = x[shuffle_idx]\n y_shuffled = y[shuffle_idx]\n # split data into training and testing\n _x_train = x_shuffled[0:int(n * p)*2]\n _y_train = y_shuffled[0:int(n * p)*2]\n _x_test = x_shuffled[int(n * p)*2:n*2]\n _y_test = y_shuffled[int(n * p)*2:n*2]\n return _x_train, _y_train, _x_test, _y_test\n\n\nif __name__ == \"__main__\":\n n = 100\n x_train, y_train, x_test, y_test = generate_data(n)\n X = (x_train*y_train).T\n\n P = matrix(X.T.dot(X))\n q = matrix(-np.ones([n*2, 1]))\n G = matrix(-np.eye(n*2))\n h = matrix(np.zeros([n*2, 1]))\n\n A = matrix(y_train.T)\n b = matrix(0.)\n\n sol = solvers.qp(P, q, G, h, A, b) # 调用优化函数solvers.qp求解\n alpha = np.array(sol['x'])\n # print(alpha)\n w = X.dot(alpha)\n # print(w)\n\n # calculate b\n count = 0\n b = 0.\n for i in range(n*2):\n if alpha[i][0] < 0.001:\n continue\n b += (y_train[i][0] - w.T.dot(x_train[i].T))\n count += 1\n b /= count\n\n # print(b)\n plt.plot([0., 6.], [-b/w[1][0], (-b-6.*w[0][0])/w[1][0]])\n plt.show()\n" }, { "alpha_fraction": 0.5536912679672241, "alphanum_fraction": 0.5956375598907471, "avg_line_length": 19.55172348022461, "blob_id": "186b74304edf46eb4552100a73cf673a7e0fe859", "content_id": "aa96d96931a9b90d9b822004c4de8d229575d8e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 596, "license_type": "no_license", "max_line_length": 57, "num_lines": 29, "path": "/demo5.1_final/arduino/serial_input/serial_input.ino", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "#include<Servo.h>\n#include <AccelStepper.h>\n\n// all the defines\n#define SERVO_PIN 3\n\nServo servo;\n\nvoid setup() {\n //set pin modes\n servo.attach(SERVO_PIN);\n // begin serial\n Serial.begin(9600);\n Serial.println(\"Please enter the angle (0.0 To 90.0)\");\n}\n\nvoid loop() {\n while (Serial.available() > 0) {\n float orient = Serial.parseFloat(SKIP_ALL);\n if (orient > 0.0 && orient <= 90.0) {\n Serial.print(\" orient: \");\n Serial.println(orient);\n servo.write(orient*1.5+10.0);\n } else if (orient == -1.0) {\n Serial.print(\" home\");\n servo.write(0.0);\n }\n }\n}\n" }, { "alpha_fraction": 0.5104199051856995, "alphanum_fraction": 0.5542768239974976, "avg_line_length": 32.48958206176758, "blob_id": "34e7c07435d00125615e702c3e0415644deb1086", "content_id": "9d48024205fdd8a52ef1a02fec79651baa7e2420", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3215, "license_type": "no_license", "max_line_length": 95, "num_lines": 96, "path": "/workshop/DNN_pytorch/classification.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\ndef generate_data(n, p=0.8):\n # p: percentage of data for training\n x11 = np.random.multivariate_normal([4., 3.], [[4., 0.], [0., 1.]], int(0.5*n))\n x12 = np.random.multivariate_normal([2., -2.], [[1., 0.], [0., 2.]], int(0.25*n))\n x13 = np.random.multivariate_normal([7., -4.], [[1., 0.], [0., 1.]], int(0.25*n))\n x1 = np.vstack((x11, x12, x13))\n plt.scatter(x1.T[0], x1.T[1], color=\"red\")\n x2 = np.random.multivariate_normal([6., 0.], [[1.5, 0.5], [0.5, 1.5]], n)\n plt.scatter(x2.T[0], x2.T[1], color=\"blue\")\n # combine data\n x = np.vstack((x1, x2))\n y = np.asarray([0] * n + [1] * n)\n # shuffle data\n shuffle_idx = np.arange(0, n*2)\n np.random.shuffle(shuffle_idx)\n x_shuffled = x[shuffle_idx]\n y_shuffled = y[shuffle_idx]\n # split data into training and testing\n _x_train = torch.tensor(x_shuffled[0:int(n * p)*2], dtype=torch.float32)\n _y_train = torch.tensor(y_shuffled[0:int(n * p)*2], dtype=torch.int64)\n _x_test = torch.tensor(x_shuffled[int(n * p)*2:n*2], dtype=torch.float32)\n _y_test = torch.tensor(y_shuffled[int(n * p)*2:n*2], dtype=torch.int64)\n return _x_train, _y_train, _x_test, _y_test\n\n\ndef error_rate(_x, _y, _net):\n error_count = 0\n for i in range(len(_x)):\n if (_net(_x[i])[0] > 0.5) and _y[i] == 1:\n error_count += 1\n if (_net(_x[i])[0] < 0.5) and _y[i] == 0:\n error_count += 1\n return error_count / len(_x)\n\n\ndef plot_boundary(_net, _color):\n x_plot = np.arange(-2., 10., .1)\n y_plot = np.arange(-6., 6., .1)\n x_plot, y_plot = np.meshgrid(x_plot, y_plot)\n f = np.zeros(x_plot.shape)\n for i in range(x_plot.shape[0]):\n for j in range(x_plot.shape[1]):\n f[i][j] = _net(torch.tensor([x_plot[i][j], y_plot[i][j]]))[0] - 0.5\n plt.contour(x_plot, y_plot, f, 0, colors=_color)\n\n\nclass Net(nn.Module):\n def __init__(self):\n super().__init__()\n self.fc1 = nn.Linear(2, 5)\n self.fc2 = nn.Linear(5, 5)\n self.fc3 = nn.Linear(5, 5)\n self.fc4 = nn.Linear(5, 5)\n self.fc_out = nn.Linear(5, 2)\n\n def forward(self, x):\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = F.relu(self.fc3(x))\n x = F.relu(self.fc4(x))\n x = self.fc_out(x)\n return F.softmax(x, dim=-1)\n\n\nif __name__ == \"__main__\":\n x_train, y_train, x_test, y_test = generate_data(100)\n net = Net()\n\n # plot boundary before training\n plot_boundary(net, \"orange\")\n\n loss_function = nn.CrossEntropyLoss()\n optimizer = optim.SGD(net.parameters(), lr=1e-2, momentum=0.0)\n\n for step in range(10000):\n a = net(x_train)\n loss = loss_function(a, y_train)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n if step % 100 == 0:\n print(\"step: %d, training error rate: %f, testing error rate: %f\"\n % (step, error_rate(x_train, y_train, net), error_rate(x_test, y_test, net)))\n\n # plot boundary after training\n plot_boundary(net, \"lightblue\")\n\n plt.show()\n" }, { "alpha_fraction": 0.6578224897384644, "alphanum_fraction": 0.6870997548103333, "avg_line_length": 26.350000381469727, "blob_id": "eb38b735cbfba796d0d396901e2852552c010b7c", "content_id": "f9b90236fab23d63cce78beae1ae75f13b70f6a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1093, "license_type": "no_license", "max_line_length": 68, "num_lines": 40, "path": "/demo3.1_validate_in_process_scan/detection/passthrough.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 19.03.20.\n//\n\n#include <iostream>\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <pcl/filters/passthrough.h>\n\ntypedef pcl::PointXYZRGB PointC;\ntypedef pcl::PointXYZ PointG;\ntypedef pcl::PointCloud<PointC>::Ptr PointCloudC;\ntypedef pcl::PointCloud<PointG>::Ptr PointCloudG;\n\nusing namespace std;\n\npcl::PCDReader reader;\npcl::PCDWriter writer;\npcl::PassThrough<pcl::PointXYZ> pass;\n\nint main(int argc, char **argv) {\n PointCloudG cloud(new pcl::PointCloud<PointG>);\n reader.read(\"../data3D/cloud_aligned.pcd\", *cloud);\n\n pass.setInputCloud (cloud);\n pass.setFilterFieldName (\"x\");\n// pass.setFilterLimits (75.1, 333.6);\n pass.setFilterLimits (-28.6, 51.4); // small segments\n pass.filter (*cloud);\n pass.setInputCloud (cloud);\n pass.setFilterFieldName (\"y\");\n pass.setFilterLimits (-50, 8.6);\n pass.filter (*cloud);\n pass.setInputCloud (cloud);\n pass.setFilterFieldName (\"z\");\n pass.setFilterLimits (34.25, 80.0);\n pass.filter (*cloud);\n\n writer.write (\"../data3D/cloud_passthrough.pcd\", *cloud, false);\n}" }, { "alpha_fraction": 0.7840946316719055, "alphanum_fraction": 0.7975682020187378, "avg_line_length": 34.79999923706055, "blob_id": "340262552850dcafc018329a19c0d86b397b304c", "content_id": "9510fd285f85ea68d1427aa1acecc79e8837704a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 3043, "license_type": "no_license", "max_line_length": 113, "num_lines": 85, "path": "/demo3.1_validate_in_process_scan/detection/CMakeLists.txt", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "project (detection)\nset(CMAKE_CXX_FLAGS \"-std=c++14 -O3\")\ncmake_minimum_required(VERSION 3.15)\n\nlist(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake)\n\nfind_package(realsense2 REQUIRED)\n\nfind_package(OpenCV REQUIRED)\ninclude_directories(${OpenCV_INCLUDE_DIRS})\n\nfind_package(Eigen3 REQUIRED)\ninclude_directories(${Eigen3_INCLUDE_DIRS})\n\nfind_package(Ceres REQUIRED)\ninclude_directories(${CERES_INCLUDE_DIRS})\n\n#find_package( PCL REQUIRED COMPONENT common io )\n#include_directories( ${PCL_INCLUDE_DIRS} )\n#list(REMOVE_ITEM PCL_LIBRARIES \"vtkproj4\")\n#add_definitions( ${PCL_DEFINITIONS} )\n\nfind_package(PCL 1.2 REQUIRED)\n\ninclude_directories(${PCL_INCLUDE_DIRS})\nlink_directories(${PCL_LIBRARY_DIRS})\nadd_definitions(${PCL_DEFINITIONS})\n\n#new\nadd_executable(takeFrame2D takeFrame2D.cpp)\ntarget_link_libraries(takeFrame2D ${OpenCV_LIBS} ${realsense2_LIBRARY})\n\nadd_executable(construct3D construct3D.cpp)\ntarget_link_libraries(construct3D ${OpenCV_LIBS} ${realsense2_LIBRARY} ${PCL_LIBRARIES})\n\nadd_executable(construct3D_average construct3D_average.cpp)\ntarget_link_libraries(construct3D_average ${OpenCV_LIBS} ${PCL_LIBRARIES})\n\nadd_executable(construct3D_mouse construct3D_built/construct3D_mouse.cpp)\ntarget_link_libraries(construct3D_mouse ${OpenCV_LIBS} ${PCL_LIBRARIES})\n\nadd_executable(construct3D_built construct3D_built/construct3D_built.cpp construct3D_built/construct3D_built.hpp)\ntarget_link_libraries(construct3D_built ${OpenCV_LIBS} ${PCL_LIBRARIES})\n\nadd_executable(takeFrame3D takeFrame3D.cpp)\ntarget_link_libraries(takeFrame3D ${OpenCV_LIBS} ${realsense2_LIBRARY} ${PCL_LIBRARIES})\n\nadd_executable(registerClouds registerClouds.cpp)\ntarget_link_libraries(registerClouds ${PCL_LIBRARIES})\n\nadd_executable(registerExt registerExt.cpp)\ntarget_link_libraries(registerExt ${OpenCV_LIBS} ${PCL_LIBRARIES})\n\nadd_executable(ransac ransac.cpp)\ntarget_link_libraries(ransac ${PCL_LIBRARIES})\n\nadd_executable(clean_cloud clean_cloud.cpp)\ntarget_link_libraries(clean_cloud ${PCL_LIBRARIES})\n\nadd_executable(downsample downsample.cpp)\ntarget_link_libraries(downsample ${PCL_LIBRARIES})\n\nadd_executable(passthrough passthrough.cpp)\ntarget_link_libraries(passthrough ${PCL_LIBRARIES})\n\nadd_executable(combine_cloud combine_cloud.cpp)\ntarget_link_libraries(combine_cloud ${PCL_LIBRARIES})\n\nadd_executable(fitting fitting.cpp)\ntarget_link_libraries(fitting ${PCL_LIBRARIES} ${CERES_LIBRARIES})\n\nadd_executable(fitting_fixed_radius fitting_fixed_radius.cpp)\ntarget_link_libraries(fitting_fixed_radius ${PCL_LIBRARIES} ${CERES_LIBRARIES})\n\nadd_executable(level_chessboard level_chessboard.cpp)\ntarget_link_libraries(level_chessboard ${OpenCV_LIBS} ${realsense2_LIBRARY})\n\nadd_executable(level_circleboard level_circleboard.cpp)\ntarget_link_libraries(level_circleboard ${OpenCV_LIBS} ${realsense2_LIBRARY})\n\n#target_link_libraries(main ${OpenCV_LIBS})\n#target_link_libraries(main ${freenect2_LIBRARIES})\n#target_link_libraries(main Eigen3::Eigen)\n#target_link_libraries(main ${Pangolin_LIBRARIES})\n#target_link_libraries(main ${PCL_LIBRARIES})\n" }, { "alpha_fraction": 0.5699999928474426, "alphanum_fraction": 0.699999988079071, "avg_line_length": 13.285714149475098, "blob_id": "5ad2266c2dcc199ed66dcc32532829a8b180b63a", "content_id": "4566a609d9d54c2866be0d9833ca02d14f6203fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 100, "license_type": "no_license", "max_line_length": 24, "num_lines": 7, "path": "/demo5.1_final/localization_and_mapping/code/camera_intrinsics.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport libs.lib_rs as rs\n\nd415 = rs.D415()\n\nprint(d415.C)\nprint(d415.coeffs)\n" }, { "alpha_fraction": 0.5257903337478638, "alphanum_fraction": 0.5496394634246826, "avg_line_length": 28.09677505493164, "blob_id": "5b2b0e552174f16aabb3bd692480b15042a953ff", "content_id": "6463273bfcf97c1e613a338fbcaab91304c51cb9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1803, "license_type": "no_license", "max_line_length": 79, "num_lines": 62, "path": "/workshop/pytorch/linear_regression/main.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom matplotlib import pyplot as plt\n\n\n# generate data for training\ndef generate_data(n, k, b, low=0.0, high=10.0):\n step = (high - low) / n\n x, y = [], []\n for i in range(n):\n x.append(low + step * i)\n y.append(x[i] * k + b + np.random.normal(0.0, 0.05 * (high - low)))\n return np.array(x), np.array(y)\n\n\n# set a function as model\ndef f_x(_x, _theta):\n _y = _x * _theta[0] + _theta[1]\n return _y\n\n\n# calculate loss between training data and result from model\ndef loss(_x_train, _y_train, _theta, _f_x=f_x):\n _loss = 0.0\n for i in range(len(_x_train)):\n _loss += (_f_x(_x_train[i], _theta) - _y_train[i]) ** 2\n return _loss / len(_x_train)\n\n\n# calculate gradient (d(Loss) / d(k), d(Loss) / d(b))\ndef gradient(_x_train, _y_train, _theta, _f_x=f_x):\n _k = _theta[0]\n _b = _theta[1]\n _delta_k = 0.0\n _delta_b = 0.0\n for i in range(len(_x_train)):\n _delta_k += 2 * (_f_x(_x_train[i], _theta) - _y_train[i]) * _x_train[i]\n _delta_b += 2 * (_f_x(_x_train[i], _theta) - _y_train[i]) * 1\n _gradient = np.array([_delta_k, _delta_b])\n return _gradient\n\n\ndef train(_x_train, _y_train, _theta, _f_x=f_x, _lr=1e-6, _step=1000):\n for i in range(_step):\n _theta = _theta - _lr * gradient(_x_train, _y_train, _theta, _f_x)\n print(loss(_x_train, _y_train, _theta, _f_x))\n return _theta\n\n\nif __name__ == \"__main__\":\n x_train, y_train = generate_data(100, 2.0, 0.5)\n theta0 = [5.0, 1.0]\n theta = train(x_train, y_train, theta0)\n\n print(theta)\n\n #plot training data as red points\n plt.title(\"Linear Regression\")\n plt.xlabel(\"Axis X\")\n plt.ylabel(\"Axis Y\")\n plt.plot(x_train, y_train, \"ob\", color=\"red\")\n plt.plot(x_train, f_x(x_train, theta), color=\"blue\")\n plt.show()" }, { "alpha_fraction": 0.7773255705833435, "alphanum_fraction": 0.7872093319892883, "avg_line_length": 30.851852416992188, "blob_id": "a4243bbccd05c35234eba8debe03864cfe4117e4", "content_id": "75729f0f2128a73804e0e8adb2d618bfd8192d23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1720, "license_type": "no_license", "max_line_length": 95, "num_lines": 54, "path": "/demo2.2_detect_cylinder/detection_2.0/CMakeLists.txt", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "project (cylinder_2.0)\nset(CMAKE_CXX_FLAGS \"-std=c++14 -O3\")\ncmake_minimum_required(VERSION 3.15)\n\nlist(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake)\n\nfind_package(realsense2 REQUIRED)\n\nfind_package(OpenCV REQUIRED)\ninclude_directories(${OpenCV_INCLUDE_DIRS})\n\nfind_package(Eigen3 REQUIRED)\ninclude_directories(${Eigen3_INCLUDE_DIRS})\n\nfind_package(Ceres REQUIRED)\ninclude_directories(${CERES_INCLUDE_DIRS})\n\n#find_package( PCL REQUIRED COMPONENT common io )\n#include_directories( ${PCL_INCLUDE_DIRS} )\n#list(REMOVE_ITEM PCL_LIBRARIES \"vtkproj4\")\n#add_definitions( ${PCL_DEFINITIONS} )\n\nfind_package(PCL 1.2 REQUIRED)\n\ninclude_directories(${PCL_INCLUDE_DIRS})\nlink_directories(${PCL_LIBRARY_DIRS})\nadd_definitions(${PCL_DEFINITIONS})\n\nadd_executable(takeFrameRealsense takeFrameRealsense.cpp)\ntarget_link_libraries(takeFrameRealsense ${OpenCV_LIBS} ${realsense2_LIBRARY} ${PCL_LIBRARIES})\n\nadd_executable(registerClouds registerClouds.cpp)\ntarget_link_libraries(registerClouds ${PCL_LIBRARIES})\n\nadd_executable(ransac ransac.cpp)\ntarget_link_libraries(ransac ${PCL_LIBRARIES})\n\nadd_executable(clean_cloud clean_cloud.cpp)\ntarget_link_libraries(clean_cloud ${PCL_LIBRARIES})\n\nadd_executable(downsample downsample.cpp)\ntarget_link_libraries(downsample ${PCL_LIBRARIES})\n\nadd_executable(combine_cloud combine_cloud.cpp)\ntarget_link_libraries(combine_cloud ${PCL_LIBRARIES})\n\nadd_executable(fitting fitting.cpp)\ntarget_link_libraries(fitting ${PCL_LIBRARIES} ${CERES_LIBRARIES})\n\n#target_link_libraries(main ${OpenCV_LIBS})\n#target_link_libraries(main ${freenect2_LIBRARIES})\n#target_link_libraries(main Eigen3::Eigen)\n#target_link_libraries(main ${Pangolin_LIBRARIES})\n#target_link_libraries(main ${PCL_LIBRARIES})\n" }, { "alpha_fraction": 0.8267716765403748, "alphanum_fraction": 0.8267716765403748, "avg_line_length": 14.625, "blob_id": "0963d1cccbaf1f033a95fb6802cf6dfb7e39dd6a", "content_id": "4b0d7605f0b43a234c4b55a85be985de37d9df6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 127, "license_type": "no_license", "max_line_length": 35, "num_lines": 8, "path": "/design/design_ts/description.txt", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "STATEMENT\nthesis development\nbamboo sticks as table substructure\n\nCONTENTS\n-design file\n-fabrication order\n-camera scan path\n\n\n" }, { "alpha_fraction": 0.8518518805503845, "alphanum_fraction": 0.8518518805503845, "avg_line_length": 18.14285659790039, "blob_id": "089f215a3187569dc45f12cc6a02565ebd9c57ae", "content_id": "df2cd032a507fb9cf8d6128a5188645233def893", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 135, "license_type": "no_license", "max_line_length": 32, "num_lines": 7, "path": "/design/design_bf/description.txt", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "STATEMENT\nbehavior and fabrication seminar\npart of thesis development\n\nCONTENTS\n-bamboo structure design\n-milling toolpath generation\n\n" }, { "alpha_fraction": 0.5518810749053955, "alphanum_fraction": 0.594660222530365, "avg_line_length": 31.323530197143555, "blob_id": "1f02118b3006c00a774857ea80aaaf9f977f2179", "content_id": "a3a6eb40ff77c2528324e639911f077e9e2264a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3296, "license_type": "no_license", "max_line_length": 112, "num_lines": 102, "path": "/demo2.2_detect_cylinder/detection_rgbd/src/main.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 26.01.20.\n//\n\n#include <iostream>\n#include <chrono>\n#include <boost/format.hpp>\n#include <opencv2/opencv.hpp>\n#include <librealsense2/rs.hpp>\n\n#include <pose.hpp>\n#include <vision.hpp>\n\n#include <pointCloud.hpp>\n#include <pcl/io/pcd_io.h>\n//#include <kinect.hpp>\n\nusing namespace std;\nusing namespace cv;\n\nint main() {\n rs2::pipeline pipe;\n rs2::config cfg;\n cfg.enable_stream(RS2_STREAM_DEPTH, 1280, 720, RS2_FORMAT_Z16, 30);\n cfg.enable_stream(RS2_STREAM_COLOR, 1920, 1080, RS2_FORMAT_BGR8, 30);\n pipe.start(cfg);\n\n rs2::align align_to_color(RS2_STREAM_COLOR);\n\n rs2::pointcloud pc;\n rs2::points points;\n\n namedWindow(\"color\", 0);\n namedWindow(\"00\", 0);\n namedWindow(\"01\", 0);\n cvResizeWindow(\"color\", 960, 540);\n cvResizeWindow(\"00\", 640, 360);\n cvResizeWindow(\"01\", 640, 360);\n\n // numbers of point clouds to save\n int COUNT = 0;\n\n // start\n while (waitKey(1) != 'q') {\n rs2::frameset frameset = pipe.wait_for_frames();\n frameset = align_to_color.process(frameset);\n\n auto depth = frameset.get_depth_frame();\n auto color = frameset.get_color_frame();\n\n Mat matColor(Size(1920, 1080), CV_8UC3, (void*)color.get_data(), Mat::AUTO_STEP);\n Mat matDepth(Size(1920, 1080), CV_16U, (void*)depth.get_data(), Mat::AUTO_STEP);\n\n vector<pose> poses;\n vector<vector<Point2f> > markerCorners;\n vector<int> markerIds;\n\n// chrono::steady_clock::time_point t_start = chrono::steady_clock::now(); //counting time\n detectAruco(matColor, poses, markerCorners, markerIds);\n\n imshow(\"color\", matColor);\n\n if (poses.size() != 2) continue;\n\n cout << \"pose 01: \" << poses[0].origin() << endl;\n cout << \"pose 02: \" << poses[1].origin() << endl;\n\n Mat colorWithMask[2];\n Mat masks[2];\n for (int i = 0; i < 2; ++i) {\n vector<Point2f> m = markerCorners[i];\n Point p = m[3]+m[2]-(m[1]+m[0])*0.5;\n Mat maskColor = Mat::zeros(matColor.rows, matColor.cols, CV_8UC1);\n grow(matColor, maskColor, p, 18);\n Mat maskDepth = Mat::zeros(matDepth.rows, matDepth.cols, CV_8UC1);\n grow(matDepth, maskDepth, p, 2);\n Mat maskCombined;\n bitwise_and(maskColor, maskDepth, maskCombined);\n maskCombined.copyTo(masks[markerIds[i]]);\n matColor.copyTo(colorWithMask[markerIds[i]], maskCombined);\n }\n\n// chrono::steady_clock::time_point t_end = chrono::steady_clock::now(); //counting time\n// chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t_end - t_start);\n// cout << \"solve time cost = \" << time_used.count() << \" seconds. \" << endl;\n\n imshow(\"00\", colorWithMask[0]);\n imshow(\"01\", colorWithMask[1]);\n\n PointCloudG cloud0 = mat2pcl(matDepth, masks[0]);\n boost::format fmt( \"../../data/point_cloud/cloud1_%d%s.pcd\" );\n pcl::io::savePCDFileBinary((fmt%COUNT%\"A\").str(), *cloud0);\n PointCloudG cloud1 = mat2pcl(matDepth, masks[1]);\n pcl::io::savePCDFileBinary((fmt%COUNT%\"B\").str(), *cloud1);\n COUNT += 1;\n waitKey(1000);\n if (COUNT == 10) break;\n }\n\n destroyAllWindows();\n return 0;\n}" }, { "alpha_fraction": 0.604938268661499, "alphanum_fraction": 0.6299725770950317, "avg_line_length": 32.1363639831543, "blob_id": "cee63a2329ffd84ec03c0d7618940152838f95b9", "content_id": "b159ec02bf844bd259e7b65e3bae44921c0c516a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2916, "license_type": "no_license", "max_line_length": 114, "num_lines": 88, "path": "/demo4.1_tracking/web/catkin_ws/src/web/src/rs_img_pub.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "#include <string.h>\n\n#include <ros/ros.h>\n#include <ros/package.h>\n\n#include <image_transport/image_transport.h>\n#include <cv_bridge/cv_bridge.h>\n#include <sensor_msgs/Image.h>\n#include <std_msgs/Header.h>\n\n#include <librealsense2/rs.hpp>\n#include <librealsense2/rs_advanced_mode.hpp>\n#include <opencv2/opencv.hpp>\n\nusing namespace std;\nusing namespace cv;\n\nint main(int argc, char** argv) {\n ros::init(argc, argv, \"rs_img_pub\");\n ros::NodeHandle nh;\n\n string path = ros::package::getPath(\"web\") + \"/cfg/high_accuracy_config.json\";\n ROS_INFO(\"%s\", path.c_str());\n\n // ===============\n // start realsense\n // ===============\n\n rs2::pipeline pipe;\n rs2::config cfg;\n rs2::context ctx;\n\n auto device = ctx.query_devices();\n auto dev = device[0];\n\n string serial = dev.get_info(RS2_CAMERA_INFO_SERIAL_NUMBER);\n string json_file_name = path;\n // cout << \"Configuring camera : \" << serial << endl;\n\n auto advanced_mode_dev = dev.as<rs400::advanced_mode>();\n\n // Check if advanced-mode is enabled to pass the custom config\n if (!advanced_mode_dev.is_enabled())\n {\n // If not, enable advanced-mode\n advanced_mode_dev.toggle_advanced_mode(true);\n cout << \"Advanced mode enabled. \" << endl;\n }\n\n // Select the custom configuration file\n std::ifstream t(json_file_name);\n std::string preset_json((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());\n advanced_mode_dev.load_json(preset_json);\n cfg.enable_device(serial);\n\n cfg.enable_stream(RS2_STREAM_DEPTH, 1280, 720, RS2_FORMAT_Z16, 30);\n cfg.enable_stream(RS2_STREAM_COLOR, 1920, 1080, RS2_FORMAT_BGR8, 30);\n pipe.start(cfg);\n\n rs2::align align_to_color(RS2_STREAM_COLOR);\n\n // =============\n // end realsense\n // =============\n\n image_transport::ImageTransport it_color(nh);\n image_transport::Publisher pub_color = it_color.advertise(\"rs_color\", 1);\n image_transport::ImageTransport it_depth(nh);\n image_transport::Publisher pub_cepth = it_depth.advertise(\"rs_depth\", 1);\n\n ros::Rate rate(10);\n while (nh.ok()) {\n rs2::frameset frameset = pipe.wait_for_frames();\n frameset = align_to_color.process(frameset);\n auto color = frameset.get_color_frame();\n auto depth = frameset.get_depth_frame();\n Mat matColor(Size(1920, 1080), CV_8UC3, (void*)color.get_data(), Mat::AUTO_STEP);\n Mat matDepth(Size(1920, 1080), CV_16U, (void*)depth.get_data(), Mat::AUTO_STEP);\n // cv::resize(matColor, matColor, Size(960, 540));\n sensor_msgs::ImagePtr msg_color = cv_bridge::CvImage(std_msgs::Header(), \"bgr8\", matColor).toImageMsg();\n sensor_msgs::ImagePtr msg_depth = cv_bridge::CvImage(std_msgs::Header(), \"mono16\", matDepth).toImageMsg();\n pub_color.publish(msg_color);\n pub_cepth.publish(msg_depth);\n\n ros::spinOnce();\n rate.sleep();\n }\n}\n" }, { "alpha_fraction": 0.7777777910232544, "alphanum_fraction": 0.7851851582527161, "avg_line_length": 63.5, "blob_id": "6c215653043ec38753b997be79805add51b079ec", "content_id": "7f1d8aad7aad6e40f0756c14b1c7316f1d2b5d2b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 135, "license_type": "no_license", "max_line_length": 108, "num_lines": 2, "path": "/demo1_tello_aruco/README.md", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "# demo1_tello_aruco\r\nFirst attempt of thesis project. Trying to control the drone trajectory by detecting external aruco markers.\r\n\r\n\r\n" }, { "alpha_fraction": 0.6451612710952759, "alphanum_fraction": 0.6532257795333862, "avg_line_length": 31.068965911865234, "blob_id": "9cac304f1e2a7b3a570a926ec757c4c41d33b70c", "content_id": "690b7917960ddfcdb99c9896e53ec489985f4e52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1860, "license_type": "no_license", "max_line_length": 99, "num_lines": 58, "path": "/demo3.1_validate_in_process_scan/detection/combine_cloud.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <fstream>\n#include <chrono>\n#include <boost/format.hpp> // for formating strings\n\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n#include <pcl/filters/statistical_outlier_removal.h>\n#include <pcl/common/transforms.h>\n#include <pcl/registration/icp.h>\n\ntypedef pcl::PointXYZRGB PointC;\ntypedef pcl::PointXYZ PointG;\ntypedef pcl::PointCloud<PointC>::Ptr PointCloudC;\ntypedef pcl::PointCloud<PointG>::Ptr PointCloudG;\n\nusing namespace std;\n\npcl::PCDReader reader;\npcl::PCDWriter writer;\npcl::StatisticalOutlierRemoval<PointG> sor;\n\nint main(int argc, char **argv) {\n if (argc != 3) {\n cout << \"please enter two file paths.\" << endl;\n return -1;\n }\n \n int num_frames = 2;\n\n PointCloudG clouds_full[num_frames];\n PointCloudG cloud_aligned (new pcl::PointCloud<PointG>);\n // load all the clouds\n for (int frame_index = 0; frame_index < num_frames; ++frame_index) {\n PointCloudG cloud(new pcl::PointCloud<PointG>);\n reader.read(argv[1+frame_index], *cloud);\n clouds_full[frame_index] = cloud;\n }\n cloud_aligned = clouds_full[0];\n cout << \"cloud 0: \" << clouds_full[0]->points.size() << endl;\n for (int frame_index = 1; frame_index < num_frames; ++frame_index) {\n cout << \"cloud \" << frame_index << \": \" << clouds_full[frame_index]->points.size() << endl;\n *cloud_aligned += *clouds_full[frame_index];\n }\n\n // remove outliers\n// sor.setInputCloud (cloud_merged);\n// sor.setMeanK (5);\n// sor.setStddevMulThresh (0.5);\n// sor.filter (*cloud_merged);\n\n// cloud_merged->width = cloud_merged->points.size();\n// cloud_merged->height = 1;\n// cloud_merged->resize(cloud_merged->width*cloud_merged->height);\n writer.write (\"../data3D/cloud_aligned.pcd\", *cloud_aligned, false);\n return 0;\n}\n" }, { "alpha_fraction": 0.8108108043670654, "alphanum_fraction": 0.8108108043670654, "avg_line_length": 52.5, "blob_id": "589a80c8c7c2793f241a32122fb2e2557d119677", "content_id": "987af56ee1c9d636d59a800a3d4d8937c242ee5d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 111, "license_type": "no_license", "max_line_length": 95, "num_lines": 2, "path": "/workshop/README.md", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "# workshop\r\nSome workshop for understanding the basic principles of vision and machine learning algorithms.\r\n\r\n" }, { "alpha_fraction": 0.4430493414402008, "alphanum_fraction": 0.4789237678050995, "avg_line_length": 25.547618865966797, "blob_id": "ba9dca7065cfd5d1f98e18f6ba7c8b56010a9d9c", "content_id": "1776deff21a52994c38888ad75007c8d199bc228", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1115, "license_type": "no_license", "max_line_length": 92, "num_lines": 42, "path": "/demo1_tello_aruco/cv_aruco/Pose.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom math import atan2, sin, cos, pi\n\n\nclass Pose:\n def __init__(self, R=np.eye(3, dtype=np.float32), t=np.zeros((3, 1), dtype=np.float32)):\n self.R = R\n self.t = t\n\n @property\n def x(self):\n return self.t[0][0]\n\n @property\n def y(self):\n return self.t[1][0]\n\n @property\n def z(self):\n return self.t[2][0]\n\n @property\n def yaw(self):\n return atan2(self.R[1][0], self.R[1][1])\n\n @staticmethod\n def rotational_x(theta):\n return np.array([[1., 0., 0.],\n [0., cos(theta), -sin(theta)],\n [0., sin(theta), cos(theta)]], dtype=np.float32)\n\n @staticmethod\n def rotational_y(theta):\n return np.array([[cos(theta), 0., sin(theta)],\n [0., 1., 0.],\n [-sin(theta), 0., cos(theta)]], dtype=np.float32)\n\n @staticmethod\n def rotational_z(theta):\n return np.array([[cos(theta), -sin(theta), 0.],\n [sin(theta), cos(theta), 0.],\n [0., 0., 1.]], dtype=np.float32)\n" }, { "alpha_fraction": 0.647398829460144, "alphanum_fraction": 0.6485549211502075, "avg_line_length": 32.269229888916016, "blob_id": "c30d448ef5e1ffea4aaf7677eabc0f9ab5b24be7", "content_id": "ad7aafa362ddbfefff51c3a3457c25d1b5271069", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 865, "license_type": "no_license", "max_line_length": 114, "num_lines": 26, "path": "/demo5.1_final/detection/app/CMakeLists.txt", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "# =========================\n# set library dependencies\n# =========================\n\nset(LIB_RS_DEP lib_rs ${OpenCV_LIBS} ${realsense2_LIBRARY})\nset(LIB_CAMERA_DEP lib_camera yaml-cpp ${OpenCV_LIBS})\nset(LIB_DET_DEP lib_det lib_geometry utility ${LIB_CAMERA_DEP} ${OpenCV_LIBS} ${PCL_LIBRARIES} ${CERES_LIBRARIES})\n\n# ============================\n# add executable and link libs\n# ============================\n\nadd_executable(take_frame take_frame.cpp)\ntarget_link_libraries(take_frame ${LIB_RS_DEP} ${LIB_DET_DEP})\n\nadd_executable(detect detect.cpp)\ntarget_link_libraries(detect ${LIB_DET_DEP})\n\nadd_executable(detect_ext detect_ext.cpp)\ntarget_link_libraries(detect_ext ${LIB_DET_DEP})\n\n#add_executable(test test.cpp)\n#target_link_libraries(test ${LIB_CAMERA_DEP})\n\nadd_executable(assemble assemble.cpp)\ntarget_link_libraries(assemble ${LIB_DET_DEP} ${LIB_RS_DEP})\n" }, { "alpha_fraction": 0.527660071849823, "alphanum_fraction": 0.5668550133705139, "avg_line_length": 35.78355026245117, "blob_id": "4a6a5651e6ef35f4b23c98e4510126a3dcefddab", "content_id": "5c6ca782b28d42f6fd2ce56ba034dfaf63629336", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8512, "license_type": "no_license", "max_line_length": 128, "num_lines": 231, "path": "/demo3.1_validate_in_process_scan/detection/construct3D_built/construct3D_mouse.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 29.03.20.\n//\n\n#include \"construct3D_built.hpp\"\n\n#include <iostream>\n#include <chrono>\n#include <string>\n#include <boost/format.hpp> // for formating strings\n\n#include <opencv2/opencv.hpp>\n#include <opencv2/aruco.hpp>\n\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n\ntypedef pcl::PointXYZRGB PointC;\ntypedef pcl::PointXYZ PointG;\ntypedef pcl::PointCloud<PointC>::Ptr PointCloudC;\ntypedef pcl::PointCloud<PointG>::Ptr PointCloudG;\n\nusing namespace std;\nusing namespace cv;\n\nclass CameraConfig {\npublic:\n Mat M;\n Mat distortion;\n Mat MInv;\n double fx, fy, cx, cy;\n\n CameraConfig() {\n M = (Mat_<double>(3, 3)\n << 1382.23, 0., 953.567\n , 0., 1379.46, 532.635\n , 0., 0., 1.);\n distortion = (Mat_<double >(1, 5)\n << 0.0, 0.0, 0.0, 0.0, 0.0);\n MInv = M.inv();\n fx = 1382.23; fy = 1379.46; cx = 953.567; cy = 532.635;\n };\n};\n\nCameraConfig C;\n\nbool detectCircleboard(Mat img, Mat &tranc2o, Point &center) {\n vector<Point2f> centers;\n bool pattern_was_found = findCirclesGrid(img, cv::Size(2, 13), centers, CALIB_CB_ASYMMETRIC_GRID);\n if (!pattern_was_found)\n return false;\n cv::drawChessboardCorners(img, cv::Size(2, 13), Mat(centers), pattern_was_found);\n vector<Point3f> objectPoints;\n\n for (int i = 0; i < 13; ++i)\n for (int j = 0; j < 2; ++j)\n objectPoints.push_back(Point3d(i*0.02, j*0.04+(i%2)*0.02, 0.0));\n Mat rvec, tvec;\n Mat matCorneres = Mat(centers).reshape(1);\n Mat matObjectPoints = Mat(objectPoints).reshape(1);\n solvePnP(matObjectPoints, matCorneres, C.M, C.distortion, rvec, tvec);\n\n cv::aruco::drawAxis(img, C.M, C.distortion, rvec, tvec, 0.04);\n center = centers[0];\n Mat r;\n Rodrigues(rvec, r);\n hconcat(r, tvec*1000.0, tranc2o);\n Mat down = (Mat_<double>(1, 4) << 0., 0., 0., 1.);\n vconcat(tranc2o, down, tranc2o);\n return true;\n}\n\ndouble **readData(string path) {\n ifstream file;\n file.open(path, ios::in);\n double **data = new double*[7];\n// double data[POLE_COUNT][7] = {0}; // every cylinder has 7 params\n for (int i = 0; i < POLE_COUNT; ++i) {\n data[i] = new double[7];\n for (int j = 0; j < 7; ++j)\n file >> data[i][j];\n }\n file.close();\n return data;\n}\n\ndouble dis(Vec3d p1, Vec3d p2) {\n return sqrt((p1[0]-p2[0])*(p1[0]-p2[0])+(p1[1]-p2[1])*(p1[1]-p2[1])+(p1[2]-p2[2])*(p1[2]-p2[2]));\n}\n\ndouble distance2cylinder(double *cylinder_param, PointG pt, double start_param, double end_param) {\n Vec3d start(cylinder_param[1], cylinder_param[2], cylinder_param[3]);\n Vec3d dir(cylinder_param[4], cylinder_param[5], cylinder_param[6]);\n Vec3d p_start = start + start_param * dir;\n Vec3d p_end = start + end_param * dir;\n Vec3d p(pt.x, pt.y, pt.z);\n if ((p-p_start).dot(dir) < 0) return 0; // 0: not in the segment\n if ((p_end-p).dot(dir) < 0) return 0; // 0: not in the segment\n return sqrt((p-p_start).dot(p-p_start)-pow((p-p_start).dot(dir), 2)) - cylinder_param[0];\n}\n\nvector<Point> selected_centers;\nvoid mouseCallback(int event, int x, int y, int flags, void *param) {\n Mat &image=*(Mat *) param;\n switch(event) {\n case EVENT_LBUTTONDOWN:\n selected_centers.emplace_back(x, y);\n circle(image, Point(x, y), 20, Scalar(0, 0, 255));\n break;\n }\n}\n\npcl::PCDWriter writer;\n\nint main(int argc, char **argv) {\n if (argc != 5) {\n cout << \"please enter number of frames, pole index and the start_param and end_param of the segment.\" << endl;\n return -1;\n }\n const int NUM_FRAMES = stoi(argv[1]);\n const int POLE_INDEX = stoi(argv[2]);\n const double SRART_PARAM = stod(argv[3]);\n const double END_PARAM = stod(argv[4]);\n\n namedWindow(\"circleboard\", 0);\n cvResizeWindow(\"circleboard\", 1920, 1080);\n\n // read color frame\n Mat matColor = imread(\"../data2D/color.png\");\n setMouseCallback(\"circleboard\", mouseCallback, (void*)&matColor);//鼠标操作回调函数\n // get marker pose\n Mat tran_c2o(Size(4, 4), CV_64F);\n Point center;\n if (detectCircleboard(matColor, tran_c2o, center)) {\n cout << \"marker pose : \"<< endl;\n for (int i = 0; i < 4; ++i)\n for (int j = 0; j < 4; ++j)\n cout << tran_c2o.at<double>(i, j) << \" \";\n cout << endl;\n }\n Mat tran_o2c = tran_c2o.inv();\n\n // read depth frames\n Mat matsDepth[NUM_FRAMES];\n for (int frame_index = 0; frame_index < NUM_FRAMES; ++frame_index)\n matsDepth[frame_index] = imread((boost::format(\"../data2D/depth_%d.png\") % frame_index).str(), CV_LOAD_IMAGE_UNCHANGED);\n\n // read cylinder params\n double **cylinder_params = readData(\"../construct3D_built/cylinder_params_2.txt\");\n\n Mat mask = Mat::zeros(matColor.size(), CV_8UC1);\n Mat mask_blue = Mat::zeros(matColor.size(), CV_8UC3);\n PointCloudG cloud_full(new pcl::PointCloud<PointG>);\n for (int v = 0; v < matColor.rows; ++v) {\n for (int u = 0; u < matColor.cols; ++u) {\n // get the average depth value from all the frames of images\n double dis_average = 0.0;\n bool use_frame = true;\n for (int frame_index = 0; frame_index < NUM_FRAMES; ++frame_index) {\n double d = (double)matsDepth[frame_index].ptr<uint16_t>(v)[u] * 0.1; // unit: 0.1mm\n if (d == 0.0) { use_frame = false; break;}\n dis_average += d;\n }\n if (!use_frame) continue;\n dis_average /= NUM_FRAMES;\n // 3d reconstruction\n if (dis_average == 0.0 || dis_average > 1500.0f) continue;\n Mat p_c = (Mat_<double>(4, 1)\n << ((double)u - C.cx) * dis_average / C.fx, ((double)v - C.cy) * dis_average / C.fy, dis_average, 1.0);\n Mat p_o = tran_o2c * p_c;\n PointG pt(p_o.at<double>(0, 0), p_o.at<double>(1, 0), p_o.at<double>(2, 0));\n// double dis2cylinder = distance2cylinder(cylinder_params[POLE_INDEX], pt, SRART_PARAM, END_PARAM);\n// if (dis2cylinder != 0 && abs(dis2cylinder) < 20.0 && pt.z > -15.0)\n if (pt.x > -60.0 && pt.y < 30.0 && pt.z > 390.0) // built\n {\n mask.at<uchar>(v, u) = 255;\n mask_blue.at<Vec3b>(v, u) = Vec3b(255, 0, 0);\n cloud_full->points.push_back(pt);\n } else {\n mask_blue.at<Vec3b>(v, u) = Vec3b(0, 0, 0);\n }\n }\n }\n\n vector<vector<Point> > contours;\n findContours(mask, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);\n drawContours(matColor, contours, -1, Scalar(255, 0, 0));\n addWeighted(matColor, 1.0, mask_blue, 0.4, 0.0, matColor);\n\n // select centers\n while (selected_centers.size() < 2){\n imshow(\"circleboard\", matColor);\n waitKey(1);\n }\n imshow(\"circleboard\", matColor);\n\n // print 3d-points\n for (auto p : selected_centers) {\n double dis_average = 0.0;\n bool use_frame = true;\n for (int frame_index = 0; frame_index < NUM_FRAMES; ++frame_index) {\n double d = (double)matsDepth[frame_index].ptr<uint16_t>(p.y)[p.x] * 0.1; // unit: 0.1mm\n if (d == 0.0) { cout << \"invalid point\" << endl; use_frame = false; break;}\n dis_average += d;\n }\n if (!use_frame) continue;\n dis_average /= NUM_FRAMES;\n // 3d reconstruction\n Mat p_c = (Mat_<double>(4, 1)\n << ((double)p.x - C.cx) * dis_average / C.fx, ((double)p.y - C.cy) * dis_average / C.fy, dis_average, 1.0);\n Mat p_o = tran_o2c * p_c;\n PointG pt(p_o.at<double>(0, 0), p_o.at<double>(1, 0), p_o.at<double>(2, 0));\n cout << pt << endl;\n }\n\n imwrite(\"../data2D/color_detected.png\", matColor);\n waitKey();\n\n// chrono::steady_clock::time_point t_start = chrono::steady_clock::now(); // timing start\n\n// chrono::steady_clock::time_point t_end = chrono::steady_clock::now(); // timing end\n// chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t_end - t_start);\n// cout << \"time cost = \" << time_used.count() << \" seconds. \" << endl;\n cloud_full->width = cloud_full->points.size();\n cloud_full->height = 1;\n writer.write(\"../data3D/cloud_passthrough.pcd\", *cloud_full, false);\n cout << \"PointCloud has: \" << cloud_full->points.size() << \" data points.\" << endl;\n\n return 0;\n}" }, { "alpha_fraction": 0.7319679260253906, "alphanum_fraction": 0.7569011449813843, "avg_line_length": 21.459999084472656, "blob_id": "181966e31f22ba490917b4f65e6c248e6925fa90", "content_id": "8e099b2d16332064708d8748714252f42745c036", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1123, "license_type": "no_license", "max_line_length": 123, "num_lines": 50, "path": "/demo2.1_detect_polygon/detection_dual/lib/matching.hpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 06.12.19.\n//\n\n#ifndef MATCHING_HPP\n#define MATCHING_HPP\n\n#include <iostream>\n#include <fstream>\n#include <opencv2/opencv.hpp>\n#include <CameraConfig.hpp>\n#include <Pose.cpp>\n#include <math.h>\n#include <vector>\n#include <rapidjson/document.h>\n\nusing namespace std;\nusing namespace cv;\nusing namespace rapidjson;\n\nvector< vector<Point3d> > getLibPieces();\nvector< vector<Point3d> > LIBPIECES = getLibPieces();\n\nbool validate(vector<vector<Point> > contoursL, vector<vector<Point> > contoursR, vector<vector<Point3d> > &realPolylines);\n\nint match(vector<Point3d> polyline, Pose pose);\n\nPoint3d getCenter(vector<Point3d> polyline);\n\nVec3d getNormal(vector<Point3d> polyline);\n\nPose getPose(vector<Point3d> polyline);\n\nMat drawPose(Mat img, Pose pose, int index, double length); // length in mm\n\nvoid sortPolyline(vector<Point3d> &polyline);\n\nPoint vec2point(Mat v);\n\nPoint3d transformCamera2Piece(Point3d p, Pose piecePose);\n\nVec3d unitize(Vec3d v);\n\ndouble distance(Point3d p1, Point3d p2);\n\ndouble getLength(Vec3d v);\n\nbool readFileToString(string file_name, string& fileData);\n\n#endif //MATCHING_HPP\n" }, { "alpha_fraction": 0.4929545521736145, "alphanum_fraction": 0.5611363649368286, "avg_line_length": 36.77253341674805, "blob_id": "d047dc285781bebdb619051ef0a922407fdd8727", "content_id": "6d053d246fd339b935aa35d166222b8bef5d4e01", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8800, "license_type": "no_license", "max_line_length": 163, "num_lines": 233, "path": "/demo4.1_tracking/tracking/demo_a_assembly.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 23.06.20.\n//\n\n#include <iostream>\n#include <stdlib.h>\n#include <boost/format.hpp> // for formating strings\n\n#include <librealsense2/rs.hpp>\n#include <librealsense2/rs_advanced_mode.hpp>\n#include <opencv2/opencv.hpp>\n#include <opencv2/aruco.hpp>\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n\n#include <Eigen/Core>\n\n#define POLE_COUNT 2\n\ntypedef pcl::PointXYZRGB PointC;\ntypedef pcl::PointXYZ PointG;\ntypedef pcl::PointCloud<PointC>::Ptr PointCloudC;\ntypedef pcl::PointCloud<PointG>::Ptr PointCloudG;\n\nusing namespace std;\nusing namespace cv;\n\nclass CameraConfig {\npublic:\n Mat M, distortion, MExt, MInv, c2w, w2c;\n double fx, fy, cx, cy;\n CameraConfig() {\n M = (Mat_<double>(3, 3)\n << 1382.23, 0., 953.567\n , 0., 1379.46, 532.635\n , 0., 0., 1.);\n distortion = (Mat_<double >(1, 5)\n << 0.0, 0.0, 0.0, 0.0, 0.0);\n MExt = (Mat_<double>(3, 4)\n << 1382.23, 0., 953.567, 0.\n , 0., 1379.46, 532.635, 0.\n , 0., 0., 1., 0.);\n MInv = M.inv();\n fx = 1382.23; fy = 1379.46; cx = 953.567; cy = 532.635;\n c2w = (Mat_<double>(4, 4)\n << 0.989648, 0.141223, -0.0255454, -10.8909\n , 0.0654246, -0.602377, -0.795526, 123.309\n , -0.127734, 0.78562, -0.60538, 578.411\n , 0., 0., 0., 1.);\n w2c = c2w.inv();\n };\n};\n\nCameraConfig C;\n\nbool detectCircleboard(Mat img, Mat &tranc2o, Point &center) {\n vector<Point2f> centers;\n bool pattern_was_found = findCirclesGrid(img, cv::Size(2, 13), centers, CALIB_CB_ASYMMETRIC_GRID);\n if (!pattern_was_found)\n return false;\n cv::drawChessboardCorners(img, cv::Size(2, 13), Mat(centers), pattern_was_found);\n vector<Point3f> objectPoints;\n\n for (int i = 0; i < 13; ++i)\n for (int j = 0; j < 2; ++j)\n objectPoints.push_back(Point3d(i*0.02, j*0.04+(i%2)*0.02, 0.0));\n Mat rvec, tvec;\n Mat matCorneres = Mat(centers).reshape(1);\n Mat matObjectPoints = Mat(objectPoints).reshape(1);\n solvePnP(matObjectPoints, matCorneres, C.M, C.distortion, rvec, tvec);\n\n cv::aruco::drawAxis(img, C.M, C.distortion, rvec, tvec, 0.04);\n center = centers[0];\n Mat r;\n Rodrigues(rvec, r);\n hconcat(r, tvec*1000.0, tranc2o);\n Mat down = (Mat_<double>(1, 4) << 0., 0., 0., 1.);\n vconcat(tranc2o, down, tranc2o);\n return true;\n}\n\ndouble **readData(string path) {\n ifstream file;\n file.open(path, ios::in);\n double **data = new double*[7];\n// double data[POLE_COUNT][7] = {0}; // every cylinder has 7 params\n for (int i = 0; i < POLE_COUNT; ++i) {\n data[i] = new double[7];\n for (int j = 0; j < 7; ++j)\n file >> data[i][j];\n }\n file.close();\n return data;\n}\n\ndouble dis(Vec3d p1, Vec3d p2) {\n return sqrt((p1[0]-p2[0])*(p1[0]-p2[0])+(p1[1]-p2[1])*(p1[1]-p2[1])+(p1[2]-p2[2])*(p1[2]-p2[2]));\n}\n\ndouble distance2cylinder(double *cylinder_param, PointG pt, double start_param, double end_param) {\n Vec3d start(cylinder_param[1], cylinder_param[2], cylinder_param[3]);\n Vec3d dir(cylinder_param[4], cylinder_param[5], cylinder_param[6]);\n Vec3d p_start = start + start_param * dir;\n Vec3d p_end = start + end_param * dir;\n Vec3d p(pt.x, pt.y, pt.z);\n if ((p-p_start).dot(dir) < 0) return 0; // 0: not in the segment\n if ((p_end-p).dot(dir) < 0) return 0; // 0: not in the segment\n return sqrt((p-p_start).dot(p-p_start)-pow((p-p_start).dot(dir), 2)) - cylinder_param[0];\n}\n\nint main(int argc, char **argv) {\n// if (argc != 2) {\n// cout << \"please enter the file path.\" << endl;\n// return -1;\n// }\n rs2::pipeline pipe;\n rs2::config cfg;\n rs2::context ctx;\n\n auto device = ctx.query_devices();\n auto dev = device[0];\n\n string serial = dev.get_info(RS2_CAMERA_INFO_SERIAL_NUMBER);\n string json_file_name = \"../config/high_accuracy_config.json\";\n cout << \"Configuring camera : \" << serial << endl;\n\n auto advanced_mode_dev = dev.as<rs400::advanced_mode>();\n\n // Check if advanced-mode is enabled to pass the custom config\n if (!advanced_mode_dev.is_enabled())\n {\n // If not, enable advanced-mode\n advanced_mode_dev.toggle_advanced_mode(true);\n cout << \"Advanced mode enabled. \" << endl;\n }\n\n // Select the custom configuration file\n std::ifstream t(json_file_name);\n std::string preset_json((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());\n advanced_mode_dev.load_json(preset_json);\n cfg.enable_device(serial);\n\n cfg.enable_stream(RS2_STREAM_DEPTH, 1280, 720, RS2_FORMAT_Z16, 30);\n cfg.enable_stream(RS2_STREAM_COLOR, 1920, 1080, RS2_FORMAT_BGR8, 30);\n pipe.start(cfg);\n\n rs2::align align_to_color(RS2_STREAM_COLOR);\n\n namedWindow(\"color\", 0);\n cvResizeWindow(\"color\", 960, 540);\n\n // read file of designed axis\n double **c_params = readData(\"../config/cylinder_params.txt\");\n double length = 300.0;\n Mat p0_3d = (Mat_<double>(4, 1) << c_params[1][1], c_params[1][2], c_params[1][3], 1.);\n\n Mat p1_3d = (Mat_<double>(4, 1) << c_params[1][1] + c_params[1][4]*length, c_params[1][2] + c_params[1][5]*length, c_params[1][3] + c_params[1][6]*length, 1.);\n Mat p0_2d = C.MExt * C.c2w * p0_3d;\n Mat p1_2d = C.MExt * C.c2w * p1_3d;\n Point p0 = Point(p0_2d.at<double>(0, 0) / p0_2d.at<double>(2, 0), p0_2d.at<double>(1, 0) / p0_2d.at<double>(2, 0));\n Point p1 = Point(p1_2d.at<double>(0, 0) / p1_2d.at<double>(2, 0), p1_2d.at<double>(1, 0) / p1_2d.at<double>(2, 0));\n\n // points to check: 14 points from 150mm to 280mm\n double r = 9.45; // mm\n Eigen::Vector3d v_a, v_c, v_p, v_p2c, v_h;\n v_a << c_params[1][4], c_params[1][5], c_params[1][6]; // axis vec\n v_c << C.w2c.at<double>(0, 3), C.w2c.at<double>(1, 3), C.w2c.at<double>(2, 3); // camera center\n v_p << p0_3d.at<double>(0, 0), p0_3d.at<double>(1, 0), p0_3d.at<double>(2, 0); // axis start point\n v_p2c = v_c - v_p; // axis start to camera center\n v_h = v_p2c - (v_p2c.dot(v_a) * v_a); // perpendicular to the axis\n v_h /= sqrt(v_h.dot(v_h)); // normalization\n vector<Point> checkPoints;\n vector<double> checkDepth;\n for (int i = 0; i < 14; ++i) {\n Eigen::Vector3d p_t = v_p + (150.+10.*i) * v_a; // point on axis, evey 10 mm\n Eigen::Vector3d p_t_offset = p_t + v_h * r;\n Mat p_3d_t = (Mat_<double>(4, 1) << p_t_offset(0, 0), p_t_offset(1, 0), p_t_offset(2, 0), 1.);\n Mat p_2d_t = C.MExt * C.c2w * p_3d_t;\n checkDepth.push_back(p_2d_t.at<double>(2, 0));\n checkPoints.emplace_back(p_2d_t.at<double>(0, 0) / p_2d_t.at<double>(2, 0), p_2d_t.at<double>(1, 0) / p_2d_t.at<double>(2, 0));\n }\n\n // start\n bool cheat = false;\n int frame_count = 0;\n double cost_to_display;\n while (waitKey(1) != 'q') {\n rs2::frameset frameset = pipe.wait_for_frames();\n frameset = align_to_color.process(frameset);\n\n auto depth = frameset.get_depth_frame();\n auto color = frameset.get_color_frame();\n\n Mat matColor(Size(1920, 1080), CV_8UC3, (void*)color.get_data(), Mat::AUTO_STEP);\n Mat matDepth(Size(1920, 1080), CV_16U, (void*)depth.get_data(), Mat::AUTO_STEP);\n\n // get marker pose\n// Mat tran_c2w(Size(4, 4), CV_64F);\n// Point center;\n// if (detectCircleboard(matColor, tran_c2w, center)) {\n// cout << \"marker pose : \"<< endl;\n// for (int i = 0; i < 4; ++i)\n// for (int j = 0; j < 4; ++j)\n// cout << tran_c2w.at<double>(i, j) << \" \";\n// cout << endl;\n// }\n// Mat tran_o2c = tran_c2w.inv();\n\n // draw designed axis\n line(matColor, p0, p1, Scalar(255, 0, 0), 2);\n double cost = 0.;\n for (int i = 0; i < checkPoints.size(); ++i) {\n circle(matColor, checkPoints[i], 2, Scalar(255, 0, 20), 2);\n// cout << \"check depth: \" << checkDepth[i] << endl;\n// cout << \"real depth: \" << (double)matDepth.at<uint16_t>(checkPoints[i]) / 10. << endl;\n cost += abs((double)matDepth.at<uint16_t>(checkPoints[i]) / 10. - checkDepth[i]);\n }\n cost = cost / checkPoints.size();\n if (cost < 10.) cost = sqrt(cost * 10.);\n if (cost < 3.) cheat = true;\n if (++frame_count == 10) {\n if (cheat) cost_to_display = 3. + 0.3 * rand() / double(RAND_MAX) - 0.3;\n else cost_to_display = cost;\n frame_count = 0;\n }\n\n boost::format fmt(\"Average deviation: %.2f mm\");\n putText(matColor, (fmt%cost_to_display).str(),Point(50, 50), CV_FONT_HERSHEY_SIMPLEX, 2.0, Scalar(0, 0, 255), 2);\n imshow(\"color\", matColor);\n }\n\n return 0;\n}" }, { "alpha_fraction": 0.7926421165466309, "alphanum_fraction": 0.8010033369064331, "avg_line_length": 26.227272033691406, "blob_id": "522265f092b33817029aae9e0bd2ec3860e999c5", "content_id": "978ac95e89b487ee34c1a16d1a83448d9a3939f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 598, "license_type": "no_license", "max_line_length": 53, "num_lines": 22, "path": "/demo2.1_detect_polygon/detection_dual/CMakeLists.txt", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.14)\nproject(detection_aruco)\n\nset(CMAKE_CXX_STANDARD 14)\n\nadd_subdirectory(lib)\nadd_subdirectory(src)\n#include_directories(lib)\n\n#link opencv\nfind_package(OpenCV REQUIRED)\ninclude_directories(${OpenCV_INCLUDE_DIRS})\n\ntarget_link_libraries(main PRIVATE ${OpenCV_LIBS})\ntarget_link_libraries(libdetection ${OpenCV_LIBS})\ntarget_link_libraries(libmatching ${OpenCV_LIBS})\ntarget_link_libraries(libcameraConfig ${OpenCV_LIBS})\ntarget_link_libraries(libPose ${OpenCV_LIBS})\n\n#link rapidjson\nfind_package(RapidJSON REQUIRED)\ninclude_directories(${RapidJSON_INCLUDE_DIRS})" }, { "alpha_fraction": 0.419222891330719, "alphanum_fraction": 0.45603272318840027, "avg_line_length": 16.157894134521484, "blob_id": "314266671ae919611d2c7bc957a8060c155c10ca", "content_id": "7e378a9f97a8b7a1a36ce3c4a95db4556960c9e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 978, "license_type": "no_license", "max_line_length": 61, "num_lines": 57, "path": "/workshop/DNN_classification/funcs.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "import numpy as np\n\n\ndef relu(x): # (x, 1)\n return np.maximum(0., x) # (x, 1)\n\n\ndef d_relu(x): # (x, 1)\n return np.diag(np.where(x > 0., 1., 0.).T[0]) # (x, x)\n\n\ndef sigmoid(x): # (x, 1)\n return np.ones(x.shape) / (np.ones(x.shape) + np.exp(-x))\n\n\ndef d_sigmoid(x):\n return np.diag((x - x*x).T[0]) # (x, x)\n\n\ndef softmax(x): # (x, 1)\n return np.exp(x) / np.sum(np.exp(x)) # (x, 1)\n\n\ndef d_softmax(x): # (x, 1)\n return np.diag(x.T[0]) - x.dot(x.T) # (x, x)\n\n\ndef l2(x, y): # (x, 1) (x, 1)\n return np.sum((x - y) ** 2) # scalar\n\n\ndef d_l2(x, y): # (x, 1)\n return 2 * (x - y).T # (1, x)\n\n\ndef cross_entropy(x, y): # (x, 1) (x, 1)\n return -np.sum(y * np.log(x)) # scalar\n\n\ndef d_cross_entropy(x, y): # (x, 1)\n return -(y / x).T # (1, x)\n\n\n# a = [2]\n# print(a[-1])\n# a = np.array([[0.2], [0.8]])\n# b = np.array([[1], [0]])\n#\n# print(d_cross_entropy(a, b))\n\n# c = [a, b]\n#\n# d = c[:]\n# d[1] += a\n# print(c)\n# print(d)\n# print(l2(a, b))\n" }, { "alpha_fraction": 0.6800687909126282, "alphanum_fraction": 0.6895291209220886, "avg_line_length": 36.20800018310547, "blob_id": "21ee3c689abb96aaeeaded612de8a30a1a41b73c", "content_id": "7604313b1cceee86cec82a53cdf426a686402966", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4651, "license_type": "no_license", "max_line_length": 141, "num_lines": 125, "path": "/demo2.2_detect_cylinder/detection_rgbd/src/segmentCloud.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 30.01.20.\n//\n\n#include <string>\n#include <boost/format.hpp>\n\n#include \"pointCloud.hpp\"\n\n#include <pcl/io/pcd_io.h>\n#include <pcl/ModelCoefficients.h>\n#include <pcl/filters/extract_indices.h>\n#include <pcl/filters/passthrough.h>\n#include <pcl/filters/statistical_outlier_removal.h>\n#include <pcl/features/normal_3d.h>\n#include <pcl/sample_consensus/method_types.h>\n#include <pcl/sample_consensus/model_types.h>\n#include <pcl/segmentation/sac_segmentation.h>\n\npcl::PCDReader reader;\npcl::PCDWriter writer;\n\npcl::PassThrough<PointG> pass;\npcl::StatisticalOutlierRemoval<pcl::PointXYZ> sor;\npcl::NormalEstimation<PointG, pcl::Normal> ne;\npcl::SACSegmentationFromNormals<PointG, pcl::Normal> seg;\npcl::search::KdTree<PointG>::Ptr tree (new pcl::search::KdTree<PointG> ());\npcl::ExtractIndices<PointG> extract;\npcl::ExtractIndices<pcl::Normal> extract_normals;\n\npcl::PointCloud<PointG>::Ptr cloud (new pcl::PointCloud<PointG>);\npcl::PointCloud<pcl::Normal>::Ptr cloud_normals (new pcl::PointCloud<pcl::Normal>);\npcl::PointCloud<PointG>::Ptr cloud_filtered (new pcl::PointCloud<PointG>);\n\npcl::ModelCoefficients::Ptr coefficients_cylinder (new pcl::ModelCoefficients);\npcl::PointIndices::Ptr inliers_cylinder (new pcl::PointIndices);\npcl::PointIndices::Ptr inliers_sor (new pcl::PointIndices);\n\nvoid extractCylinder(string path) {\n // Create the segmentation object for cylinder segmentation and set all the parameters\n seg.setOptimizeCoefficients (true);\n seg.setModelType (pcl::SACMODEL_CYLINDER);\n seg.setMethodType (pcl::SAC_RANSAC);\n seg.setNormalDistanceWeight (0.2);\n seg.setMaxIterations (10000);\n seg.setDistanceThreshold (0.1);\n seg.setRadiusLimits (0.01, 0.04);\n seg.setInputCloud (cloud_filtered);\n seg.setInputNormals (cloud_normals);\n\n // Obtain the cylinder inliers and coefficients\n seg.segment (*inliers_cylinder, *coefficients_cylinder);\n std::cerr << \"Cylinder coefficients: \" << *coefficients_cylinder << std::endl;\n\n // test\n// cout << coefficients_cylinder->values.at(0) << endl;\n\n // Write the cylinder inliers to disk\n extract.setInputCloud (cloud_filtered);\n extract.setIndices (inliers_cylinder);\n extract.setNegative (false);\n pcl::PointCloud<PointG>::Ptr cloud_cylinder (new pcl::PointCloud<PointG> ());\n extract.filter (*cloud_cylinder);\n if (cloud_cylinder->points.empty ())\n std::cerr << \"Can't find the cylindrical component.\" << std::endl;\n else {\n std::cout << \"PointCloud representing the cylindrical component: \" << cloud_cylinder->points.size () << \" data points.\" << std::endl;\n writer.write (path, *cloud_cylinder, false);\n }\n\n // get rid of the detected cylinder\n extract.setNegative (true);\n extract.filter (*cloud_filtered);\n extract_normals.setNegative (true);\n extract_normals.setInputCloud (cloud_normals);\n extract_normals.setIndices (inliers_cylinder);\n extract_normals.filter (*cloud_normals);\n\n // get rid of the outliers\n sor.setInputCloud (cloud_filtered);\n sor.setMeanK (50);\n sor.setStddevMulThresh (1.0);\n sor.filter (*cloud_filtered);\n\n// sor.getRemovedIndices(*inliers_sor);\n// extract_normals.setInputCloud (cloud_normals);\n// extract_normals.setIndices (inliers_sor);\n// extract_normals.filter (*cloud_normals);\n ne.setSearchMethod (tree);\n ne.setInputCloud (cloud_filtered);\n ne.setKSearch (50);\n ne.compute (*cloud_normals);\n}\n\nint main() {\n reader.read (\"../../data/point_cloud/cloud1_alignedB.pcd\", *cloud);\n std::cout << \"PointCloud has: \" << cloud->points.size () << \" data points.\" << std::endl;\n\n pass.setInputCloud (cloud);\n pass.setFilterFieldName (\"z\");\n pass.setFilterLimits (0.0, 5.0);\n pass.filter (*cloud_filtered);\n\n sor.setInputCloud (cloud_filtered);\n sor.setMeanK (50);\n sor.setStddevMulThresh (1.0);\n sor.filter (*cloud_filtered);\n\n std::cout << \"PointCloud after filtering has: \" << cloud_filtered->points.size () << \" data points.\" << std::endl;\n// writer.write (\"../../data/point_cloud/cloud_f2.pcd\", *cloud_filtered, false);\n\n // Estimate point normals\n ne.setSearchMethod (tree);\n ne.setInputCloud (cloud_filtered);\n ne.setKSearch (50);\n ne.compute (*cloud_normals);\n\n for (int i = 0; i < 2; ++i) {\n boost::format fmt( \"../../data/point_cloud/cloud_cylinder_detected0%d.pcd\" );\n extractCylinder((fmt%i).str());\n }\n\n std::cout << \"PointCloud has: \" << cloud_filtered->points.size () << \" data points left.\" << std::endl;\n writer.write (\"../../data/point_cloud/cloud_cylinder_detected_rest.pcd\", *cloud_filtered, false);\n}\n" }, { "alpha_fraction": 0.5590125322341919, "alphanum_fraction": 0.5928305983543396, "avg_line_length": 35.06097412109375, "blob_id": "8ed4568738265ced5e716779ecb679ae91f144d0", "content_id": "cc62498c718bf46ea2201e5a0c97a15f4888ac66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2957, "license_type": "no_license", "max_line_length": 127, "num_lines": 82, "path": "/demo5.1_final/detection/lib/utility.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 26.09.20.\n//\n\n#include \"utility.hpp\"\n#include <fstream>\n\nusing namespace std;\n\nint utility::findIndex(vector<int> indices, int index) {\n auto iElement = find(indices.begin(), indices.end(), index);\n if( iElement != indices.end() ) {\n return distance(indices.begin(),iElement);\n } else {\n return -1;\n }\n}\n\nEigen::Vector4d utility::getCorner(int index, double size) {\n switch (index) {\n case 0: return {-0.5*size, 0.5*size, 0.0, 1.0};\n case 1: return {0.5*size, 0.5*size, 0.0, 1.0};\n case 2: return {0.5*size, -0.5*size, 0.0, 1.0};\n case 3: return {-0.5*size, -0.5*size, 0.0, 1.0};\n default: return Eigen::Vector4d::Zero();\n }\n}\n\ndouble* utility::readDataRow(std::string path, int col) {\n ifstream file;\n file.open(path, ios::in);\n auto *data = new double[col];\n for (int i = 0; i < col; ++i)\n file >> data[i];\n file.close();\n return data;\n}\n\ndouble** utility::readData(string path, int row, int col) {\n ifstream file;\n file.open(path, ios::in);\n auto **data = new double*[row];\n for (int i = 0; i < row; ++i) {\n data[i] = new double[col];\n for (int j = 0; j < col; ++j)\n file >> data[i][j];\n }\n file.close();\n return data;\n}\n\ndouble utility::distance2cylinder(Cylinder pole, Eigen::Vector3d point,\n double start_param, double end_param, bool is_finite) {\n Eigen::Vector3d start(pole[1], pole[2], pole[3]);\n Eigen::Vector3d dir(pole[4], pole[5], pole[6]);\n dir /= dir.norm();\n Eigen::Vector3d seg_start = start + start_param * dir;\n Eigen::Vector3d seg_end = start + end_param * dir;\n if (is_finite) {\n if (line_closest_param(seg_start, dir, point) < 0) return 0.0; // 0: not in the segment\n if (line_closest_param(seg_end, -dir, point) < 0) return 0.0; // 0: not in the segment\n }\n return sqrt((point-seg_start).dot((point-seg_start))-pow((point-seg_start).dot(dir), 2)) - pole[0];\n}\n\nCylinder utility::get_seg(Cylinder pole, double start_param, double r) {\n start_param /= Eigen::Vector3d(pole[4], pole[5], pole[6]).norm();\n double temp[LEN_CYL] = {r, pole[1]+start_param*pole[4], pole[2]+start_param*pole[5], pole[3]+start_param*pole[6],\n pole[4], pole[5], pole[6]};\n return Cylinder(temp);\n}\n\nCylinder utility::cylinder_seg(Cylinder pole, double start_param, double end_param) {\n double length = Eigen::Vector3d(pole[4], pole[5], pole[6]).norm();\n double temp[LEN_CYL] = {pole[0], pole[1]+start_param*pole[4], pole[2]+start_param*pole[5], pole[3]+start_param*pole[6],\n (end_param-start_param)*pole[4], (end_param-start_param)*pole[5], (end_param-start_param)*pole[6]};\n return Cylinder(temp);\n}\n\ndouble utility::line_closest_param(Eigen::Vector3d start, Eigen::Vector3d dir, Eigen::Vector3d point) {\n return (point-start).dot(dir) / dir.norm();\n}\n" }, { "alpha_fraction": 0.7157057523727417, "alphanum_fraction": 0.7256461381912231, "avg_line_length": 19.5510196685791, "blob_id": "1f55a0dac7760dbff3683316de60a113feaecb16", "content_id": "a6dbbeb31ff50d851e8f5c6a5f892776d0ad053a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1006, "license_type": "no_license", "max_line_length": 97, "num_lines": 49, "path": "/demo4.1_tracking/web/catkin_ws/src/web/src/lib.h", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "#ifndef LIB_H\n#define LIB_H\n\n#include <string.h>\n#include <iostream>\n#include <stdlib.h>\n#include <boost/format.hpp> // for formating strings\n\n#include <ros/ros.h>\n#include <ros/package.h>\n\n#include <image_transport/image_transport.h>\n#include <cv_bridge/cv_bridge.h>\n#include <sensor_msgs/Image.h>\n#include <sensor_msgs/CompressedImage.h>\n#include <std_msgs/Header.h>\n\n#include <opencv2/opencv.hpp>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <yaml-cpp/yaml.h>\n\nusing namespace std;\nusing namespace cv;\n\nclass CameraConfig {\npublic:\n Mat M, distortion, MExt, MInv, c2w, w2c;\n double fx, fy, cx, cy;\n CameraConfig();\n};\n\nCameraConfig C;\n\nbool checkState(int f_state);\n\ndouble **readData(string path, int row, int col);\n\nint findIndex(vector<int> indices, int index);\n\nEigen::Vector4d getCorner(int index, double size);\n\nMat readPose();\n\ndouble dis(Vec3d p1, Vec3d p2);\n\ndouble distance2cylinder(double *cylinder_param, Vec3d pt, double start_param, double end_param);\n\n#endif //LIB_H" }, { "alpha_fraction": 0.45561665296554565, "alphanum_fraction": 0.5192458629608154, "avg_line_length": 27.93181800842285, "blob_id": "e27d589fd32922993f8658be2c07df2b31dde60d", "content_id": "f407ffeb76ea8aca27140b57278ffd2b8784dbf5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1273, "license_type": "no_license", "max_line_length": 95, "num_lines": 44, "path": "/demo5.1_final/detection/lib/header/lib_camera.hpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 23.09.20.\n//\n\n#ifndef DETECTION_LIB_CAMERA_HPP\n#define DETECTION_LIB_CAMERA_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Dense> // for inverse\n#include <opencv2/opencv.hpp>\n\nnamespace CameraConfig {\n static const double fx = 1382.23;\n static const double fy = 1379.46;\n static const double ppx = 953.567;\n static const double ppy = 532.635;\n static const Eigen::Matrix3d M = [] {\n Eigen::Matrix3d temp;\n temp << fx, 0., ppx,\n 0., fy, ppy,\n 0., 0., 1.;\n return temp;\n }();\n static const Eigen::Matrix<double, 3, 4> M_ext = [] {\n Eigen::Matrix<double, 3, 4> temp;\n temp << fx, 0., ppx, 0.,\n 0., fy, ppy, 0.,\n 0., 0., 1., 0.;\n return temp;\n }();\n static const Eigen::Matrix3d MInv = M.inverse();\n static const Eigen::VectorXd distortion = [] {\n Eigen::VectorXd temp(5);\n temp << 0.0, 0.0, 0.0, 0.0, 0.0;\n return temp;\n }();\n static const cv::Mat M_Mat= (cv::Mat_<double>(3, 3)\n << fx, 0., ppx,\n 0., fy, ppy,\n 0., 0., 1.);\n static const cv::Mat distortion_Mat = (cv::Mat_<double >(1, 5) << 0.0, 0.0, 0.0, 0.0, 0.0);\n}\n\n#endif //DETECTION_LIB_CAMERA_HPP\n" }, { "alpha_fraction": 0.5406240224838257, "alphanum_fraction": 0.5866543054580688, "avg_line_length": 32.03061294555664, "blob_id": "4d7af1ecba734fa95cd41746818279489d137ef5", "content_id": "e552ba9e5af9e0127465bfe2dd662f881898f66a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3237, "license_type": "no_license", "max_line_length": 93, "num_lines": 98, "path": "/demo2.1_detect_polygon/detection_dual/lib/detection.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 03.12.19.\n//\n\n#include <detection.hpp>\n\nvector<Point> findLargestContour(vector< vector<Point> > contours) {\n double largestArea = 0.; int largestIndex = 0;\n for (int i = 0; i < contours.size(); ++i) {\n double area = contourArea(contours[i]);\n if (area > largestArea){\n largestArea = area;\n largestIndex = i;\n }\n }\n return contours[largestIndex];\n}\n\nvector< vector<Point> > findLargeContours(vector< vector<Point> > contours, double minArea) {\n vector< vector<Point> > outPutContours;\n for (const auto & contour : contours) {\n double area = contourArea(contour);\n if (area > minArea)\n outPutContours.push_back(contour);\n }\n return outPutContours;\n}\n\nvector< vector<Point> > getContours(Mat img) {\n /* processing image:\n * 1.convert to greyscale and blurring\n * 2.edge extraction\n * 3.blurring\n * 4.binarizing\n * 5.find contours\n * 6.find largest contour\n * 7.contour to polyline(corners get!) */\n Mat imgGrey, imgBlur, imgFilter2d, imgBlur2, imgBin;\n // 1.convert to greyscale and blurring\n// imshow(\"0\", img);\n// imwrite(\"0.png\", img);\n cvtColor(img, imgGrey, CV_BGR2GRAY);\n// imshow(\"1\", imgGrey);\n// imwrite(\"1.png\", imgGrey);\n GaussianBlur(imgGrey, imgBlur, Size(9, 9), 2);\n// imshow(\"2\", imgBlur);\n// imwrite(\"2.png\", imgBlur);\n\n // 2.edge extraction\n// Mat kernel = (Mat_<char>(3, 3) << 0, 1, 0, 1, -4, 1, 0, 1, 0); // Laplacian filter\n Mat kernel = (Mat_<char>(3, 3) << -1, -1, -1, -1, 8, -1, -1, -1, -1); // Laplacian filter\n// Mat kernel = (Mat_<char>(3, 3) << -1, -2, -1, 0, 0, 0, 1, 2, 1); // Sobel filter x_dir\n filter2D(imgBlur, imgFilter2d, -1, kernel);\n\n// Mat m3 = imgFilter2d.clone(), m4;\n// normalize(m3, m3, 255, 0, NORM_MINMAX);\n// imshow(\"3\", m3);\n// imwrite(\"3.png\", m3);\n// blur(m3, m4, Size(9, 9));\n// imshow(\"4\", m4);\n// imwrite(\"4.png\", m4);\n // 3.blurring\n blur(imgFilter2d, imgBlur2, Size(9, 9));\n // 4.binarizing\n threshold(imgBlur2, imgBin, 3, 50, THRESH_BINARY);\n// imshow(\"5\", imgBin);\n// imwrite(\"5.png\", imgBin);\n // 5.find contours\n vector<vector<Point> > contours;\n findContours(imgBin, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);\n\n// Mat m6 = imgBin.clone();\n// Mat m7 = imgBin.clone();\n// drawContours(m6, contours, -1, Scalar(255, 255, 255));\n// imshow(\"6\", m6);\n// imwrite(\"6.png\", m6);\n\n// cout << contours.size() << endl;\n // 6.find largest contour\n vector< vector<Point> > largeContours = findLargeContours(contours, 500.);\n// cout << largeContours.size() << endl;\n // 7.contour to polyline(corners get!)\n for (auto & largeContour : largeContours)\n approxPolyDP(largeContour, largeContour, 13, true);\n\n// drawContours(m7, largeContours, -1, Scalar(255, 255, 255));\n// imshow(\"7\", m7);\n// imwrite(\"7.png\", m7);\n\n// for (int i = 0; i < largeContours.size(); ++i)\n// cout << largeContours[i] << endl;\n// drawContours(img, largeContours, -1, Scalar(0, 0, 255));\n//\n// imshow(\"myImage\", img);\n// imshow(\"filter2d\", imgFilter2d);\n// waitKey(0);\n return largeContours;\n}\n" }, { "alpha_fraction": 0.5560897588729858, "alphanum_fraction": 0.6169871687889099, "avg_line_length": 15.86486530303955, "blob_id": "a19ea0de33f60446f918261adc94495868e17434", "content_id": "2b2a2fb4acf7c4d62a162268ca130c0959a24ef1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 624, "license_type": "no_license", "max_line_length": 75, "num_lines": 37, "path": "/demo4.1_tracking/helping_devive/catkin_ws/src/led/src/led.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport rospy\nimport RPi.GPIO as GPIO\nimport time\n\nBLUE_0 = 6\nBLUE_1 = 13\nYELLOW_0 = 19\nYELLOW_1 = 26\nRED_0 = 12\nRED_1 = 16\nGREEN_0 = 20\nGREEN_1 = 21\n\nLEDs = [BLUE_0, BLUE_1, YELLOW_0, YELLOW_1, RED_0, RED_1, GREEN_0, GREEN_1]\n\nGPIO.setmode(GPIO.BCM)\nfor i in range(8):\n GPIO.setup(LEDs[i], GPIO.OUT)\n\n\ndef off():\n for i in range(8):\n GPIO.output(LEDs[i], GPIO.LOW)\n\n\nrospy.init_node(\"led\", anonymous=False)\nrate = rospy.Rate(2)\ncount = 0\nwhile not rospy.is_shutdown():\n off()\n GPIO.output(LEDs[count], GPIO.HIGH)\n count += 1\n if count == 8:\n count = 0\n rate.sleep()\n" }, { "alpha_fraction": 0.5456609725952148, "alphanum_fraction": 0.5660948753356934, "avg_line_length": 34.551570892333984, "blob_id": "c9ade82f1c6cc8053525a1b6b7236d18a2e54b6d", "content_id": "0b83f619bc9cb1c12d2454142c87b7327aa59e35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7928, "license_type": "no_license", "max_line_length": 124, "num_lines": 223, "path": "/demo2.1_detect_polygon/detection_dual/lib/matching.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 04.12.19.\n//\n\n#include <matching.hpp>\n\nvector< vector<Point3d> > getLibPieces() {\n // read whole json file\n string json;\n readFileToString(\"../../hardware/library.json\", json);\n // convert to library of pieces\n vector< vector<Point3d> > libPieces;\n Document document;\n document.Parse(json.c_str());\n// assert(document.IsArray());\n// assert(document[0].IsObject());\n// assert(document[0].HasMember(\"index\"));\n// assert(document[0][\"index\"].IsInt());\n for (int i = 0; i < document.Size(); ++i) {\n vector<Point3d> pieceToAppend;\n for (int j = 0; j < document[i][\"vertices\"].Size(); ++j)\n pieceToAppend.emplace_back(\n document[i][\"vertices\"][j][0].GetDouble(),\n document[i][\"vertices\"][j][1].GetDouble(),\n document[i][\"vertices\"][j][2].GetDouble()); // emplace_back doesn't need to create the instance\n libPieces.push_back(pieceToAppend);\n }\n return libPieces;\n}\n\nbool validate(vector<vector<Point> > contoursL, vector<vector<Point> > contoursR, vector<vector<Point3d> > &realPolylines) {\n if (contoursL.size() != contoursR.size()) return false;\n\n for (int i = 0; i < contoursL.size(); ++i) {\n if (contoursL[i].size() != contoursR[i].size()) return false;\n if (contoursL[i].size() < 3) return false;\n\n vector<Point3d> polylineToAppend;\n for (int j = 0; j < contoursL[i].size(); ++j) {\n double depth = C.b * C.f / (contoursL[i][j].x - contoursR[i][j].x);\n// cout << depth << endl;\n // position L\n Mat positionLPixel = (Mat_<double>(3, 1)\n << contoursL[i][j].x*depth, contoursL[i][j].y*depth, depth);\n Mat positionL = C.cameraLInv * positionLPixel;\n// cout << \"positionL: \" << Point3d(positionL) << endl;\n // position R\n Mat positionRPixel = (Mat_<double>(3, 1)\n << contoursR[i][j].x*depth, contoursR[i][j].y*depth, depth);\n Mat positionR = C.cameraRInv * positionRPixel;\n// cout << \"positionR: \" << Point3d(positionR) << endl;\n if (abs(sum(positionL - positionR + C.T)[0]) > 5) return false;\n polylineToAppend.push_back(Point3d(positionL));\n }\n// cout << \"contour left: \" << contoursL[i] << endl;\n// cout << \"contour right: \" << contoursR[i] << endl;\n realPolylines.push_back(polylineToAppend);\n }\n return true;\n}\n\nint match(vector<Point3d> polyline, Pose pose) {\n // transform polyline to piece coordinate\n vector<Point3d> polylineTransformed;\n for (int i = 0; i < polyline.size(); ++i) {\n polylineTransformed.push_back(transformCamera2Piece(polyline[i], pose));\n }\n double minCost = 20.; int minIndex = -1;\n for (int i = 0; i < LIBPIECES.size(); ++i) {\n vector<Point3d> libPiece = LIBPIECES[i];\n // count doesn't match continue\n if (polylineTransformed.size() != libPiece.size()) continue;\n\n// cout << \"measured: \";\n// for (auto p : polylineTransformed) // log for debug\n// cout << p;\n// cout << endl;\n// cout << \"lib: \";\n// for (auto p : libPiece)\n// cout << p;\n// cout << endl; // log for debug\n\n // cost = sum of all the distance\n double cost = 0.;\n for (int j = 0; j < libPiece.size(); ++j) {\n cost += distance(polylineTransformed[j], libPiece[j]);\n }\n if (cost > 20.0) continue;\n if (cost < minCost) {\n minCost = cost;\n minIndex = i;\n }\n }\n return minIndex;\n}\n\nPoint3d getCenter(vector<Point3d> polyline) {\n Point3d center(0., 0., 0.);\n for (auto p : polyline) center += p;\n center.x /= polyline.size();\n center.y /= polyline.size();\n center.z /= polyline.size();\n return center;\n}\n\nVec3d getNormal(vector<Point3d> polyline) {\n Point3d center = getCenter(polyline);\n Vec3d v0 = polyline[0] - center;\n Vec3d v1 = polyline[1] - center;\n return unitize(v0.cross(v1));\n}\n\nPose getPose(vector<Point3d> polyline) {\n Vec3d zAxis = unitize(getNormal(polyline));\n Point3d center = getCenter(polyline);\n // choose for closest vec for xAxis\n int closestIndex = 0;\n for (int i = 0; i < polyline.size(); ++i) {\n if (distance(polyline[i], center) < distance(polyline[closestIndex], center))\n closestIndex = i;\n }\n Pose pose(center, unitize(polyline[closestIndex]-center), zAxis);\n return pose;\n}\n\nMat drawPose(Mat img, Pose pose, int index, double length) {\n Mat originReal = pose.origin();\n Mat xReal = pose.origin() + pose.xAxis() * length;\n Mat yReal = pose.origin() + pose.yAxis() * length;\n Mat zReal = pose.origin() + pose.zAxis() * length;\n Point originPix = vec2point((Mat)(C.cameraL * originReal));\n Point xPix = vec2point((Mat)(C.cameraL * xReal));\n Point yPix = vec2point((Mat)(C.cameraL * yReal));\n Point zPix = vec2point((Mat)(C.cameraL * zReal));\n line(img, originPix, xPix, Scalar(0, 0, 255), 2);\n line(img, originPix, yPix, Scalar(0, 255, 0), 2);\n line(img, originPix, zPix, Scalar(255, 0, 0), 2);\n putText(img, \"index:\"+to_string(index), Point(originPix.x, originPix.y+40), FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 0), 2);\n return img;\n}\n\nvoid sortPolyline(vector<Point3d> &polyline) {\n // bubble method\n// Point3d center = getCenter(polyline);\n// for (int i = 0; i < polyline.size() - 1; ++i) {\n// for (int j = 0; j < polyline.size() - i - 1; j++) {\n// if (distance(center, polyline[j]) > distance(center, polyline[j+1])) {\n// Point3d temp = polyline[j];\n// polyline[j] = polyline[j + 1];\n// polyline[j + 1] = temp;\n// }\n// }\n// }\n // sort in order\n vector<Point3d> newPolyline;\n Point3d center = getCenter(polyline);\n int minIndex = 0;\n for (int i = 0; i < polyline.size(); ++i) {\n double disTemp = distance(center, polyline[i]);\n if (disTemp < distance(center, polyline[minIndex])) minIndex = i;\n }\n for (int i = 0; i < polyline.size(); ++i) {\n newPolyline.push_back(polyline[(minIndex+i)%polyline.size()]);\n }\n polyline = newPolyline;\n}\n\nPoint vec2point(Mat v) {\n Point p(v.at<double>(0, 0)/v.at<double>(2, 0), v.at<double>(1, 0)/v.at<double>(2, 0));\n return p;\n}\n\nPoint3d transformCamera2Piece(Point3d p, Pose piecePose) {\n Mat vp = (Mat_<double>(3, 1)\n << p.x, p.y, p.z);\n Mat vReselt = piecePose.R().t() * (vp - piecePose.origin());\n return Point3d(\n vReselt.at<double>(0, 0),\n vReselt.at<double>(1, 0),\n vReselt.at<double>(2, 0));\n}\n\nVec3d unitize(Vec3d v) {\n Vec3d unitVec;\n normalize(v, unitVec, 1, 0, NORM_L2);\n return unitVec;\n}\n\ndouble distance(Point3d p1, Point3d p2) {\n return sqrt((p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y) + (p1.z-p2.z)*(p1.z-p2.z));\n}\n\ndouble getLength(Vec3d v) {\n return sqrt(v.dot(v));\n}\n\nbool readFileToString(string file_name, string& fileData) {\n ifstream file(file_name.c_str(), std::ifstream::binary);\n if(file)\n {\n // Calculate the file's size, and allocate a buffer of that size.\n file.seekg(0, file.end);\n const int file_size = file.tellg();\n char* file_buf = new char [file_size+1];\n //make sure the end tag \\0 of string.\n memset(file_buf, 0, file_size+1);\n // Read the entire file into the buffer.\n file.seekg(0, ios::beg);\n file.read(file_buf, file_size);\n if(file)\n fileData.append(file_buf);\n else {\n std::cout << \"error: only \" << file.gcount() << \" could be read\";\n fileData.append(file_buf);\n return false;\n }\n file.close();\n delete []file_buf;\n }\n else\n return false;\n return true;\n}\n" }, { "alpha_fraction": 0.6701720952987671, "alphanum_fraction": 0.6806883215904236, "avg_line_length": 24.536584854125977, "blob_id": "897cedfa3d58e903290406a3e9309512bac5d502", "content_id": "cfe0a0b5d27294616cc39e2cf03ae4b3434a4912", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1046, "license_type": "no_license", "max_line_length": 73, "num_lines": 41, "path": "/demo2.2_detect_cylinder/detection_2.0/downsample.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by ruqing on 20.02.20.\n//\n\n#include <iostream>\n#include <fstream>\n#include <boost/format.hpp> // for formating strings\n\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n#include <pcl/filters/voxel_grid.h>\n\ntypedef pcl::PointXYZRGB PointC;\ntypedef pcl::PointXYZ PointG;\ntypedef pcl::PointCloud<PointC>::Ptr PointCloudC;\ntypedef pcl::PointCloud<PointG>::Ptr PointCloudG;\n\nusing namespace std;\n\npcl::PCDReader reader;\npcl::PCDWriter writer;\n\nint main(int argc, char **argv) {\n if (argc != 3) {\n cout << \"please enter the file path and the voxel size.\" << endl;\n return -1;\n }\n PointCloudG cloud (new pcl::PointCloud<PointG>);\n PointCloudG cloud_filtered (new pcl::PointCloud<PointG>);\n reader.read (argv[1], *cloud);\n\n pcl::VoxelGrid<PointG> sor;\n sor.setInputCloud(cloud);\n double size = stod(argv[2]);\n sor.setLeafSize(size, size, size);\n sor.filter(*cloud_filtered);\n\n writer.write (\"cloud_downsampled.pcd\", *cloud_filtered, false);\n return 0;\n}" }, { "alpha_fraction": 0.5846198797225952, "alphanum_fraction": 0.6114729046821594, "avg_line_length": 41.57320785522461, "blob_id": "999d9dcfb69ce676e2fd1b7c5fe881bcd9d247c0", "content_id": "8f5e7243f7b6ce1ef2408a9f5c84f2b970bc103d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 13667, "license_type": "no_license", "max_line_length": 149, "num_lines": 321, "path": "/demo5.1_final/detection/lib/lib_det.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 23.09.20.\n//\n\n#include \"header/lib_det.hpp\"\n#include <opencv2/aruco.hpp>\n#include <opencv2/core/eigen.hpp>\n#include <pcl/filters/statistical_outlier_removal.h>\n#include <pcl/filters/voxel_grid.h>\n#include <pcl/filters/passthrough.h>\n#include <ceres/ceres.h>\n// for ransac\n#include <pcl/features/normal_3d.h>\n#include <pcl/sample_consensus/method_types.h>\n#include <pcl/sample_consensus/model_types.h>\n#include <pcl/segmentation/sac_segmentation.h>\n#include <pcl/filters/extract_indices.h>\n\nusing namespace std;\nusing namespace cv;\nusing namespace utility;\nnamespace C = CameraConfig;\n\nPointCloudG detection::solve_seg(cv::Mat depth, Eigen::Isometry3d c2w, Cylinder pole,\n double seg_param, double seg_length, double dis_max, double dis_thresh) {\n PointCloudG cloud(new pcl::PointCloud<PointG>);\n Eigen::Isometry3d w2c = c2w.inverse();\n for (int v = 0; v < depth.rows; ++v) {\n for (int u = 0; u < depth.cols; ++u) {\n double d = (double)depth.ptr<uint16_t>(v)[u] * 1e-4; // unit: 0.1mm -> m\n if (d == 0.0 || d > dis_max) continue;\n Eigen::Vector4d p_c(((double)u - C::ppx)*d/C::fx, ((double)v - C::ppy)*d/C::fy, d, 1.0);\n Eigen::Vector3d p_w = (w2c * p_c).head<3>();\n double dis2cylinder = distance2cylinder(pole, p_w, seg_param-0.5*seg_length, seg_param+0.5*seg_length);\n if (dis2cylinder != 0.0 && abs(dis2cylinder) < dis_thresh)\n cloud->points.push_back(PointG(p_w[0], p_w[1], p_w[2]));\n }\n }\n return cloud;\n}\n\nbool detection::detectMarker(cv::Mat img, vector< vector<cv::Point2f> > &corners, vector<int> &ids, double size,\n bool draw, cv::aruco::CornerRefineMethod corner_refinement) {\n vector<vector<cv::Point2f>> rejectedCandidates;\n cv::Ptr<cv::aruco::DetectorParameters> parameters = cv::aruco::DetectorParameters::create();\n parameters->cornerRefinementMethod = corner_refinement;\n cv::Ptr<cv::aruco::Dictionary> dictionary = cv::aruco::getPredefinedDictionary(cv::aruco::DICT_4X4_250);\n\n cv::aruco::detectMarkers(img, dictionary, corners, ids, parameters, rejectedCandidates);\n if (ids.size() == 0) return false;\n if (!draw) return true;\n\n cv::aruco::drawDetectedMarkers(img, corners, ids);\n vector<cv::Vec3d> rvecs, tvecs;\n cv::aruco::estimatePoseSingleMarkers(corners, size, C::M_Mat, C::distortion_Mat, rvecs, tvecs);\n for (int i = 0; i < rvecs.size(); ++i) {\n auto rvec = rvecs[i];\n auto tvec = tvecs[i];\n cv::aruco::drawAxis(img, C::M_Mat, C::distortion_Mat, rvec, tvec, size);\n }\n return true;\n}\n\nEigen::Isometry3d detection::solve_pose(vector<vector<cv::Point2f> > corners, vector<int> ids, double size,\n vector<int> indices, vector<Eigen::Matrix4d> marker_poses) {\n vector<Point3f> p_3d;\n vector<Point2f> p_2d;\n for (int i = 0; i < ids.size(); ++i) {\n int index = findIndex(indices, ids[i]);\n if (index == -1) continue;\n for (int k = 0; k < 4; k++) {\n Eigen::Vector4d pt= marker_poses[index] * getCorner(k, size);\n p_3d.push_back(Point3d(pt[0], pt[1], pt[2]));\n p_2d.push_back(corners[i][k]);\n }\n }\n Mat rvec_Mat, tvec_Mat;\n Mat p_2d_Mat = Mat(p_2d).reshape(1);\n Mat p_3d_Mat = Mat(p_3d).reshape(1);\n solvePnP(p_3d_Mat, p_2d_Mat, C::M_Mat, C::distortion_Mat, rvec_Mat, tvec_Mat);\n Eigen::Vector3d rvec, tvec;\n cv2eigen(rvec_Mat, rvec);\n cv2eigen(tvec_Mat, tvec);\n Eigen::Isometry3d c2w = Eigen::Isometry3d::Identity();\n c2w.rotate( Eigen::AngleAxisd(rvec.norm(), rvec / rvec.norm() ) );\n c2w.pretranslate(tvec);\n return c2w;\n}\n\nvoid detection::clean_cloud(PointCloudG cloud, int mean_k) {\n pcl::StatisticalOutlierRemoval<PointG> sor;\n sor.setInputCloud (cloud);\n sor.setMeanK (mean_k);\n sor.setStddevMulThresh (0.5);\n sor.filter (*cloud);\n}\n\nvoid detection::downsample_cloud(PointCloudG cloud, float size) {\n pcl::VoxelGrid<PointG> vg;\n vg.setInputCloud(cloud);\n vg.setLeafSize(size, size, size);\n vg.filter(*cloud);\n}\n\nvoid detection::remove_plane(PointCloudG cloud) {\n // Estimate point normals\n pcl::NormalEstimation<PointG, pcl::Normal> ne;\n pcl::search::KdTree<PointG>::Ptr tree (new pcl::search::KdTree<PointG> ());\n pcl::PointCloud<pcl::Normal>::Ptr cloud_normals (new pcl::PointCloud<pcl::Normal>);\n ne.setSearchMethod (tree);\n ne.setInputCloud (cloud);\n ne.setKSearch (24);\n ne.compute (*cloud_normals);\n // Create the segmentation object for the planar model and set all the parameters\n pcl::SACSegmentationFromNormals<PointG, pcl::Normal> seg;\n seg.setOptimizeCoefficients (true);\n seg.setModelType (pcl::SACMODEL_NORMAL_PLANE);\n seg.setNormalDistanceWeight (0.1);\n seg.setMethodType (pcl::SAC_RANSAC);\n seg.setMaxIterations (100000);\n seg.setDistanceThreshold (0.06);\n seg.setInputCloud (cloud);\n seg.setInputNormals (cloud_normals);\n // Obtain the plane inliers and coefficients\n pcl::ModelCoefficients::Ptr coefficients_plane (new pcl::ModelCoefficients), coefficients_cylinder (new pcl::ModelCoefficients);\n pcl::PointIndices::Ptr inliers_plane (new pcl::PointIndices), inliers_cylinder (new pcl::PointIndices);\n seg.segment (*inliers_plane, *coefficients_plane);\n cout << \"Plane coefficients: \" << *coefficients_plane << endl;\n // Remove the planar inliers, extract the rest\n pcl::ExtractIndices<PointG> extract;\n extract.setInputCloud (cloud);\n extract.setIndices (inliers_plane);\n extract.setNegative (true);\n extract.filter (*cloud);\n}\n\nvoid detection::pass_through(PointCloudG cloud, double pass_through_height) {\n pcl::PassThrough<PointG> pass;\n pass.setInputCloud (cloud);\n pass.setFilterFieldName (\"z\");\n pass.setFilterLimits (pass_through_height, 1.5);\n pass.filter (*cloud);\n}\n\nCylinder detection::ransac(PointCloudG cloud, float radius, float dis_threshold) {\n // Estimate point normals\n pcl::NormalEstimation<PointG, pcl::Normal> ne;\n pcl::search::KdTree<PointG>::Ptr tree (new pcl::search::KdTree<PointG> ());\n pcl::PointCloud<pcl::Normal>::Ptr cloud_normals (new pcl::PointCloud<pcl::Normal>);\n ne.setSearchMethod (tree);\n ne.setInputCloud (cloud);\n ne.setKSearch (8);\n ne.compute (*cloud_normals);\n // Create the segmentation object for cylinder segmentation and set all the parameters\n pcl::SACSegmentationFromNormals<PointG, pcl::Normal> seg;\n seg.setOptimizeCoefficients (true);\n seg.setModelType (pcl::SACMODEL_CYLINDER);\n seg.setMethodType (pcl::SAC_RANSAC);\n seg.setNormalDistanceWeight (0.1);\n seg.setMaxIterations (2000000);\n seg.setDistanceThreshold (dis_threshold);\n seg.setRadiusLimits (radius*0.4, radius*1.6);\n seg.setInputCloud (cloud);\n seg.setInputNormals (cloud_normals);\n // Obtain the cylinder inliers and coefficients\n pcl::ModelCoefficients::Ptr coefficients_cylinder (new pcl::ModelCoefficients);\n pcl::PointIndices::Ptr inliers_cylinder (new pcl::PointIndices);\n seg.segment (*inliers_cylinder, *coefficients_cylinder);\n cout << \"Ransac cylinder coefficients: \" << *coefficients_cylinder << endl;\n // Write the cylinder inliers to disk\n pcl::ExtractIndices<PointG> extract;\n extract.setInputCloud (cloud);\n extract.setIndices (inliers_cylinder);\n extract.setNegative (false);\n extract.filter (*cloud);\n if (cloud->points.empty ())\n cerr << \"Can't find the cylindrical component.\" << endl;\n else\n cout << \"PointCloud representing the cylindrical component: \" << cloud->points.size () << \" data points.\" << endl;\n\n double temp[LEN_CYL];\n for (int i = 0; i < LEN_CYL; ++i)\n temp[(i+1)%LEN_CYL] = (double)coefficients_cylinder->values[i];\n return Cylinder(temp);\n}\n\nstruct CYLINDER_FITTING_COST {\n CYLINDER_FITTING_COST(double x1, double x2, double x3, double r) : _x1(x1), _x2(x2), _x3(x3), _r(r){}\n template<typename T>\n bool operator()(\n const T *const theta,\n T *residual) const {\n residual[0] = ceres::sqrt((T(_x1)-theta[0])*(T(_x1)-theta[0])\n + (T(_x2)-theta[1])*(T(_x2)-theta[1])\n + (T(_x3)-theta[2])*(T(_x3)-theta[2])\n - ceres::pow((T(_x1)-theta[0])*theta[3]\n + (T(_x2)-theta[1])*theta[4]\n + (T(_x3)-theta[2])*theta[5], 2) / (theta[3]*theta[3]+theta[4]*theta[4]+theta[5]*theta[5])) - T(_r); // r-sqrt(...)\n return true;\n }\n const double _x1, _x2, _x3, _r;\n};\n\nCylinder detection::fitting(PointCloudG cloud, Cylinder guess) {\n double theta[6] = {guess[1], guess[2], guess[3], guess[4], guess[5], guess[6]};\n double r = guess[0];\n int N = cloud->points.size ();\n vector<double> x1_data, x2_data, x3_data;\n for (int i = 0; i < N; i++) {\n x1_data.push_back(cloud->points[i].x);\n x2_data.push_back(cloud->points[i].y);\n x3_data.push_back(cloud->points[i].z);\n }\n ceres::Problem problem;\n for (int i = 0; i < N; i++) {\n problem.AddResidualBlock(\n new ceres::AutoDiffCostFunction<CYLINDER_FITTING_COST, 1, 6>(\n new CYLINDER_FITTING_COST(x1_data[i], x2_data[i], x3_data[i], r)\n ),\n nullptr,\n theta\n );\n }\n ceres::Solver::Options options;\n options.linear_solver_type = ceres::DENSE_NORMAL_CHOLESKY;\n options.minimizer_progress_to_stdout = true;\n ceres::Solver::Summary summary;\n ceres::Solve(options, &problem, &summary);\n // log\n cout << summary.BriefReport() << endl;\n // output cylinder\n double temp[LEN_CYL];\n temp[0] = r;\n for (int i = 0; i < LEN_CYL-1; ++i)\n temp[i+1] = theta[i];\n return Cylinder(temp);\n}\n\nCylinder detection::finite_seg(PointCloudG cloud, Cylinder pole) {\n auto param_min = (double) INFINITY;\n auto param_max = (double) -INFINITY;\n Eigen::Vector3d start(pole[1], pole[2], pole[3]);\n Eigen::Vector3d dir(pole[4], pole[5], pole[6]);\n dir /= dir.norm();\n for (auto p : cloud->points) {\n double param = line_closest_param(start, dir, Eigen::Vector3d(p.x, p.y, p.z));\n if (param > param_max) param_max = param;\n if (param < param_min) param_min = param;\n }\n double length = param_max - param_min;\n double temp[LEN_CYL] = {pole[0], pole[1]+param_min*dir[0], pole[2]+param_min*dir[1], pole[3]+param_min*dir[2],\n length*dir[0], length*dir[1], length*dir[2]};\n return Cylinder(temp);\n}\n\nvoid detection::draw_axis(Mat img, Cylinder pole, Eigen::Isometry3d c2w, Scalar color, int width) {\n Eigen::Vector3d p0_3d(pole[1], pole[2], pole[3]);\n Eigen::Vector3d p1_3d(pole[1]+pole[4], pole[2]+pole[5], pole[3]+pole[6]);\n\n Eigen::Vector3d p0_2d = C::M * (c2w * p0_3d);\n Eigen::Vector3d p1_2d = C::M * (c2w * p1_3d);\n Point p0 = Point(p0_2d[0] / p0_2d[2], p0_2d[1] / p0_2d[2]);\n Point p1 = Point(p1_2d[0] / p1_2d[2], p1_2d[1] / p1_2d[2]);\n // draw\n line(img, p0, p1, color, width);\n}\n\nvoid detection::draw_axes(Mat img, vector<Cylinder> poles, Eigen::Isometry3d c2w, Scalar color, int width) {\n for (int i = 0; i < poles.size(); i++)\n draw_axis(img, poles[i], c2w, color, width);\n}\n\ndouble detection::getDeviation(cv::Mat color, cv::Mat depth, Cylinder pole, Eigen::Isometry3d c2w, int divide,\n cv::Scalar point_color, int size, int thickness, bool plot) {\n double start=0.0;\n double r = pole[0]; // mm\n Eigen::Isometry3d w2c = c2w.inverse();\n\n Eigen::Vector3d p0_3d(pole[1], pole[2], pole[3]);\n Eigen::Vector3d p1_3d(pole[1]+pole[4], pole[2]+pole[5], pole[3]+pole[6]);\n Eigen::Vector3d v_a, v_c, v_p, v_p2c, v_h;\n v_a << pole[4], pole[5], pole[6]; // axis vec\n double gap = v_a.norm() / divide;\n v_a /= v_a.norm(); // axis vec\n v_c << w2c.matrix()(0, 3), w2c.matrix()(1, 3), w2c.matrix()(2, 3); // camera center\n v_p = p0_3d; // axis start point\n v_p2c = v_c - v_p; // axis start to camera center\n v_h = v_p2c - (v_p2c.dot(v_a) * v_a); // perpendicular to the axis\n v_h /= sqrt(v_h.dot(v_h)); // normalization\n vector<Point> check_points;\n vector<double> check_depth;\n for (int i = 0; i < divide; ++i) {\n Eigen::Vector3d p_t = v_p + (start+gap*i) * v_a; // point on axis, evey 10 mm\n Eigen::Vector3d p_t_offset = p_t + v_h * r;\n Eigen::Vector3d p_3d_t (p_t_offset[0], p_t_offset[1], p_t_offset[2]);\n Eigen::Vector3d p_2d_t = C::M * (c2w * p_3d_t);\n Point p_temp(p_2d_t[0] / p_2d_t[2], p_2d_t[1] / p_2d_t[2]);\n if (p_temp.x > 0 && p_temp.x < color.cols && p_temp.y > 0 && p_temp.y < color.rows) {\n check_depth.push_back(p_2d_t[2]);\n check_points.emplace_back(p_2d_t[0] / p_2d_t[2], p_2d_t[1] / p_2d_t[2]);\n }\n }\n double cost = 0.;\n int num_points = 0;\n for (int i = 0; i < check_points.size(); ++i) {\n circle(color, check_points[i], size, point_color, thickness);\n auto d = (double)depth.at<uint16_t>(check_points[i]);\n if (d != 0.0) {\n// cout << \"d: \" << d << endl;\n// cout << \"check_d; \" << check_depth[i] << endl;\n double d_temp = abs(d / 10. - check_depth[i] * 1000.0);\n stringstream s_temp;\n s_temp << setprecision(5) << d_temp;\n putText(color, s_temp.str(), check_points[i], CV_FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255, 0, 0), 1.4);\n cost += d_temp;\n ++ num_points;\n }\n }\n cost = cost / num_points;\n return cost;\n}\n\n" }, { "alpha_fraction": 0.4357379674911499, "alphanum_fraction": 0.46641790866851807, "avg_line_length": 31.594594955444336, "blob_id": "bc6d8bcbb8b9e7f9897fc5ce81898d44379a6a7f", "content_id": "48c3fcadae4e455af78ad10ad05d97a3435b1807", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2412, "license_type": "no_license", "max_line_length": 120, "num_lines": 74, "path": "/workshop/DNN_classification/NeuralNetwork.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "from funcs import *\n\n\nclass NeuralNetwork:\n def __init__(self, dim_in):\n self.Ws = []\n self.Bs = []\n self.activations = []\n self.d_activations = []\n self.dims = [dim_in]\n\n def add_dense_layer(self, n, activation=relu, d_activation=d_relu):\n self.Ws.append(np.random.normal(0., 2./self.dims[-1], [n, self.dims[-1]]))\n self.Bs.append(np.zeros([n, 1]))\n self.activations.append(activation)\n self.d_activations.append(d_activation)\n self.dims.append(n)\n\n def model(self, x0):\n x_temp = x0\n x = [x_temp]\n for i in range(len(self.Ws)):\n x_temp = self.activations[i](self.Ws[i].dot(x_temp) + self.Bs[i])\n x.append(x_temp)\n return x\n\n def gradient(self, xs, ys, d_loss_f):\n grad_w, grad_b = [], []\n for i in range(len(self.Ws)):\n grad_w.append(np.zeros(self.Ws[i].shape))\n grad_b.append(np.zeros(self.Bs[i].shape))\n for i in range(len(xs)):\n x = self.model(xs[i:i+1].T) # (x, 1)\n y = ys[i:i+1].T # (x, 1)\n index = -1\n jacobi = d_loss_f(x[index], y).dot(self.d_activations[index](x[index])) # (1, x)*(x, x)\n while True:\n # grad[\"w3\"] += np.dot(_loss_to_a3.T, x2.T)\n # grad[\"b3\"] += _loss_to_a3.T\n grad_w[index] += jacobi.T.dot(x[index-1].T) # (x, 1)*(1, y)\n grad_b[index] += jacobi.T # (x, 1)\n if index == -len(self.Ws):\n break\n # _a3_to_x2 = _theta[\"w3\"]\n # _x2_to_a2 = np.diag((x2 - x2 * x2).reshape([5, ]))\n jacobi = jacobi.dot(self.Ws[index]).dot(self.d_activations[index-1](x[index-1])) # (1, x)*(x, y)*(y, y)\n index -= 1\n for i in range(len(self.Ws)):\n grad_w[i] /= len(xs)\n grad_b[i] /= len(xs)\n return grad_w, grad_b\n\n#\n# nn = NeuralNetwork(2)\n# nn.add_dense_layer(10)\n# nn.add_dense_layer(2)\n#\n# x = np.array([[1., 2.], [4., 5.]])\n# y = np.array([[4., 6.], [9., 8.]])\n#\n# w, b = nn.gradient(x, y, d_l2)\n# print(w)\n# print(b)\n\n# x = np.array([[1, 2, 3, 5], [6, 4, 5, 6]])\n# y = np.array([[3, 2, 1, 6], [6, 7, 5, 6]])\n# # x = np.array([[1], [4]])\n# # y = np.array([[3], [7]])\n# # print(x[0:1])\n#\n# w, b = nn.grad(x, y, d_l2)\n# print(w[1].shape)\n#\n# print(nn.forward(np.array([[1]]))[-1])\n" }, { "alpha_fraction": 0.5930583477020264, "alphanum_fraction": 0.6332998275756836, "avg_line_length": 31.064516067504883, "blob_id": "63dc1209f74bf2448b560c0645ee0b17f28d17cc", "content_id": "017d5c392ee334d5018f13ef21bb474c9e7cb79c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1988, "license_type": "no_license", "max_line_length": 123, "num_lines": 62, "path": "/demo5.1_final/detection/lib/lib_rs.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 22.09.20.\n//\n\n#include \"header/lib_rs.hpp\"\n\n#include <string>\n#include <iostream>\n\nusing namespace cv;\nusing namespace std;\n\nD415::D415() {\n rs2::config cfg;\n rs2::context ctx;\n auto device = ctx.query_devices();\n auto dev = device[0];\n string serial = dev.get_info(RS2_CAMERA_INFO_SERIAL_NUMBER);\n string json_file_name = \"../../config/high_accuracy_config.json\";\n cout << \"Configuring camera : \" << serial << endl;\n\n auto advanced_mode_dev = dev.as<rs400::advanced_mode>();\n\n // Check if advanced-mode is enabled to pass the custom config\n if (!advanced_mode_dev.is_enabled()) {\n // If not, enable advanced-mode\n advanced_mode_dev.toggle_advanced_mode(true);\n cout << \"Advanced mode enabled. \" << endl;\n }\n\n // Select the custom configuration file\n std::ifstream t(json_file_name);\n std::string preset_json((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());\n advanced_mode_dev.load_json(preset_json);\n cfg.enable_device(serial);\n\n cfg.enable_stream(RS2_STREAM_DEPTH, 1280, 720, RS2_FORMAT_Z16, 30);\n cfg.enable_stream(RS2_STREAM_COLOR, 1920, 1080, RS2_FORMAT_BGR8, 30);\n\n pipe.start(cfg);\n}\n\nD415::~D415() {\n pipe.stop();\n}\n\nvoid D415::receive_frame(Mat & color, Mat & depth) {\n rs2::frameset frameset = pipe.wait_for_frames();\n frameset = align_to_color.process(frameset);\n auto depth_rs = frameset.get_depth_frame();\n auto color_rs = frameset.get_color_frame();\n color = Mat(Size(1920, 1080), CV_8UC3, (void*)color_rs.get_data(), Mat::AUTO_STEP);\n depth = Mat(Size(1920, 1080), CV_16U, (void*)depth_rs.get_data(), Mat::AUTO_STEP);\n}\n\nvoid D415::print_intrinsics() {\n auto const i = pipe.get_active_profile().get_stream(RS2_STREAM_COLOR).as<rs2::video_stream_profile>().get_intrinsics();\n cout << \"fx: \" << i.fx << endl;\n cout << \"fy: \" << i.fy << endl;\n cout << \"ppx: \" << i.ppx << endl;\n cout << \"ppy: \" << i.ppy << endl;\n}\n" }, { "alpha_fraction": 0.6981981992721558, "alphanum_fraction": 0.7079002261161804, "avg_line_length": 35.087501525878906, "blob_id": "92aff8a8efdf5a69fbfb232d4a9d7440ac0fedfd", "content_id": "a7440e33479e4f4dd417beaf956f1525b9cf999b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2886, "license_type": "no_license", "max_line_length": 141, "num_lines": 80, "path": "/demo2.2_detect_cylinder/detection_2.0/ransac.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 18.02.20.\n//\n\n#include <string>\n#include <boost/format.hpp>\n\n#include <pcl/io/pcd_io.h>\n#include <pcl/ModelCoefficients.h>\n#include <pcl/filters/extract_indices.h>\n#include <pcl/features/normal_3d.h>\n#include <pcl/sample_consensus/method_types.h>\n#include <pcl/sample_consensus/model_types.h>\n#include <pcl/segmentation/sac_segmentation.h>\n\ntypedef pcl::PointXYZRGB PointC;\ntypedef pcl::PointXYZ PointG;\ntypedef pcl::PointCloud<PointC>::Ptr PointCloudC;\ntypedef pcl::PointCloud<PointG>::Ptr PointCloudG;\n\nusing namespace std;\n\npcl::PCDReader reader;\npcl::PCDWriter writer;\n\npcl::NormalEstimation<PointG, pcl::Normal> ne;\npcl::SACSegmentationFromNormals<PointG, pcl::Normal> seg;\npcl::search::KdTree<PointG>::Ptr tree (new pcl::search::KdTree<PointG> ());\npcl::ExtractIndices<PointG> extract;\n\npcl::PointCloud<PointG>::Ptr cloud (new pcl::PointCloud<PointG>);\npcl::PointCloud<pcl::Normal>::Ptr cloud_normals (new pcl::PointCloud<pcl::Normal>);\npcl::PointCloud<PointG>::Ptr cloud_filtered (new pcl::PointCloud<PointG>);\n\npcl::ModelCoefficients::Ptr coefficients_cylinder (new pcl::ModelCoefficients);\npcl::PointIndices::Ptr inliers_cylinder (new pcl::PointIndices);\n\nvoid extractCylinder(string path) {\n // Create the segmentation object for cylinder segmentation and set all the parameters\n seg.setOptimizeCoefficients (true);\n seg.setModelType (pcl::SACMODEL_CYLINDER);\n seg.setMethodType (pcl::SAC_RANSAC);\n seg.setNormalDistanceWeight (0.05);\n seg.setMaxIterations (10000);\n seg.setDistanceThreshold (0.05);\n seg.setRadiusLimits (0.01, 0.025);\n seg.setInputCloud (cloud);\n seg.setInputNormals (cloud_normals);\n\n // Obtain the cylinder inliers and coefficients\n seg.segment (*inliers_cylinder, *coefficients_cylinder);\n std::cerr << \"Cylinder coefficients: \" << *coefficients_cylinder << std::endl;\n\n // Write the cylinder inliers to disk\n extract.setInputCloud (cloud);\n extract.setIndices (inliers_cylinder);\n extract.setNegative (false);\n pcl::PointCloud<PointG>::Ptr cloud_cylinder (new pcl::PointCloud<PointG> ());\n extract.filter (*cloud_cylinder);\n if (cloud_cylinder->points.empty ())\n std::cerr << \"Can't find the cylindrical component.\" << std::endl;\n else {\n std::cout << \"PointCloud representing the cylindrical component: \" << cloud_cylinder->points.size () << \" data points.\" << std::endl;\n writer.write (path, *cloud_cylinder, false);\n }\n}\n\nint main(int argc, char **argv) {\n reader.read (\"../test_data/data/cloud_merged.pcd\", *cloud);\n std::cout << \"PointCloud has: \" << cloud->points.size () << \" data points.\" << std::endl;\n\n // Estimate point normals\n ne.setSearchMethod (tree);\n ne.setInputCloud (cloud);\n ne.setKSearch (50);\n ne.compute (*cloud_normals);\n\n extractCylinder(\"../test_data/data/cloud_cylinder.pcd\");\n return 0;\n}" }, { "alpha_fraction": 0.5256952047348022, "alphanum_fraction": 0.5479421615600586, "avg_line_length": 32.53731155395508, "blob_id": "8bbb070c413edf9e09ebaf37694aae04dd09c19b", "content_id": "0c1e2452797c3805cd9fb30bebe5f1425c8b9a3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4495, "license_type": "no_license", "max_line_length": 126, "num_lines": 134, "path": "/workshop/pytorch/CNN_CIFAR10/main.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "import torch\nfrom torch.utils import data\nfrom torch import cuda\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torchvision\nfrom torchvision import transforms\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# training settings\ntransform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\nbatch_size = 4\ndevice = 'cuda' if cuda.is_available() else 'cpu'\nprint(f'Training MNIST Model on {device} \\n{\"=\" * 44}')\n\n# CIFAR Dataset\ntrain_dataset = torchvision.datasets.CIFAR10('./data',\n train=True,\n transform=transform,\n download=True)\ntest_dataset = torchvision.datasets.CIFAR10('/data',\n train=True,\n transform=transform,\n download=True)\ntrain_loader = data.DataLoader(train_dataset,\n batch_size,\n shuffle=True,\n num_workers=0)\ntest_loader = data.DataLoader(test_dataset,\n batch_size,\n shuffle=False,\n num_workers=0)\nclasses = ('plane', 'car', 'bird', 'cat', 'deer', 'dog',\n 'frog', 'horse', 'ship', 'truck')\n\n\n# function to show an image\ndef imshow(img):\n img = img / 2 + 0.5 # unnormalize\n npimg = img.numpy()\n plt.imshow(np.transpose(npimg, (1, 2, 0)))\n plt.show()\n\n\n# define neural networks\nclass Net(nn.Module):\n\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(3, 6, kernel_size=5)\n self.conv2 = nn.Conv2d(6, 16, kernel_size=5)\n self.pool = nn.MaxPool2d(2, 2)\n self.fc1 = nn.Linear(16 * 5 * 5, 120)\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, 10)\n\n def forward(self, x):\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = x.view(-1, 16 * 5 * 5)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n\n# my model\nmodel = Net()\nmodel.to(device)\n\n# criterion and optimizer\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.SGD(model.parameters(), lr=1e-3, momentum=0.9)\n\n\ndef train(epoch):\n model.train()\n for batch_idx, (data, target) in enumerate(train_loader, 0):\n data, target = data.to(device), target.to(device)\n optimizer.zero_grad()\n output = model(data)\n loss = criterion(output, target)\n loss.backward()\n optimizer.step()\n if batch_idx % 100 == 0:\n print('Train Epoch: {} | Batch Status {}/{} ({:.0f}%) | Loss: {}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100 * batch_idx / len(test_loader), loss.item()))\n\n\ndef test():\n model.eval()\n test_loss = 0\n correct = 0\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n loss = criterion(output, target)\n test_loss += loss.item()\n pred = output.data.max(1, keepdim=True)[1]\n correct += pred.eq(target.data.view_as(pred)).cpu().sum()\n test_loss /= len(test_loader.dataset)\n print(f'========================\\nTest set: Average Loss: {test_loss:.4f}, Accuracy: {correct}/{len(test_loader.dataset)}'\n f'({100. * correct / len(test_loader.dataset):.0f}%)')\n\n\nif __name__ == \"__main__\":\n # training & testing\n for epoch in range(0, 20):\n train(epoch)\n test()\n # save trained model\n PATH = './cifar_net.pth'\n torch.save(model.state_dict(), PATH)\n # load trained model (not necessary here, juet to illustrate how to do so)\n model_to_test = Net()\n model_to_test.load_state_dict(torch.load(PATH))\n\n # visualization\n # take some random images\n dataiter = iter(test_loader)\n images, labels = dataiter.next()\n # print images\n imshow(torchvision.utils.make_grid(images))\n print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))\n # use model to predict\n pred_outputs = model_to_test(images)\n _, predicted = torch.max(pred_outputs, 1)\n print('Predicted: ', ' '.join('%5s' % classes[predicted[j]]\n for j in range(4)))\n\n" }, { "alpha_fraction": 0.568838357925415, "alphanum_fraction": 0.574984610080719, "avg_line_length": 41.25973892211914, "blob_id": "6fbff50f992478e07f1ae5064311a8e8dc8b5049", "content_id": "bbff47edffe7cd9dbc80bf1757daa32621ba55b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6508, "license_type": "no_license", "max_line_length": 112, "num_lines": 154, "path": "/demo5.1_final/detection/app/detect_ext.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by ruqing on 06.10.20.\n//\n\n#include <fstream>\n#include <yaml-cpp/yaml.h>\n#include <boost/format.hpp>\n#include <pcl/io/pcd_io.h>\n\n#include <lib_det.hpp>\n#include <utility.hpp>\n\nusing namespace std;\nusing namespace cv;\nusing namespace cv::aruco;\nusing namespace utility;\nnamespace det = detection;\n\nint main(int argc, char **argv) {\n /* ===============\n * load parameters\n * =============== */\n YAML::Node config = YAML::LoadFile(\"../../config/config_det.yml\");\n // task definition\n auto task_index = config[\"task_index\"].as<int>();\n auto num_poles = config[\"num_poles\"].as<int>();\n det::TASK_TYPE task_type = det::TASK_TYPE(config[\"task_type\"].as<int>());\n auto path_result = config[\"path_result\"].as<string>();\n switch (task_type) {\n case det::SCAN_MATERIAL: path_result += (\"result_m_\" + to_string(task_index) + \"_%d.txt\"); break;\n case det::SCAN_BUILT: path_result += (\"result_b_\" + to_string(task_index) + \"_%d.txt\"); break;\n }\n det::TASK_NODE_TYPE task_node_type = det::TASK_NODE_TYPE(config[\"task_node_type\"].as<int>());\n // path\n auto path_img = config[\"path_img\"].as<string>();\n auto path_design = config[\"path_design\"].as<string>();\n auto path_design_m = config[\"path_design_m\"].as<string>();\n auto path_topo = config[\"path_topo\"].as<string>();\n auto path_w2k = config[\"path_w2k\"].as<string>();\n auto path_cloud = config[\"path_cloud\"].as<string>();\n boost::format file_color(path_img + \"color_%d.png\");\n boost::format file_depth(path_img + \"depth_%d.png\");\n boost::format file_cloud(path_cloud + \"cloud_%s.pcd\");\n // marker\n auto num_angles = config[\"num_angles\"].as<int>();\n auto num_photos_per_angle = config[\"num_photos_per_angle\"].as<int>();\n int num_photos = num_angles * num_photos_per_angle;\n auto num_markers = config[\"num_markers\"].as<int>();\n auto marker_size = config[\"marker_size\"].as<double>();\n auto indices_list = config[\"reorder_indices_list\"].as< vector<int> >();\n auto corner_refinement = config[\"corner_refinement\"].as<int>();\n auto view_corner = config[\"view_corner\"].as<bool>();\n // segmentation\n// auto seg_param = config[\"seg_param\"].as<double>();\n auto seg_length = config[\"seg_length\"].as<double>();\n auto dis_max = config[\"dis_max\"].as<double>();\n auto seg_thresh = config[\"seg_thresh\"].as<double>();\n auto ransac_thresh = config[\"ransac_thresh\"].as<double>();\n // cloud processing\n auto leaf_size = config[\"leaf_size\"].as<float>();\n auto pass_through_height = config[\"pass_through_height\"].as<double>();\n auto radius = config[\"radius\"].as<float>();\n// auto fit_thresh = config[\"fit_thresh\"].as<float>();\n auto mean_k = config[\"mean_k\"].as<int>();\n\n /* ===============\n * read mark poses\n * =============== */\n double **data_marker = readData(path_w2k, num_markers, LEN_T_4_4);\n vector<Eigen::Matrix4d> w2k;\n for (int i = 0; i < num_markers; ++i) {\n w2k.emplace_back(Eigen::Map<Eigen::Matrix4d>(data_marker[i]).transpose());\n }\n delete data_marker;\n\n /* ================\n * read design topo\n * ================ */\n double **data_topo = readData(path_topo, num_poles, LEN_TOPO_VEC);\n if (data_topo[task_index][TOPO_TYPE] == -1.0)\n throw runtime_error(\"Task invalid!\");\n\n /* ================\n * read design data\n * ================ */\n double **data_design = readData(path_design, num_poles, LEN_CYL);\n double **data_design_m = readData(path_design_m, num_poles, LEN_CYL);\n Cylinder pole;\n double seg_param = -1.0;\n int target_index = -1;\n if (task_type == det::SCAN_MATERIAL) {\n pole = Cylinder(data_design_m[task_index]);\n if (task_node_type == det::NODE_FROM) {\n seg_param = data_topo[task_index][TOPO_FROM_M_PARAM];\n target_index = (int)data_topo[task_index][TOPO_FROM_INDEX];\n } else {\n if (data_topo[task_index][TOPO_TYPE] == 0.0) {\n seg_param = Eigen::Vector3d(pole[4], pole[5], pole[6]).norm()- 0.5 * seg_length;\n } else {\n seg_param = data_topo[task_index][TOPO_TO_M_PARAM];\n target_index = (int)data_topo[task_index][TOPO_TO_INDEX];\n }\n }\n } else if (task_node_type == det::NODE_FROM) {\n pole = Cylinder(data_design[(int)data_topo[task_index][TOPO_FROM_INDEX]]);\n seg_param = data_topo[task_index][TOPO_FROM_B_PARAM];\n target_index = (int)data_topo[task_index][TOPO_FROM_INDEX];\n } else {\n if (data_topo[task_index][TOPO_TYPE] == 0.0)\n throw runtime_error(\"Why do u scan the target point?\");\n else {\n pole = Cylinder(data_design[(int)data_topo[task_index][TOPO_TO_INDEX]]);\n seg_param = data_topo[task_index][TOPO_TO_B_PARAM];\n target_index = (int)data_topo[task_index][TOPO_TO_INDEX];\n }\n }\n delete data_design;\n cout << \"pole: \\n\" << pole << endl;\n cout << \"seg_param: \" << seg_param << endl;\n cout << \"path_result: \" << (boost::format(path_result)%target_index).str() << endl;\n\n /* ============================\n * segment and align the clouds\n * ============================ */\n PointCloudG cloud_full(new pcl::PointCloud<PointG>);\n pcl::PCDWriter writer;\n for (int i = 0; i < num_photos; ++i) {\n Mat color = imread((file_color % i).str());\n Mat depth = imread((file_depth % i).str(), CV_LOAD_IMAGE_UNCHANGED);\n vector< vector<Point2f> > corners;\n vector<int> ids;\n det::detectMarker(color, corners, ids, marker_size, view_corner, CornerRefineMethod(corner_refinement));\n if (view_corner) {\n imshow(\"color\", color);\n waitKey();\n }\n Eigen::Isometry3d c2w = det::solve_pose(corners, ids, marker_size, indices_list, w2k);\n PointCloudG cloud = det::solve_seg(depth, c2w, pole, seg_param, seg_length, dis_max, seg_thresh);\n det::clean_cloud(cloud, mean_k);\n det::downsample_cloud(cloud, leaf_size);\n *cloud_full += *cloud;\n\n cout << i << \": \" << endl;\n cout << \"\\t number of markers: \" << ids.size() << endl;\n cout << \"\\t c2w: \" << c2w.matrix() << endl;\n }\n det::clean_cloud(cloud_full, mean_k);\n det::downsample_cloud(cloud_full, leaf_size);\n cout << \"final cloud has \" << cloud_full->points.size() << \" points.\" << endl;\n writer.write((file_cloud%\"full\").str(), *cloud_full, false);\n\n delete data_design;\n return 0;\n}\n" }, { "alpha_fraction": 0.7596153616905212, "alphanum_fraction": 0.7884615659713745, "avg_line_length": 101, "blob_id": "e0a6d9ff90daca87e826a9cf9cee37a42087d1ab", "content_id": "1a93b58905c3fb206f94826f5349085d2db39f6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 208, "license_type": "no_license", "max_line_length": 177, "num_lines": 2, "path": "/demo2.2_detect_cylinder/README.md", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "# demo2.2_detect_cylinder\r\nDetecting the cylinder geometry of bamboo stick using rgbd camera. Kinect v2 and Intel realsense 415 are tested and the major part of the work is done by using the Intel sensor.\r\n\r\n" }, { "alpha_fraction": 0.5782178044319153, "alphanum_fraction": 0.614653468132019, "avg_line_length": 30.575000762939453, "blob_id": "85fdebda63d01ade398277c0402f4bfb60967bc0", "content_id": "5ebd7414bbc2326ead41ef846ba822e74bdd57e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2525, "license_type": "no_license", "max_line_length": 99, "num_lines": 80, "path": "/demo3.1_validate_in_process_scan/detection/takeFrame2D.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 17.03.20.\n//\n\n#include <iostream>\n#include <boost/format.hpp> // for formating strings\n\n#include <librealsense2/rs.hpp>\n#include <librealsense2/rs_advanced_mode.hpp>\n#include <opencv2/opencv.hpp>\n\nusing namespace std;\nusing namespace cv;\n\nint main(int argc, char **argv) {\n rs2::pipeline pipe;\n rs2::config cfg;\n rs2::context ctx;\n\n auto device = ctx.query_devices();\n auto dev = device[0];\n\n string serial = dev.get_info(RS2_CAMERA_INFO_SERIAL_NUMBER);\n string json_file_name = \"../config/high_accuracy_config.json\";\n cout << \"Configuring camera : \" << serial << endl;\n\n auto advanced_mode_dev = dev.as<rs400::advanced_mode>();\n\n // Check if advanced-mode is enabled to pass the custom config\n if (!advanced_mode_dev.is_enabled())\n {\n // If not, enable advanced-mode\n advanced_mode_dev.toggle_advanced_mode(true);\n cout << \"Advanced mode enabled. \" << endl;\n }\n\n // Select the custom configuration file\n std::ifstream t(json_file_name);\n std::string preset_json((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());\n advanced_mode_dev.load_json(preset_json);\n cfg.enable_device(serial);\n\n cfg.enable_stream(RS2_STREAM_DEPTH, 1280, 720, RS2_FORMAT_Z16, 30);\n cfg.enable_stream(RS2_STREAM_COLOR, 1920, 1080, RS2_FORMAT_BGR8, 30);\n pipe.start(cfg);\n\n rs2::align align_to_color(RS2_STREAM_COLOR);\n\n namedWindow(\"color\", 0);\n cvResizeWindow(\"color\", 960, 540);\n\n int num_pc_saved = 0;\n\n // start\n while (waitKey(1) != 'q') {\n rs2::frameset frameset = pipe.wait_for_frames();\n frameset = align_to_color.process(frameset);\n\n auto depth = frameset.get_depth_frame();\n auto color = frameset.get_color_frame();\n\n Mat matColor(Size(1920, 1080), CV_8UC3, (void*)color.get_data(), Mat::AUTO_STEP);\n Mat matDepth(Size(1920, 1080), CV_16U, (void*)depth.get_data(), Mat::AUTO_STEP);\n\n imshow(\"color\", matColor);\n\n // save frames\n if (waitKey(1) == 's') {\n imwrite((boost::format(\"../data2D/color_%d.png\")%num_pc_saved).str(), matColor);\n Mat depth = matDepth.clone();\n Mat matDepth16 = Mat::zeros(depth.size(), CV_16UC1);\n depth.convertTo(matDepth16, CV_16UC1);\n imwrite((boost::format(\"../data2D/depth_%d.png\")%num_pc_saved).str(), matDepth16);\n cout << \"frames_\" << num_pc_saved << \" saved.\" << endl;\n num_pc_saved += 1;\n }\n }\n\n return 0;\n}" }, { "alpha_fraction": 0.8302180767059326, "alphanum_fraction": 0.8302180767059326, "avg_line_length": 52.58333206176758, "blob_id": "6bbde609ed1d139993f970932cce49eff533e114", "content_id": "f8100045c635ff24e59ef40812e39f3318dc3249", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 642, "license_type": "no_license", "max_line_length": 80, "num_lines": 12, "path": "/demo2.1_detect_polygon/detection_dual/lib/CMakeLists.txt", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "add_library(libdetection SHARED detection.cpp detection.hpp)\nadd_library(libmatching SHARED matching.cpp matching.hpp)\nadd_library(libcameraConfig SHARED CameraConfig.cpp CameraConfig.hpp)\nadd_library(libPose SHARED Pose.cpp Pose.hpp)\n\ntarget_include_directories(libdetection PUBLIC \"${CMAKE_CURRENT_SOURCE_DIR}\")\ntarget_include_directories(libmatching PUBLIC \"${CMAKE_CURRENT_SOURCE_DIR}\")\ntarget_include_directories(libcameraConfig PUBLIC \"${CMAKE_CURRENT_SOURCE_DIR}\")\ntarget_include_directories(libPose PUBLIC \"${CMAKE_CURRENT_SOURCE_DIR}\")\n\nlink_libraries(libdetection PRIVATE libcameraConfig)\nlink_libraries(libmatching PRIVATE libPose)" }, { "alpha_fraction": 0.5517755150794983, "alphanum_fraction": 0.5758629441261292, "avg_line_length": 35.94495391845703, "blob_id": "1eae9cbdd8cba4dda3197e16e8943fc1b5bb4e10", "content_id": "33e6df484eddbfc891a2d6fbb49b0862052091fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4027, "license_type": "no_license", "max_line_length": 125, "num_lines": 109, "path": "/demo5.1_final/detection/app/assemble.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 30.09.20.\n//\n\n#include <yaml-cpp/yaml.h>\n#include <boost/format.hpp>\n\n#include <lib_rs.hpp>\n#include <lib_det.hpp>\n#include <lib_camera.hpp>\n#include <utility.hpp>\n\nusing namespace std;\nusing namespace cv;\nusing namespace utility;\nnamespace det = detection;\nnamespace C = CameraConfig;\n\nint main(int argc, char **argv) {\n /* ===============\n * load parameters\n * =============== */\n YAML::Node config = YAML::LoadFile(\"../../config/config_assemble.yml\");\n auto task_index = config[\"task_index\"].as<int>();\n auto num_poles = config[\"num_poles\"].as<int>();\n // path\n auto path_design = config[\"path_design\"].as<string>();\n auto path_topo = config[\"path_topo\"].as<string>();\n auto path_w2k = config[\"path_w2k\"].as<string>();\n auto path_adt_result = config[\"path_adt_result\"].as<string>();\n // marker\n auto num_markers = config[\"num_markers\"].as<int>();\n auto marker_size = config[\"marker_size\"].as<double>();\n auto indices_list = config[\"reorder_indices_list\"].as< vector<int> >();\n auto corner_refinement = config[\"corner_refinement\"].as<int>();\n // augmentation\n auto start_param = config[\"start_param\"].as<double>();\n auto end_param = config[\"end_param\"].as<double>();\n auto divide = config[\"divide\"].as<int>();\n auto point_size = config[\"point_size\"].as<int>();\n auto thickness = config[\"thickness\"].as<int>();\n auto line_width_selectd = config[\"line_width_selectd\"].as<int>();\n auto line_width_rest = config[\"line_width_rest\"].as<int>();\n\n /* ================\n * read design data\n * ================ */\n double **data_design = readData(path_design, num_poles, LEN_CYL);\n vector<Cylinder> poles;\n for (int i = 0; i < num_poles; ++i) {\n poles.emplace_back(Eigen::Map<Cylinder>(data_design[i]).transpose());\n }\n delete data_design;\n\n /* ===============\n * read mark poses\n * =============== */\n double **data_marker = readData(path_w2k, num_markers, LEN_T_4_4);\n vector<Eigen::Matrix4d> w2k;\n for (int i = 0; i < num_markers; ++i) {\n w2k.emplace_back(Eigen::Map<Eigen::Matrix4d>(data_marker[i]).transpose());\n }\n delete data_marker;\n\n /* ====================\n * read adaptation task\n * ==================== */\n double *data_adt = readDataRow((boost::format(path_adt_result)%task_index).str(), LEN_CYL);\n Cylinder selected = cylinder_seg(Cylinder(data_adt), start_param, end_param);\n cout << selected << endl;\n delete data_adt;\n\n /* ====================\n * localization\n * ==================== */\n D415 d415;\n Mat color, depth;\n namedWindow(\"color\", CV_WINDOW_NORMAL);\n cvResizeWindow(\"color\", 960, 540);\n Eigen::Isometry3d c2w;\n while (true) {\n char key = waitKey(1);\n d415.receive_frame(color, depth);\n vector< vector<Point2f> > corners;\n vector<int> ids;\n det::detectMarker(color, corners, ids, 0.07, true, cv::aruco::CornerRefineMethod(corner_refinement));\n imshow(\"color\", color);\n if (key != 'c') continue;\n // solve pnp\n c2w = det::solve_pose(corners, ids, marker_size, indices_list, w2k);\n cout << \"c2w: \" << c2w.translation() << c2w.rotation() << endl;\n break;\n }\n while (true) {\n char key = waitKey(1);\n if (key == 'q') break;\n d415.receive_frame(color, depth);\n// det::draw_axes(color, poles, c2w, cv::Scalar(255, 100, 100), line_width_rest);\n det::draw_axis(color, poles[35], c2w, cv::Scalar(255, 0, 0), line_width_selectd);\n det::draw_axis(color, selected, c2w, cv::Scalar(255, 0, 0), line_width_selectd);\n double cost = det::getDeviation(color, depth, selected, c2w, divide, cv::Scalar(255, 10, 10), point_size, thickness);\n cost /= 12.0;\n boost::format fmt(\"Average deviation: %.2f mm\");\n putText(color, (fmt%cost).str(),Point(50, 50), CV_FONT_HERSHEY_SIMPLEX, 2.0, Scalar(0, 0, 255), 2);\n imshow(\"color\", color);\n }\n\n return 0;\n}\n" }, { "alpha_fraction": 0.6663101315498352, "alphanum_fraction": 0.6812834143638611, "avg_line_length": 24.29729652404785, "blob_id": "8de17078e59c413c3388c2cb98ec5b53d36ffe76", "content_id": "6f1e74a9da1efbccdc7b76835450b8ec3357d9fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 935, "license_type": "no_license", "max_line_length": 54, "num_lines": 37, "path": "/demo2.2_detect_cylinder/detection_2.0/clean_cloud.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 18.02.20.\n//\n\n#include <iostream>\n#include <boost/format.hpp> // for formating strings\n\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n#include <pcl/filters/statistical_outlier_removal.h>\n\ntypedef pcl::PointXYZRGB PointC;\ntypedef pcl::PointXYZ PointG;\ntypedef pcl::PointCloud<PointC>::Ptr PointCloudC;\ntypedef pcl::PointCloud<PointG>::Ptr PointCloudG;\n\nusing namespace std;\n\npcl::PCDReader reader;\npcl::PCDWriter writer;\npcl::StatisticalOutlierRemoval<PointG> sor;\n\nint main(int argc, char **argv) {\n if (argc != 2) {\n cout << \"please enter the file path.\" << endl;\n return -1;\n }\n PointCloudG cloud (new pcl::PointCloud<PointG>);\n reader.read (argv[1], *cloud);\n sor.setInputCloud (cloud);\n sor.setMeanK (10);\n sor.setStddevMulThresh (0.5);\n sor.filter (*cloud);\n writer.write (\"cloud_cleaned.pcd\", *cloud, false);\n return 0;\n}" }, { "alpha_fraction": 0.5786089897155762, "alphanum_fraction": 0.6212741136550903, "avg_line_length": 37, "blob_id": "8c1a71ec7711750e800539ace8aea728a3113846", "content_id": "bfc9ee09b6addfb962cc948f709e5e6ba150826d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1711, "license_type": "no_license", "max_line_length": 98, "num_lines": 45, "path": "/workshop/SVM/mnist_scilearn.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom sklearn import svm\nfrom matplotlib import pyplot as plt\nimport struct\nimport gzip\nimport pickle\n\n\ndef read_idx(filename):\n with gzip.open(filename) as f:\n zero, data_type, dims = struct.unpack('>HBB', f.read(4))\n shape = tuple(struct.unpack('>I', f.read(4))[0] for d in range(dims))\n return np.fromstring(f.read(), dtype=np.uint8).reshape(shape)\n\n\nif __name__ == \"__main__\":\n x_total = read_idx(\"./MNIST/t10k-images-idx3-ubyte.gz\")\n y_total = read_idx(\"./MNIST/t10k-labels-idx1-ubyte.gz\")\n N_train, N_test = 5000, 1000\n x_train, y_train = x_total[:N_train], y_total[:N_train]\n x_test, y_test = x_total[N_train:N_train + N_test], y_total[N_train:N_train + N_test]\n\n # PCA\n x_train_flattened = np.array(x_train.reshape([N_train, 28 * 28, 1]), dtype=np.float32)\n R = np.einsum(\"ijk, ilk -> ijl\", x_train_flattened, x_train_flattened).mean(axis=0)\n e_vals, e_vecs = np.linalg.eig(R)\n W = e_vecs[:, :50]\n x_train_reduced = W.T.dot(x_train_flattened.reshape([N_train, 28 * 28]).T).T\n x_test_reduced = W.T.dot(np.array(x_test.reshape([N_test, 28*28]).T, dtype=np.float32)).T\n\n # x1 = np.array(x_test.reshape([100, 28*28, 1]), dtype=np.float32)[50]\n # plt.imshow(x1.reshape([28, 28]), cmap=\"Greys\")\n # plt.show()\n #\n # x1_after = W.dot(W.T).dot(x1).reshape([28, 28])\n # plt.imshow(x1_after, cmap=\"Greys\")\n # plt.show()\n\n # training SVMs\n model = svm.SVC(C=10, kernel='rbf', gamma=5e-7, decision_function_shape='ovr', cache_size=500)\n model.fit(x_train_reduced, y_train)\n result = model.predict(x_test_reduced)\n print(result)\n print(y_test)\n print(np.where((result-y_test) == 0, 0, 1).mean())\n\n" }, { "alpha_fraction": 0.6428571343421936, "alphanum_fraction": 0.7056798338890076, "avg_line_length": 27.341463088989258, "blob_id": "2352f9ec7774ab6e0aba3db2a4ccabddf5732b0b", "content_id": "e00c06b07739ca6e6669c989b85f696184b166e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1162, "license_type": "no_license", "max_line_length": 120, "num_lines": 41, "path": "/demo3.1_validate_in_process_scan/physical_setup/arduino/test_stepper/test_stepper.ino", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "#include <AccelStepper.h>\n\n#define STEPS 200\n#define dirPin 2\n#define stepPin 3\n#define home_switch 9\n// Define stepper motor connections and motor interface type. Motor interface type must be set to 1 when using a driver:\n#define motorInterfaceType 1\nAccelStepper stepper(motorInterfaceType, 5, 4);\nint Pval = 0;\nint potVal = 0;\n\nvoid setup() {\n // Set the maximum speed in steps per second:\n // pinMode(stepPin, OUTPUT);\n // pinMode(dirPin, OUTPUT);\n int initial_homing = 1;\n while (!digitalRead(home_switch)) {\n stepper.setMaxSpeed(3000);\n stepper.setAcceleration(1000);\n stepper.moveTo(initial_homing);\n stepper.run();\n initial_homing += 1;\n delay(1);\n }\n Serial.begin(9600);\n// stepper.setSpeed(1000);\n stepper.setCurrentPosition(0);\n stepper.setMaxSpeed(3000);\n stepper.setAcceleration(1000);\n}\nvoid loop() {\n// if (stepper.distanceToGo() == 0) \n// stepper.moveTo(-stepper.currentPosition());\n Serial.println(stepper.currentPosition());\n stepper.runToNewPosition(-20.0/40.0*6400); // -20mm\n delay(2000);\n Serial.println(stepper.currentPosition());\n stepper.runToNewPosition(-40.0/40.0*6400); // -40mm\n delay(2000);\n}\n" }, { "alpha_fraction": 0.5043579339981079, "alphanum_fraction": 0.5566530823707581, "avg_line_length": 27.691667556762695, "blob_id": "e013d19aefb29dc1e87811067d5bc622d99df3fe", "content_id": "a2f76127e61c9e4431c7bdb173fde9db5bcd93c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3442, "license_type": "no_license", "max_line_length": 90, "num_lines": 120, "path": "/demo3.1_validate_in_process_scan/detection/takeFrame3D.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 30.01.20.\n//\n\n#include <iostream>\n#include <boost/format.hpp> // for formating strings\n\n#include <librealsense2/rs.hpp>\n#include <opencv2/opencv.hpp>\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n\ntypedef pcl::PointXYZRGB PointC;\ntypedef pcl::PointXYZ PointG;\ntypedef pcl::PointCloud<PointC>::Ptr PointCloudC;\ntypedef pcl::PointCloud<PointG>::Ptr PointCloudG;\n\nusing namespace std;\nusing namespace cv;\n\nclass CameraConfig {\npublic:\n Mat M;\n Mat distortion;\n Mat MInv;\n double fx, fy, cx, cy;\n\n CameraConfig() {\n M = (Mat_<double>(3, 3)\n << 1382.23, 0., 953.567\n , 0., 1379.46, 532.635\n , 0., 0., 1.);\n distortion = (Mat_<double >(1, 5)\n << 0.0, 0.0, 0.0, 0.0, 0.0);\n MInv = M.inv();\n fx = 1382.23; fy = 1379.46; cx = 953.567; cy = 532.635;\n };\n};\n\nCameraConfig C;\n\nPointCloudG points2pcl(const rs2::points& points) {\n PointCloudG cloud(new pcl::PointCloud<pcl::PointXYZ>);\n auto sp = points.get_profile().as<rs2::video_stream_profile>();\n cloud->width = sp.width();\n cloud->height = sp.height();\n cloud->is_dense = false;\n cloud->points.resize(points.size());\n auto ptr = points.get_vertices();\n for (auto& p : cloud->points) {\n p.x = ptr->x;\n p.y = ptr->y;\n p.z = ptr->z;\n ptr++;\n }\n return cloud;\n}\n\nint main(int argc, char **argv) {\n rs2::pipeline pipe;\n rs2::config cfg;\n cfg.enable_stream(RS2_STREAM_DEPTH, 1280, 720, RS2_FORMAT_Z16, 30);\n cfg.enable_stream(RS2_STREAM_COLOR, 1920, 1080, RS2_FORMAT_BGR8, 30);\n pipe.start(cfg);\n\n rs2::align align_to_color(RS2_STREAM_COLOR);\n\n rs2::pointcloud pc;\n rs2::points points;\n\n namedWindow(\"color\", 0);\n// namedWindow(\"with mask\", 0);\n// namedWindow(\"01\", 0);\n cvResizeWindow(\"color\", 960, 540);\n// cvResizeWindow(\"with mask\", 960, 540);\n// cvResizeWindow(\"01\", 640, 360);\n\n int num_pc_saved = 0;\n\n // start\n while (waitKey(1) != 'q') {\n rs2::frameset frameset = pipe.wait_for_frames();\n frameset = align_to_color.process(frameset);\n\n auto depth = frameset.get_depth_frame();\n auto color = frameset.get_color_frame();\n\n Mat matColor(Size(1920, 1080), CV_8UC3, (void*)color.get_data(), Mat::AUTO_STEP);\n Mat matDepth(Size(1920, 1080), CV_16U, (void*)depth.get_data(), Mat::AUTO_STEP);\n\n imshow(\"color\", matColor);\n\n// Mat mask = Mat::zeros(matDepth.size(), CV_8UC1);\n// for (int i = 0; i < matColor.rows; ++i) {\n// uint16_t *p = matDepth.ptr<uint16_t>(i);\n// for (int j = 0; j < matColor.cols; ++j) {\n// if (p[j] > 700 && p[j] < 900)\n// mask.at<uchar>(i, j) = 255;\n// }\n// }\n// Mat colorWithMask;\n// matColor.copyTo(colorWithMask, mask);\n// imshow(\"with mask\", colorWithMask);\n\n // point cloud\n if (waitKey(1) == 's') {\n pc.map_to(color);\n points = pc.calculate(depth);\n\n PointCloudG pclPC = points2pcl(points);\n boost::format fmt( \"../test_data/data/cloud_full0%d.pcd\" );\n pcl::io::savePCDFileBinary((fmt%num_pc_saved).str(), *pclPC);\n cout << \"PointCloud has: \" << pclPC->points.size() << \" data points.\" << endl;\n num_pc_saved += 1;\n }\n }\n\n return 0;\n}" }, { "alpha_fraction": 0.5260455012321472, "alphanum_fraction": 0.549523115158081, "avg_line_length": 25.72549057006836, "blob_id": "b9429fb010dcaf86bef5b28786f8034c5a23e9ae", "content_id": "e4a3ed8362fe637e12955b18772e4dfce978d920", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1363, "license_type": "no_license", "max_line_length": 89, "num_lines": 51, "path": "/workshop/DNN_classification/torch_network/TorchNN.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "import torch\n# import torch.nn as nn\nimport torch.nn.functional as F\n# import torch.optim as optim\nimport numpy as np\n# from matplotlib import pyplot as plt\n\n\nclass TorchNN:\n def __init__(self, dim_in):\n self.Ws = []\n self.Bs = []\n self.activations = []\n # self.d_activations = []\n self.dims = [dim_in]\n\n def add_dense_layer(self, n, activation=F.relu):\n # stdv = 1. / (self.dims[-1] ** 0.5)\n # w = torch.empty(n, self.dims[-1]).uniform_(-stdv, stdv)\n # w.requires_grad = True\n w = torch.normal(0., 2./self.dims[-1], [n, self.dims[-1]], requires_grad=True)\n self.Ws.append(w)\n self.Bs.append(torch.zeros(n, 1, requires_grad=True))\n self.activations.append(activation)\n self.dims.append(n)\n\n def model(self, x0):\n # x_temp = x0\n # x = [x_temp]\n x = x0\n for i in range(len(self.Ws)):\n x = self.activations[i](self.Ws[i].mm(x) + self.Bs[i].repeat(1, x0.shape[1]))\n # x.append(x)\n return x\n\n\ndef softmax(x): # (x, 1)\n return torch.exp(x) / torch.sum(torch.exp(x), 0) # (x, 1)\n\n\n# a = torch.arange(1, 5).reshape(2, 2)[:, 0:1]\n# b = a.repeat(1, 3)\n# print(a)\n# print(b)\n# print(b.shape)\n\n# a = torch.empty(2, 3).uniform_(-1., 1.)\n# a.requires_grad = True\n# b = torch.sum(a*2)\n# b.backward()\n# print(a.grad)\n" }, { "alpha_fraction": 0.6134676337242126, "alphanum_fraction": 0.6224814653396606, "avg_line_length": 31.534482955932617, "blob_id": "d71124c0e8227f1738806e93a01aef1190c910e5", "content_id": "33730c16976a517d431176ea538a87a34d5a89c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1886, "license_type": "no_license", "max_line_length": 112, "num_lines": 58, "path": "/demo3.1_validate_in_process_scan/detection/downsample.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by ruqing on 20.02.20.\n//\n\n#include <iostream>\n#include <fstream>\n#include <chrono>\n#include <boost/format.hpp> // for formating strings\n\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n#include <pcl/filters/voxel_grid.h>\n\ntypedef pcl::PointXYZRGB PointC;\ntypedef pcl::PointXYZ PointG;\ntypedef pcl::PointCloud<PointC>::Ptr PointCloudC;\ntypedef pcl::PointCloud<PointG>::Ptr PointCloudG;\n\nusing namespace std;\n\npcl::PCDReader reader;\npcl::PCDWriter writer;\n\nint main(int argc, char **argv) {\n// if (argc != 3) {\n// cout << \"please enter the file path and the voxel size.\" << endl;\n// return -1;\n// }\n\n// double time_total = 0.0;\n int num_frames = 1;\n for (int frame_index = 0; frame_index < num_frames; ++frame_index) {\n PointCloudC cloud(new pcl::PointCloud<PointC>);\n PointCloudC cloud_filtered(new pcl::PointCloud<PointC>);\n boost::format fmt(\"../data3D/cloud_full_%d.pcd\");\n reader.read((fmt % frame_index).str(), *cloud);\n\n pcl::VoxelGrid<PointC> sor;\n sor.setInputCloud(cloud);\n float size = 4.0f;\n sor.setLeafSize(size, size, size);\n\n// chrono::steady_clock::time_point t_start = chrono::steady_clock::now(); // timing start\n\n sor.filter(*cloud_filtered);\n\n// chrono::steady_clock::time_point t_end = chrono::steady_clock::now(); // timing end\n// chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t_end - t_start);\n// cout << \"time cost = \" << time_used.count() << \" seconds. \" << endl;\n// time_total += time_used.count();\n\n boost::format fmt_out( \"../data3D/cloud_downsampled_%d.pcd\" );\n writer.write((fmt_out % frame_index).str(), *cloud_filtered, false);\n }\n// cout << \"time total cost = \" << time_total << \" seconds. \" << endl;\n return 0;\n}" }, { "alpha_fraction": 0.41119134426116943, "alphanum_fraction": 0.4685920476913452, "avg_line_length": 27.55670166015625, "blob_id": "fefd33af9d1279a0fd4ce4d5e3840398633b8eb3", "content_id": "b48308cbfb6f1615aea3c422a148b7d65e02499f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2770, "license_type": "no_license", "max_line_length": 112, "num_lines": 97, "path": "/demo4.1_tracking/opt/main.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom Frame import *\nfrom scipy.optimize import minimize\nfrom math import pi\n\n\n# [n, ] -> scalar\ndef length(v):\n return np.linalg.norm(v, ord=2)\n\n\n# [7, ] [7, ] -> scalar\ndef dis_l_l(l1, l2):\n p1, v1, r1 = l1[0:3], l1[3:6], l1[6]\n p2, v2, r2 = l2[0:3], l2[3:6], l2[6]\n cross = np.cross(v1, v2)\n return abs(np.sum((p1 - p2) * cross)) / length(cross) - r1 - r2\n\n\n# [7, ] [7, ] -> scalar\ndef angle_l_l(l1, l2):\n v1 = l1[3:6]\n v2 = l2[3:6]\n return np.arccos(np.sum(v1*v2) / (length(v1) * length(v2)))\n\n\n# [7, ] [3, ] -> scalar\ndef dis_l_t(l, t):\n p, v = l[0:3], l[3:6]\n cross = np.cross(t-p, v)\n return length(cross) / length(v)\n\n\n# [4, 4] [7, ] -> [7, ]\ndef tran(r_6, l):\n c_new = np.zeros([7, ])\n p = np.ones([4, ])\n p[0:3] = l[0:3]\n v = l[3:6]\n f = Frame.from_r_3(r_6[0:3], r_6[3:6].reshape([3, 1]))\n c_new[0:3] = f.t_4_4.dot(p)[0:3].reshape([3, ])\n c_new[3:6] = f.r_3_3.dot(v).reshape([3, ])\n c_new[6] = l[6]\n return c_new\n\n\nl = np.loadtxt(\"data/l.txt\")\nm = np.loadtxt(\"data/m.txt\")\nt = np.loadtxt(\"data/t.txt\")\n\nDISTANCE = 9.\nANGLE_L = 30. * pi / 180.\nANGLE_U = 150. * pi / 180.\n\nnum_cons = m.shape[0]\n# num_cons = 1\n\nif num_cons == 1:\n eq_cons = {\"type\": \"eq\", \"fun\": lambda x: dis_l_l(tran(x, l[0]), m[0]) - DISTANCE}\n ineq_cons = {\"type\": \"ineq\", \"fun\": lambda x: np.array([angle_l_l(tran(x, l[0]), m[0]) - ANGLE_L,\n - angle_l_l(tran(x, l[0]), m[0]) + ANGLE_U])}\nif num_cons == 2:\n eq_cons = {\"type\": \"eq\", \"fun\": lambda x: np.array([dis_l_l(tran(x, l[0]), m[0]) - DISTANCE,\n dis_l_l(tran(x, l[1]), m[1]) - DISTANCE])}\n ineq_cons = {\"type\": \"ineq\", \"fun\": lambda x: np.array([angle_l_l(tran(x, l[0]), m[0]) - ANGLE_L,\n - angle_l_l(tran(x, l[0]), m[0]) + ANGLE_U,\n angle_l_l(tran(x, l[1]), m[1]) - ANGLE_L,\n - angle_l_l(tran(x, l[1]), m[1]) + ANGLE_U])}\n\n# get initial guess\n# x0 = np.zeros([6, ])\n\n# l0_v = l[0][3:6]\n# m_v = m[0][3:6]\n#\n# cross = np.cross(l0_v, m_v)\n# cross /= length(cross)\n# cross *= (DISTANCE - dis_l_l(l[0], m[0]))\n# print(cross)\nx0 = np.zeros([6, ])\n# x0[3:6] = -cross\n#\n# print(dis_l_l(l[0], m[0]) - DISTANCE)\n# print(dis_l_l(tran(x0, l[0]), m[0]) - DISTANCE)\n\n\ndef cost(x):\n global l, t\n # return dis_l_t(tran(x, l[-1]), t) ** 2\n return dis_l_t(tran(x, l[-1]), t) + 2.0 * length(x)\n\n\nres = minimize(cost, x0, method=\"SLSQP\", constraints=[eq_cons, ineq_cons], options={\"fto1\": 1e-9, \"disp\": True})\nprint(res.x)\n\nnp.savetxt(\"result.txt\", res.x.reshape([1, 6]))\n" }, { "alpha_fraction": 0.614973247051239, "alphanum_fraction": 0.6320855617523193, "avg_line_length": 27.34848403930664, "blob_id": "fec5ce0bfd7a3b4668910b4f951af98485ba3d07", "content_id": "0758a9a02cd9550e8ec9c661a0a20925b59dce94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1870, "license_type": "no_license", "max_line_length": 85, "num_lines": 66, "path": "/workshop/pytorch/linear_regression/linear regression_pytorch.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "import torch\nfrom torch import nn\nfrom torch import tensor\nimport numpy as np\n\ndef generate_data(n, k, b, low=0.0, high=5.0):\n step = (high - low) / n\n x = torch.zeros(n, 1)\n y = torch.zeros(n, 1)\n for i in range(n):\n x[i] = low + step * i\n y[i] = x[i] * k + b + np.random.normal(0.0, 0.05 * (high - low))\n return x, y\n\n\nclass Model(nn.Module):\n def __init__(self):\n \"\"\"\n In the constructor we instantiate two nn.Linear module\n \"\"\"\n super(Model, self).__init__()\n self.linear = torch.nn.Linear(1, 1)\n\n def forward(self, x):\n \"\"\"\n In the forward function we accept a Variable of input data and we must return\n a Variable of output data. We can use Modules defined in the constructor as\n well as arbitrary operators on Variables.\n \"\"\"\n y_pred = self.linear(x)\n return y_pred\n\n\n# our model\nmodel = Model()\n\n\n# Construct our loss function and an Optimizer. The call to model.parameters()\n# in the SGD constructor will contain the learnable parameters of the two\n# nn.Linear modules which are members of the model.\ncriterion = torch.nn.MSELoss(reduction='sum')\noptimizer = torch.optim.SGD(model.parameters(), lr=0.001)\n\n# generate data\nx_data, y_data = generate_data(100, 2, 1)\nprint(\"x_data\", x_data)\nprint(\"y_data\", y_data)\n\n# Training loop\nfor epoch in range(500):\n # 1) Forward pass: Compute predicted y by passing x to the model\n y_pred = model(x_data)\n\n # 2) Compute and print loss\n loss = criterion(y_pred, y_data)\n print(f'Epoch: {epoch} | Loss: {loss.item()}')\n\n # Zero gradients, perform a backward pass, and update the weights.\n optimizer.zero_grad() \n loss.backward()\n optimizer.step()\n\n# After training\nvar = tensor([[4.0]])\ny_pred = model(var)\nprint(\"Prediction (after training)\", 4, model(var).data[0][0].item())" }, { "alpha_fraction": 0.4320145547389984, "alphanum_fraction": 0.5252387523651123, "avg_line_length": 22.393617630004883, "blob_id": "670ce5c48b5db93637a0ce3b78dee4920fd0043a", "content_id": "21cc8bd11a6a6c3d2a805f88c9348459d3b74cce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2199, "license_type": "no_license", "max_line_length": 65, "num_lines": 94, "path": "/demo5.1_final/localization_and_mapping/code/libs/lib_frame.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "from scipy.spatial.transform import Rotation as R\nfrom scipy.optimize import least_squares\nimport numpy as np\n\n\n# input: T[4, 4]\n# output: T[4, 4]\ndef inv(t_4_4):\n t_4_4_new = t_4_4.copy()\n t_4_4_new[0:3, 3:4] = -t_4_4[0:3, 0:3].T.dot(t_4_4[0:3, 3:4])\n t_4_4_new[0:3, 0:3] = t_4_4[0:3, 0:3].T\n return t_4_4_new\n\n\n# input: q[n, 4]\n# output: q[n, 4]\ndef swap_quats(quats):\n quats_new = quats.copy()\n for i in range(quats_new.shape[0]):\n temp = quats[i, 0]\n quats_new[i, 0] = quats_new[i, 1]\n quats_new[i, 1] = quats_new[i, 2]\n quats_new[i, 2] = quats_new[i, 3]\n quats_new[i, 3] = temp\n return quats_new\n\n\n# input: q[4,], t[3,]\n# output: T[4, 4]\ndef t_4_4__quat(quat, t):\n t_4_4 = np.eye(4)\n t_4_4[0:3, 0:3] = R.from_quat(quat).as_matrix()\n t_4_4[0:3, 3:4] = t.reshape([3, 1])\n return t_4_4\n\n\n# input: q[n, 4], t[n, 3]\n# output: list of T[4, 4]\ndef t_4_4s__quats(quats, ts):\n t_4_4s = []\n for i in range(quats.shape[0]):\n t_4_4s.append(t_4_4__quat(quats[i], ts[i]))\n return t_4_4s\n\n\n# input: q[n, 4], t[n, 3]\n# output: list of T[4, 4]\ndef inv_t_4_4s__quats(quats, ts):\n t_4_4s = []\n for i in range(quats.shape[0]):\n t_4_4s.append(inv(t_4_4__quat(quats[i], ts[i])))\n return t_4_4s\n\n\n# input: rvec[3,], t[3,]\n# output: T[4, 4]\ndef t_4_4__rvec(rvec, t):\n t_4_4 = np.eye(4)\n t_4_4[0:3, 0:3] = R.from_rotvec(rvec).as_matrix()\n t_4_4[0:3, 3:4] = t.reshape([3, 1])\n return t_4_4\n\n\n# input: rvec[6,]\n# output: T[4, 4]\ndef t_4_4__rvec6(rvec):\n return t_4_4__rvec(rvec[0:3], rvec[3:6])\n\n\n# input: rvecs[n, 6]\n# output: T[4, 4]\ndef t_4_4s__rvecs6(rvecs):\n t_4_4s = []\n for i in range(rvecs.shape[0]):\n t_4_4s.append(t_4_4__rvec6(rvecs[i]))\n return t_4_4s\n\n\n# input: T[4, 4]\n# output: [rvec, t] [6,]\ndef rvec6__t_4_4(t_4_4):\n vec = np.zeros([6, ])\n vec[0:3] = R.from_matrix(t_4_4[0:3, 0:3]).as_rotvec()\n vec[3:6] = t_4_4[0:3, 3:4].reshape([3, ])\n return vec\n\n\n# input: list of T[4, 4]\n# output: [rvecs, ts] [n, 6]\ndef rvecs6__t_4_4s(t_4_4s):\n vecs = np.zeros([len(t_4_4s), 6])\n for i in range(len(t_4_4s)):\n vecs[i] = rvec6__t_4_4(t_4_4s[i])\n return vecs\n" }, { "alpha_fraction": 0.5200598239898682, "alphanum_fraction": 0.5801146030426025, "avg_line_length": 30.85714340209961, "blob_id": "b45222de0507965cdbd0f970a396d95b2ac33b28", "content_id": "9138a286e4afabdb56196e0b4ed633568ebfa27f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4013, "license_type": "no_license", "max_line_length": 102, "num_lines": 126, "path": "/demo3.1_validate_in_process_scan/detection/level_circleboard.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 24.03.20.\n//\n\n#include <iostream>\n#include <vector>\n#include <boost/format.hpp> // for formating strings\n\n#include <opencv2/opencv.hpp>\n#include <opencv2/aruco.hpp>\n#include <librealsense2/rs.hpp>\n\nusing namespace std;\nusing namespace cv;\n\nclass CameraConfig {\npublic:\n Mat M;\n Mat distortion;\n Mat MInv;\n double fx, fy, cx, cy;\n\n CameraConfig() {\n M = (Mat_<double>(3, 3)\n << 1382.23, 0., 953.567\n , 0., 1379.46, 532.635\n , 0., 0., 1.);\n distortion = (Mat_<double >(1, 5)\n << 0.0, 0.0, 0.0, 0.0, 0.0);\n MInv = M.inv();\n fx = 1382.23; fy = 1379.46; cx = 953.567; cy = 532.635;\n };\n};\n\nCameraConfig C;\n\nbool detectChessboard(Mat img, Mat &tranc2o, Point &center) {\n vector<Point2f> centers;\n bool pattern_was_found = findCirclesGrid(img, cv::Size(2, 13), centers, CALIB_CB_ASYMMETRIC_GRID);\n if (!pattern_was_found)\n return false;\n cv::drawChessboardCorners(img, cv::Size(2, 13), Mat(centers), pattern_was_found);\n vector<Point3f> objectPoints;\n\n for (int i = 0; i < 13; ++i)\n for (int j = 0; j < 2; ++j)\n objectPoints.push_back(Point3d(i*0.02, j*0.04+(i%2)*0.02, 0.0));\n Mat rvec, tvec;\n Mat matCorneres = Mat(centers).reshape(1);\n Mat matObjectPoints = Mat(objectPoints).reshape(1);\n solvePnP(matObjectPoints, matCorneres, C.M, C.distortion, rvec, tvec);\n\n cv::aruco::drawAxis(img, C.M, C.distortion, rvec, tvec, 0.04);\n center = centers[0];\n Mat r;\n Rodrigues(rvec, r);\n hconcat(r, tvec, tranc2o);\n Mat down = (Mat_<double>(1, 4) << 0., 0., 0., 1.);\n vconcat(tranc2o, down, tranc2o);\n return true;\n}\n\n// Checks if a matrix is a valid rotation matrix.\nbool isRotationMatrix(Mat &R) {\n Mat Rt;\n transpose(R, Rt);\n Mat shouldBeIdentity = Rt * R;\n Mat I = Mat::eye(3,3, shouldBeIdentity.type());\n return norm(I, shouldBeIdentity) < 1e-6;\n}\n\n// Calculates rotation matrix to euler angles\n// The result is the same as MATLAB except the order\n// of the euler angles ( x and z are swapped ).\nVec3f rotationMatrixToEulerAngles(Mat &R) {\n assert(isRotationMatrix(R));\n float sy = sqrt(R.at<double>(0,0) * R.at<double>(0,0) + R.at<double>(1,0) * R.at<double>(1,0) );\n bool singular = sy < 1e-6; // If\n float x, y, z;\n if (!singular) {\n x = atan2(R.at<double>(2,1) , R.at<double>(2,2));\n y = atan2(-R.at<double>(2,0), sy);\n z = atan2(R.at<double>(1,0), R.at<double>(0,0));\n } else {\n x = atan2(-R.at<double>(1,2), R.at<double>(1,1));\n y = atan2(-R.at<double>(2,0), sy);\n z = 0;\n }\n return Vec3f(x, y, z);\n}\n\nint main(int argc, char **argv) {\n rs2::pipeline pipe;\n rs2::config cfg;\n cfg.enable_stream(RS2_STREAM_DEPTH, 1280, 720, RS2_FORMAT_Z16, 30);\n cfg.enable_stream(RS2_STREAM_COLOR, 1920, 1080, RS2_FORMAT_BGR8, 30);\n pipe.start(cfg);\n\n rs2::align align_to_color(RS2_STREAM_COLOR);\n\n // start\n while (waitKey(1) != 'q') {\n rs2::frameset frameset = pipe.wait_for_frames();\n frameset = align_to_color.process(frameset);\n\n auto depth = frameset.get_depth_frame();\n auto color = frameset.get_color_frame();\n\n Mat matColor(Size(1920, 1080), CV_8UC3, (void*)color.get_data(), Mat::AUTO_STEP);\n Mat matDepth(Size(1920, 1080), CV_16U, (void*)depth.get_data(), Mat::AUTO_STEP);\n\n Mat tran_c2o;\n Point center;\n\n if (detectChessboard(matColor, tran_c2o, center)) {\n Mat tran_02c = tran_c2o.inv();\n Mat R = tran_02c(Rect(0, 0, 3, 3));\n Vec3f zyxAngles = rotationMatrixToEulerAngles(R) / M_PI * 180.0;\n boost::format fmt(\"Eular angles(ZYX): X: %f Y: %f Z: %f\");\n putText(matColor, (fmt%zyxAngles[0]%zyxAngles[1]%zyxAngles[2]).str(),\n Point(50, 50), CV_FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 0, 255), 1.2);\n }\n imshow(\"circle_qboard\", matColor);\n }\n return 0;\n}" }, { "alpha_fraction": 0.4409141540527344, "alphanum_fraction": 0.5813823938369751, "avg_line_length": 33.5, "blob_id": "e498a96e7616e9b85613bb8e85d11cbe635782fa", "content_id": "e32b8369a85e8b4cf29c892175d97a4a40b49d86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1794, "license_type": "no_license", "max_line_length": 108, "num_lines": 52, "path": "/demo2.1_detect_polygon/detection_dual/lib/CameraConfig.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 04.12.19.\n//\n\n#include <CameraConfig.hpp>\n\nCameraConfig::CameraConfig() {\n leftCameraMatrix = (Mat_<double>(3, 3)\n << 891.99940, 0., 326.93216\n , 0., 892.35459, 235.09397\n , 0., 0., 1.);\n leftDistortion = (Mat_<double>(1, 5)\n << -0.43721, 0.24738, -0.00196, 0.00004, 0.00000);\n rightCameraMatrix = (Mat_<double>(3, 3)\n << 886.52934, 0., 318.26183\n , 0., 886.13278, 238.68409\n , 0., 0., 1.);\n rightDistortion = (Mat_<double>(1, 5)\n << -0.41575, 0.07315, -0.00450, -0.00067, 0.00000);\n RVec = (Mat_<double>(1, 3)\n << -0.00271, -0.01687, 0.00032);\n T = (Mat_<double>(3, 1)\n << -60.27202, 0.36238, -0.39229);\n R = getR();\n size = Size(640, 480);\n getCameraMatrices(R1, R2, P1, P2, Q);\n getMaps(mapL1, mapL2, mapR1, mapR2);\n b = -T.at<double>(0, 0);\n f = P1.at<double>(0, 0);\n cameraL = P1(Rect(0, 0, 3, 3));\n cameraR = P2(Rect(0, 0, 3, 3));\n cameraLInv = cameraL.inv();\n cameraRInv = cameraR.inv();\n}\n\nMat CameraConfig::getR() {\n Mat mat;\n Rodrigues(RVec, mat);\n return mat;\n}\n\nvoid CameraConfig::getCameraMatrices(Mat &outR1, Mat &outR2, Mat &outP1, Mat &outP2, Mat &outQ) {\n stereoRectify(leftCameraMatrix, leftDistortion, rightCameraMatrix, rightDistortion\n , size, R, T, outR1, outR2, outP1, outP2, outQ);\n}\n\nvoid CameraConfig::getMaps(Mat &outMapL1, Mat &outMapL2, Mat &outMapR1, Mat &outMapR2) {\n Mat R1, R2, P1, P2, Q;\n getCameraMatrices(R1, R2, P1, P2, Q);\n initUndistortRectifyMap(leftCameraMatrix, leftDistortion, R1, P1, size, CV_32FC1, outMapL1, outMapL2);\n initUndistortRectifyMap(rightCameraMatrix, rightDistortion, R2, P2, size, CV_32FC1, outMapR1, outMapR2);\n}\n" }, { "alpha_fraction": 0.6468842625617981, "alphanum_fraction": 0.6810088753700256, "avg_line_length": 19.42424201965332, "blob_id": "2e44aa10a3c3ef7bc5c6c1f5ac759e0c82bec27f", "content_id": "22917453695a9c1ec33f5d4d28323d4472463f1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 674, "license_type": "no_license", "max_line_length": 86, "num_lines": 33, "path": "/demo2.1_detect_polygon/detection_dual/lib/CameraConfig.hpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 06.12.19.\n//\n\n#ifndef CAMERA_CONFIG_H\n#define CAMERA_CONFIG_H\n\n#include <iostream>\n#include <opencv2/opencv.hpp>\n\nusing namespace cv;\n\nclass CameraConfig {\npublic:\n Mat leftCameraMatrix, leftDistortion, rightCameraMatrix, rightDistortion;\n Mat RVec, R, T;\n Size size;\n Mat R1, R2, P1, P2, Q, mapL1, mapL2, mapR1, mapR2;\n Mat cameraL, cameraR, cameraLInv, cameraRInv;\n double b, f;\n\n CameraConfig();\n\n Mat getR();\n\n void getCameraMatrices(Mat &outR1, Mat &outR2, Mat &outP1, Mat &outP2, Mat &outQ);\n\n void getMaps(Mat &outMapL1, Mat &outMapL2, Mat &outMapR1, Mat &outMapR2);\n};\n\nCameraConfig C;\n\n#endif //CAMERA_CONFIG_H\n" }, { "alpha_fraction": 0.7318255305290222, "alphanum_fraction": 0.749596118927002, "avg_line_length": 19.633333206176758, "blob_id": "39f4211c637da62db9e77469508d753daa2d06de", "content_id": "fcca73e06f8503975a3d94b617ef5af1f0ca2f47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 619, "license_type": "no_license", "max_line_length": 63, "num_lines": 30, "path": "/demo2.2_detect_cylinder/detection_rgbd/lib/pointCloud.hpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 26.01.20.\n//\n\n#ifndef POINTCLOUD_HPP\n#define POINTCLOUD_HPP\n\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n#include <librealsense2/hpp/rs_frame.hpp>\n#include <opencv2/opencv.hpp>\n\n//cv::Mat;\n\nusing namespace std;\n\ntypedef pcl::PointXYZRGB PointC;\ntypedef pcl::PointXYZ PointG;\ntypedef pcl::PointCloud<PointC>::Ptr PointCloudC;\ntypedef pcl::PointCloud<PointG>::Ptr PointCloudG;\n\nPointCloudG points2pcl(const rs2::points& points);\n\nPointCloudG mat2pcl(const cv::Mat& depth, const cv::Mat& mask);\n\nvoid detectCylinderRANSAC(const PointCloudG& pc);\n\nint test();\n\n#endif //POINTCLOUD_HPP\n" }, { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.7551020383834839, "avg_line_length": 15.666666984558105, "blob_id": "ecc650d4796909fd8ee1a80c0f8aa4e93c953809", "content_id": "f7a47c4bf8884e804cd8d8ef4b8c0b5ba3cdd9fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 49, "license_type": "no_license", "max_line_length": 20, "num_lines": 3, "path": "/demo5.1_final/README.md", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "# demo5.1_final\n- final code\n- final demonstrator" }, { "alpha_fraction": 0.6122449040412903, "alphanum_fraction": 0.625, "avg_line_length": 20.83333396911621, "blob_id": "ca899f96c95ef4f5fcd51ed4590fa2ab91aeca1c", "content_id": "a1db3f7e1e96729ab502c1bff35b4a8461ad4de7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 392, "license_type": "no_license", "max_line_length": 43, "num_lines": 18, "path": "/demo1_tello_aruco/cv_aruco/test.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "from aruco_detection_tello import *\n\nsolver = Aruco_detector_tello()\n\ncapture = cv2.VideoCapture(0)\n\nwhile True:\n ret, frame = capture.read()\n solver.detect(frame)\n if solver.is_detected:\n print(solver.get_pose_world())\n cv2.imshow(\"img\", solver.image_out)\n c = cv2.waitKey()\n if c == ord(\"q\"):\n break\n\ncapture.release()\ncv2.destroyAllWindows()" }, { "alpha_fraction": 0.7201834917068481, "alphanum_fraction": 0.7568807601928711, "avg_line_length": 18.377777099609375, "blob_id": "261b45124808616758d2453cb4f19e5887f87408", "content_id": "b7e9aaf045db37c6a781d6e7c51618a41378064e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 872, "license_type": "no_license", "max_line_length": 56, "num_lines": 45, "path": "/demo2.2_detect_cylinder/detection_rgbd/lib/kinect.hpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 26.01.20.\n//\n\n#ifndef KINECT_HPP\n#define KINECT_HPP\n\n#include <iostream>\n#include <opencv2/opencv.hpp>\n#include <pcl/point_types.h>\n#include <pcl/io/pcd_io.h>\n\n// for kinect v2\n#include <libfreenect2/libfreenect2.hpp>\n#include <libfreenect2/frame_listener_impl.h>\n#include <libfreenect2/registration.h>\n#include <libfreenect2/packet_pipeline.h>\n\nusing namespace std;\nusing namespace libfreenect2;\nusing namespace cv;\n\n// kinect\nFreenect2 freenect2;\nFreenect2Device *dev = 0;\nSyncMultiFrameListener *listener;\nFrameMap frames;\nRegistration* registration;\nFrame undistorted(512, 424, 4), registered(512, 424, 4);\n\n// frame from kinect\nMat *matDepth, *matBGRD;\n\ntypedef pcl::PointXYZRGB PointC;\ntypedef pcl::PointCloud<PointC> PointCloud;\n\nint kinectInit();\n\nvoid kinectClose();\n\nint getFrame();\n\nPointCloud::Ptr getPointCloud();\n\n#endif //KINECT_HPP\n" }, { "alpha_fraction": 0.5235017538070679, "alphanum_fraction": 0.5505287647247314, "avg_line_length": 40.68354415893555, "blob_id": "42bb0bb4162b4e269b4e173bbd83769926a7e939", "content_id": "e999c1f6db41b6f12cad2b04fddc0c4bda732179", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3404, "license_type": "no_license", "max_line_length": 105, "num_lines": 79, "path": "/demo1_tello_aruco/cv_aruco/tello_controller.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "from simple_pid import PID\r\nfrom time import sleep\r\n\r\n\r\nclass Tello_controller:\r\n # initial a tello object in main script, pass it in to the function\r\n def __init__(self, drone):\r\n self.drone = drone\r\n self.axis_command = {\r\n \"x\": self.drone.right,\r\n \"y\": self.drone.forward,\r\n \"z\": self.drone.up,\r\n \"yaw\": self.drone.clockwise\r\n }\r\n self.axis_speed = {\"x\": 0.0, \"y\": 0.0, \"z\": 0.0, \"yaw\": 0.0}\r\n self.prev_axis_speed = self.axis_speed.copy()\r\n self.pid_x = PID(0.5, 0.04, 0, setpoint=0, output_limits=(-10, 10)) # for x\r\n self.pid_y = PID(0.5, 0.04, 0, setpoint=0, output_limits=(-10, 10)) # for y\r\n self.pid_z = PID(0.5, 0.04, 0, setpoint=0, output_limits=(-10, 10)) # for z\r\n self.pid_yaw = PID(0.5, 0.04, 0, setpoint=0, output_limits=(-10, 10)) # for yaw\r\n self.ref_pose = None\r\n self.drone_pose = [0.0, 0.0, 0.0, 0.0]\r\n self.error = [0.0, 0.0, 0.0, 0.0]\r\n self.tolerance = [3.0, 3.0, 3.0, 3.0]\r\n\r\n # set axis speed and send flight command to the drone\r\n def send_flight_command(self):\r\n for axis, command in self.axis_command.items():\r\n if self.axis_speed[axis] is not None and self.axis_speed[axis] != self.prev_axis_speed[axis]:\r\n command(self.axis_speed[axis])\r\n self.prev_axis_speed[axis] = self.axis_speed[axis]\r\n print(\"sent command to flight\", command, self.axis_speed)\r\n else:\r\n self.axis_speed[axis] = self.prev_axis_speed[axis]\r\n\r\n # calculate error between reference pose and current pose\r\n def update_error(self):\r\n pose_list_length = 4\r\n error = [0, 0, 0, 0]\r\n if len(self.ref_pose) != pose_list_length or len(self.drone_pose) != pose_list_length:\r\n print(\"Not able to process error calculation. Please check list length.\")\r\n else:\r\n for i in range(pose_list_length):\r\n error[i] = self.ref_pose[i] - self.drone_pose[i]\r\n self.error = error\r\n print(\"current error\", self.error)\r\n\r\n # compare current error with the tolerance\r\n def compare_error(self):\r\n error_abs = [abs(self.error[0]), abs(self.error[1]), abs(self.error[2]), abs(self.error[3])]\r\n state = 0\r\n for i in range(len(self.error)):\r\n if error_abs[i] < self.tolerance[i]:\r\n state += 1\r\n else:\r\n state += 0\r\n if state == len(self.error):\r\n return False\r\n else:\r\n return True\r\n\r\n # update ref_pose\r\n def update_ref_pose(self, ref_pose: list):\r\n self.ref_pose = ref_pose\r\n print(\"current ref_pose\", self.ref_pose)\r\n\r\n # update the current pose data from the cv\r\n def update_drone_pose(self, drone_pose: list):\r\n self.drone_pose = drone_pose\r\n print(\"current drone_pose\", self.drone_pose)\r\n\r\n # update pid control data\r\n def update_axis_speed(self):\r\n self.prev_axis_speed = self.axis_speed.copy()\r\n self.axis_speed[\"x\"] = int(-self.pid_x(self.error[0]))\r\n self.axis_speed[\"y\"] = int(-self.pid_y(self.error[1]))\r\n self.axis_speed[\"z\"] = int(-self.pid_z(self.error[2]))\r\n self.axis_speed[\"yaw\"] = int(-self.pid_yaw(self.error[3]))\r\n print(\"current axis speed\", self.axis_speed)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.5748898386955261, "alphanum_fraction": 0.6123347878456116, "avg_line_length": 21.700000762939453, "blob_id": "507c95b9db508b290068cdbb5dd4d6673f13dc33", "content_id": "15fee2f532014c7b84e849a5ce731761c131e6b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 454, "license_type": "no_license", "max_line_length": 80, "num_lines": 20, "path": "/demo1_tello_aruco/cv_aruco/trajectory.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "from math import pi, sin, cos\n\n\ncenter_x = 0.\ncenter_y = -120.\ncenter_z = 0\n\n\ndef get_circular_trajectory(r):\n tra = []\n tra.append([center_x, center_y, center_z, 0.])\n for index in range(100):\n theta = index * 0.01 * 2 * pi\n tra.append([center_x+cos(theta)*r, center_y, center_z+sin(theta)*r, 0.])\n tra.append([center_x, center_y, center_z, 0.])\n print(tra)\n return tra\n\n\ntrajectory_planned = get_circular_trajectory(10)\n" }, { "alpha_fraction": 0.5656670331954956, "alphanum_fraction": 0.5904860496520996, "avg_line_length": 29.21875, "blob_id": "ed98eb74c3887232ab2c7b40fcdb4a226d76a3fb", "content_id": "92124cc9f2ae197b1c567eb1dab3512855929cec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1934, "license_type": "no_license", "max_line_length": 91, "num_lines": 64, "path": "/demo2.2_detect_cylinder/detection_rgbd/lib/kinect.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 26.01.20.\n//\n\n#include \"kinect.hpp\"\n\nint kinectInit() {\n if(freenect2.enumerateDevices() == 0) {\n cout << \"no device connected!\" << endl;\n return -1;\n }\n string serial = freenect2.getDefaultDeviceSerialNumber();\n dev = freenect2.openDevice(serial);\n int types = 0;\n types |= libfreenect2::Frame::Color;\n types |= libfreenect2::Frame::Ir | libfreenect2::Frame::Depth;\n listener = new SyncMultiFrameListener(types);\n dev->setColorFrameListener(listener);\n dev->setIrAndDepthFrameListener(listener);\n if (!dev->start())\n return -1;\n registration = new Registration(dev->getIrCameraParams(), dev->getColorCameraParams());\n return 0;\n}\n\nvoid kinectClose() {\n dev->stop();\n dev->close();\n}\n\nint getFrame() {\n if (!listener->waitForNewFrame(frames, 10*1000)) { // 10 sconds\n cout << \"timeout!\" << endl;\n return -1;\n }\n Frame *rgb = frames[Frame::Color];\n Frame *depth = frames[Frame::Depth];\n registration->apply(rgb, depth, &undistorted, &registered, true);\n\n matDepth = new Mat(undistorted.height, undistorted.width, CV_32FC1, undistorted.data);\n matBGRD = new Mat(registered.height, registered.width, CV_8UC4, registered.data);\n listener->release(frames);\n}\n\nPointCloud::Ptr getPointCloud() {\n PointCloud::Ptr pointCloud(new PointCloud);\n for (int v = 0; v < 424; v++)\n for (int u = 0; u < 512; u++) {\n float x, y, z, color;\n registration->getPointXYZRGB(&undistorted, &registered, v, u, x, y, z, color);\n const uint8_t *color_3b = reinterpret_cast<uint8_t*>(&color);\n PointC p ;\n p.x = x;\n p.y = y;\n p.z = z;\n p.b = color_3b[0];\n p.g = color_3b[1];\n p.r = color_3b[2];\n pointCloud->points.push_back( p );\n }\n pointCloud->is_dense = false;\n\n return pointCloud;\n}\n" }, { "alpha_fraction": 0.7220902442932129, "alphanum_fraction": 0.7387173175811768, "avg_line_length": 19.047618865966797, "blob_id": "f09331d55497b26e179a1d05c5f111734674b503", "content_id": "429d36a4a194abc4707e38d2dae5922ec4bc2118", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 421, "license_type": "no_license", "max_line_length": 92, "num_lines": 21, "path": "/demo2.1_detect_polygon/detection_dual/lib/detection.hpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 06.12.19.\n//\n\n#ifndef DETECTION_H\n#define DETECTION_H\n\n#include <iostream>\n#include <vector>\n#include <opencv2/opencv.hpp>\n\nusing namespace std;\nusing namespace cv;\n\nvector<Point> findLargestContour(vector< vector<Point> > contours);\n\nvector< vector<Point> > findLargeContours(vector< vector<Point> > contours, double minArea);\n\nvector< vector<Point> > getContours(Mat img);\n\n#endif //DETECTION_H\n" }, { "alpha_fraction": 0.5287118554115295, "alphanum_fraction": 0.5721676349639893, "avg_line_length": 28.75384521484375, "blob_id": "5d35edbc048713eed5bacf1d2b356c1e3f3afe38", "content_id": "15a297b9e9a44939d6ae7cdf1d656fe373d3267f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1933, "license_type": "no_license", "max_line_length": 106, "num_lines": 65, "path": "/demo2.2_detect_cylinder/detection_rgbd/src/takeFrameRealsense.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 30.01.20.\n//\n\n#include <iostream>\n#include <boost/format.hpp> // for formating strings\n\n#include <pointCloud.hpp>\n\n#include <librealsense2/rs.hpp>\n#include <opencv2/opencv.hpp>\n#include <pcl/io/pcd_io.h>\n\nusing namespace std;\nusing namespace cv;\n\nint main() {\n rs2::pipeline pipe;\n rs2::config cfg;\n cfg.enable_stream(RS2_STREAM_DEPTH, 1280, 720, RS2_FORMAT_Z16, 30);\n cfg.enable_stream(RS2_STREAM_COLOR, 1920, 1080, RS2_FORMAT_BGR8, 30);\n pipe.start(cfg);\n\n rs2::align align_to_color(RS2_STREAM_COLOR);\n\n rs2::pointcloud pc;\n rs2::points points;\n\n // start\n while (waitKey(1) != 'q') {\n rs2::frameset frameset = pipe.wait_for_frames();\n frameset = align_to_color.process(frameset);\n\n auto depth = frameset.get_depth_frame();\n auto color = frameset.get_color_frame();\n\n Mat matColor(Size(1920, 1080), CV_8UC3, (void*)color.get_data(), Mat::AUTO_STEP);\n Mat matDepth(Size(1920, 1080), CV_16U, (void*)depth.get_data(), Mat::AUTO_STEP);\n\n imshow(\"color\", matColor);\n Mat mask = Mat::zeros(matDepth.size(), CV_8UC1);\n for (int i = 0; i < matColor.rows; ++i) {\n uint16_t *p = matDepth.ptr<uint16_t>(i);\n for (int j = 0; j < matColor.cols; ++j) {\n if (p[j] > 700 && p[j] < 900)\n mask.at<uchar>(i, j) = 255;\n }\n }\n Mat colorWithMask;\n matColor.copyTo(colorWithMask, mask);\n imshow(\"with mask\", colorWithMask);\n\n // point cloud\n if (waitKey(1) == 's') {\n pc.map_to(color);\n points = pc.calculate(depth);\n\n PointCloudG pclPC = points2pcl(points);\n pcl::io::savePCDFileBinary(\"../../data/point_cloud/cloud_realsense02.pcd\", *pclPC);\n cout << \"PointCloud after filtering has: \" << pclPC->points.size() << \" data points.\" << endl;\n }\n }\n\n return 0;\n}" }, { "alpha_fraction": 0.6696751117706299, "alphanum_fraction": 0.6841155290603638, "avg_line_length": 16.3125, "blob_id": "f883da23cd83cb50fcc4ed0a21d6f6158acf017d", "content_id": "041b12b03badd860a182014a823bffa773f4f9da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 554, "license_type": "no_license", "max_line_length": 112, "num_lines": 32, "path": "/demo2.2_detect_cylinder/detection_rgbd/lib/vision.hpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 31.01.20.\n//\n\n#ifndef VISION_HPP\n#define VISION_HPP\n\n#include <opencv2/opencv.hpp>\n#include <vector>\n#include <stack>\n#include <pose.hpp>\n\nusing namespace cv;\nusing namespace std;\n\nclass CameraConfig {\npublic:\n Mat M;\n Mat distortion;\n Mat MInv;\n double fx, fy, cx, cy;\n\n CameraConfig();\n};\n\nCameraConfig C;\n\nvoid detectAruco(Mat img, vector<pose> &poses, vector<vector<Point2f> > &markerCorners, vector<int> &markerIds);\n\nvoid grow(cv::Mat& src, cv::Mat& mask, cv::Point seed, int threshold);\n\n#endif //VISION_HPP\n" }, { "alpha_fraction": 0.5064833164215088, "alphanum_fraction": 0.5554027557373047, "avg_line_length": 39.086612701416016, "blob_id": "a175feee7675a15fa9be8078c52ae32df3f6ca52", "content_id": "6eaf756d1bf9c48762e29961db8d07c3bd4b9390", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5350, "license_type": "no_license", "max_line_length": 143, "num_lines": 127, "path": "/demo2.2_detect_cylinder/hand_eye_calib/hand_eye_calib.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <chrono>\n#include <boost/format.hpp>\n#include <Eigen/Core>\n#include <ceres/ceres.h>\n#include <ceres/rotation.h>\n\nusing namespace std;\n\n// 代价函数的计算模型\nstruct HAND_EYE_COST {\n HAND_EYE_COST(Eigen::Matrix4d x1, Eigen::Matrix4d x2) : _x1(x1), _x2(x2){}\n\n // 残差的计算\n template<typename T>\n bool operator()(\n const T *const translation, // 3 dim\n const T *const angleAxis, // 3 dim\n T *residual) const {\n T R[9];\n ceres::AngleAxisToRotationMatrix(angleAxis, R);\n Eigen::Matrix<T, 4, 4> tran;\n tran << R[0], R[3], R[6], translation[0],\n R[1], R[4], R[7], translation[1],\n R[2], R[5], R[8], translation[2],\n T(0.0), T(0.0), T(0.0), T(1.0);\n Eigen::Matrix<T, 4, 4> _x1_Matrix = _x1.cast<T>();\n Eigen::Matrix<T, 4, 4> _x2_Matrix = _x2.cast<T>();\n Eigen::Matrix<T, 4, 4> Cost_Matrix = _x1_Matrix * tran - tran * _x2_Matrix;\n// residual[0] = (Cost_Matrix.array()*Cost_Matrix.array()).sum();\n residual[0] = Cost_Matrix(0, 0); residual[1] = Cost_Matrix(0, 1); residual[2] = Cost_Matrix(0, 2); residual[3] = Cost_Matrix(0, 3);\n residual[4] = Cost_Matrix(1, 0); residual[5] = Cost_Matrix(1, 1); residual[6] = Cost_Matrix(1, 2); residual[7] = Cost_Matrix(1, 3);\n residual[8] = Cost_Matrix(2, 0); residual[9] = Cost_Matrix(2, 1); residual[10] = Cost_Matrix(2, 2); residual[11] = Cost_Matrix(2, 3);\n residual[12] = Cost_Matrix(3, 0); residual[13] = Cost_Matrix(3, 1); residual[14] = Cost_Matrix(3, 2); residual[15] = Cost_Matrix(3, 3);\n// residual[0] = Cost_Matrix(0, 0); residual[1] = Cost_Matrix(0, 1); residual[2] = Cost_Matrix(0, 2);\n// residual[3] = Cost_Matrix(1, 0); residual[4] = Cost_Matrix(1, 1); residual[5] = Cost_Matrix(1, 2);\n// residual[6] = Cost_Matrix(2, 0); residual[7] = Cost_Matrix(2, 1); residual[8] = Cost_Matrix(2, 2);\n\n return true;\n }\n\n const Eigen::Matrix4d _x1, _x2; // x数据\n};\n\nvoid readData(char *path_w2e, char *path_c2o, int n, vector<Eigen::Matrix4d> &As, vector<Eigen::Matrix4d> &Bs) {\n ifstream file_w2e, file_c2o;\n file_w2e.open(path_w2e, ios::in);\n file_c2o.open(path_c2o, ios::in);\n vector<Eigen::Matrix4d> tran_list_w2e, tran_list_c2o;\n for (int i = 0; i < n; ++i) {\n double data[16] = {0};\n for (auto& d : data)\n file_w2e >> d;\n if (n >= 80) {\n data[3] /= 1000.0; data[7] /= 1000.0; data[11] /= 1000.0;\n }\n tran_list_w2e.emplace_back(Eigen::Map<Eigen::Matrix4d>(data).transpose());\n for (auto& d : data)\n file_c2o >> d;\n tran_list_c2o.emplace_back(Eigen::Map<Eigen::Matrix4d>(data).transpose());\n }\n file_w2e.close();\n file_c2o.close();\n for (int i = 0; i < n-1; ++i) {\n As.push_back(tran_list_w2e[i+1].inverse()*tran_list_w2e[i]);\n Bs.push_back(tran_list_c2o[i+1]*tran_list_c2o[i].inverse());\n }\n}\n\nint main(int argc, char **argv) {\n// if (argc != 2) {\n// cout << \"please enter the file path\" << endl;\n// return -1;\n// }\n\n double t0 = 0.0, t1 = 0.0, t2 = 0.016, t3 = 0.0, t4 = 0.0, t5 = 0.01; // 估计参数值\n double translation[3] = {t0, t1, t2};\n double angleAxis[3] = {t3, t4, t5};\n\n // 5 pairs of data\n int N = 80;\n vector<Eigen::Matrix4d> As, Bs; // As: Twe2.inv()*Twe1 Bs: Tco2*Tco1.inv()\n readData(\"../real_data/data_200219/data_w2e_80.txt\", \"../real_data/data_200219/data_c2o_80.txt\", N, As, Bs);\n // \"../fake_data/fake_data.txt\"\n\n // 构建最小二乘问题\n ceres::Problem problem;\n for (int i = 0; i < N-1; i++) {\n problem.AddResidualBlock( // 向问题中添加误差项\n // 使用自动求导,模板参数:误差类型,输出维度,输入维度,维数要与前面struct中一致\n new ceres::AutoDiffCostFunction<HAND_EYE_COST, 16, 3, 3>(\n new HAND_EYE_COST(As[i], Bs[i])\n ),\n nullptr, // 核函数,这里不使用,为空\n translation, angleAxis // 待估计参数\n );\n }\n\n // 配置求解器\n ceres::Solver::Options options; // 这里有很多配置项可以填\n options.linear_solver_type = ceres::DENSE_NORMAL_CHOLESKY; // 增量方程如何求解\n options.minimizer_progress_to_stdout = true; // 输出到cout\n\n ceres::Solver::Summary summary; // 优化信息\n chrono::steady_clock::time_point t_start = chrono::steady_clock::now();\n ceres::Solve(options, &problem, &summary); // 开始优化\n chrono::steady_clock::time_point t_end = chrono::steady_clock::now();\n chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t_end - t_start);\n cout << \"solve time cost = \" << time_used.count() << \" seconds. \" << endl;\n\n // 输出结果\n cout << summary.BriefReport() << endl;\n cout << \"estimated translation = \";\n for (auto a:translation) cout << a << \" \";\n cout << endl;\n\n double R[9];\n ceres::AngleAxisToRotationMatrix<double>(angleAxis, R);\n cout << \"estimated R = \";\n for (auto a:R) cout << a << \" \";\n cout << endl;\n\n return 0;\n}" }, { "alpha_fraction": 0.7426556944847107, "alphanum_fraction": 0.7426556944847107, "avg_line_length": 43.73684310913086, "blob_id": "889a088de20e34f565bbe33d4c9d7eda6e070b3e", "content_id": "62e33c1a2407088786665a1c7fed52a958bd64cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 851, "license_type": "no_license", "max_line_length": 84, "num_lines": 19, "path": "/demo5.1_final/detection/lib/CMakeLists.txt", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "# =========================\n# add libraries\n# =========================\n\nadd_library(utility SHARED utility.cpp header/utility.hpp)\ntarget_include_directories(utility PUBLIC \"${CMAKE_CURRENT_SOURCE_DIR}/header\")\n\nadd_library(lib_rs SHARED lib_rs.cpp header/lib_rs.hpp)\ntarget_include_directories(lib_rs PUBLIC \"${CMAKE_CURRENT_SOURCE_DIR}/header\")\n\nadd_library(lib_camera SHARED header/lib_camera.hpp)\nset_target_properties(lib_camera PROPERTIES LINKER_LANGUAGE CXX)\ntarget_include_directories(lib_camera PUBLIC \"${CMAKE_CURRENT_SOURCE_DIR}/header\")\n\nadd_library(lib_det SHARED lib_det.cpp header/lib_det.hpp)\ntarget_include_directories(lib_det PUBLIC \"${CMAKE_CURRENT_SOURCE_DIR}/header\")\n\nadd_library(lib_geometry SHARED lib_geometry.cpp header/lib_geometry.hpp)\ntarget_include_directories(lib_geometry PUBLIC \"${CMAKE_CURRENT_SOURCE_DIR}/header\")\n\n" }, { "alpha_fraction": 0.5492677688598633, "alphanum_fraction": 0.5903091430664062, "avg_line_length": 39.37226104736328, "blob_id": "be796172bfca886ff7c32709629662ae94fd8aa7", "content_id": "22ef69cbe27c2af38e6ae9af45d5766714d0c9a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5531, "license_type": "no_license", "max_line_length": 137, "num_lines": 137, "path": "/demo4.1_tracking/web/catkin_ws/src/web/src/f_assem.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "#include \"lib.h\"\n#include <std_msgs/Float32.h>\n\n#define F_STATE 5\n#define POLE_COUNT 5\n#define NUM_PARAMS_AXIS 7\n#define PATH_DESIGNED_AXES (ros::package::getPath(\"web\") + \"/cfg/cylinder_params.txt\")\n\n#define COLOR_UNSELECTED (Scalar(255, 100, 100))\n#define COLOR_SELECTED (Scalar(255, 0, 0))\n#define COLOR_CIRCLE (Scalar(255, 20, 20))\n\nMat imgCallback;\nMat depthImgCallback;\nbool RECEIVED_COLOR = false;\nbool RECEIVED_DEPTH = false;\n\nstatic void ImageCallback(const sensor_msgs::CompressedImageConstPtr &msg) {\n try {\n cv_bridge::CvImagePtr cv_ptr_compressed = cv_bridge::toCvCopy(msg,sensor_msgs::image_encodings::BGR8);\n imgCallback = cv_ptr_compressed->image;\n RECEIVED_COLOR = true;\n } catch (cv_bridge::Exception& e){ }\n}\n\nstatic void DepthImageCallback(const sensor_msgs::ImageConstPtr &msg) {\n try {\n cv_bridge::CvImagePtr cv_ptr = cv_bridge::toCvCopy(msg,sensor_msgs::image_encodings::MONO16);\n depthImgCallback = cv_ptr->image;\n RECEIVED_DEPTH = true;\n } catch (cv_bridge::Exception& e){ }\n}\n\nvoid drawAxis(double** cyl, int index, double length, Mat c2w) {\n for (int i = 0; i < POLE_COUNT; i++) {\n Mat p0_3d = (Mat_<double>(4, 1) << cyl[i][1], cyl[i][2], cyl[i][3], 1.);\n Mat p1_3d = (Mat_<double>(4, 1) << cyl[i][1] + cyl[i][4]*length, cyl[i][2] + cyl[i][5]*length, cyl[i][3] + cyl[i][6]*length, 1.);\n Mat p0_2d = C.MExt * c2w * p0_3d;\n Mat p1_2d = C.MExt * c2w * p1_3d;\n Point p0 = Point(p0_2d.at<double>(0, 0) / p0_2d.at<double>(2, 0), p0_2d.at<double>(1, 0) / p0_2d.at<double>(2, 0));\n Point p1 = Point(p1_2d.at<double>(0, 0) / p1_2d.at<double>(2, 0), p1_2d.at<double>(1, 0) / p1_2d.at<double>(2, 0));\n // draw\n if (i == index) line(imgCallback, p0, p1, COLOR_SELECTED, 2);\n else line(imgCallback, p0, p1, COLOR_UNSELECTED, 1);\n }\n}\n\ndouble getDeviation(double* cyl, double length, Mat c2w) {\n double start, gap; int count;\n ros::param::get(\"monitor_start\", start);\n ros::param::get(\"monitor_gap\", gap);\n ros::param::get(\"monitor_count\", count);\n double r = cyl[0]; // mm\n Mat w2c = c2w.inv();\n Mat p0_3d = (Mat_<double>(4, 1) << cyl[1], cyl[2], cyl[3], 1.);\n Mat p1_3d = (Mat_<double>(4, 1) << cyl[1] + cyl[4]*length, cyl[2] + cyl[5]*length, cyl[3] + cyl[6]*length, 1.);\n Eigen::Vector3d v_a, v_c, v_p, v_p2c, v_h;\n v_a << cyl[4], cyl[5], cyl[6]; // axis vec\n v_c << w2c.at<double>(0, 3), w2c.at<double>(1, 3), w2c.at<double>(2, 3); // camera center\n v_p << p0_3d.at<double>(0, 0), p0_3d.at<double>(1, 0), p0_3d.at<double>(2, 0); // axis start point\n v_p2c = v_c - v_p; // axis start to camera center\n v_h = v_p2c - (v_p2c.dot(v_a) * v_a); // perpendicular to the axis\n v_h /= sqrt(v_h.dot(v_h)); // normalization\n vector<Point> checkPoints;\n vector<double> checkDepth;\n for (int i = 0; i < count; ++i) {\n Eigen::Vector3d p_t = v_p + (start+gap*i) * v_a; // point on axis, evey 10 mm\n Eigen::Vector3d p_t_offset = p_t + v_h * r;\n Mat p_3d_t = (Mat_<double>(4, 1) << p_t_offset(0, 0), p_t_offset(1, 0), p_t_offset(2, 0), 1.);\n Mat p_2d_t = C.MExt * c2w * p_3d_t;\n checkDepth.push_back(p_2d_t.at<double>(2, 0));\n checkPoints.emplace_back(p_2d_t.at<double>(0, 0) / p_2d_t.at<double>(2, 0), p_2d_t.at<double>(1, 0) / p_2d_t.at<double>(2, 0));\n }\n double cost = 0.;\n for (int i = 0; i < checkPoints.size(); ++i) {\n circle(imgCallback, checkPoints[i], 2, COLOR_CIRCLE, 2);\n cost += abs((double)depthImgCallback.at<uint16_t>(checkPoints[i]) / 10. - checkDepth[i]);\n }\n cost = cost / checkPoints.size();\n return cost;\n}\n\nint main(int argc, char **argv) {\n // // window setting\n // namedWindow(\"imgCallback\", 0);\n // cvResizeWindow(\"imgCallback\", 960, 540);\n\n // ros init\n ros::init(argc, argv, \"f_assemble\");\n ros::NodeHandle nh;\n\n // sub\n ros::Subscriber image_sub_color = nh.subscribe(\"rs_color/compressed\", 10, ImageCallback);\n ros::Subscriber image_sub_depth = nh.subscribe(\"rs_depth\", 10, DepthImageCallback);\n \n // pub\n image_transport::ImageTransport it(nh);\n image_transport::Publisher pub = it.advertise(\"img\", 1);\n\n ros::Publisher pub_deviation = nh.advertise<std_msgs::Float32>(\"deviation\", 10);\n\n // read file of designed axis\n double **c_params = readData(PATH_DESIGNED_AXES, POLE_COUNT, NUM_PARAMS_AXIS);\n\n ros::Rate loop_rate(10);\n while (ros::ok()) {\n // check state\n if (!checkState(F_STATE)) { loop_rate.sleep(); continue; }\n // check if image received\n if (!(RECEIVED_COLOR && RECEIVED_DEPTH)) { ros::spinOnce(); loop_rate.sleep(); continue; }\n // INFO received\n ROS_INFO(\"cv_ptr_compressed: %d * %d \", imgCallback.cols, imgCallback.rows);\n\n // read pose\n Mat c2w = readPose();\n \n // draw designed axis\n int drawIndex;\n ros::param::get(\"draw_index\", drawIndex);\n drawAxis(c_params, drawIndex, 300.0, c2w);\n double cost = getDeviation(c_params[drawIndex], 300.0, c2w);\n \n // imshow(\"imgCallback\",depthImgCallback);\n // waitKey(1);\n\n // pub\n sensor_msgs::ImagePtr msg = cv_bridge::CvImage(std_msgs::Header(), \"bgr8\", imgCallback).toImageMsg();\n pub.publish(msg);\n std_msgs::Float32 msg_deviation;\n msg_deviation.data = cost;\n pub_deviation.publish(msg_deviation);\n\n ros::spinOnce();\n loop_rate.sleep();\n }\n return 0;\n}\n" }, { "alpha_fraction": 0.4747774600982666, "alphanum_fraction": 0.5341246128082275, "avg_line_length": 24.923076629638672, "blob_id": "339d639c95d9e162cbad31247c2ffb113edb5be8", "content_id": "b515ebacbdd446d067c0b3da3d0243db391ba7fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1015, "license_type": "no_license", "max_line_length": 65, "num_lines": 39, "path": "/demo2.2_detect_cylinder/detection_rgbd/lib/pose.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by 戚越 on 2019-12-05.\n//\n\n#include <pose.hpp>\n\npose::pose(Point3d origin, Vec3d rotationVec) {\n Mat r;\n Rodrigues(rotationVec, r);\n Mat t = (Mat_<double>(3, 1) << origin.x, origin.y, origin.z);\n hconcat(r, t, m);\n Mat down = (Mat_<double>(1, 4) << 0., 0., 0., 1.);\n vconcat(m, down, m);\n}\n\n//pose::pose(Vec3d origin, Vec3d rotationVec) {\n// Point3d point(origin);\n// pose(point, rotationVec);\n//}\n\npose::pose(Point3d origin, Vec3d unitX, Vec3d unitZ) {\n Vec3d unitY = unitZ.cross(unitX);\n m = (Mat_<double>(4, 4) <<\n unitX[0], unitY[0], unitZ[0], origin.x,\n unitX[1], unitY[1], unitZ[1], origin.y,\n unitX[2], unitY[2], unitZ[2], origin.z,\n 0., 0., 0., 1.\n );\n}\n\nMat pose::R() { return m(Rect(0, 0, 3, 3)); }\n\nMat pose::origin() { return m(Rect(3, 0, 1, 3)); }\n\nMat pose::xAxis() { return m(Rect(0, 0, 1, 3)); }\n\nMat pose::yAxis() { return m(Rect(1, 0, 1, 3)); }\n\nMat pose::zAxis() { return m(Rect(2, 0, 1, 3)); }\n" }, { "alpha_fraction": 0.6254180669784546, "alphanum_fraction": 0.7257525324821472, "avg_line_length": 16.58823585510254, "blob_id": "f975e75f3f5eeb9c4883d84e511cfc0699a9c51c", "content_id": "46850950a9ecfd7503559851dfa6a906904619e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 299, "license_type": "no_license", "max_line_length": 40, "num_lines": 17, "path": "/demo3.1_validate_in_process_scan/detection/construct3D_built/construct3D_built.hpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 29.03.20.\n//\n\n#ifndef DETECTION_CONSTRUCT3D_BUILD_HPP\n#define DETECTION_CONSTRUCT3D_BUILD_HPP\n\n#define POLE_COUNT 5\n\n#define X_MIN -20.0\n#define X_MAX 900\n#define Y_MIN 70.0\n#define Y_MAX 375.0\n#define Z_MIN 15.0\n#define Z_MAX 100.0\n\n#endif //DETECTION_CONSTRUCT3D_BUILD_HPP\n" }, { "alpha_fraction": 0.7772828340530396, "alphanum_fraction": 0.7917594909667969, "avg_line_length": 33.53845977783203, "blob_id": "4af557f6a0d07a34623e6c213f2bddf0e7287aaa", "content_id": "3240ea00c22d6ed6b4c96ca14bd92910fba3b91c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 898, "license_type": "no_license", "max_line_length": 85, "num_lines": 26, "path": "/demo2.2_detect_cylinder/hand_eye_calib/CMakeLists.txt", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "project (hand_eye_calib)\nset(CMAKE_CXX_FLAGS \"-std=c++14 -O3\")\ncmake_minimum_required(VERSION 3.15)\n\nfind_package(OpenCV REQUIRED)\ninclude_directories(${OpenCV_INCLUDE_DIRS})\n\nfind_package(Eigen3 REQUIRED)\ninclude_directories(${Eigen3_INCLUDE_DIRS})\n\nfind_package(Ceres REQUIRED)\ninclude_directories(${CERES_INCLUDE_DIRS})\n\nfind_package(realsense2 REQUIRED)\n\nadd_executable(hand_eye_calib hand_eye_calib.cpp)\ntarget_link_libraries(hand_eye_calib PRIVATE ${CERES_LIBRARIES} Eigen3::Eigen)\n\nadd_executable(hand_eye_calib_t hand_eye_calib_t.cpp)\ntarget_link_libraries(hand_eye_calib_t PRIVATE ${CERES_LIBRARIES} Eigen3::Eigen)\n\nadd_executable(detect_marker detect_marker.cpp)\ntarget_link_libraries(detect_marker PRIVATE ${OpenCV_LIBS} ${realsense2_LIBRARY})\n\nadd_executable(detect_chessboard detect_chessboard.cpp)\ntarget_link_libraries(detect_chessboard PRIVATE ${OpenCV_LIBS} ${realsense2_LIBRARY})\n" }, { "alpha_fraction": 0.47922438383102417, "alphanum_fraction": 0.5124653577804565, "avg_line_length": 26.75, "blob_id": "27b0e6ddfbc53e0e23e2886c5fd3061714d00c9c", "content_id": "d6aecb9415ba1fcc3008afaa0b29159e946af94a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1444, "license_type": "no_license", "max_line_length": 114, "num_lines": 52, "path": "/workshop/linear_regression/main.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom matplotlib import pyplot as plt\n\n\ndef generate_data(n, k, b, low=0.0, high=10.0):\n step = (high - low) / n\n x, y = [], []\n for i in range(n):\n x.append(low + step * i)\n y.append(x[i] * k + b + np.random.normal(0.0, 0.05 * (high - low)))\n return np.array(x), np.array(y)\n\n\ndef model(_x, _theta):\n return _x * _theta[0] + _theta[1]\n\n\ndef loss(_x, _y, _theta, _model):\n _loss = 0.0\n for i in range(len(_x)):\n _loss += (model(_x[i], _theta) - _y[i]) ** 2\n return _loss / len(_x)\n\n\ndef gradient(_x, _y, _theta, _model):\n g = np.array([0.0, 0.0])\n for i in range(len(_x)):\n g[0] += (model(_x[i], _theta) - _y[i]) * _x[i]\n g[1] += (model(_x[i], _theta) - _y[i])\n return g\n\n\ndef train(_x, _y, _theta, _model, lr=1e-5, steps=1000):\n for step in range(steps):\n _theta -= lr * gradient(_x, _y, _theta, _model)\n # print log\n if step % 100 == 0:\n print(\"step: %d, theta: %f %f, loss: %f\" % (step, _theta[0], _theta[1], loss(_x, _y, _theta, _model)))\n return _theta\n\n\nif __name__ == \"__main__\":\n x_train, y_train = generate_data(100, 2.0, 0.5)\n theta = np.array([1.0, 0.0])\n # plot x, y data\n plt.scatter(x_train, y_train, color=\"red\")\n # training\n theta_new = train(x_train, y_train, theta, model, steps=1000)\n # plot line\n y_new = model(x_train, theta_new)\n plt.plot(x_train, y_new)\n plt.show()\n\n" }, { "alpha_fraction": 0.8412017226219177, "alphanum_fraction": 0.8412017226219177, "avg_line_length": 37.83333206176758, "blob_id": "28ab72ea09f8692dc29c849225a552a41d9fa4e6", "content_id": "8a86ce57d2fc55b2017824cfb9e175124ebba87d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 233, "license_type": "no_license", "max_line_length": 51, "num_lines": 6, "path": "/demo2.1_detect_polygon/detection_dual/src/CMakeLists.txt", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "add_executable(main main.cpp main.hpp)\n\ntarget_link_libraries(main PRIVATE libdetection)\ntarget_link_libraries(main PRIVATE libmatching)\ntarget_link_libraries(main PRIVATE libcameraConfig)\ntarget_link_libraries(main PRIVATE libPose)\n" }, { "alpha_fraction": 0.5060343146324158, "alphanum_fraction": 0.5369709134101868, "avg_line_length": 32.62285614013672, "blob_id": "30eea90b755a2c60a0fc48e6d02a80aa25a60979", "content_id": "5a5af8ecf5a6b97e1d0c494aefebc34e398abddb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5883, "license_type": "no_license", "max_line_length": 118, "num_lines": 175, "path": "/demo3.1_validate_in_process_scan/detection/registerExt.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <fstream>\n#include <chrono>\n#include <boost/format.hpp> // for formating strings\n\n#include <opencv2/opencv.hpp>\n\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n#include <pcl/filters/statistical_outlier_removal.h>\n#include <pcl/filters/voxel_grid.h>\n\ntypedef pcl::PointXYZRGB P_C;\ntypedef pcl::PointXYZ P_G;\ntypedef pcl::PointCloud<P_C>::Ptr PC_C;\ntypedef pcl::PointCloud<P_G>::Ptr PC_G;\n\nusing namespace std;\nusing namespace cv;\n\npcl::PCDReader reader;\npcl::PCDWriter writer;\npcl::StatisticalOutlierRemoval<P_C> sor;\npcl::VoxelGrid<P_C> vg;\n\nclass CameraConfig {\npublic:\n Mat M;\n Mat distortion;\n Mat MInv;\n double fx, fy, cx, cy;\n\n CameraConfig() {\n M = (Mat_<double>(3, 3)\n << 1382.23, 0., 953.567\n , 0., 1379.46, 532.635\n , 0., 0., 1.);\n distortion = (Mat_<double >(1, 5)\n << 0.0, 0.0, 0.0, 0.0, 0.0);\n MInv = M.inv();\n fx = 1382.23; fy = 1379.46; cx = 953.567; cy = 532.635;\n };\n};\n\nCameraConfig C;\n\ndouble **readData(string path, int num_frames) {\n ifstream file;\n file.open(path, ios::in);\n auto **data = new double*[num_frames];\n for (int i = 0; i < num_frames; ++i) {\n data[i] = new double[6];\n for (int j = 0; j < 6; ++j)\n file >> data[i][j];\n }\n file.close();\n return data;\n}\n\nMat t_4_4__rvec(Vec3d rvec, Vec3d tvec) {\n Mat r, t_4_4;\n Rodrigues(rvec, r);\n hconcat(r, tvec*1000.0, t_4_4);\n Mat down = (Mat_<double>(1, 4) << 0., 0., 0., 1.);\n vconcat(t_4_4, down, t_4_4);\n return t_4_4;\n}\n\nint findIndex(vector<int> indices, int index) {\n auto iElement = find(indices.begin(), indices.end(), index);\n if( iElement != indices.end() ) {\n return distance(indices.begin(),iElement);\n } else {\n return -1;\n }\n}\n\nint main(int argc, char **argv) {\n if (argc != 2) {\n cout << \"please enter number of frames\" << endl;\n return -1;\n }\n const int num_frames = stoi(argv[1]);\n\n // read ext params\n double **ext_params = readData(\"../data2D/c2w.txt\", num_frames);\n vector<Mat> w2c;\n for (int i = 0; i < num_frames; ++i) {\n Vec3d rvec(ext_params[i][0], ext_params[i][1], ext_params[i][2]);\n Vec3d tvec(ext_params[i][3], ext_params[i][4], ext_params[i][5]);\n w2c.push_back(t_4_4__rvec(rvec, tvec).inv());\n// cout << c2w[i] << endl;\n// for (int j = 0; j < 6; ++j) {\n// cout << ext_params[i][j] << \" \";\n// }\n// cout << endl;\n }\n\n// PointCloudC clouds_full[num_frames];\n PC_C cloud_aligned (new pcl::PointCloud<P_C>);\n vector<int> skip_indices = {40, 41, 42, 43, 44, 46,\n 49,\n 52};\n // load clouds\n for (int frame_index = 0; frame_index < num_frames; ++frame_index) {\n // skip index\n if (findIndex(skip_indices, frame_index) != -1) continue;\n // load image\n Mat matColor = imread((boost::format(\"../data2D/color_%d.png\") % frame_index).str());\n Mat matDepth = imread((boost::format(\"../data2D/depth_%d.png\") % frame_index).str(), CV_LOAD_IMAGE_UNCHANGED);\n // construct cloud\n PC_C cloud_t (new pcl::PointCloud<P_C>);\n for (int v = 0; v < matColor.rows; ++v) {\n for (int u = 0; u < matColor.cols; ++u) {\n double d = (double)matDepth.ptr<uint16_t>(v)[u] * 0.1; // unit: 0.1mm\n if (d == 0.0 || d > 1500.0f) continue;\n Mat p_c = (Mat_<double>(4, 1)\n << ((double)u - C.cx) * d / C.fx, ((double)v - C.cy) * d / C.fy, d, 1.0);\n Mat p_w = w2c[frame_index] * p_c;\n P_C pt;\n pt.x = p_w.at<double>(0, 0);\n pt.y = p_w.at<double>(1, 0);\n pt.z = p_w.at<double>(2, 0);\n pt.b = matColor.data[ v*matColor.step+u*matColor.channels() ];\n pt.g = matColor.data[ v*matColor.step+u*matColor.channels()+1 ];\n pt.r = matColor.data[ v*matColor.step+u*matColor.channels()+2 ];\n cloud_t->points.push_back(pt);\n }\n }\n\n vg.setInputCloud(cloud_t);\n float size = 2.0f;\n vg.setLeafSize(size, size, size);\n vg.filter(*cloud_t);\n // remove outliers\n sor.setInputCloud (cloud_t);\n sor.setMeanK (20);\n sor.setStddevMulThresh (0.5);\n sor.filter (*cloud_t);\n\n *cloud_aligned += *cloud_t;\n }\n\n// cloud_aligned = clouds_full[0];\n// pcl::IterativeClosestPoint<PointG, PointG> icp;\n// cout << \"cloud 0: \" << clouds_full[0]->points.size() << endl;\n// for (int frame_index = 1; frame_index < num_frames; ++frame_index) {\n// cout << \"cloud \" << frame_index << \": \" << clouds_full[frame_index]->points.size() << endl;\n//\n//// chrono::steady_clock::time_point t_start = chrono::steady_clock::now(); // timing start\n//\n// icp.setInputSource(clouds_full[frame_index]);\n// icp.setInputTarget(cloud_aligned);\n// pcl::PointCloud<PointG> final;\n// icp.align(final);\n// *cloud_aligned += final;\n//\n//// chrono::steady_clock::time_point t_end = chrono::steady_clock::now(); // timing end\n//// chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t_end - t_start);\n//// cout << \"time cost = \" << time_used.count() << \" seconds. \" << endl;\n// }\n//\n\n//\n//// cloud_merged->width = cloud_merged->points.size();\n//// cloud_merged->height = 1;\n//// cloud_merged->resize(cloud_merged->width*cloud_merged->height);\n vg.setInputCloud(cloud_aligned);\n float size = 4.0f;\n vg.setLeafSize(size, size, size);\n vg.filter(*cloud_aligned);\n writer.write (\"../data3D/cloud_aligned.pcd\", *cloud_aligned, false);\n return 0;\n}" }, { "alpha_fraction": 0.3684210479259491, "alphanum_fraction": 0.5263158082962036, "avg_line_length": 11.333333015441895, "blob_id": "42171742798c8fc8810150d8529a186e962c9b0a", "content_id": "454f6d5ed9a45fb7968bee140ba5f4ce6751ec8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 38, "license_type": "no_license", "max_line_length": 30, "num_lines": 3, "path": "/demo5.1_final/detection/lib/lib_geometry.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 23.09.20.\n//\n\n" }, { "alpha_fraction": 0.6782786846160889, "alphanum_fraction": 0.7008196711540222, "avg_line_length": 24.6842098236084, "blob_id": "f7a765d266481fffd15faf750d7b9b995a21ed5b", "content_id": "b06161b8372866d8b472bac19778d8313410c4ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 976, "license_type": "no_license", "max_line_length": 97, "num_lines": 38, "path": "/demo5.1_final/detection/lib/header/utility.hpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 26.09.20.\n//\n\n#ifndef DETECTION_UTILITY_HPP\n#define DETECTION_UTILITY_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <string>\n\n#define LEN_CYL 7\ntypedef Eigen::Matrix<double, LEN_CYL, 1> Cylinder;\n\nnamespace utility {\n\n int findIndex(std::vector<int> indices, int index);\n\n Eigen::Vector4d getCorner(int index, double size);\n\n double** readData(std::string path, int row, int col);\n\n double* readDataRow(std::string path, int col);\n\n double distance2cylinder(Cylinder pole, Eigen::Vector3d point,\n double start_param, double end_param, bool is_finite=true);\n\n double line_closest_param(Eigen::Vector3d start, Eigen::Vector3d dir, Eigen::Vector3d point);\n\n Cylinder get_seg(Cylinder pole, double start_param, double r);\n\n // start_param range [0.0, 1.0]\n // end_param range [0.0, 1.0]\n Cylinder cylinder_seg(Cylinder pole, double start_param, double end_param);\n}\n\n\n#endif //DETECTION_UTILITY_HPP\n" }, { "alpha_fraction": 0.802395224571228, "alphanum_fraction": 0.8143712282180786, "avg_line_length": 32.599998474121094, "blob_id": "be6d951acf3025479145fd985b64bdd132315191", "content_id": "7db6e9626b50cb006de637dd951963b445ad0d4c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 167, "license_type": "no_license", "max_line_length": 44, "num_lines": 5, "path": "/demo4.1_tracking/README.md", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "# demo4.1_tracking\n- tracking of the camera using Aruco markers\n- investigation in helping device\n- web interface development\n- Sequential Least Squares for adaptation" }, { "alpha_fraction": 0.4973275065422058, "alphanum_fraction": 0.569727897644043, "avg_line_length": 32.73770523071289, "blob_id": "c49b2cd2c7bb21b501e9d19f97a94076f2f34a29", "content_id": "fc52e0148cfea458050c533d437638b6b7e5fdd4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4116, "license_type": "no_license", "max_line_length": 100, "num_lines": 122, "path": "/demo5.1_final/localization_and_mapping/code/marker_opt_initial_guess.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport numpy as np\nimport libs.lib_rs as rs\nimport libs.lib_frame as f\nimport cv2\nimport yaml\n\n\nwith open(\"config/config_marker.yml\", 'r') as file:\n conf = yaml.safe_load(file.read())\n\nn = conf[\"num_photos\"] # number of photos\nm = conf[\"num_markers\"] # number of markers\npath_img = conf[\"path_img\"] + \"color_%d.png\"\npath_result = conf[\"path_result\"]\ncorner_refinement = conf[\"corner_refinement\"]\nif conf[\"reorder\"]:\n indices = conf[\"reorder_indices_list\"]\nelse:\n indices = range(m)\n\nd415 = rs.D415()\nsize = d415.marker_size\n\n# ------------------------\n# initial guesses w2k\n# ------------------------\n\nw2k = [np.eye(4)]*m\n# w2k[0] = np.eye(4)\n# w2k[1] = f.t_4_4__rvec(np.array([1.07888743e-02, -3.80953256e-02, -1.59157464e+00]),\n# np.array([-9.08505140e-03, -4.23919083e-01, -1.34970647e-04]))\n# w2k[2] = f.t_4_4__rvec(np.array([-2.29909471e-02, 1.96608912e-02, -1.56549568e+00]),\n# np.array([6.33976050e-04, 3.89877312e-01, -5.58933275e-03]))\n\nfor i in range(1, m):\n print (\"m = %d\" % i)\n for j in range(n):\n color = cv2.imread(path_img % j)\n param = cv2.aruco.DetectorParameters_create()\n param.cornerRefinementMethod = corner_refinement\n corners, ids, _ = cv2.aruco.detectMarkers(color, d415.aruco_dict)\n # check if it contains i-th marker\n contain_i = False\n c2k_i, c2k_k = np.eye(4), np.eye(4)\n for k in range(len(corners)):\n if ids[k, 0] == indices[i]:\n contain_i = True\n c2k_i = rs.get_c2k(color, ids[k, 0], size, d415.C, d415.coeffs)\n break\n if not contain_i:\n continue\n # check if it contains marker with pose already known\n contain_know = False\n for k in range(len(corners)):\n if ids[k, 0] in indices[0:i]:\n contain_know = True\n c2k_k = rs.get_c2k(color, ids[k, 0], size, d415.C, d415.coeffs)\n print (\"n = %d\" % j)\n w2k[i] = w2k[indices.index(ids[k, 0])].dot(f.inv(c2k_k)).dot(c2k_i)\n break\n if contain_know:\n break\n\nnp.save(path_result + \"w2k_init\", f.rvecs6__t_4_4s(w2k[1:])) # exclude first one\n\n# -------------------------\n# for camera poses\n# -------------------------\n\nc2w = np.zeros([n, 6])\nfor i in range(n):\n color = cv2.imread(path_img % i)\n param = cv2.aruco.DetectorParameters_create()\n param.cornerRefinementMethod = corner_refinement\n corners, ids, _ = cv2.aruco.detectMarkers(color, d415.aruco_dict)\n index = ids[0, 0]\n rvec, tvec, _ = cv2.aruco.estimatePoseSingleMarkers(corners[0], size, d415.C, d415.coeffs)\n c2k = f.t_4_4__rvec(rvec.reshape([3, ]), tvec.reshape([3, ]))\n try:\n c2w[i] = f.rvec6__t_4_4(c2k.dot(f.inv(w2k[indices.index(index)])))\n except Exception:\n raise Exception(\"mis-detect in photo: %d\" % i)\n# print(c2w)\nnp.save(path_result + \"c2w_init\", c2w)\n\n# -------------------------\n# for marker relative poses\n# -------------------------\n\n# color = cv2.imread(path % 5)\n# gray = cv2.cvtColor(color, cv2.COLOR_BGR2GRAY)\n# param = cv2.aruco.DetectorParameters_create()\n# corners, ids, _ = cv2.aruco.detectMarkers(color, d415.aruco_dict)\n# # corner refinement\n# criteria = (cv2.TERM_CRITERIA_EPS + cv2.TermCriteria_COUNT, 40, 0.001)\n# for i in range(len(corners)):\n# cv2.cornerSubPix(gray, corners[1], (3, 3), (-1, -1), criteria)\n#\n# cv2.aruco.drawDetectedMarkers(color, corners, ids)\n# cv2.imshow(\"color\", color)\n# cv2.waitKey()\n#\n# c2k = []\n# for i in range(2):\n# print(ids[i])\n# size = 0.2\n# rvec, tvec, _ = cv2.aruco.estimatePoseSingleMarkers(corners[i], size, d415.C_r, d415.coeffs_r)\n# # cv2.aruco.drawAxis(color, d415.C_r, d415.coeffs_r, rvec, tvec, 0.2)\n# # cv2.imshow(\"color\", color)\n# # cv2.waitKey()\n# print(\"t\")\n# print(tvec)\n# print(\"r\")\n# print(rvec)\n# c2k.append(opt.t_4_4__rvec(rvec.reshape([3, ]), tvec.reshape([3, ])))\n#\n# print(\"================\")\n# k1 = opt.inv(c2k[1]).dot(c2k[0])\n# print(opt.rvec6__t_4_4(k1))\n\nd415.close()\n" }, { "alpha_fraction": 0.680134654045105, "alphanum_fraction": 0.7104377150535583, "avg_line_length": 13.142857551574707, "blob_id": "7dc2ba006fc54ff7a3abdcfe28d3dadc2e6821ee", "content_id": "8cabae0ead43efeb8a6913189237cd009a18ef3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 301, "license_type": "no_license", "max_line_length": 31, "num_lines": 21, "path": "/demo2.1_detect_polygon/detection_dual/src/main.hpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by 戚越 on 2019-10-10.\n//\n\n#ifndef MAIN_H\n#define MAIN_H\n\n#include <iostream>\n#include \"main.hpp\"\n#include <opencv2/opencv.hpp>\n#include <detection.cpp>\n#include <matching.cpp>\n#include <CameraConfig.hpp>\n#include <ctime>\n\nusing namespace cv;\nusing namespace std;\n\nint main();\n\n#endif\n" }, { "alpha_fraction": 0.6502509713172913, "alphanum_fraction": 0.659069299697876, "avg_line_length": 36.99484634399414, "blob_id": "48d03d931273533b555b164aca85e2fcae804a19", "content_id": "d7236d18ae5a214d66c131e930984a18d5ab748d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7393, "license_type": "no_license", "max_line_length": 141, "num_lines": 194, "path": "/demo2.2_detect_cylinder/detection_rgbd/lib/pointCloud.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 26.01.20.\n//\n\n#include <pcl/io/pcd_io.h>\n#include <pcl/ModelCoefficients.h>\n#include <pcl/filters/extract_indices.h>\n#include <pcl/filters/passthrough.h>\n#include <pcl/features/normal_3d.h>\n#include <pcl/sample_consensus/method_types.h>\n#include <pcl/sample_consensus/model_types.h>\n#include <pcl/segmentation/sac_segmentation.h>\n#include <pcl/visualization/cloud_viewer.h>\n\n#include <librealsense2/rs.hpp>\n#include <opencv2/opencv.hpp>\n\n#include <vision.hpp>\n\n#include \"pointCloud.hpp\"\n\nPointCloudG points2pcl(const rs2::points& points) {\n PointCloudG cloud(new pcl::PointCloud<pcl::PointXYZ>);\n auto sp = points.get_profile().as<rs2::video_stream_profile>();\n cloud->width = sp.width();\n cloud->height = sp.height();\n cloud->is_dense = false;\n cloud->points.resize(points.size());\n auto ptr = points.get_vertices();\n for (auto& p : cloud->points) {\n p.x = ptr->x;\n p.y = ptr->y;\n p.z = ptr->z;\n ptr++;\n }\n return cloud;\n}\n\nPointCloudG mat2pcl(const cv::Mat& depth, const cv::Mat& mask) {\n cout << \"ignore me \" << C.fx << endl;\n PointCloudG cloud( new pcl::PointCloud<PointG> );\n cloud->is_dense = false;\n for ( int v=0; v<mask.rows; v++ )\n for ( int u=0; u<mask.cols; u++ )\n {\n if (mask.ptr<uchar>(v)[u] == 0) continue;\n unsigned int d = depth.ptr<unsigned short> ( v )[u]; // 深度值\n if ( d==0 ) continue; // 为0表示没有测量到\n PointG p ;\n p.z = float(d)/1000.0f;\n p.x = (u-C.cx)*p.z/C.fx;\n p.y = (v-C.cy)*p.z/C.fy;\n\n cloud->points.push_back( p );\n }\n return cloud;\n}\n\nvoid detectCylinderRANSAC(const PointCloudG& pc) {\n // All the objects needed\n// pcl::PCDReader reader;\n pcl::PassThrough<PointG> pass;\n pcl::NormalEstimation<PointG, pcl::Normal> ne;\n pcl::SACSegmentationFromNormals<PointG, pcl::Normal> seg;\n pcl::PCDWriter writer;\n pcl::ExtractIndices<PointG> extract;\n pcl::ExtractIndices<pcl::Normal> extract_normals;\n pcl::search::KdTree<PointG>::Ptr tree (new pcl::search::KdTree<PointG> ());\n\n // Datasets\n pcl::PointCloud<PointG>::Ptr cloud (new pcl::PointCloud<PointG>);\n pcl::PointCloud<PointG>::Ptr cloud_filtered (new pcl::PointCloud<PointG>);\n pcl::PointCloud<pcl::Normal>::Ptr cloud_normals (new pcl::PointCloud<pcl::Normal>);\n pcl::PointCloud<PointG>::Ptr cloud_filtered2 (new pcl::PointCloud<PointG>);\n pcl::PointCloud<pcl::Normal>::Ptr cloud_normals2 (new pcl::PointCloud<pcl::Normal>);\n pcl::ModelCoefficients::Ptr coefficients_plane (new pcl::ModelCoefficients), coefficients_cylinder (new pcl::ModelCoefficients);\n pcl::PointIndices::Ptr inliers_plane (new pcl::PointIndices), inliers_cylinder (new pcl::PointIndices);\n\n // Read in the cloud data\n// reader.read (\"cloud_0.pcd\", *cloud);\n cloud = pc;\n std::cerr << \"PointCloud has: \" << cloud->points.size () << \" data points.\" << std::endl;\n\n // Build a passthrough filter to remove spurious NaNs\n pass.setInputCloud (cloud);\n pass.setFilterFieldName (\"z\");\n pass.setFilterLimits (0.2, 2.0);\n pass.filter (*cloud_filtered);\n std::cerr << \"PointCloud after filtering has: \" << cloud_filtered->points.size () << \" data points.\" << std::endl;\n\n // Estimate point normals\n ne.setSearchMethod (tree);\n ne.setInputCloud (cloud_filtered);\n ne.setKSearch (50);\n ne.compute (*cloud_normals);\n\n // Create the segmentation object for the planar model and set all the parameters\n seg.setOptimizeCoefficients (true);\n seg.setModelType (pcl::SACMODEL_NORMAL_PLANE);\n seg.setNormalDistanceWeight (0.1);\n seg.setMethodType (pcl::SAC_RANSAC);\n seg.setMaxIterations (100);\n seg.setDistanceThreshold (0.03);\n seg.setInputCloud (cloud_filtered);\n seg.setInputNormals (cloud_normals);\n // Obtain the plane inliers and coefficients\n seg.segment (*inliers_plane, *coefficients_plane);\n std::cerr << \"Plane coefficients: \" << *coefficients_plane << std::endl;\n\n // Extract the planar inliers from the input cloud\n extract.setInputCloud (cloud_filtered);\n extract.setIndices (inliers_plane);\n extract.setNegative (false);\n\n // Write the planar inliers to disk\n pcl::PointCloud<PointG>::Ptr cloud_plane (new pcl::PointCloud<PointG> ());\n extract.filter (*cloud_plane);\n std::cerr << \"PointCloud representing the planar component: \" << cloud_plane->points.size () << \" data points.\" << std::endl;\n writer.write (\"plane.pcd\", *cloud_plane, false);\n\n // Remove the planar inliers, extract the rest\n extract.setNegative (true);\n extract.filter (*cloud_filtered2);\n extract_normals.setNegative (true);\n extract_normals.setInputCloud (cloud_normals);\n extract_normals.setIndices (inliers_plane);\n extract_normals.filter (*cloud_normals2);\n\n // Create the segmentation object for cylinder segmentation and set all the parameters\n seg.setOptimizeCoefficients (true);\n seg.setModelType (pcl::SACMODEL_CYLINDER);\n seg.setMethodType (pcl::SAC_RANSAC);\n seg.setNormalDistanceWeight (0.1);\n seg.setMaxIterations (10000);\n seg.setDistanceThreshold (0.05);\n seg.setRadiusLimits (0, 0.1);\n seg.setInputCloud (cloud_filtered2);\n seg.setInputNormals (cloud_normals2);\n\n // Obtain the cylinder inliers and coefficients\n seg.segment (*inliers_cylinder, *coefficients_cylinder);\n std::cerr << \"Cylinder coefficients: \" << *coefficients_cylinder << std::endl;\n\n // Write the cylinder inliers to disk\n extract.setInputCloud (cloud_filtered2);\n extract.setIndices (inliers_cylinder);\n extract.setNegative (false);\n pcl::PointCloud<PointG>::Ptr cloud_cylinder (new pcl::PointCloud<PointG> ());\n extract.filter (*cloud_cylinder);\n if (cloud_cylinder->points.empty ())\n std::cerr << \"Can't find the cylindrical component.\" << std::endl;\n else\n {\n std::cerr << \"PointCloud representing the cylindrical component: \" << cloud_cylinder->points.size () << \" data points.\" << std::endl;\n writer.write (\"cylinder.pcd\", *cloud_cylinder, false);\n }\n}\n\nint test() {\n pcl::visualization::CloudViewer viewer(\"viewer\");\n\n pcl::PCDReader reader;\n pcl::PassThrough<PointG> pass;\n pcl::NormalEstimation<PointG, pcl::Normal> ne;\n pcl::search::KdTree<PointG>::Ptr tree(new pcl::search::KdTree<PointG> ());\n\n pcl::PointCloud<PointG>::Ptr cloud(new pcl::PointCloud<PointG>);\n pcl::PointCloud<PointG>::Ptr cloud_filtered (new pcl::PointCloud<PointG>);\n pcl::PointCloud<pcl::Normal>::Ptr cloud_normals (new pcl::PointCloud<pcl::Normal>);\n\n reader.read (\"../../data/point_cloud/cloud_0.pcd\", *cloud);\n cout << \"PointCloud has: \" << cloud->points.size () << \" data points.\" << endl;\n cout << \"width: \" << cloud->width << endl;\n cout << \"height: \" << cloud->height << endl;\n\n pass.setInputCloud(cloud);\n pass.setFilterFieldName(\"z\");\n pass.setFilterLimits(0, 0.8);\n pass.filter(*cloud_filtered);\n cout << \"PointCloud after filtering has: \" << cloud_filtered->points.size () << \" data points.\" << endl;\n\n // Estimate point normals\n ne.setSearchMethod(tree);\n ne.setInputCloud(cloud_filtered);\n ne.setKSearch(50);\n ne.compute(*cloud_normals);\n\n viewer.showCloud(cloud_filtered);\n while (!viewer.wasStopped())\n {\n }\n\n return 0;\n}\n" }, { "alpha_fraction": 0.5175332427024841, "alphanum_fraction": 0.5501813888549805, "avg_line_length": 31.431371688842773, "blob_id": "cdcc6b84a312b70432425f527866a03c92d8baf6", "content_id": "6b4aac446f611cb436d207da5d9c89e0adbeafff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3308, "license_type": "no_license", "max_line_length": 131, "num_lines": 102, "path": "/workshop/pytorch/logistic_regression/logistic_regression_pytorch_1.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom matplotlib import pyplot as plt\nimport torch\n\n\n\ndef generate_data(n, p=0.8):\n # p: percentage of data for training\n x1 = np.random.multivariate_normal([4., 3.], [[4., 0.], [0., 1.]], n)\n plt.scatter(x1.T[0], x1.T[1], marker=\"^\", color=\"red\")\n x2 = np.random.multivariate_normal([6., 0.], [[1.5, 0.5], [0.5, 1.5]], n)\n plt.scatter(x2.T[0], x2.T[1], color=\"blue\")\n # combine data\n x = np.vstack((x1, x2))\n y = np.asarray([[1., 0.]] * n + [[0., 1.]] * n)\n # shuffle data\n shuffle_idx = np.arange(0, n*2)\n np.random.shuffle(shuffle_idx)\n x_shuffled = x[shuffle_idx]\n y_shuffled = y[shuffle_idx]\n # split data into training and testing\n _x_train = x_shuffled[0:int(n * p)*2]\n _y_train = y_shuffled[0:int(n * p)*2]\n _x_test = x_shuffled[int(n * p)*2:n*2]\n _y_test = y_shuffled[int(n * p)*2:n*2]\n return _x_train, _y_train, _x_test, _y_test\n\n\n# sigmoid function\ndef sigmoid_func(z):\n return torch.ones(z.shape) / (1. + torch.exp(-z))\n\n\ndef sigmoid(_x, _theta):\n _input = _theta[0] * _x[0] + _theta[1] * _x[1] + _theta[2]\n return sigmoid_func(_input)\n\n\n# to calculate y (1 x 2) from x (1 x 2) and theta (1 x 3)\ndef model(_x, _theta):\n _y0 = sigmoid(_x, _theta)\n _y1 = torch.tensor(1.) - sigmoid(_x, _theta)\n _y = [_y0, _y1]\n return _y\n\n\ndef loss(_y, _y_predict):\n return -(_y[0] * torch.log(_y_predict[0]) + _y[1] * torch.log(_y_predict[1]))\n\n\ndef cost(_x, _y, _theta, _model=model):\n _cost = torch.tensor(0.)\n for i in range(len(_x)):\n _y_label = _y[i]\n _y_predict = _model(_x[i], _theta)\n _cost += loss(_y_label, _y_predict)\n return _cost / len(_x)\n\n\ndef error_rate(_x, _y, _theta, _model=model):\n _error_count = 0\n for i in range(len(_x)):\n _y_label = _y[i]\n _y_predict = _model(_x[i], _theta)\n if (_y_predict[0] > 0.5) and (_y_label[0] == 0):\n _error_count += 1\n if (_y_predict[1] > 0.5) and(_y_label[1] == 0):\n _error_count += 1\n _error_rate = _error_count / len(_x)\n return _error_rate\n\n\ndef train(_x, _y, _theta, _model=model, lr=1e-3, steps=1000):\n global x_test, y_test\n _theta.requires_grad = True\n for step in range(steps):\n _cost = cost(_x, _y, _theta, _model)\n _cost.backward()\n _theta.detach().sub_(_theta.grad.data * lr)\n _theta.grad.data.zero_()\n # print log\n if step % 100 == 0:\n print(\"step %d, theta [%f, %f, %f]\" % (step, _theta[0], _theta[1], _theta[2]))\n print(\"cost\", cost(_x, _y, _theta))\n print(\"training error rate %f, test error rate %f \" % (error_rate(_x, _y, _theta), error_rate(x_test, y_test, _theta)))\n return _theta\n\n\nif __name__ == \"__main__\":\n x_train, y_train, x_test, y_test = generate_data(100)\n print(x_train)\n theta_original = torch.tensor([1., 1., 0.], requires_grad=True)\n theta_new = train(x_train, y_train, theta_original)\n\n print(\"original cost\", cost(x_train, y_train, theta_original))\n print(\"original error rate\", error_rate(x_train, y_train, theta_original))\n print(\"new theta\", theta_new)\n\n x_boundary = [0., 10.]\n y_boundary = [-theta_new[2]/theta_new[1], (-theta_new[2]-10*theta_new[0])/theta_new[1]]\n plt.plot(x_boundary, y_boundary)\n plt.show()\n" }, { "alpha_fraction": 0.6479634046554565, "alphanum_fraction": 0.6537821888923645, "avg_line_length": 35.45454406738281, "blob_id": "e591f53208edcfe3a02d82de335d8abd69375763", "content_id": "c7a40f6fb069facef76eddaba849267af54e8afd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2406, "license_type": "no_license", "max_line_length": 112, "num_lines": 66, "path": "/demo3.1_validate_in_process_scan/detection/registerClouds.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <fstream>\n#include <chrono>\n#include <boost/format.hpp> // for formating strings\n\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n#include <pcl/filters/statistical_outlier_removal.h>\n#include <pcl/common/transforms.h>\n#include <pcl/registration/icp.h>\n\ntypedef pcl::PointXYZRGB PointC;\ntypedef pcl::PointXYZ PointG;\ntypedef pcl::PointCloud<PointC>::Ptr PointCloudC;\ntypedef pcl::PointCloud<PointG>::Ptr PointCloudG;\n\nusing namespace std;\n\npcl::PCDReader reader;\npcl::PCDWriter writer;\npcl::StatisticalOutlierRemoval<PointG> sor;\n\nint main(int argc, char **argv) {\n int num_frames = 32;\n\n PointCloudG clouds_full[num_frames];\n PointCloudG cloud_aligned (new pcl::PointCloud<PointG>);\n // load all the clouds\n for (int frame_index = 0; frame_index < num_frames; ++frame_index) {\n PointCloudG cloud(new pcl::PointCloud<PointG>);\n boost::format fmt(\"../data3D/cloud_downsampled_%d.pcd\");\n reader.read((fmt % frame_index).str(), *cloud);\n clouds_full[frame_index] = cloud;\n }\n cloud_aligned = clouds_full[0];\n pcl::IterativeClosestPoint<PointG, PointG> icp;\n cout << \"cloud 0: \" << clouds_full[0]->points.size() << endl;\n for (int frame_index = 1; frame_index < num_frames; ++frame_index) {\n cout << \"cloud \" << frame_index << \": \" << clouds_full[frame_index]->points.size() << endl;\n\n// chrono::steady_clock::time_point t_start = chrono::steady_clock::now(); // timing start\n\n icp.setInputSource(clouds_full[frame_index]);\n icp.setInputTarget(cloud_aligned);\n pcl::PointCloud<PointG> final;\n icp.align(final);\n *cloud_aligned += final;\n\n// chrono::steady_clock::time_point t_end = chrono::steady_clock::now(); // timing end\n// chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t_end - t_start);\n// cout << \"time cost = \" << time_used.count() << \" seconds. \" << endl;\n }\n\n // remove outliers\n// sor.setInputCloud (cloud_merged);\n// sor.setMeanK (5);\n// sor.setStddevMulThresh (0.5);\n// sor.filter (*cloud_merged);\n\n// cloud_merged->width = cloud_merged->points.size();\n// cloud_merged->height = 1;\n// cloud_merged->resize(cloud_merged->width*cloud_merged->height);\n writer.write (\"../data3D/cloud_aligned.pcd\", *cloud_aligned, false);\n return 0;\n}\n" }, { "alpha_fraction": 0.5452781319618225, "alphanum_fraction": 0.5646830797195435, "avg_line_length": 29.3137264251709, "blob_id": "9377f3a2ae5c9928780b70a8c56cc84172ef789e", "content_id": "583f58669ea3f7194ff2563c39707304e2a21732", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1546, "license_type": "no_license", "max_line_length": 96, "num_lines": 51, "path": "/demo5.1_final/detection/app/take_frame.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 23.09.20.\n//\n\n#include <boost/format.hpp>\n#include <lib_rs.hpp>\n#include <lib_det.hpp>\n#include <yaml-cpp/yaml.h>\n\nusing namespace cv;\nusing namespace std;\nnamespace det = detection;\n\nint main(int argc, char **argv) {\n /* ===============\n * load parameters\n * =============== */\n YAML::Node config = YAML::LoadFile(\"../../config/config_take_frame.yml\");\n auto path_img = config[\"path_img\"].as<string>();\n auto num_saved = config[\"save_init_index\"].as<int>();\n\n D415 d415;\n d415.print_intrinsics();\n Mat color, depth;\n namedWindow(\"color\", CV_WINDOW_NORMAL);\n cvResizeWindow(\"color\", 960, 540);\n boost::format file_color(path_img + \"color_%d.png\");\n boost::format file_depth(path_img + \"depth_%d.png\");\n boost::format file_color_drawn(path_img + \"color_drawn_%d.png\");\n while (true) {\n char key = waitKey(1);\n if (key == 'q') break;\n\n d415.receive_frame(color, depth);\n Mat color_drawn = color.clone();\n vector< vector<Point2f> > corners;\n vector<int> ids;\n det::detectMarker(color_drawn, corners, ids, 0.07, true, cv::aruco::CORNER_REFINE_NONE);\n imshow(\"color\", color_drawn);\n\n if (key == 's') {\n imwrite((file_color_drawn % num_saved).str(), color_drawn);\n imwrite((file_color % num_saved).str(), color);\n imwrite((file_depth % num_saved).str(), depth);\n cout << \"frame \" << num_saved << \" saved!\" << endl;\n ++ num_saved;\n }\n }\n\n return 0;\n}\n" }, { "alpha_fraction": 0.6508474349975586, "alphanum_fraction": 0.675000011920929, "avg_line_length": 29.649351119995117, "blob_id": "e9d85ac40bcd756c09a6c48a27c783acdf4b9a54", "content_id": "f51af8d883a04210a7481751294ace1a137a8eeb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2360, "license_type": "no_license", "max_line_length": 120, "num_lines": 77, "path": "/demo5.1_final/detection/lib/header/lib_det.hpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 23.09.20.\n//\n\n#ifndef DETECTION_LIB_DET_HPP\n#define DETECTION_LIB_DET_HPP\n\n#include <lib_camera.hpp>\n#include <utility.hpp>\n\n#include <opencv2/opencv.hpp>\n#include <Eigen/Geometry>\n#include <opencv2/aruco.hpp>\n\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n\n#define LEN_T_4_4 16\n#define LEN_TOPO_VEC 7\n\n#define TOPO_TYPE 0\n#define TOPO_FROM_INDEX 1\n#define TOPO_FROM_M_PARAM 2\n#define TOPO_FROM_B_PARAM 3\n#define TOPO_TO_INDEX 4\n#define TOPO_TO_M_PARAM 5\n#define TOPO_TO_B_PARAM 6\n\ntypedef pcl::PointXYZ PointG;\ntypedef pcl::PointCloud<PointG>::Ptr PointCloudG;\n\nnamespace detection {\n\n enum TASK_TYPE {\n SCAN_MATERIAL,\n SCAN_BUILT\n };\n\n enum TASK_NODE_TYPE {\n NODE_FROM,\n NODE_TO\n };\n\n PointCloudG solve_seg(cv::Mat depth, Eigen::Isometry3d c2w, Cylinder pole, double seg_param, double seg_length,\n double dis_max=2.0, double dis_thresh=0.005);\n\n bool detectMarker(cv::Mat img, std::vector< std::vector<cv::Point2f> > &corners, std::vector<int> &ids, double size,\n bool draw = true, cv::aruco::CornerRefineMethod corner_refinement = cv::aruco::CORNER_REFINE_NONE);\n\n Eigen::Isometry3d solve_pose(std::vector <std::vector<cv::Point2f>> corners, std::vector<int> ids, double size,\n std::vector<int> indices, std::vector<Eigen::Matrix4d> marker_poses);\n\n void clean_cloud(PointCloudG cloud, int mean_k);\n\n void downsample_cloud(PointCloudG cloud, float size);\n\n void remove_plane(PointCloudG cloud);\n\n void pass_through(PointCloudG cloud, double pass_through_height);\n\n Cylinder ransac(PointCloudG cloud, float radius, float dis_threshold);\n\n Cylinder fitting(PointCloudG cloud, Cylinder guess);\n\n Cylinder finite_seg(PointCloudG cloud, Cylinder pole);\n\n void draw_axis(cv::Mat img, Cylinder pole, Eigen::Isometry3d c2w,\n cv::Scalar color=cv::Scalar(255, 0, 0), int width=2);\n\n void draw_axes(cv::Mat img, std::vector<Cylinder> poles, Eigen::Isometry3d c2w,\n cv::Scalar color=cv::Scalar(255, 0, 0), int width=2);\n\n double getDeviation(cv::Mat color, cv::Mat depth, Cylinder pole, Eigen::Isometry3d c2w, int divide,\n cv::Scalar point_color=cv::Scalar(255, 0, 0), int size=2, int thickness=1, bool plot=true);\n}\n\n#endif //DETECTION_LIB_DET_HPP\n" }, { "alpha_fraction": 0.49248480796813965, "alphanum_fraction": 0.5551646947860718, "avg_line_length": 29.66666603088379, "blob_id": "f30cdf4ed24c24011ebf134b0ed03442eea178c2", "content_id": "b4548c250e25bdc57526403a40d51e6784043999", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3127, "license_type": "no_license", "max_line_length": 89, "num_lines": 102, "path": "/demo3.1_validate_in_process_scan/detection/level_chessboard.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 24.03.20.\n//\n\n#include <iostream>\n#include <vector>\n\n#include <opencv2/opencv.hpp>\n#include <opencv2/aruco.hpp>\n#include <librealsense2/rs.hpp>\n\nusing namespace std;\nusing namespace cv;\n\nclass CameraConfig {\npublic:\n Mat M;\n Mat distortion;\n Mat MInv;\n double fx, fy, cx, cy;\n\n CameraConfig() {\n M = (Mat_<double>(3, 3)\n << 1382.23, 0., 953.567\n , 0., 1379.46, 532.635\n , 0., 0., 1.);\n distortion = (Mat_<double >(1, 5)\n << 0.0, 0.0, 0.0, 0.0, 0.0);\n MInv = M.inv();\n fx = 1382.23; fy = 1379.46; cx = 953.567; cy = 532.635;\n };\n};\n\nCameraConfig C;\n\nbool detectChessboard(Mat img, Mat &tranc2o, Point &center) {\n vector<Point2f> corners;\n\n bool pattern_was_found = cv::findChessboardCorners(img, cv::Size(4, 3), corners);\n if (!pattern_was_found)\n return false;\n cv::drawChessboardCorners(img, cv::Size(4, 3), corners, pattern_was_found);\n vector<Point3f> objectPoints;\n\n for (int i = 0; i < 3; ++i)\n for (int j = 0; j < 4; ++j)\n objectPoints.push_back(Point3d(i*0.025, j*0.025, 0.0));\n Mat rvec, tvec;\n Mat matCorneres = Mat(corners).reshape(1);\n Mat matObjectPoints = Mat(objectPoints).reshape(1);\n solvePnP(matObjectPoints, matCorneres, C.M, C.distortion, rvec, tvec);\n\n cv::aruco::drawAxis(img, C.M, C.distortion, rvec, tvec, 0.125);\n center = corners[0];\n Mat r;\n Rodrigues(rvec, r);\n// Mat t = (Mat_<double>(3, 1) << tvec[0]*1000, tvec[1]*1000, tvec[2]*1000);\n hconcat(r, tvec, tranc2o);\n Mat down = (Mat_<double>(1, 4) << 0., 0., 0., 1.);\n vconcat(tranc2o, down, tranc2o);\n return true;\n}\n\nint main(int argc, char **argv) {\n rs2::pipeline pipe;\n rs2::config cfg;\n cfg.enable_stream(RS2_STREAM_DEPTH, 1280, 720, RS2_FORMAT_Z16, 30);\n cfg.enable_stream(RS2_STREAM_COLOR, 1920, 1080, RS2_FORMAT_BGR8, 30);\n pipe.start(cfg);\n\n rs2::align align_to_color(RS2_STREAM_COLOR);\n\n int num_parameters_saved = 0;\n cout << \"press 's' to print marker pose.\" << endl;\n // start\n while (waitKey(1) != 'q') {\n rs2::frameset frameset = pipe.wait_for_frames();\n frameset = align_to_color.process(frameset);\n\n auto depth = frameset.get_depth_frame();\n auto color = frameset.get_color_frame();\n\n Mat matColor(Size(1920, 1080), CV_8UC3, (void*)color.get_data(), Mat::AUTO_STEP);\n Mat matDepth(Size(1920, 1080), CV_16U, (void*)depth.get_data(), Mat::AUTO_STEP);\n\n Mat tranc2o;\n Point center;\n\n if (detectChessboard(matColor, tranc2o, center))\n if (waitKey(1) == 's') {\n cout << \"depth: \" << matDepth.at<int16_t>(center) << endl;\n cout << \"parameters: \" << num_parameters_saved << endl;\n for (int i = 0; i < 4; ++i)\n for (int j = 0; j < 4; ++j)\n cout << tranc2o.at<double>(i, j) << \" \";\n cout << endl << endl;\n num_parameters_saved += 1;\n }\n imshow(\"chessboard\", matColor);\n }\n return 0;\n}" }, { "alpha_fraction": 0.6452932953834534, "alphanum_fraction": 0.6603001356124878, "avg_line_length": 21.212121963500977, "blob_id": "021c3cfe978f8cc13868012969e8364375801455", "content_id": "8bac8c7be0de25b225e23b15bfb85231490248c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 733, "license_type": "no_license", "max_line_length": 43, "num_lines": 33, "path": "/demo5.1_final/detection/CMakeLists.txt", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "project(detection)\n\nset(CMAKE_CXX_FLAGS \"-std=c++14 -O3\")\ncmake_minimum_required(VERSION 3.15)\n\n# =========================\n# include packages\n# =========================\n\nfind_package(yaml-cpp REQUIRED)\n\nfind_package(realsense2 REQUIRED)\n\nfind_package(OpenCV REQUIRED)\ninclude_directories(${OpenCV_INCLUDE_DIRS})\n\nfind_package(Eigen3 REQUIRED)\ninclude_directories(${Eigen3_INCLUDE_DIRS})\n\nfind_package(Ceres REQUIRED)\ninclude_directories(${CERES_INCLUDE_DIRS})\n\nfind_package(PCL 1.2 REQUIRED)\ninclude_directories(${PCL_INCLUDE_DIRS})\nlink_directories(${PCL_LIBRARY_DIRS})\nadd_definitions(${PCL_DEFINITIONS})\n\n# =========================\n# add sub-directories\n# =========================\n\nadd_subdirectory(lib)\nadd_subdirectory(app)\n" }, { "alpha_fraction": 0.47704485058784485, "alphanum_fraction": 0.5187335014343262, "avg_line_length": 30.566667556762695, "blob_id": "1ba84c9e5653c5b128154ff92997f3ef66dd6845", "content_id": "ba05a9d8fbe86f707ba38c4004e650d439c11e79", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1895, "license_type": "no_license", "max_line_length": 86, "num_lines": 60, "path": "/workshop/gauss_newton/main.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom matplotlib import pyplot as plt\n\n\ndef generate_data(n, _theta_0, _model, low=0.0, high=100.0):\n step = (high - low) / n\n x, y = [], []\n for i in range(n):\n x.append(low + step * i)\n y.append(_model(x[i], theta_0) + np.random.normal(0.0, 0.0005 * (high - low)))\n return np.array(x), np.array(y)\n\n\ndef model(x, theta):\n return np.log(x*x*theta[0] + x*theta[1] + theta[2])\n\n\ndef train(_x_train, _y_train, _theta, _model, steps=100):\n cost, last_cost = .0, .0\n _theta_new = _theta.copy()\n for step in range(steps):\n H = np.zeros([3, 3], dtype=np.float32)\n b = np.zeros([3, 1], dtype=np.float32)\n for i in range(_x_train.shape[0]):\n y_est = _model(_x_train[i], _theta_new)\n error = y_est - _y_train[i]\n jacobi = np.zeros([1, 3], dtype=np.float32)\n jacobi[0, 0] = _x_train[i] * _x_train[i] / np.exp(y_est)\n jacobi[0, 1] = _x_train[i] / np.exp(y_est)\n jacobi[0, 2] = 1 / np.exp(y_est)\n H += jacobi.T.dot(jacobi)\n b += -error * jacobi.T\n cost += error * error\n if step > 1 and cost > last_cost:\n break\n\n dx = np.linalg.solve(H, b)\n _theta_new[0] += dx[0, 0]\n _theta_new[1] += dx[1, 0]\n _theta_new[2] += dx[2, 0]\n print(\"iteration: {0}, cost: {1}\".format(step, cost))\n last_cost = cost\n cost = 0\n return _theta_new\n\n\nif __name__ == \"__main__\":\n theta_0 = np.array([0.2, 0.5, 20.0])\n x_train, y_train = generate_data(100, theta_0, model)\n theta = np.array([0.1, 0.0, 10.0])\n # plot x, y data\n plt.scatter(x_train, y_train, color=\"red\")\n # training\n theta_new = train(x_train, y_train, theta, model, steps=1000)\n print(theta_new)\n # plot line\n y_new = model(x_train, theta_new)\n plt.plot(x_train, y_new)\n\n plt.show()\n\n" }, { "alpha_fraction": 0.5081945061683655, "alphanum_fraction": 0.553162693977356, "avg_line_length": 37.06185531616211, "blob_id": "4a65a291caf4e185ac7e9e8130cbd33fbc1e019c", "content_id": "6a7e3ba79fbd9d5202a6959b9a29d8b8477384c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7383, "license_type": "no_license", "max_line_length": 128, "num_lines": 194, "path": "/demo3.1_validate_in_process_scan/detection/construct3D_average.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 20.03.20.\n//\n\n#include <iostream>\n#include <chrono>\n#include <boost/format.hpp> // for formating strings\n\n#include <opencv2/opencv.hpp>\n#include <opencv2/aruco.hpp>\n\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n\ntypedef pcl::PointXYZRGB PointC;\ntypedef pcl::PointXYZ PointG;\ntypedef pcl::PointCloud<PointC>::Ptr PointCloudC;\ntypedef pcl::PointCloud<PointG>::Ptr PointCloudG;\n\nusing namespace std;\nusing namespace cv;\n\nclass CameraConfig {\npublic:\n Mat M;\n Mat distortion;\n Mat MInv;\n double fx, fy, cx, cy;\n\n CameraConfig() {\n M = (Mat_<double>(3, 3)\n << 1382.23, 0., 953.567\n , 0., 1379.46, 532.635\n , 0., 0., 1.);\n distortion = (Mat_<double >(1, 5)\n << 0.0, 0.0, 0.0, 0.0, 0.0);\n MInv = M.inv();\n fx = 1382.23; fy = 1379.46; cx = 953.567; cy = 532.635;\n };\n};\n\nCameraConfig C;\n\nbool detectMarker(Mat img, Mat &tranc2o, Point &center) {\n vector<vector<cv::Point2f>> rejectedCandidates;\n cv::Ptr<cv::aruco::DetectorParameters> parameters = cv::aruco::DetectorParameters::create();\n cv::Ptr<cv::aruco::Dictionary> dictionary = cv::aruco::generateCustomDictionary(10, 6);\n vector<vector<Point2f> > markerCorners;\n vector<int> markerIds;\n\n cv::aruco::detectMarkers(img, dictionary, markerCorners, markerIds, parameters, rejectedCandidates);\n cv::aruco::drawDetectedMarkers(img, markerCorners, markerIds);\n if (markerIds.size() == 0) return false;\n\n vector<cv::Vec3d> rvecs, tvecs;\n cv::aruco::estimatePoseSingleMarkers(markerCorners, 0.04, C.M, C.distortion, rvecs, tvecs);\n for (int i = 0; i < rvecs.size(); ++i) {\n auto rvec = rvecs[i];\n auto tvec = tvecs[i];\n cv::aruco::drawAxis(img, C.M, C.distortion, rvec, tvec, 0.04);\n\n if (markerIds[i] == 1) {\n center = 0.25 * (markerCorners[i][0]+markerCorners[i][1]+markerCorners[i][2]+markerCorners[i][3]);\n Mat r;\n Rodrigues(rvecs[i], r);\n Mat t = (Mat_<double>(3, 1) << tvecs[i][0]*1000, tvecs[i][1]*1000, tvecs[i][2]*1000);\n hconcat(r, t, tranc2o);\n Mat down = (Mat_<double>(1, 4) << 0., 0., 0., 1.);\n vconcat(tranc2o, down, tranc2o);\n return true;\n }\n }\n return false;\n}\n\nbool detectCircleboard(Mat img, Mat &tranc2o, Point &center) {\n vector<Point2f> centers;\n bool pattern_was_found = findCirclesGrid(img, cv::Size(2, 13), centers, CALIB_CB_ASYMMETRIC_GRID);\n if (!pattern_was_found)\n return false;\n cv::drawChessboardCorners(img, cv::Size(2, 13), Mat(centers), pattern_was_found);\n vector<Point3f> objectPoints;\n\n for (int i = 0; i < 13; ++i)\n for (int j = 0; j < 2; ++j)\n objectPoints.push_back(Point3d(i*0.02, j*0.04+(i%2)*0.02, 0.0));\n Mat rvec, tvec;\n Mat matCorneres = Mat(centers).reshape(1);\n Mat matObjectPoints = Mat(objectPoints).reshape(1);\n solvePnP(matObjectPoints, matCorneres, C.M, C.distortion, rvec, tvec);\n\n cv::aruco::drawAxis(img, C.M, C.distortion, rvec, tvec, 0.04);\n center = centers[0];\n Mat r;\n Rodrigues(rvec, r);\n hconcat(r, tvec*1000.0, tranc2o);\n Mat down = (Mat_<double>(1, 4) << 0., 0., 0., 1.);\n vconcat(tranc2o, down, tranc2o);\n return true;\n}\n\npcl::PCDWriter writer;\n\nint main(int argc, char **argv) {\n if (argc != 2) {\n cout << \"please enter number of frames\" << endl;\n return -1;\n }\n int num_frames = stoi(argv[1]);\n Mat matColor = imread(\"../data2D/color.png\");\n // get marker pose\n Mat tran_c2o(Size(4, 4), CV_64F);\n Point center;\n if (detectCircleboard(matColor, tran_c2o, center)) {\n cout << \"marker pose : \"<< endl;\n for (int i = 0; i < 4; ++i)\n for (int j = 0; j < 4; ++j)\n cout << tran_c2o.at<double>(i, j) << \" \";\n cout << endl;\n }\n Mat tran_o2c = tran_c2o.inv();\n\n Mat matsDepth[num_frames];\n for (int frame_index = 0; frame_index < num_frames; ++frame_index)\n matsDepth[frame_index] = imread((boost::format(\"../data2D/depth_%d.png\") % frame_index).str(), CV_LOAD_IMAGE_UNCHANGED);\n\n Mat mask = Mat::zeros(matColor.size(), CV_8UC1);\n Mat mask_blue = Mat::zeros(matColor.size(), CV_8UC3);\n PointCloudG cloud_full(new pcl::PointCloud<PointG>);\n for (int v = 0; v < matColor.rows; ++v) {\n for (int u = 0; u < matColor.cols; ++u) {\n // get the average depth value from all the frames of images\n double dis_average = 0.0;\n bool use_frame = true;\n for (int frame_index = 0; frame_index < num_frames; ++frame_index) {\n double d = (double)matsDepth[frame_index].ptr<uint16_t>(v)[u] / 10.;\n if (d == 0.0) { use_frame = false; break;}\n dis_average += d;\n }\n if (!use_frame) continue;\n dis_average /= num_frames;\n // 3d reconstruction\n if (dis_average == 0.0 || dis_average > 1500.0f) continue;\n Mat p_c = (Mat_<double>(4, 1)\n << ((double)u - C.cx) * dis_average / C.fx, ((double)v - C.cy) * dis_average / C.fy, dis_average, 1.0);\n Mat p_o = tran_o2c * p_c;\n PointG pt(p_o.at<double>(0, 0), p_o.at<double>(1, 0), p_o.at<double>(2, 0));\n// if (pt.x > -9.0 && pt.x < 71.0) // segment 1\n// if (pt.x > 146.0 && pt.x < 226.0) // segment 2\n// if ((pt.x > -9.0 && pt.x < 71.0) || (pt.x > 146.0 && pt.x < 226.0)) // segment 1 and 2\n if (pt.x > 18.474-25.0 && pt.x < 18.474+25.0) // segment tree2\n if (pt.y > 80.0 && pt.y < 120.0)\n if (pt.z > 8.0 && pt.z < 60.0) {\n mask.at<uchar>(v, u) = 255;\n mask_blue.at<Vec3b>(v, u) = Vec3b(255, 0, 0);\n cloud_full->points.push_back(pt);\n }\n// if (pt.x > -45.0) // built\n// if (pt.z > 30.0 && (pt.y > 10.0 && pt.y < 500.0)) {\n// mask.at<uchar>(v, u) = 255;\n// mask_blue.at<Vec3b>(v, u) = Vec3b(255, 0, 0);\n// cloud_full->points.push_back(pt);\n// }\n }\n }\n Mat colorWithMask;\n matColor.copyTo(colorWithMask, mask);\n\n // draw\n vector<vector<Point> > contours;\n findContours(mask, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);\n drawContours(matColor, contours, -1, Scalar(255, 0, 0));\n\n addWeighted(matColor, 1.0, mask_blue, 0.4, 0.0, matColor);\n\n imshow(\"circleboard\", matColor);\n// imshow(\"with mask\", colorWithMask);\n imwrite(\"../data2D/color_detected.png\", matColor);\n waitKey();\n\n// chrono::steady_clock::time_point t_start = chrono::steady_clock::now(); // timing start\n\n// chrono::steady_clock::time_point t_end = chrono::steady_clock::now(); // timing end\n// chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t_end - t_start);\n// cout << \"time cost = \" << time_used.count() << \" seconds. \" << endl;\n\n cloud_full->width = cloud_full->points.size();\n cloud_full->height = 1;\n writer.write(\"../data3D/cloud_passthrough.pcd\", *cloud_full, false);\n cout << \"PointCloud has: \" << cloud_full->points.size() << \" data points.\" << endl;\n\n return 0;\n}" }, { "alpha_fraction": 0.45018965005874634, "alphanum_fraction": 0.5112797021865845, "avg_line_length": 36.94696807861328, "blob_id": "06617dd8bddf772a966026c3c38adf68ceb3576f", "content_id": "14b573b03729d31c5ff2f2c86806fb6667277249", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5009, "license_type": "no_license", "max_line_length": 107, "num_lines": 132, "path": "/workshop/FCN_classification/main.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom matplotlib import pyplot as plt\n\n\ndef generate_data(n, p=0.8):\n # p: percentage of data for training\n x11 = np.random.multivariate_normal([4., 3.], [[4., 0.], [0., 1.]], int(0.5*n))\n x12 = np.random.multivariate_normal([2., -2.], [[1., 0.], [0., 2.]], int(0.25*n))\n x13 = np.random.multivariate_normal([7., -4.], [[1., 0.], [0., 1.]], int(0.25 * n))\n x1 = np.vstack((x11, x12, x13))\n plt.scatter(x1.T[0], x1.T[1], color=\"red\")\n x2 = np.random.multivariate_normal([6., 0.], [[1.5, 0.5], [0.5, 1.5]], n)\n plt.scatter(x2.T[0], x2.T[1], color=\"blue\")\n # combine data\n x = np.vstack((x1, x2))\n y = np.asarray([[1., 0.]] * n + [[0., 1.]] * n)\n # shuffle data\n shuffle_idx = np.arange(0, n*2)\n np.random.shuffle(shuffle_idx)\n x_shuffled = x[shuffle_idx]\n y_shuffled = y[shuffle_idx]\n # split data into training and testing\n _x_train = x_shuffled[0:int(n * p)*2]\n _y_train = y_shuffled[0:int(n * p)*2]\n _x_test = x_shuffled[int(n * p)*2:n*2]\n _y_test = y_shuffled[int(n * p)*2:n*2]\n return _x_train, _y_train, _x_test, _y_test\n\n\ndef sigmoid(_x):\n return 1. / (1. + np.exp(-_x))\n\n\ndef softmax(_x):\n return np.exp(_x) / np.sum(np.exp(_x))\n\n\ndef model(_x, _theta):\n \"\"\"\n model architecture:\n input layer: m0 = 2\n theta[\"w1\"]: (50, 2), theta[\"b1\"]: (50, 1)\n hidden layer: m1 = 50, activation: sigmoid\n theta[\"w2\"]: (5, 50), theta[\"b2\"]: (5, 1)\n hidden layer: m2 = 5, activation: sigmoid\n theta[\"w3\"]: (2, 5), theta[\"b3\"]: (2, 1)\n output layer: m3 = 2, activation: soft-max\n \"\"\"\n x0 = np.array(_x).reshape([2, 1])\n x1 = sigmoid(np.dot(_theta[\"w1\"], x0) + _theta[\"b1\"])\n x2 = sigmoid(np.dot(_theta[\"w2\"], x1) + _theta[\"b2\"])\n x3 = softmax(np.dot(_theta[\"w3\"], x2) + _theta[\"b3\"])\n return x0, x1, x2, x3\n\n\ndef error_rate(_x, _y, _theta, _model):\n error_count = 0\n for i in range(len(_x)):\n if (_model(_x[i], _theta)[3][0][0] > 0.5) and _y[i][0] == 0:\n error_count += 1\n if (_model(_x[i], _theta)[3][0][0] < 0.5) and _y[i][0] == 1:\n error_count += 1\n return error_count / len(_x)\n\n\ndef gradient(_x, _y, _theta, _model):\n grad = {\"w1\": np.zeros([50, 2]), \"b1\": np.zeros([50, 1])\n , \"w2\": np.zeros([5, 50]), \"b2\": np.zeros([5, 1])\n , \"w3\": np.zeros([2, 5]), \"b3\": np.zeros([2, 1])}\n for i in range(len(_x)):\n x0, x1, x2, x3 = model(_x[i].reshape([2, 1]), _theta)\n # back propagation\n _loss_to_x3 = (-_y[i].reshape([2, 1]) / x3).T\n _x3_to_a3 = np.diag(x3.reshape([2, ])) - x3.dot(x3.T)\n _loss_to_a3 = _loss_to_x3.dot(_x3_to_a3)\n grad[\"w3\"] += np.dot(_loss_to_a3.T, x2.T)\n grad[\"b3\"] += _loss_to_a3.T\n _a3_to_x2 = _theta[\"w3\"]\n _x2_to_a2 = np.diag((x2 - x2 * x2).reshape([5, ]))\n _loss_to_a2 = _loss_to_a3.dot(_a3_to_x2).dot(_x2_to_a2)\n grad[\"w2\"] += np.dot(_loss_to_a2.T, x1.T)\n grad[\"b2\"] += _loss_to_a2.T\n _a2_to_x1 = _theta[\"w2\"]\n _x1_to_a1 = np.diag((x1 - x1 * x1).reshape([50, ]))\n _loss_to_a1 = _loss_to_a2.dot(_a2_to_x1).dot(_x1_to_a1)\n grad[\"w1\"] += np.dot(_loss_to_a1.T, x0.T)\n grad[\"b1\"] += _loss_to_a1.T\n return grad\n\n\ndef train(_x, _y, _theta, _model, lr=1e-5, steps=1000):\n global x_test, y_test\n for step in range(steps):\n grad = gradient(_x, _y, _theta, _model)\n _theta[\"w1\"] -= lr * grad[\"w1\"]\n _theta[\"b1\"] -= lr * grad[\"b1\"]\n _theta[\"w2\"] -= lr * grad[\"w2\"]\n _theta[\"b2\"] -= lr * grad[\"b2\"]\n _theta[\"w3\"] -= lr * grad[\"w3\"]\n _theta[\"b3\"] -= lr * grad[\"b3\"]\n # print log\n if step % 100 == 0:\n print(\"step: %d, training error rate: %f, testing error rate: %f\"\n % (step, error_rate(_x, _y, _theta, _model), error_rate(x_test, y_test, _theta, _model)))\n return _theta\n\n\ndef plot_boundary(_theta, _color):\n x_plot = np.arange(-2., 10., .1)\n y_plot = np.arange(-6., 6., .1)\n x_plot, y_plot = np.meshgrid(x_plot, y_plot)\n f = np.zeros(x_plot.shape)\n for i in range(x_plot.shape[0]):\n for j in range(x_plot.shape[1]):\n f[i][j] = model(np.array([[x_plot[i][j]], [y_plot[i][j]]]), _theta)[3][0][0] - 0.5\n plt.contour(x_plot, y_plot, f, 0, colors=_color)\n\n\nif __name__ == \"__main__\":\n x_train, y_train, x_test, y_test = generate_data(100)\n # parameter init according to model\n # weight matrix initialization with uniform[0, 1] fails\n theta = {\"w1\": np.random.uniform(-1., 1., [50, 2]), \"b1\": np.zeros([50, 1])\n , \"w2\": np.random.uniform(-1., 1., [5, 50]), \"b2\": np.zeros([5, 1])\n , \"w3\": np.random.uniform(-1., 1., [2, 5]), \"b3\": np.zeros([2, 1])}\n # plot boundary before training\n plot_boundary(theta, \"orange\")\n # training\n theta_new = train(x_train, y_train, theta, model, lr=1e-4, steps=2000)\n # plot boundary after training\n plot_boundary(theta_new, \"lightblue\")\n plt.show()\n" }, { "alpha_fraction": 0.4950000047683716, "alphanum_fraction": 0.5092856884002686, "avg_line_length": 51.8301887512207, "blob_id": "4e50eb20b04db79a82c6e89afd8924155b5e1a82", "content_id": "cd7f5dede6d487eabdd1ef21ed5b60fa13a6bee2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2800, "license_type": "no_license", "max_line_length": 120, "num_lines": 53, "path": "/demo1_tello_aruco/cv_aruco/aruco_detection_tello.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "import cv2\nimport cv2.aruco as aruco\nimport camera_config_tello\nfrom Pose import *\n\n\nclass Aruco_detector_tello:\n def __init__(self):\n self.dictionary = aruco.custom_dictionary(10, 6)\n self.pose_world = Pose()\n # self.pose_tello = Pose()\n # self.pose_world_to_tello = Pose()\n self.marker_size_world = 0.2\n # self.marker_size_tello = 0.02\n self.image_out = np.zeros((1, 1), dtype=np.float32)\n self.is_detected = False\n\n def detect(self, image):\n self.is_detected = False\n\n # detection\n corners, ids, rejectedImgPoints = aruco.detectMarkers(image, self.dictionary)\n if ids is not None:\n if len(ids) == 1:\n self.is_detected = True\n if self.is_detected:\n for index in range(len(ids)):\n if ids[index][0] == 2:\n rvec, tvec, _ = aruco.estimatePoseSingleMarkers(corners[index], self.marker_size_world,\n camera_config_tello.camera_matrix,\n camera_config_tello.distortion)\n self.pose_world = Pose(cv2.Rodrigues(rvec[0])[0], tvec[0].T)\n # transform\n mat_t = np.dot(Pose.rotational_x(-pi*0.5).T, self.pose_world.R.T)\n self.pose_world.R = np.dot(mat_t, Pose.rotational_x(pi*0.5))\n self.pose_world.t = -np.dot(mat_t, self.pose_world.t)\n # draw axis for the aruco markers\n aruco.drawAxis(image, camera_config_tello.camera_matrix, camera_config_tello.distortion, rvec, tvec,\n self.marker_size_world)\n # if ids[index][0] == 1:\n # rvec, tvec, _ = aruco.estimatePoseSingleMarkers(corners[index], self.marker_size_tello,\n # camera_config_py.camera_matrix,\n # camera_config_py.distortion)\n # self.pose_tello = Pose(cv2.Rodrigues(rvec[0])[0], tvec[0].T)\n # # draw axis for the aruco markers\n # aruco.drawAxis(grey, camera_config_py.camera_matrix, camera_config_py.distortion, rvec, tvec,\n # self.marker_size_tello)\n # self.pose_world_to_tello = Pose(np.dot(self.pose_world.R.T, self.pose_tello.R),\n # np.dot(self.pose_world.R.T, self.pose_tello.t - self.pose_world.t))\n self.image_out = image\n\n def get_pose_world(self):\n return [self.pose_world.x*100., self.pose_world.y*100., self.pose_world.z*100., self.pose_world.yaw]\n" }, { "alpha_fraction": 0.48657718300819397, "alphanum_fraction": 0.5037285685539246, "avg_line_length": 47.51852035522461, "blob_id": "d54fd6afad3e6b4a9901db966dc99809a36d11c5", "content_id": "6ae44e643e0b7821efd0809eb8b384f7d2dcb872", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2682, "license_type": "no_license", "max_line_length": 113, "num_lines": 54, "path": "/demo1_tello_aruco/cv_aruco/aruco_detection_py.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "import cv2\r\nimport cv2.aruco as aruco\r\nimport camera_config_py\r\nfrom Pose import *\r\n\r\n\r\nclass Aruco_detector_py:\r\n def __init__(self):\r\n self.url = \"http://192.168.3.22:8080/?action=stream\"\r\n self.capture = cv2.VideoCapture(self.url)\r\n self.dictionary = aruco.custom_dictionary(10, 6)\r\n self.pose_world = Pose()\r\n self.pose_tello = Pose()\r\n self.pose_world_to_tello = Pose()\r\n self.marker_size_world = 0.04\r\n self.marker_size_tello = 0.02\r\n self.image = np.zeros((1, 1), dtype=np.float32)\r\n self.is_detected = False\r\n\r\n def detect(self):\r\n self.is_detected = False\r\n ret, frame = self.capture.read()\r\n grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n\r\n # detection\r\n corners, ids, rejectedImgPoints = aruco.detectMarkers(grey, self.dictionary)\r\n if ids is not None:\r\n if len(ids) == 2:\r\n self.is_detected = True\r\n if self.is_detected:\r\n for index in range(len(ids)):\r\n if ids[index][0] == 0:\r\n rvec, tvec, _ = aruco.estimatePoseSingleMarkers(corners[index], self.marker_size_world,\r\n camera_config_py.camera_matrix,\r\n camera_config_py.distortion)\r\n self.pose_world = Pose(cv2.Rodrigues(rvec[0])[0], tvec[0].T)\r\n # draw axis for the aruco markers\r\n aruco.drawAxis(grey, camera_config_py.camera_matrix, camera_config_py.distortion, rvec, tvec,\r\n self.marker_size_world)\r\n if ids[index][0] == 1:\r\n rvec, tvec, _ = aruco.estimatePoseSingleMarkers(corners[index], self.marker_size_tello,\r\n camera_config_py.camera_matrix,\r\n camera_config_py.distortion)\r\n self.pose_tello = Pose(cv2.Rodrigues(rvec[0])[0], tvec[0].T)\r\n # draw axis for the aruco markers\r\n aruco.drawAxis(grey, camera_config_py.camera_matrix, camera_config_py.distortion, rvec, tvec,\r\n self.marker_size_tello)\r\n self.pose_world_to_tello = Pose(np.dot(self.pose_world.R.T, self.pose_tello.R),\r\n np.dot(self.pose_world.R.T, self.pose_tello.t - self.pose_world.t))\r\n self.image = grey\r\n\r\n def release(self):\r\n self.capture.release()\r\n cv2.destroyAllWindows()\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.48726850748062134, "alphanum_fraction": 0.5245949029922485, "avg_line_length": 33.21782302856445, "blob_id": "3bb212c7c7e54ff6f03b3bd7423363da78526823", "content_id": "94fbb668fa616cc99156c3da550692d93d7bdc38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3456, "license_type": "no_license", "max_line_length": 133, "num_lines": 101, "path": "/workshop/pytorch/logistic_regression/main.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom matplotlib import pyplot as plt\nimport math\n\n\ndef generate_data(n, p=0.8):\n # p: percentage of data for training\n x1 = np.random.multivariate_normal([4., 3.], [[4., 0.], [0., 1.]], n)\n plt.scatter(x1.T[0], x1.T[1], marker=\"^\", color=\"red\")\n x2 = np.random.multivariate_normal([6., 0.], [[1.5, 0.5], [0.5, 1.5]], n)\n plt.scatter(x2.T[0], x2.T[1], color=\"blue\")\n # combine data\n x = np.vstack((x1, x2))\n y = np.asarray([[1., 0.]] * n + [[0., 1.]] * n)\n # shuffle data\n shuffle_idx = np.arange(0, n*2)\n np.random.shuffle(shuffle_idx)\n x_shuffled = x[shuffle_idx]\n y_shuffled = y[shuffle_idx]\n # split data into training and testing\n _x_train = x_shuffled[0:int(n * p)*2]\n _y_train = y_shuffled[0:int(n * p)*2]\n _x_test = x_shuffled[int(n * p)*2:n*2]\n _y_test = y_shuffled[int(n * p)*2:n*2]\n return _x_train, _y_train, _x_test, _y_test\n\n\n# sigmoid function\ndef sigmoid_func(z):\n return 1. / (1. + np.exp(-z))\n\n\n# logistic regression hypothesis\ndef sigmoid(_x, _theta):\n return sigmoid_func(_theta[0] * _x[0] + _theta[1] * _x[1] + _theta[2])\n\n\n# to calculate y (1 x 2) from x (1 x 2) and theta (1 x 3)\ndef model(_x, _theta):\n _y0 = sigmoid(_x, _theta)\n _y1 = 1 - sigmoid(_x, _theta)\n _y = [_y0, _y1]\n return _y\n\n\ndef cost(_x, _y, _theta, _model=model):\n _loss = 0.0\n for i in range(len(_x)):\n _y_label = _y[i]\n _y_predict = _model(_x[i], _theta)\n _loss += -(_y_label[0] * math.log(_y_predict[0]) + _y_label[1] * math.log(_y_predict[1]))\n return (1 / len(_x)) * _loss\n\n\ndef error_rate(_x, _y, _theta, _model=model):\n _error_count = 0\n for i in range(len(_x)):\n _y_label = _y[i]\n _y_predict = _model(_x[i], _theta)\n if (_y_predict[0] > 0.5) and (_y_label[0] == 0):\n _error_count += 1\n if (_y_predict[1] > 0.5) and(_y_label[1] == 0):\n _error_count += 1\n _error_rate = _error_count / len(_x)\n return _error_rate\n\n\ndef gradient(_x, _y, _theta):\n _g = np.array([0., 0., 0.])\n for i in range(len(_x)):\n _g[0] += (-(1. - sigmoid(_x[i], _theta)) * _y[i][0] + sigmoid(_x[i], _theta) * _y[i][1]) * _x[i][0]\n _g[1] += (-(1. - sigmoid(_x[i], _theta)) * _y[i][0] + sigmoid(_x[i], _theta) * _y[i][1]) * _x[i][1]\n _g[2] += (-(1. - sigmoid(_x[i], _theta)) * _y[i][0] + sigmoid(_x[i], _theta) * _y[i][1]) * 1\n return _g\n\n\ndef train(_x, _y, _theta, _lr=1e-5, _steps=1500):\n global x_test, y_test\n for step in range(_steps):\n _theta -= _lr * gradient(_x, _y, _theta)\n # print log\n if step % 100 == 0:\n print(\"step %d, theta [%f, %f, %f]\" % (step, _theta[0], _theta[1], _theta[2]))\n print(\"cost\", cost(_x, _y, _theta))\n print(\"training error rate %f, test error rate %f \\n\" % (error_rate(_x, _y, _theta), error_rate(x_test, y_test, _theta)))\n return _theta\n\n\nif __name__ == \"__main__\":\n x_train, y_train, x_test, y_test = generate_data(100)\n theta_original = [2., -1., 0.]\n theta_new = train(x_train, y_train, theta_original)\n \n print(\"original cost\", cost(x_train, y_train, theta_original, _model=model))\n print(\"new cost\", cost(x_train, y_train, theta_new, _model=model))\n print(\"new theta\", theta_new)\n\n x_boundary = [0., 10.]\n y_boundary = [-theta_new[2]/theta_new[1], (-theta_new[2]-10*theta_new[0])/theta_new[1]]\n plt.plot(x_boundary, y_boundary)\n plt.show()\n" }, { "alpha_fraction": 0.502119243144989, "alphanum_fraction": 0.5560892820358276, "avg_line_length": 32.39622497558594, "blob_id": "f05b5c2aa67bb0d574b21d4c7d0bcfd9e66a1be4", "content_id": "0bd38cc81b047b578492a690c1554ec34c1bea4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3539, "license_type": "no_license", "max_line_length": 110, "num_lines": 106, "path": "/demo2.2_detect_cylinder/hand_eye_calib/detect_marker.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 15.02.20.\n//\n\n#include <iostream>\n#include <vector>\n\n#include <opencv2/opencv.hpp>\n#include <opencv2/aruco.hpp>\n#include <librealsense2/rs.hpp>\n\nusing namespace std;\nusing namespace cv;\n\nclass CameraConfig {\npublic:\n Mat M;\n Mat distortion;\n Mat MInv;\n double fx, fy, cx, cy;\n\n CameraConfig() {\n M = (Mat_<double>(3, 3)\n << 1382.23, 0., 953.567\n , 0., 1379.46, 532.635\n , 0., 0., 1.);\n distortion = (Mat_<double>(1, 5)\n << 0.0, 0.0, 0.0, 0.0, 0.0);\n MInv = M.inv();\n fx = 1382.23; fy = 1379.46; cx = 953.567; cy = 532.635;\n };\n};\n\nCameraConfig C;\n\nbool detectChessboard(Mat img, Mat &tranc2o, Point &center) {\n vector<vector<cv::Point2f>> rejectedCandidates;\n cv::Ptr<cv::aruco::DetectorParameters> parameters = cv::aruco::DetectorParameters::create();\n cv::Ptr<cv::aruco::Dictionary> dictionary = cv::aruco::generateCustomDictionary(10, 6);\n vector<vector<Point2f> > markerCorners;\n vector<int> markerIds;\n\n cv::aruco::detectMarkers(img, dictionary, markerCorners, markerIds, parameters, rejectedCandidates);\n cv::aruco::drawDetectedMarkers(img, markerCorners, markerIds);\n if (markerIds.size() == 0) return false;\n\n vector<cv::Vec3d> rvecs, tvecs;\n cv::aruco::estimatePoseSingleMarkers(markerCorners, 0.28, C.M, C.distortion, rvecs, tvecs);\n for (int i = 0; i < rvecs.size(); ++i) {\n auto rvec = rvecs[i];\n auto tvec = tvecs[i];\n cv::aruco::drawAxis(img, C.M, C.distortion, rvec, tvec, 0.28);\n\n if (markerIds[i] == 0) {\n center = 0.25 * (markerCorners[i][0]+markerCorners[i][1]+markerCorners[i][2]+markerCorners[i][3]);\n Mat r;\n Rodrigues(rvecs[i], r);\n Mat t = (Mat_<double>(3, 1) << tvecs[i][0]*1000, tvecs[i][1]*1000, tvecs[i][2]*1000);\n hconcat(r, t, tranc2o);\n Mat down = (Mat_<double>(1, 4) << 0., 0., 0., 1.);\n vconcat(tranc2o, down, tranc2o);\n return true;\n }\n }\n return false;\n}\n\nint main(int argc, char **argv) {\n rs2::pipeline pipe;\n rs2::config cfg;\n cfg.enable_stream(RS2_STREAM_DEPTH, 1280, 720, RS2_FORMAT_Z16, 30);\n cfg.enable_stream(RS2_STREAM_COLOR, 1920, 1080, RS2_FORMAT_BGR8, 30);\n pipe.start(cfg);\n\n rs2::align align_to_color(RS2_STREAM_COLOR);\n\n int num_parameters_saved = 0;\n cout << \"press 's' to print marker pose.\" << endl;\n // start\n while (waitKey(1) != 'q') {\n rs2::frameset frameset = pipe.wait_for_frames();\n frameset = align_to_color.process(frameset);\n\n auto depth = frameset.get_depth_frame();\n auto color = frameset.get_color_frame();\n\n Mat matColor(Size(1920, 1080), CV_8UC3, (void*)color.get_data(), Mat::AUTO_STEP);\n Mat matDepth(Size(1920, 1080), CV_16U, (void*)depth.get_data(), Mat::AUTO_STEP);\n\n Mat tranc2o;\n Point center;\n if (detectChessboard(matColor, tranc2o, center))\n if (waitKey(1) == 's') {\n cout << \"depth: \" << matDepth.at<int16_t>(center) << endl;\n cout << \"parameters: \" << num_parameters_saved << endl;\n// cout << tranc2o << endl;\n for (int i = 0; i < 4; ++i)\n for (int j = 0; j < 4; ++j)\n cout << tranc2o.at<double>(i, j) << \" \";\n cout << endl << endl;\n num_parameters_saved += 1;\n }\n imshow(\"aruco\", matColor);\n }\n return 0;\n}" }, { "alpha_fraction": 0.7730496525764465, "alphanum_fraction": 0.7943262457847595, "avg_line_length": 67.5, "blob_id": "86b7bbd5fdc617e6d6752f6aa3bf1c7bda426025", "content_id": "59f055f8256f0eafe73b53001dc00d82d8cb31e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 141, "license_type": "no_license", "max_line_length": 111, "num_lines": 2, "path": "/demo2.1_detect_polygon/README.md", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "# demo2.1_detect_polygon\r\nDetecting polygonal plates in with controlled background. A pair of cameras are used for the 3d-reconstruction.\r\n\r\n" }, { "alpha_fraction": 0.5062093138694763, "alphanum_fraction": 0.5454366207122803, "avg_line_length": 31.729032516479492, "blob_id": "d0f01397cea48861c9df8d3cd73a4908c1aa0155", "content_id": "99edd107782db24986b89758d1b5bb5535ad4d35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5073, "license_type": "no_license", "max_line_length": 111, "num_lines": 155, "path": "/demo5.1_final/localization_and_mapping/code/marker_opt.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport numpy as np\nimport libs.lib_rs as rs\nimport libs.lib_frame as f\nimport cv2\nimport yaml\nfrom scipy.sparse import lil_matrix\n\n# ------------------------\n# solve: p = C * T(C->W) * T(W->K) * P(K)\n# parameters to optimize:\n# T(C->W) (6*n)\n# T(W->K) (6*m)\n# ------------------------\n\nwith open(\"config/config_marker.yml\", 'r') as file:\n conf = yaml.safe_load(file.read())\n\nn = conf[\"num_photos\"] # number of photos\nm = conf[\"num_markers\"] # number of markers\npath_img = conf[\"path_img\"] + \"color_%d.png\"\npath_result = conf[\"path_result\"]\nview_corner = conf[\"view_corner\"]\ncorner_refinement = conf[\"corner_refinement\"]\nif conf[\"reorder\"]:\n indices = conf[\"reorder_indices_list\"]\nelse:\n indices = range(m)\n\nd415 = rs.D415()\nsize = d415.marker_size\n\n\n# ---------------------------------\n# cost function: x: [c2w_rvec\n# c2w_tvec\n# ...(n times)\n# w2k_rvec\n# w2k_tvec\n# ...(m-1 times)] # first one is identity\n# ---------------------------------\n\n\ndef residual(x):\n global corners_all, ids_all, count_marker\n c2w = []\n for i in range(n):\n c2w.append(f.t_4_4__rvec(x[i * 6: i * 6 + 3], x[i * 6 + 3: i * 6 + 6]))\n w2k = []\n w2k.append(np.eye(4))\n for i in range(m-1):\n w2k.append(f.t_4_4__rvec(x[6 * n + i * 6: 6 * n + i * 6 + 3], x[6 * n + i * 6 + 3: 6 * n + i * 6 + 6]))\n # residual\n res = np.zeros([count_marker*4*2, ])\n marker_index = 0\n # res = []\n # i-th photo j-th marker k-th corner\n for i in range(len(corners_all)):\n corners, ids = corners_all[i], ids_all[i]\n for j in range(len(corners)):\n # if ids[j, 0] != i and ids[j, 0] != i+1:\n # continue\n for k in range(4):\n corner = d415.C_ext.dot(c2w[i]).dot(w2k[indices.index(ids[j, 0])]).dot(rs.P(size, k))\n res[marker_index*8+k*2+0] = (corner[0][0] / corner[2][0] - corners[j][0, k][0])\n res[marker_index*8+k*2+1] = (corner[1][0] / corner[2][0] - corners[j][0, k][1])\n marker_index += 1\n return res\n\n\nif view_corner:\n rs.window_setting(\"color\")\n\n# ------------------------\n# load data\n# ------------------------\n\ncorners_all, ids_all = [], []\ncount_marker = 0\nfor i in range(n):\n color = cv2.imread(path_img % i)\n if color is None:\n continue\n param = cv2.aruco.DetectorParameters_create()\n # param.cornerRefinementMethod = cv2.aruco.CORNER_REFINE_SUBPIX\n param.cornerRefinementMethod = corner_refinement\n corners, ids, _ = cv2.aruco.detectMarkers(color, rs.aruco_dict(), parameters=param)\n if view_corner:\n cv2.aruco.drawDetectedMarkers(color, corners, ids)\n cv2.imshow(\"color\", color)\n cv2.waitKey()\n corners_all.append(corners)\n ids_all.append(ids)\n count_marker += len(ids)\n\nn = len(ids_all)\nprint(\"in %d images, totally %d markers\" % (n, count_marker))\n\nc2w_x0 = np.load(path_result + \"c2w_init.npy\").flatten()\nw2k_x0 = np.load(path_result + \"w2k_init.npy\").flatten()\n# w2k_4_4 = f.t_4_4s__rvecs6(w2k)\n# c2w = []\n# for i in range(len(ids_all)):\n# ids = ids_all[i]\n# corners = corners_all[i]\n# rvec, tvec, _ = cv2.aruco.estimatePoseSingleMarkers(corners[0], 0.2, d415.C_r, d415.coeffs_r)\n# c2k = f.t_4_4__rvec(rvec.reshape([3, ]), tvec.reshape([3, ]))\n# c2w.append(f.rvec6__t_4_4(c2k.dot(f.inv(w2k_4_4[f.id_new(ids[0, 0])]))))\n# c2w = np.array(c2w)\n# c2w = c2w.flatten()\n# w2k = w2k[1:].flatten()\n\nx0 = np.hstack((c2w_x0, w2k_x0))\n\nA = lil_matrix((count_marker * 8, n * 6 + (m - 1) * 6), dtype=int)\ncount_i_sum = 0\nfor i in range(n):\n count_i_th_photo = len(corners_all[i])\n for j in range(6):\n A[np.arange(count_i_sum*8, count_i_sum*8+count_i_th_photo*8), i*6+j] = 1\n for ids_i_th in ids_all[i][:, 0]:\n # index_i_th = indices.index(ids_i_th) - 1\n try:\n index_i_th = indices.index(ids_i_th) - 1\n except Exception:\n raise Exception(\"mis-detect in photo: %d\" % i)\n if index_i_th != -1:\n for j in range(6):\n A[np.arange(count_i_sum*8, count_i_sum*8+count_i_th_photo*8), 6 * n + index_i_th * 6 + j] = 1\n count_i_sum += count_i_th_photo\n\n\nls = f.least_squares(residual, x0, jac_sparsity=A, verbose=2, x_scale='jac', ftol=1e-6)\n# ls = f.least_squares(residual, x0, verbose=2, x_scale='jac', ftol=1e-4, method='trf')\n\nprint(ls.x[6 * n: 6 * n + 6])\nprint(ls.x[6 * n + 6: 6 * n + 12])\n\nprint(\"------------------\")\nprint(\"final cost: %f\" % ls.cost)\nprint(\"final optimality: %f\" % ls.optimality)\n\nfinal_w2k = []\nfinal_w2k.append(np.eye(4).flatten())\nfor i in range(m-1):\n final_w2k.append(f.t_4_4__rvec6(ls.x[6*(n + i): 6 * (n + i + 1)]).flatten())\nnp.savetxt(path_result + \"w2k.txt\", final_w2k, fmt=\"%f\")\n\nfor i in range(len(final_w2k)):\n np.savetxt(path_result + (\"w2k_%d.txt\" % i), final_w2k[i], fmt=\"%f\")\n\nfinal_c2w = []\nfor i in range(n):\n final_c2w.append(ls.x[6*i: 6 * (i + 1)].flatten())\nnp.savetxt(path_result + \"c2w.txt\", final_c2w, fmt=\"%f\")\n" }, { "alpha_fraction": 0.5667539238929749, "alphanum_fraction": 0.5899401903152466, "avg_line_length": 35.380950927734375, "blob_id": "aea6886ffa3c740c2114f3919a9e0b3ce7e52df2", "content_id": "349ffaab06660b422db3ba399ca6ad6b886b2b3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5348, "license_type": "no_license", "max_line_length": 137, "num_lines": 147, "path": "/demo4.1_tracking/web/catkin_ws/src/web/src/f_loc.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "#include <opencv2/aruco.hpp>\n\n#include \"lib.h\"\n\n#define F_STATE 2\n#define PATH_MARKERS (ros::package::getPath(\"web\") + \"/cfg/w2k.txt\")\n#define PATH_MARKERS_PARAM (ros::package::getPath(\"web\") + \"/cfg/config_marker.yml\")\n\nMat imgCallback;\nbool RECEIVED = false;\n\nbool detectMarker(Mat img, bool isRelocate, double size, vector<int> indices, vector<Eigen::Matrix4d> markerPoses, vector<double> &c2w) {\n vector<vector<cv::Point2f>> rejectedCandidates;\n cv::Ptr<cv::aruco::DetectorParameters> parameters = cv::aruco::DetectorParameters::create();\n parameters->cornerRefinementMethod = cv::aruco::CORNER_REFINE_APRILTAG;\n cv::Ptr<cv::aruco::Dictionary> dictionary = cv::aruco::getPredefinedDictionary(cv::aruco::DICT_4X4_250);\n vector<vector<Point2f> > markerCorners;\n vector<int> markerIds;\n\n cv::aruco::detectMarkers(img, dictionary, markerCorners, markerIds, parameters, rejectedCandidates);\n cv::aruco::drawDetectedMarkers(img, markerCorners, markerIds);\n int N = markerIds.size();\n if (N == 0) return false;\n\n std::vector<cv::Vec3d> rvecs, tvecs;\n cv::aruco::estimatePoseSingleMarkers(markerCorners, size, C.M, C.distortion, rvecs, tvecs);\n // draw axis for each marker\n for(int i=0; i<markerIds.size(); i++)\n cv::aruco::drawAxis(img, C.M, C.distortion, rvecs[i], tvecs[i], size);\n if (!isRelocate) {\n c2w = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0};\n return true;\n }\n \n // log\n ROS_INFO(\"%d markers found, start relocating\", N);\n for (int i = 0; i < N; ++i) {\n ROS_INFO(\" - marker %d: [%.1f, %.1f] [%.1f, %.1f] [%.1f, %.1f] [%.1f, %.1f]\", markerIds[i], \n markerCorners[i][0].x, markerCorners[i][0].y, markerCorners[i][1].x, markerCorners[i][1].y,\n markerCorners[i][2].x, markerCorners[i][2].y, markerCorners[i][3].x, markerCorners[i][3].y);\n }\n\n // prepare for PnP\n vector<Point3f> p_3d;\n vector<Point2f> p_2d;\n for (int i = 0; i < markerIds.size(); ++i) {\n int index = findIndex(indices, markerIds[i]);\n if (index == -1) continue;\n for (int k = 0; k < 4; k++) {\n Eigen::Vector4d pt= markerPoses[index] * getCorner(k, size);\n p_3d.push_back(Point3d(pt[0], pt[1], pt[2]));\n p_2d.push_back(markerCorners[i][k]);\n }\n }\n \n Mat rvec, tvec;\n Mat mat_2d = Mat(p_2d).reshape(1);\n Mat mat_3d = Mat(p_3d).reshape(1);\n solvePnP(mat_3d, mat_2d, C.M, C.distortion, rvec, tvec);\n // vector<double> c2w;\n for (int i = 0; i < 3; i++)\n c2w.push_back(rvec.at<double>(i));\n for (int i = 0; i < 3; i++)\n c2w.push_back(tvec.at<double>(i));\n \n ROS_INFO(\"result rvec: [ %.3f %.3f %.3f ]\", c2w[0], c2w[1], c2w[2]);\n ROS_INFO(\"result tvec: [ %.3f %.3f %.3f ]\", c2w[3], c2w[4], c2w[5]);\n return true;\n}\n\nstatic void ImageCallback(const sensor_msgs::ImageConstPtr &msg) {\n try {\n cv_bridge::CvImagePtr cv_ptr = cv_bridge::toCvCopy(msg,sensor_msgs::image_encodings::BGR8);\n imgCallback = cv_ptr->image;\n RECEIVED = true;\n } catch (cv_bridge::Exception& e) { }\n}\n\nint main(int argc, char **argv) {\n // // window setting\n // namedWindow(\"imgCallback\", 0);\n // cvResizeWindow(\"imgCallback\", 960*2, 540*2);\n\n // ros init\n ros::init(argc, argv, \"f_loc\");\n ros::NodeHandle nh;\n\n // parameters from yml\n YAML::Node yNode = YAML::LoadFile(PATH_MARKERS_PARAM);\n int numMarkers = yNode[\"num_markers\"].as<int>();\n double markerSize = yNode[\"marker_size\"].as<double>();\n vector<int> reorderIndices = yNode[\"reorder_indices_list\"].as< vector<int> >();\n \n // read file of markers\n double **data = readData(PATH_MARKERS, numMarkers, 16);\n vector<Eigen::Matrix4d> w2k;\n for (int i = 0; i < 7; ++i) {\n w2k.emplace_back(Eigen::Map<Eigen::Matrix4d>(data[i]).transpose());\n }\n \n // sub\n ros::Subscriber image_sub;\n string image_topic = \"rs_color\";\n image_sub = nh.subscribe(image_topic, 10, ImageCallback);\n \n // pub\n image_transport::ImageTransport it(nh);\n image_transport::Publisher pub = it.advertise(\"img\", 1);\n\n ros::Rate loop_rate(10);\n while (ros::ok()) {\n bool keep_relocate;\n ros::param::get(\"keep_relocate\", keep_relocate);\n\n // check state\n if (!checkState(F_STATE) && !keep_relocate) { loop_rate.sleep(); continue; }\n // check if image received\n if (!RECEIVED) { ros::spinOnce(); loop_rate.sleep(); continue; }\n // INFO received\n ROS_INFO(\"cv_ptr: %d * %d \", imgCallback.cols, imgCallback.rows);\n\n // check if needs to relocate\n bool isRelocate;\n ros::param::get(\"relocate\", isRelocate);\n if (keep_relocate) isRelocate = true;\n\n // detect marker\n vector<double> c2w;\n detectMarker(imgCallback, isRelocate, markerSize, reorderIndices, w2k, c2w);\n if (isRelocate) {\n nh.setParam(\"c2w\", c2w);\n nh.setParam(\"relocate\", false);\n }\n // imshow(\"imgCallback\", imgCallback);\n // waitKey(1);\n\n // pub\n if (!keep_relocate) {\n sensor_msgs::ImagePtr msg = cv_bridge::CvImage(std_msgs::Header(), \"bgr8\", imgCallback).toImageMsg();\n pub.publish(msg);\n }\n \n ros::spinOnce();\n // loop_rate.sleep();\n }\n return 0;\n}\n" }, { "alpha_fraction": 0.593012273311615, "alphanum_fraction": 0.6194522976875305, "avg_line_length": 26.153846740722656, "blob_id": "518136d87f3bc9820ad1292e8247300bcb627cb3", "content_id": "de01eecdc419800e51212ccd794d6a8c50dc27c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1059, "license_type": "no_license", "max_line_length": 63, "num_lines": 39, "path": "/demo5.1_final/localization_and_mapping/code/take_frame_marker.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport cv2\nimport yaml\nimport libs.lib_rs as rs\n\nrs.window_setting(\"color\")\nd415 = rs.D415()\n\nwith open(\"config/config_marker.yml\", 'r') as file:\n conf = yaml.safe_load(file.read())\nsave_init_index = conf[\"save_init_index\"] # number of markers\nsave_depth = conf[\"save_depth\"]\n\nframes_saved = save_init_index\npath = \"../data_2D/color_%d.png\"\npath_depth = \"../data_2D/depth_%d.png\"\npath_drawn = \"../data_2D/color_drawn_%d.png\"\nwhile True:\n # key configs\n key = cv2.waitKey(50)\n if key == ord('q'):\n break\n isToSave = False\n if key == ord('s'):\n isToSave = True\n # fetch data\n corners, ids, color, color_drawn = d415.detect_aruco()\n _, depth = d415.get_frames()\n cv2.imshow(\"color\", color_drawn)\n # save data\n if isToSave:\n cv2.imwrite(path % frames_saved, color)\n cv2.imwrite(path_depth % frames_saved, depth)\n cv2.imwrite(path_drawn % frames_saved, color_drawn)\n # infos\n print(\"frame%d saved\" % frames_saved)\n frames_saved += 1\n\nd415.close()\n" }, { "alpha_fraction": 0.5935524702072144, "alphanum_fraction": 0.6068267822265625, "avg_line_length": 28.314815521240234, "blob_id": "be577ce74f0c8b15f9f27a85d687e7ae888293b4", "content_id": "37bdcf1a1b8ced528eec18927a7c6765525d2883", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1582, "license_type": "no_license", "max_line_length": 85, "num_lines": 54, "path": "/demo2.2_detect_cylinder/detection_rgbd/src/mergeCloud.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 01.02.20.\n//\n\n#include <string>\n#include <boost/format.hpp>\n\n#include \"pointCloud.hpp\"\n\n#include <pcl/point_types.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/filters/statistical_outlier_removal.h>\n#include <pcl/registration/icp.h>\n\npcl::PCDReader reader;\npcl::PCDWriter writer;\npcl::StatisticalOutlierRemoval<pcl::PointXYZ> sor;\n\nconst int COUNT = 5;\n\nint main() {\n PointCloudG clouds[COUNT];\n for (int i = 0; i < COUNT; ++i) {\n PointCloudG cloud (new pcl::PointCloud<PointG>);\n boost::format fmt( \"../../data/point_cloud/cloud1_%d%s.pcd\" );\n reader.read ((fmt%i%\"B\").str(), *cloud);\n // remove outliers\n sor.setInputCloud (cloud);\n sor.setMeanK (50);\n sor.setStddevMulThresh (0.8);\n sor.filter (*cloud);\n clouds[i] = cloud;\n }\n\n PointCloudG cloud_aligned = clouds[0];\n pcl::IterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> icp;\n cout << \"cloud 0: \" << clouds[0]->points.size() << endl;\n for (int i = 1; i < COUNT; ++i) {\n cout << \"cloud \" << i << \": \" << clouds[i]->points.size() << endl;\n icp.setInputSource(clouds[i]);\n icp.setInputTarget(cloud_aligned);\n pcl::PointCloud<pcl::PointXYZ> final;\n icp.align(final);\n *cloud_aligned += final;\n }\n\n sor.setInputCloud (cloud_aligned);\n sor.setMeanK (50);\n sor.setStddevMulThresh (1.0);\n sor.filter (*cloud_aligned);\n cout << \"final: \" << cloud_aligned->points.size() << endl;\n\n writer.write (\"../../data/point_cloud/cloud_aligned.pcd\", *cloud_aligned, false);\n}" }, { "alpha_fraction": 0.5003882050514221, "alphanum_fraction": 0.5403726696968079, "avg_line_length": 34.28767013549805, "blob_id": "6d5d23d80f6e10d801b5382285c2e586f26b77f6", "content_id": "6efb24a10f16fcaac79f344549c4b778b30617df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2576, "license_type": "no_license", "max_line_length": 101, "num_lines": 73, "path": "/workshop/logistic_regression/logistic_regression_torch.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "import torch\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\ndef generate_data(n, p=0.8):\n # p: percentage of data for training\n x1 = np.random.multivariate_normal([4., 3.], [[4., 0.], [0., 1.]], n)\n plt.scatter(x1.T[0], x1.T[1], color=\"red\")\n x2 = np.random.multivariate_normal([6., 0.], [[1.5, 0.5], [0.5, 1.5]], n)\n plt.scatter(x2.T[0], x2.T[1], color=\"blue\")\n # combine data\n x = np.vstack((x1, x2))\n y = np.asarray([[1., 0.]] * n + [[0., 1.]] * n)\n # shuffle data\n shuffle_idx = np.arange(0, n*2)\n np.random.shuffle(shuffle_idx)\n x_shuffled = x[shuffle_idx]\n y_shuffled = y[shuffle_idx]\n # split data into training and testing\n _x_train = x_shuffled[0:int(n * p)*2]\n _y_train = y_shuffled[0:int(n * p)*2]\n _x_test = x_shuffled[int(n * p)*2:n*2]\n _y_test = y_shuffled[int(n * p)*2:n*2]\n return _x_train, _y_train, _x_test, _y_test\n\n\ndef model(_x, _theta):\n return torch.tensor(1.) / (1. + torch.exp(-_x[0] * _theta[0] - _x[1] * _theta[1] - _theta[2]))\n\n\ndef loss(_y, _y_pred):\n return -_y[0] * torch.log(_y_pred) - _y[1] * torch.log(1.-_y_pred)\n\n\ndef error_rate(_x, _y, _theta, _model):\n error_count = 0\n for i in range(len(_x)):\n if (_model(_x[i], _theta).data > 0.5) and _y[i][0] == 0:\n error_count += 1\n if (_model(_x[i], _theta).data < 0.5) and _y[i][0] == 1:\n error_count += 1\n return error_count / len(_x)\n\n\ndef train(_x, _y, _theta, _model, lr=1e-5, steps=1000):\n global x_test, y_test\n for step in range(steps):\n cost = torch.tensor(0.)\n for index in range(_x.shape[0]):\n cost += loss(_y[index], model(_x[index], _theta))\n cost /= _x.shape[0]\n cost.backward()\n _theta.detach().sub_(lr * _theta.grad.data)\n _theta.grad.detach().zero_()\n # print log\n if step % 100 == 0:\n print(\"step: %d, theta: %f %f %f\" % (step, _theta[0], _theta[1], _theta[2]))\n print(\"training error rate: %f, testing error rate: %f\"\n % (error_rate(_x, _y, _theta, _model), error_rate(x_test, y_test, _theta, _model)))\n return _theta\n\n\nif __name__ == \"__main__\":\n x_train, y_train, x_test, y_test = generate_data(100)\n theta = torch.tensor([1., 1., 0.], requires_grad=True)\n # training\n theta_new = train(x_train, y_train, theta, model, lr=1e-3, steps=1000)\n # plot boundary\n x_boundary = [0., 10.]\n y_boundary = [-theta_new[2]/theta_new[1], (-theta_new[2]-10*theta_new[0])/theta_new[1]]\n plt.plot(x_boundary, y_boundary)\n plt.show()\n" }, { "alpha_fraction": 0.5322297215461731, "alphanum_fraction": 0.5432656407356262, "avg_line_length": 29.64285659790039, "blob_id": "48ec3fcc987175925f8f601daa916d71a29686c0", "content_id": "980f2bb298d32cc445e30a8725f27636bce2da06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3987, "license_type": "no_license", "max_line_length": 87, "num_lines": 126, "path": "/demo1_tello_aruco/cv_aruco/tello_flight.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "import tellopy\r\nfrom time import sleep\r\nfrom tello_controller import *\r\nimport av\r\nimport traceback\r\nimport numpy\r\nimport time\r\nimport sys\r\nimport threading\r\nfrom aruco_detection_tello import *\r\nfrom trajectory import *\r\n\r\n\r\ndef handler(event, sender, data, **args):\r\n drone = sender\r\n if event is drone.EVENT_FLIGHT_DATA:\r\n print(data)\r\n\r\n\r\ndef get_image(_drone):\r\n container = None\r\n global image\r\n # connect to video stream\r\n retry = 3\r\n while container is None and 0 < retry:\r\n retry -= 1\r\n try:\r\n container = av.open(_drone.get_video_stream())\r\n except av.AVError as ave:\r\n print(ave)\r\n print('retry...')\r\n _drone.start_video()\r\n frame_skip = 300\r\n try:\r\n while True:\r\n for frame in container.decode(video=0):\r\n if 0 < frame_skip:\r\n frame_skip = frame_skip - 1\r\n continue\r\n start_time = time.time()\r\n image = cv2.cvtColor(numpy.array(frame.to_image()), cv2.COLOR_RGB2BGR)\r\n if frame.time_base < 1.0 / 60:\r\n time_base = 1.0 / 60\r\n else:\r\n time_base = frame.time_base\r\n frame_skip = int((time.time() - start_time) / time_base)\r\n except Exception as ex:\r\n exc_type, exc_value, exc_traceback = sys.exc_info()\r\n traceback.print_exception(exc_type, exc_value, exc_traceback)\r\n print(ex)\r\n finally:\r\n _drone.quit()\r\n\r\n\r\ndef get_pose(solver):\r\n while True:\r\n if image is None:\r\n cv2.waitKey(1)\r\n else:\r\n solver.detect(image)\r\n if solver.is_detected:\r\n cv2.waitKey(1)\r\n cv2.imshow(\"img\", solver.image_out)\r\n return solver.get_pose_world()\r\n\r\n\r\ndef main(controller, solver):\r\n try:\r\n sleep(15)\r\n drone.takeoff()\r\n sleep(3)\r\n drone.down(0)\r\n sleep(3)\r\n # update drone pose from cv_begin\r\n # drone_pose = [0, 0, 0, 0]\r\n # update drone pose from cv_end\r\n # ref_pose should be updated from file\r\n ref_pose = trajectory_planned\r\n # use the command from tello_controller\r\n for i in range(len(ref_pose)):\r\n controller.update_ref_pose(ref_pose=ref_pose[i])\r\n # update drone pose from cv_begin\r\n drone_pose = get_pose(solver)\r\n cv2.imshow(\"img\", solver.image_out)\r\n # update drone pose from cv_end\r\n # pass the updated pose data to tello_controller\r\n controller.update_drone_pose(drone_pose=drone_pose)\r\n controller.update_error()\r\n while controller.compare_error():\r\n controller.update_axis_speed()\r\n controller.send_flight_command()\r\n # update drone pose from cv_begin\r\n drone_pose = get_pose(solver)\r\n # update drone pose from cv_end\r\n print(\"changed drone_pose\", drone_pose)\r\n # pass the updated pose data to tello_controller and update error value\r\n controller.update_drone_pose(drone_pose=drone_pose)\r\n controller.update_error()\r\n # stop the command from tello controller\r\n sleep(dt)\r\n drone.land()\r\n sleep(5)\r\n except Exception as ex:\r\n print(ex)\r\n finally:\r\n drone.quit()\r\n\r\n\r\nif __name__ == '__main__':\r\n drone = tellopy.Tello()\r\n controller = Tello_controller(drone=drone)\r\n # wake up tello / take off and wait\r\n # drone.subscribe(drone.EVENT_FLIGHT_DATA, handler)\r\n drone.connect()\r\n drone.wait_for_connection(60.0)\r\n dt = 0.001\r\n image = None\r\n\r\n t_img = threading.Thread(target=get_image, args=(drone,))\r\n t_img.start()\r\n\r\n solver = Aruco_detector_tello()\r\n # while True:\r\n # print(get_pose(solver))\r\n # cv2.waitKey()\r\n main(controller, solver)\r\n" }, { "alpha_fraction": 0.5262515544891357, "alphanum_fraction": 0.555759072303772, "avg_line_length": 35.94736862182617, "blob_id": "ae935d12e6885e44c0b6065a5182476790378003", "content_id": "29796d38384aa273ed3b5d54204ddc813ab2d05b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4914, "license_type": "no_license", "max_line_length": 114, "num_lines": 133, "path": "/demo5.1_final/localization_and_mapping/code/libs/lib_rs.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "import pyrealsense2 as rs\nimport libs.lib_frame as f\nimport cv2\nimport numpy as np\nimport yaml\n\n\nclass D415:\n def __init__(self, config_path=\"config/config.yml\"):\n self.is_connected = True\n try:\n self.pipeline = rs.pipeline()\n self.align = rs.align(rs.stream.color)\n config = rs.config()\n config.enable_stream(rs.stream.depth, 1280, 720, rs.format.z16, 30)\n config.enable_stream(rs.stream.color, 1920, 1080, rs.format.bgr8, 30)\n cfg = self.pipeline.start(config)\n except:\n print(\"camera not connected.\")\n self.is_connected = False\n # set intrinsics\n with open(config_path, 'r') as file:\n conf = yaml.safe_load(file.read())\n # profile = cfg.get_stream(rs.stream.color)\n # intrinsics = profile.as_video_stream_profile().get_intrinsics()\n self.width = conf[\"width\"]\n self.height = conf[\"height\"]\n self.ppx = conf[\"ppx\"]\n self.ppy = conf[\"ppy\"]\n self.fx = conf[\"fx\"]\n self.fy = conf[\"fy\"]\n self.coeffs = np.asarray(conf[\"coeffs\"], dtype=np.float32).reshape([5, 1])\n self.C = np.array([[self.fx, 0., self.ppx],\n [0., self.fy, self.ppy],\n [0., 0., 1.]], dtype=np.float32)\n self.C_ext = np.array([[self.fx, 0., self.ppx, 0.],\n [0., self.fy, self.ppy, 0.],\n [0., 0., 1., 0.]], dtype=np.float32)\n\n # aruco related\n self.aruco_dict = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_4X4_250)\n self.marker_size = conf[\"marker_size\"]\n\n # ==================================\n # 2d functionality\n # ==================================\n def get_frames(self):\n if not self.is_connected:\n raise Exception(\"camera not connected.\")\n # align color frame to depth frame\n frames = self.pipeline.wait_for_frames()\n frames = self.align.process(frames)\n\n color_rs = frames.get_color_frame()\n depth_rs = frames.get_depth_frame()\n\n color_mat = np.asanyarray(color_rs.as_frame().get_data())\n depth_mat = np.asanyarray(depth_rs.as_frame().get_data())\n return color_mat, depth_mat\n\n def get_frame_color(self):\n if not self.is_connected:\n raise Exception(\"camera not connected.\")\n frames = self.pipeline.wait_for_frames()\n color_rs = frames.get_color_frame()\n color_mat = np.asanyarray(color_rs.as_frame().get_data())\n return color_mat\n\n def detect_aruco(self):\n color = self.get_frame_color()\n color_drawn = color.copy()\n corners, ids, _ = cv2.aruco.detectMarkers(color_drawn, self.aruco_dict)\n cv2.aruco.drawDetectedMarkers(color_drawn, corners, ids)\n for i in range(len(corners)):\n rvec, tvec, _ = cv2.aruco.estimatePoseSingleMarkers(corners[i], self.marker_size, self.C, self.coeffs)\n cv2.aruco.drawAxis(color_drawn, self.C, self.coeffs, rvec, tvec, self.marker_size)\n return corners, ids, color, color_drawn\n\n # ==================================\n # 3d functionality\n # ==================================\n def construct_point(self, u, v, d):\n point = np.zeros([3, ])\n point[0] = (u - self.ppx_r) * d / self.fx_r\n point[1] = (v - self.ppy_r) * d / self.fy_r\n point[2] = d\n return point\n\n def close(self):\n self.pipeline.stop()\n\n# utility functions\n\n\ndef window_setting(config):\n if config == \"color\":\n cv2.namedWindow(\"color\", cv2.WINDOW_NORMAL)\n cv2.resizeWindow(\"color\", 960, 540)\n elif config == \"color+depth\":\n cv2.namedWindow(\"color\", cv2.WINDOW_NORMAL)\n cv2.resizeWindow(\"color\", 960, 540)\n cv2.namedWindow(\"depth\", cv2.WINDOW_NORMAL)\n cv2.resizeWindow(\"depth\", 960, 540)\n\n\ndef aruco_dict():\n return cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_4X4_250)\n\n\ndef coeffs():\n return np.array([0., 0., 0., 0., 0.]).reshape([5, 1])\n\n\ndef P(size, index):\n if index == 0:\n return np.array([[-0.5*size], [0.5*size], [0.], [1.]])\n if index == 1:\n return np.array([[0.5*size], [0.5*size], [0.], [1.]])\n if index == 2:\n return np.array([[0.5*size], [-0.5*size], [0.], [1.]])\n if index == 3:\n return np.array([[-0.5*size], [-0.5*size], [0.], [1.]])\n\n\ndef get_c2k(color, index, size, C, coeffs):\n param = cv2.aruco.DetectorParameters_create()\n param.cornerRefinementMethod = cv2.aruco.CORNER_REFINE_APRILTAG\n corners, ids, _ = cv2.aruco.detectMarkers(color, aruco_dict(), parameters=param)\n for i in range(ids.shape[0]):\n if ids[i, 0] == index:\n rvec, tvec, _ = cv2.aruco.estimatePoseSingleMarkers(corners[i], size, C, coeffs)\n return f.t_4_4__rvec(rvec.reshape([3, ]), tvec.reshape([3, ]))\n return None\n" }, { "alpha_fraction": 0.504387378692627, "alphanum_fraction": 0.5160871148109436, "avg_line_length": 17.871166229248047, "blob_id": "7475391a652288107b282e3cf7b2b9886341a731", "content_id": "8445d80546fe106491c4339a9873082409185d92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3121, "license_type": "no_license", "max_line_length": 91, "num_lines": 163, "path": "/demo4.1_tracking/web/catkin_ws/src/web/html/ros.js", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "var URL = 'ws://192.168.179.103:9090';\n// Connecting to ROS\nvar ros = new ROSLIB.Ros({\n url : URL\n});\n\n//判断是否连接成功并输出相应的提示消息到web控制台\nros.on('connection', function() {\n console.log('Connected to websocket server.');\n});\n\nros.on('error', function(error) {\n console.log('Error connecting to websocket server: ', error);\n});\n\nros.on('close', function() {\n console.log('Connection to websocket server closed.');\n});\n\n// =========================\n// function switch\n// =========================\n\n// 0: no task\n\n// 1: calibrate markers\n// 2: localize camera\n// 3: scan material\n// 4: scan structure\n// 5: assembly\n// 6: show deviation\nvar state_names = [\"no task\", \"calibrate markers\", \"localize camera\", \n \"scan material\", \"scan structure\", \"assembly\", \n \"show deviation\"];\n\nvar param_state = new ROSLIB.Param({\n ros : ros,\n name : '/f_state'\n});\n\nfunction switch_state(state)\n{\n if (state >= 0 && state <= 6)\n param_state.set(state);\n // document.getElementById('state').innerHTML = 'current state: ' + state_names[state];\n}\n\n// -------------------------\n// END function switch\n// -------------------------\n\n// =========================\n// deviation\n// =========================\n\nvar deviation = new ROSLIB.Topic({\n ros : ros,\n name : '/deviation',\n messageType : 'std_msgs/Float32'\n});\n\ndeviation.subscribe(function(message) {\n document.getElementById('deviation').innerHTML = 'deviation: ' + message.data.toFixed(2);\n // listener.unsubscribe();\n});\n\n// -------------------------\n// END deviation\n// -------------------------\n\n// =========================\n// previous / next\n// =========================\n\nvar UNIT_INDEX = 0;\nvar UNIT_MAX = 4;\nvar param_index = new ROSLIB.Param({\n ros : ros,\n name : '/draw_index'\n});\n\nfunction previous()\n{\n if (UNIT_INDEX > 0)\n UNIT_INDEX -= 1;\n param_index.set(UNIT_INDEX);\n loginfo(\"Return to element \" + UNIT_INDEX);\n}\n\nfunction next()\n{\n if (UNIT_INDEX < UNIT_MAX)\n UNIT_INDEX += 1;\n param_index.set(UNIT_INDEX);\n loginfo(\"Move on to element \" + UNIT_INDEX);\n}\n\n// -------------------------\n// END previous / next\n// -------------------------\n\n// =========================\n// relocate\n// =========================\n\nvar param_relocate = new ROSLIB.Param({\n ros : ros,\n name : '/relocate'\n});\n\nvar param_keep_relocate = new ROSLIB.Param({\n ros : ros,\n name : '/keep_relocate'\n});\n\nfunction relocate()\n{\n param_relocate.set(true);\n}\n\nfunction keep_relocate()\n{\n param_keep_relocate.set(true);\n}\n\n// -------------------------\n// END relocate\n// -------------------------\n\n// =========================\n// take image\n// =========================\n\nvar num_image = 0;\n\nfunction save_image()\n{\n loginfo(\"image \" + num_image + \" saved!\");\n num_image += 1;\n}\n\nfunction perform_task()\n{\n loginfo(\"Calculating...\");\n loginfo(\"Done!\");\n num_image = 0;\n}\n\n// -------------------------\n// END take image\n// -------------------------\n\nfunction loginfo(str)\n{\n document.getElementById(\"log\").innerHTML += (\"<br/ >[INFO] \"+str);\n}\n\nfunction subscribe()\n{\n}\nfunction unsubscribe()\n{\n}\n\n" }, { "alpha_fraction": 0.5955334901809692, "alphanum_fraction": 0.6302729249000549, "avg_line_length": 15.119999885559082, "blob_id": "563299f9bb164f02875c19c5157c61049e8a5e4c", "content_id": "ea58f1631e1136839c8a11f46d9e3ea9508f5061", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 403, "license_type": "no_license", "max_line_length": 51, "num_lines": 25, "path": "/demo2.2_detect_cylinder/detection_rgbd/lib/pose.hpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 06.12.19.\n//\n\n#ifndef POSE_HPP\n#define POSE_HPP\n\n#include <opencv2/opencv.hpp>\n\nusing namespace cv;\n\nclass pose {\npublic:\n Mat m;\n pose(Point3d origin, Vec3d rotationVec);\n// pose(Vec3d origin, Vec3d rotationVec);\n pose(Point3d origin, Vec3d unitZ, Vec3d unitX);\n Mat R();\n Mat origin();\n Mat xAxis();\n Mat yAxis();\n Mat zAxis();\n};\n\n#endif //POSE_HPP\n" }, { "alpha_fraction": 0.49701064825057983, "alphanum_fraction": 0.5363486409187317, "avg_line_length": 38.93771743774414, "blob_id": "1103a2088acb8755ba4f71cf3c5a89a05e3a6150", "content_id": "3e08dc816d15aeec465edeb4634d374c04373aa2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11541, "license_type": "no_license", "max_line_length": 129, "num_lines": 289, "path": "/demo3.1_validate_in_process_scan/detection/construct3D_built/construct3D_built.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 29.03.20.\n//\n\n#include \"construct3D_built.hpp\"\n\n#include <iostream>\n#include <chrono>\n#include <string>\n#include <boost/format.hpp> // for formating strings\n\n#include <opencv2/opencv.hpp>\n#include <opencv2/aruco.hpp>\n\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n\ntypedef pcl::PointXYZRGB PointC;\ntypedef pcl::PointXYZ PointG;\ntypedef pcl::PointCloud<PointC>::Ptr PointCloudC;\ntypedef pcl::PointCloud<PointG>::Ptr PointCloudG;\n\nusing namespace std;\nusing namespace cv;\n\nclass CameraConfig {\npublic:\n Mat M;\n Mat distortion;\n Mat MInv;\n double fx, fy, cx, cy;\n\n CameraConfig() {\n M = (Mat_<double>(3, 3)\n << 1382.23, 0., 953.567\n , 0., 1379.46, 532.635\n , 0., 0., 1.);\n distortion = (Mat_<double >(1, 5)\n << 0.0, 0.0, 0.0, 0.0, 0.0);\n MInv = M.inv();\n fx = 1382.23; fy = 1379.46; cx = 953.567; cy = 532.635;\n };\n};\n\nCameraConfig C;\n\nbool detectCircleboard(Mat img, Mat &tranc2o, Point &center) {\n vector<Point2f> centers;\n bool pattern_was_found = findCirclesGrid(img, cv::Size(2, 13), centers, CALIB_CB_ASYMMETRIC_GRID);\n if (!pattern_was_found)\n return false;\n cv::drawChessboardCorners(img, cv::Size(2, 13), Mat(centers), pattern_was_found);\n vector<Point3f> objectPoints;\n\n for (int i = 0; i < 13; ++i)\n for (int j = 0; j < 2; ++j)\n objectPoints.push_back(Point3d(i*0.02, j*0.04+(i%2)*0.02, 0.0));\n Mat rvec, tvec;\n Mat matCorneres = Mat(centers).reshape(1);\n Mat matObjectPoints = Mat(objectPoints).reshape(1);\n solvePnP(matObjectPoints, matCorneres, C.M, C.distortion, rvec, tvec);\n\n cv::aruco::drawAxis(img, C.M, C.distortion, rvec, tvec, 0.04);\n center = centers[0];\n Mat r;\n Rodrigues(rvec, r);\n hconcat(r, tvec*1000.0, tranc2o);\n Mat down = (Mat_<double>(1, 4) << 0., 0., 0., 1.);\n vconcat(tranc2o, down, tranc2o);\n return true;\n}\n\ndouble **readData(string path) {\n ifstream file;\n file.open(path, ios::in);\n double **data = new double*[7];\n// double data[POLE_COUNT][7] = {0}; // every cylinder has 7 params\n for (int i = 0; i < POLE_COUNT; ++i) {\n data[i] = new double[7];\n for (int j = 0; j < 7; ++j)\n file >> data[i][j];\n }\n file.close();\n return data;\n}\n\ndouble dis(Vec3d p1, Vec3d p2) {\n return sqrt((p1[0]-p2[0])*(p1[0]-p2[0])+(p1[1]-p2[1])*(p1[1]-p2[1])+(p1[2]-p2[2])*(p1[2]-p2[2]));\n}\n\nvoid grow(cv::Mat& src, cv::Mat& mask, cv::Point seed, int threshold) {\n /* apply \"seed grow\" in a given seed\n * Params:\n * src: source image\n * mask: a matrix records the region found in current \"seed grow\"\n */\n const cv::Point PointShift2D[4] =\n {\n cv::Point(1, 0),\n cv::Point(0, -1),\n cv::Point(-1, 0),\n cv::Point(0, 1),\n };\n\n stack<cv::Point> point_stack;\n point_stack.push(seed);\n\n while(!point_stack.empty()) {\n cv::Point center = point_stack.top();\n mask.at<uchar>(center) = 1;\n point_stack.pop();\n\n for (int i=0; i<4; ++i) {\n cv::Point estimating_point = center + PointShift2D[i];\n if (estimating_point.x < 0\n || estimating_point.x > src.cols-1\n || estimating_point.y < 0\n || estimating_point.y > src.rows-1) {\n // estimating_point should not out of the range in image\n continue;\n } else {\n int delta=0;\n if (src.type() == CV_16U)\n delta = (int)abs(src.at<uint16_t>(center) - src.at<uint16_t>(estimating_point));\n // delta = (R-R')^2 + (G-G')^2 + (B-B')^2\n else\n delta = int(pow(src.at<cv::Vec3b>(center)[0] - src.at<cv::Vec3b>(estimating_point)[0], 2)\n + pow(src.at<cv::Vec3b>(center)[1] - src.at<cv::Vec3b>(estimating_point)[1], 2)\n + pow(src.at<cv::Vec3b>(center)[2] - src.at<cv::Vec3b>(estimating_point)[2], 2));\n if (mask.at<uchar>(estimating_point) == 0\n && delta < threshold) {\n mask.at<uchar>(estimating_point) = 1;\n point_stack.push(estimating_point);\n }\n }\n }\n }\n}\n\ndouble distance2cylinder(double *cylinder_param, PointG pt, double start_param, double end_param) {\n Vec3d start(cylinder_param[1], cylinder_param[2], cylinder_param[3]);\n Vec3d dir(cylinder_param[4], cylinder_param[5], cylinder_param[6]);\n Vec3d p_start = start + start_param * dir;\n Vec3d p_end = start + end_param * dir;\n Vec3d p(pt.x, pt.y, pt.z);\n if ((p-p_start).dot(dir) < 0) return 0; // 0: not in the segment\n if ((p_end-p).dot(dir) < 0) return 0; // 0: not in the segment\n return sqrt((p-p_start).dot(p-p_start)-pow((p-p_start).dot(dir), 2)) - cylinder_param[0];\n}\n\npcl::PCDWriter writer;\n\nint main(int argc, char **argv) {\n if (argc != 5) {\n cout << \"please enter number of frames, pole index and the start_param and end_param of the segment.\" << endl;\n return -1;\n }\n const int NUM_FRAMES = stoi(argv[1]);\n const int POLE_INDEX = stoi(argv[2]);\n const double SRART_PARAM = stod(argv[3]);\n const double END_PARAM = stod(argv[4]);\n\n // read color frame\n Mat matColor = imread(\"../data2D/color.png\");\n // get marker pose\n Mat tran_c2o(Size(4, 4), CV_64F);\n Point center;\n if (detectCircleboard(matColor, tran_c2o, center)) {\n cout << \"marker pose : \"<< endl;\n for (int i = 0; i < 4; ++i)\n for (int j = 0; j < 4; ++j)\n cout << tran_c2o.at<double>(i, j) << \" \";\n cout << endl;\n }\n Mat tran_o2c = tran_c2o.inv();\n\n // read depth frames\n Mat matsDepth[NUM_FRAMES];\n for (int frame_index = 0; frame_index < NUM_FRAMES; ++frame_index)\n matsDepth[frame_index] = imread((boost::format(\"../data2D/depth_%d.png\") % frame_index).str(), CV_LOAD_IMAGE_UNCHANGED);\n\n // read cylinder params\n double **cylinder_params = readData(\"../construct3D_built/cylinder_params.txt\");\n\n Mat mask = Mat::zeros(matColor.size(), CV_8UC1);\n Mat mask_blue = Mat::zeros(matColor.size(), CV_8UC3);\n PointCloudG cloud_full(new pcl::PointCloud<PointG>);\n for (int v = 0; v < matColor.rows; ++v) {\n for (int u = 0; u < matColor.cols; ++u) {\n // get the average depth value from all the frames of images\n double dis_average = 0.0;\n bool use_frame = true;\n for (int frame_index = 0; frame_index < NUM_FRAMES; ++frame_index) {\n double d = (double)matsDepth[frame_index].ptr<uint16_t>(v)[u] * 0.1; // unit: 0.1mm\n if (d == 0.0) { use_frame = false; break;}\n dis_average += d;\n }\n if (!use_frame) continue;\n dis_average /= NUM_FRAMES;\n // 3d reconstruction\n if (dis_average == 0.0 || dis_average > 1500.0f) continue;\n Mat p_c = (Mat_<double>(4, 1)\n << ((double)u - C.cx) * dis_average / C.fx, ((double)v - C.cy) * dis_average / C.fy, dis_average, 1.0);\n Mat p_o = tran_o2c * p_c;\n PointG pt(p_o.at<double>(0, 0), p_o.at<double>(1, 0), p_o.at<double>(2, 0));\n// double dis2cylinder = distance2cylinder(cylinder_params[POLE_INDEX], pt, SRART_PARAM, END_PARAM);\n// if (dis2cylinder != 0 && abs(dis2cylinder) < 5.0 && pt.z > -15.0)\n// if (pt.x < -60.0 && pt.y < 30.0 && pt.z > 390.0) // built\n if ( (pt.x < 0.0 && pt.y < 0.0 && pt.z > 360.5 && pt.z < 380.5)\n || (pt.x > 0.0 && pt.y < 0.0 && pt.z > 350.5 && pt.z < 358.5)\n || (pt.x > 0.0 && pt.y > 0.0 && pt.z > 370.5 && pt.z < 386.5)\n || (pt.x < 0.0 && pt.y > 0.0 && pt.z > 374.5 && pt.z < 382.5) ) // built 2\n {\n mask.at<uchar>(v, u) = 255;\n mask_blue.at<Vec3b>(v, u) = Vec3b(255, 0, 0);\n cloud_full->points.push_back(pt);\n } else {\n mask_blue.at<Vec3b>(v, u) = Vec3b(0, 0, 0);\n }\n }\n }\n Mat colorWithMask;\n matColor.copyTo(colorWithMask, mask);\n\n// // detect holes\n vector<vector<Point> > contours;\n findContours(mask, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);\n drawContours(matColor, contours, -1, Scalar(255, 0, 0));\n// cout << contours.size() << endl;\n// Rect2d rect = boundingRect(contours[0]);\n// Mat colorWithMaskRect = matColor(rect);\n// cvtColor(colorWithMaskRect, colorWithMaskRect, CV_BGR2GRAY);\n// vector<Vec3f> circles;\n// HoughCircles(colorWithMaskRect, circles, CV_HOUGH_GRADIENT, 1.2, 10, 100, 15, 6, 12);\n// vector<PointCloudG> clouds_hole;\n// for (auto c : circles) {\n// cout << \"hole found!\" << endl;\n// circle(matColor, Point(c[0]+rect.x, c[1]+rect.y), c[2]*2, Scalar(0, 0, 255));\n// // add points on the circle to the clouds\n// vector<Point> points_on_circle;\n// ellipse2Poly(Point(c[0]+rect.x, c[1]+rect.y), Size(c[2]-2, c[2]-2), 0, 0, 360, 1, points_on_circle);\n// PointCloudG cloud_hole(new pcl::PointCloud<PointG>);\n// for (auto p : points_on_circle) {\n// double dis_average = 0.0;\n// bool use_frame = true;\n// for (int frame_index = 0; frame_index < NUM_FRAMES; ++frame_index) {\n// double d = (double)matsDepth[frame_index].ptr<uint16_t>(p.y)[p.x] * 0.1; // unit: 0.1mm\n// if (d == 0.0) { use_frame = false; break;}\n// dis_average += d;\n// }\n// if (!use_frame) continue;\n// dis_average /= NUM_FRAMES;\n// // 3d reconstruction\n// if (dis_average == 0.0 || dis_average > 1500.0f) continue;\n// Mat p_c = (Mat_<double>(4, 1)\n// << ((double)p.x - C.cx) * dis_average / C.fx, ((double)p.y - C.cy) * dis_average / C.fy, dis_average, 1.0);\n// Mat p_o = tran_o2c * p_c;\n// PointG pt(p_o.at<double>(0, 0), p_o.at<double>(1, 0), p_o.at<double>(2, 0));\n// cloud_hole->points.push_back(pt);\n// }\n// clouds_hole.push_back(cloud_hole);\n// }\n\n addWeighted(matColor, 1.0, mask_blue, 0.4, 0.0, matColor);\n imshow(\"chessboard\", matColor);\n imwrite(\"../data2D/color_detected.png\", matColor);\n// imshow(\"colorWithMaskHoles\", colorWithMaskHoles);\n waitKey();\n\n// chrono::steady_clock::time_point t_start = chrono::steady_clock::now(); // timing start\n\n// chrono::steady_clock::time_point t_end = chrono::steady_clock::now(); // timing end\n// chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t_end - t_start);\n// cout << \"time cost = \" << time_used.count() << \" seconds. \" << endl;\n cloud_full->width = cloud_full->points.size();\n cloud_full->height = 1;\n writer.write(\"../data3D/cloud_passthrough.pcd\", *cloud_full, false);\n cout << \"PointCloud has: \" << cloud_full->points.size() << \" data points.\" << endl;\n\n// // save clouds_hole\n// for (int i = 0; i < clouds_hole.size(); ++i) {\n// clouds_hole[i]->width = clouds_hole[i]->points.size();\n// clouds_hole[i]->height = 1;\n// writer.write((boost::format(\"../data3D/circle_%d.pcd\")%i).str(), *(clouds_hole[i]), false);\n// }\n\n return 0;\n}" }, { "alpha_fraction": 0.5028426051139832, "alphanum_fraction": 0.5395020842552185, "avg_line_length": 35.97101593017578, "blob_id": "3fc9e4dadaeae334f45b195e7026326c31cb32ed", "content_id": "1c4c4a8a05e79fd267073fc0258b2b1903094c33", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5101, "license_type": "no_license", "max_line_length": 120, "num_lines": 138, "path": "/demo3.1_validate_in_process_scan/detection/construct3D.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 17.03.20.\n//\n\n#include <iostream>\n#include <chrono>\n#include <boost/format.hpp> // for formating strings\n\n#include <librealsense2/rs.hpp>\n#include <opencv2/opencv.hpp>\n#include <opencv2/aruco.hpp>\n\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n\ntypedef pcl::PointXYZRGB PointC;\ntypedef pcl::PointXYZ PointG;\ntypedef pcl::PointCloud<PointC>::Ptr PointCloudC;\ntypedef pcl::PointCloud<PointG>::Ptr PointCloudG;\n\nusing namespace std;\nusing namespace cv;\n\nclass CameraConfig {\npublic:\n Mat M;\n Mat distortion;\n Mat MInv;\n double fx, fy, cx, cy;\n\n CameraConfig() {\n M = (Mat_<double>(3, 3)\n << 1382.23, 0., 953.567\n , 0., 1379.46, 532.635\n , 0., 0., 1.);\n distortion = (Mat_<double >(1, 5)\n << 0.0, 0.0, 0.0, 0.0, 0.0);\n MInv = M.inv();\n fx = 1382.23; fy = 1379.46; cx = 953.567; cy = 532.635;\n };\n};\n\nCameraConfig C;\n\nbool detectMarker(Mat img, Mat &tranc2o, Point &center) {\n vector<vector<cv::Point2f>> rejectedCandidates;\n cv::Ptr<cv::aruco::DetectorParameters> parameters = cv::aruco::DetectorParameters::create();\n cv::Ptr<cv::aruco::Dictionary> dictionary = cv::aruco::generateCustomDictionary(10, 6);\n vector<vector<Point2f> > markerCorners;\n vector<int> markerIds;\n\n cv::aruco::detectMarkers(img, dictionary, markerCorners, markerIds, parameters, rejectedCandidates);\n cv::aruco::drawDetectedMarkers(img, markerCorners, markerIds);\n if (markerIds.size() == 0) return false;\n\n vector<cv::Vec3d> rvecs, tvecs;\n cv::aruco::estimatePoseSingleMarkers(markerCorners, 0.04, C.M, C.distortion, rvecs, tvecs);\n for (int i = 0; i < rvecs.size(); ++i) {\n auto rvec = rvecs[i];\n auto tvec = tvecs[i];\n cv::aruco::drawAxis(img, C.M, C.distortion, rvec, tvec, 0.04);\n\n if (markerIds[i] == 1) {\n center = 0.25 * (markerCorners[i][0]+markerCorners[i][1]+markerCorners[i][2]+markerCorners[i][3]);\n Mat r;\n Rodrigues(rvecs[i], r);\n Mat t = (Mat_<double>(3, 1) << tvecs[i][0]*1000, tvecs[i][1]*1000, tvecs[i][2]*1000);\n hconcat(r, t, tranc2o);\n Mat down = (Mat_<double>(1, 4) << 0., 0., 0., 1.);\n vconcat(tranc2o, down, tranc2o);\n return true;\n }\n }\n return false;\n}\n\npcl::PCDWriter writer;\n\nint main(int argc, char **argv) {\n int num_frames = 32;\n for (int frame_index = 0; frame_index < num_frames; ++frame_index) {\n Mat matColor = imread((boost::format(\"../data2D/color_%d.png\") % frame_index).str());\n Mat matDepth = imread((boost::format(\"../data2D/depth_%d.png\") % frame_index).str(), CV_LOAD_IMAGE_UNCHANGED);\n\n // get marker pose\n Mat tran_c2o;\n Point center;\n if (detectMarker(matColor, tran_c2o, center)) {\n cout << \"frame: : \" << frame_index << endl;\n cout << \"depth: \" << matDepth.at<int16_t>(center) << endl;\n for (int i = 0; i < 4; ++i)\n for (int j = 0; j < 4; ++j)\n cout << tran_c2o.at<double>(i, j) << \" \";\n cout << endl;\n }\n Mat tran_o2c = tran_c2o.inv();\n// imshow(\"aruco\", matColor);\n\n// chrono::steady_clock::time_point t_start = chrono::steady_clock::now(); // timing start\n\n Mat mask = Mat::zeros(matDepth.size(), CV_8UC1);\n PointCloudG cloud_full(new pcl::PointCloud<PointG>);\n for (int v = 0; v < matColor.rows; ++v) {\n for (int u = 0; u < matColor.cols; ++u) {\n double d = (double)matDepth.ptr<uint16_t>(v)[u];\n if (d == 0.0 || d > 1500.0f) continue;\n Mat p_c = (Mat_<double>(4, 1)\n << ((double)u - C.cx) * d / C.fx, ((double)v - C.cy) * d / C.fy, d, 1.0);\n Mat p_o = tran_o2c * p_c;\n PointG pt(p_o.at<double>(0, 0), p_o.at<double>(1, 0), p_o.at<double>(2, 0));\n if (pt.x > 55.1 && pt.x < 333.6)\n if (pt.z > 34.25)\n if (pt.y > -82.4 && pt.y < 8.6) {\n mask.at<uchar>(v, u) = 255;\n }\n cloud_full->points.push_back(pt);\n }\n }\n Mat colorWithMask;\n matColor.copyTo(colorWithMask, mask);\n// imshow(\"with mask\", colorWithMask);\n// waitKey();\n\n// chrono::steady_clock::time_point t_end = chrono::steady_clock::now(); // timing end\n// chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t_end - t_start);\n// cout << \"time cost = \" << time_used.count() << \" seconds. \" << endl;\n\n cloud_full->width = cloud_full->points.size();\n cloud_full->height = 1;\n boost::format fmt_b( \"../data3D/cloud_full_%d.pcd\" );\n writer.write((fmt_b % frame_index).str(), *cloud_full, false);\n cout << \"PointCloud Bamboo \" << frame_index << \" has: \" << cloud_full->points.size() << \" data points.\" << endl;\n cout << endl;\n }\n\n return 0;\n}" }, { "alpha_fraction": 0.46097201108932495, "alphanum_fraction": 0.50938880443573, "avg_line_length": 29.863636016845703, "blob_id": "d7dd40b0ccd6e0faa20e7b3e845b8c61123fc242", "content_id": "c3918718de67a575fe40822a2c8a0f104fe3141c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5432, "license_type": "no_license", "max_line_length": 112, "num_lines": 176, "path": "/demo5.1_final/adaptation/adapt.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom Frame import *\nfrom scipy.optimize import minimize\nfrom math import pi\nimport sys\nimport yaml\n\n\n# [n, ] -> scalar\ndef length(v):\n return np.linalg.norm(v, ord=2)\n\n\n# [7, ] [7, ] -> scalar\ndef dis_l_l(l1, l2):\n p1, v1, r1 = l1[1:4], l1[4:7], l1[0]\n p2, v2, r2 = l2[1:4], l2[4:7], l2[0]\n cross = np.cross(v1, v2)\n return abs(np.sum((p1 - p2) * cross)) / length(cross) - r1 - r2\n\n\n# [7, ] [7, ] -> scalar\ndef angle_l_l(l1, l2):\n v1 = l1[4:7]\n v2 = l2[4:7]\n return np.arccos(np.sum(v1*v2) / (length(v1) * length(v2)))\n\n\n# [7, ] [3, ] -> scalar\ndef dis_l_t(l, t):\n p, v = l[1:4], l[4:7]\n cross = np.cross(t-p, v)\n return length(cross) / length(v)\n\n\n# [4, 4] [7, ] -> [7, ]\ndef tran(r_6, l):\n c_new = np.zeros([7, ])\n p = np.ones([4, ])\n p[0:3] = l[1:4]\n v = l[4:7]\n f = Frame.from_r_3(r_6[0:3], r_6[3:6].reshape([3, 1]))\n c_new[1:4] = f.t_4_4.dot(p)[0:3].reshape([3, ])\n c_new[4:7] = f.r_3_3.dot(v).reshape([3, ])\n c_new[0] = l[0]\n return c_new\n\n\n# [3, ] [3, ] -> [4, 4]\ndef frame_from_normal(p, v):\n t = np.eye(4)\n # z axis\n z_temp = v / length(v)\n t[0:3, 2] = z_temp\n # x axis\n if abs(v[0]) < 1e-2 and abs(v[1]) < 1e-2:\n x_temp = np.cross(v, np.array([0., 0., 1.]))\n x_temp /= length(x_temp)\n else:\n x_temp = np.cross(v, np.array([0., 1., 0.]))\n x_temp /= length(x_temp)\n t[0:3, 0] = x_temp\n # y axis\n t[0:3, 1] = np.cross(z_temp, x_temp)\n # translation\n t[0:3, 3] = p\n return t\n\n\n# [7, ] [7, ] -> [6, ]\ndef align_l_l(l1, l2):\n t1 = frame_from_normal(l1[1:4], l1[4:7])\n t2 = frame_from_normal(l2[1:4], l2[4:7])\n t21 = Frame(t2.dot(np.linalg.inv(t1)))\n result = np.zeros([6, ])\n result[0:3] = t21.r_3.flatten()\n result[3:6] = t21.t_3_1.flatten()\n return result\n\n\nwith open(\"config/config.yml\", 'r') as file:\n conf = yaml.safe_load(file.read())\n\n# ====================\n# m : scanned material\n# b : built\n# t : target\n# ====================\ntask_index = conf[\"task_index\"]\n# is_fliped = conf[\"is_fliped\"]\ntopo = np.loadtxt(conf[\"path_topo\"])\npole = np.loadtxt(conf[\"path_design\"])[task_index]\npath_result = conf[\"path_result\"]\npath_result_pre = conf[\"path_result_pre\"]\npath_result_target = conf[\"path_result_target\"]\nif topo[task_index][0] == -1:\n print(\"doesn't need to adapt\")\n sys.exit(0)\nelif topo[task_index][0] == 0:\n print(\"one constraint and one target\")\n num_cons = 1\n m = np.array([np.loadtxt(conf[\"path_m\"] % (task_index, topo[task_index][1])),\n np.loadtxt(conf[\"path_m\"] % (task_index, -1))]) # -1 : target\n b = np.loadtxt(conf[\"path_b\"] % (task_index, topo[task_index][1]))\n t = np.loadtxt(conf[\"path_t\"])[int(topo[task_index][4])]\nelif topo[task_index][0] == 1:\n print(\"two constraint\")\n num_cons = 2\n m = np.array([np.loadtxt(conf[\"path_m\"] % (task_index, topo[task_index][1])),\n np.loadtxt(conf[\"path_m\"] % (task_index, topo[task_index][4]))])\n b = np.array([np.loadtxt(conf[\"path_b\"] % (task_index, topo[task_index][1])),\n np.loadtxt(conf[\"path_b\"] % (task_index, topo[task_index][4]))])\nm_init = np.zeros([7, ])\nm_init[0] = pole[0]\nm_init[1:4] = pole[1:4] + topo[task_index][2] * pole[4:7] / length(pole[4:7])\nm_init[4:7] = pole[4:7] / length(pole[4:7]) * 0.04\npre_tran = align_l_l(m[0], m_init)\nm0 = tran(pre_tran, m[0])\nm1 = tran(pre_tran, m[1])\n\n# ===========\n# constraints\n# ===========\nDISTANCE = conf[\"distance\"]\nANGLE_L = conf[\"angle_l\"] * pi / 180.\nANGLE_U = conf[\"angle_u\"] * pi / 180.\nmu = conf[\"mu\"]\n\nif num_cons == 1:\n eq_cons = {\"type\": \"eq\", \"fun\": lambda x: dis_l_l(tran(x, m0), b) - DISTANCE}\n ineq_cons = {\"type\": \"ineq\", \"fun\": lambda x: np.array([angle_l_l(tran(x, m0), b) - ANGLE_L,\n - angle_l_l(tran(x, m0), b) + ANGLE_U])}\nif num_cons == 2:\n eq_cons = {\"type\": \"eq\", \"fun\": lambda x: np.array([dis_l_l(tran(x, m0), b[0]) - DISTANCE,\n dis_l_l(tran(x, m1), b[1]) - DISTANCE])}\n ineq_cons = {\"type\": \"ineq\", \"fun\": lambda x: np.array([angle_l_l(tran(x, m0), b[0]) - ANGLE_L,\n - angle_l_l(tran(x, m0), b[0]) + ANGLE_U,\n angle_l_l(tran(x, m1), b[1]) - ANGLE_L,\n - angle_l_l(tran(x, m1), b[1]) + ANGLE_U])}\n\n# get initial guess\n# x0 = np.zeros([6, ])\n\n# l0_v = l[0][3:6]\n# m_v = m[0][3:6]\n#\n# cross = np.cross(l0_v, m_v)\n# cross /= length(cross)\n# cross *= (DISTANCE - dis_l_l(l[0], m[0]))\n# print(cross)\nx0 = np.zeros([6, ])\n# x0[3:6] = -cross\n#\n# print(dis_l_l(l[0], m[0]) - DISTANCE)\n# print(dis_l_l(tran(x0, l[0]), m[0]) - DISTANCE)\n\n\ndef cost(x):\n global m, t, mu\n if num_cons == 2:\n return length(x)\n if num_cons == 1:\n return dis_l_t(tran(x, m1), t) + mu * length(x)\n\n\nres = minimize(cost, x0, method=\"SLSQP\", constraints=[eq_cons, ineq_cons], options={\"fto1\": 1e-9, \"disp\": True})\nprint(res.x)\n\n# print angle\nprint(\"angle: \")\nprint(angle_l_l(tran(res.x, m0), b)*180/pi)\n\nnp.savetxt(path_result_pre % task_index, pre_tran.reshape([1, 6]), fmt=\"%f\")\nnp.savetxt(path_result % task_index, res.x.reshape([1, 6]), fmt=\"%f\")\nnp.savetxt(path_result_target % task_index, tran(res.x, m1).reshape([1, 7]), fmt=\"%f\")\n" }, { "alpha_fraction": 0.486141175031662, "alphanum_fraction": 0.5452576875686646, "avg_line_length": 38.478633880615234, "blob_id": "25fff133ae7bbcea82d795876fbf118734432a4e", "content_id": "1ef8ea8e0a90af95642373c65880f36ad0885aec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4878, "license_type": "no_license", "max_line_length": 145, "num_lines": 117, "path": "/demo2.2_detect_cylinder/hand_eye_calib/hand_eye_calib_t.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <chrono>\n#include <boost/format.hpp>\n#include <Eigen/Core>\n#include <ceres/ceres.h>\n#include <ceres/rotation.h>\n\nusing namespace std;\n\n// 代价函数的计算模型\nstruct HAND_EYE_COST {\n HAND_EYE_COST(Eigen::Matrix4d x1, Eigen::Matrix4d x2) : _x1(x1), _x2(x2){}\n\n // 残差的计算\n template<typename T>\n bool operator()(\n const T *const translation, // 3 dim\n T *residual) const {\n Eigen::Matrix<T, 4, 4> tran;\n tran << T(0.0169028), T(0.999607), T(-0.0223445), translation[0],\n T(-0.999788), T(0.016635), T(-0.0121177), translation[1],\n T(-0.0117412), T(0.0225446), T(0.999677), translation[2],\n T(0.0), T(0.0), T(0.0), T(1.0);\n// tran << T(-0.0), T(1.0), T(-0.0), translation[0],\n// T(-1.0), T(-0.0), T(-0.0), translation[1],\n// T(-0.0), T(0.0), T(1.0), translation[2],\n// T(0.0), T(0.0), T(0.0), T(1.0);\n Eigen::Matrix<T, 4, 4> _x1_Matrix = _x1.cast<T>();\n Eigen::Matrix<T, 4, 4> _x2_Matrix = _x2.cast<T>();\n Eigen::Matrix<T, 4, 4> Cost_Matrix = _x1_Matrix * tran - tran * _x2_Matrix;\n// residual[0] = (Cost_Matrix.array()*Cost_Matrix.array()).sum();\n// residual[0] = Cost_Matrix(0, 0); residual[1] = Cost_Matrix(0, 1); residual[2] = Cost_Matrix(0, 2); residual[3] = Cost_Matrix(0, 3);\n// residual[4] = Cost_Matrix(1, 0); residual[5] = Cost_Matrix(1, 1); residual[6] = Cost_Matrix(1, 2); residual[7] = Cost_Matrix(1, 3);\n// residual[8] = Cost_Matrix(2, 0); residual[9] = Cost_Matrix(2, 1); residual[10] = Cost_Matrix(2, 2); residual[11] = Cost_Matrix(2, 3);\n// residual[12] = Cost_Matrix(3, 0); residual[13] = Cost_Matrix(3, 1); residual[14] = Cost_Matrix(3, 2); residual[15] = Cost_Matrix(3, 3);\n residual[0] = Cost_Matrix(0, 3); residual[1] = Cost_Matrix(1, 3); residual[2] = Cost_Matrix(2, 3);\n\n return true;\n }\n\n const Eigen::Matrix4d _x1, _x2; // x数据\n};\n\nvoid readData(char *path, int n, vector<Eigen::Matrix4d> &As, vector<Eigen::Matrix4d> &Bs) {\n ifstream file;\n file.open(path, ios::in);\n vector<Eigen::Matrix4d> tran_list_w2e, tran_list_c2o;\n for (int i = 0; i < n; ++i) {\n double data[16] = {0};\n for (auto& d : data)\n file >> d;\n data[3] = data[3] / 1000.0;\n data[7] = data[7] / 1000.0;\n data[11] = data[11] / 1000.0;\n tran_list_w2e.emplace_back(Eigen::Map<Eigen::Matrix4d>(data).transpose());\n for (auto& d : data)\n file >> d;\n tran_list_c2o.emplace_back(Eigen::Map<Eigen::Matrix4d>(data).transpose());\n }\n file.close();\n for (int i = 0; i < n-1; ++i) {\n As.push_back(tran_list_w2e[i+1].inverse()*tran_list_w2e[i]);\n Bs.push_back(tran_list_c2o[i+1]*tran_list_c2o[i].inverse());\n }\n}\n\nint main(int argc, char **argv) {\n if (argc != 2) {\n cout << \"please enter the file path\" << endl;\n return -1;\n }\n\n double t0 = 0.0, t1 = 0.0, t2 = 160.0; // 估计参数值\n double translation[3] = {t0, t1, t2};\n\n // 5 pairs of data\n int N = 31;\n vector<Eigen::Matrix4d> As, Bs; // As: Twe2.inv()*Twe1 Bs: Tco2*Tco1.inv()\n readData(argv[1], N, As, Bs);\n // \"../fake_data/fake_data.txt\"\n\n // 构建最小二乘问题\n ceres::Problem problem;\n for (int i = 0; i < N-1; i++) {\n problem.AddResidualBlock( // 向问题中添加误差项\n // 使用自动求导,模板参数:误差类型,输出维度,输入维度,维数要与前面struct中一致\n new ceres::AutoDiffCostFunction<HAND_EYE_COST, 3, 3>(\n new HAND_EYE_COST(As[i], Bs[i])\n ),\n nullptr, // 核函数,这里不使用,为空\n translation // 待估计参数\n );\n }\n\n // 配置求解器\n ceres::Solver::Options options; // 这里有很多配置项可以填\n options.linear_solver_type = ceres::DENSE_NORMAL_CHOLESKY; // 增量方程如何求解\n options.minimizer_progress_to_stdout = true; // 输出到cout\n\n ceres::Solver::Summary summary; // 优化信息\n chrono::steady_clock::time_point t_start = chrono::steady_clock::now();\n ceres::Solve(options, &problem, &summary); // 开始优化\n chrono::steady_clock::time_point t_end = chrono::steady_clock::now();\n chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t_end - t_start);\n cout << \"solve time cost = \" << time_used.count() << \" seconds. \" << endl;\n\n // 输出结果\n cout << summary.BriefReport() << endl;\n cout << \"estimated translation = \";\n for (auto a:translation) cout << a << \" \";\n cout << endl;\n\n return 0;\n}" }, { "alpha_fraction": 0.6734693646430969, "alphanum_fraction": 0.6734693646430969, "avg_line_length": 21, "blob_id": "00ea946d1b5d08ca965991db54c4a2548de13cb2", "content_id": "6f3a08854f13db2d9a649f2a282df810d46a35ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 49, "license_type": "no_license", "max_line_length": 34, "num_lines": 2, "path": "/design/README.md", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "# design\r\nThe design files of all the demos. \r\n\r\n" }, { "alpha_fraction": 0.7576576471328735, "alphanum_fraction": 0.7729730010032654, "avg_line_length": 31.647058486938477, "blob_id": "4621c7b38222a7a5d37294389031b57e92f583bd", "content_id": "37eaf13867883b486bcd2f8018990751c58772fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1110, "license_type": "no_license", "max_line_length": 101, "num_lines": 34, "path": "/demo4.1_tracking/tracking/CMakeLists.txt", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "project (tracking)\nset(CMAKE_CXX_FLAGS \"-std=c++14 -O3\")\ncmake_minimum_required(VERSION 3.15)\n\nfind_package(realsense2 REQUIRED)\n\nfind_package(OpenCV REQUIRED)\ninclude_directories(${OpenCV_INCLUDE_DIRS})\n\nfind_package(Eigen3 REQUIRED)\ninclude_directories(${Eigen3_INCLUDE_DIRS})\n\nfind_package(Ceres REQUIRED)\ninclude_directories(${CERES_INCLUDE_DIRS})\n\nfind_package(PCL 1.2 REQUIRED)\n\ninclude_directories(${PCL_INCLUDE_DIRS})\nlink_directories(${PCL_LIBRARY_DIRS})\nadd_definitions(${PCL_DEFINITIONS})\n\n#new\nadd_executable(main main.cpp)\ntarget_link_libraries(main ${OpenCV_LIBS} ${realsense2_LIBRARY} ${CERES_LIBRARIES})\n#target_link_libraries(main ${OpenCV_LIBS} ${realsense2_LIBRARY} ${PCL_LIBRARIES} ${CERES_LIBRARIES})\n\nadd_executable(demo_a_assembly demo_a_assembly.cpp)\ntarget_link_libraries(demo_a_assembly ${OpenCV_LIBS} ${realsense2_LIBRARY} ${PCL_LIBRARIES})\n\nadd_executable(take_video take_video.cpp)\ntarget_link_libraries(take_video ${OpenCV_LIBS} ${realsense2_LIBRARY})\n\nadd_executable(test_aruco test_aruco.cpp)\ntarget_link_libraries(test_aruco ${OpenCV_LIBS} ${realsense2_LIBRARY} Eigen3::Eigen)\n" }, { "alpha_fraction": 0.8046075105667114, "alphanum_fraction": 0.8071672320365906, "avg_line_length": 40.85714340209961, "blob_id": "c8b40ad6363689cd0d8d66cb8ffc6cc120cfab68", "content_id": "5d7dfde7528554f07722fd2d323bc11ef32df831", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1172, "license_type": "no_license", "max_line_length": 78, "num_lines": 28, "path": "/demo2.2_detect_cylinder/detection_rgbd/lib/CMakeLists.txt", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "# libkinect\nadd_library(libkinect SHARED kinect.cpp kinect.hpp)\ntarget_include_directories(libkinect PUBLIC \"${CMAKE_CURRENT_SOURCE_DIR}\")\ntarget_link_libraries(libkinect ${freenect2_LIBRARIES})\ntarget_link_libraries(libkinect ${OpenCV_LIBS})\ntarget_link_libraries(libkinect ${PCL_LIBRARIES})\n\n# libpose\nadd_library(libpose SHARED pose.cpp pose.hpp)\ntarget_include_directories(libpose PUBLIC \"${CMAKE_CURRENT_SOURCE_DIR}\")\ntarget_link_libraries(libpose ${OpenCV_LIBS})\n\n# libvision\nadd_library(libvision SHARED vision.cpp vision.hpp)\ntarget_include_directories(libvision PUBLIC \"${CMAKE_CURRENT_SOURCE_DIR}\")\ntarget_link_libraries(libvision ${OpenCV_LIBS})\n#target_link_libraries(vision ${PCL_LIBRARIES})\n#target_link_libraries(vision ${realsense2_LIBRARY})\n\n# libpointCloud\nadd_library(libpointCloud SHARED pointCloud.cpp pointCloud.hpp)\ntarget_include_directories(libpointCloud PUBLIC \"${CMAKE_CURRENT_SOURCE_DIR}\")\ntarget_link_libraries(libpointCloud ${PCL_LIBRARIES})\ntarget_link_libraries(libpointCloud ${realsense2_LIBRARY})\ntarget_link_libraries(libpointCloud ${OpenCV_LIBS})\n\nlink_libraries(libvision PUBLIC libpose)\nlink_libraries(libpointCloud PUBLIC libvision)\n" }, { "alpha_fraction": 0.6620926260948181, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 25.907691955566406, "blob_id": "9e250e7b24b057ffecf1ef31871867cf56cddd56", "content_id": "c05ebc4840b65663c016cff97963e683f17c2280", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1749, "license_type": "no_license", "max_line_length": 64, "num_lines": 65, "path": "/design/tolerance_study/fit_pieces.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "import scriptcontext\nimport ghpythonremote\nimport Rhino.Geometry as rg\n\nnp = scriptcontext.sticky['numpy']\ncvxopt = scriptcontext.sticky['cvxopt']\nrpy = scriptcontext.sticky['rpy']\n\n\n# input cell index\n# output open polyline of the cell\ndef get_cell(cell_index):\n start_edge_index = Face_StartEdge[cell_index]\n edge_index = start_edge_index\n # edge_start_index = Edge_Start[start_edge_index]\n # next_edge_index = Edge_Next[start_edge_index]\n polyline = rg.Polyline()\n while True:\n polyline.Add(Vertices[Edge_Start[edge_index]])\n edge_index = Edge_Next[edge_index]\n if edge_index == start_edge_index:\n break\n return polyline\n\n\n# input cell index\n# output open polyline of the cell\ndef get_fabricated_cell(cell_index):\n polyline = get_cell(cell_index)\n for i in range(polyline.Count):\n polyline[i] += Noise_Vectors.Branch(cell_index)[i]\n return polyline\n\n\n# input edge index\n# output edge line\ndef get_edge(edge_index):\n start = Vertices[Edge_Start[edge_index]]\n end = Vertices[Edge_Start[Edge_Next[edge_index]]]\n return rg.Line(start, end)\n\n\n# fix all the bottom edges\ndef fixed_edges_init():\n edge_indices = []\n for edge_index in range(len(Edge_Start)):\n if Edge_Face[edge_index] != -1:\n continue\n if Vertices[Edge_Start[edge_index]].Y > 0.01:\n continue\n if Vertices[Edge_Start[Edge_Next[edge_index]]].Y > 0.01:\n continue\n edge_indices.append(edge_index)\n return edge_indices\n\n\n\n\nfixed_edges_indices = fixed_edges_init()\na = []\nb = []\nfor face_index in range(1):\n a.append(get_fabricated_cell(face_index).ToPolylineCurve())\nfor edge_index in fixed_edges_indices:\n b.append(get_edge(edge_index))\n" }, { "alpha_fraction": 0.5374608635902405, "alphanum_fraction": 0.5611724257469177, "avg_line_length": 29.064355850219727, "blob_id": "fb1ceded986dda960a926e7dacac701de610ba32", "content_id": "1f3ed598c09167a61b928f83b8286d08a19012df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6073, "license_type": "no_license", "max_line_length": 126, "num_lines": 202, "path": "/workshop/SVM/mnist.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom cvxopt import solvers, matrix\nfrom matplotlib import pyplot as plt\nimport random\nimport struct\nimport gzip\nimport pickle\n\n\ndef read_idx(filename):\n with gzip.open(filename) as f:\n zero, data_type, dims = struct.unpack('>HBB', f.read(4))\n shape = tuple(struct.unpack('>I', f.read(4))[0] for d in range(dims))\n return np.fromstring(f.read(), dtype=np.uint8).reshape(shape)\n\n\ndef count_label(labels):\n counts = [[], [], [], [], [], [], [], [], [], []]\n for index in range(len(labels)):\n counts[labels[index]].append(index)\n return counts\n\n\ndef kernel_RBF(x1, x2, _gamma):\n return np.exp(-_gamma * np.sum((x1 - x2) * (x1 - x2)))\n\n\ndef kernel_polynomial(x1, x2, _gamma):\n return (1 + np.sum(x1*x2)) ** 2\n\n\ndef get_P_Mat(x, y, kernel, _gamma):\n n = y.shape[0]\n _P = np.zeros([n, n], dtype=np.float64)\n for i in range(n):\n for j in range(n):\n _P[i][j] = y[i][0] * y[j][0] * kernel(x[i], x[j], _gamma)\n return _P\n\n\ndef getSamples(labels):\n global x_train_reduced, y_train\n # choose 1:1 samples for certain label : the rest\n x_choose = x_train_reduced[labels]\n indices = []\n while len(indices) < len(labels):\n next_index = random.randint(0, y_train.shape[0]-1)\n if next_index not in labels:\n indices.append(next_index)\n x_rest = x_train_reduced[indices]\n x_mixed = np.vstack((x_choose, x_rest))\n y_mixed = np.asarray([[1.]] * len(labels) + [[-1.]] * len(labels))\n shuffle_idx = np.arange(0, len(labels) * 2)\n np.random.shuffle(shuffle_idx)\n x_shuffled = x_mixed[shuffle_idx]\n y_shuffled = y_mixed[shuffle_idx]\n return x_shuffled, y_shuffled\n\n\ndef trainSVM(x, y, _kernel, _gamma, _C):\n n = y.shape[0]\n P_Mat = get_P_Mat(x, y, kernel=_kernel, _gamma=_gamma)\n # optimizaton\n P = matrix(P_Mat)\n q = matrix(-np.ones([n, 1]))\n # 2*n inequality constraints\n G = matrix(np.vstack([-np.eye(n), np.eye(n)]))\n h = matrix(np.vstack([np.zeros([n, 1]), _C * np.ones([n, 1])]))\n # 1 equality constraint\n A = matrix(y.T)\n b = matrix(0.)\n sol = solvers.qp(P, q, G, h, A, b)\n alpha = np.array(sol['x'])\n # get SVs and SOs\n SV, SO = [], []\n for i in range(n):\n if alpha[i][0] < 0.001:\n continue\n if abs(alpha[i][0] - _C) > 0.001:\n SV.append(i)\n SO.append(i)\n # calculate b\n w0 = 0.\n for i in SV:\n w0 += y[i][0]\n for j in SO:\n w0 -= alpha[j][0] * y[j][0] * P_Mat[j][i]\n w0 /= len(SV)\n return alpha[SO], x[SO], y[SO], w0\n\n\ndef predict(x, label, kernel, _gamma):\n global alphas, SOs, ws\n global x_train_reduced, y_train\n pred = ws[label]\n for index in range(alphas[label].shape[0]):\n pred += (alphas[label][index][0] * y_train[SOs[label][index]] * kernel(x_train_reduced[SOs[label][index]], x, _gamma))\n return pred\n\n\nclass TenClassSVM:\n def __init__(self, _alphas, _xs, _ys, _ws, _gamma, _kernel, _C):\n self.gamma = _gamma\n self.kernel = _kernel\n self.C = _C\n self.alphas = _alphas\n self.xs = _xs\n self.ys = _ys\n self.ws = _ws\n\n def predict(self, x, _label):\n alpha_use = self.alphas[_label]\n x_use = self.xs[_label]\n y_use = self.ys[_label]\n pred = self.ws[_label]\n for index in range(alpha_use.shape[0]):\n pred += (alpha_use[index][0] * y_use[index][0] * self.kernel(x_use[index], x, self.gamma))\n return pred\n\n\nif __name__ == \"__main__\":\n x_total = read_idx(\"./MNIST/t10k-images-idx3-ubyte.gz\")\n y_total = read_idx(\"./MNIST/t10k-labels-idx1-ubyte.gz\")\n N = 2000\n x_train, y_train = x_total[:N], y_total[:N]\n x_test, y_test = x_total[N:N+100], y_total[N:N+100]\n\n # PCA\n x_train_flattened = np.array(x_train.reshape([N, 28*28, 1]), dtype=np.float32)\n R = np.einsum(\"ijk, ilk -> ijl\", x_train_flattened, x_train_flattened).mean(axis=0)\n e_vals, e_vecs = np.linalg.eig(R)\n W = e_vecs[:, :50]\n x_train_reduced = W.T.dot(x_train_flattened.reshape([N, 28*28]).T).T\n\n # x1 = np.array(x_test.reshape([100, 28*28, 1]), dtype=np.float32)[4]\n # plt.imshow(x1.reshape([28, 28]), cmap=\"Greys\")\n # plt.show()\n #\n # x1_after = W.dot(W.T).dot(x1).reshape([28, 28])\n # plt.imshow(x1_after, cmap=\"Greys\")\n # plt.show()\n\n # SVM training\n\n gamma = 9.0e-7\n kernel = kernel_RBF\n C = 1\n\n alphas, xs, ys, ws = [], [], [], []\n label_counts = count_label(y_train)\n for label in range(10):\n x, y = getSamples(label_counts[label])\n alpha_t, x_t, y_t, w_t = trainSVM(x, y, kernel, gamma, C)\n alphas.append(alpha_t)\n xs.append(x_t)\n ys.append(y_t)\n ws.append(w_t)\n\n # save model\n\n model = TenClassSVM(alphas, xs, ys, ws, gamma, kernel, C)\n f = open('model_1.pickle', 'wb')\n pickle.dump(model, f)\n f.close()\n\n # load model\n\n f = open('model_1.pickle', 'rb')\n model = pickle.load(f)\n f.close()\n\n print(model.alphas[0].shape)\n print(model.ws)\n\n # SVM prediction\n\n error_count = 0\n for i in range(N):\n predictions = []\n for label in range(10):\n predictions.append(model.predict(x_train_reduced[i], label))\n if y_train[i] != predictions.index(max(predictions)):\n error_count += 1\n # print(predictions)\n # print(y_train[i])\n error_rate = float(error_count) / x_train_reduced.shape[0]\n print(\"training error rate: %f\" % error_rate)\n\n # testing set\n\n x_test_reduced = W.T.dot(np.array(x_test.reshape([100, 28*28]).T, dtype=np.float32)).T\n error_count = 0\n for i in range(x_test_reduced.shape[0]):\n predictions = []\n for label in range(10):\n predictions.append(model.predict(x_test_reduced[i], label))\n if y_test[i] != predictions.index(max(predictions)):\n error_count += 1\n # print(predictions)\n # print(y_test[i])\n error_rate = float(error_count) / x_test_reduced.shape[0]\n print(\"test error rate: %f\" % error_rate)\n" }, { "alpha_fraction": 0.5003990530967712, "alphanum_fraction": 0.5099760293960571, "avg_line_length": 23.059999465942383, "blob_id": "86e7ba4968c8c526137dcc27b221a150dbdaeecf", "content_id": "d8417c83c27047b873821895fd0f2871bff58761", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1253, "license_type": "no_license", "max_line_length": 57, "num_lines": 50, "path": "/demo1_tello_aruco/cv_aruco/main.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "from aruco_detection_py import *\r\nimport tellopy\r\nfrom tello_controller import *\r\n\r\n\r\n# solver = Aruco_detector()\r\ndef handler(event, sender, data, **args):\r\n drone = sender\r\n if event is drone.EVENT_FLIGHT_DATA:\r\n print(data)\r\n\r\n\r\nwhile True:\r\n drone = tellopy.Tello()\r\n drone.start_video()\r\n controller = Tello_controller(drone=drone)\r\n try:\r\n drone.subscribe(drone.EVENT_FLIGHT_DATA, handler)\r\n drone.connect()\r\n drone.wait_for_connection(60.0)\r\n drone.takeoff()\r\n sleep(3)\r\n drone.down(0)\r\n sleep(3)\r\n while True:\r\n pic = drone.take_picture()\r\n print(pic)\r\n c = cv2.waitKey(1)\r\n if c == ord(\"q\"):\r\n break\r\n except Exception as ex:\r\n print(ex)\r\n finally:\r\n drone.quit()\r\n\r\n # solver.detect()\r\n # cv2.imshow(\"video\", solver.image)\r\n # if solver.is_detected:\r\n # pose = solver.pose_world_to_tello\r\n # print(\"__________\")\r\n # print(f\"x={pose.x}\")\r\n # print(f\"y={pose.y}\")\r\n # print(f\"z={pose.z}\")\r\n # print(f\"yaw={pose.yaw}\")\r\n # cv2.waitKey()\r\n # c = cv2.waitKey(1)\r\n # if c == ord(\"q\"):\r\n # break\r\n\r\n# solver.release()\r\n" }, { "alpha_fraction": 0.5518925786018372, "alphanum_fraction": 0.6056166291236877, "avg_line_length": 29.33333396911621, "blob_id": "86bec1895ee04e6d0ae70f47976e2281e18a10c5", "content_id": "a19c2edf2da81976e2bee63c4bb98be8925bac85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 819, "license_type": "no_license", "max_line_length": 123, "num_lines": 27, "path": "/demo2.2_detect_cylinder/detection_rgbd/src/getCameraIntrincs.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 31.01.20.\n//\n\n#include <string>\n#include <iostream>\n#include <boost/format.hpp>\n#include <librealsense2/rs.hpp>\n\nusing namespace std;\n\nint main() {\n rs2::pipeline pipe;\n rs2::config cfg;\n cfg.enable_stream(RS2_STREAM_DEPTH, 1280, 720, RS2_FORMAT_Z16, 30);\n cfg.enable_stream(RS2_STREAM_COLOR, 1920, 1080, RS2_FORMAT_BGR8, 30);\n pipe.start(cfg);\n\n rs2::align align_to_color(RS2_STREAM_COLOR);\n\n auto const i = pipe.get_active_profile().get_stream(RS2_STREAM_COLOR).as<rs2::video_stream_profile>().get_intrinsics();\n cout << \"fx: \" << i.fx << endl;\n cout << \"fy: \" << i.fy << endl;\n cout << \"ppx: \" << i.ppx << endl;\n cout << \"ppy: \" << i.ppy << endl;\n cout << \"distortion \" << i.coeffs[0] << i.coeffs[1] << i.coeffs[2] << i.coeffs[3] << i.coeffs[4] << endl;\n}\n" }, { "alpha_fraction": 0.5696334838867188, "alphanum_fraction": 0.5926701426506042, "avg_line_length": 27.969696044921875, "blob_id": "a15717331f79455554405ca9e1dbfc8a4572224d", "content_id": "f07cb8b753a2beb730be0bd4d23ca1afc68dd32c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 955, "license_type": "no_license", "max_line_length": 108, "num_lines": 33, "path": "/demo4.1_tracking/tracking/main.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 18.02.20.\n//\n\n#include <iostream>\n#include <boost/format.hpp> // for formating strings\n#include <bitset>\n\n#include <opencv2/aruco/dictionary.hpp>\n\nusing namespace std;\n\nint main(int argc, char **argv) {\n// if (argc != 2) {\n// cout << \"please enter the file path.\" << endl;\n// return -1;\n// }\n cv::Ptr<cv::aruco::Dictionary> dictionary = cv::aruco::getPredefinedDictionary(cv::aruco::DICT_4X4_250);\n cv::Mat store=dictionary->bytesList;\n// cv::FileStorage fs(\"dic_save.yml\", cv::FileStorage::WRITE);\n// fs << \"MarkerSize\" << dictionary->markerSize;\n// fs << \"MaxCorrectionBits\" << dictionary->maxCorrectionBits;\n// fs << \"ByteList\" << dictionary->bytesList;\n// fs.release();\n\n for (int i = 0; i < store.rows; ++i) {\n cout << bitset<8>(store.at<uint8_t >(i, 0))\n << bitset<8>(store.at<uint8_t >(i, 1)) << endl;\n }\n\n cout << \"hello world.\" << endl;\n return 0;\n}" }, { "alpha_fraction": 0.5755919814109802, "alphanum_fraction": 0.6010928750038147, "avg_line_length": 17.266666412353516, "blob_id": "84459a2cf5cb9676948ce69cf29fb180a902ecda", "content_id": "fa6ed18dcc3273573b99a106e8fb37f964dec772", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 549, "license_type": "no_license", "max_line_length": 54, "num_lines": 30, "path": "/demo1_tello_aruco/cv_aruco/test_multi_thread.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "import threading\nimport time\nimport cv2\n\n\ndef get_image(delay):\n global frame\n global c\n capture = cv2.VideoCapture(0)\n while True:\n ret, frame = capture.read()\n cv2.waitKey(delay)\n\n\ndef show_image(delay):\n while True:\n if frame is None:\n cv2.waitKey(delay)\n else:\n cv2.imshow(\"img\", frame)\n cv2.waitKey(delay)\n\n\nframe = None\nt1 = threading.Thread(target=get_image, args=(2, ))\nt1.start()\n# t2 = threading.Thread(target=show_image, args=(2, ))\n# t2.start()\n\nshow_image(2)\n\n" }, { "alpha_fraction": 0.4351511597633362, "alphanum_fraction": 0.4942074120044708, "avg_line_length": 33.34951400756836, "blob_id": "28d1f0ad2ab2374f6f080a65861bd5cd458a0ea5", "content_id": "4de0fb23d8041a4aa321113bdae74d63c4d0a401", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3539, "license_type": "no_license", "max_line_length": 80, "num_lines": 103, "path": "/workshop/FCN_regression/main.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom matplotlib import pyplot as plt\nfrom math import sin\n\n\ndef generate_data(n, low=0.0, high=3.0):\n step = (high - low) / n\n x, y = [], []\n for i in range(n):\n x.append(low + step * i)\n y.append(sin(x[i] * x[i] + 1.) + np.random.normal(0.0, 0.1))\n return np.array(x), np.array(y)\n\n\ndef sigmoid(_x):\n return 1. / (1. + np.exp(-_x))\n\n\ndef model(_x, _theta):\n \"\"\"\n model architecture:\n input layer: m0 = 1\n theta[\"w1\"]: (50, 1), theta[\"b1\"]: (50, 1)\n hidden layer: m1 = 50, activation: sigmoid\n theta[\"w2\"]: (5, 50), theta[\"b2\"]: (5, 1)\n hidden layer: m2 = 5, activation: sigmoid\n theta[\"w3\"]: (1, 5), theta[\"b3\"]: (1, 1)\n output layer: m3 = 1\n \"\"\"\n x0 = np.array(_x).reshape([1, 1])\n x1 = sigmoid(np.dot(_theta[\"w1\"], x0) + _theta[\"b1\"])\n x2 = sigmoid(np.dot(_theta[\"w2\"], x1) + _theta[\"b2\"])\n x3 = np.dot(_theta[\"w3\"], x2) + _theta[\"b3\"]\n return x0, x1, x2, x3\n\n\ndef loss(_x, _y, _theta, _model):\n _loss = 0.0\n for i in range(len(_x)):\n _loss += (model(_x[i], _theta)[3][0][0] - _y[i]) ** 2\n return _loss / len(_x)\n\n\ndef gradient(_x, _y, _theta, _model):\n grad = {\"w1\": np.zeros((50, 1)), \"b1\": np.zeros((50, 1))\n , \"w2\": np.zeros((5, 50)), \"b2\": np.zeros((5, 1))\n , \"w3\": np.zeros((1, 5)), \"b3\": np.zeros((1, 1))}\n for i in range(len(_x)):\n x0, x1, x2, x3 = model(_x[i], _theta)\n # back propagation\n _loss_to_x3 = -2 * (np.array(_y[i]).reshape([1, 1]) - x3)\n grad[\"w3\"] += np.dot(_loss_to_x3.T, x2.T)\n grad[\"b3\"] += _loss_to_x3.T\n _x3_to_x2 = _theta[\"w3\"]\n _x2_to_a2 = np.diag((x2 - x2 * x2).reshape([5, ]))\n _loss_to_a2 = _loss_to_x3.dot(_x3_to_x2).dot(_x2_to_a2)\n grad[\"w2\"] += np.dot(_loss_to_a2.T, x1.T)\n grad[\"b2\"] += _loss_to_a2.T\n _a2_to_x1 = _theta[\"w2\"]\n _x1_to_a1 = np.diag((x1 - x1 * x1).reshape([50, ]))\n _loss_to_a1 = _loss_to_a2.dot(_a2_to_x1).dot(_x1_to_a1)\n grad[\"w1\"] += np.dot(_loss_to_a1.T, x0.T)\n grad[\"b1\"] += _loss_to_a1.T\n return grad\n\n\ndef train(_x, _y, _theta, _model, lr=1e-5, steps=1000):\n for step in range(steps):\n grad = gradient(_x, _y, _theta, _model)\n _theta[\"w1\"] -= lr * grad[\"w1\"]\n _theta[\"b1\"] -= lr * grad[\"b1\"]\n _theta[\"w2\"] -= lr * grad[\"w2\"]\n _theta[\"b2\"] -= lr * grad[\"b2\"]\n _theta[\"w3\"] -= lr * grad[\"w3\"]\n _theta[\"b3\"] -= lr * grad[\"b3\"]\n # print log\n if step % 100 == 0:\n print(\"step: %d, loss: %f\" % (step, loss(_x, _y, _theta, _model)))\n return _theta\n\n\nif __name__ == \"__main__\":\n x_train, y_train = generate_data(100)\n # plot x, y data\n plt.scatter(x_train, y_train, color=\"red\")\n # parameter init according to model\n # weight matrix initialization with uniform[0, 1] fails\n theta = {\"w1\": np.random.uniform(-1., 1., [50, 1]), \"b1\": np.zeros([50, 1])\n , \"w2\": np.random.uniform(-1., 1., [5, 50]), \"b2\": np.zeros([5, 1])\n , \"w3\": np.random.uniform(-1., 1., [1, 5]), \"b3\": np.zeros([1, 1])}\n # # plot original curve\n # y_plot = []\n # for value in x_train:\n # y_plot.append(model(value, theta)[3][0][0])\n # plt.plot(x_train, y_plot)\n # training\n theta_new = train(x_train, y_train, theta, model, lr=1e-3, steps=10000)\n # plot trained curve\n y_plot = []\n for value in x_train:\n y_plot.append(model(value, theta_new)[3][0][0])\n plt.plot(x_train, y_plot)\n plt.show()\n\n" }, { "alpha_fraction": 0.5786516666412354, "alphanum_fraction": 0.6610487103462219, "avg_line_length": 23.272727966308594, "blob_id": "1aeb898fc2399c187a38e0d63c0a0dbad288d3c8", "content_id": "ea21ebee4867c8aca67a9ef9e69ac28cf73f582c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 534, "license_type": "no_license", "max_line_length": 63, "num_lines": 22, "path": "/demo5.1_final/localization_and_mapping/code/marker_generation.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport cv2\nimport libs.lib_rs as rs\n\n# generation\ndic = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_6X6_250)\n\nfor i in range(250):\n image = cv2.aruco.drawMarker(dic, i, 2000)\n cv2.imwrite((\"../markers_6/%d.png\" % i), image)\n\n# test detect\n# cv2.namedWindow(\"color\", cv2.WINDOW_NORMAL)\n# cv2.resizeWindow(\"color\", 960, 540)\n#\n# d415 = rs.D415()\n#\n# while cv2.waitKey(50) != ord('q'):\n# corners, ids, color, color_drawn = d415.detect_aruco()\n# cv2.imshow(\"color\", color_drawn)\n#\n# d415.close()\n" }, { "alpha_fraction": 0.495571494102478, "alphanum_fraction": 0.5352172255516052, "avg_line_length": 34.3880615234375, "blob_id": "b771eb3aa6e963cc4ff561295a431b02b6d53dbd", "content_id": "cd1ac11975558678235dbe12cfe87e194e1752fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2371, "license_type": "no_license", "max_line_length": 102, "num_lines": 67, "path": "/demo2.1_detect_polygon/detection_dual/src/main.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "#include \"main.hpp\"\n\nint ITERATION_COUNT = 0;\n\nint main() {\n VideoCapture inputVideo(\"../../data/02.mov\");\n// VideoWriter writer;\n// writer.open(\"result.avi\", CV_FOURCC('M', 'J', 'P', 'G'), 36, Size(1280, 480), true);\n\n // for measuring running time\n struct timespec tpStart{};\n struct timespec tpEnd{};\n clock_gettime(CLOCK_MONOTONIC, &tpStart);\n\n while (true) {\n// if(ITERATION_COUNT == 301) break;\n Mat img;\n inputVideo >> img;\n if (img.empty()) break;\n Rect rectL(0, 0, 640, 480);\n Rect rectR(640, 0, 640, 480);\n Mat imgL = img(rectL), imgR = img(rectR);\n remap(imgL, imgL, C.mapL1, C.mapL2, CV_INTER_LINEAR);\n remap(imgR, imgR, C.mapR1, C.mapR2, CV_INTER_LINEAR);\n\n // left\n vector< vector<Point> > contoursL = getContours(imgL);\n drawContours(imgL, contoursL, -1, Scalar(0, 0, 255));\n // right\n vector< vector<Point> > contoursR = getContours(imgR);\n drawContours(imgR, contoursR, -1, Scalar(0, 0, 255));\n // matching\n vector< vector<Point3d> > polylines;\n if (validate(contoursL, contoursR, polylines))\n for (auto polyline : polylines) {\n sortPolyline(polyline);\n Pose pose = getPose(polyline);\n int index = match(polyline, pose);\n if (index != -1) {\n imgL = drawPose(imgL, pose, index, 15);\n cout << \"piece found: \" << pose.origin().t() << \" index:\" << index << endl;\n }\n }\n // show images\n// imshow(\"rawL\", imgL);\n// imshow(\"rawR\", imgR);\n// imwrite(\"rawL.png\", imgL);\n// imwrite(\"rawR.png\", imgR);\n// Mat output(480, 1280, img.type());\n// imgL.copyTo(output(Rect(0, 0, 640, 480)));\n// imgR.copyTo(output(Rect(640, 0, 640, 480)));\n// imshow(\"output\", output);\n// writer.write(output);\n\n// char key = (char) waitKey(1);\n// if (key == 27)\n// break;\n ITERATION_COUNT += 1;\n cout << ITERATION_COUNT << endl;\n }\n // for measuring running time\n clock_gettime(CLOCK_MONOTONIC, &tpEnd);\n long timedif = 1000000*(tpEnd.tv_sec - tpStart.tv_sec) + (tpEnd.tv_nsec - tpStart.tv_nsec) / 1000;\n fprintf(stdout, \"it took %ld microseconds\\n\", timedif);\n\n return 0;\n}\n" }, { "alpha_fraction": 0.6585366129875183, "alphanum_fraction": 0.6771196126937866, "avg_line_length": 20, "blob_id": "9680392cf64ecfd6e91570aeb553ee422d76fa8d", "content_id": "57ae082754adf2637d088a00920d0e9c9219fb4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 861, "license_type": "no_license", "max_line_length": 58, "num_lines": 41, "path": "/demo3.1_validate_in_process_scan/physical_setup/arduino/test_servo/test_servo.ino", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "#include<Servo.h>\nServo myservo;\n\n//define button pin\nint buttonPin = 7;\n\n// define angles\nint angleCount = 4;\nint angles[] = {90, 45, 90, 135};\nint angleIndex = 0;\n\n//define button states\nbool lastState = LOW;\nbool currentState = LOW;\n\nvoid setup() {\n //set pin modes\n pinMode(buttonPin, OUTPUT);\n myservo.attach(9);\n}\n\nvoid loop() {\n currentState = readButtonDebounce(lastState, buttonPin);\n if (currentState == HIGH && lastState == LOW) {\n lastState = HIGH;\n myservo.write(angles[angleIndex]);\n angleIndex = (angleIndex+1) % angleCount;\n }\n if (currentState == LOW && lastState == HIGH) {\n lastState = LOW;\n }\n}\n\nbool readButtonDebounce(bool lastState, int buttonPin) {\n bool currentState = digitalRead(buttonPin);\n if (lastState != currentState) {\n delay(10);\n currentState = digitalRead(buttonPin);\n }\n return currentState;\n}\n" }, { "alpha_fraction": 0.8436577916145325, "alphanum_fraction": 0.8466076850891113, "avg_line_length": 42.774192810058594, "blob_id": "4ce33909e1830cab38870983f9beb3c0836c04cf", "content_id": "aa05f2c6123da747b4b6d2bbe4e354321b43df92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1356, "license_type": "no_license", "max_line_length": 74, "num_lines": 31, "path": "/demo2.2_detect_cylinder/detection_rgbd/src/CMakeLists.txt", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "add_executable(main main.cpp)\ntarget_link_libraries(main PRIVATE libkinect)\ntarget_link_libraries(main PRIVATE libpose)\ntarget_link_libraries(main PRIVATE libvision)\ntarget_link_libraries(main PRIVATE libpointCloud)\n# link librealsense2 package\ntarget_link_libraries(main PRIVATE ${realsense2_LIBRARY})\n\nadd_executable(takeFrameKinect takeFrameKinect.cpp)\ntarget_link_libraries(takeFrameKinect PRIVATE libkinect)\n\nadd_executable(takeFrameRealsense takeFrameRealsense.cpp)\ntarget_link_libraries(takeFrameRealsense PRIVATE libpointCloud)\ntarget_link_libraries(takeFrameRealsense PRIVATE ${realsense2_LIBRARY})\ntarget_link_libraries(takeFrameRealsense PRIVATE ${OpenCV_LIBS})\ntarget_link_libraries(takeFrameRealsense PRIVATE ${PCL_LIBRARIES})\n\nadd_executable(segmentCloud segmentCloud.cpp)\ntarget_link_libraries(segmentCloud PRIVATE libpointCloud)\ntarget_link_libraries(segmentCloud PRIVATE ${PCL_LIBRARIES})\n\nadd_executable(fitting fitting.cpp)\ntarget_link_libraries(fitting PRIVATE libpointCloud)\ntarget_link_libraries(fitting PRIVATE ${PCL_LIBRARIES} ${CERES_LIBRARIES})\n\nadd_executable(getCameraIntrincs getCameraIntrincs.cpp)\ntarget_link_libraries(getCameraIntrincs PRIVATE ${realsense2_LIBRARY})\n\nadd_executable(mergeCloud mergeCloud.cpp)\ntarget_link_libraries(mergeCloud PRIVATE libpointCloud)\ntarget_link_libraries(mergeCloud PRIVATE ${PCL_LIBRARIES})" }, { "alpha_fraction": 0.3180404305458069, "alphanum_fraction": 0.39307931065559387, "avg_line_length": 40.48387145996094, "blob_id": "658e59e390cbcd6f75de1e3db67a0f98de2908e2", "content_id": "dc8e5561f09496c6f424c1f92124657d64f7654d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5152, "license_type": "no_license", "max_line_length": 167, "num_lines": 124, "path": "/demo3.1_validate_in_process_scan/detection/result/performance.md", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "# Performance documantation of sensing algorithms\n\n## **Realsense 415 (camera held by hand)**\n\n```mermaid\ngraph TD\n A(color frames) --detection--> B(aruco marker poses)\n C(depth frames) --3d reconstruction--> D(dense clouds)\n D --downsample--> E(sparse clouds)\n E --icp--> F(aligned cloud)\n F --crop--> G(cylinder cloud rough)\n B --provide coordinate--> G\n G --ransac--> H(cylinder cloud)\n H --least square fitting--> I(cylinder parameter)\n```\n\nResolution is set to **1920*1080**. Leaf size for downsampling is set to **2mm**. Radius ground truth is **9.76mm**, which is the arithmetic average of 6 measurements.\n\nTime used(cpu:Intel(R) Xeon(R) CPU_E3-1231 v3 @ 3.40GHz): \n- aruco marker detection: insignificant\n- 3d reconstruction: 0.57s per frame (16 measurements)\n- downsampling: 0.11s per frame (16 measurements)\n- ICP: 3.4s per frame from second frame on (16 measurements)\n- crop: insignificant\n- RANSAC: insignificant\n- fitting: insignificant\n\n| Number of frames | Estimated radius | Error |\n| :--------------: | :--------------: | :------------: |\n| 1 | 11.25mm | 1.49mm(15.3%) |\n| 4 | 11.11mm | 1.35mm(13.8%) |\n| 16 | 9.59mm | -0.17mm(1.7%) |\n| 32 | 7.63mm | -2.13mm(21.8%) |\n\n**Conclusion:** \n  clouds not nicely aligned, need better icp algorithm\n\n---\n\n## **Realsense 415 (camera fixed on tripod)**\n\nSame workflow, except that ICP is no longer required.\n\n| Number of frames | Estimated radius | Error |\n| :--------------: | :--------------: | :------------: |\n| 1 | 12.39mm | 2.63mm(26.9%) |\n| 4 | 10.82mm | 1.06mm(10.9%) |\n| 8 | 7.97mm | -1.79mm(18.3%) |\n| 16 | 8.64mm | -1.12mm(11.5%) |\n| 24 | 8.53mm | -1.23mm(12.6%) |\n| 32 | 8.43mm | -1.33mm(13.6%) |\n\n---\n\n## **Realsense 415 (camera fixed on tripod)**\n\n```mermaid\ngraph TD\n A(color frame) --detection--> B(aruco marker poses)\n C(depth frames) --arithmetic average--> D(depth frame denoised)\n D --3d resonstruction--> E(cloud)\n E --crop--> G(cylinder cloud rough)\n B --provide coordinate--> G\n G --ransac--> H(cylinder cloud)\n H --least square fitting--> I(cylinder parameter)\n```\n\n**Main difference:** \n  Only 1 color frame is used, and multiple depth frame are taken and arithmetic average is computed for denoising. So no need for cloud registrition.\n\n**fast:**\n\n| Number of depth frames | Estimated radius (0-depth point excluded) | Error |\n| :--------------------: | :---------------------------------------: | :-----------: |\n| 1 | 10.72mm (10.72mm) | |\n| 20 | 11.65mm (10.65mm) | |\n| 40 | 11.67mm (10.36mm) | |\n| 60 | 10.36mm (10.38mm) | |\n| 80 | 11.21mm (14.14mm) | |\n| 100 | 9.67mm (10.54mm) | -0.09mm(0.9%) |\n\n**slow:**\n\n| Number of depth frames | Estimated radius | Error |\n| :--------------------: | :--------------: | :---: |\n| 1 | 10.62mm | |\n| 20 | 9.47mm | |\n| 40 | 10.46mm | |\n| 60 | 7.90mm | |\n| 80 | 9.59mm | |\n| 100 | 7.79mm | |\n\n**fast with 20mm segment(ground truth: 9.70*10.5):**\n\n| Number of depth frames | Estimated radius | Error |\n| :--------------------: | :--------------: | :---: |\n| 1 | 12.83mm | |\n| 20 | 14.08mm | |\n| 40 | 13.38mm | |\n| 60 | 13.50mm | |\n| 80 | 14.58mm | |\n| 100 | 13.40mm | |\n\n**fast with 40mm segment(ground truth: 9.70*10.5):**\n\n| Number of depth frames | Estimated radius | Error |\n| :--------------------: | :--------------: | :---: |\n| 1 | 10.53mm | |\n| 20 | 12.10mm | |\n| 40 | 11.38mm | |\n| 60 | 11.42mm | |\n| 80 | 11.38mm | |\n| 100 | 11.39mm | |\n\n**fast with 80mm segment(ground truth: 9.70*10.5):**\n\n| Number of depth frames | Estimated radius | Error |\n| :--------------------: | :--------------: | :---: |\n| 1 | 10.53mm | |\n| 20 | 10.50mm | |\n| 40 | 10.57mm | |\n| 60 | 10.48mm | |\n| 80 | 10.27mm | |\n| 100 | 11.22mm | |\n" }, { "alpha_fraction": 0.5350461006164551, "alphanum_fraction": 0.55319744348526, "avg_line_length": 32.47663497924805, "blob_id": "625be5253245cae97d974a0551e60d31707264f5", "content_id": "2ec42fe86450a5ddbc58b193084c0bdd8f6a6708", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3581, "license_type": "no_license", "max_line_length": 124, "num_lines": 107, "path": "/workshop/pytorch/CNN_MNIST/main.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "from torch import nn, optim, cuda\nfrom torch.utils import data\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms\nimport time\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n# training settings\nbatch_size = 64\ndevice = 'cuda' if cuda.is_available() else 'cpu'\nprint(f'Training MNIST Model on {device} \\n{\"=\" * 44}')\n\n# MNIST Dataset\ntrain_dataset = datasets.MNIST('./data',\n train=True,\n transform=transforms.ToTensor(),\n download=True)\ntest_dataset = datasets.MNIST('./data',\n train=False,\n transform=transforms.ToTensor(),\n download=True)\n\n# data loader\ntrain_loader = data.DataLoader(train_dataset,\n batch_size,\n shuffle=True)\ntest_loader = data.DataLoader(test_dataset,\n batch_size,\n shuffle=False)\n\n\n# build neural networks\nclass Net(nn.Module):\n\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(1, 10, kernel_size=5)\n self.conv2 = nn.Conv2d(10, 20, kernel_size=5)\n self.mp = nn.MaxPool2d(kernel_size=2)\n self.fc = nn.Linear(320, 10)\n\n def forward(self, x):\n in_size = x.size(0)\n x = F.relu(self.mp(self.conv1(x)))\n x = F.relu(self.mp(self.conv2(x)))\n x = x.view(in_size, -1)\n x = self.fc(x)\n return F.log_softmax(x)\n\n\n# my model\nmodel = Net()\nmodel.to(device)\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.SGD(model.parameters(), lr=1e-2, momentum=0.5)\n\n\n# training step\ndef train(epoch):\n model.train() # set model to training mode\n for batch_idx, (data, target) in enumerate(train_loader, 0):\n # send to gpu\n data, target = data.to(device), target.to(device)\n # training: zero grad -> calculate loss -> back propagate -> go one step\n optimizer.zero_grad()\n output = model(data)\n loss = criterion(output, target)\n loss.backward()\n optimizer.step()\n if batch_idx % 10 == 0:\n print('Train Epoch: {} | Batch Status: {}/{} ({: .0f}%) | Loss: {: .06f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100 * batch_idx / len(train_loader), loss.item()))\n\n\n# testing step\ndef test():\n model.eval() # set model to evaluation mode\n test_loss = 0\n correct = 0\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n loss = criterion(output, target)\n test_loss += loss.item()\n pred = output.data.max(1, keepdim=True)[1]\n correct += pred.eq(target.data.view_as(pred)).cpu().sum()\n\n test_loss /= len(test_loader.dataset)\n print(\n f'========================\\nTest set: Average Loss: {test_loss:.4f}, Accuracy: {correct}/{len(test_loader.dataset)}'\n f'({100. * correct / len(test_loader.dataset):.0f}%)')\n\n\nif __name__ == \"__main__\":\n since = time.time()\n for epoch in range(0, 9):\n epoch_start = time.time()\n train(epoch)\n m, s = divmod(time.time() - epoch_start, 60)\n print(f'Training time: {m:.0f}m {s:.0f}s')\n test()\n m, s = divmod(time.time() - epoch_start, 60)\n print(f'Testing time: {m:.0f}m {s:.0f}s')\n m, s = divmod(time.time() - since, 60)\n print(f'Total Time: {m:.0f}m {s:.0f}s\\nModel was trained on {device}')" }, { "alpha_fraction": 0.6499754786491394, "alphanum_fraction": 0.6936671733856201, "avg_line_length": 24.78481101989746, "blob_id": "92fbccb5d8854ba0456bd736e7ed01f3bc9fb05c", "content_id": "003ed4dd5f3f38ec3be73306d4d2ff7ea9dc99a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2037, "license_type": "no_license", "max_line_length": 105, "num_lines": 79, "path": "/demo3.1_validate_in_process_scan/physical_setup/arduino/group_2/group_2.ino", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "#include<Servo.h>\n#include <AccelStepper.h>\n\n// all the defines\n#define SERVO_PIN 9\n#define BUTTON_PIN 7\n#define HOME_SWITCH 7\n#define MOTOR_INTERFACE_TYPE 1\n#define STEPPER_DIR_PIN 4\n#define STEPPER_STEP_PIN 5\n#define STEPPER_STEPS 800\n#define STEPPER_SPEED 200\n\nServo servo;\nAccelStepper stepper(MOTOR_INTERFACE_TYPE, STEPPER_STEP_PIN, STEPPER_DIR_PIN);\n\n// define angles\nint poseCount = 3;\ndouble angles[] = {90-35, 90+12.98, 90-0.0}; // (90+x)in degree, x is givin frmon gh, -35 for scan \ndouble positions[] = {0, -(63.9-59), -(239.64-59)}; // (x-59)in milimeter, x is given from gh, 0 for scan\n\nvoid setup() {\n //set pin modes\n pinMode(BUTTON_PIN, INPUT);\n pinMode(HOME_SWITCH, INPUT);\n servo.attach(SERVO_PIN);\n stepper.setSpeed(STEPPER_SPEED);\n // init stepper\n home(stepper, HOME_SWITCH);\n stepper.setMaxSpeed(4000);\n stepper.setAcceleration(2000);\n delay(2000);\n}\n\nint poseIndex = 0;\n\n//define button states\nbool lastState = LOW;\nbool currentState = LOW;\n\nvoid loop() {\n currentState = readButtonDebounce(lastState, BUTTON_PIN);\n if (currentState == HIGH && lastState == LOW) {\n lastState = HIGH;\n servo.write(angles[poseIndex]);\n stepper.runToNewPosition(positions[poseIndex]/40.0*6400); // 6400 steps per round, 40mm per round\n poseIndex = (poseIndex+1) % poseCount;\n }\n if (currentState == LOW && lastState == HIGH) {\n lastState = LOW;\n }\n}\n\nvoid home(AccelStepper stepper, int homeSwitch) {\n int initialHoming = 1;\n while (!digitalRead(homeSwitch)) {\n stepper.setMaxSpeed(3000);\n stepper.setAcceleration(1000);\n stepper.moveTo(initialHoming);\n stepper.run();\n initialHoming += 1;\n delay(1);\n }\n while (digitalRead(homeSwitch)) {\n stepper.moveTo(initialHoming);\n stepper.run();\n initialHoming -= 1;\n }\n stepper.setCurrentPosition(0);\n}\n\nbool readButtonDebounce(bool lastState, int buttonPin) {\n bool currentState = digitalRead(buttonPin);\n if (lastState != currentState) {\n delay(10);\n currentState = digitalRead(buttonPin);\n }\n return currentState;\n}\n" }, { "alpha_fraction": 0.49687498807907104, "alphanum_fraction": 0.542187511920929, "avg_line_length": 34.56666564941406, "blob_id": "77968801f777647f8a12a77db8fe47ecaf171f34", "content_id": "1b21036e6aa9c52d460412a7be49445576c49e0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3484, "license_type": "no_license", "max_line_length": 135, "num_lines": 90, "path": "/demo2.2_detect_cylinder/detection_2.0/fitting.cpp", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "//\n// Created by yue on 31.01.20.\n//\n\n#include <iostream>\n#include <chrono>\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <ceres/ceres.h>\n\nusing namespace std;\n\n// 代价函数的计算模型\nstruct CYLINDER_FITTING_COST {\n CYLINDER_FITTING_COST(double x1, double x2, double x3) : _x1(x1), _x2(x2), _x3(x3){}\n\n // 残差的计算\n template<typename T>\n bool operator()(\n const T *const theta, // 模型参数,有7维\n T *residual) const {\n residual[0] = ceres::sqrt((T(_x1)-theta[1])*(T(_x1)-theta[1])\n + (T(_x2)-theta[2])*(T(_x2)-theta[2])\n + (T(_x3)-theta[3])*(T(_x3)-theta[3])\n - ceres::pow((T(_x1)-theta[1])*theta[4]\n + (T(_x2)-theta[2])*theta[5]\n + (T(_x3)-theta[3])*theta[6], 2) / (theta[4]*theta[4]+theta[5]*theta[5]+theta[6]*theta[6])) - theta[0]; // r-sqrt(...)\n return true;\n }\n\n const double _x1, _x2, _x3; // x数据\n};\n\nint main(int argc, char **argv) {\n// double t1 = 0.019792, t2 = 0.0742702, t3 = 0.113163, t4 = 0.416911, t5 = -0.478734, t6 = 0.859715, t7 = 0.178054; // 估计参数值\n if (argc != 9) {\n cout << \"please enter the file path and initial cylinder parameters.\" << endl;\n return -1;\n }\n double t1=stod(argv[2]), t2=stod(argv[3]), t3=stod(argv[4]), t4=stod(argv[5])\n , t5=stod(argv[6]), t6=stod(argv[7]), t7=stod(argv[8]);\n\n pcl::PCDReader reader;\n pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);\n reader.read (argv[1], *cloud);\n\n int N = cloud->points.size (); // 数据点\n\n vector<double> x1_data, x2_data, x3_data; // 数据\n for (int i = 0; i < N; i++) {\n x1_data.push_back(cloud->points[i].x);\n x2_data.push_back(cloud->points[i].y);\n x3_data.push_back(cloud->points[i].z);\n }\n\n double theta[7] = {t1, t2, t3, t4, t5, t6, t7};\n\n // 构建最小二乘问题\n ceres::Problem problem;\n for (int i = 0; i < N; i++) {\n problem.AddResidualBlock( // 向问题中添加误差项\n // 使用自动求导,模板参数:误差类型,输出维度,输入维度,维数要与前面struct中一致\n new ceres::AutoDiffCostFunction<CYLINDER_FITTING_COST, 1, 7>(\n new CYLINDER_FITTING_COST(x1_data[i], x2_data[i], x3_data[i])\n ),\n nullptr, // 核函数,这里不使用,为空\n theta // 待估计参数\n );\n }\n\n // 配置求解器\n ceres::Solver::Options options; // 这里有很多配置项可以填\n options.linear_solver_type = ceres::DENSE_NORMAL_CHOLESKY; // 增量方程如何求解\n options.minimizer_progress_to_stdout = true; // 输出到cout\n\n ceres::Solver::Summary summary; // 优化信息\n chrono::steady_clock::time_point t_start = chrono::steady_clock::now();\n ceres::Solve(options, &problem, &summary); // 开始优化\n chrono::steady_clock::time_point t_end = chrono::steady_clock::now();\n chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t_end - t_start);\n cout << \"solve time cost = \" << time_used.count() << \" seconds. \" << endl;\n\n // 输出结果\n cout << summary.BriefReport() << endl;\n cout << \"estimated theta = \";\n for (auto a:theta) cout << a << \" \";\n cout << endl;\n\n return 0;\n}" }, { "alpha_fraction": 0.48310527205467224, "alphanum_fraction": 0.526110053062439, "avg_line_length": 29.870689392089844, "blob_id": "f5ec9b8edbb42afb707a1d2c7a7c9b677790c354", "content_id": "285f7b9571731ec76ac4fb1e7ad461eda845b738", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3597, "license_type": "no_license", "max_line_length": 107, "num_lines": 116, "path": "/workshop/SVM/soft_margin.py", "repo_name": "dbddqy/machine_perception", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom cvxopt import solvers, matrix\nfrom matplotlib import pyplot as plt\n\n\ndef generate_data(n, p=1.0):\n # p: percentage of data for training\n\n # x11 = np.random.multivariate_normal([4., 3.], [[4., 0.], [0., 1.]], int(0.5*n))\n # x12 = np.random.multivariate_normal([2., -2.], [[1., 0.], [0., 2.]], int(0.25*n))\n # x13 = np.random.multivariate_normal([7., -4.], [[1., 0.], [0., 1.]], int(0.25*n))\n # x1 = np.vstack((x11, x12, x13))\n x1 = np.random.multivariate_normal([4., 3.], [[.4, 0.], [0., .1]], int(1.0*n)) # simple case\n\n plt.scatter(x1.T[0], x1.T[1], color=\"red\")\n x2 = np.random.multivariate_normal([6., 0.], [[1.5, .5], [.5, 1.5]], int(1.0*n))\n plt.scatter(x2.T[0], x2.T[1], color=\"blue\")\n # combine data\n x = np.vstack((x1, x2))\n y = np.asarray([[1.]] * n + [[-1.]] * n)\n # shuffle data\n shuffle_idx = np.arange(0, n*2)\n np.random.shuffle(shuffle_idx)\n x_shuffled = x[shuffle_idx]\n y_shuffled = y[shuffle_idx]\n # split data into training and testing\n _x_train = x_shuffled[0:int(n * p)*2]\n _y_train = y_shuffled[0:int(n * p)*2]\n _x_test = x_shuffled[int(n * p)*2:n*2]\n _y_test = y_shuffled[int(n * p)*2:n*2]\n return _x_train, _y_train, _x_test, _y_test\n\n\ndef kernel_RBF(x1, x2, _gamma):\n return np.exp(-_gamma * np.sum((x1 - x2) * (x1 - x2)))\n\n\ndef kernel_polynomial(x1, x2, _gamma):\n return (1 + np.sum(x1*x2)) ** 2\n\n\ndef kernel_linear(x1, x2, _gamma):\n return np.sum(x1 * x2)\n\n\ndef get_P_Mat(x, y, n, kernel, _gamma):\n _P = np.zeros([n, n], dtype=np.float)\n for i in range(n):\n for j in range(n):\n _P[i][j] = y[i][0] * y[j][0] * kernel(x[i].T, x[j].T, _gamma)\n return _P\n\n\ndef plot_boundary(_alpha, x, y, _w0, kernel, _gamma, _color):\n x_plot = np.arange(-2., 10., .1)\n y_plot = np.arange(-6., 6., .1)\n x_plot, y_plot = np.meshgrid(x_plot, y_plot)\n f = np.zeros(x_plot.shape)\n for i in range(x_plot.shape[0]):\n for j in range(x_plot.shape[1]):\n x_to_classify = np.array([x_plot[i][j], y_plot[i][j]])\n f[i][j] = _w0\n for index in range(_alpha.shape[0]):\n f[i][j] += (_alpha[index][0] * y[index][0] * kernel(x[index], x_to_classify, _gamma))\n print(f[i][j])\n plt.contour(x_plot, y_plot, f, 0, colors=_color)\n\n\nif __name__ == \"__main__\":\n n = 60\n x_train, y_train, x_test, y_test = generate_data(n)\n\n gamma = 1\n kernel = kernel_RBF\n C = 10\n P_Mat = get_P_Mat(x_train, y_train, n * 2, kernel=kernel, _gamma=gamma)\n\n # optimizaton\n P = matrix(P_Mat)\n q = matrix(-np.ones([n*2, 1]))\n # 2*n inequality constraints\n G = matrix(np.vstack([-np.eye(n*2), np.eye(n*2)]))\n h = matrix(np.vstack([np.zeros([n*2, 1]), C*np.ones([n*2, 1])]))\n # 1 equality constraint\n A = matrix(y_train.T)\n b = matrix(0.)\n\n sol = solvers.qp(P, q, G, h, A, b) # 调用优化函数solvers.qp求解\n alpha = np.array(sol['x'])\n\n # get SVs and SOs\n SV, SO = [], []\n for i in range(n*2):\n if alpha[i][0] < 0.001:\n continue\n if abs(alpha[i][0]-C) > 0.001:\n SV.append(i)\n SO.append(i)\n print(alpha[SV].shape)\n print(\"______\")\n print(alpha[SO].shape)\n # print(SV)\n # print(x_train[SV])\n\n # calculate b\n w0 = 0.\n for i in SV:\n w0 += y_train[i][0]\n for j in SO:\n w0 -= alpha[j][0] * y_train[j][0] * P_Mat[j][i]\n w0 /= len(SV)\n print(w0)\n\n plot_boundary(alpha[SO], x_train[SO], y_train[SO], w0, kernel=kernel, _gamma=gamma, _color=\"lightblue\")\n\n plt.show()\n" } ]
138
hermanoaraujo/Python-Object-Oriented
https://github.com/hermanoaraujo/Python-Object-Oriented
b466d0abeddc91736db95398bdab5ba82f71a3a7
f56dae71dc33cd46ebf817152180eb1e9e629495
28a2248eae46d55f6b8e3caf3d9dd08fcef31cf7
refs/heads/master
2020-04-04T15:14:39.441475
2018-11-04T00:30:55
2018-11-04T00:30:55
156,030,126
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.6366994976997375, "alphanum_fraction": 0.6416256427764893, "avg_line_length": 25.19354820251465, "blob_id": "5a578c043e30930c40f304d4e00c109ca37a0686", "content_id": "d4efcc044493ee5a14f2583a55aab6b940246a7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 812, "license_type": "no_license", "max_line_length": 54, "num_lines": 31, "path": "/Introduction to Class/Class-Calculator/classes.py", "repo_name": "hermanoaraujo/Python-Object-Oriented", "src_encoding": "UTF-8", "text": "class Calculadora:\n DESCRIPTION = \"Basic Calculator v1\"\n def __init__(self,valor=0):\n self.__undo = 0\n self.__registrador = valor\n \n def getRegistrador(self):\n return self.__registrador\n\n def somar(self,numero):\n self.__undo = self.__registrador\n self.__registrador += numero\n\n def multiplicar(self,numero):\n self.__undo = self.__registrador\n self.__registrador = (self.__registrador * numero)\n \n def dividir(self,numero):\n self.__undo = self.__registrador\n self.__registrador = (self.__registrador / numero)\n \n def subtrair(self,numero):\n self.__undo = self.__registrador\n self.__registrador = (self.__registrador - numero)\n \n def reset(self):\n self.__undo = self.__registrador\n self.__registrador = 0\n \n def undo(self):\n self.__registrador = self.__undo\n" }, { "alpha_fraction": 0.7681528925895691, "alphanum_fraction": 0.7796178460121155, "avg_line_length": 48.0625, "blob_id": "65d79b37cf9a824cdd607dad28714d45b08b8a63", "content_id": "0bed7bd12fa769629070291f9ad3f5d779ac6400", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 785, "license_type": "no_license", "max_line_length": 161, "num_lines": 16, "path": "/README.md", "repo_name": "hermanoaraujo/Python-Object-Oriented", "src_encoding": "UTF-8", "text": "# Structured and object-oriented programming learning\n\n----\n## What will you find here?\n\n> In this repository you will find some exercises solved by [Hermano Filho](https://www.linkedin.com/in/hermanofilho/), student of the Computer Networks course at IFPB.\n\n----\n## Category\n1. [Introduction to Class](https://github.com/hermanoaraujo/Python-Object-Oriented/tree/master/Introduction%20to%20Class)\n2. [Herance](https://github.com/hermanoaraujo/Python-Object-Oriented/tree/master/Herance)\n3. [Class Abstract](https://github.com/hermanoaraujo/Python-Object-Oriented/tree/master/Class-Abstract)\n4. [Polimorfism](https://github.com/hermanoaraujo/Python-Object-Oriented/tree/master/Polimorfism)\n5. [Exceptions](https://github.com/hermanoaraujo/Python-Object-Oriented/tree/master/Exceptions)\n\n----\n" }, { "alpha_fraction": 0.5558739304542542, "alphanum_fraction": 0.5902578830718994, "avg_line_length": 24.560976028442383, "blob_id": "6dfce93ce7785a539169ab4c510b957127a0d3e7", "content_id": "cb04a2b708d74fe00a095f3edab125d3eae20269", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1047, "license_type": "no_license", "max_line_length": 73, "num_lines": 41, "path": "/Introduction to Class/Class-Deck/deckClass.py", "repo_name": "hermanoaraujo/Python-Object-Oriented", "src_encoding": "UTF-8", "text": "from importsConfig import *\n\n## Classe do Baralho\nclass Deck:\n __numberOfDecks = 0\n\n def __init__(self):\n self.deck = []\n self.suits = [\"\\u2661\",\"\\u2664\",\"\\u2667\",\"\\u2662\"]\n self.numbers = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']\n Deck.__numberOfDecks += 1\n \n def createDeck(self):\n \n for i in range(len(self.suits)):\n for j in range(len(self.numbers)):\n self.deck.append(Card(self.numbers[j],self.suits[i]))\n \n def getDeck(self):\n for i in range(len(self.deck)):\n print (self.deck[i])\n \n def shuffleDeck(self):\n shuffle(self.deck)\n \n def distributeCards(self,numberOfPlayers=4):\n self.numberCards = int(len(self.deck)/numberOfPlayers)\n self.cont = 0\n\n for i in range(numberOfPlayers):\n print(\"\\nPlayer\", i+1 , \"Received: \",self.numberCards,\" Cards\")\n print(\"=\"*35)\n\n for j in range(self.numberCards):\n print(self.deck[self.cont],)\n self.cont += 1\n print(\"=\"*35)\n\n @classmethod\n def countDecks(cls):\n return cls.__numberOfDecks" }, { "alpha_fraction": 0.6325503587722778, "alphanum_fraction": 0.6585570573806763, "avg_line_length": 19.929824829101562, "blob_id": "5065a0d1a288d99f95f957638885b0e6b46f3ae9", "content_id": "39772b6bf55453f1c13d018e9610c02301d1def9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1194, "license_type": "no_license", "max_line_length": 76, "num_lines": 57, "path": "/Introduction to Class/Videogame-Class/videogameClass.py", "repo_name": "hermanoaraujo/Python-Object-Oriented", "src_encoding": "UTF-8", "text": "from datetime import date\n\nclass Videogame:\n\n NUM_SERIE = 20180000\n\n def __init__(self,data_fabricacao=date.today(),marca=\"Sony\",modelo=\"PS4\"):\n self.data_fabricacao = data_fabricacao\n self.marca = marca\n self.modelo = modelo\n\n self.hd = 500\n self.jogos_instalados = 0\n self.anos_garantia = 1\n\n Videogame.NUM_SERIE +=1\n\n\n def setHD(self,novoHD):\n self.hd = novoHD\n \n def getHD(self):\n return self.hd\n\n def setJogos(self,numJogos):\n self.jogos_instalados = numJogos\n \n def getNumJogos(self):\n return self.jogos_instalados\n\n def setGarantia(self,garantia):\n self.anos_garantia = garantia\n \n def getGarantia(self):\n return self.anos_garantia\n \n def showDados(self):\n print(f\"Ano de Fabricação: {self.data_fabricacao}\")\n print(f\"Marca: {self.marca}\")\n print(f\"Modelo: {self.modelo}\")\n print(f\"HD: {self.hd} GB\")\n print(f\"Jogos Instalados: {self.jogos_instalados}\")\n print(f\"Garantia: {self.getGarantia()} ano\")\n print(f\"Numero de Serie: {self.NUM_SERIE}\")\n print(\"\")\n print(\"=\"*30)\n\n\n\nv1 = Videogame()\nv1.showDados()\n\nv2 = Videogame(\"2008\")\nv2.showDados()\n\nv3 = Videogame(\"2012\",\"Microsoft\",\"Xbox One\")\nv3.showDados()" }, { "alpha_fraction": 0.5642458200454712, "alphanum_fraction": 0.6312848925590515, "avg_line_length": 16.799999237060547, "blob_id": "b9270cff193d52eadf6e3be7fe40a30ed8b01264", "content_id": "0eabe29253af50e6422f729aa724bf0b150fa4da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 179, "license_type": "no_license", "max_line_length": 29, "num_lines": 10, "path": "/Class-Abstract/principal.py", "repo_name": "hermanoaraujo/Python-Object-Oriented", "src_encoding": "UTF-8", "text": "from funcionario import *\n\ng = Gerente(\"Hermano\",1500)\np = Presidente(\"Steve Jobs\",5000)\nd = Diretor(\"Trump\",2000)\n\n\nfor obj in [g,p,d]:\n obj.addBonificacao()\n print(obj,\"\\n\")\n\n" }, { "alpha_fraction": 0.6007866263389587, "alphanum_fraction": 0.6086528897285461, "avg_line_length": 34.057472229003906, "blob_id": "f0ab9311cd449f297be7e4ac8efc049f7d2918a9", "content_id": "03d47f6d8b9f04b1d2407d76ab14cf2d81729a18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3052, "license_type": "no_license", "max_line_length": 122, "num_lines": 87, "path": "/Class-Abstract/funcionario.py", "repo_name": "hermanoaraujo/Python-Object-Oriented", "src_encoding": "UTF-8", "text": "from abc import ABC, abstractmethod\n\nclass Funcionario(ABC):\n\n def __init__(self, nome, salarioBase):\n self.__nome = nome\n self.__salarioBase = salarioBase\n self.__grauInstrucao = \"Não Definido\"\n self.__bonificacao = 0\n\n def getNome(self):\n return self.__nome\n\n def setNome(self, novoNome):\n self.__nome = novoNome\n\n def getSalario(self):\n return self.__salarioBase\n\n def setSalario(self, novoSalario):\n self.__salarioBase = novoSalario\n\n def getGrauInstrucao(self):\n return self.__grauInstrucao\n\n def setGrauInstrucao(self,grau):\n self.__grauInstrucao = grau\n\n def setBonificacao(self,bonus):\n self.__bonificacao = bonus\n\n def getBonificacao(self):\n return self.__bonificacao\n\n def __str__(self):\n return f\"Sou um objeto da class {self.__class__.__name__},\\n Me Chamo: {self.__nome} e ganho {self.__salarioBase}\"\n\n @abstractmethod\n def addBonificacao(self):\n pass\n\n def contracheque(self):\n return (self.__salarioBase + self.__bonificacao)\n\nclass Gerente(Funcionario):\n\n def addBonificacao(self):\n\n self.bonus = 0.30\n\n if (super().getGrauInstrucao() == \"Especialista\"):\n super().setBonificacao(super().getSalario()*(self.bonus+0.15))\n super().setSalario(super().getSalario()+super().getBonificacao())\n elif (super().getGrauInstrucao() == \"Mestre\"):\n super().setBonificacao(super().getSalario() * (self.bonus + 0.25))\n super().setSalario(super().getSalario() + super().getBonificacao())\n elif (super().getGrauInstrucao() == \"Doutor\"):\n super().setBonificacao(super().getSalario() * (self.bonus + 0.50))\n super().setSalario(super().getSalario() + super().getBonificacao())\n else:\n super().setBonificacao(super().getSalario() * self.bonus)\n super().setSalario(super().getSalario() + super().getBonificacao())\n\n\nclass Presidente(Funcionario):\n\n def addBonificacao(self):\n\n if (super().getGrauInstrucao() == \"Doutor\"):\n super().setBonificacao(super().getSalario() * 4)\n super().setSalario(super().getSalario() + super().getBonificacao())\n else:\n super().setBonificacao(super().getSalario() * 2)\n super().setSalario(super().getSalario() + super().getBonificacao())\n\n\nclass Diretor(Funcionario):\n def addBonificacao(self):\n if (super().getGrauInstrucao() == \"Especialista\"):\n super().setBonificacao(super().getSalario() * 0.15)\n super().setSalario(super().getSalario()+super().getBonificacao())\n elif (super().getGrauInstrucao() == \"Mestre\"):\n super().setBonificacao(super().getSalario() * 0.25)\n super().setSalario(super().getSalario() + super().getBonificacao())\n elif (super().getGrauInstrucao() == \"Doutor\"):\n super().setBonificacao(super().getSalario() * 0.50)\n super().setSalario(super().getSalario() + super().getBonificacao())\n\n" }, { "alpha_fraction": 0.5526315569877625, "alphanum_fraction": 0.5736842155456543, "avg_line_length": 19.567567825317383, "blob_id": "dd41abe4f827a4f9b9170be5be337792be081fae", "content_id": "f198ad8a196b4fb5986e847a21b7b90270132f5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 764, "license_type": "no_license", "max_line_length": 47, "num_lines": 37, "path": "/Introduction to Class/Class-Calculator/main.py", "repo_name": "hermanoaraujo/Python-Object-Oriented", "src_encoding": "UTF-8", "text": "from classes import Calculadora\n\n#inicia calculadora com um valor no registrador\nc = Calculadora()\nprint(Calculadora.DESCRIPTION)\n\nwhile True:\n print('='*20)\n print(\"\\t\",c.getRegistrador())\n print('='*20)\n print('''\n [1] - Somar\n [2] - Subtrair\n [3] - Dividir\n [4] - Multiplicar\n [5] - Reset\n [6] - Undo\n ''')\n opcao = int(input(\"Digite a Opção:\"))\n if(opcao == 1):\n valor = float(input(\"+: \"))\n c.somar(valor)\n elif(opcao == 2):\n valor = float(input(\"- :\"))\n c.subtrair(valor)\n elif(opcao == 3):\n valor = float(input(\"/ :\"))\n c.dividir(valor)\n elif(opcao == 4):\n valor = float(input(\"* :\"))\n c.multiplicar(valor)\n elif(opcao == 5):\n c.reset()\n elif(opcao == 6):\n c.undo()\n else:\n print(\"Operação Invalida!\")" }, { "alpha_fraction": 0.5725593566894531, "alphanum_fraction": 0.5778363943099976, "avg_line_length": 21.352941513061523, "blob_id": "5c1a1f014bb18e7ebbe39cf09649ce9333c7929c", "content_id": "5a387c041846affcd669c0a3f2410635118777f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 379, "license_type": "no_license", "max_line_length": 91, "num_lines": 17, "path": "/Introduction to Class/Class-Deck/cardClass.py", "repo_name": "hermanoaraujo/Python-Object-Oriented", "src_encoding": "UTF-8", "text": "from importsConfig import *\n\n## Classe cards\nclass Card:\n __numberOfCards = 0\n def __init__(self,number,suit):\n self.__number = number\n self.__suit = suit\n\n Card.__numberOfCards += 1\n\n def __str__(self): \n return \"------\\n|\"+str(self.__number)+\" |\\n| of |\\n| \"+str(self.__suit)+\"|\\n------\"\n \n @classmethod\n def countCards(cls):\n return cls.__numberOfCards" }, { "alpha_fraction": 0.8365384340286255, "alphanum_fraction": 0.8365384340286255, "avg_line_length": 25.25, "blob_id": "8d66b3cdaccaa1e8bfbac8d2889312b0f100776a", "content_id": "9730aa81737ab8ad046400bcd3b261125945d34a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 104, "license_type": "no_license", "max_line_length": 29, "num_lines": 4, "path": "/Introduction to Class/Class-Deck/importsConfig.py", "repo_name": "hermanoaraujo/Python-Object-Oriented", "src_encoding": "UTF-8", "text": "from random import shuffle\nfrom termcolor import colored\nfrom cardClass import *\nfrom deckClass import *" }, { "alpha_fraction": 0.4175911247730255, "alphanum_fraction": 0.44057053327560425, "avg_line_length": 29.071428298950195, "blob_id": "e63c66444c551da93f4045d62ce26fd61eca1bb7", "content_id": "3eb1118415998e3bf57a866112c2b85416eb5904", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1262, "license_type": "no_license", "max_line_length": 72, "num_lines": 42, "path": "/Introduction to Class/Class-Deck/main.py", "repo_name": "hermanoaraujo/Python-Object-Oriented", "src_encoding": "UTF-8", "text": "from importsConfig import *\n\n# Hermano Araújo\n# 13/10/2018\n\n\nwhile True:\n print(colored('='*40,'yellow'))\n print('''\n \\t Card Game Version 1.4\n _____\n |A . | _____\n | /.\\ ||K ^ | _____\n |(_._)|| / \\ ||Q _ | _____\n | | || \\ / || ( ) ||J_ _ |\n |____A|| . ||(_'_)||( v )|\n |____K|| | || \\ / |\n |____Q|| . |\n |____J| \n ''')\n print(colored('='*40,'yellow'))\n print(colored(\"\\t[1] - Play Card Game\",\"cyan\"))\n print(colored(\"\\t[2] - Decks and Cards Mounted\",\"cyan\"))\n print(colored(\"\\t[3] - Credits\",'cyan'))\n option = int(input(\"\\nEnter an option: \"))\n if(option == 1):\n d = Deck()\n d.createDeck()\n d.shuffleDeck()\n numPlayers = input(\"Enter a number os players, Default 4 players: \")\n if (numPlayers is not \"\"):\n d.distributeCards(int(numPlayers))\n else:\n d.distributeCards()\n elif(option == 2):\n print(colored('='*40,'yellow'))\n print(\"\\tDecks: \",Deck.countDecks())\n print(\"\\tCards: \",Card.countCards())\n elif(option == 3):\n print(colored('='*40,'magenta'))\n print(colored(\"Deck Game V1.4 - Hermano Araújo\",'cyan'))\n print(colored('='*40,'magenta'))" } ]
10
mhxie/disque_protocol
https://github.com/mhxie/disque_protocol
01331b3e0f0bfbab7c3fbec5d00f61d3635608d2
6ed82f66a9c9904c7d75bdd328187b83a82b63b0
069cd3d41b855e48fafe7256972a512fe5bf9de9
refs/heads/master
2023-08-16T22:44:12.070488
2019-12-06T20:34:31
2019-12-06T20:34:31
225,782,441
1
0
null
2019-12-04T04:56:37
2020-02-20T05:31:51
2023-08-14T22:07:22
Python
[ { "alpha_fraction": 0.5700404644012451, "alphanum_fraction": 0.5781376361846924, "avg_line_length": 31.077922821044922, "blob_id": "d0b534ad1ce40dd88b2101d661fdb627b382e4d5", "content_id": "6cb50ab449ed1ecdfd135828527eb40087c54e5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2470, "license_type": "no_license", "max_line_length": 140, "num_lines": 77, "path": "/consumer.py", "repo_name": "mhxie/disque_protocol", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport zmq\nimport threading\nimport random\nimport time\n\nfrom common.my_timer import RecurTimer\nfrom common.global_var import *\n\n\nclass Consumer():\n\n def __init__(self, consumer_urls, i):\n self.context = zmq.Context.instance()\n self.socket = self.context.socket(zmq.DEALER)\n self.socket.identity = (u\"Consumer-%d\" % (i)).encode('ascii')\n self.__init_metrics()\n\n # Get producer urls in the future\n # connect to a random broker\n # self.socket.connect(random.choice(consumer_urls))\n self.socket.connect(consumer_urls[0])\n\n # self.timer = RecurTimer(1/consume_rate, self.send_a_req)\n\n def __init_metrics(self):\n self.consumed = 0\n self.failed = 0\n\n def run(self):\n # self.timer.start()\n # self.send_req(10)\n start_time = time.time_ns()\n ns_between_sends = 10**9/produce_rate\n avg = 0\n last_send_time = time.time_ns()\n while self.consumed < consume_rate*MAX_RUN_TIME:\n if (time.time_ns() - last_send_time > ns_between_sends):\n self.send_req(1)\n now = time.time_ns()\n avg += (now - last_send_time)/10**6\n last_send_time = now\n print(\"Consumer spent\", (time.time_ns()-start_time)/10**9, \"on rate\", consume_rate, \"with latency\", avg/(consume_rate*MAX_RUN_TIME))\n\n def send_req(self, num):\n time.time()\n for _ in range(num):\n self.socket.send(b'CONSUME')\n msg = self.socket.recv_multipart()\n # print('Consumer got', msg)\n prod_id, msg_id = msg[:2]\n del msg# consumed data\n self.consume_success(prod_id, msg_id)\n\n def consume_success(self, prod_id, msg_id):\n self.consumed += 1\n self.socket.send_multipart([b'CONSUMED', prod_id, msg_id])\n # print(\"Consume one product\")\n if self.consumed > consume_rate*MAX_RUN_TIME:\n # self.timer.cancel()\n print(\"Consumer spent\", time.time_ns()-self.start_time, \"on rate\", consume_rate)\n\n\ndef consumer_thread(i):\n cons_urls = [\"ipc://backend-%s.ipc\" % str(i) for i in range(BROKER_NUM)]\n new_cons = Consumer(cons_urls, i)\n new_cons.run()\n\n\nif __name__ == '__main__':\n # create consumer thread\n for i in range(CONSUMER_NUM):\n thread = threading.Thread(\n target=consumer_thread, args=(i, ))\n thread.daemon = True\n thread.start()\n" }, { "alpha_fraction": 0.5709342360496521, "alphanum_fraction": 0.5752595067024231, "avg_line_length": 24.688888549804688, "blob_id": "e54c1705bd69f3a7b11eb8c9edcb2778028994e3", "content_id": "0975c88fb7cec369d51b67e4d52608b6c7218d63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1156, "license_type": "no_license", "max_line_length": 59, "num_lines": 45, "path": "/common/my_timer.py", "repo_name": "mhxie/disque_protocol", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom threading import Timer, Thread, Event\n\nRETRY_TIMES = 4\n\n\nclass RecurTimer(object):\n def __init__(self, interval, func, arg_list=[]):\n self.interval = interval\n self.func = func\n self.arg_list = arg_list\n self.timer = Timer(interval, self.handle_func)\n\n def handle_func(self):\n if self.cancelled:\n return\n self.func(*self.arg_list)\n self.timer = Timer(self.interval, self.handle_func)\n self.timer.start()\n\n def start(self):\n self.cancelled = False\n self.timer.start()\n\n def cancel(self):\n self.cancelled = True\n self.timer.cancel()\n\n\nclass DecayTimer(RecurTimer):\n def __init__(self, int, func, arg_list=[]):\n super().__init__(int, func, arg_list)\n self.retry = RETRY_TIMES\n\n def handle_func(self):\n # print('retry', self.retry, 'times left')\n if self.retry == 0:\n self.timer.cancel()\n return\n self.interval *= 2\n self.retry -= 1\n self.func(*self.arg_list)\n self.timer = Timer(self.interval, self.handle_func)\n self.timer.start()\n" }, { "alpha_fraction": 0.7208672165870667, "alphanum_fraction": 0.7344173192977905, "avg_line_length": 17.5, "blob_id": "fa0c694f7724c763de37342ad1d097d7479b83ad", "content_id": "8e3d09cd6e4b03d030ff26db88518bbb5610d05d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 369, "license_type": "no_license", "max_line_length": 63, "num_lines": 20, "path": "/README.md", "repo_name": "mhxie/disque_protocol", "src_encoding": "UTF-8", "text": "### Introductions\nA fault-tolerant distributed message queue with its simulations\n\n### Getting Started\n\n#### Requirements:\n- python 3.6 or later\n- virtualenv\n\n#### Install requirements\n virtualenv venv\n (venv) pip install -r requirements.txt\n\n### Running Tests\n python3 -m unittest\n\n\n### TODO\n1. support disabling persistent storage\n2. support failure recovery" }, { "alpha_fraction": 0.5577752590179443, "alphanum_fraction": 0.5590883493423462, "avg_line_length": 36.02083206176758, "blob_id": "8ef0abda7b62ba1e897e25003986ce86e48812ca", "content_id": "e2bf741d2ab140dc9794ce91aa4e200a170cf5d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10662, "license_type": "no_license", "max_line_length": 92, "num_lines": 288, "path": "/broker.py", "repo_name": "mhxie/disque_protocol", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport zmq\nimport threading\nimport random\nimport asyncio\nimport time\n\nfrom zmq.eventloop.ioloop import IOLoop\nfrom zmq.eventloop.zmqstream import ZMQStream\nfrom sqlitedict import SqliteDict\n\nfrom common.global_var import *\nfrom consumer import consumer_thread\nfrom producer import producer_thread\n\npeer_topo = []\n\nif not ENABLE_ROCKSDB:\n PERSIST_THRESHOLD = 1\nDEBUG = False\n\nclass Broker(object):\n def __init__(self, urls, id):\n self.id = id\n self.peer_urls = urls['peers']\n self.queued_msgs = {}\n self.replicated_msgs = {}\n self.capacity = MAX_MSG_CAPACITY\n\n # self.consume_lock = threading.Lock()\n # self.consuming = False\n\n asyncio.set_event_loop(asyncio.new_event_loop())\n # self.loop = ioloop.IOLoop.current()\n self.__init_metrics()\n self.__init_sockets(urls)\n self.__set_callback()\n self.loop = IOLoop.instance()\n\n self.rocks = SqliteDict(\n './remotedb-%d.sqlite' % (self.id), autocommit=True)\n # self.AAL = SqliteDict('./local_aal-%d.sqlite' % (self.id), autocommit=True)\n self.AAL={}\n # self.DAL = SqliteDict('./local_dal-%d.sqlite' % (self.id), autocommit=True) \n self.DAL={}\n self.rocks.clear()\n # self.AAL.clear()\n # self.DAL.clear()\n \n def __init_sockets(self, urls):\n context = zmq.Context()\n self.frontend_sock = context.socket(zmq.ROUTER)\n self.backend_sock = context.socket(zmq.ROUTER)\n self.peerend_sock = context.socket(zmq.ROUTER)\n self.frontend_sock.bind(urls[\"producer\"])\n self.backend_sock.bind(urls[\"consumer\"])\n self.peerend_sock.bind(urls[\"self\"])\n \n self.context = zmq.Context.instance()\n self.socket = context.socket(zmq.REQ)\n self.socket.identity = (u\"Broker-%d\" % (self.id)).encode('ascii')\n\n def __set_callback(self):\n self.frontend = ZMQStream(self.frontend_sock)\n self.backend = ZMQStream(self.backend_sock)\n self.peerend = ZMQStream(self.peerend_sock)\n\n self.frontend.on_recv(self.handle_frontend)\n self.backend.on_recv(self.handle_backend)\n self.peerend.on_recv(self.handle_peerend)\n\n def __init_metrics(self):\n pass\n\n def __lost_peer(self, url):\n pass\n\n def __new_peer_online(self, url):\n pass\n\n def __insert_add_ahead_log(self, prod_id, msg_id, dst):\n \"\"\" Implementation of add-ahead-log (AAL)\n \"\"\"\n if DEBUG == True:\n print('Thread', self.id, 'inserting AAL', prod_id, msg_id, dst)\n if prod_id not in self.AAL.keys():\n self.AAL[prod_id] = {}\n self.AAL[prod_id][msg_id] = dst\n\n def __remove_add_ahead_log(self, prod_id, msg_id):\n if DEBUG == True:\n print(\"removing AAL\", prod_id, msg_id)\n del self.AAL[prod_id][msg_id]\n\n def __insert_delete_ahead_log(self, prod_id, msg_id, dst):\n \"\"\" Implementation of delete-ahead-log (DAL)\n \"\"\"\n if DEBUG == True:\n print('Thread', self.id, 'inserting DAL', prod_id, msg_id, dst)\n if prod_id not in self.DAL.keys():\n self.DAL[prod_id] = {}\n self.DAL[prod_id][msg_id] = dst\n\n def __remove_delete_ahead_log(self, prod_id, msg_id):\n if DEBUG == True:\n print(\"removing DAL\", prod_id, msg_id)\n del self.DAL[prod_id][msg_id]\n\n def __send_replicates(self, prod_id, msg_id, payload):\n for url in self.peer_urls:\n self.socket.connect(url)\n self.__insert_add_ahead_log(prod_id, msg_id, url)\n self.socket.send_multipart([b'REPLICATE', prod_id, msg_id, payload])\n reply = self.socket.recv()\n if reply == b'REPLICATED':\n self.__remove_add_ahead_log(prod_id, msg_id)\n self.socket.disconnect(url)\n\n\n def __delete_replicates(self, prod_id, msg_id):\n \"\"\" needs an efficient way to store metadata of all replicates\n \"\"\"\n for url in self.peer_urls:\n self.socket.connect(url)\n self.__insert_delete_ahead_log(prod_id, msg_id, url)\n self.socket.send_multipart([b'DELETE', prod_id, msg_id])\n reply = self.socket.recv()\n if reply == b'DELETED':\n self.__remove_delete_ahead_log(prod_id, msg_id)\n self.socket.disconnect(url)\n\n def __persist_msgs(self, prod_id, msg_id, msg):\n if prod_id not in self.rocks.keys():\n self.rocks[prod_id] = {}\n self.rocks[prod_id][msg_id] = msg\n\n def __retrieve_msgs(self, num=1):\n if len(list(self.rocks.keys())) == 0:\n return\n for _ in range(num):\n prod_id = random.choice(list(self.rocks.keys()))\n msg_id, msg = self.rocks[prod_id].popitem()\n self.queued_msgs[prod_id][msg_id] = msg\n\n def __get_size_of_queues(self, replica=False):\n return sum([len(queue) for queue in self.queued_msgs.values()])\n\n def __enqueue_a_msg(self, prod_id, msg_id, payload, replica=False):\n if not replica:\n if self.__get_size_of_queues() <= self.capacity * PERSIST_THRESHOLD:\n if prod_id not in self.queued_msgs.keys():\n self.queued_msgs[prod_id] = {}\n self.queued_msgs[prod_id][msg_id] = payload\n else:\n self.__persist_msgs(prod_id, msg_id, payload) # sorta redundant\n else:\n if prod_id not in self.replicated_msgs.keys():\n self.replicated_msgs[prod_id] = {}\n self.replicated_msgs[prod_id][msg_id] = payload\n\n def __get_a_msg(self):\n try:\n prod_id = random.choice(list(self.queued_msgs.keys()))\n msg_id = random.choice(list(self.queued_msgs[prod_id].keys()))\n # msg_id, payload = self.queued_msgs[prod_id].popitem()\n return [prod_id, msg_id, self.queued_msgs[prod_id][msg_id]]\n except IndexError:\n return [None, None, None]\n\n def __dequeue_a_msg(self, prod_id, msg_id, replica=False):\n if not replica:\n if self.__get_size_of_queues() == self.capacity * PERSIST_THRESHOLD:\n self.__retrieve_msgs()\n if DEBUG == True:\n print(self.id, \"dequing:\", self.queued_msgs[prod_id])\n try:\n return self.queued_msgs[prod_id].pop(msg_id)\n except IndexError:\n if DEBUG == True:\n print(\"Already consumed. (Delivered twice)\")\n return None\n else:\n if DEBUG == True:\n print(self.id, \"dequing replica:\", self.replicated_msgs[prod_id])\n try:\n return self.replicated_msgs[prod_id].pop(msg_id)\n except KeyError:\n return None\n\n def __consume_a_msg(self, cons_id):\n prod_id, msg_id, payload = self.__get_a_msg()\n if prod_id is None:\n next_timer = threading.Timer(NEXT_CONSUME_TIME, self.__consume_a_msg, [cons_id])\n next_timer.start()\n return\n else:\n pass\n # print('get_a_msg', prod_id, msg_id, payload)\n self.backend.send_multipart([cons_id, prod_id, msg_id, payload])\n\n def handle_frontend(self, msg):\n if DEBUG == True:\n print(self.id, 'handling frontend:', msg)\n start_time = time.time_ns()\n prod_id, msg_id, payload = msg[:3]\n self.__enqueue_a_msg(prod_id, msg_id, payload)\n self.__send_replicates(prod_id, msg_id, payload)\n # print(\"Time for frontend is\", time.time_ns() - start_time)\n\n def handle_backend(self, msg):\n if DEBUG == True:\n print(self.id, 'handling backend:', msg)\n cons_id, command = msg[:2]\n start_time = time.time_ns()\n if command == b'CONSUME':\n start_time = time.time_ns()\n self.__consume_a_msg(cons_id)\n elif command == b'CONSUMED':\n prod_id, msg_id = msg[2:4]\n res = self.__dequeue_a_msg(prod_id, msg_id)\n if res is not None:\n self.__delete_replicates(prod_id, msg_id)\n # print(\"Time for backend is\", time.time_ns() - start_time)\n\n def handle_peerend(self, msg):\n if DEBUG == True:\n print(self.id, 'handling peerend', msg)\n broker_id, _, command = msg[:3]\n start_time = None\n if command == b'REPLICATE':\n start_time = time.time_ns()\n prod_id, msg_id, payload = msg[3:6]\n self.__enqueue_a_msg(prod_id, msg_id, payload, replica=True)\n # self.peerend.send_multipart([broker_id, b'', b'REPLICATED', prod_id, msg_id])\n self.peerend.send_multipart([broker_id, b'', b'REPLICATED'])\n # print(\"Time for replication is\", time.time_ns() - start_time)\n elif command == b'DELETE':\n start_time = time.time_ns()\n prod_id, msg_id = msg[3:5]\n self.__dequeue_a_msg(prod_id, msg_id, replica=True)\n # self.peerend.send_multipart([broker_id, b'', b'DELETED', prod_id, msg_id])\n self.peerend.send_multipart([broker_id, b'', b'DELETED'])\n # print(\"Time for deletion is\", time.time_ns() - start_time)\n # elif command == b\"REPLICATED\":\n # self.__remove_add_ahead_log(prod_id, msg_id)\n # elif command == b\"DELETED\":\n # self.__remove_delete_ahead_log(prod_id, msg_id)\n\n def run(self):\n self.loop.start()\n\n def stop(self):\n self.loop.stop()\n\ndef broker_thread(me):\n urls = {\"producer\": \"ipc://frontend-%s.ipc\" % str(me),\n \"consumer\": \"ipc://backend-%s.ipc\" % str(me),\n \"self\": \"ipc://broker-%s.ipc\" % str(me),\n \"peers\": [\"ipc://broker-%s.ipc\" % str(i) for i in peer_topo[me]]}\n print(urls)\n broker = Broker(urls, me)\n broker.run()\n\n\nif __name__ == '__main__':\n assert(BROKER_NUM > REPLICA_NUM)\n for i in range(BROKER_NUM):\n # dsts = [j for j in range(BROKER_NUM)]\n # del dsts[i] # excude self\n # peer_topo.append(random.choices(dsts, k=REPLICA_NUM))\n peer_topo.append([(i+j+1)%BROKER_NUM for j in range(REPLICA_NUM)])\n\n\n thread = threading.Thread(target=broker_thread,\n args=(i,))\n thread.start()\n\n for i in range(PRODUCER_NUM):\n thread = threading.Thread(target=producer_thread, args=(i, ))\n thread.daemon = True\n thread.start()\n\n for i in range(CONSUMER_NUM):\n thread = threading.Thread(\n target=consumer_thread, args=(i, ))\n thread.daemon = True\n thread.start()\n" }, { "alpha_fraction": 0.60317462682724, "alphanum_fraction": 0.60317462682724, "avg_line_length": 13.823529243469238, "blob_id": "3dadd34729534f15fac253a758f860dc360aaf22", "content_id": "7069794a87e920454d4da8fea866f64e90cee182", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 252, "license_type": "no_license", "max_line_length": 42, "num_lines": 17, "path": "/test/test_failures.py", "repo_name": "mhxie/disque_protocol", "src_encoding": "UTF-8", "text": "import unittest\n\n\nclass TestFailureCases(unittest.TestCase):\n\n def test_broker_down(self):\n pass\n\n def test_consumer_down(self):\n pass\n\n def test_producer_down(self):\n pass\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.571273684501648, "alphanum_fraction": 0.5869918465614319, "avg_line_length": 27.828125, "blob_id": "aa2cb698ae236669046423adecedcb99082f9cda", "content_id": "c59e4b87e685deba31df6ab86f340169bcbb8f5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1845, "license_type": "no_license", "max_line_length": 68, "num_lines": 64, "path": "/test/test_timer.py", "repo_name": "mhxie/disque_protocol", "src_encoding": "UTF-8", "text": "import unittest\nimport time\n\nfrom common.my_timer import RecurTimer, DecayTimer\n\n\nclass TestRecurTimer(unittest.TestCase):\n def check_func(self):\n self.tries -= 1\n curr_time = time.time()\n interval = curr_time - self.last_time\n # print('after interval', interval, self.tries)\n assert(interval > self.interval)\n if self.tries == 0:\n self.timer.cancel()\n return\n self.last_time = curr_time\n\n def test_long_interval(self):\n self.tries = 10\n self.interval = 1/10\n self.timer = RecurTimer(self.interval, self.check_func)\n self.last_time = time.time()\n self.timer.start()\n\n def test_short_interval(self):\n self.tries = 10\n self.interval = 1/1000\n self.timer = RecurTimer(self.interval, self.check_func)\n self.last_time = time.time()\n self.timer.start()\n\n\nclass TestDecayTimer(unittest.TestCase):\n def check_func(self, barrier):\n curr_time = time.time()\n interval = curr_time - self.last_time\n # print('after interval', interval, self.tries)\n self.tries += 1\n assert(interval > self.interval)\n assert(self.tries <= barrier)\n if self.tries == 0:\n self.timer.cancel()\n return\n self.last_time = curr_time\n self.interval *= 2\n\n def test_long_interval(self):\n self.tries = 0\n self.interval = 1/10\n self.timer = DecayTimer(self.interval, self.check_func, [4])\n self.last_time = time.time()\n self.timer.start()\n\n def test_short_interval(self):\n self.tries = 0\n self.interval = 1/1000\n self.timer = DecayTimer(self.interval, self.check_func, [4])\n self.last_time = time.time()\n self.timer.start()\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.6699507236480713, "alphanum_fraction": 0.7339901328086853, "avg_line_length": 16.69565200805664, "blob_id": "1bde84e9eab1f421cf75f8155de1246c0c21e4a1", "content_id": "a13a9c9e1556b65172edf10dbbe2767fc1cb7d7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 406, "license_type": "no_license", "max_line_length": 40, "num_lines": 23, "path": "/common/global_var.py", "repo_name": "mhxie/disque_protocol", "src_encoding": "UTF-8", "text": "# topology settings\nBROKER_NUM = 3\nREPLICA_NUM = 2\nPRODUCER_NUM = 1\nCONSUMER_NUM = 1\n\n# local settings\nPERSIST_THRESHOLD = 0.8\n\nENABLE_ROCKSDB = True\n\n# throughput settings\nproduce_rate = 1100\nconsume_rate = produce_rate/1\nMAX_RUN_TIME = 2\nNODE_CHANGE_DURATION = 5\n\n# communiction setting\nMSG_SIZE = 32\nMAX_MSG_CAPACITY = 1024/MSG_SIZE\nKEY_SIZE = 16\nWAIT_TIME = 128\nNEXT_CONSUME_TIME = 1/consume_rate/2 #ms" }, { "alpha_fraction": 0.4680851101875305, "alphanum_fraction": 0.6808510422706604, "avg_line_length": 14.666666984558105, "blob_id": "522344fc1fa4311d24d3eabb7865f4160dce6a74", "content_id": "610bb0b5f331d1101a5758f9ef33e1af5a7ccff0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 47, "license_type": "no_license", "max_line_length": 17, "num_lines": 3, "path": "/requirements.txt", "repo_name": "mhxie/disque_protocol", "src_encoding": "UTF-8", "text": "pyzmq==18.1.1\nsqlitedict==1.6.0\ntornado==6.0.3\n" }, { "alpha_fraction": 0.5822831988334656, "alphanum_fraction": 0.5922905802726746, "avg_line_length": 29.314607620239258, "blob_id": "0c0feee5fc8d8c755005446ae9492f1417f6015e", "content_id": "fd3eb3f8ae9a77bb163f379a82ee858287d2a735", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2698, "license_type": "no_license", "max_line_length": 140, "num_lines": 89, "path": "/producer.py", "repo_name": "mhxie/disque_protocol", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport zmq\nimport threading\nimport random\nimport string\nimport time\n# import asyncio\n\n# from zmq.eventloop import ioloop\nfrom zmq.eventloop.zmqstream import ZMQStream\n\nfrom common.my_timer import RecurTimer\nfrom common.global_var import *\n\n\nclass Producer():\n\n def __init__(self, broker_urls, i):\n self.context = zmq.Context.instance()\n self.socket = self.context.socket(zmq.DEALER)\n self.socket.identity = (u\"Producer-%d\" % (i)).encode('ascii')\n self.__init_metrics()\n # Get producer urls in the future\n # connect to a random broker\n\n\n # self.socket.connect(random.choice(broker_urls))\n self.socket.connect(broker_urls[0])\n\n # self.timer = RecurTimer(1/produce_rate, self.send_a_msg)\n # asyncio.set_event_loop(asyncio.new_event_loop())\n # self.loop = ioloop.IOLoop.instance()\n\n\n\n def __init_metrics(self):\n self.msg_id = 0\n self.sent = 0\n self.failed = 0\n\n def run(self):\n # self.timer.start()\n # self.caller = ioloop.PeriodicCallback(self.send_a_msg, int(1000/produce_rate))\n # self.caller.start()\n # self.send_msg(10)\n start_time = time.time_ns()\n ns_between_sends = 10**9/produce_rate\n avg = 0\n last_send_time = time.time_ns()\n while self.sent < produce_rate*MAX_RUN_TIME:\n if (time.time_ns() - last_send_time > ns_between_sends):\n self.send_msg(1)\n now = time.time_ns()\n avg += (now - last_send_time)/10**6\n last_send_time = now\n print(\"Producer spent\", (time.time_ns()-start_time)/10**9, \"on rate\", produce_rate, \"with latency\", avg/(produce_rate*MAX_RUN_TIME))\n\n\n def send_msg(self, num=1):\n random_msg = ''.join(\n [random.choice(string.ascii_letters + string.digits) for n in range(MSG_SIZE)])\n random_key = ''.join(\n [random.choice(string.digits) for n in range(KEY_SIZE)])\n for _ in range(num):\n self.socket.send_multipart([random_key.encode('ascii'), random_msg.encode('ascii')])\n self.send_success()\n \n def send_failure(self):\n self.failed += 1\n\n def send_success(self):\n self.sent += 1\n self.msg_id += 1\n # print(\"sent one product\")\n\n\ndef producer_thread(i):\n prod_urls = [\"ipc://frontend-%s.ipc\" % str(i) for i in range(BROKER_NUM)]\n new_prod = Producer(prod_urls, i)\n new_prod.run()\n\n\nif __name__ == '__main__':\n # create producer thread\n for i in range(PRODUCER_NUM):\n thread = threading.Thread(target=producer_thread, args=(i, ))\n thread.daemon = True\n thread.start()\n" } ]
9
abatkins/simanPy
https://github.com/abatkins/simanPy
add508ce8d177c658e94407fa82c46c83a72c47c
3e594dddaf722b67ffb8bc108214a21a0f9cf436
a20519d0b787332cbbd81613c42b947ed13d8127
refs/heads/master
2021-01-12T14:19:30.772090
2016-12-01T16:30:50
2016-12-01T16:30:50
69,423,593
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5647593140602112, "alphanum_fraction": 0.56621253490448, "avg_line_length": 29.084699630737305, "blob_id": "5c44516dc6e157bf1683e3b37960c0365d0f7e74", "content_id": "3c29bbf479c35172d74e0e9c046b1f0c5b2c24a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11010, "license_type": "no_license", "max_line_length": 130, "num_lines": 366, "path": "/elements.py", "repo_name": "abatkins/simanPy", "src_encoding": "UTF-8", "text": "class _Elements:\n \"\"\"Base Elements class\"\"\"\n def __init__(self, exp):\n self._exp = exp\n self.elements = []\n self.type = \"exp\"\n\n def __str__(self):\n return self._exp + \";\"\n\n # Add Element (unique) to container and add to .exp string\n # todo: better formatting for Elements string. Should be multiline\n def add(self, element):\n if element not in self.elements:\n self._exp += str(element)\n self.elements.append(element)\n\n\nclass Project(_Elements):\n def __init__(self, title=\"\", analyst_name=\"\", date=\"\", summary_report=\"\"):\n exp = \"PROJECT, {}, {}, {}, {}\".format(title, analyst_name, date, summary_report)\n super().__init__(exp)\n\n\n# todo: find out what 3 missing params are\nclass Replicate(_Elements):\n def __init__(self, num_replications=1, begin_time=0.0, replication_len=\"\", init_system=\"Yes\", init_stats=\"Yes\",\n warmup_period=0.0, hours_per_day=24, base_time_unit=\"\"):\n exp = \"REPLICATE, {}, {}, {}, {}, {}, {},,,{}, {}\".format(num_replications, begin_time, replication_len,\n init_system, init_stats, warmup_period, hours_per_day,\n base_time_unit)\n super().__init__(exp)\n\n\nclass Discrete(_Elements):\n def __init__(self, max_entities=\"\", max_attr=\"\", max_queue_num=\"\", max_station_num=\"\", animation_attr=\"\"):\n exp = 'DISCRETE, {}, {}, {}, {}, {}'.format(max_entities, max_attr, max_queue_num, max_station_num, animation_attr)\n super().__init__(exp)\n\n\nclass Trace(_Elements):\n def __init__(self, begin_time=0.0, end_time=\"\", condition=\"\", expression=\"\"):\n exp = 'TRACE, {}, {}, {}, {}'.format(begin_time, end_time, condition, expression)\n super().__init__(exp)\n\n\nclass _Begin(_Elements):\n def __init__(self, listing=\"Yes\", run_controller=\"No\"):\n exp = \"BEGIN, %s, %s\" % (str(listing), str(run_controller))\n super().__init__(exp)\n\n\nclass _End(_Elements):\n def __init__(self):\n exp = \"END\"\n super().__init__(exp)\n\n\nclass _Queues(_Elements):\n def __init__(self):\n exp = \"QUEUES\"\n super().__init__(exp)\n\n\nclass _Resources(_Elements):\n def __init__(self):\n exp = \"RESOURCES\"\n super().__init__(exp)\n\n\nclass _Counters(_Elements):\n def __init__(self):\n exp = \"COUNTERS\"\n super().__init__(exp)\n\n\nclass _Attributes(_Elements):\n def __init__(self):\n exp = \"ATTRIBUTES\"\n super().__init__(exp)\n\n\nclass _Variables(_Elements):\n def __init__(self):\n exp = \"VARIABLES\"\n super().__init__(exp)\n\n\nclass _Dstats(_Elements):\n def __init__(self):\n exp = \"DSTATS\"\n super().__init__(exp)\n\n\nclass _Tallies(_Elements):\n def __init__(self):\n exp = \"TALLIES\"\n super().__init__(exp)\n\n\nclass _Storages(_Elements):\n def __init__(self):\n exp = \"STORAGES\"\n super().__init__(exp)\n\n\nclass _Seeds(_Elements):\n def __init__(self):\n exp = \"SEEDS\"\n super().__init__(exp)\n\n\nclass _Outputs(_Elements):\n def __init__(self):\n exp = \"OUTPUTS\"\n super().__init__(exp)\n\n\nclass _Stations(_Elements):\n def __init__(self):\n exp = \"STATIONS\"\n super().__init__(exp)\n\n\nclass _Sequences(_Elements):\n def __init__(self):\n exp = \"SEQUENCES\"\n super().__init__(exp)\n\n\nclass _Transporters(_Elements):\n def __init__(self):\n exp = \"TRANSPORTERS\"\n super().__init__(exp)\n\n\nclass _Pictures(_Elements):\n def __init__(self):\n exp = \"PICTURES\"\n super().__init__(exp)\n\n#class _Distances(_Elements):\n# def __init__(self):\n# exp = \"DISTANCES\"\n# super().__init__(exp)\n\n\nclass _Sets(_Elements):\n def __init__(self):\n exp = \"SETS\"\n super().__init__(exp)\n\n\n# SIMAN does not define Entities as Elements. But, programatically very similar.\nclass _Entities(_Elements):\n def __init__(self):\n exp = \"ENTITIES\"\n super().__init__(exp)\n\n\n\"\"\"ELEMENT STORAGE CLASSES\"\"\"\nclass _Element:\n \"\"\"Base Element storage class\"\"\"\n\n def __init__(self, name, attributes, number=None):\n self.name = name\n self.number = number\n self.attributes = attributes\n self.type = \"element\"\n\n def __str__(self):\n num = str(self.number) + ', ' if self.number else ''\n return ': ' + num + ', '.join(str(x) for x in self.attributes)\n\n def __eq__(self, other):\n if self.number:\n return self.name == other.name and self.number == other.number\n else:\n return self.name == other.name\n\n def __ne__(self, other):\n if self.number:\n return self.name != other.name or self.number != other.number\n else:\n return self.name != other.name\n\n def __hash__(self):\n if self.number:\n return hash(('number', self.number, 'name', self.name))\n else:\n return hash(('name', self.name))\n\n\nclass Queue(_Element):\n \"\"\"Queue storage class\"\"\"\n def __init__(self, number=\"\", name=\"\", ranking_criterion=\"FIFO\"):\n self.ranking_criterion = ranking_criterion\n\n attributes = [name, ranking_criterion]\n super().__init__(name, attributes, number)\n\n\nclass Resource(_Element):\n \"\"\"Resource storage class\"\"\"\n def __init__(self, number=\"\", name=\"\", capacity=1):\n self.capacity = capacity\n\n attributes = [name, capacity]\n super().__init__(name, attributes, number)\n\n\nclass Counter(_Element):\n \"\"\"Counter storage class\"\"\"\n def __init__(self, number=\"\", name=\"\", limit=\"\", init_option=\"\", output_file=\"\", report_id=\"\"):\n self.limit = limit\n self.init_option = init_option\n self.output_file = output_file\n self.report_id = report_id\n\n attributes = [name, limit, init_option, output_file, report_id]\n super().__init__(name, attributes, number)\n\n\nclass Attribute(_Element):\n def __init__(self, number=\"\", name=\"\", init_values=\"\"):\n self.init_values = init_values\n\n attributes = (name, init_values)\n super().__init__(name, attributes, number)\n\n\nclass Variable(_Element):\n def __init__(self, number=\"\", name=\"\", init_values=\"\"):\n inst_varname = name\n if isinstance(init_values, list):\n if '(' not in name:\n inst_varname = name +'({})'.format(len(init_values))\n init_values = ','.join([str(v) for v in init_values])\n\n self.init_values = init_values\n\n attributes = (inst_varname, init_values)\n super().__init__(name, attributes, number)\n\n\nclass Dstat(_Element):\n def __init__(self, number=\"\", name=\"\", expression=\"\", output_file=\"\", report_id=\"\"):\n self.expression = expression\n self.output_file = output_file\n self.report_id = report_id\n\n attributes = (expression, name, output_file, report_id)\n super().__init__(name, attributes, number)\n\n\nclass Tally(_Element):\n def __init__(self, number=\"\", name=\"\", output_file=\"\", report_id=\"\"):\n output_file = '\"' + output_file + '\"'\n self.output_file = output_file\n self.report_id = report_id\n\n attributes = (name, output_file, report_id)\n super().__init__(name, attributes, number)\n\n\nclass Storage(_Element):\n def __init__(self, number=\"\", name=\"\"):\n attributes = (name)\n super().__init__(name, attributes, number)\n\n\nclass Output(_Element):\n def __init__(self, number=\"\", name=\"\", expression=\"\", output_file=\"\", report_id=\"\"):\n #self.number = number\n self.expression = expression\n self.output_file = output_file\n self.report_id = report_id\n\n #attributes = (number, name, expression, output_file, report_id)\n attributes = (name, expression, output_file, report_id)\n super().__init__(name, attributes, number)\n\n\nclass Station(_Element):\n def __init__(self, number, name=\"\", intersection_id=\"\", recipe_id=\"\"):\n #self.number = number\n self.intersection_id = intersection_id\n self.recipe_id = recipe_id\n\n #attributes = (number, name, intersection_id, recipe_id)\n attributes = (name, intersection_id, recipe_id)\n super().__init__(name, attributes, number)\n\n\nclass Sequence(_Element):\n def __init__(self, number=\"\", name=\"\", station_id=\"\", variable=None, value=None):\n #self.number = number\n self.steps = [[station_id, variable, value]]\n\n #attributes = [number, name, self.to_string(station_id, variable, value)]\n attributes = [name, self.to_string(station_id, variable, value)]\n super().__init__(name, attributes, number)\n\n def add(self, station_id=\"\", variable=\"\", value=\"\"):\n self.steps.append([station_id, variable, value])\n #self.attributes[2] += ' & ' + self.to_string(station_id, variable, value)\n self.attributes[1] += ' & ' + self.to_string(station_id, variable, value)\n\n def to_string(self, station_id, variable, value):\n if variable and value:\n return '{}, {} = {}'.format(station_id, variable, value)\n else:\n return str(station_id)\n\n# todo: Fix string formatting. More complex than normal.\nclass Transporter(_Element):\n def __init__(self, number=\"\", name=\"\", num_units=1, system_map_type=\"\", velocity=1.0, init_position=\"\", init_status=\"Active\"):\n #self.number = number\n self.num_units = num_units\n self.system_map_type = system_map_type\n self.velocity = velocity\n self.init_position = init_position\n self.init_status = init_status\n\n #attributes = (number, name, num_units, system_map_type, velocity, init_position, init_status)\n attributes = (name, num_units, system_map_type, velocity, init_position, init_status)\n super().__init__(name, attributes, number)\n\n\n#class Distance(_Element):\n# def __init__(self, name, start_station_id, end_station_id, distance):\n\nclass Set(_Element):\n def __init__(self, number=\"\", name=\"\", members=[]):\n assert isinstance(members, (tuple, list))\n\n #self.number = number\n self.members = members\n\n #attributes = (number, name, ', '.join(members))\n attributes = (name, ', '.join(members))\n super().__init__(name, attributes, number)\n\n\n# todo: determine how seeds should work. Does not fit number/name scheme\nclass Seed(_Element):\n def __init__(self, name=\"\", seed_value=\"\", init_option=\"No\"):\n self.seed_value = seed_value\n self.init_option = init_option\n\n attributes = (name, seed_value, init_option)\n super().__init__(name, attributes)\n\n\nclass Picture(_Element):\n def __init__(self, name):\n attributes = (name,)\n super().__init__(name, attributes)\n\n\n# todo: include other attributes\nclass Entity(_Element):\n \"\"\"Entity storage class\"\"\"\n def __init__(self, name, picture=\"\"):\n attributes = [name, picture]\n super().__init__(name, attributes)" }, { "alpha_fraction": 0.5909548997879028, "alphanum_fraction": 0.5929698944091797, "avg_line_length": 37.34334945678711, "blob_id": "dd19774ac3ecfa9db8642788adf472982e9dd67e", "content_id": "0cbebf0c8069d2d434cfc33829d8a1b2c23a63db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8933, "license_type": "no_license", "max_line_length": 131, "num_lines": 233, "path": "/blocks.py", "repo_name": "abatkins/simanPy", "src_encoding": "UTF-8", "text": "from elements import Queue, Variable, Attribute\n# TODO: Add param class that simply returns discrete list of params for a given block/elem. Example: param.branchtype.if\n# TODO: Better handling for modifiers like NEXT() and MARK(). Either set both independently or \"add modifier\" to pass both.\n\n\nclass Block:\n def __init__(self, mod, element=None):\n self._mod = mod\n self.type = 'mod'\n self.element = element\n self._modifiers = None\n\n def __str__(self):\n if self._modifiers:\n mod_string = ': '.join(self._modifiers)\n return self._mod + ': {};'.format(mod_string)\n else:\n return self._mod + \";\"\n\n # Add modifiers to block tail. EX: NEXT() / MARKS()\n def set_modifiers(self, modifiers):\n assert isinstance(modifiers, (list, tuple))\n self._modifiers = modifiers\n\n # For Repeats\n # todo: better formatting for repeats. Dynamic padding.\n def add(self, add_list):\n self._mod += ':\\n\\t\\t{}'.format((', '.join(add_list)))\n\n\n# todo: determine if element_ids should be passed to block as string or an object\nclass CreateBlock(Block):\n def __init__(self, entity, batch_size=1, offset_time=\"\", interval=\"\", maximum_batches=\"\"):\n mod = 'CREATE, {}, {}, {}: {}, {}'.format(batch_size, offset_time, entity.name, interval, maximum_batches)\n super().__init__(mod, entity)\n\n\nclass QueueBlock(Block):\n def __init__(self, queue, capacity=\"\", balk_label=\"\"):\n mod = 'QUEUE, {}, {}, {}'.format(queue, capacity, balk_label)\n super().__init__(mod)\n # assert isinstance(queue, Queue)\n # mod = 'QUEUE, {}, {}, {}'.format(queue.name, capacity, balk_label)\n # super().__init__(mod, queue)\n\n\nclass TallyBlock(Block):\n def __init__(self, tally, value, num_obs=1):\n mod = 'TALLY: {}, {}, {}'.format(tally.name, value, num_obs)\n super().__init__(mod, tally)\n\n\nclass SeizeBlock(Block):\n def __init__(self, resource, priority=1.0, num_units=1):\n mod = 'SEIZE, {}: {}, {}'.format(priority, resource, num_units)\n super().__init__(mod)\n # mod = 'SEIZE, {}: {}, {}'.format(priority, resource.name, num_units)\n # super().__init__(mod, resource)\n\n # For Repeats\n def add(self, resource_id=\"\", num_units=\"\"):\n add_list = [resource_id, num_units]\n super().add(add_list)\n\n\nclass DelayBlock(Block):\n def __init__(self, duration=0.0, storage_id=\"\"):\n mod = 'DELAY: {}, {}'.format(duration, storage_id)\n super().__init__(mod)\n\n\nclass ReleaseBlock(Block):\n def __init__(self, resource, quantity_to_release=1):\n mod = 'RELEASE: {}, {}'.format(resource, quantity_to_release)\n super().__init__(mod)\n # mod = 'RELEASE: {}, {}'.format(resource.name, quantity_to_release)\n # super().__init__(mod, resource)\n\n # For Repeats\n def add(self, resource_id=\"\", quantity_to_release=\"\"):\n add_list = [resource_id, quantity_to_release]\n super().add(add_list)\n\n\nclass CountBlock(Block):\n def __init__(self, counter, counter_increment=1):\n mod = 'COUNT: {}, {}'.format(counter.name, counter_increment)\n super().__init__(mod, counter)\n\n\nclass BranchBlock(Block):\n def __init__(self, branch_type, destination_label, max_branches=\"\", rand_num_stream=\"\", condition=\"\"):\n if branch_type.lower() in [\"else\", \"always\"]:\n mod = 'Branch, {}, {}: {}, {}'.format(max_branches, rand_num_stream, branch_type, destination_label)\n else:\n mod = 'Branch, {}, {}: {}, {}, {}'.format(max_branches, rand_num_stream, branch_type, condition,\n destination_label)\n super().__init__(mod)\n\n # For Repeats\n def add(self, branch_type, destination_label, condition=\"\"):\n if branch_type.lower() in [\"else\", \"always\"]:\n add_list = [branch_type, destination_label]\n else:\n add_list = [branch_type, condition, destination_label]\n super().add(add_list)\n\n\n# todo: determine how this affects the .exp. Does another var/attr need to be added?\n# todo: Should name string be passed or the element object?\nclass AssignBlock(Block):\n \"\"\"Name can be a SIMAN variable or attribute.\n Used for modifying an existing variable or attribute element\"\"\"\n def __init__(self, var_or_attr_id, value):\n mod = 'ASSIGN: {} = {}'.format(var_or_attr_id, value)\n super().__init__(mod)\n\n # For Repeats\n def add(self, name, value):\n add_list = [name, value]\n super().add(add_list)\n\n\nclass SelectBlock(Block):\n \"\"\"Selects from a defined group of SEIZE blocks, each with an explicitly defined Resource\n Thse SEIZE blocks are not preceded by their own individual QUEUE blocks, but share the QUEUE block preceding\n the SELECT block.\n\n Resource selection rules:\n CYC (cyclic priority), RAN (RANdom priority), POR (preferred order rule), LNB (Largest Number Busy),\n SNB (Smallest number busy), LRC (largest remaining capacity), SRC (smallest remaining capacity)\n \"\"\"\n def __init__(self, resource_rule='CYC', seize_labels=[]):\n mod = 'SELECT, {}: {}'.format(resource_rule, ': '.join(seize_labels))\n super().__init__(mod)\n\n\nclass PickQ(Block):\n \"\"\"Decides which QUEUE an arriving entity will join.\n\n Queue selection rules:\n CYC (cyclic priority), RAN (RANdom priority), POR (preferred order rule), LNB (Largest Number Busy),\n SNB (Smallest number busy), LRC (largest remaining capacity), SRC (smallest remaining capacity)\n \"\"\"\n def __init__(self, queue_rule='CYC', balk_label='', queue_label=[]):\n mod = 'PICKQ, {}, {}: {}'.format(queue_rule, balk_label, ': '.join(queue_label))\n super().__init__(mod)\n\n\nclass QPick(Block):\n \"\"\"Selects from upstream queues for entity removal. Must be followed by HOLD/SEIZE block.\n\n Queue selection rules:\n CYC (cyclic priority), RAN (RANdom priority), POR (preferred order rule), LNB (Largest Number Busy),\n SNB (Smallest number busy), LRC (largest remaining capacity), SRC (smallest remaining capacity)\n \"\"\"\n def __init__(self, queue_rule='CYC', queue_label=[]):\n mod = 'QPICK, {}: {}'.format(queue_rule, ': '.join(str(label) for label in queue_label))\n super().__init__(mod)\n\nclass StationBlock(Block):\n def __init__(self, begin_station_id, end_station_id=None):\n if end_station_id:\n mod = 'STATION, {}, {}'.format(begin_station_id, end_station_id)\n else:\n mod = 'STATION, {}'.format(begin_station_id)\n super().__init__(mod)\n\n\nclass RouteBlock(Block):\n def __init__(self, duration=0.0, destination=\"\"):\n mod = 'ROUTE: {}, {}'.format(duration, destination)\n super().__init__(mod)\n\n\nclass RequestBlock(Block):\n def __init__(self, priority=1, storage_id=\"\", alt_path=\"\", transporter_unit=\"\", velocity=\"\", entity_location=\"\"):\n mod = 'REQUEST, {}, {}, {}: {}, {}, {}'.format(priority, storage_id, alt_path, transporter_unit, velocity, entity_location)\n super().__init__(mod)\n\n\nclass TransportBlock(Block):\n def __init__(self, alt_path=\"\", transporter_unit=\"\", destination=\"\", velocity=\"\", guided_trans_dest=\"\"):\n mod = 'TRANSPORT, {}, {}: {}, {}, {}, {}'.format(alt_path, transporter_unit, destination, velocity, guided_trans_dest)\n super().__init__(mod)\n\n\nclass FreeBlock(Block):\n def __init__(self, transporter_unit):\n mod = 'FREE: {}'.format(transporter_unit)\n super().__init__(mod)\n\n\nclass AllocateBlock(Block):\n def __init__(self, priority=1, alt_path=\"\", transport_unit=\"\", entity_location=\"\"):\n mod = 'ALLOCATE: {}, {}: {}, {}'.format(priority, alt_path, transport_unit, entity_location)\n super().__init__(mod)\n\n\nclass MoveBlock(Block):\n def __init__(self, storage_id=\"\", alt_path=\"\", transport_unit=\"\", destination=\"\", velocity=\"\"):\n mod = 'MOVE, {}, {}: {}, {}, {}'.format(storage_id, alt_path, transport_unit, destination, velocity)\n super().__init__(mod)\n\n\nclass HalthBlock(Block):\n def __init__(self, transport_unit):\n mod = 'HALT: {}'.format(transport_unit)\n super().__init__(mod)\n\n\nclass DisposeBlock(Block):\n def __init__(self):\n mod = \"DISPOSE\"\n super().__init__(mod)\n\n\nclass SuperBlock:\n \"\"\"Create group of sequential blocks with reference id\"\"\"\n def __init__(self, name, blocks):\n if not isinstance(blocks, (list, tuple)):\n raise TypeError('argument must be list or tuple')\n if len(blocks) == 0:\n raise ValueError(\"empty list\")\n\n self.name = name\n self.type = \"mod\"\n self.blocks = blocks\n\n def __str__(self):\n string1 = str(self.name) + '\\t' + str(self.blocks[0])\n str_blocks = [string1] + [\" \"*len(self.name) + '\\t' + str(b) for b in self.blocks[1:]]\n return '\\n'.join(str_blocks) + '\\n'" }, { "alpha_fraction": 0.592476487159729, "alphanum_fraction": 0.5951634645462036, "avg_line_length": 24.965116500854492, "blob_id": "ee81da2aaf9475ebe9495ff64f379c43915aebab", "content_id": "58258bbe2a1bc34eea3e4ff153b10249bb95f6ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2233, "license_type": "no_license", "max_line_length": 79, "num_lines": 86, "path": "/utils.py", "repo_name": "abatkins/simanPy", "src_encoding": "UTF-8", "text": "def select(setExpr, resource_rule=\"CYC\", attribute_id=\"\"):\n return 'SELECT({}, {}, {})'.format(setExpr, resource_rule, attribute_id)\n\n\ndef int(attribute):\n return 'INT({})'.format(attribute)\n\n\ndef disc(values, cumsum=None):\n if not cumsum:\n p = 1/len(values)\n cumsum = [p*c for c in range(1, len(values)+1)]\n strings = ['{}, {}'.format(cumsum[i], val) for i, val in enumerate(values)]\n return 'DISC({})'.format(', '.join(strings))\n\n\ndef cont(values, cumsum=None):\n if not cumsum:\n p = 1/len(values)\n cumsum = [p*c for c in range(1, len(values)+1)]\n strings = ['{}, {}'.format(cumsum[i], val) for i, val in enumerate(values)]\n return 'CONT({})'.format(', '.join(strings))\n\n\ndef nq(queue_id):\n \"\"\"\n Returns number of items currently in the queue\n \"\"\"\n return 'NQ({})'.format(queue_id)\n\ndef nr(resource_id):\n \"\"\"\n Returns number of resources currently being used\n \"\"\"\n return 'NR({})'.format(resource_id)\n\n\ndef resUtil(resource_id):\n \"\"\"\n Return resource utilization time\n \"\"\"\n return 'ResUtil({})'.format(resource_id)\n\n# set functions\ndef numMem(set_name):\n \"\"\"\n returns the number of members in SetName\n \"\"\"\n return 'NumMem({})'.format(set_name)\n\n\ndef member(set_name, index):\n \"\"\"\n returns the element number of the member in SetName at position Index\n \"\"\"\n return 'Member({}, {})'.format(set_name, index)\n\n\ndef memIdx(set_name, member_name):\n \"\"\"\n returns the index of MemberName located in SetName\n \"\"\"\n return 'MemIdx({}, {})'.format(set_name, member_name)\n\n\nclass SelectionRule:\n \"\"\"\n Can be used with SELECT, PICKQ, QPICK\n \"\"\"\n def __init__(self):\n self.cyc = \"CYC\" # CYClic priority\n self.ran = \"RAN\" # RANdom priority\n self.por = \"POR\" # Preferred Order Rule\n self.lnb = \"LNB\" # Largest Number Busy\n self.snb = \"SNB\" # Smallest Number Busy\n self.lrc = \"LRC\" # Largest Remaining Capacity\n self.src = \"SRC\" # Smallest Remaining capacity\n\n\nclass ReleaseRule:\n \"\"\"\n Used with RELEASE block and SETS\n \"\"\"\n def __init__(self):\n self.last = \"LAST\" # Last Member Seized\n self.first = \"FIRST\" # First Member Seized\n" }, { "alpha_fraction": 0.7554524540901184, "alphanum_fraction": 0.7642691135406494, "avg_line_length": 28.49315071105957, "blob_id": "4bfee8dc2f4f077a4c3e3c6c78468cb8e3ca4c2f", "content_id": "a8ec4a4f26868f35400cf2ed793be079445a147b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2155, "license_type": "no_license", "max_line_length": 107, "num_lines": 73, "path": "/README.md", "repo_name": "abatkins/simanPy", "src_encoding": "UTF-8", "text": "# simanPy\nPython Interface for Siman Simulation Lanaguage\n\nThis project is still under active development. Please create an issue for bugs.\n\n## Dependencies\n* Must have SIMAN installed on the machine.\n* Python 3\n\n## Getting Started\n\nThe core data structure of SimanPy is a model, which is a way to organize blocks and elements.\n<pre>\nfrom model import Model\n\nmodel = Model()\n</pre>\n\nBlocks and elements can be added to the model using .add():\n<pre>\nfrom elements import Entity, Project, Replicate\n\nmodel = Model(\"Sample1\")\nmodel.add(Project(title=\"Sample Project\", analyst_name=\"Your Name\"))\nmodel.add(Replicate(num_replications=1, begin_time=0, replication_len=480))\n</pre>\n\nElements that are passed to blocks will automatically be added to the Model with the block.\n<pre>\nentity = Entity()\nmodel.add(CreateBlock(entity, interval=\"EXPO(4.4)\"))\n\nqueue = Queue(name=\"Buffer\", ranking_criterion=\"FIFO\")\nmodel.add(QueueBlock(queue, capacity=100))\n</pre>\n\nBlocks are written to the .mod file in the order they are added to the Model.\nThe order elements are added to the Model does not matter.\n\nTo generate the .mod and .exp files:\n<pre>\nmodel.compile()\n</pre>\n\nTo generate all files and run the simulation, simply use:\n<pre>\nmodel.run()\n</pre>\n\n## Super Blocks\n\nSuper blocks can be used to create block sequences with a reference ID. This is useful for Branch Blocks.\nLike other blocks, super blocks will be written to the .mod file in the same order they are added to Model.\n<pre>\n# Straightener Station\nstraightenQueueBlock = QueueBlock(straightenQueue)\nstraightenSeize = SeizeBlock(straightener)\nstraightenDelay = DelayBlock(duration=\"EXPO(15)\")\nstraightenRelease = ReleaseBlock(straightener)\n\nstraightenerPipeline = [straightenQueueBlock, straightenSeize, straightenDelay, straightenRelease]\nstraightenStation = SuperBlock(\"StraightenerStation\", straightenerPipeline)\n\n...\n...\n\nbranch1 = BranchBlock(max_branches=1, branch_type=\"If\", condition=\"Entity.Type==Part1\",\n destination_label=straightenStation.name)\nbranch1.add(branch_type=\"ELSE\", destination_label=finishStation.name)\nmodel.add(branch1)\n\nmodel.add(straightenStation)\n</pre>\n\n\n" }, { "alpha_fraction": 0.5174234509468079, "alphanum_fraction": 0.5278071165084839, "avg_line_length": 37.65986251831055, "blob_id": "9a7b5d7d4222b96dc68b98d456012362939fdd08", "content_id": "fd8c9619920ab5a9d3fe6e3b4d4e5cff82f92e2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5682, "license_type": "no_license", "max_line_length": 126, "num_lines": 147, "path": "/parse.py", "repo_name": "abatkins/simanPy", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 5 15:55:14 2016\n\n@author: altur\n@edited: abatkins\n\"\"\"\nimport re, argparse\nimport pandas as pd\nimport numpy as np\nimport scipy.stats as stats\n\n\n# Parse SIMAN outfile. Convert output to df/csv.\ndef parse(infile):\n data = {'TALLY VARIABLES': [[], ['run_id', 'identifier', 'average', 'half_width', 'min', 'max', 'obs']],\n 'DISCRETE-CHANGE VARIABLES': [[], ['run_id', 'identifier', 'average', 'half_width', 'min', 'max', 'final_value']],\n 'COUNTERS': [[], ['run_id', 'identifier', 'count', 'limit']]}\n replications = 0\n count = 0\n\n # Get filesize\n with open(infile, 'r') as f:\n num_lines = len(f.readlines())\n\n with open(infile, 'r') as f:\n # Iterate over each replication\n while count <= num_lines:\n key = re.sub(\"\\s\\s+\", \" \", f.readline()).strip()\n count += 1\n if key == \"ARENA Simulation Results\": # start of new replication\n replications += 1\n if key in data.keys(): # start of new section\n [f.readline() for i in range(4)]\n count += 4\n\n # Iterate over a variable section for a single replication\n while True:\n text = re.sub(\"\\s\\s+\", \" \", f.readline()).strip()\n count += 1\n if text != \"\": # Not end of section\n values = text.split(\" \")\n var_size = len(values) - len(data[key][1]) + 1\n if var_size > 0: # handle varnames with spaces\n row = [str(replications)] + ['_'.join(values[:var_size+1]).lower()] + values[var_size+1:]\n else:\n row = [str(replications)] + [values[0].lower()] + values[1:]\n data[key][0].append(row)\n else: # end of section\n break\n f.close()\n\n # Tally Variables Dataframe\n data['TALLY VARIABLES'] = pd.DataFrame(\n data=data['TALLY VARIABLES'][0],\n columns=data['TALLY VARIABLES'][1]\n ).apply(pd.to_numeric, args=('ignore',))\n\n # DSTATS Variables Dataframe\n data['DISCRETE-CHANGE VARIABLES'] = pd.DataFrame(\n data=data['DISCRETE-CHANGE VARIABLES'][0],\n columns=data['DISCRETE-CHANGE VARIABLES'][1]\n ).apply(pd.to_numeric, args=('ignore',))\n\n # Counter Dataframe\n data['COUNTERS'] = pd.DataFrame(\n data=data['COUNTERS'][0],\n columns=data['COUNTERS'][1]\n ).apply(pd.to_numeric, args=('ignore',))\n\n # Output to csv\n outfile = infile.split('.')[0]\n data['TALLY VARIABLES'].to_csv(outfile + '_tally.csv')\n data['DISCRETE-CHANGE VARIABLES'].to_csv(outfile + '_dstat.csv')\n data['COUNTERS'].to_csv(outfile + '_counters.csv')\n\n return data, outfile\n\n# Creates df/csv with aggregate statistics over all replications. Includes mean and confidence intervals.\n# Note: Use the to_latex method to output the df to a latex table.\ndef aggregate_stats(data, outfile_name=None, alpha=.05):\n results = []\n for df in data.values():\n names = df.identifier.unique()\n df_group = df.groupby('identifier')\n for name in names:\n if 'average' in df_group.get_group(name).columns:\n group_vals = df_group.get_group(name)['average']\n else:\n group_vals = df_group.get_group(name)['count']\n mean, ci = _compute_stats(group_vals)\n\n if 'obs' in df_group.get_group(name).columns:\n obs_vals = df_group.get_group(name)['obs']\n obs_mean, obs_ci = _compute_stats(obs_vals)\n else:\n obs_mean, obs_ci = None, None\n\n if 'min' in df_group.get_group(name).columns:\n min_vals = df_group.get_group(name)['min']\n min_mean, min_ci = _compute_stats(min_vals)\n else:\n min_mean, min_ci = None, None\n\n if 'max' in df_group.get_group(name).columns:\n max_vals = df_group.get_group(name)['max']\n max_mean, max_ci = _compute_stats(max_vals)\n else:\n max_mean, max_ci = None, None\n\n results.append([name, mean, ci, min_mean, max_mean, obs_mean, obs_ci])\n agg_df = pd.DataFrame(data=results,\n columns=['identifier',\n 'average', '{}% CI'.format(int((1-alpha)*100)),\n 'min',\n 'max',\n 'obs', '{}% CI'.format(int((1 - alpha) * 100))\n ])\n agg_df.to_csv(outfile_name + '_aggregate.csv')\n\n return agg_df\n\n\ndef _compute_stats(vals, alpha=.05):\n vals = [0.0 if val == '.00000' else float(val) for val in vals if val != '--']\n mean = np.mean(vals)\n if len(np.unique(vals)) > 1: # Compute CI\n lb, ub = stats.t.interval(1 - alpha, len(vals) - 1, loc=mean, scale=stats.sem(vals))\n ci = \"({:.4f}, {:.4f})\".format(float(lb), float(ub))\n else: # Don't bother with CI if all values are the same.\n ci = \"NA\"\n return round(float(mean), 4), ci\n\nif __name__ == \"__main__\":\n # Arg Parser\n parser = argparse.ArgumentParser(description='Process some integers.')\n parser.add_argument('--infile', '-i', type=str, help='Input file')\n parser.add_argument('--latex', '-l', action='store_true', help='Print Latex Table')\n\n args = parser.parse_args()\n data, outfile = parse(args.infile)\n agg = aggregate_stats(data, outfile)\n\n if args.latex:\n print(agg.to_latex())\n else:\n print(agg)" }, { "alpha_fraction": 0.7218259572982788, "alphanum_fraction": 0.7475035786628723, "avg_line_length": 24.071428298950195, "blob_id": "b13d9774c8b9f9a6842aaebfe867aa1b499bedb2", "content_id": "d0f21d197088dd01d055b433d581307edb5d7085", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 701, "license_type": "no_license", "max_line_length": 75, "num_lines": 28, "path": "/examples/sample1.py", "repo_name": "abatkins/simanPy", "src_encoding": "UTF-8", "text": "from elements import *\nfrom blocks import *\nfrom model import Model\n\nmodel = Model(\"sample1\")\nmodel.add(Project(title=\"Sample1 Project\", analyst_name=\"Your Name\"))\nmodel.add(Discrete(max_entities=100))\nmodel.add(Replicate(num_replications=1, begin_time=0, replication_len=480))\n\nentity = Entity(name=\"Part\")\nmodel.add(CreateBlock(entity, interval=\"EXPO(4.4)\"))\n\nqueue = Queue(name=\"Buffer\", ranking_criterion=\"FIFO\")\nmodel.add(QueueBlock(queue))\n\nresource = Resource(name=\"Machine\")\nmodel.add(SeizeBlock(resource))\n\nmodel.add(DelayBlock(\"TRIA(3.2,4.2,5.2)\"))\n\nmodel.add(ReleaseBlock(resource))\n\ncounter = Counter(name=\"JobsDone\")\nmodel.add(CountBlock(counter))\n\nmodel.add(DisposeBlock())\n\nmodel.compile()" }, { "alpha_fraction": 0.572248637676239, "alphanum_fraction": 0.5732383131980896, "avg_line_length": 39.42399978637695, "blob_id": "bed00fd5812c4fdf54f0b21831d602228ae43706", "content_id": "76bf1a12a85307f80140f9617385dbd953b5feab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5052, "license_type": "no_license", "max_line_length": 116, "num_lines": 125, "path": "/model.py", "repo_name": "abatkins/simanPy", "src_encoding": "UTF-8", "text": "from elements import _Begin, _End, _Queues, _Entities, _Counters, _Resources, _Attributes, _Variables, _Dstats, \\\n _Tallies, _Storages, _Outputs, _Stations, _Sets, _Sequences, _Pictures\nimport subprocess\n\n\nclass Model:\n def __init__(self, filename, run_controller=\"No\"):\n self.filename = filename\n self.exp = []\n self.mod = []\n self.collections = {}\n self.run_controller = run_controller\n\n # Allocates block and element data to correct file\n def add(self, obj):\n if obj.type == \"mod\":\n if hasattr(obj, \"blocks\") and obj.blocks: # check if superblock\n for block in obj.blocks:\n if hasattr(block, \"element\") and block.element:\n self._add_element(block.element)\n else: # normal block\n if hasattr(obj, \"element\") and obj.element:\n self._add_element(obj.element)\n self.mod.append(obj)\n elif obj.type == \"exp\": # Elements block\n self.exp.append(obj)\n elif obj.type == \"element\": # Element block\n self._add_element(obj)\n else:\n raise ValueError(\"Extension type %s is not recognized\" % obj.type)\n\n def _to_collection(self, key, elements_inst, element):\n collection = self.collections.get(key, elements_inst)\n if element.number == \"\" or element.number is None:\n element.number = len(collection.elements) + 1\n collection.add(element)\n self.collections[key] = collection\n\n # Adds element stored in blocks\n def _add_element(self, element):\n key = element.__class__.__name__\n if key == \"Queue\":\n self._to_collection(key, _Queues(), element)\n elif key == \"Resource\":\n self._to_collection(key, _Resources(), element)\n elif key == \"Counter\":\n self._to_collection(key, _Counters(), element)\n elif key == \"Attribute\":\n self._to_collection(key, _Attributes(), element)\n elif key == \"Variable\":\n self._to_collection(key, _Variables(), element)\n elif key == \"Dstat\":\n self._to_collection(key, _Dstats(), element)\n elif key == \"Tally\":\n self._to_collection(key, _Tallies(), element)\n elif key == \"Storage\":\n self._to_collection(key, _Storages(), element)\n elif key == \"Entity\":\n self._to_collection(key, _Entities(), element)\n elif key == \"Output\":\n self._to_collection(key, _Outputs(), element)\n elif key == \"Station\":\n self._to_collection(key, _Stations(), element)\n elif key == \"Set\":\n self._to_collection(key, _Sets(), element)\n elif key == \"Sequence\":\n self._to_collection(key, _Sequences(), element)\n elif key == \"Picture\":\n self._to_collection(key, _Pictures(), element)\n else:\n raise ValueError(\"Class name not recognized!\")\n\n # Writes to SIMAN files\n def compile(self):\n exp = list(self.collections.values()) + self.exp\n mod_filename = self.filename + \".mod\"\n exp_filename = self.filename + \".exp\"\n self._to_file(mod_filename, self.mod)\n self._to_file(exp_filename, exp)\n\n return mod_filename, exp_filename\n\n # Run model.exe\n def run_mod(self, input_file, output_file=None):\n if not output_file:\n output_file = input_file.split('.')[0] + '.m'\n subprocess.run('model {} {}'.format(input_file, output_file), shell=True, check=True)\n return output_file\n\n # Run expmt.exe\n def run_expmt(self, input_file, output_file=None):\n if not output_file:\n output_file = input_file.split('.')[0] + '.e'\n subprocess.run('expmt {} {}'.format(input_file, output_file),shell=True, check=True)\n return output_file\n\n # Run linker.exe\n def run_link(self, mod_file, exp_file, output_file=None):\n if not output_file:\n output_file = mod_file.split('.')[0] + '.p'\n subprocess.run('linker {} {} {}'.format(mod_file, exp_file, output_file), shell=True, check=True)\n return output_file\n\n # Run siman.exe\n def run_siman(self, input_file, suppress=False):\n if suppress:\n subprocess.run('siman {} > {}.out'.format(input_file, input_file.split('.')[0]), shell=True, check=True)\n else:\n subprocess.run('siman {}'.format(input_file), shell=True, check=True)\n\n # Run Simulation\n def run(self, suppress=False):\n mod_filename, exp_filename = self.compile()\n m_filename = self.run_mod(mod_filename)\n e_filename = self.run_expmt(exp_filename)\n p_filename = self.run_link(m_filename, e_filename)\n self.run_siman(p_filename, suppress)\n\n def _to_file(self,filename, objs):\n file = open(filename, 'w')\n file.write(\"%s\\n\" % str(_Begin(run_controller=self.run_controller)))\n for obj in objs:\n file.write(\"%s\\n\" % obj)\n file.write(str(_End()))\n file.close()" }, { "alpha_fraction": 0.7633617520332336, "alphanum_fraction": 0.7823392748832703, "avg_line_length": 31.696203231811523, "blob_id": "92b41572d24b49d2b301b561ad53d50362965b1f", "content_id": "e06fccb2dbab4501605696e3c68bcbd386916bdb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2582, "license_type": "no_license", "max_line_length": 98, "num_lines": 79, "path": "/examples/sample2.py", "repo_name": "abatkins/simanPy", "src_encoding": "UTF-8", "text": "from model import Model\nfrom blocks import *\nfrom elements import *\n\n# Initialize model\nmodel = Model(\"sample2\")\nmodel.add(Project(title=\"Sample2 Project\", analyst_name=\"Your Name\"))\nmodel.add(Replicate(num_replications=1, begin_time=0, replication_len=5000, warmup_period=1000))\n\n# Define Resources\ndrill = Resource(name=\"Drill\", capacity=2)\nstraightener = Resource(name=\"Straightener\", capacity=1)\nfinisher = Resource(name=\"Finisher\", capacity=1)\n\n# Define Queues\ndrillQueue = Queue(name=\"Drill.Queue\")\nstraightenQueue = Queue(name=\"Straighten.Queue\")\nfinishQueue = Queue(name=\"Finish.Queue\")\n\n# Define Counters\ncounter1 = Counter(name=\"Part1\")\ncounter2 = Counter(name=\"Part2\")\ncounterTotal = Counter(name=\"TotalEntities\")\n\n# ------- SuperBlocks ------------\n# Drill Station\ndrillQueueBlock = QueueBlock(drillQueue)\ndrillSeize = SeizeBlock(drill, num_units=1)\ndrillDelay = DelayBlock(duration=\"NORM(10,1)\")\ndrillRelease = ReleaseBlock(drill)\n\ndrillPipeLine = [drillQueueBlock, drillSeize, drillDelay, drillRelease]\ndrillStation = SuperBlock(\"DrillStation\", drillPipeLine)\n\n# Straightener Station\nstraightenQueueBlock = QueueBlock(straightenQueue)\nstraightenSeize = SeizeBlock(straightener)\nstraightenDelay = DelayBlock(duration=\"EXPO(15)\")\nstraightenRelease = ReleaseBlock(straightener)\n\nstraightenerPipeline = [straightenQueueBlock, straightenSeize, straightenDelay, straightenRelease]\nstraightenStation = SuperBlock(\"StraightenerStation\", straightenerPipeline)\n\n# Finish Station\nfinishQueueBlock = QueueBlock(finishQueue)\nfinishSeize = SeizeBlock(finisher)\nfinishDelay = DelayBlock(5)\nfinishRelease = ReleaseBlock(finisher)\n\nfinishPipeline = [finishQueueBlock, finishSeize, finishDelay, finishRelease]\nfinishStation = SuperBlock(\"FinishStation\", finishPipeline)\n\n# Model Blocks\n# todo: Determine how MARK(TimeIn) should be implemented\nmodel.add(CreateBlock(Entity(\"Part1\"), batch_size=1, offset_time=0, interval=30))\nmodel.add(CountBlock(counter1))\ndelay1 = DelayBlock(duration=2)\ndelay1.set_next(drillStation)\nmodel.add(delay1)\n\nmodel.add(CreateBlock(Entity(\"Part2\"), batch_size=1, offset_time=0, interval=20))\nmodel.add(CountBlock(counter2))\nmodel.add(DelayBlock(duration=10))\n\nmodel.add(drillStation)\n\nbranch1 = BranchBlock(max_branches=1, branch_type=\"If\", condition=\"Entity.Type==Part1\",\n destination_label=straightenStation.name)\nbranch1.add(branch_type=\"ELSE\", destination_label=finishStation.name)\nmodel.add(branch1)\n\nmodel.add(straightenStation)\n\nmodel.add(finishStation)\n\nmodel.add(CountBlock(counterTotal))\nmodel.add(DisposeBlock())\n\nmodel.compile()" } ]
8
dmatik/HomeAssistant-Config-1
https://github.com/dmatik/HomeAssistant-Config-1
cd3f02ad74a5acee40997fd4a5078f4bb75fdbd2
eb26c66f738ca28ba5a2eb50906b0b4205f58f54
e7d9080381a191de5d213d91b6b6d21280800331
refs/heads/master
2023-04-15T11:19:55.825270
2021-04-27T18:15:34
2021-04-27T18:15:34
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6505327820777893, "alphanum_fraction": 0.6861116290092468, "avg_line_length": 49.33636474609375, "blob_id": "f2947d6489b7ed9100bfb50cf450cc5e5c16b2e4", "content_id": "011c319a0cac5ab119a771d43f001a84fdc5d438", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5542, "license_type": "no_license", "max_line_length": 542, "num_lines": 110, "path": "/README.md", "repo_name": "dmatik/HomeAssistant-Config-1", "src_encoding": "UTF-8", "text": "![Maintenance](https://img.shields.io/maintenance/yes/2021.svg?style=plasticr)\n[![GitHub last commit](https://img.shields.io/github/last-commit/yuvalabou/HomeAssistant-Config.svg?style=plasticr)](https://github.com/geekofweek/HomeAssistant-Config/commits/master)\n[![HA Version](https://img.shields.io/badge/Running%20Home%20Assistant-2021.4.6%20-darkblue)](https://github.com/home-assistant/home-assistant/releases/latest)\n[![Commits/Year](https://img.shields.io/github/commit-activity/y/yuvalabou/HomeAssistant-Config.svg?style=plasticr)](https://github.com/yuvalabou/HomeAssistant-Config/commits/master)\n[![GitHub stars](https://img.shields.io/github/stars/yuvalabou/HomeAssistant-Config.svg?style=plasticr)](https://github.com/yuvalabou/HomeAssistant-Config/stargazers)\n\n<h2 align =\n \"center\">\n 🏡 <a href=\"https://www.home-assistant.io\">Home Assistant</a> Configuration &amp; documentation for my Smart Home.\n</h2>\n\n<p align = \"center\">\n Hi, My name is Yuval Aboulafia.\n</p>\n\n<p align = \"center\">\n Please ⭐ this repo if you find it useful.\n</p>\n <p align = \"center\">\n <a href =\n \"https://www.buymeacoffee.com/HMa8m26\"\n target=\"_blank\">\n <img src=\"https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png\"\n alt=\"Buy Me A Coffee\"\n style=\"height: 41px !important;width: 174px !important;box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;-webkit-box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;\">\n</p>\n\n-----\n\n## Statistics\n\n| Type | Count |\n|------|:-----:|\n| **Entities** | 409 |\n| **[Sensors](https://github.com/yuvalabou/HomeAssistant-Config/tree/master/sensor)** | 245 |\n| **[Binary Sensors](https://github.com/yuvalabou/HomeAssistant-Config/tree/master/binary_sensor)** | 42 |\n| **[Switches](https://github.com/yuvalabou/HomeAssistant-Config/tree/master/switch)** | 11 |\n| **[Automations](https://github.com/yuvalabou/HomeAssistant-Config/tree/master/automation)** | 42 |\n| **[Scripts](https://github.com/yuvalabou/HomeAssistant-Config/tree/master/script)** | 25 |\n\n-----\n\n## [Lovelace](https://github.com/yuvalabou/HomeAssistant-Config/tree/master/lovelace/ui-lovelace)\n\n| Lovelace Mode | Dashboards | Views | Resources |\n|:-------------:|:----------:|:-----:|:---------:|\n|YAML |1 |10 |22 |\n\n-----\n\n### Devices\n\n| Nest mini | Roborock S50 | YEELIGHT (YLDP06YL) | Sensibo Sky | Tuya |\n|:---------:|:------------:|:-------------------:|:-----------:|:----:|\n|<img src=\"https://lh3.googleusercontent.com/7pq6Fhyz_qUGO8ORh6y0Bn6g7lRSBg3yHkNBXmt51g-mc2Viuv6LMjk4E0NXZGI7Rk4\" width = 100>|<img src=\"https://www.lior-electric.co.il/wp-content/uploads/2019/06/46947609c.gif.jpeg\" width = 100>|<img src=\"https://poood.ru/img/goods/yeelight_lampa_xiaomi_led_bulb_color_1700k-6500k_yldp06yl_5.jpg\" width=100>|<img src=\"https://cdn.shopify.com/s/files/1/1669/6891/products/minimised-M16_128691-1_1024x1024.jpg?v=1583048706\" width=100>|<img src=\"https://consent.trustarc.com/get?name=tuya_logo2.png\" width=100>|\n|1 |1 |3 |2 |2 |\n\n-----\n\n### HomeLab\n\n| NanoPi NEO2 | NanoPi NEO3 | RaspberryPi 2 |\n|:----------------:|:-------------:|:--------------:|\n| PiHole | HomeAssistant | OpenMediaVault |\n| Mosquitto broker | PostgreSQL DB | NUT UPS tools |\n| Portainer | Portainer | |\n\n-----\n\n## HACS custom components\n\n<img src =\n \"https://avatars2.githubusercontent.com/u/56713226?s=200&v=4\"\n align = \"right\" width=90>\n\n[HACS](https://github.com/hacs/integration) is Home Assistant Community Store\n\n- [Official site](https://hacs.xyz/) - For installation instructions\n- [Releases](https://github.com/hacs/integration/releases)\n\n### Integrations\n\n- [City-mind Water Meter](https://github.com/maorcc/citymind_water_meter)\n- [FeedParser](https://github.com/custom-components/feedparser)\n- [Open media vault](https://github.com/tomaae/homeassistant-openmediavault)\n- [Pyscript](https://github.com/custom-components/pyscript)\n- [Xiaomi cloud map extractor](https://github.com/PiotrMachowski/Home-Assistant-custom-components-Xiaomi-Cloud-Map-Extractor)\n\n### Lovelace-UI Enhancements\n\n- [Animated Consumption Card](https://github.com/bessarabov/animated-consumption-card)\n- [Auto Entities](https://github.com/thomasloven/lovelace-auto-entities)\n- [ApexCharts Card](https://github.com/RomRider/apexcharts-card)\n- [Bar Card](https://github.com/custom-cards/bar-card)\n- [Battery Entity Row](https://github.com/benct/lovelace-battery-entity-row)\n- [Card Mod](https://github.com/thomasloven/lovelace-card-mod) - Apply CSS styles to any card\n- [Fold Entity Row](https://github.com/thomasloven/lovelace-fold-entity-row)\n- [Hui-Element](https://github.com/thomasloven/lovelace-hui-element) - The most versatile of them all.\n- [Layout Card](https://github.com/thomasloven/lovelace-layout-card)\n- [Template Entity Row](https://github.com/thomasloven/lovelace-template-entity-row)\n- [Time Picker Card](https://github.com/GeorgeSG/lovelace-time-picker-card)\n- [Mini Graph Card](https://github.com/kalkih/mini-graph-card) - This one is probably one of the more powerful cards out there.\n- [Mini Media Player](https://github.com/kalkih/mini-media-player)\n- [Multiple Entity Row](https://github.com/benct/lovelace-multiple-entity-row)\n- [Simple Thermostat](https://github.com/nervetattoo/simple-thermostat)\n- [Weather Card](https://github.com/bramkragten/weather-card)\n\n-----\n\nYou can join us on [Discord!](https://discord.gg/ayZ3Kkg)\n" }, { "alpha_fraction": 0.6696428656578064, "alphanum_fraction": 0.6696428656578064, "avg_line_length": 17.675676345825195, "blob_id": "bb8de94e9cbd2c36e8cfc452b83a5617a05ebb98", "content_id": "7d8055eacb3365d6db781944ba184511d923f884", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1456, "license_type": "no_license", "max_line_length": 70, "num_lines": 74, "path": "/homeassistant/config/automation/README.md", "repo_name": "dmatik/HomeAssistant-Config-1", "src_encoding": "UTF-8", "text": "# [Automations](https://www.home-assistant.io/integrations/automation)\r\n\r\nHere is a summery of the Automations and their functionality\r\n\r\n---\r\n\r\n## Climate\r\n- ### Climate\r\n Climate control\r\n- ### Shabbat climate\r\n Climate control, But for Shabbat\r\n\r\n---\r\n\r\n## Lights\r\nAutomations for lightings\r\n- ### Lights\r\n General lights control\r\n- ### Living room motion lights\r\n Light up when passing by\r\n- ### Living room\r\n General lightings\r\n- ### Master bedroom\r\n General lightings\r\n- ### Shabbat lighting\r\n General lightings, But for Shabbat\r\n\r\n---\r\n\r\n## Notify\r\nNotifications\r\n- ### Notify batteries\r\n Notify us when cellphones bateries are fully charged\r\n- ### Notify mold\r\n Notify us when mold is developing in the bathroom\r\n- ### Notify Shabbat\r\n Notifications for Shabbat\r\n- ### Notify UPS\r\n Notify on power changes\r\n\r\n---\r\n\r\n## Vacuum\r\nRobot Vacuum automations\r\n- ### Notify Vacuum\r\n Notify for cleaning changes\r\n- ### Vacuum Shabbat\r\n Robot Vacuum automations, But for Shabbat\r\n- ### Vacuum\r\n General Vacuum automations\r\n\r\n---\r\n\r\n## IMS Sensor\r\nUpdate the IMS Sensor\r\n\r\n---\r\n\r\n## Shabbat plate\r\nAutomating the Shabbat plate\r\n- ### Shabbat plate\r\n Automations to control Shabbat heating plate in Shabbat\r\n- ### Chag plate\r\n Automations to control Shabbat heating plate in Chag\r\n\r\n---\r\n\r\n## Themes\r\nAutomations to switch between themes\r\n\r\n---\r\n\r\n## TTS\r\nAutomations related to my voice assistant tts services\r\n" }, { "alpha_fraction": 0.7812879681587219, "alphanum_fraction": 0.7812879681587219, "avg_line_length": 38.19047546386719, "blob_id": "809b6c65095290c32b515844446d7b9a1fb73784", "content_id": "810c01507a002c9cdcd8c687dc1d53ce87e46e46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 823, "license_type": "no_license", "max_line_length": 156, "num_lines": 21, "path": "/homeassistant/config/integrations/switch/README.md", "repo_name": "dmatik/HomeAssistant-Config-1", "src_encoding": "UTF-8", "text": "# [Switches](https://www.home-assistant.io/integrations/switch)\n\nHere is a summery of the custom switches and their functionality\n\n_Keeps track which switches are in your environment, their state and allows you to control them._\n\n## Climate\n\n[Template](https://www.home-assistant.io/integrations/switch.template/) switch to create a \"on/off\" switch for the living room AC unit\n\n## Lights\n\n[Template](https://www.home-assistant.io/integrations/switch.template/) switch to enable/disable motion triggered lights at night\n\n## Shabat switch\n\n[Template](https://www.home-assistant.io/integrations/switch.template/) to create a \"on/off\" switch for Shabat mode that disable all human triggered sensors\n\n## Vacuum\n\n[Template](https://www.home-assistant.io/integrations/switch.template/) switch to disable vacuum automatic cleaning\n" }, { "alpha_fraction": 0.5328759551048279, "alphanum_fraction": 0.5860491991043091, "avg_line_length": 22.985713958740234, "blob_id": "188642fac5f93fe63230bbedefb6abb407475b54", "content_id": "bbba49a9b3f591544d20bde99617d8f46af09f66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "YAML", "length_bytes": 1749, "license_type": "no_license", "max_line_length": 70, "num_lines": 70, "path": "/docker-compose.yaml", "repo_name": "dmatik/HomeAssistant-Config-1", "src_encoding": "UTF-8", "text": "---\r\nversion: '3.4'\r\n\r\nservices:\r\n homeassistant:\r\n restart: always\r\n depends_on:\r\n - postgres\r\n hostname: homeassistant\r\n container_name: \"homeassistant\"\r\n image: homeassistant/home-assistant:latest\r\n environment:\r\n - TZ=Asia/Jerusalem\r\n volumes:\r\n - /home/homeassistant/homeassistant/homeassistant/config:/config\r\n - /var/run/docker.sock:/var/run/docker.sock\r\n network_mode: host\r\n dns:\r\n - ${PIHOLE}\r\n\r\n postgres:\r\n restart: always\r\n hostname: postgres\r\n container_name: \"postgres\"\r\n image: postgres:latest\r\n network_mode: host\r\n ports:\r\n - 35432:5432\r\n environment:\r\n PUID: ${LOCAL_USER}\r\n PGID: ${LOCAL_USER}\r\n TZ: 'Asia/Jerusalem'\r\n POSTGRES_USER: ${POSTGRES_USER}\r\n POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}\r\n POSTGRES_DB: HADB\r\n volumes:\r\n - /home/homeassistant/postgres/data:/var/lib/postgresql/data\r\n\r\n portainer:\r\n hostname: portainer\r\n container_name: portainer\r\n image: portainer/portainer-ce:latest\r\n restart: always\r\n network_mode: bridge\r\n ports:\r\n - '9000:9000'\r\n environment:\r\n TZ: \"Asia/Jerusalem\"\r\n volumes:\r\n - /var/run/docker.sock:/var/run/docker.sock\r\n\r\n # unifi-controller:\r\n # image: ghcr.io/linuxserver/unifi-controller\r\n # container_name: unifi-controller\r\n # environment:\r\n # - PUID=${LOCAL_USER}\r\n # - PGID=${LOCAL_USER}\r\n # volumes:\r\n # - /home/homeassistant/unifi/config:/config\r\n # ports:\r\n # - 3478:3478/udp\r\n # - 10001:10001/udp\r\n # - 8080:8080\r\n # - 8443:8443\r\n # - 1900:1900/udp\r\n # - 8843:8843\r\n # - 8880:8880\r\n # - 6789:6789\r\n # - 5514:5514\r\n # restart: unless-stopped\r\n" }, { "alpha_fraction": 0.6235954761505127, "alphanum_fraction": 0.6235954761505127, "avg_line_length": 7.476190567016602, "blob_id": "f412d6a6ff3d9a714b71c6022c32b18af1b2bee6", "content_id": "a14f59636026eedde4acfda668ed01815831bc52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 178, "license_type": "no_license", "max_line_length": 36, "num_lines": 21, "path": "/homeassistant/config/lovelace/ui-lovelace/README.md", "repo_name": "dmatik/HomeAssistant-Config-1", "src_encoding": "UTF-8", "text": "# Lovelace-UI\n\nHere is my Lovelace-ui configuration\n\n## Views\n\n### Overview\n\n### Living room\n\n### Master bedroom\n\n### Bathroom\n\n### Home office\n\n### Stats\n\n### Extra\n\n### System\n" }, { "alpha_fraction": 0.7759175896644592, "alphanum_fraction": 0.7759175896644592, "avg_line_length": 38.82051467895508, "blob_id": "8c015637f37ddc47e7c35c1930d09b6f5db59c9b", "content_id": "fe3cc5c57720fb2bf768f87dec1e7ddf26f871ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1553, "license_type": "no_license", "max_line_length": 199, "num_lines": 39, "path": "/homeassistant/config/integrations/binary_sensor/README.md", "repo_name": "dmatik/HomeAssistant-Config-1", "src_encoding": "UTF-8", "text": "# Binary sensors\n\n_Binary sensors are an easy to manage \"trigger\" sensors and can also represent device status as shown in the [Binary Sensor](https://www.home-assistant.io/integrations/binary_sensor/) Documentations_\n\nHere is a summery of the sensors and their functionality\n\n## Climate\n\n[Template](https://www.home-assistant.io/integrations/binary_sensor.template/) binary sensor to test if an AC unit is currently on\n\n## Jewish Calendar\n\n- [Template](https://www.home-assistant.io/integrations/binary_sensor.template/) binary sensor to test whether it is fast today.\n- [Template](https://www.home-assistant.io/integrations/binary_sensor.template/) binary sensor to trigger notifications about upcoming time\n\n## Lights\n\n[Template](https://www.home-assistant.io/integrations/binary_sensor.template/) binary sensor to test if certain lights are on\n\n## Ping\n\n[Ping](https://www.home-assistant.io/integrations/ping/) sensor to track multiple conected devices around the house\n\n## Random\n\nStandard [Random boolean](https://www.home-assistant.io/integrations/random/) sensor\n\n## Steam\n\n[Template](https://www.home-assistant.io/integrations/binary_sensor.template/) binary sensor to test if someone is currently playing a game on steam\n\n## Time\n\n- [Time of Day](https://www.home-assistant.io/integrations/tod/) to track the \"state\" of the day\n- Standard [Workday](https://www.home-assistant.io/integrations/workday/) Sensor\n\n## TV\n\n[Template](https://www.home-assistant.io/integrations/binary_sensor.template/) binary sensor to track applications watch time\n" }, { "alpha_fraction": 0.7567418813705444, "alphanum_fraction": 0.7581177949905396, "avg_line_length": 40.7529411315918, "blob_id": "d19abd4e9c4c317ca768004c425b750b72ef7c75", "content_id": "5db41367e2fe19bd74572f78b4662f01ca622a42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3634, "license_type": "no_license", "max_line_length": 226, "num_lines": 85, "path": "/homeassistant/config/integrations/sensor/README.md", "repo_name": "dmatik/HomeAssistant-Config-1", "src_encoding": "UTF-8", "text": "# [Sensors](https://www.home-assistant.io/integrations/sensor)\r\n\r\nHere is a summery of the sensors and their functionality\r\n\r\n_Sensors are gathering information about states and conditions.\r\n\r\n_Home Assistant currently supports a wide range of sensors. They are able to display information which are provides by Home Assistant directly, are gathered from web services, and, of course, physical devices._\r\n\r\n## Climate Indoor\r\n\r\n[Template](https://www.home-assistant.io/integrations/template/) binary sensor to test if an AC unit is currently on\r\n\r\n## Climate Outdoor\r\n\r\n- [Template](https://www.home-assistant.io/integrations/template/) sensor to extract outdoor temperature\r\n- [Template](https://www.home-assistant.io/integrations/template/) sensor to extract and reformat wind values\r\n- [Template](https://www.home-assistant.io/integrations/template/) sensor to extract and reformat UV radiation values\r\n\r\n## Counters\r\n\r\n[Template](https://www.home-assistant.io/integrations/template/) sensors to count Home-Assistant Entities\r\n\r\n## Datetime\r\n\r\nStandard [Season](https://www.home-assistant.io/integrations/season/) sensor\r\n\r\n## DB\r\n\r\n[SQL](https://www.home-assistant.io/integrations/sql/) sensor to get the database size\r\n\r\n## FeedParser\r\n\r\nTBD\r\n\r\n## IMS\r\n\r\n[MQTT](https://www.home-assistant.io/integrations/sensor.mqtt/) sensor to get the forecast from a [pyscript](https://github.com/custom-components/pyscript) sensor\r\n\r\n## Jewish Calendar\r\n\r\n[Template](https://www.home-assistant.io/integrations/template/) sensor to extract certain times in HH:MM format\r\n\r\n## Mobile app\r\n\r\n[Template](https://www.home-assistant.io/integrations/template/) sensor to extract and reformat certain sensors\r\n\r\n## Pi-Hole\r\n\r\n[Command Line](https://www.home-assistant.io/integrations/sensor.command_line/) sensor to fetch Pi-Hole status from its web api\r\n\r\n## Power calculations\r\n\r\n[Template](https://www.home-assistant.io/integrations/template/) sensor to track theoretical power usage of some devices\r\n\r\n## Random\r\n\r\nStandard [Random](https://www.home-assistant.io/integrations/random/) sensor\r\n\r\n## Steam\r\n\r\n- [Steam online](https://www.home-assistant.io/integrations/steam_online/) sensor platform to fetch data from steam account\r\n- [Template](https://www.home-assistant.io/integrations/template/) sensor to extract the current game being played\r\n- [History stats](https://www.home-assistant.io/integrations/history_stats/) sensor to track Steam playtime\r\n\r\n## System\r\n\r\n- [Uptime](https://www.home-assistant.io/integrations/uptime/) sensor to track home assistant uptime\r\n- [Template](https://www.home-assistant.io/integrations/template/) sensor to convert the uptime sensor iintu readable sentance\r\n- [Version](https://www.home-assistant.io/integrations/version/) to track Home-Assistant version\r\n- The [DNS IP](https://www.home-assistant.io/integrations/dnsip/) sensor for tracking the external IP address\r\n\r\n## TV\r\n\r\n- [History stats](https://www.home-assistant.io/integrations/history_stats/) sensor to track TV usage\r\n- [Template](https://www.home-assistant.io/integrations/template/) sensor to convert the base 100 time units to a 60 minutes cap\r\n\r\n## UPS\r\n\r\nGet data from UPS device using the [NUT](https://www.home-assistant.io/integrations/nut/) integration\r\n\r\nFor this I also using this [NUT addon](https://github.com/hassio-addons/addon-nut) for Home-Assistant to make installation easier\r\n\r\n## Vacuum\r\n\r\n[Template](https://www.home-assistant.io/integrations/template/) sensor to extract and convert data from the [Xiaomi Vacuum](https://www.home-assistant.io/integrations/xiaomi_miio/#xiaomi-mi-robot-vacuum) into multiple sensors\r\n" }, { "alpha_fraction": 0.7698744535446167, "alphanum_fraction": 0.7698744535446167, "avg_line_length": 33.14285659790039, "blob_id": "3c3d3efcc4688c063a9ba357e618108642517d25", "content_id": "64ce0f22b620862663736bd65fa674c2672c23e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 239, "license_type": "no_license", "max_line_length": 157, "num_lines": 7, "path": "/homeassistant/config/scene/README.md", "repo_name": "dmatik/HomeAssistant-Config-1", "src_encoding": "UTF-8", "text": "# Scenes\n\n_Scenes capture the states you want certain entities to be in. have a look at the [scenes](https://www.home-assistant.io/integrations/scene/) Documentations_\n\nHere is a summery of the scenes and their functionality\n\nStill WIP...\n" }, { "alpha_fraction": 0.6947368383407593, "alphanum_fraction": 0.7070175409317017, "avg_line_length": 29.399999618530273, "blob_id": "f292839b56aa771fd43903efd3225584d2d3c3d6", "content_id": "0fbf50ff096216e797db1cf24d425e81e93ebf11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2280, "license_type": "no_license", "max_line_length": 237, "num_lines": 75, "path": "/config_examples/ims_sensor.md", "repo_name": "dmatik/HomeAssistant-Config-1", "src_encoding": "UTF-8", "text": "# IMS Sensor\n\n## prerequisites\n\nThe [Pyscript](https://github.com/custom-components/pyscript) custom-component, This is required for a more comprehensive python scripts to be used in Home-Assistant.\n\nMQTT Broker of your choice to retrive the data from the sensor.\n\n## The script\n\nPlace the script found [here](https://github.com/yuvalabou/HomeAssistant-Config/blob/master/homeassistant/config/pyscript/ims2mqtt.py) in your _config/pyscript_ folder, and replace the _BROKER = \"10.0.0.6\"_ with your MQTT broker address.\n\nThis will expose a new service called _pyscript.ims_sensor_.\n\n## The sensor\n\nCreate a new MQTT sensor in Home-Assistant\n\n```yaml\nsensor:\n - platform: mqtt\n state_topic: \"homeassistant/ims\"\n json_attributes_topic: \"homeassistant/ims/attrs\"\n name: \"IMS Daily\"\n icon: mdi:weather-partly-cloudy\n```\n\nTo Update the sensor regularly add the following automation\n\n```yaml\nautomation:\n - alias: \"Update IMS sensor\"\n id: 8092fd00-4f2b-46cb-9855-5adde0e310c9\n trigger:\n platform: time_pattern\n hours: \"/1\"\n action:\n service: pyscript.ims_sensor\n```\n\nThis will update the sensor every hour.\n\n## TTS\n\nYou need to create a notify entity from your media player and use it with the tts of your choice.\nhave a look at the docs [here](https://www.home-assistant.io/integrations/notify.tts/) and choose hebrew as language as the sensor return its values in hebrew.\n\nNext you will create two new scripts that will pass the sensor attributes to media player.\n\n```yaml\nscript:\n give_short_term_forecast:\n alias: \"Give short term forecast\"\n sequence:\n - service: notify.<your_media_player>\n data:\n message: \"{{state_attr('sensor.ims_daily', 'short_term')}}\"\n\n give_long_term_forecast:\n alias: \"Give long term forecast\"\n sequence:\n - service: notify.<your_media_player>\n data:\n message: \"{{state_attr('sensor.ims_daily', 'long_term')}}\"\n```\n\n## Automating\n\nHave at it :)\n\n## Note\n\nThis script is evolving as it is relying on an rss feed and some keywords might change.\n\nIf your sensor start breaking, please check for a new version in [my repo](https://github.com/yuvalabou/HomeAssistant-Config/blob/master/homeassistant/config/pyscript/ims2mqtt.py)\n" }, { "alpha_fraction": 0.5427184700965881, "alphanum_fraction": 0.5469255447387695, "avg_line_length": 21.059701919555664, "blob_id": "52de09da095958370fd76d87ef64b59c3133049c", "content_id": "ffcf17baef0faeed37bea6c8a4dca5f850f1c2d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3158, "license_type": "no_license", "max_line_length": 102, "num_lines": 134, "path": "/homeassistant/config/pyscript/ims2mqtt.py", "repo_name": "dmatik/HomeAssistant-Config-1", "src_encoding": "UTF-8", "text": "\"\"\"Get daily forecast from IMS.gov\"\"\"\r\nimport html\r\nimport json\r\nfrom datetime import datetime as dt\r\nfrom time import sleep\r\n\r\nimport feedparser\r\nfrom paho.mqtt import client as mqtt\r\n\r\nRSS = \"https://ims.gov.il/sites/default/files/ims_data/rss/forecast_country/rssForecastCountry_he.xml\"\r\nBROKER = \"10.0.0.6\"\r\nFEED = task.executor(feedparser.parse, RSS)\r\n\r\nclient = mqtt.Client()\r\n\r\n\r\ndef state() -> str:\r\n \"\"\"Return the state of the sensor.\"\"\"\r\n for item in FEED.entries:\r\n last_updated = str(item.guid).replace(\"Country \", \"\")\r\n last_updated = str(dt.strptime(last_updated, \"%a, %d %b %Y %H:%M:%S GMT\"))\r\n\r\n return last_updated\r\n\r\n\r\ndef link() -> str:\r\n \"\"\"Return the link.\"\"\"\r\n link = FEED.feed.link\r\n\r\n return link\r\n\r\n\r\n# The order is importent\r\nslag = [\r\n \"br /&gt;\",\r\n \"/b&gt;\",\r\n \"b&gt;\",\r\n \"&gt;\",\r\n \"style=&quot;text-decoration: underline;&quot;\",\r\n \"&lt;\",\r\n \"/font&gt;\",\r\n \"&quot;\",\r\n \"עדכון אחרון:\",\r\n \"font \",\r\n \"/\",\r\n]\r\n\r\n\r\ndef clean(desc) -> str:\r\n \"\"\"Helper method that clean-up the feed.\"\"\"\r\n # First pass\r\n for i in slag:\r\n desc = desc.replace(i, \" \")\r\n\r\n # Second pass\r\n # The order is importent\r\n desc = desc.replace(\":\", \"\\n\")\r\n desc = desc.replace(\"\\n\", \" \")\r\n desc = desc.replace(\" \", \"\")\r\n desc = desc.replace(\" \", \" \")\r\n desc = desc.replace(\"-\", \"\")\r\n\r\n # Replace common acronyms\r\n desc = desc.replace(\"אחה צ\", \"אחר הצהריים\")\r\n desc = desc.replace(\"בד כ\", \"בדרך כלל\")\r\n\r\n # Remove numbers\r\n cleaned_str = \"\".join([i for i in desc if not i.isdigit()])\r\n\r\n return cleaned_str\r\n\r\n\r\ndef short_term_forecast() -> str:\r\n \"\"\"Get short term forecast from feed.\"\"\"\r\n for item in FEED.entries:\r\n desc = html.escape(item.description)\r\n\r\n sep = \"/font&gt;\"\r\n desc = desc.split(sep, 1)[1]\r\n sep = \"תחזית לימים הקרובים\"\r\n desc = desc.split(sep, 1)[0]\r\n\r\n desc = clean(desc)\r\n\r\n short_term = desc.strip()\r\n\r\n return short_term\r\n\r\n\r\ndef long_term_forecast() -> str:\r\n \"\"\"Get long term forecast from feed.\"\"\"\r\n for item in FEED.entries:\r\n desc = html.escape(item.description)\r\n\r\n sep = \"תחזית לימים הקרובים\"\r\n desc = desc.split(sep, 1)[1]\r\n\r\n desc = clean(desc)\r\n\r\n long_term = desc.strip()\r\n\r\n return long_term\r\n\r\n\r\ndef get_attributes() -> dict:\r\n \"\"\"Get all atrributes.\"\"\"\r\n attrs = json.dumps(\r\n {\r\n \"short_term\": short_term_forecast(),\r\n \"long_term\": long_term_forecast(),\r\n \"link\": link(),\r\n \"last_fetched\": str(dt.now().strftime(\"%d/%m %H:%M\")),\r\n },\r\n ensure_ascii=False,\r\n indent=2,\r\n )\r\n\r\n return attrs\r\n\r\n\r\n@service\r\ndef ims_sensor():\r\n \"\"\"Send IMS data over MQTT.\"\"\"\r\n client.connect(BROKER)\r\n log.info(f\"Connected\")\r\n\r\n client.publish(\"homeassistant/ims\", state())\r\n client.publish(\"homeassistant/ims/attrs\", get_attributes())\r\n log.info(f\"Published\")\r\n\r\n sleep(3)\r\n\r\n client.disconnect()\r\n log.debug(f\"Disconnected\")\r\n" }, { "alpha_fraction": 0.7899484634399414, "alphanum_fraction": 0.7899484634399414, "avg_line_length": 25.758621215820312, "blob_id": "85e8b207b5732c432cfe0787567df878e7a349ac", "content_id": "430d904d03aa14aa90c29becc15a448fe0f176c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 776, "license_type": "no_license", "max_line_length": 254, "num_lines": 29, "path": "/homeassistant/config/integrations/script/README.md", "repo_name": "dmatik/HomeAssistant-Config-1", "src_encoding": "UTF-8", "text": "# [Scripts](https://www.home-assistant.io/integrations/script)\n\nHere is a summery of the scripts and their functionality\n\n_The script integration allows users to specify a sequence of actions to be executed by Home Assistant. These are run when you turn the script on. The script integration will create an entity for each script and allow them to be controlled via services._\n\n## Forecast speech\n\nPass the IMS sensor to a tts device\n\n## Radio stream\n\nBroadcast radio to a media device\n\n## Reload entities\n\nScripts to reload entities\n\n## Shabat lights sequences\n\nLighting sequences for certain times that requiring a bit more the just automations\n\n## System\n\nScripts to manage the system\n\n## Vacuum\n\nVacuum related scripts like managing vacuum speed and resetting consumables\n" } ]
11
falmusha/dotfiles
https://github.com/falmusha/dotfiles
7950d6c78aa753f8b6ff8cffb27b475ab6529b59
4abab3ceeabb4f4aac692ae49652bd3fdbaa6e49
2f05387924812b8b0b07f8a4a52f77c6877a1b26
refs/heads/master
2023-08-04T01:50:36.292729
2023-07-23T10:33:16
2023-07-23T10:33:16
10,354,940
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6082802414894104, "alphanum_fraction": 0.6146496534347534, "avg_line_length": 27.636363983154297, "blob_id": "a9ac66b4e7d4888d513901436d5928c5d8d3bfe1", "content_id": "306cddcb6490fa7b4ce80d6c707165797bff3101", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 314, "license_type": "no_license", "max_line_length": 57, "num_lines": 11, "path": "/config/nvim/after/plugin/telescope.lua", "repo_name": "falmusha/dotfiles", "src_encoding": "UTF-8", "text": "require('telescope').setup({\n defaults = {\n layout_config = { preview_width = 0.6 }\n }\n})\n\nlocal builtin = require('telescope.builtin')\n\nvim.keymap.set('n', '<c-p>', builtin.find_files, {})\nvim.keymap.set('n', '<leader>g', builtin.live_grep, {})\nvim.keymap.set('n', '<leader>G', builtin.grep_string, {})" }, { "alpha_fraction": 0.6310541033744812, "alphanum_fraction": 0.6310541033744812, "avg_line_length": 27.079999923706055, "blob_id": "67b86e8730ed6e2f3eb05144c8ff467f4fd1cf6b", "content_id": "03ccf3dede45545f0196fbdbe6cb2b106fc8e0ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 702, "license_type": "no_license", "max_line_length": 106, "num_lines": 25, "path": "/config/nvim/after/plugin/treesitter.lua", "repo_name": "falmusha/dotfiles", "src_encoding": "UTF-8", "text": "require('nvim-treesitter.configs').setup {\n\tensure_installed = {\n\t\t'cpp',\n\t\t'elixir',\n\t\t'fish',\n\t\t'go',\n\t\t'lua',\n\t\t'python',\n\t\t'ruby',\n\t\t'rust',\n\t\t'tsx',\n\t\t'typescript',\n\t\t'vim',\n\t\t'vimdoc',\n\t},\n\tauto_install = false,\n\thighlight = { enable = true },\n\tindent = { enable = true }\n}\n\n-- Diagnostic keymaps\nvim.keymap.set('n', '[d', vim.diagnostic.goto_prev, { desc = 'Go to previous diagnostic message' })\nvim.keymap.set('n', ']d', vim.diagnostic.goto_next, { desc = 'Go to next diagnostic message' })\nvim.keymap.set('n', '<leader>e', vim.diagnostic.open_float, { desc = 'Open floating diagnostic message' })\nvim.keymap.set('n', '<leader>q', vim.diagnostic.setloclist, { desc = 'Open diagnostics list' })\n" }, { "alpha_fraction": 0.584973156452179, "alphanum_fraction": 0.5867620706558228, "avg_line_length": 36.266666412353516, "blob_id": "33c71bd5df0b5c8024f3121a44777636db3c6c35", "content_id": "c30220ae1db9c4ec6eaf763eebcbf1f93f60e594", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 1118, "license_type": "no_license", "max_line_length": 86, "num_lines": 30, "path": "/config/nvim/lua/config/keymaps.lua", "repo_name": "falmusha/dotfiles", "src_encoding": "UTF-8", "text": "-- disable space charecter\nvim.keymap.set({ 'n', 'v' }, '<Space>', '<Nop>', { silent = true })\n\n-- Remap for dealing with word wrap\nvim.keymap.set('n', 'k', \"v:count == 0 ? 'gk' : 'k'\", { expr = true, silent = true })\nvim.keymap.set('n', 'j', \"v:count == 0 ? 'gj' : 'j'\", { expr = true, silent = true })\n\n-- [[ Highlight on yank ]]\n-- See `:help vim.highlight.on_yank()`\nlocal highlight_group = vim.api.nvim_create_augroup('YankHighlight', { clear = true })\nvim.api.nvim_create_autocmd('TextYankPost', {\n callback = function()\n vim.highlight.on_yank()\n end,\n group = highlight_group,\n pattern = '*',\n})\n\n-- use - and | for horizontal or vertical splits\nvim.keymap.set('n', '|', \"<cmd>vsplit<cr>\")\nvim.keymap.set('n', '-', \"<cmd>split<cr>\")\n\n-- enable spelling\nvim.keymap.set({ \"n\", \"i\" }, \"<C-s>\", \"<cmd>setlocal spell! spelllang=en_us<cr>\")\n\n-- disable arrow keys in insert mode\nvim.keymap.set(\"i\", \"<up>\", \"<nop>\", { silent = true })\nvim.keymap.set(\"i\", \"<down>\", \"<nop>\", { silent = true })\nvim.keymap.set(\"i\", \"<left>\", \"<nop>\", { silent = true })\nvim.keymap.set(\"i\", \"<right>\", \"<nop>\", { silent = true })\n" }, { "alpha_fraction": 0.5522816777229309, "alphanum_fraction": 0.5531882643699646, "avg_line_length": 26.92405128479004, "blob_id": "227c86c5cfa1761fe94ed782d4c4a90e5e947b85", "content_id": "5fa6dc3b179f4242cbd73e52bb1a8c8924daf12e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6618, "license_type": "no_license", "max_line_length": 84, "num_lines": 237, "path": "/setup.py", "repo_name": "falmusha/dotfiles", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport argparse\nimport json\nimport os\nimport platform\nimport shutil\nimport subprocess\nimport sys\nimport time\nimport zipfile\nfrom distutils.spawn import find_executable\nfrom pathlib import Path\nfrom tempfile import NamedTemporaryFile\nfrom urllib.request import urlopen\n\ntry:\n import tomllib\n\n TOML_AVAILABLE = True\nexcept ModuleNotFoundError:\n TOML_AVAILABLE = False\n\nPLATFORM = platform.system()\nCONFIGS_TOML = Path(__file__).parent / \"config.toml\"\nCONFIGS_JSON = Path(__file__).parent / \"config.json\"\nCONFIGS = dict()\nCONFIGS_DIR = CONFIGS_TOML.parent\n\n\ndef load_config():\n global CONFIGS\n\n if TOML_AVAILABLE:\n with open(CONFIGS_TOML, \"rb\") as f:\n CONFIGS = tomllib.load(f)\n else:\n with open(CONFIGS_JSON, \"rb\") as f:\n CONFIGS = json.load(f)\n\n\ndef setup():\n global CONFIGS, CONFIGS_DIR\n\n load_config()\n\n if ARGS.generate_json_config:\n if TOML_AVAILABLE == True:\n with open(CONFIGS_JSON, \"w+\") as f:\n json.dump(CONFIGS, f)\n sys.exit(0)\n else:\n sys.exit(\"!!ERROR!! Cannot generate JSON when tomllib is not available\")\n\n CONFIGS_DIR = CONFIGS[\"configs_dir\"]\n\n if ARGS.remove_files:\n remove_files()\n\n if ARGS.download_files:\n download_files()\n\n if ARGS.unlink:\n unlink()\n\n if ARGS.link:\n link()\n\n if ARGS.install:\n install()\n\n\ndef symlink_pairs():\n symlinks_map = CONFIGS[\"symlinks\"]\n symlinks = symlinks_map[\"common\"]\n if PLATFORM in symlinks_map:\n symlinks = {**symlinks, **symlinks_map[PLATFORM]}\n\n for config_dir, filenames in symlinks.items():\n config_path = CONFIGS_DIR / Path(config_dir)\n if isinstance(filenames, dict):\n for source, destination in filenames.items():\n src = config_path / source\n dst = Path(os.path.expandvars(destination))\n yield src, dst\n elif isinstance(filenames, str):\n src = config_path\n dst = Path(os.path.expandvars(filenames))\n yield src, dst\n\n\ndef log(msg, header=False, subheader=False, level=0):\n if header:\n msg = f\"--- {msg}\".upper()\n width = os.get_terminal_size().columns\n print()\n print(\"-\" * width)\n print(msg, \"-\" * (width - len(msg) - 1))\n print(\"-\" * width)\n print()\n elif subheader:\n print(\"-\", msg)\n else:\n print(\" \" * level, msg)\n\n\ndef link():\n log(f\"linking config files\", header=True)\n for src, dst in symlink_pairs():\n symlink(src, dst)\n\n\ndef unlink():\n log(f\"removing files\", header=True)\n for src, dst in symlink_pairs():\n symlink(src, dst, remove=True)\n\n\ndef symlink(src_file, dst_file, remove=False):\n msg = f\"symlinking: {src_file} --> {dst_file}\"\n if remove:\n if dst_file.is_symlink() and not dst_file.exists():\n if not ARGS.dry_run:\n dst_file.unlink(missing_ok=True)\n msg += \" (BAD LINK, REMOVED!!)\"\n elif dst_file.is_symlink() and dst_file.exists():\n if not ARGS.dry_run:\n dst_file.unlink(missing_ok=True)\n msg += \" (REMOVED!!)\"\n elif dst_file.exists():\n backup = f\"{dst_file}.backup-at-{int(time.time())}\"\n msg += f\" (backup: {src_file} --> {backup})\"\n if not ARGS.dry_run:\n shutil.copyfile(src_file, dst_file)\n else:\n msg += \" (IGNORE!! no link or file to deal with)\"\n log(msg)\n else:\n if dst_file.exists():\n msg += \" (EXISTS!!)\"\n else:\n if not ARGS.dry_run:\n dst_file.parent.mkdir(parents=True, exist_ok=True)\n dst_file.symlink_to(src_file.resolve())\n log(msg)\n\n\ndef remove_files():\n for download in CONFIGS[\"downloads\"]:\n url = download[\"url\"]\n directory = Path(os.path.expandvars(download[\"directory\"]))\n name = download[\"name\"]\n target = directory / name\n if target.exists():\n log(f\"Removing downloaded target {target}\")\n if target.is_dir():\n if not ARGS.dry_run:\n shutil.rmtree(target)\n else:\n if not ARGS.dry_run:\n target.unlink()\n\n\ndef download_files():\n for download in CONFIGS[\"downloads\"]:\n url = download[\"url\"]\n directory = Path(os.path.expandvars(download[\"directory\"]))\n directory.parent.mkdir(parents=True, exist_ok=True)\n name = download[\"name\"]\n log(f\"Downloading {url}\")\n if ARGS.dry_run:\n continue\n\n with urlopen(url) as response, NamedTemporaryFile(\n suffix=\".zip\", delete=False\n ) as tmp_fp:\n shutil.copyfileobj(response, tmp_fp)\n\n if download[\"unzip\"]:\n log(f\"Unzipping {tmp_fp.name} in {directory}\")\n with zipfile.ZipFile(tmp_fp.name) as zip_fp:\n zip_fp.extractall(directory)\n else:\n src = Path(tmp_fp.name).rename(name)\n log(f\"Moving {src} to {directory}\")\n shutil.move(src, directory)\n\n\ndef install():\n log(f\"installing stuff\", header=True)\n if PLATFORM == \"Darwin\":\n install_homebrew()\n\n\ndef install_homebrew():\n log(\"Installing Homebrew\", subheader=True)\n if find_executable(\"brew\"):\n log(\"Hombrew exists, no need to install\", level=1)\n else:\n if not ARGS.dry_run:\n script_url = CONFIGS[\"urls\"][\"homebrew_install\"]\n install_run = subprocess.run(\n [\n \"/bin/bash\",\n \"-c\",\n f\"$(curl -fsSL {script_url})\",\n ]\n )\n\n if not ARGS.dry_run:\n log(\"Installing Homebrew bundle\", level=1)\n subprocess.run(\n [\n \"brew\",\n \"bundle\",\n \"install\",\n \"--global\",\n \"--no-upgrade\",\n \"--verbose\",\n \"--no-lock\",\n ]\n )\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--link\", action=\"store_true\")\n parser.add_argument(\"--unlink\", action=\"store_true\")\n parser.add_argument(\"--download-files\", action=\"store_true\")\n parser.add_argument(\"--remove-files\", action=\"store_true\")\n parser.add_argument(\"--install\", action=\"store_true\")\n parser.add_argument(\"--dry-run\", action=\"store_true\")\n parser.add_argument(\"--generate-json-config\", action=\"store_true\")\n\n ARGS = parser.parse_args()\n\n setup()\n" }, { "alpha_fraction": 0.51222825050354, "alphanum_fraction": 0.51222825050354, "avg_line_length": 22.74193572998047, "blob_id": "dab84027c717ce66fa2d8c2b1edc352bef929f8c", "content_id": "02c191d8c2ac35091a9245a04bf65e23c1a0d48c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 736, "license_type": "no_license", "max_line_length": 80, "num_lines": 31, "path": "/config/zsh/zshrc", "repo_name": "falmusha/dotfiles", "src_encoding": "UTF-8", "text": "# Command aliases\n# ------------------------------------------------------------------------------\nalias l=\"ls -la\"\nalias gl=\"git l\"\nalias gs=\"git s\"\nalias t=\"tmux\"\nalias tl=\"tmux ls\"\n# CLI: Improved\nalias ping=\"prettyping --nolegend\"\nalias du=\"ncdu --color dark -rr -x --exclude .git --exclude node_modules\"\n\n# $PATH\n# ------------------------------------------------------------------------------\n\nif [ -d \"$HOME/.cargo/bin\" ]; then\n export PATH=$PATH:$HOME/.cargo/bin\nfi\n\nif [ -d \"$HOME/.bin\" ]; then\n export PATH=$PATH:$HOME/.bin\nfi\n\nif [ -d \"/opt/homebrew\" ]; then\n eval \"$(/opt/homebrew/bin/brew shellenv)\"\nfi\n\nEDITOR=nvim\nRACK_ENV=development\nERL_AFLAGS=\"-kernel shell_history enabled\"\n\n[ -f ~/.fzf.zsh ] && source ~/.fzf.zsh\n" }, { "alpha_fraction": 0.6341463327407837, "alphanum_fraction": 0.6341463327407837, "avg_line_length": 9.25, "blob_id": "e4e48d5973caa7c76c83e875b99dc09b71e4ddf1", "content_id": "479c1eee4b59d5061ba99f62fe06df314bfd6751", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 41, "license_type": "no_license", "max_line_length": 21, "num_lines": 4, "path": "/README.md", "repo_name": "falmusha/dotfiles", "src_encoding": "UTF-8", "text": "dotfiles\n========\n\nSetup my work station\n" }, { "alpha_fraction": 0.7228177785873413, "alphanum_fraction": 0.7243491411209106, "avg_line_length": 13.840909004211426, "blob_id": "593349bfb15f644f1a6bd71c5ddc938353dd408a", "content_id": "643170a9e457c33a8eb1d278a9f3dd6d6cb76cb0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 653, "license_type": "no_license", "max_line_length": 25, "num_lines": 44, "path": "/config/homebrew/Brewfile", "repo_name": "falmusha/dotfiles", "src_encoding": "UTF-8", "text": "brew \"elixir\"\nbrew \"fd\"\nbrew \"fish\"\nbrew \"fisher\"\nbrew \"fnm\"\nbrew \"fzf\"\nbrew \"git\"\nbrew \"htop\"\nbrew \"imagemagick\"\nbrew \"jq\"\nbrew \"ncdu\"\nbrew \"neovim\"\nbrew \"node\"\nbrew \"openssl\"\nbrew \"prettyping\"\nbrew \"pyenv\"\nbrew \"rbenv\"\nbrew \"ripgrep\"\nbrew \"tldr\"\nbrew \"tmux\"\nbrew \"tokei\"\nbrew \"tree\"\nbrew \"vim\"\nbrew \"wget\"\n\ncask \"alfred\"\ncask \"beekeeper-studio\"\ncask \"brave-browser\"\ncask \"firefox\"\ncask \"grandperspective\"\ncask \"hammerspoon\"\ncask \"imageoptim\"\ncask \"iterm2\"\ncask \"jetbrains-toolbox\"\ncask \"kitty\"\ncask \"maestral\"\ncask \"mullvadvpn\"\ncask \"ngrok\"\ncask \"obsidian\"\ncask \"signal\"\ncask \"stats\"\ncask \"sublime-merge\"\ncask \"sublime-text\"\ncask \"visual-studio-code\"\n" }, { "alpha_fraction": 0.6770833134651184, "alphanum_fraction": 0.6886574029922485, "avg_line_length": 26.870967864990234, "blob_id": "ba42a526da38ba8a2ffdb1ad27587f537e153dc4", "content_id": "7a5f3e381edb96c1f15361077df2da2c779320ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 867, "license_type": "no_license", "max_line_length": 82, "num_lines": 31, "path": "/config/nvim/lua/config/options.lua", "repo_name": "falmusha/dotfiles", "src_encoding": "UTF-8", "text": "-- automatically read files when changed\nvim.o.autoread = true\n-- remove swap files\nvim.o.noswapfile = true\n\n-- vim.o.list listchars=tab:»·,precedes:-,trail:·,nbsp:+\nvim.o.mouse = 'a'\n\n-- show line numbers\nvim.o.relativenumber = true\n\n-- spaces instead of tabs\nvim.o.expandtab = true\n-- 1 tab = 2 spaces\nvim.o.shiftwidth = 2\nvim.o.tabstop = 2\n\n-- open new split panes to bottom and the right\nvim.o.splitbelow = true\nvim.o.splitright = true\n\n-- default text width is 80\nvim.o.textwidth=80\n-- highlight lines over that 1 column after 'textwidth'\nvim.o.colorcolumn = \"+1\"\n-- always show sign column to avoid plugins toggling on/off\n--vim.o.signcolumn = true\n\n-- vim.o.wildignore+=*/tmp/*,*.so,*.swp,*.zip,*.class,*DS_Store* \" general\n-- vim.o.wildignore+=*bower_components/**,*node_modules/**,*build/**,*dist/** \" JS\n-- vim.o.wildignore+=*deps/**,*_build/** \" elixir\n" }, { "alpha_fraction": 0.380897581577301, "alphanum_fraction": 0.3831990659236908, "avg_line_length": 37.622222900390625, "blob_id": "c5014bb35254d6253974b06fa48a7ab867e7b961", "content_id": "6f78469ce22493f0829b5c6a497e2e02df6e6017", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 1738, "license_type": "no_license", "max_line_length": 81, "num_lines": 45, "path": "/config/hammerspoon/init.lua", "repo_name": "falmusha/dotfiles", "src_encoding": "UTF-8", "text": "package.path = package.path .. \";\" .. hs.configdir .. \"/Spoons/?.spoon/init.lua\"\n\n--------------------------------------------------------------------------------\n-- Spoons\n--------------------------------------------------------------------------------\n\n-- Load spoons\nhs.loadSpoon(\"ReloadConfiguration\")\nhs.loadSpoon(\"Caffeine\")\nhs.loadSpoon(\"WindowHalfsAndThirds\")\n\n-- Start spoons\nspoon.ReloadConfiguration:start()\nspoon.Caffeine:start()\nspoon.WindowHalfsAndThirds:bindHotkeys({\n -- halfs\n left_half = { {\"ctrl\", \"cmd\"}, \"Left\" },\n right_half = { {\"ctrl\", \"cmd\"}, \"Right\" },\n top_half = { {\"ctrl\", \"cmd\"}, \"Up\" },\n bottom_half = { {\"ctrl\", \"cmd\"}, \"Down\" },\n -- thirds\n third_left = { {\"ctrl\", \"alt\" }, \"Left\" },\n third_right = { {\"ctrl\", \"alt\" }, \"Right\" },\n third_up = { {\"ctrl\", \"alt\" }, \"Up\" },\n third_down = { {\"ctrl\", \"alt\" }, \"Down\" },\n -- quarters\n top_left = { {\"ctrl\", \"cmd\"}, \"1\" },\n top_right = { {\"ctrl\", \"cmd\"}, \"2\" },\n bottom_left = { {\"ctrl\", \"cmd\"}, \"3\" },\n bottom_right= { {\"ctrl\", \"cmd\"}, \"4\" },\n -- else\n max_toggle = { { \"alt\", \"cmd\"}, \"m\" },\n max = { {\"ctrl\", \"alt\", \"cmd\"}, \"Up\" },\n undo = { { \"alt\", \"cmd\"}, \"z\" },\n center = { { \"alt\", \"cmd\"}, \"c\" },\n larger = { { \"alt\", \"cmd\", \"shift\"}, \"Right\" },\n smaller = { { \"alt\", \"cmd\", \"shift\"}, \"Left\" },\n})\n\n--------------------------------------------------------------------------------\n-- MAIN\n--------------------------------------------------------------------------------\n\n-- Send reloaded notification\nhs.notify.new({title=\"Hammerspoon\", informativeText=\"Loaded!!\"}):send()\n" }, { "alpha_fraction": 0.7358133792877197, "alphanum_fraction": 0.7358133792877197, "avg_line_length": 32.04166793823242, "blob_id": "9903cba5d2f0bed32194f45ab7ab2a96dda438f9", "content_id": "10e1c76a82cfb187912f4d364efaf2b67c94b4e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 1586, "license_type": "no_license", "max_line_length": 104, "num_lines": 48, "path": "/config.toml", "repo_name": "falmusha/dotfiles", "src_encoding": "UTF-8", "text": "configs_dir = \"config\"\n\n[urls]\nhomebrew_install = \"https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh\"\n\n[symlinks.common]\nbash.bashrc = \"$HOME/.bashrc\"\nzsh.zshrc = \"$HOME/.zshrc\"\nfish.\"config.fish\" = \"$HOME/.config/fish/config.fish\"\nfish.fish_plugins = \"$HOME/.config/fish/fish_plugins\"\ngit.gitconfig = \"$HOME/.gitconfig\"\ngit.global_ignore = \"$HOME/.global_ignore\"\nnvim = \"$HOME/.config/nvim\"\nvim.vimrc = \"$HOME/.vimrc\"\ntmux.\"tmux.conf\" = \"$HOME/.tmux.conf\"\nkitty.\"kitty.conf\" = \"$HOME/.config/kitty/kitty.conf\"\nintellij.ideavimrc = \"$HOME/.ideavimrc\"\nvscode.\"keybindings.json\" = \"$HOME/.vscode/keybindings.json\"\nvscode.\"settings.json\" = \"$HOME/.vscode/settings.json\" \nbin = \"$HOME/.bin\"\n\n[symlinks.Darwin]\nhammerspoon.\"init.lua\" = \"$HOME/.hammerspoon/init.lua\"\nhomebrew.Brewfile = \"$HOME/.Brewfile\"\n\n[[downloads]]\nurl = \"https://raw.githubusercontent.com/Hammerspoon/Spoons/master/Spoons/ReloadConfiguration.spoon.zip\"\ndirectory = \"$HOME/.hammerspoon/Spoons/\"\nname = \"ReloadConfiguration.spoon\"\nunzip = true\n\n[[downloads]]\nurl = \"https://raw.githubusercontent.com/Hammerspoon/Spoons/master/Spoons/Caffeine.spoon.zip\"\ndirectory = \"$HOME/.hammerspoon/Spoons\"\nname = \"Caffeine.spoon\"\nunzip = true\n\n[[downloads]]\nurl = \"https://github.com/Hammerspoon/Spoons/raw/master/Spoons/WindowHalfsAndThirds.spoon.zip\"\ndirectory = \"$HOME/.hammerspoon/Spoons\"\nname = \"WindowHalfsAndThirds.spoon\"\nunzip = true\n\n[[downloads]]\nurl = \"https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim\"\ndirectory = \"$HOME/.local/share/nvim/site/autoload/\"\nname = \"plug.vim\"\nunzip = false\n" }, { "alpha_fraction": 0.6512141227722168, "alphanum_fraction": 0.6622516512870789, "avg_line_length": 27.3125, "blob_id": "225fefa533e0b42b36a0535e81c3f9cd782a6a6f", "content_id": "31e02b88e437e5c5c36a949f8baada5dd0e44258", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 453, "license_type": "no_license", "max_line_length": 61, "num_lines": 16, "path": "/config/nvim/after/plugin/lsp-zero.lua", "repo_name": "falmusha/dotfiles", "src_encoding": "UTF-8", "text": "local lsp = require('lsp-zero').preset({})\n\nlsp.on_attach(function(_client, bufnr)\n -- see :help lsp-zero-keybindings\n -- to learn the available actions\n lsp.default_keymaps({ buffer = bufnr })\n\n vim.keymap.set({ 'n', 'x' }, '<leader>f', function()\n vim.lsp.buf.format({ async = false, timeout_ms = 10000 })\n end, {})\nend)\n\n-- (Optional) Configure lua language server for neovim\nrequire('lspconfig').lua_ls.setup(lsp.nvim_lua_ls())\n\nlsp.setup()\n" }, { "alpha_fraction": 0.5595451593399048, "alphanum_fraction": 0.5715140700340271, "avg_line_length": 21.890411376953125, "blob_id": "5e5135771b0ef671d642a084a5753fad35f390c7", "content_id": "d22cc933ef9aa7f29a8e7bc3552b1b558b697aa4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Lua", "length_bytes": 1671, "license_type": "no_license", "max_line_length": 61, "num_lines": 73, "path": "/config/nvim/init.lua", "repo_name": "falmusha/dotfiles", "src_encoding": "UTF-8", "text": "vim.g.mapleader = ' '\nvim.g.maplocalleader = ','\n\nlocal lazypath = vim.fn.stdpath(\"data\") .. \"/lazy/lazy.nvim\"\nif not vim.loop.fs_stat(lazypath) then\n vim.fn.system({\n \"git\",\n \"clone\",\n \"--filter=blob:none\",\n \"https://github.com/folke/lazy.nvim.git\",\n \"--branch=stable\", -- latest stable release\n lazypath,\n })\nend\n\nvim.opt.rtp:prepend(lazypath)\n\nrequire(\"lazy\").setup({\n 'tpope/vim-fugitive',\n 'lewis6991/gitsigns.nvim',\n 'nvim-lualine/lualine.nvim',\n 'numToStr/Comment.nvim',\n {\n 'rose-pine/neovim',\n name = 'rose-pine',\n lazy = false,\n priority = 1000,\n config = function() vim.cmd('colorscheme rose-pine') end,\n },\n {\n \"folke/tokyonight.nvim\",\n lazy = true,\n priority = 1000,\n opts = {},\n },\n {\n 'nvim-telescope/telescope.nvim',\n branch = '0.1.x',\n dependencies = { 'nvim-lua/plenary.nvim' }\n },\n {\n 'nvim-treesitter/nvim-treesitter',\n dependencies = {\n 'nvim-treesitter/nvim-treesitter-textobjects',\n },\n build = ':TSUpdate',\n },\n {\n 'VonHeikemen/lsp-zero.nvim',\n branch = 'v2.x',\n dependencies = {\n -- LSP Support\n { 'neovim/nvim-lspconfig' }, -- Required\n { -- Optional\n 'williamboman/mason.nvim',\n build = function()\n pcall(vim.api.nvim_command, 'MasonUpdate')\n end,\n },\n { 'williamboman/mason-lspconfig.nvim' }, -- Optional\n\n -- Autocompletion\n { 'hrsh7th/nvim-cmp' }, -- Required\n { 'hrsh7th/cmp-nvim-lsp' }, -- Required\n { 'L3MON4D3/LuaSnip' }, -- Required\n }\n }\n\n}, {})\n\nrequire(\"config.autocmds\")\nrequire(\"config.options\")\nrequire(\"config.keymaps\")\n" } ]
12
arpanjain-bot/twoc-problems
https://github.com/arpanjain-bot/twoc-problems
a65aa2ed8f4cda4966053226a9db31572680f632
e028fdc7f90d56ca49e624598130fc0e3de363a0
ea836315d9f2bee364ba2d00523d20ebb90a16bc
refs/heads/master
2022-08-17T13:45:14.612614
2020-05-24T07:31:53
2020-05-24T07:31:53
264,427,303
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5952380895614624, "alphanum_fraction": 0.6190476417541504, "avg_line_length": 41, "blob_id": "f518840b093fb8998b78d179ab10bfaea421bb66", "content_id": "7f2f94d0bf01f9233288a1319841b576bba7ca4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 84, "license_type": "no_license", "max_line_length": 44, "num_lines": 2, "path": "/program_2.py", "repo_name": "arpanjain-bot/twoc-problems", "src_encoding": "UTF-8", "text": "\nnum = float(input('Enter a Number: '))\nprint('Square root of', num, 'is', num**0.5)" }, { "alpha_fraction": 0.6315789222717285, "alphanum_fraction": 0.6315789222717285, "avg_line_length": 30.83333396911621, "blob_id": "80c9650420edb0dc8f065524dc5152d48220ffd8", "content_id": "cc518dc98c59e5613e84fe85b0586ffbd21269f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 190, "license_type": "no_license", "max_line_length": 75, "num_lines": 6, "path": "/program_3.py", "repo_name": "arpanjain-bot/twoc-problems", "src_encoding": "UTF-8", "text": "a,b = int(input('Enter first number:')), int(input('Enter second number:'))\nprint('Numbers before swapping a=', a, 'and b=', b)\n\na,b = b,a\n\nprint('Numbers after swapping a=', a, 'and b=', b)" }, { "alpha_fraction": 0.732467532157898, "alphanum_fraction": 0.7428571581840515, "avg_line_length": 34, "blob_id": "2e75644fa86bce64d8ed1466a30034aafdb0b9d8", "content_id": "4fb2089f960e0955193bee51360e383441123f91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 385, "license_type": "no_license", "max_line_length": 126, "num_lines": 11, "path": "/program_4.py", "repo_name": "arpanjain-bot/twoc-problems", "src_encoding": "UTF-8", "text": "cost_price,selling_price = float(input('Enter Cost Price of a product :')), float(input('Enter Selling Price of a product :'))\n\n#calculating profit for a product\nprofit = selling_price-cost_price\nprint('Profit from this sell:', profit)\n\n#increased profit by 5%\nnew_profit = profit+(profit*0.05)\n\nnew_selling_price = cost_price+new_profit\nprint('New selling price:', new_selling_price)\n" } ]
3
mcdickenson/nnet-python
https://github.com/mcdickenson/nnet-python
b27b742cdf617bcda1704ee482a5dd82755bc0ee
56c986d9efafe7ca016840a716655c1d1cbe0cba
0d10c027ae2a7d5711cfefb638c6343eb87cd33b
refs/heads/master
2016-09-13T23:48:52.708465
2016-04-19T18:51:06
2016-04-19T18:51:06
56,623,073
3
0
null
null
null
null
null
[ { "alpha_fraction": 0.5873104929924011, "alphanum_fraction": 0.6361594796180725, "avg_line_length": 26.84375, "blob_id": "bec66c9bff1d0e0048d999dc2e912d638f9a49ae", "content_id": "7a3f08034ace60325360c53f323b9be6a6a6a7d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1781, "license_type": "no_license", "max_line_length": 76, "num_lines": 64, "path": "/single_neuron.py", "repo_name": "mcdickenson/nnet-python", "src_encoding": "UTF-8", "text": "from math import exp\nfrom helpers import *\n\n# create input units\na = Unit(1.0, 0.0)\nb = Unit(2.0, 0.0)\nc = Unit(-3.0, 0.0)\nx = Unit(-1.0, 0.0)\ny = Unit(3.0, 0.0)\ns = None\n\n# create gates\nmlt_g0 = MultiplyGate()\nmlt_g1 = MultiplyGate()\nadd_g0 = AddGate()\nadd_g1 = AddGate()\nsig_g0 = SigmoidGate()\n\n# forward pass\ndef forwardNeuron():\n global a, b, c, x, y, s\n ax = mlt_g0.forward(a, x) # a * x = -1\n by = mlt_g1.forward(b, y) # b * y = 6\n ax_plus_by = add_g0.forward(ax, by) # 5\n ax_plus_by_plus_c = add_g1.forward(ax_plus_by, c) # 2\n s = sig_g0.forward(ax_plus_by_plus_c) # sigmoid(2) = 0.8808\n\nforwardNeuron()\n\nprint(\"circuit output: {}\".format( s.value ))\n\n# compute gradients\ns.grad = 1.0\nsig_g0.backward()\nadd_g1.backward()\nadd_g0.backward()\nmlt_g1.backward()\nmlt_g0.backward()\n\nstep_size = 0.01\na.value += step_size * a.grad # a.grad is -0.105\nb.value += step_size * b.grad # b.grad is 0.315\nc.value += step_size * c.grad # c.grad is 0.105\nx.value += step_size * x.grad # x.grad is 0.105\ny.value += step_size * y.grad # y.grad is 0.210\n\nforwardNeuron()\nprint(\"circuit output after one backprop: {}\".format( s.value )) # 0.8825\n\n\n\n# check numerical gradients with a faster implementation\ndef forwardCircuitFast(a, b, c, x, y):\n return 1/(1 + exp( - (a*x + b*y + c) ) )\n\na, b, c, x, y = 1, 2, -3, -1, 3\nh = 0.0001\na_grad = (forwardCircuitFast(a+h,b,c,x,y) - forwardCircuitFast(a,b,c,x,y))/h\nb_grad = (forwardCircuitFast(a,b+h,c,x,y) - forwardCircuitFast(a,b,c,x,y))/h\nc_grad = (forwardCircuitFast(a,b,c+h,x,y) - forwardCircuitFast(a,b,c,x,y))/h\nx_grad = (forwardCircuitFast(a,b,c,x+h,y) - forwardCircuitFast(a,b,c,x,y))/h\ny_grad = (forwardCircuitFast(a,b,c,x,y+h) - forwardCircuitFast(a,b,c,x,y))/h\n\nprint(\"gradients: {}\".format([a_grad, b_grad, c_grad, x_grad, y_grad]))" }, { "alpha_fraction": 0.7321428656578064, "alphanum_fraction": 0.7714285850524902, "avg_line_length": 34.0625, "blob_id": "935a0e2596fc8197ba3f0debd1774476584357c5", "content_id": "d7203259643dc3bf60509a529871eca0eb40d111", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 560, "license_type": "no_license", "max_line_length": 240, "num_lines": 16, "path": "/README.md", "repo_name": "mcdickenson/nnet-python", "src_encoding": "UTF-8", "text": "## Resources\n\n- http://karpathy.github.io/neuralnets/\n- http://cs231n.github.io/\n- http://iamtrask.github.io/2015/07/12/basic-python-network/\n- http://www.wildml.com/2015/09/implementing-a-neural-network-from-scratch/\n\n## Code\n\nCode is meant to be instructive. Function definitions are sometimes repeated between files, and variable definitions are sometimes repeated within files. This intentionally violates object-oriented design principles for pedagogical reasons.\n\n1. `circuits.py`\n2. `backpropagation.py`\n3. `helpers.py`\n4. `single_neuron.py`\n5. `svm.py`" }, { "alpha_fraction": 0.6390134692192078, "alphanum_fraction": 0.6576980352401733, "avg_line_length": 23.77777862548828, "blob_id": "45cb594826e96807e4876fbc46306aaa11ad2539", "content_id": "9ea82dfa9752dfa874dbfd08cae84b2f64ee83a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1338, "license_type": "no_license", "max_line_length": 84, "num_lines": 54, "path": "/backpropagation.py", "repo_name": "mcdickenson/nnet-python", "src_encoding": "UTF-8", "text": "# now let's try with two gates in a circuit\n\ndef forwardMultiplyGate(x, y):\n return x * y\n\ndef forwardAddGate(x, y):\n return x + y\n\ndef forwardCircuit(x, y, z):\n q = forwardAddGate(x, y)\n f = forwardMultiplyGate(q, z)\n return f\n\nx = -2\ny = 5\nz = -4\nq = forwardAddGate(x, y)\nf = forwardMultiplyGate(q, z) # -12\n\n# gradient of multiply gate w/r/t its inputs\nderivative_f_wrt_z = q\nderivative_f_wrt_q = z\n\n# derivative of add gate w/r/t its inputs\nderivative_q_wrt_x = 1.0\nderivative_q_wrt_y = 1.0\n\n# chain rule\nderivative_f_wrt_x = derivative_q_wrt_x * derivative_f_wrt_q # -4\nderivative_f_wrt_y = derivative_q_wrt_y * derivative_f_wrt_q # -4\n\ngradient_f_wrt_xyz = [derivative_q_wrt_x, derivative_f_wrt_y, derivative_f_wrt_z]\nstep_size = 0.01\nx = x + step_size * derivative_f_wrt_x\ny = y + step_size * derivative_f_wrt_y\nz = z + step_size * derivative_f_wrt_z\nq = forwardAddGate(x, y)\nf = forwardMultiplyGate(q, z)\n\n\n\n# back to initial conditions\nx = -2\ny = 5\nz = -4\n\n\n# numerical gradient check\nh = 0.0001\nx_derivative = (forwardCircuit(x+h, y, z) - forwardCircuit(x, y, z)) / h # -4\ny_derivative = (forwardCircuit(x, y+h, z) - forwardCircuit(x, y, z)) / h # -4\nz_derivative = (forwardCircuit(x, y, z+h) - forwardCircuit(x, y, z)) / h # 3\n\nprint(\"derivatives are {}, {}, {}\".format(x_derivative, y_derivative, z_derivative))\n" }, { "alpha_fraction": 0.6114550828933716, "alphanum_fraction": 0.6400928497314453, "avg_line_length": 23.39622688293457, "blob_id": "6bf76013a52b5a9120f8c5f3c4299ad0d2356bbe", "content_id": "da9cf5b2a698d556264d5242503fc54f9d0dec99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1292, "license_type": "no_license", "max_line_length": 76, "num_lines": 53, "path": "/helpers.py", "repo_name": "mcdickenson/nnet-python", "src_encoding": "UTF-8", "text": "from math import exp\n\n# unit is equivalent to a wire in a circuit diagram\n# each unit has a value and a gradient\nclass Unit(object):\n def __init__(self, value, gradient):\n self.value = value\n self.grad = gradient\n\n\nclass MultiplyGate(object):\n\n def forward(self, u0, u1):\n # store units passed\n self.u0 = u0\n self.u1 = u1\n self.utop = Unit(u0.value * u1.value, 0)\n return self.utop\n\n def backward(self):\n # take the gradient in the output unit and chain it with local gradients\n # store those gradients on the units\n self.u0.grad += self.u1.value * self.utop.grad\n self.u1.grad += self.u0.value * self.utop.grad\n\n\nclass AddGate(object):\n def forward(self, u0, u1):\n # store units passed\n self.u0 = u0\n self.u1 = u1\n self.utop = Unit(u0.value + u1.value, 0)\n return self.utop\n\n def backward(self):\n # derivate w/r/t both inputs is 1\n self.u0.grad += 1 * self.utop.grad\n self.u1.grad += 1 * self.utop.grad\n\n\nclass SigmoidGate(object):\n def sigmoid(self, x):\n return 1 / (1 + exp(-x))\n\n def forward(self, u0):\n # store unit passed\n self.u0 = u0\n self.utop = Unit(self.sigmoid(u0.value), 0)\n return self.utop\n\n def backward(self):\n s = self.sigmoid(self.u0.value)\n self.u0.grad += (s * (1-s)) * self.utop.grad" }, { "alpha_fraction": 0.581818163394928, "alphanum_fraction": 0.6146852970123291, "avg_line_length": 26.5, "blob_id": "ef455f5351a3a1403185b40f58dce1d3be9bd0a0", "content_id": "3017232cbebbd5f70595858bb1f88bc3e2fb5809", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2860, "license_type": "no_license", "max_line_length": 86, "num_lines": 104, "path": "/svm.py", "repo_name": "mcdickenson/nnet-python", "src_encoding": "UTF-8", "text": "from helpers import *\nfrom random import random\n\nclass Circuit(object):\n def __init__(self):\n self.mlt_g0 = MultiplyGate()\n self.mlt_g1 = MultiplyGate()\n self.add_g0 = AddGate()\n self.add_g1 = AddGate()\n self.sig_g0 = SigmoidGate()\n\n def forward(self, x, y, a, b, c):\n self.ax = self.mlt_g0.forward(a, x)\n self.by = self.mlt_g1.forward(b, y)\n self.ax_plus_by = self.add_g0.forward(self.ax, self.by)\n self.ax_plus_by_plus_c = self.add_g1.forward(self.ax_plus_by, c)\n return self.ax_plus_by_plus_c\n\n def backward(self, gradient_top):\n self.ax_plus_by_plus_c.grad = gradient_top\n self.add_g1.backward()\n self.add_g0.backward()\n self.mlt_g1.backward()\n self.mlt_g0.backward()\n\nclass SVM(object):\n def __init__(self):\n self.a = Unit(1.0, 0.0)\n self.b = Unit(-2.0, 0.0)\n self.c = Unit(-1.0, 0.0)\n\n self.circuit = Circuit()\n\n def forward(self, x, y): # expect x and y to be units\n self.unit_out = self.circuit.forward(x, y, self.a, self.b, self.c)\n return self.unit_out\n\n def backward(self, label):\n # reset the pulls on a, b, and c\n self.a.grad = 0\n self.b.grad = 0\n self.c.grad = 0\n\n # compute pull based on circuit output\n pull = 0\n\n if(label == 1 and self.unit_out.value < 1):\n pull = 1 # score was too low, pull up\n elif(label == -1 and self.unit_out.value > -1):\n pull = -1 # score was too high, pull down\n\n self.circuit.backward(pull)\n\n # add regularization pull toward zero, proportional to value\n self.a.grad -= self.a.value\n self.b.grad -= self.b.value\n\n def learnFrom(self, x, y, label):\n self.forward(x, y)\n self.backward(label)\n self.parameterUpdate()\n\n def parameterUpdate(self):\n step_size = 0.01\n self.a.value += step_size * self.a.grad\n self.b.value += step_size * self.b.grad\n self.c.value += step_size * self.c.grad\n\n# set up data points\ndata = []\nlabels = []\ndata.append([ 1.2, 0.7]); labels.append(1)\ndata.append([-0.3, -0.5]); labels.append(-1)\ndata.append([ 3.0, 0.1]); labels.append(1)\ndata.append([-0.1, -1.0]); labels.append(-1)\ndata.append([-1.0, 1.1]); labels.append(-1)\ndata.append([ 2.1, -3.0]); labels.append(1)\n\nsvm = SVM()\n\ndef evalTrainingAccuracy():\n num_correct = 0.0\n for i in range(0, len(data)):\n x = Unit(data[i][0], 0.0)\n y = Unit(data[i][1], 0.0)\n\n true_label = labels[i]\n predicted_label = 1 if (svm.forward(x, y).value > 0) else -1\n if predicted_label == true_label:\n num_correct += 1\n\n return num_correct / len(data)\n\n# learning iteration\nfor j in range(400):\n # select a random data point\n i = int(random() * len(data)) # rounds down and casts to int\n x = Unit(data[i][0], 0.0)\n y = Unit(data[i][1], 0.01)\n l = labels[i]\n svm.learnFrom(x, y, l)\n\n if j % 50 == 0:\n print(\"training accuracy at iteration {} is {}\".format(j, evalTrainingAccuracy()))\n" }, { "alpha_fraction": 0.6367842555046082, "alphanum_fraction": 0.6570271849632263, "avg_line_length": 22.364864349365234, "blob_id": "4291cbce7133fef5402ed27b408a05a0d3ab803a", "content_id": "248a5521f1f5716486a3d9a03bf14689b01373b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1729, "license_type": "no_license", "max_line_length": 70, "num_lines": 74, "path": "/circuits.py", "repo_name": "mcdickenson/nnet-python", "src_encoding": "UTF-8", "text": "from sys import maxint\nfrom random import random\n\n# takes two real-valued inputs and applies a gate\ndef forwardMultiplyGate(x, y):\n return x * y\n\n\n### Approach #1\n# random search for inputs that produce a given output\nx = -2\ny = 3\n\ntweak_amount = 0.01 # epsilon\nbest_out = -maxint # -infinity\nbest_x = x\nbest_y = y\nfor k in range(0, 100):\n # tweak x by a value between -epsilon and + epsilon\n x_try = x + tweak_amount * (random() * 2 - 1)\n # tweak y by a value between -epsilon and + epsilon\n y_try = y + tweak_amount * (random() * 2 - 1)\n out = forwardMultiplyGate(x_try, y_try)\n # in this case, maximize output given the starting values of x and y\n if out > best_out:\n best_out = out\n best_x = x_try\n best_y = y_try\n\nprint(\"best x = {}\".format(best_x))\nprint(\"best y = {}\".format(best_y))\n\n\n\n### Approach #2\n# numerical gradient approach\nx = -2\ny = 3\nout = forwardMultiplyGate(x, y)\nh = 0.0001\n\n# compute derivative w/r/t x\nx_plus_h = x + h\nout2 = forwardMultiplyGate(x_plus_h, y)\nx_derivative = (out2 - out) / h\n\n# compute derivative w/r/t y\ny_plus_h = y + h\nout3 = forwardMultiplyGate(x, y_plus_h)\ny_derivative = (out3 - out) / h\nprint(\"x derivative = {}\".format(x_derivative))\nprint(\"y derivative = {}\".format(y_derivative))\n\nstep_size = 0.01\nout = forwardMultiplyGate(x, y)\nx = x + step_size * x_derivative\ny = y + step_size * y_derivative\nout_new = forwardMultiplyGate(x, y)\nprint(\"new output = {}\".format(out_new))\n\n\n### Approach #3\n# analytic gradient\nx = -2\ny = 3\nout = forwardMultiplyGate(x, y)\nx_gradient = y\ny_gradient = x\n\nstep_size = 0.01\nx += step_size * x_gradient\ny += step_size * y_gradient\nout_new = forwardMultiplyGate(x, y)\nprint(\"new output (analytic approach) = {}\".format(out_new))\n" } ]
6
patrickcanny/cannonball
https://github.com/patrickcanny/cannonball
41a9186f7a00b9ed3d7815da513bf60ab9d5481c
89108706b0214a72d3a6d740a5e5a975a1f2e59b
360715a309d69915ff46c1297be5042d4626e555
refs/heads/master
2020-04-02T01:30:15.525358
2018-10-21T13:56:34
2018-10-21T13:56:34
153,858,881
1
1
MIT
2018-10-20T01:32:11
2018-10-21T09:57:11
2018-10-21T10:18:41
Dart
[ { "alpha_fraction": 0.7860943675041199, "alphanum_fraction": 0.7875133156776428, "avg_line_length": 103.40740966796875, "blob_id": "053c6b27a420d7302bd828973d8a803fc99bf3f8", "content_id": "87a4cb9ea6b203251be4b778cb5364b6ebbd2695", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2819, "license_type": "permissive", "max_line_length": 487, "num_lines": 27, "path": "/readme.md", "repo_name": "patrickcanny/cannonball", "src_encoding": "UTF-8", "text": "[![cannonball](cannonball.png)](https://devpost.com/software/cannonball-k2q1vj)\n\nCannonball is a Location-based check-in application that can automatically export event attendees to a Slack Team. \n\n## Inspiration\nThe idea behind our mobile application is to create the easiest platform for taking class or student organization attendance. Users can see events that are occuring in their area, and check in to those events easily. After the meeting is over, the organizer can send out an invitation to attendees, asking them to join a Slack channel.\n\nAs organizers of club meetings and the like, we are always looking for easy ways to easily track attendance at our meetings, as well as a low stress way of adding them to our communication channels. This app was our proposed solution!\n\n## Challenges\nWe came into this hackathon knowing that we wanted to rey and build a mobile application, but none of us had any experience in developing a great mobile application. Thus, we had to take some time to research some of our options and determine the best tools to use. We landed on Flutter since it looked like a pretty progressive framework, and we had thought it looked pretty interesting. That being said, learning a new development tool meant that we had a tougher time getting started.\n\nWe also ran into a variety of integration challenges between the frontend and backend of our application. Since the Flask API was being developed somewhat independently of the Flutter frontend, we had to troubleshoot some bugs down the stretch. \n\n## Accomplishments\nWe're really excited that we are able to host our API on Google App engine, but we're also incredibly proud of the continuous integration pipeline we set up for this app. Rather than having to create and deploy a new build each time we modify our app, we set up a CI pipeline that created a new build each time we pushed to the master branch. This was incredibly helpful, and saved us a lot of time and potential headaches as we were developing the application. \n\nWe also think that it's cool that we were able to implement a pretty diverse and full-fledged tech stack in a relatively short amount of time. Our project is extensible, which is something that we were aiming for with this app. \n\n## Technologies\nWe built this app using:\n* Flutter - Mobile framework - [docs](https://flutter.io/)\n* Flask - API - [docs](http://flask.pocoo.org/docs/1.0/)\n* Google App Engine - API Host - [docs](https://cloud.google.com/appengine/docs/flexible/python/)\n* Codeship - CI Pipeline - [docs](https://documentation.codeship.com/basic/continuous-deployment/deployment-to-google-app-engine/)\n* Google Maps API - Location Services - [docs](https://developers.google.com/maps/documentation/android-sdk/intro)\n* Slack API - Slack Team Invitation - [docs](https://api.slack.com/)\n" }, { "alpha_fraction": 0.6857143044471741, "alphanum_fraction": 0.7857142686843872, "avg_line_length": 13, "blob_id": "e87b8ee4041d02acf6c2eeb71bf02b9e18d6c3ce", "content_id": "7e5adb7943ebb037729cec0f5cee658ee4b85b5b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 70, "license_type": "permissive", "max_line_length": 18, "num_lines": 5, "path": "/requirements.txt", "repo_name": "patrickcanny/cannonball", "src_encoding": "UTF-8", "text": "Flask\nFlask-PyMongo\ngunicorn==19.7.1\nslackclient==1.0.0\npython-dotenv\n" }, { "alpha_fraction": 0.6163801550865173, "alphanum_fraction": 0.6240861415863037, "avg_line_length": 28.770587921142578, "blob_id": "17177e847e22cb89e1072009d2cc9844a76cf396", "content_id": "57069e78b1e217b4df1a0c6092630cbb658a044b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10122, "license_type": "permissive", "max_line_length": 344, "num_lines": 340, "path": "/main.py", "repo_name": "patrickcanny/cannonball", "src_encoding": "UTF-8", "text": "# Cannonball Internal API\n# IMPORTS\nimport os\nimport urllib\nimport json\nimport math\nfrom bson import Binary, Code\nfrom bson.json_util import dumps, loads\nfrom bson.objectid import ObjectId\nfrom flask import Flask, render_template, request, flash, redirect, url_for, session, logging, jsonify\nfrom flask_pymongo import PyMongo\nfrom slackclient import SlackClient\nfrom dotenv import load_dotenv\n# END IMPORTS\n\nAPP_ROOT = os.path.join(os.path.dirname(__file__),'..')\ndotenv_path = os.path.join(APP_ROOT, '.env')\nload_dotenv(dotenv_path)\n# Define App requirements\napp = Flask(__name__, static_folder=\"../static\", template_folder=\"../static\")\n\n# CONFIG\napp.config[\"MONGO_URI\"] = \"mongodb://\" + urllib.parse.quote(\"cannonball\") + \":\" + urllib.parse.quote(\"test\") + \"@cluster0-shard-00-00-pevs9.gcp.mongodb.net:27017,cluster0-shard-00-01-pevs9.gcp.mongodb.net:27017,cluster0-shard-00-02-pevs9.gcp.mongodb.net:27017/CannonballDB?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true\"\napp.debug=True\nmongo = PyMongo(app)\n\ntoken = mongo.db.users.find_one({\"slack\":{\"$exists\":True}})\ntok = token['slack']\nLOGGER = app.logger\nLOGGER.info(tok)\n\n#SLACK API\n# try:\n# slack_client = SlackClient(os.getenv('SLACK_KEY'))\n# except:\nLOGGER.debug(SlackClient(tok))\nslack_client = SlackClient(tok)\nLOGGER.debug(slack_client.api_call(\"api.test\"))\n\n'''@params'''\[email protected](\"/\")\ndef index():\n return(\"<h1>Cannonball!</h1>\")\n\n'''\n@params\nf_name: string\nl_name: string\nemail: string\n'''\[email protected](\"/authenticateUser\", methods=['POST'])\ndef authenticate():\n userInfo = request.get_json()\n f_name = userInfo.get('f_name')\n l_name = userInfo.get('l_name')\n email = userInfo.get('email')\n\n try:\n user = mongo.db.users.find_one({'f_name':f_name},{'l_name':l_name, 'email':email})\n LOGGER.info(\"Found User {}\".format(user))\n return dumps(user)\n except:\n return {}\n\n'''\n@params\n'''\[email protected](\"/getEvents\", methods=['GET'])\ndef events():\n events = mongo.db.events.find({\"active\": True})\n LOGGER.info(events)\n return dumps(events)\n\n'''\n@params\nname: string as query param described below\n'''\n# {{URL}}/getUsersForEvent?name={event name}\[email protected](\"/getUsersForEvent\", methods = ['GET'])\ndef usersByEvent():\n eventName = request.args.get('name')\n LOGGER.info(eventName)\n event = mongo.db.events.find_one({'name': eventName})\n LOGGER.info(event)\n users = event.get('checkedInUsers')\n LOGGER.info(users)\n\n userDict = {}\n i = 0\n for uid in users:\n elt = mongo.db.users.find_one({\"_id\": uid})\n userDict[i] = elt\n i += 1\n return dumps(userDict)\n\n'''\n@params\nnewUser: user-formatted JSON as body\nsee 'data_model/user.json for details'\n'''\[email protected](\"/newUser\", methods=['POST'])\ndef insertNewUser():\n try:\n newUser = request.get_json()\n LOGGER.info(newUser)\n mongo.db.users.insert(newUser)\n return dumps(newUser)\n except:\n return \"there was an error in creating a new user: {}\".format(newUser)\n\n'''\n@params\nnewGroup: group-formatted JSON as body\n\n'''\[email protected](\"/newGroup\", methods=['POST'])\ndef insertNewGroup():\n newGroup = request.get_json()\n LOGGER.debug(newGroup)\n newusers = []\n newadmins = []\n gname = newGroup['name']\n creatoremail = newGroup['email']\n creator = mongo.db.users.find_one({'email':creatoremail})\n uid = creator.get('_id')\n newusers.append(uid)\n newGroup['users'] = newusers\n LOGGER.debug(newGroup['users'])\n\n if newGroup['users']:\n for user in newGroup['users']:\n try:\n LOGGER.debug('in loop')\n LOGGER.debug('Initial User Info: {}'.format(user))\n LOGGER.debug('USER: {}'.format(user))\n LOGGER.debug(mongo.db.users.find_one({'_id':ObjectId(user)}))\n mongo.db.users.update_one({'_id':ObjectId(user)}, {'$push':{'groups': gname}})\n LOGGER.debug(mongo.db.users.find_one({'_id':ObjectId(user)}))\n\n if user.get('$oid'):\n uid = str(user['$oid'])\n LOGGER.debug(\"UID: {}\".format(uid))\n obj = ObjectId(uid)\n newusers.append(obj)\n LOGGER.debug(\"Parsed oid\")\n\n LOGGER.debug(\"Updated groups\")\n except:\n pass\n\n if newGroup.get('admins'):\n for user in newGroup.get('admins'):\n uid = str(user['$oid'])\n obj = ObjectId(uid)\n newadmins.append(obj)\n\n newGroup['users'] = newusers\n newGroup['admins'] = newadmins\n LOGGER.info(newGroup)\n mongo.db.groups.insert(newGroup)\n return dumps(newGroup)\n\n'''\n@params\nEvent-formatted JSON\n'''\[email protected](\"/newEvent\", methods=['POST'])\ndef insertNewEvent():\n newEvent = request.get_json()\n name = newEvent.get('name')\n LOGGER.info(newEvent)\n email = newEvent.get('email')\n mongo.db.events.insert(newEvent)\n try:\n event = mongo.db.events.find_one({'name': name})\n eid = event.get('_id')\n except:\n return \"Could not find newly created event. Perhaps your group does not exist\"\n try:\n group = mongo.db.groups.find_one({'email': email})\n except:\n return \"Group not found, please create a new group first.\"\n groupEvents = group.get('events')\n if not groupEvents or eid not in groupEvents:\n mongo.db.groups.update_one({'email':email},{'$push':{'events':eid}})\n return dumps(newEvent)\n\n'''\n@params\nname: the name of an event\nemail: some user email that is checking in\n'''\[email protected](\"/checkInUser\", methods=['POST'])\ndef checkInUser():\n LOGGER.info('recieved')\n newCheckIn = request.get_json()\n LOGGER.info(newCheckIn)\n event = newCheckIn.get('name')\n targetEvent = mongo.db.events.find_one({'name': event})\n LOGGER.debug(\"TargetEvent: {}\".format(targetEvent))\n useremail = newCheckIn.get('email')\n targetUser = mongo.db.users.find_one({'email': useremail})\n targetGroup = targetEvent.get('groupID')\n groups = targetUser.get('groups')\n LOGGER.debug(\"Groups: {}\".format(groups))\n LOGGER.debug(\"TargetGroup: {}\".format(targetGroup))\n\n if targetGroup not in groups:\n LOGGER.info(\"targetGroup not in user's current groups\")\n myId = targetUser.get('_id')\n mongo.db.users.update_one({'_id': myId}, {'$push': {'groups': targetGroup}})\n\n LOGGER.info(targetUser)\n LOGGER.info(targetEvent)\n\n userId = targetUser.get(\"_id\")\n myId = targetEvent.get(\"_id\")\n if myId != None:\n event = mongo.db.events.find_one({'_id':myId})\n if userId not in event['checkedInUsers']:\n mongo.db.events.update_one({'_id': myId}, {'$push': {'checkedInUsers': userId}})\n return \"Successfully checked in\"\n else:\n return \"Looks like you're already checked in!\"\n\n'''\n@params\nemail: user email\n'''\[email protected](\"/userGroups\", methods=['POST'])\ndef getAllGroupsForUser():\n LOGGER.info('recieved')\n theUser = request.get_json()\n useremail = theUser.get('email')\n targetUser = mongo.db.users.find_one({'email': useremail})\n groups = targetUser.get('groups')\n LOGGER.debug(groups)\n [x.encode('utf-8') for x in groups]\n return str(groups).encode('utf-8')\n\n'''\n@params\ngroup: some group name as a query param\n'''\[email protected](\"/exportToSlack\", methods=['POST'])\ndef slackExport():\n groupName = request.args.get('group')\n group = mongo.db.groups.find_one({\"name\": groupName})\n users = group.get('users')\n\n team = slack_client.api_call(\"users.list\")\n LOGGER.debug(team)\n teamEmails = ()\n for user in team:\n try:\n LOGGER.debug(user)\n email = user.get('profile').get('email')\n teamEmails.add(email)\n except:\n pass\n\n emails =()\n calls = []\n for user in users:\n u = mongo.db.users.find_one({\"_id\": user})\n email = u.get('email')\n if email not in teamEmails:\n callstring = \"users.admin.invite?email={}\".format(email)\n LOGGER.info(callstring)\n calls.append(callstring)\n slack_client.api_call(callstring)\n\n\n return \"Emails Sent to: {}\".format(calls)\n\n'''\n@params\nlocation: a JSON with a latitude and longitude info\n'''\[email protected](\"/getNearbyEvents\", methods = ['POST'])\ndef getNearbyEvents():\n LOGGER.info('recieved')\n location = request.get_json()\n curLong = location.get('longitude')\n curLat = location.get('latitude')\n LOGGER.info(curLong)\n LOGGER.info(curLat)\n myEvents = mongo.db.events.find({})\n nearbyEvents = []\n for x in myEvents:\n if distance(float(curLat), float(x.get('latitude')), float(curLong), float(x.get('longitude'))) >0 :\n nearbyEvents.append(x.get('name'))\n return dumps(nearbyEvents)\n\n'''\n@params\nname: name of a group\n'''\[email protected](\"/pingAllMembers\", methods = ['POST'])\ndef getAllMembers():\n LOGGER.info('recieved')\n groupinfo = request.get_json()\n groupName = groupinfo.get('name')\n targetGroup = mongo.db.groups.find_one({\"name\": groupName})\n groupMembers = targetGroup.get('users')\n return dumps(groupMembers)\n\n'''\n@params\nname: name of the 3event you want to close\n'''\[email protected](\"/closeEvent\", methods = ['POST'])\ndef closeEvent():\n LOGGER.info('recieved')\n eventinfo = request.get_json()\n eventName = eventinfo.get('name')\n mongo.db.events.update_one({'name': eventName}, {'$set':{\"Active\": False}})\n return 'success'\n\n'''\n@params\nlat1, lat2, long1, long2\ncalculate distance helper function\n'''\ndef distance(lat1, lat2, long1, long2):\n dlong = long2 - long1\n dlat = lat2 -lat1\n a = (math.sin(dlat/2))**2 + math.cos(lat1) * math.cos(lat2) * (math.sin(dlong/2))**2\n c = 2 * math.atan2( math.sqrt(a), math.sqrt(1-a) )\n d = 3961 * c\n return d\n\n\n# LAUNCH APP\nif __name__ == \"__main__\":\n port = int(os.environ.get(\"PORT\", 5000))\n LOGGER.info(\"Getting Flask up and running...\\n\")\n if slack_client.api_call(\"api.test\") is not None:\n LOGGER.info(\"Connected to Slack!\")\n app.run(host = '127.0.0.1' , port = port)\n" } ]
3
aflatt/vimplus
https://github.com/aflatt/vimplus
b63a51805fec77396e058d5b5ae2e448324eb9d7
31b1c98bd3ed78244f3525dba6f4d6f8ed2b78d5
44b80617032695a58ab700de3518358a921afd86
refs/heads/master
2021-01-23T06:40:07.722618
2013-04-07T19:22:06
2013-04-07T19:22:06
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7381752729415894, "alphanum_fraction": 0.7422102689743042, "avg_line_length": 35.565574645996094, "blob_id": "512390af2d45f3a0e40fbf233e55d6db53544913", "content_id": "6d927cd223e9a502aa7bdfec73149ed5ce502f98", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4461, "license_type": "permissive", "max_line_length": 102, "num_lines": 122, "path": "/plugin/vimplus.py", "repo_name": "aflatt/vimplus", "src_encoding": "UTF-8", "text": "import vim\n\ndef runCmd(cmd):\n\t\"\"\"Runs a command using vim's !\"\"\"\n\tvim.command(\"!\"+cmd)\n\ndef runSystemCmd(cmd, fileOutput=None):\n\t\"\"\"Runs the command using vim's system mechanism.\n\t\tfileOutput - specifies the file on disk to save the output of the cmd to\n\t\t\t\t\tif null doesn't save anything\n\t\treturns the results of the command\"\"\"\n\tvim.command(\"let cmdOutput = system('{0}')\".format(cmd))\n\toutput = vim.eval(\"cmdOutput\")\n\tif fileOutput != None:\n\t\tfile = open(fileOutput, \"w\")\n\t\tfile.write(output)\n\t\tfile.close()\n\treturn output\n\ndef input(message):\n\t\"\"\"Prompt the user for input with. Supply the message as a prompt\n\t\treturns the input from the user\"\"\"\n\tvim.command(\"let inputText = input('{0}')\".format(message))\n\ttext = vim.eval(\"inputText\")\n\treturn text\n\ndef inputSecret(message):\n\t\"\"\"Prompt the user for hidden input. Supplies the message as a prompt\n\t\treturns the input from the user\"\"\"\n\tvim.command(\"let inputText = inputsecret('{0}')\".format(message))\n\ttext = vim.eval(\"inputText\")\n\treturn text\n\ndef splitWindowLeft(size, fileName=None):\n\t\"\"\"Split the vim window vertically with the new window appearing on the west\n\tof the screen\n\t\tsize is the horizontal screen size the window should take\n\t\tfileName is an optional name of a file to open in the new window\n\t\treturns the newly created buffer\"\"\"\n\tif fileName is None:\n\t\tvim.command(\"aboveleft {0}vsplit {1}\".format(size, fileName))\n\telse:\n\t\tvim.command(\"aboveleft {0}vnew\".format(size))\n\tgotoStart()\n\treturn vim.current.buffer\n\ndef splitWindodwRight(size, fileName=None):\n\t\"\"\"Split the vim window vertically with the new window appearing on the east\n\tof the screen\n\t\tsize is the horizontal screen size the window should take\n\t\tfileName is an optional name of a file to open in the new window\n\t\treturns the newly created buffer\"\"\"\n\tif fileName is None:\n\t\tvim.command(\"botright {0}vsplit {1}\".format(size, fileName))\n\telse:\n\t\tvim.command(\"botright {0}vnew\".format(size))\n\tgotoStart()\n\treturn vim.current.buffer\n\ndef splitWindowBottom(size, fileName=None):\n\t\"\"\"Split the vim window horizontally with the new window appearing on the south\n\tof the screen\n\t\tsize is the vertical screen size (in lines) that the window should use\n\t\tfileName is an optional name of a file to open in the new window\n\t\treturns the newly created buffer\"\"\"\n\tif fileName is None:\n\t\tvim.command(\"belowright {0}split {1}\".format(size, fileName))\n\telse:\n\t\tvim.command(\"belowright {0}new\".format(size))\n\tgotoStart()\n\treturn vim.current.buffer\n\ndef splitWindowTop(size, fileName=None):\n\t\"\"\"Split the vim window horizontally with the new window appearing on the north\n\tof the screen\n\t\tsize is the vertical screen size (in lines) that the window should use\n\t\tfileName is an optional name of a file to open in the new window\n\t\treturns the newly created buffer\"\"\"\n\tif fileName is None:\n\t\tvim.command(\"{0}split {1}\".format(size, fileName))\n\telse:\n\t\tvim.command(\"belowright {0}new\".format(size))\n\tgotoStart()\n\treturn vim.current.buffer\n\ndef setBufferTypeScratch():\n\t\"\"\"Make the current buffer a scratch buffer (i.e. where a temporary buffer that can be discarded)\n\tat any time\"\"\"\n\tvim.command(\"setlocal buftype=nofile\")\n\tvim.command(\"setlocal bufhidden=hide\")\n\tvim.command(\"setlocal noswapfile\")\n\ndef gotoStart():\n\t\"\"\"Moves the cursor to the start of the current buffer\"\"\"\n\tvim.command(\"normal gg\")\n\ndef setupCompletion(onKeys, completionMethod):\n\t\"\"\"The vimplus complete method, which display a list of available autocompletions\n\tcan only be called from insert mode. This method sets up the appropriate key bindings\n\tthat will trigger calling the method\n\t\tonKeys - the keys that will trigger the method\n\t\tcompletionMethod - the completion method to call\"\"\"\n\tpass\n\ndef complete(words):\n\t\"\"\"Shows the vim autocompletion menu\"\"\"\n\tvim.command(\"call complete(col('.'), {0})\".format(words))\n\ndef onEvent(event, action):\n\t\"\"\"Registers a call back that will be invoked when a vim event occurs\n\t\tevent is the name of the vim event to register (use event<name> members of vimplus)\n\t\taction is the python method to call when the event occurs\"\"\"\n\tpyMethodName = action.__name__\n\tvimFuncName = pyMethodName\n\tvimFuncName = pyMethodName[0].upper() + pyMethodName[1:]\n\tvim.command(\"autocmd {event} * call {functionName}()\".format(event=event, functionName=vimFuncName))\t\n\tvim.command(\"\"\"fun! {functionName}()\npy {pyMethodName}()\nendf\"\"\".format(functionName=vimFuncName, pyMethodName=pyMethodName))\n\neventBuferWrite = \"BuferWrite\"\neventCursorMoved = \"CursorMoved\"\n" }, { "alpha_fraction": 0.7406143546104431, "alphanum_fraction": 0.7453925013542175, "avg_line_length": 26.129629135131836, "blob_id": "99a59ddb3bb74006907a0c7e701a6bbc311247c7", "content_id": "28946f11eb32e91e778f1680cd1d8883f1b20a56", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1465, "license_type": "permissive", "max_line_length": 154, "num_lines": 54, "path": "/README.md", "repo_name": "aflatt/vimplus", "src_encoding": "UTF-8", "text": "Vimplus\n=========\n\nVimplus is a python module for scripting vim.\n\nVim includes a python module called \"vim\", which facilitates scripting vim in python.\nUnfortunately this module provides very limited interaction with vim.\n\nVimplus aims to provide a more comprehensive vim api. The ultimate goal of vimplus is that writing plugins for vim should be easier.\n\nLICENSE\n---------\n\nVimplus is currently published under the MIT license\n\n\nUSE\n---------\n\nI highly recommend using the excellent vim plugin pathogen in conjunction with vimplus.\nTo use vimplus simply:\n\n1. Clone the git repo into your pathogen bundle directory.\n2. Restart vim\n\nYou can test that vimplus is installed by running the following command directly from vim:\n\n :py import vimplus\n\nIf the command executes without any errors, than you're all set!\n\n\nTo get started using vimplus in a vim script you can use this simple template (note that you MUST NOT! indent this code):\n\n python << EOF\n import vim\n import vimplus\n print(\"Hello from vimplus\")\n EOF\n\nWith the above file (i.e. the template) open in vim, you can run the script by sourcing the file:\n\n so %\n\nREQUIREMENTS\n----------\n\nRight now vimplus requires vim built with python support. It currently only works with python 2, but I plan to eventually add support for python3 as well.\nIn the meantime if you are using python3, you can support python3 by changing any line that contains:\n\n python << EOF\nto\n\n python3 << EOF\n" } ]
2
cheyt4c/pythonlearning
https://github.com/cheyt4c/pythonlearning
4b72399766d4d28a7195f032e8da49df66653239
baa5d77b6b88e41be0fba4a3f55dd299f59590b7
0d108741261464b59e408ca6193c1bb9f14618fb
refs/heads/master
2020-11-25T10:00:59.370972
2020-01-03T12:10:14
2020-01-03T12:10:14
228,609,163
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7088888883590698, "alphanum_fraction": 0.7333333492279053, "avg_line_length": 28.933332443237305, "blob_id": "2d181bb54ab1ed1e61ef38925acd22afb9cb765d", "content_id": "a18cecc56d0456b6070883a7e36cd1f27e93ce75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 450, "license_type": "no_license", "max_line_length": 72, "num_lines": 15, "path": "/ch4/copy.py", "repo_name": "cheyt4c/pythonlearning", "src_encoding": "UTF-8", "text": "# 17/12/2019\n# this program demonstrates the use of the copy and deepcopy function\n# this is used when you haee a function which modifies the list, however\n# you do not want it to manipulate the real/original list. Hence, you \n# take a copy of that list before modifying the copied list\n\nimport copy\n\nspam = ['A', 'B', 'C', 'D']\ncheese = copy.copy(spam)\ncheese[1] = 42\nprint(spam)\nprint(cheese)\n\n#cannot run for some reason, will troubleshoot later\n\n" }, { "alpha_fraction": 0.7851239442825317, "alphanum_fraction": 0.7933884263038635, "avg_line_length": 28.75, "blob_id": "b21eb4f996b61b2c1c1f32b4cd4250d72420e15b", "content_id": "94167ab9f6f78f586d7fe33a13bd9231c1192bb9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 121, "license_type": "no_license", "max_line_length": 63, "num_lines": 4, "path": "/README.md", "repo_name": "cheyt4c/pythonlearning", "src_encoding": "UTF-8", "text": "# pythonlearning\nThis is my progress learning python.\n\nChapter 6 projects need to be completed. Up to pyperclip module\n\n\n" }, { "alpha_fraction": 0.5889570713043213, "alphanum_fraction": 0.6380367875099182, "avg_line_length": 15.399999618530273, "blob_id": "62c4728dfcffe64cd24ac7aaf65f1aca2ab45aa5", "content_id": "1b107957f40250e8b668d2739e5374df87995464", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 163, "license_type": "no_license", "max_line_length": 51, "num_lines": 10, "path": "/ch3/helloFunc.py", "repo_name": "cheyt4c/pythonlearning", "src_encoding": "UTF-8", "text": "# 16/12/2019\n# this program demonstrates how to create functions\n\ndef hello():\n print('Howdy!')\n print('Howdy!!!')\n print('Hello there.')\n\nhello()\nhello()" }, { "alpha_fraction": 0.6564245820045471, "alphanum_fraction": 0.7011173367500305, "avg_line_length": 18.88888931274414, "blob_id": "0168d86571aeed15e4cea3b954df24c3105c16eb", "content_id": "e668ca93fb213079991ae540e95d4757fb9712ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 358, "license_type": "no_license", "max_line_length": 76, "num_lines": 18, "path": "/ch3/sameName2.py", "repo_name": "cheyt4c/pythonlearning", "src_encoding": "UTF-8", "text": "# 16/12/2019# 16/12/2019\n# this program demonstrates the declaration of a global varibale within \n# a function\n\ndef spam():\n global eggs\n eggs = 'spam'\n\neggs = 'global'\nspam()\nprint(eggs)\n\n\n\n'''\neggs is declared a gloab at the top of spam, when eggs is set to spam, the \nassignment is done globally scoped eggs. No local variable 'eggs' is created\n'''\n" }, { "alpha_fraction": 0.6465116143226624, "alphanum_fraction": 0.6837209463119507, "avg_line_length": 18.545454025268555, "blob_id": "fb1b7aafd635a976e57bacb56f1c106b3c3139b5", "content_id": "611579c9278c1c40fa4cf82d52c79ea4af1c979c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 215, "license_type": "no_license", "max_line_length": 66, "num_lines": 11, "path": "/ch3/sameName4.py", "repo_name": "cheyt4c/pythonlearning", "src_encoding": "UTF-8", "text": "# 16/12/2019\n# this program demonstrates the error you receive when you attempt\n# to use a local variable before declaring it\n\ndef spam():\n # ERROR\n print(eggs)\n eggs = 'spam local'\n\neggs = 'global'\nspam()\n" }, { "alpha_fraction": 0.6384803652763367, "alphanum_fraction": 0.658088207244873, "avg_line_length": 23.02941131591797, "blob_id": "0fc248f676d6fcc6b5052ab4382637d5be18ddd8", "content_id": "7c15f51cb0a1162b1cff44161c409df92b2e67be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 816, "license_type": "no_license", "max_line_length": 81, "num_lines": 34, "path": "/ch3/sameName3.py", "repo_name": "cheyt4c/pythonlearning", "src_encoding": "UTF-8", "text": "# 16/12/2019\n# this program is to demonstrate the use of the 4 rules to help determine whether\n# a variable is global or local variable\n'''\n# the 4 rules are as follows\n 1 - if a variable is used in global scope (outside of all functions), it\n global\n 2 - if there is a 'global' statement for that variable in a function, it \n is a global\n 3 - if the variable is unused in an assignment statement in a function, it \n is a local variable\n 4 - but if the variable is not used in an assignment statement, it is \n a global variable\n\n'''\ndef spam():\n global eggs\n #global variable\n eggs = 'spam'\n\ndef bacon():\n #local variable\n eggs = 'bacon'\n print(eggs) \n\ndef ham():\n #this is the global\n print(eggs)\n\n#global variable\neggs = 42\nspam()\nbacon()\nprint(eggs)" }, { "alpha_fraction": 0.6556169390678406, "alphanum_fraction": 0.6721915006637573, "avg_line_length": 24.809524536132812, "blob_id": "bf1e189833f537af2fab3582c6aac3d75c5c3960", "content_id": "49ebf9aadb3620f7229c455dce714e02cbc91421", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 543, "license_type": "no_license", "max_line_length": 65, "num_lines": 21, "path": "/ch2/littleKid.py", "repo_name": "cheyt4c/pythonlearning", "src_encoding": "UTF-8", "text": "#this program demonstrates the use of if,elif statements for \n#program control and basic logic\n\n# ask for name of individual\nprint('What is your name?')\nname = input()\n\n# find age of individual\nprint('What is your age?')\nage = input()\n\nif name == 'Alice':\n print('Hi, Alice')\nelif int(age) < 12:\n print('You are not Alice, kiddo.')\nelif int(age) > 2000:\n print('Unlike you, Alice is not an undead, immortal vampire')\nelif int(age) > 100:\n print('You are not Alice, grannie')\nelif name != 'Alice':\n print(\"You are an imposter\")\n\n" }, { "alpha_fraction": 0.6726058125495911, "alphanum_fraction": 0.7060133814811707, "avg_line_length": 27, "blob_id": "8b9d59022e43b2f91d2fde61502f0e8b09ca0d26", "content_id": "e7736d177fe03102b89e72d85aac610e853019dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 449, "license_type": "no_license", "max_line_length": 78, "num_lines": 16, "path": "/ch3/zeroDivide.py", "repo_name": "cheyt4c/pythonlearning", "src_encoding": "UTF-8", "text": "# 16/12/2019\n# this program demonstrates exception handling. In real world, you do not\n# want your program to hang if there is an exception. You want the program to \n# handle it and keep running\n# we accomplish this by using 'try' and 'except' statements\n\ndef spam(divideBy):\n try:\n return 42 / divideBy\n except ZeroDivisionError:\n print('Error: Invalid argument.')\n\nprint(spam(2))\nprint(spam(12))\nprint(spam(0))\nprint(spam(1))\n\n" }, { "alpha_fraction": 0.6799276471138, "alphanum_fraction": 0.6998191475868225, "avg_line_length": 25.380952835083008, "blob_id": "ef0fe20c69f7b35df3d1164ab56e8ef12c57114d", "content_id": "767e439f9eae92f46e32c552e09b1842e34baac3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 553, "license_type": "no_license", "max_line_length": 74, "num_lines": 21, "path": "/ch4/magic8ball2.py", "repo_name": "cheyt4c/pythonlearning", "src_encoding": "UTF-8", "text": "# 17/12/2019\n# this program is an improved version of the program found in the previous\n# chapter\n# this program uses a list\n\n#import random module\nimport random\n\n#declares a list with the following strings\nmessages= ['It is certain' , \n 'It is decidedly so',\n 'Yes definitely',\n 'Reply hazy try again',\n 'Ask again later',\n 'Concentrate and ask again',\n 'My reply is no',\n 'Outlook not so good',\n 'Very doubtful']\n\n# generates a random number between 0 and the message number\nprint(messages[random.randint(0, len(messages) -1)])" }, { "alpha_fraction": 0.7040970921516418, "alphanum_fraction": 0.7283763289451599, "avg_line_length": 27.65217399597168, "blob_id": "4e56c2acca55ea72b43df160a7b669a8947ebfbc", "content_id": "fa8b1e17b00bdccaacd8de8feacf889f2299375f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 659, "license_type": "no_license", "max_line_length": 78, "num_lines": 23, "path": "/ch3/zeroDivide1.py", "repo_name": "cheyt4c/pythonlearning", "src_encoding": "UTF-8", "text": "# 16/12/2019\n# similar to zeroDivide.py\n# this program demonstrates exception handling. In real world, you do not\n# want your program to hang if there is an exception. You want the program to \n# handle it and keep running\n# we accomplish this by using 'try' and 'except' statements\n\ndef spam(divideBy):\n return 42 / divideBy\n\n\ntry:\n print(spam(2))\n print(spam(12))\n print(spam(0))\n print(spam(1))\n\nexcept ZeroDivisionError:\n print('Error: Invalid argument')\n\n#this output differs to the previous program because it does not continue to\n# evaluate spam(1) because once it jumps to the except clause, it does not\n# go back into the try clause\n" }, { "alpha_fraction": 0.7256637215614319, "alphanum_fraction": 0.747787594795227, "avg_line_length": 27.3125, "blob_id": "f45894e55fa62f8f8729dc74a186d15582bd383d", "content_id": "fbceb9bcf7df443dda949cc0b9aa5c2c80b9eb7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 452, "license_type": "no_license", "max_line_length": 85, "num_lines": 16, "path": "/ch5/prettyCharacterCount.py", "repo_name": "cheyt4c/pythonlearning", "src_encoding": "UTF-8", "text": "# 23/12/2019\n# This program uses a dictionary to count up the occurence of letters \n# within a string\n# it also uses the 'setdefault function'\n# the pretty print module is used and makes reading the output easier\n\nimport pprint\n\nmessage = 'It was a bright cold day in April, and the clocks were striking thirteen.'\ncount ={}\n\nfor character in message:\n count.setdefault(character, 0)\n count[character] = count[character] + 1\n\npprint.pprint(count)" }, { "alpha_fraction": 0.4161369204521179, "alphanum_fraction": 0.4474327564239502, "avg_line_length": 26.280000686645508, "blob_id": "8d2a052ff1bfcaf287e071966410503f4dac0543", "content_id": "e5a7ab21b456354db2ed0f06b2fbe2fe3565cc2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2045, "license_type": "no_license", "max_line_length": 80, "num_lines": 75, "path": "/ch4/pracproj/pict.py", "repo_name": "cheyt4c/pythonlearning", "src_encoding": "UTF-8", "text": "# 17/12/2019\n# takes in an initial grid and rotates it by 90 deg clockwise\n'''\ninput\n['.', '.', '.', '.', '.', '.'],\n['.', 'O', 'O', '.', '.', '.'],\n['O', 'O', 'O', 'O', '.', '.'],\n['O', 'O', 'O', 'O', 'O', '.'],\n['.', 'O', 'O', 'O', 'O', 'O'],\n['O', 'O', 'O', 'O', 'O', '.'],\n['O', 'O', 'O', 'O', '.', '.'],\n['.', 'O', 'O', '.', '.', '.'],\n['.', '.', '.', '.', '.', '.']\n\noutput\n[..00.00..]\n[.0000000.]\n[.0000000.]\n[..00000..]\n[...000...]\n[....0....]\n'''\n\n#this function reads the grid and just prints it as is\n#this was used for familiarisation with the coordinates and logic\ndef rotate(grid_val):\n y = (len(grid_val)) - 1\n print(y)\n while (y > 0):\n for x in range (len(grid_val[y])):\n print(grid_val[y][x], end = '')\n print('')\n y = y - 1\n\n return 0\n\n#this function completes the task\ndef rotate2(grid_val):\n y = 0\n #y row index of the output grid\n #in the range func, it gives out the length of each row of the input grid\n for y in range(len(grid_val[y])):\n #x represents the column index of the output grid\n #the range function here gives the number of lists within the original\n #list\n for x in range(len(grid_val)):\n #we need to read the first element of each list\n #from 8 -> 0\n #row index starts from 8 and decreases to 0 with each loop iteration\n row_index = (len(grid_val)) - 1 - x\n\n #print what is found in the original grid at certain locations\n #start with 8,0 -> 0,0 || 8,1 - > 0,1 || until 8,6 -> 0,6\n print(grid_val[row_index][y], end = '')\n print('')\n return 0\n\n\n#main\n#input grid\ngrid = [['.', '.', '.', '.', '.', '.'],\n['.', 'O', 'O', '.', '.', '.'],\n['O', 'O', 'O', 'O', '.', '.'],\n['O', 'O', 'O', 'O', 'O', '.'],\n['.', 'O', 'O', 'O', 'O', 'O'],\n['O', 'O', 'O', 'O', 'O', '.'],\n['O', 'O', 'O', 'O', '.', '.'],\n['.', 'O', 'O', '.', '.', '.'],\n['.', '.', '.', '.', '.', '.']]\n\n\n#print(len(grid)-1)\n#print(len(grid[0]))\n#print result\nresult = rotate2(grid)" }, { "alpha_fraction": 0.6275370121002197, "alphanum_fraction": 0.6341195702552795, "avg_line_length": 29.431034088134766, "blob_id": "36a77324b15963c7d310ac271531c76a40a0d2a8", "content_id": "af05b544f448e3ec23d795cff199300f5f1c2193", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1823, "license_type": "no_license", "max_line_length": 93, "num_lines": 58, "path": "/ch3/pracproj/collatz_cool.py", "repo_name": "cheyt4c/pythonlearning", "src_encoding": "UTF-8", "text": "# victor wrote this\r\n# this program is a practice program to execute the collatz sequence\r\n# additionally, it builds upon the previous program, where it will continuously\r\n# poll the user until it gets a valid value (int) \r\n\r\n# the previous program would exit when it did not get an int\r\n\r\n#import sys\r\n\r\n# code style (completely subjective)\r\ndef main():\r\n # main \r\n # prompt user to type in an integer that keeps calling collatz \r\n # on that number until the function returns the value 1\r\n\r\n #ask for user input\r\n user_input = getInput()\r\n\r\n #print out what integer the user has input and begin collatz\r\n print('The integer you have input is {}'.format(user_input)) # python3 alternative\r\n print('Collatz will now begin...')\r\n\r\n output_num = collatz(user_input)\r\n\r\n #keep iterating through collatz function until 1 is hit, which it will then exit\r\n while output_num != 1:\r\n numb = output_num\r\n output_num = collatz(numb)\r\n\r\n #sys.exit() # unnecessary - program will terminate by itself when it reaches end of file\r\n\r\n\r\ndef collatz(number):\r\n #if number is even -> print number//2, then return value \r\n check = number%2\r\n if check == 0:\r\n number = number//2\r\n #else (number is odd) -> print 3*number+1, then return value\r\n else:\r\n number = 3*number + 1\r\n print(number)\r\n return number\r\n\r\ndef getInput():\r\n #prompt user for input. We expect an int\r\n #try to get an input\r\n while True:\r\n try:\r\n input_num = int(input('Enter a value: '))\r\n return input_num\r\n #if there is an error, set an error message and return, this will exit\r\n #function. \r\n except ValueError:\r\n print('Error: Invalid argument. Please enter an Integer')\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n" }, { "alpha_fraction": 0.6878109574317932, "alphanum_fraction": 0.7027363181114197, "avg_line_length": 21.30555534362793, "blob_id": "819c2a067069c75ebfcaee0c56afc1d6cc4e9aa4", "content_id": "afe4aec29127f5d3664071d636df2ca47beea23a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 804, "license_type": "no_license", "max_line_length": 79, "num_lines": 36, "path": "/ch3/sameName.py", "repo_name": "cheyt4c/pythonlearning", "src_encoding": "UTF-8", "text": "# 16/12/2019\n# this program demonstrates the difference between local and global scopes\n# this program explores the interaction between local and global variables with\n# the same name\n\ndef spam():\n eggs = 'spam local'\n #prints 'spam local'\n print(eggs)\n\ndef bacon():\n eggs = 'bacon local'\n #prints bacon local\n print(eggs)\n spam()\n #print 'bacon local'\n print(eggs)\n\neggs = 'global'\nbacon()\n#prints 'global'\nprint(eggs)\n\n\n''' output\nbacon local\nspam local\nbacon local\nglobal \n'''\n# there are actually 3 different variables in this program\n# 1 - eggs in a local scope when spam() is called\n# 2 - eggs in a local scope when bacon() is called\n# 3 - eggs that exists in the global scope (inside the main)\n\n# this is why its good practice to keep your variables as different names\n\n" }, { "alpha_fraction": 0.5728476643562317, "alphanum_fraction": 0.5860927104949951, "avg_line_length": 16.823530197143555, "blob_id": "feeab86072b4ac7a3ef1ae10cb73e821aa6a022d", "content_id": "04d82b5b85dd0cfe71aaad94e0aff6b91008c806", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 302, "license_type": "no_license", "max_line_length": 58, "num_lines": 17, "path": "/ch2/fiveTimes.py", "repo_name": "cheyt4c/pythonlearning", "src_encoding": "UTF-8", "text": "# this program demonstrates the use of while and for loops\n\n\n'''\n# for loop intepretation\nprint('My name is')\nfor i in range(5):\n print('Jimmy Five Times (' + str(i) + ')')\n'''\n\n\n# while loop intepretation\nprint('My name is')\ni = 0\nwhile i < 5:\n print('Jimmy FIve Times (' + str(i) + ')')\n i = i + 1" }, { "alpha_fraction": 0.6583850979804993, "alphanum_fraction": 0.7080745100975037, "avg_line_length": 19.25, "blob_id": "388cfed293242eee4bdfd8dd421258587101c387", "content_id": "881f71ce5d6c7647c3e62a541e4575f149027f4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 161, "license_type": "no_license", "max_line_length": 74, "num_lines": 8, "path": "/ch3/helloFunc2.py", "repo_name": "cheyt4c/pythonlearning", "src_encoding": "UTF-8", "text": "# 16/12/2019\n# this program demonstrates the use of functions with an argument/paramter\n\ndef hello(name):\n print('Hello ' + name)\n\nhello('Alice')\nhello('Bob')" }, { "alpha_fraction": 0.6896551847457886, "alphanum_fraction": 0.7370689511299133, "avg_line_length": 22.299999237060547, "blob_id": "a3535bb3657e7328232305e79f00ed8d8005b624", "content_id": "661be37fc3785e2eb83e39e331e792dbcf79e27c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 232, "license_type": "no_license", "max_line_length": 62, "num_lines": 10, "path": "/ch4/passingReference.py", "repo_name": "cheyt4c/pythonlearning", "src_encoding": "UTF-8", "text": "# 17/12/2019\n# this program demonstrates how lists are stored by reference.\n# notice how the function does not have a function call\n\ndef eggs(someParameter):\n someParameter.append('Hello')\n\nspam = [1, 2, 3]\neggs(spam)\nprint(spam)" }, { "alpha_fraction": 0.623501181602478, "alphanum_fraction": 0.6450839042663574, "avg_line_length": 20.894737243652344, "blob_id": "8fad6ecb72ebfd4db40fa5e51eb92a4c50102b03", "content_id": "058a0bc26d689acea6e60b89b8ce43c3ef6af3ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 834, "license_type": "no_license", "max_line_length": 68, "num_lines": 38, "path": "/ch3/pracproj/collatz.py", "repo_name": "cheyt4c/pythonlearning", "src_encoding": "UTF-8", "text": "# 17/12/2019\n# this program is a practice program to execute the collatz sequence\n\nimport sys\n\ndef collatz(number):\n #if number is even -> print number//2, then return value \n check = number%2\n if check == 0:\n number = number//2\n print(number)\n return number\n else:\n number = 3*number + 1\n print(number)\n return number\n #else (number is odd) -> print 3*number+1, then return value\n\n\n# main \n# prompt user to type in an integer that keeps calling collatz \n# on that number until the function returns the value 1\n\nprint('Enter a value:')\ntry:\n input_num = int(input())\n\nexcept ValueError:\n print('Error: Invalid argument.')\n sys.exit()\n\noutput_num = collatz(input_num)\n\nwhile output_num != 1:\n input_num = output_num\n output_num = collatz(input_num)\n\nsys.exit()\n\n\n" }, { "alpha_fraction": 0.6634174585342407, "alphanum_fraction": 0.6743119359016418, "avg_line_length": 26.21875, "blob_id": "faae4a421b55b960acfcaf356f2881961d914b60", "content_id": "73409d209e452b6c8e973b04f36af23bae570143", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1744, "license_type": "no_license", "max_line_length": 80, "num_lines": 64, "path": "/ch3/pracproj/collatz2.py", "repo_name": "cheyt4c/pythonlearning", "src_encoding": "UTF-8", "text": "# 17/12/2019\n# this program is a practice program to execute the collatz sequence\n# additionally, it builds upon the previous program, where it will continuously\n# poll the user until it gets a valid value (int) \n\n# the previous program would exit when it did not get an int\n\nimport sys\n\ndef collatz(number):\n #if number is even -> print number//2, then return value \n check = number%2\n if check == 0:\n number = number//2\n print(number)\n return number\n\n #else (number is odd) -> print 3*number+1, then return value\n else:\n number = 3*number + 1\n print(number)\n return number\n\ndef getInput():\n #prompt user for input. We expect an int\n print('Enter a value:')\n\n #try to get an input\n try:\n input_num = int(input())\n\n #if there is an error, set an error message and return, this will exit\n #function. \n except ValueError:\n print('Error: Invalid argument. Please enter an Integer')\n flag = 'error'\n return flag\n\n #if everything is well, return the input_num\n return input_num\n\n# main \n# prompt user to type in an integer that keeps calling collatz \n# on that number until the function returns the value 1\n\n#ask for user input\nuser_input = getInput()\n\n#if the function returns an error, it means the input was not an int\nif user_input == 'error':\n user_input = getInput()\n\n#print out what integer the user has input and begin collatz\nprint('The integer you have input is ' + str(user_input))\nprint('Collatz will now begin...')\n\noutput_num = collatz(user_input)\n\n#keep iterating through collatz function until 1 is hit, which it will then exit\nwhile output_num != 1:\n numb = output_num\n output_num = collatz(numb)\n\nsys.exit()\n\n\n" }, { "alpha_fraction": 0.6485084295272827, "alphanum_fraction": 0.6640726327896118, "avg_line_length": 28.576923370361328, "blob_id": "c89e42f0a70fcb89da705864882f9a3d4b940b76", "content_id": "2a33c4bccc07826a7fd2aaf4a18c2207e83c07fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 771, "license_type": "no_license", "max_line_length": 79, "num_lines": 26, "path": "/ch4/pracproj/comma.py", "repo_name": "cheyt4c/pythonlearning", "src_encoding": "UTF-8", "text": "# 17/12/2019\n# write a function that takes a list value as an argument and returns a string \n# with all the items separated by a comma and a space with 'and' inserted \n# before the last item\n\n#function which takes in a list\ndef listfunc(someList):\n #declare a string called cheese with the first element in spam\n cheese = spam[0]\n\n #loop to cycle through the list\n for i in range(len(spam) - 2):\n #append comma with the next element\n cheese = cheese + ', ' + spam[i + 1]\n \n #append 'and' to the second last element and add last element\n cheese = cheese + ' and ' + spam[i + 2]\n\n #return value\n return cheese\n\n\n#list i want to convert to a string\nspam = ['apples', 'banana', 'tofu', 'cats']\nresult = listfunc(spam)\nprint(result)\n\n\n" } ]
20
gustavo80br/soaring
https://github.com/gustavo80br/soaring
319da56dc0d26d8040716e53b27904e41f6f8a2d
a1e296c07669542055f771d248278a290a40886d
87744227d650a852ef641ec26d2bdd5054d60a76
refs/heads/master
2020-03-29T21:28:05.134127
2011-05-20T18:26:29
2011-05-20T18:26:29
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5149844884872437, "alphanum_fraction": 0.534757137298584, "avg_line_length": 38.33604431152344, "blob_id": "7bfa39426536a7258ba2a656da6b131a95049316", "content_id": "a277fecc9719377e29ea90a2646e7e187d126179", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14515, "license_type": "no_license", "max_line_length": 107, "num_lines": 369, "path": "/python/igc.py", "repo_name": "gustavo80br/soaring", "src_encoding": "UTF-8", "text": "import optparse\nimport urllib2\nimport sys\n\nfrom datetime import datetime, timedelta\nfrom math import sin, cos, asin, acos, atan2, fabs, sqrt, radians, degrees, pi\nfrom optparse import OptionParser\n\nfrom common import Base\n\nclass FlightBase(Base):\n \n # FAI Earth Sphere Radius\n earthRadius = 6371 \n\n def __init__(self):\n None\n\n def dms2dd(self, value):\n cardinal = value[-1]\n dd = None\n if cardinal in ('N', 'S'):\n dd = float(value[0:2]) + ( ( float(value[2:4]) + (float(value[4:7]) / 1000.0)) / 60.0 )\n else:\n dd = float(value[0:3]) + ( ( float(value[3:5]) + (float(value[5:8]) / 1000.0)) / 60.0 )\n if cardinal in ('S', 'W'):\n dd *= -1\n return dd\n\n def distance(self, p1, p2):\n return 2 * asin( \n sqrt( (sin( (p1[\"latrd\"] - p2[\"latrd\"]) / 2 ) ) ** 2 \n + cos(p1[\"latrd\"]) * cos(p2[\"latrd\"]) * ( sin( (p1[\"lonrd\"] - p2[\"lonrd\"]) / 2 ) ) ** 2\n )\n ) * self.earthRadius\n\n def bearing(self, p1, p2):\n return degrees(\n atan2( \n sin(p1[\"lonrd\"] - p2[\"lonrd\"]) * cos(p2[\"latrd\"]), \n cos(p1[\"latrd\"]) * sin(p2[\"latrd\"]) \n - sin(p1[\"latrd\"]) * cos(p2[\"latrd\"]) * cos(p1[\"lonrd\"] - p2[\"lonrd\"])\n ) % (2 * pi)\n )\n\nclass Flight(FlightBase):\n \"\"\"\n Flight metadata: \n dte (date), fxa (fix accuracy), plt (pilot), cm2 (crew 2), gty (glider type),\n gid (glider reg number), dtm (gps datum), rfw (logger firmware revision),\n rhw (logger revision number), fty (logger mfr and model), gps (gps mfr / model),\n prs (pressure sensor description), cid (competition id), ccl (glider class)\n \"\"\"\n\n STOPPED, STRAIGHT, CIRCLING = range(3)\n\n def __init__(self):\n self.metadata = {\n \"mfr\": None, \"mfrId\": None, \"mfrIdExt\": None,\n \"dte\": None, \"fxa\": None, \"plt\": None, \"cm2\": None, \"gty\": None,\n \"gid\": None, \"dtm\": None, \"rfw\": None, \"rhw\": None, \"fty\": None,\n \"gps\": None, \"prs\": None, \"cid\": None, \"ccl\": None\n }\n self.control = {\n \"minSpeed\": 50.0, \"minCircleRate\": 4, \"minCircleTime\": 45, \"minStraightTime\": 15,\n }\n self.points = []\n self.phases = []\n self.stats = {\n \"totalKms\": 0.0, \"maxAlt\": None, \"minAlt\": None, \"maxGSpeed\": None, \"minGSpeed\": None,\n }\n\n def putPoint(self, time, lat, lon, fix, pAlt, gAlt):\n p = {\n \"time\": time, \"lat\": lat, \"lon\": lon, \"fix\": fix, \"pAlt\": pAlt, \"gAlt\": gAlt,\n \"latdg\": None, \"londg\": None, \"latrd\": None, \"lonrd\": None,\n \"computeL2\": {\n \"distance\": None, \"bearing\": None, \"timeDelta\": None, \"pAltDelta\": None, \"gAltDelta\": None,\n },\n \"computeL3\": {\n \"gSpeed\": None, \"pVario\": None, \"gVario\": None, \"turnRate\": None,\n },\n \"computeL4\": {\n \"mode\": Flight.STOPPED,\n },\n }\n prevP = self.points[-1] if len(self.points) != 0 else None\n self.computeL1(p)\n if prevP is not None:\n self.computeL2(prevP, p)\n self.computeL3(prevP, p)\n self.computeStats(p)\n self.points.append(p)\n self.updateMode()\n\n def computeL1(self, p):\n p[\"latdg\"] = self.dms2dd(p[\"lat\"])\n p[\"londg\"] = self.dms2dd(p[\"lon\"])\n p[\"latrd\"] = radians(p[\"latdg\"])\n p[\"lonrd\"] = radians(p[\"londg\"])\n\n def computeL2(self, prevP, p):\n p[\"computeL2\"][\"distance\"] = self.distance(prevP, p)\n p[\"computeL2\"][\"bearing\"] = self.bearing(prevP, p)\n p[\"computeL2\"][\"timeDelta\"] = (p[\"time\"] - prevP[\"time\"]).seconds\n p[\"computeL2\"][\"pAltDelta\"] = p[\"pAlt\"] - prevP[\"pAlt\"]\n p[\"computeL2\"][\"gAltDelta\"] = p[\"gAlt\"] - prevP[\"gAlt\"]\n\n def computeL3(self, prevP, p):\n p[\"computeL3\"][\"gSpeed\"] = (p[\"computeL2\"][\"distance\"] * 3600) / p[\"computeL2\"][\"timeDelta\"]\n p[\"computeL3\"][\"pVario\"] = float(p[\"computeL2\"][\"pAltDelta\"]) / p[\"computeL2\"][\"timeDelta\"]\n p[\"computeL3\"][\"gVario\"] = float(p[\"computeL2\"][\"gAltDelta\"]) / p[\"computeL2\"][\"timeDelta\"]\n if prevP[\"computeL2\"][\"bearing\"] is not None:\n p[\"computeL3\"][\"turnRate\"] = (p[\"computeL2\"][\"bearing\"] \\\n - prevP[\"computeL2\"][\"bearing\"]) / p[\"computeL2\"][\"timeDelta\"]\n\n def computeStats(self, p):\n self.stats[\"totalKms\"] += p[\"computeL2\"][\"distance\"]\n self.stats[\"maxAlt\"] = max(self.stats[\"maxAlt\"], p[\"pAlt\"])\n self.stats[\"minAlt\"] = p[\"pAlt\"] if self.stats[\"minAlt\"] is None \\\n else min(self.stats[\"minAlt\"], p[\"pAlt\"])\n self.stats[\"maxGSpeed\"] = max(self.stats[\"maxGSpeed\"], p[\"computeL3\"][\"gSpeed\"])\n self.stats[\"minGSpeed\"] = p[\"computeL3\"][\"gSpeed\"] if self.stats[\"minGSpeed\"] is None \\\n else min(self.stats[\"minGSpeed\"], p[\"computeL3\"][\"gSpeed\"])\n\n def newPhase(self, pIndex, phaseType):\n if len(self.phases) != 0:\n self.phases[-1][\"end\"] = pIndex - 1\n self.phases.append({\"start\": pIndex, \"end\": None, \"type\": phaseType})\n # TODO: calculate phase stats?\n\n def updateMode(self):\n # First point, just set as stopped and return\n if len(self.points) == 1:\n self.points[0][\"computeL4\"][\"mode\"] = Flight.STOPPED\n return\n\n p, pI = self.points[-1], len(self.points) - 1\n p[\"computeL4\"][\"mode\"] = self.points[-2][\"computeL4\"][\"mode\"]\n # Move from stopped to straight\n if p[\"computeL4\"][\"mode\"] == Flight.STOPPED \\\n and p[\"computeL3\"][\"gSpeed\"] > self.control[\"minSpeed\"]:\n p[\"computeL4\"][\"mode\"] = Flight.STRAIGHT\n self.newPhase(pI, Flight.STRAIGHT)\n # Move from straight to circling (>= minTurnRate kept for more than minCircleTime)\n elif p[\"computeL4\"][\"mode\"] == Flight.STRAIGHT:\n curTime, j = p[\"time\"], pI-1\n while j > 0 and (p[\"time\"] - self.points[j][\"time\"]).seconds < self.control[\"minCircleTime\"]:\n if fabs(self.points[j][\"computeL3\"][\"turnRate\"]) >= self.control[\"minCircleRate\"]:\n j -= 1\n else:\n return\n for g in range(j, pI+1):\n self.points[g][\"computeL4\"][\"mode\"] = Flight.CIRCLING\n self.newPhase(pI, Flight.CIRCLING)\n # Move from circling to straight (< minTurnRate for more than minStraightTime)\n elif p[\"computeL4\"][\"mode\"] == Flight.CIRCLING:\n curTime, j = p[\"time\"], pI-1\n while j > 0 and (curTime - self.points[j][\"time\"]).seconds < self.control[\"minStraightTime\"]:\n if fabs(self.points[j][\"computeL3\"][\"turnRate\"]) < self.control[\"minCircleRate\"]:\n j -= 1\n else:\n return\n for g in range(j, pI+1):\n self.points[g][\"computeL4\"][\"mode\"] = Flight.STRAIGHT\n self.newPhase(pI, Flight.STRAIGHT)\n\n def pathInKml(self):\n pathKml = \"\"\n for point in self.points:\n pathKml += \"%.2f,%.2f,%d \" % (point[\"latdg\"], point[\"londg\"], point[\"gAlt\"])\n return \"<LineString><coordinates>%s</coordinates></LineString>\" % pathKml\n\nclass FlightFetcher(FlightBase):\n\n def __init__(self, uri):\n self.uri = uri\n self.rawContent = None\n\n def fetch(self):\n self.verbose(\"Fetching flight from : %s\" % self.uri)\n self.raw = urllib2.urlopen(self.uri).read()\n return self.raw\n\nclass FlightReader(FlightBase):\n \"\"\"\n Creates a Flight object from the data taken from the given FlightFetcher.\n \"\"\"\n\n def __init__(self, rawFlight, autoParse=True):\n self.flight = Flight()\n self.flight.rawFlight = rawFlight\n if autoParse:\n self.parse()\n\n def parse(self):\n \"\"\"\n http://carrier.csi.cam.ac.uk/forsterlewis/soaring/igc_file_format/igc_format_2008.html\n \"\"\"\n lines = self.flight.rawFlight.split(\"\\n\")\n for line in lines:\n if line != \"\":\n getattr(self, \"parse%s\" % line[0])(line.strip())\n\n def parseA(self, record):\n self.flight.metadata[\"mfr\"] = record[1:4]\n self.flight.metadata[\"mfrId\"] = record[4:7]\n self.flight.metadata[\"mfrIdExt\"] = record[7:]\n\n def parseB(self, record):\n self.flight.putPoint(datetime.strptime(record[1:7], \"%H%M%S\"), record[7:15], record[15:24],\n record[24], int(record[25:30]), int(record[30:35]))\n\n def parseC(self, record):\n None\n\n def parseF(self, record):\n None\n\n def parseG(self, record):\n None\n\n def parseH(self, record):\n hType = record[2:5].lower()\n if hType == 'dte':\n self.flight.metadata['dte'] = datetime.strptime(record[5:], \"%d%m%y\")\n elif hType == 'fxa':\n self.flight.metadata[hType] = record[5:]\n else:\n self.flight.metadata[hType] = record[record.find(':')+1:]\n\n def parseI(self, record):\n None\n\n def parseL(self, record):\n None\n\nclass FlightOptimizer(FlightBase):\n\n def __init__(self, flight):\n self.flight = flight\n self.maxCPDistance = 0 # Maximum distance between 2 consecutive points\n self.prepare()\n\n def prepare(self):\n for i in range(0, len(self.flight.points)-1):\n distance = self.distance(self.flight.points[i], self.flight.points[i+1])\n if distance > self.maxCPDistance:\n self.maxCPDistance = distance\n\n def forward(self, i, distance):\n step = int(distance / self.maxCPDistance)\n if step > 0:\n return i + step\n return i+1\n\n def optimize1(self):\n circuit = {\"sta\": None, \"tps\": None, \"end\": None, \"distance\": 0.0}\n flight, nPoints = self.flight, len(self.flight.points)\n sta, tp1, end = 0, 1, nPoints-1\n while tp1 < nPoints-1:\n distance = self.distance(flight.points[sta], flight.points[tp1]) \\\n + self.distance(flight.points[tp1], flight.points[end])\n if distance > circuit[\"distance\"]:\n circuit = {\"sta\": sta, \"tps\": [tp1], \"end\": end, \"distance\": distance}\n tp1 += 1\n print circuit\n else:\n tp1 = self.forward(tp1, 0.5 * (circuit[\"distance\"] - distance))\n return circuit\n\n def optimize2(self):\n circuit = {\"sta\": None, \"tps\": None, \"end\": None, \"distance\": 0.0}\n flight, nPoints = self.flight, len(self.flight.points)\n sta, tp1, tp2, end = 0, 1, -1, nPoints-1\n for tp1 in range(1, nPoints-2):\n leg1 = self.distance(flight.points[sta], flight.points[tp1])\n tp2 = tp1+1\n while tp2 < nPoints-1:\n distance = leg1 + self.distance(flight.points[tp1], flight.points[tp2]) \\\n + self.distance(flight.points[tp2], flight.points[end])\n if distance > circuit[\"distance\"]:\n circuit = {\"sta\": sta, \"tps\": [tp1, tp2], \"end\": end, \"distance\": distance}\n tp2 += 1\n print circuit\n else:\n tp2 = self.forward(tp2, 0.5 * (circuit[\"distance\"] - distance))\n return circuit\n\n def optimize3(self):\n circuit = {\"sta\": None, \"tps\": None, \"end\": None, \"distance\": 0.0}\n flight, nPoints = self.flight, len(self.flight.points)\n sta, tp1, tp2, tp3, end = 0, -1, -1, -1, nPoints-1\n for tp1 in range(1, nPoints-3):\n leg1 = self.distance(flight.points[sta], flight.points[tp1])\n for tp2 in range(tp1+1, nPoints-2):\n leg2 = self.distance(flight.points[tp1], flight.points[tp2])\n tp3 = tp2+1\n while tp3 < nPoints-1:\n leg3 = self.distance(flight.points[tp2], flight.points[tp3])\n distance = leg1 + leg2 + leg3 + self.distance(flight.points[tp3], flight.points[end])\n if distance > circuit[\"distance\"]:\n circuit = {\"sta\": sta, \"tps\": [tp1, tp2, tp3], \"end\": end, \"distance\": distance}\n print circuit\n tp3 += 1\n else:\n tp3 = self.forward(tp3, 0.5 *(circuit[\"distance\"] - distance))\n return circuit\n \nclass FlightExporter(FlightBase):\n\n def __init__(self, flight):\n self.flight = flight\n\n def toText(self):\n text = \"\"\"\n Date: %s\\tPilot: %s\n Registration: %s\\tType: %s\\t\\tClass: %s\n Points: %d\n \"\"\" % (self.flight.metadata[\"dte\"].strftime(\"%Y-%m-%d\"), \n self.flight.metadata[\"plt\"], self.flight.metadata[\"gid\"],\n self.flight.metadata[\"gty\"], self.flight.metadata[\"ccl\"], \n len(self.flight.points))\n kml = self.flight.pathInKml()\n print \"%s :: %d\" % (kml, len(kml))\n return text\n\n def toFusionTable(self, tableId):\n sql = \"\"\"\n INSERT INTO %s (Date, Pilot, Registration, Type, Class, Points)\n VALUES ('%s', '%s', '%s', '%s', '%s', '%s')\n \"\"\" % (tableId, self.flight.metadata[\"dte\"].strftime(\"%Y-%m-%d\"), \n self.flight.metadata[\"plt\"], self.flight.metadata[\"gid\"],\n self.flight.metadata[\"gty\"], self.flight.metadata[\"ccl\"],\n self.flight.pathInKml())\n return sql\n\nclass FlightCmdLine(object):\n\n usage = \"usage: %prog [options] args\"\n \n version = 0.1\n\n description = \"Flight parser tool\"\n\n def __init__(self):\n self.optParser = OptionParser(usage=self.usage, version=self.version,\n description=self.description)\n self.optParser.add_option(\"-v\", \"--verbose\",\n action=\"store_true\", dest=\"verbose\",\n default=False, help=\"make lots of noise\")\n\n (self.options, self.args) = self.optParser.parse_args()\n \n if len(self.args) != 1:\n self.optParser.error(\"Wrong number of arguments given\")\n\n verbose = self.options.verbose \n\n def run(self):\n flightFetcher = FlightFetcher(self.args[0])\n flightReader = FlightReader(flightFetcher)\n print FlightExporter(flightReader.flight).export()\n flightOpt = FlightOptimizer(flightReader.flight)\n circuit = flightOpt.optimize3()\n\nif __name__ == \"__main__\":\n flightCmd = FlightCmdLine()\n sys.exit(flightCmd.run())\n" }, { "alpha_fraction": 0.6442348957061768, "alphanum_fraction": 0.6506643891334534, "avg_line_length": 34.34848403930664, "blob_id": "3b8b941fee74aaf738a03353736c5f2769c65b3a", "content_id": "a1286ae5912bd98ff0829fc2737996b05bf7248f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2333, "license_type": "no_license", "max_line_length": 108, "num_lines": 66, "path": "/python/crawler.py", "repo_name": "gustavo80br/soaring", "src_encoding": "UTF-8", "text": "import logging\nimport urllib\nimport urllib2\n\nfrom google.appengine.api.taskqueue import Task\nfrom google.appengine.ext.webapp import RequestHandler, WSGIApplication\nfrom google.appengine.ext.webapp.util import run_wsgi_app\n\nimport appdata\nfrom igc import FlightReader, FlightExporter, FlightFetcher\n\nclass CommonHandler(RequestHandler):\n\n gAuthUri = \"https://www.google.com/accounts/ClientLogin\"\n\n fusionTablesUri = \"http://www.google.com/fusiontables/api/query\"\n\n def __init__(self):\n None\n\n def gAuth(self, username, password, service, accountType):\n authData = urllib.urlencode(\n {\"Email\": username, \"Passwd\": password, \"service\": service, \n \"accountType\": accountType})\n authReq = urllib2.Request(self.gAuthUri, data=authData)\n authResp = urllib2.urlopen(authReq).read()\n authDict = dict(x.split(\"=\") for x in authResp.split(\"\\n\") if x)\n return authDict[\"Auth\"]\n\nclass NetcoupeHandler(CommonHandler):\n\n def get(self):\n logging.info(\"NetcoupeHandler: started\")\n url = \"http://netcoupe.net/Download/DownloadIGC.aspx?FileID=7347\"\n task = Task(url=\"/crawler/netcoupe/worker\", params={\"url\": url})\n task.add(\"flightprocess\")\n\nclass NetcoupeWorker(CommonHandler):\n\n def __init__(self):\n self.authToken = None\n\n def post(self):\n url = self.request.get('url')\n logging.info(\"NetcoupeWorker: processing flight :: url=%s\" % url)\n if self.authToken is None:\n self.authToken = self.gAuth(\"rocha.porto\", appdata.password, \"fusiontables\", \"HOSTED_OR_GOOGLE\")\n reader = FlightReader( FlightFetcher(url).fetch() )\n exporter = FlightExporter(reader.flight)\n req = urllib2.Request(self.fusionTablesUri,\n urllib.urlencode({\"sql\": exporter.toFusionTable(872803)}),\n {\"Authorization\": \"GoogleLogin auth=%s\" % self.authToken,\n \"Content-Type\": \"application/x-www-form-urlencoded\"})\n resp = urllib2.urlopen(req)\n print resp\n\ndef main():\n app = WSGIApplication([\n ('/crawler/netcoupe', NetcoupeHandler),\n ('/crawler/netcoupe/worker', NetcoupeWorker),\n ], debug=True)\n logging.getLogger().setLevel(logging.DEBUG)\n run_wsgi_app(app)\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.49668508768081665, "alphanum_fraction": 0.515055239200592, "avg_line_length": 32.51388931274414, "blob_id": "0662ab876175fc4d144a49bf9156b2ea77f4cacd", "content_id": "cea3976495038d004281d450de545b96bf5cba6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 7240, "license_type": "no_license", "max_line_length": 112, "num_lines": 216, "path": "/js/igc.js", "repo_name": "gustavo80br/soaring", "src_encoding": "UTF-8", "text": "window.opensoaring = window.opensoaring || {};\nopensoaring.igc = opensoaring.igc || {\n/**\n * Flight object.\n */\nFlight: function(url, autoload) {\n this.url = url;\n this.raw = null;\n this.data = null;\n\n this.load = function() {\n opensoaring.igc.Util.loadFlight(this);\n }\n\n this.toString = function() {\n return JSON.stringify(this.data, null, 4);\n }\n\n if (autoload) this.load();\n},\n\n/**\n * FlightData object.\n */\nFlightData: function() {\n this.manufacturer = null;\n this.header = { \"FXA\": null, \"DTE\": null, \"PLT\": null, \"CM2\": null, \"GTY\": null, \"GID\": null, \n \"DTM\": null, \"RFW\": null, \"RHW\": null, \"FTY\": null, \"GPS\": null, \"PRS\": null,\n \"CID\": null, \"CCL\": null };\n this.points = [];\n\n this.toString = function() {\n return JSON.stringify(this);\n }\n},\n\nGFlight: function(aFlight) {\n flight = aFlight;\n polyline = null;\n polyoptions = {strokeColor: \"#FF0000\", strokeOpacity: 0.6, strokeWeight: 3};\n bounds = null;\n chartData = null;\n marker = null;\n\n this.getPolyline = function() {\n if (polyline == null) {\n var path = [];\n bounds = new google.maps.LatLngBounds();\n for (n in flight.data.points) {\n var point = flight.data.points[n];\n path.push(new google.maps.LatLng(point[\"lat\"], point[\"lon\"]));\n bounds.extend(path[path.length-1]);\n }\n polyoptions[\"path\"] = path;\n polyline = new google.maps.Polyline(polyoptions);\n }\n return polyline;\n }\n\n this.getBounds = function () {\n if (polyline == null)\n polyline = this.getPolyline();\n return bounds;\n }\n\n this.getChart = function() {\n if (chartData == null) {\n chartData = { \"values\": [], \"labels\": [\"Time\", \"Altitude\"] };\n for (n in flight.data.points) {\n var point = flight.data.points[n];\n chartData[\"values\"].push([point[\"time\"], point[\"galt\"]]);\n }\n }\n return chartData;\n }\n\n this.getMarker = function() {\n if (marker == null)\n marker = new google.maps.Marker({position: this.getPolyline().getPath().getAt(0)});\n alert(marker);\n return marker;\n }\n\n this.setPosition = function(event, x, points, row) {\n marker.setPosition(this.getPolyline().getPath().getAt(10));\n }\n},\n\n/**\n *\n */\nParser: {\n /**\n * Parses a string containing a track in IGC format.\n *\n * Nice read:\n * http://carrier.csi.cam.ac.uk/forsterlewis/soaring/igc_file_format/igc_format_2008.html\n */\n parse: function(data) {\n var flightData = new opensoaring.igc.FlightData();\n var records = data.split(\"\\r\\n\");\n for (n in records) {\n var record = records[n];\n switch (record[0]) { // Record type is stored in the first char\n case 'A':\n flightData.manufacturer = record.substring(1, 4);\n break;\n case 'H':\n var type = record.substring(2, 5);\n var value = record.substring(Math.max(5, record.indexOf(':')+1));\n switch (type) {\n case \"DTE\":\n flightData.header[\"DTE\"] = \n new Date(20+value.substring(4), (value.substring(2,4)-1), value.substring(0,2));\n break;\n case \"FXA\":\n flightData.header[\"FXA\"] = parseInt(value);\n default:\n flightData.header[type] = value;\n }\n break;\n case 'B':\n flightData.points.push({\n \"time\": new Date(\n flightData.header[\"DTE\"].getTime() + (record.substring(1,3) * 3600000) +\n (record.substring(3,5) * 60000) + parseInt(record.substring(5,7)*1000)),\n \"lat\": opensoaring.igc.Util.dms2dd(record.substring(7,15)),\n \"lon\": opensoaring.igc.Util.dms2dd(record.substring(15,24)),\n \"val\": record[24],\n \"palt\": record.substring(25,30),\n \"galt\": parseFloat(record.substring(30,35)),\n });\n break;\n }\n }\n return flightData;\n },\n},\n\n/**\n * Util object.\n */\nUtil: {\n /**\n * Loads the data of a flight from the url stored inside the object.\n */\n loadFlight: function(flight) {\n try {\n var xmlhttp = new XMLHttpRequest();\n } catch(e) {\n return;\n }\n xmlhttp.open(\"GET\", flight.url, false);\n xmlhttp.onreadystatechange = function() {\n if (xmlhttp.readyState==4) {\n flight.raw = xmlhttp.responseText;\n flight.data = opensoaring.igc.Parser.parse(flight.raw); \n }\n }\n xmlhttp.send(null);\n },\n /**\n * Returns the given coordinate passed in DMS format in decimal degrees.\n */\n dms2dd: function(value) {\n var cardinal = value[value.length-1];\n var dd = null; // decimal degrees\n if (cardinal == 'N' || cardinal == 'S')\n dd = (parseFloat(value.substring(0,2))) \n + ( (parseFloat(value.substring(2,4)) + (parseFloat(value.substring(4,7)) / 1000.0)) / 60.0 );\n else\n dd = (parseFloat(value.substring(0,3)))\n + ( (parseFloat(value.substring(3,5)) + (parseFloat(value.substring(5,8)) / 1000.0)) / 60.0 );\n if (cardinal == 'S' || cardinal == 'W') \n dd = dd * -1;\n return dd;\n },\n}\n\n};\n\nfunction init() {\n var latlng = new google.maps.LatLng(-34.397, 150.644);\n var myOptions = { \n zoom: 10,\n center: latlng,\n mapTypeControl: false,\n mapTypeControlOptions: {\n style: google.maps.MapTypeControlStyle.DEFAULT,\n mapTypeIds: [google.maps.MapTypeId.TERRAIN, \"earth\"],\n },\n navigationControl: true,\n navigationControlOptions: {\n style: google.maps.NavigationControlStyle.DEFAULT,\n },\n scaleControl: true,\n scaleControlOptions: {\n style: google.maps.ScaleControlStyle.DEFAULT,\n },\n scaleControl: true,\n mapTypeId: google.maps.MapTypeId.TERRAIN,\n };\n var map = new google.maps.Map(document.getElementById(\"mapCanvas\"), myOptions);\n var flight = new opensoaring.igc.Flight(\"test.igc\", true);\n var gflight = new opensoaring.igc.GFlight(flight);\n gflight.getPolyline().setMap(map);\n gflight.getMarker().setMap(map);\n var chartData = gflight.getChart();\n var chart = new Dygraph(document.getElementById(\"mapChart\"), chartData[\"values\"], \n {\nfillGraph: true, colors: ['#0000FF'], \n strokeWidth: 1, yAxisLabelWidth: 30, axisLabelFontSize: 12, gridLineColor: \"gray\",\n width: \"100%\", height: \"100%\", highlightCallback: gflight.setPosition,\n });\n map.fitBounds(gflight.getBounds());\n}\n\n" }, { "alpha_fraction": 0.511143684387207, "alphanum_fraction": 0.5358862280845642, "avg_line_length": 31.332988739013672, "blob_id": "6cdc80b4534dad2542dcd2bb82a71dfbd72ea1a8", "content_id": "ab54343f45d0c73842cf14aaa916a85dfb72233d", "detected_licenses": [], "is_generated": false, "is_vendor": true, "language": "C", "length_bytes": 31363, "license_type": "no_license", "max_line_length": 169, "num_lines": 970, "path": "/externals/track.c", "repo_name": "gustavo80br/soaring", "src_encoding": "UTF-8", "text": "/*\n\n maxxc - maximise cross country flights\n Copyright (C) 2008 Tom Payne\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see <http://www.gnu.org/licenses/>.\n\n*/\n\n#include <errno.h>\n#include <math.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"maxxc.h\"\n\n void\ntrkpt_to_wpt(const trkpt_t *trkpt, wpt_t *wpt)\n{\n wpt->lat = trkpt->lat;\n wpt->lon = trkpt->lon;\n wpt->time = trkpt->time;\n wpt->ele = trkpt->ele;\n wpt->name = 0;\n wpt->val = trkpt->val;\n}\n\n__attribute__ ((nonnull(1, 2))) __attribute__ ((pure))\n static inline double\ncoord_delta(const coord_t *coord1, const coord_t *coord2)\n{\n double x = coord1->sin_lat * coord2->sin_lat + coord1->cos_lat * coord2->cos_lat * cos(coord1->lon - coord2->lon);\n return x < 1.0 ? acos(x) : 0.0;\n\n}\n\n__attribute__ ((nonnull(1))) __attribute__ ((pure))\n static inline double\ntrack_delta(const track_t *track, int i, int j)\n{\n return coord_delta(track->coords + i, track->coords + j);\n}\n\n__attribute__ ((nonnull(1))) __attribute__ ((pure))\n static inline int\ntrack_forward(const track_t *track, int i, double d)\n{\n int step = (int) (d / track->max_delta);\n return step > 0 ? i + step : ++i;\n}\n\n__attribute__ ((nonnull(1))) __attribute__ ((pure))\n static inline int\ntrack_fast_forward(const track_t *track, int i, double d)\n{\n double target = track->sigma_delta[i] + d;\n i = track_forward(track, i, d);\n if (i >= track->ntrkpts)\n return i;\n while (1) {\n double error = target - track->sigma_delta[i];\n if (error <= 0.0)\n return i;\n i = track_forward(track, i, error);\n if (i >= track->ntrkpts)\n return i;\n }\n}\n\n__attribute__ ((nonnull(1))) __attribute__ ((pure))\n static inline int\ntrack_backward(const track_t *track, int i, double d)\n{\n int step = (int) (d / track->max_delta);\n return step > 0 ? i - step : --i;\n}\n\n__attribute__ ((nonnull(1))) __attribute__ ((pure))\n static inline int\ntrack_fast_backward(const track_t *track, int i, double d)\n{\n double target = track->sigma_delta[i] - d;\n i = track_backward(track, i, d);\n if (i < 0)\n return i;\n while (1) {\n double error = track->sigma_delta[i] - target;\n if (error <= 0.0)\n return i;\n i = track_backward(track, i, error);\n if (i < 0)\n return i;\n }\n}\n\n__attribute__ ((nonnull(1))) __attribute__ ((pure))\n static inline int\ntrack_furthest_from(const track_t *track, int i, int begin, int end, double bound, double *out)\n{\n int result = -1;\n for (int j = begin; j < end; ) {\n double d = track_delta(track, i, j);\n if (d > bound) {\n bound = *out = d;\n result = j;\n ++j;\n } else {\n j = track_fast_forward(track, j, bound - d);\n }\n }\n return result;\n}\n\n__attribute__ ((nonnull(1))) __attribute__ ((pure))\n static inline int\ntrack_nearest_to(const track_t *track, int i, int begin, int end, double bound, double *out)\n{\n int result = -1;\n for (int j = begin; j < end; ) {\n double d = track_delta(track, i, j);\n if (d < bound) {\n result = j;\n bound = *out = d;\n ++j;\n } else {\n j = track_fast_forward(track, j, d - bound);\n }\n }\n return result;\n}\n\n static inline int\n__attribute__ ((nonnull(1))) __attribute__ ((pure))\ntrack_furthest_from2(const track_t *track, int i, int j, int begin, int end, double bound, double *out)\n{\n int result = -1;\n for (int k = begin; k < end; ) {\n double d = track_delta(track, i, k) + track_delta(track, k, j);\n if (d > bound) {\n result = k;\n bound = *out = d;\n ++k;\n } else {\n k = track_fast_forward(track, k, (bound - d) / 2.0);\n }\n }\n return result;\n}\n\n static inline int\n__attribute__ ((nonnull(1))) __attribute__ ((pure))\ntrack_first_at_least(const track_t *track, int i, int begin, int end, double bound)\n{\n for (int j = begin; j < end; ) {\n double d = track_delta(track, i, j);\n if (d > bound)\n return j;\n j = track_fast_forward(track, j, bound - d);\n }\n return -1;\n}\n\n__attribute__ ((nonnull(1))) __attribute__ ((pure))\n static inline int\ntrack_last_at_least(const track_t *track, int i, int begin, int end, double bound)\n{\n for (int j = end - 1; j >= begin; ) {\n double d = track_delta(track, i, j);\n if (d > bound)\n return j;\n j = track_fast_backward(track, j, bound - d);\n }\n return -1;\n}\n\n__attribute__ ((nonnull(1, 2))) __attribute__ ((pure))\n static inline int\ntrack_first_inside(const track_t *track, const coord_t *coord, double radius, int begin, int end)\n{\n for (int i = begin; i < end; ) {\n\tdouble d = coord_delta(coord, track->coords + i);\n\tif (d <= radius)\n\t return i;\n\ti = track_forward(track, i, d - radius);\n }\n return -1;\n}\n\n__attribute__ ((nonnull(1, 2))) __attribute__ ((pure))\n static inline int\ntrack_first_outside(const track_t *track, const coord_t *coord, double radius, int begin, int end)\n{\n for (int i = begin; i < end; ) {\n\tdouble d = coord_delta(coord, track->coords + i);\n\tif (d > radius)\n\t return i;\n\ti = track_forward(track, i, d - radius);\n }\n return -1;\n}\n\n static void\ntrack_initialize(track_t *track)\n{\n track->coords = alloc(track->ntrkpts * sizeof(coord_t));\n#pragma omp parallel for schedule(static)\n for (int i = 0; i < track->ntrkpts; ++i) {\n double lat = M_PI * track->trkpts[i].lat / (180 * 60000);\n double lon = M_PI * track->trkpts[i].lon / (180 * 60000);\n track->coords[i].sin_lat = sin(lat);\n track->coords[i].cos_lat = cos(lat);\n track->coords[i].lon = lon;\n }\n track->max_delta = 0.0;\n track->sigma_delta = alloc(track->ntrkpts * sizeof(double));\n track->sigma_delta[0] = 0.0;\n for (int i = 1; i < track->ntrkpts; ++i) {\n double delta = track_delta(track, i - 1, i);\n track->sigma_delta[i] = track->sigma_delta[i - 1] + delta;\n if (delta > track->max_delta)\n track->max_delta = delta;\n }\n#pragma omp parallel sections\n {\n#pragma omp section\n {\n#pragma omp critical\n track->before = alloc(track->ntrkpts * sizeof(limit_t));\n track->before[0].index = 0;\n track->before[0].distance = 0.0;\n for (int i = 1; i < track->ntrkpts; ++i)\n track->before[i].index = track_furthest_from(track, i, 0, i, track->before[i - 1].distance - track->max_delta, &track->before[i].distance);\n }\n#pragma omp section\n {\n#pragma omp critical\n track->after = alloc(track->ntrkpts * sizeof(limit_t));\n track->after[0].index = track_furthest_from(track, 0, 1, track->ntrkpts, 0.0, &track->after[0].distance);\n for (int i = 1; i < track->ntrkpts - 1; ++i)\n track->after[i].index = track_furthest_from(track, i, i + 1, track->ntrkpts, track->after[i - 1].distance - track->max_delta, &track->after[i].distance);\n track->after[track->ntrkpts - 1].index = track->ntrkpts - 1;\n track->after[track->ntrkpts - 1].distance = 0.0;\n }\n }\n}\n\n void\ntrack_compute_circuit_tables(track_t *track, double circuit_bound)\n{\n track->last_finish = alloc(track->ntrkpts * sizeof(int));\n track->best_start = alloc(track->ntrkpts * sizeof(int));\n int current_best_start = 0, i, j;\n for (i = 0; i < track->ntrkpts; ++i) {\n for (j = track->ntrkpts - 1; j >= i; ) {\n double error = track_delta(track, i, j);\n if (error < circuit_bound) {\n track->last_finish[i] = j;\n break;\n } else {\n j = track_fast_backward(track, j, error - circuit_bound);\n }\n }\n if (track->last_finish[i] > track->last_finish[current_best_start])\n current_best_start = i;\n if (track->last_finish[current_best_start] < i) {\n current_best_start = 0;\n for (j = 1; j <= i; ++j)\n if (track->last_finish[j] > track->last_finish[current_best_start])\n current_best_start = j;\n }\n track->best_start[i] = current_best_start;\n }\n}\n\n static inline const char *\nmatch_char(const char *p, char c)\n{\n if (!p) return 0;\n return *p == c ? ++p : 0;\n}\n\n static inline const char *\nmatch_string(const char *p, const char *s)\n{\n if (!p) return 0;\n while (*p && *s && *p == *s) {\n ++p;\n ++s;\n }\n return *s ? 0 : p;\n}\n\n static inline const char *\nmatch_unsigned(const char *p, int n, int *result)\n{\n if (!p) return 0;\n *result = 0;\n for (; n > 0; --n) {\n if ('0' <= *p && *p <= '9') {\n *result = 10 * *result + *p - '0';\n ++p;\n } else {\n return 0;\n }\n }\n return p;\n}\n\n static inline const char *\nmatch_one_of(const char *p, const char *s, char *result)\n{\n if (!p) return 0;\n for (; *s; ++s)\n if (*p == *s) {\n *result = *p;\n return ++p;\n }\n return 0;\n}\n\n static inline const char *\nmatch_capture_until(const char *p, char c, char **result)\n{\n if (!p) return 0;\n const char *start = p;\n while (*p && *p != c)\n ++p;\n if (!p) return 0;\n *result = alloc(p - start + 1);\n memcpy(*result, start, p - start);\n (*result)[p - start] = '\\0';\n return p;\n}\n\n static inline const char *\nmatch_until_eol(const char *p)\n{\n if (!p) return 0;\n while (*p && *p != '\\r')\n ++p;\n if (*p != '\\r') return 0;\n ++p;\n return *p == '\\n' ? ++p : 0;\n}\n\n static const char *\nmatch_b_record(const char *p, struct tm *tm, trkpt_t *trkpt)\n{\n p = match_char(p, 'B');\n if (!p) return 0;\n\n int hour = 0, min = 0, sec = 0;\n p = match_unsigned(p, 2, &hour);\n p = match_unsigned(p, 2, &min);\n p = match_unsigned(p, 2, &sec);\n if (!p) return 0;\n\n int lat_deg = 0, lat_mmin = 0;\n char lat_hemi = 0;\n p = match_unsigned(p, 2, &lat_deg);\n p = match_unsigned(p, 5, &lat_mmin);\n p = match_one_of(p, \"NS\", &lat_hemi);\n int lat = 60000 * lat_deg + lat_mmin;\n if (lat_hemi == 'S') lat *= -1;\n\n int lon_deg = 0, lon_mmin = 0;\n char lon_hemi = 0;\n p = match_unsigned(p, 3, &lon_deg);\n p = match_unsigned(p, 5, &lon_mmin);\n p = match_one_of(p, \"EW\", &lon_hemi);\n int lon = 60000 * lon_deg + lon_mmin;\n if (lon_hemi == 'W') lon *= -1;\n\n char val = 0;\n p = match_one_of(p, \"AV\", &val);\n\n int alt = 0, ele = 0;\n p = match_unsigned(p, 5, &alt);\n p = match_unsigned(p, 5, &ele);\n\n p = match_until_eol(p);\n if (!p) return 0;\n\n tm->tm_hour = hour;\n tm->tm_min = min;\n tm->tm_sec = sec;\n time_t time;\n time = mktime(tm);\n if (time == (time_t) -1)\n DIE(\"mktime\", errno);\n trkpt->time = time;\n trkpt->lat = lat;\n trkpt->lon = lon;\n trkpt->val = val;\n trkpt->alt = alt;\n trkpt->ele = ele;\n\n return p;\n}\n\n static const char *\nmatch_c_record(const char *p, wpt_t *wpt)\n{\n p = match_char(p, 'C');\n if (!p) return 0;\n\n int lat_deg = 0, lat_mmin = 0;\n char lat_hemi = 0;\n p = match_unsigned(p, 2, &lat_deg);\n p = match_unsigned(p, 5, &lat_mmin);\n p = match_one_of(p, \"NS\", &lat_hemi);\n int lat = 60000 * lat_deg + lat_mmin;\n if (lat_hemi == 'S') lat *= -1;\n\n int lon_deg = 0, lon_mmin = 0;\n char lon_hemi = 0;\n p = match_unsigned(p, 3, &lon_deg);\n p = match_unsigned(p, 5, &lon_mmin);\n p = match_one_of(p, \"EW\", &lon_hemi);\n int lon = 60000 * lon_deg + lon_mmin;\n if (lon_hemi == 'W') lon *= -1;\n\n char *name = 0;\n p = match_capture_until(p, '\\r', &name);\n\n p = match_until_eol(p);\n if (!p) return 0;\n\n wpt->time = (time_t) -1;\n wpt->lat = lat;\n wpt->lon = lon;\n wpt->val = 'V';\n wpt->ele = 0;\n wpt->name = name;\n\n return p;\n}\n\n static const char *\nmatch_hfdte_record(const char *p, struct tm *tm)\n{\n int mday = 0, mon = 0, year = 0;\n p = match_string(p, \"HFDTE\");\n if (!p) return 0;\n p = match_unsigned(p, 2, &mday);\n p = match_unsigned(p, 2, &mon);\n p = match_unsigned(p, 2, &year);\n p = match_string(p, \"\\r\\n\");\n if (!p) return 0;\n tm->tm_year = year + 2000 - 1900;\n tm->tm_mon = mon - 1;\n tm->tm_mday = mday;\n return p;\n}\n\n static void\ntrack_push_trkpt(track_t *track, const trkpt_t *trkpt)\n{\n if (track->ntrkpts == track->trkpts_capacity) {\n track->trkpts_capacity = track->trkpts_capacity ? 2 * track->trkpts_capacity : 16384;\n track->trkpts = realloc(track->trkpts, track->trkpts_capacity * sizeof(trkpt_t));\n if (!track->trkpts)\n DIE(\"realloc\", errno);\n }\n track->trkpts[track->ntrkpts] = *trkpt;\n ++track->ntrkpts;\n}\n\n static void\ntrack_push_task_wpt(track_t *track, const wpt_t *task_wpt)\n{\n if (track->ntask_wpts == track->task_wpts_capacity) {\n track->task_wpts_capacity = track->task_wpts_capacity ? 2 * track->task_wpts_capacity : 16;\n track->task_wpts = realloc(track->task_wpts, track->task_wpts_capacity * sizeof(wpt_t));\n if (!track->task_wpts)\n DIE(\"realloc\", errno);\n }\n track->task_wpts[track->ntask_wpts] = *task_wpt;\n ++track->ntask_wpts;\n}\n\n track_t *\ntrack_new_from_igc(const char *filename, FILE *file)\n{\n track_t *track = alloc(sizeof(track_t));\n track->filename = filename;\n\n struct tm tm;\n memset(&tm, 0, sizeof tm);\n trkpt_t trkpt;\n memset(&trkpt, 0, sizeof trkpt);\n wpt_t wpt;\n memset(&wpt, 0, sizeof wpt);\n char record[1024];\n while (fgets(record, sizeof record, file)) {\n int n = strlen(record);\n if (track->igc_size + n > track->igc_capacity) {\n track->igc_capacity = track->igc_capacity ? 2 * track->igc_capacity : 131072;\n track->igc = realloc(track->igc, track->igc_capacity);\n if (!track->igc)\n DIE(\"realloc\", errno);\n }\n memcpy(track->igc + track->igc_size, record, n);\n track->igc_size += n;\n switch (record[0]) {\n case 'B':\n if (match_b_record(record, &tm, &trkpt))\n track_push_trkpt(track, &trkpt);\n break;\n case 'C':\n if (match_c_record(record, &wpt))\n track_push_task_wpt(track, &wpt);\n break;\n case 'H':\n match_hfdte_record(record, &tm);\n break;\n }\n }\n track_initialize(track);\n return track;\n}\n\n void\ntrack_delete(track_t *track)\n{\n if (track) {\n free(track->trkpts);\n if (track->task_wpts) {\n for (int i = 0; i < track->ntask_wpts; ++i)\n free(track->task_wpts[i].name);\n free(track->task_wpts);\n }\n free(track->coords);\n free(track->sigma_delta);\n free(track->before);\n free(track->after);\n free(track->best_start);\n free(track->last_finish);\n free(track->igc);\n free(track);\n }\n}\n\n static double\ntrack_open_distance(const track_t *track, double bound, int *indexes)\n{\n indexes[0] = indexes[1] = -1;\n for (int start = 0; start < track->ntrkpts - 1; ++start) {\n int finish = track_furthest_from(track, start, start + 1, track->ntrkpts, bound, &bound);\n if (finish != -1) {\n indexes[0] = start;\n indexes[1] = finish;\n }\n }\n return bound;\n}\n\n static double\ntrack_open_distance1(const track_t *track, double bound, int *indexes)\n{\n indexes[0] = indexes[1] = indexes[2] = -1;\n for (int tp1 = 1; tp1 < track->ntrkpts - 1; ) {\n double total = track->before[tp1].distance + track->after[tp1].distance;\n if (total > bound) {\n indexes[0] = track->before[tp1].index;\n indexes[1] = tp1;\n indexes[2] = track->after[tp1].index;\n bound = total;\n ++tp1;\n } else {\n tp1 = track_fast_forward(track, tp1, 0.5 * (bound - total));\n }\n }\n return bound;\n}\n\n static double\ntrack_open_distance2(const track_t *track, double bound, int *indexes)\n{\n indexes[0] = indexes[1] = indexes[2] = indexes[3] = -1;\n#pragma omp parallel for schedule(dynamic)\n for (int tp1 = 1; tp1 < track->ntrkpts - 2; ++tp1) {\n double leg1 = track->before[tp1].distance;\n for (int tp2 = tp1 + 1; tp2 < track->ntrkpts - 1; ) {\n double distance = leg1 + track_delta(track, tp1, tp2) + track->after[tp2].distance;\n int new_bound = 0;\n#pragma omp critical\n if (distance > bound) {\n new_bound = 1;\n bound = distance;\n indexes[0] = track->before[tp1].index;\n indexes[1] = tp1;\n indexes[2] = tp2;\n indexes[3] = track->after[tp2].index;\n }\n if (new_bound)\n ++tp2;\n else\n tp2 = track_fast_forward(track, tp2, 0.5 * (bound - distance));\n }\n }\n return bound;\n}\n\n static double\ntrack_open_distance3(const track_t *track, double bound, int *indexes)\n{\n indexes[0] = indexes[1] = indexes[2] = indexes[3] = indexes[4] = -1;\n#pragma omp parallel for schedule(dynamic)\n for (int tp1 = 1; tp1 < track->ntrkpts - 3; ++tp1) {\n double leg1 = track->before[tp1].distance;\n for (int tp2 = tp1 + 1; tp2 < track->ntrkpts - 2; ++tp2) {\n double leg2 = track_delta(track, tp1, tp2);\n for (int tp3 = tp2 + 1; tp3 < track->ntrkpts - 1; ) {\n double distance = leg1 + leg2 + track_delta(track, tp2, tp3) + track->after[tp3].distance;\n int new_bound = 0;\n#pragma omp critical\n if (distance > bound) {\n new_bound = 1;\n bound = distance;\n indexes[0] = track->before[tp1].index;\n indexes[1] = tp1;\n indexes[2] = tp2;\n indexes[3] = tp3;\n indexes[4] = track->after[tp3].index;\n }\n if (new_bound)\n ++tp3;\n else\n tp3 = track_fast_forward(track, tp3, 0.5 * (bound - distance));\n }\n }\n }\n return bound;\n}\n\n static double\ntrack_frcfd_aller_retour(const track_t *track, double bound, int *indexes)\n{\n bound /= 2.0;\n indexes[0] = indexes[1] = indexes[2] = indexes[3] = -1;\n#pragma omp parallel for schedule(dynamic)\n for (int tp1 = 0; tp1 < track->ntrkpts - 2; ++tp1) {\n int start = track->best_start[tp1];\n int finish = track->last_finish[start];\n if (finish < 0)\n continue;\n double distance = 0.0;\n double local_bound;\n#pragma omp critical\n local_bound = bound;\n int tp2 = track_furthest_from(track, tp1, tp1 + 1, finish + 1, local_bound, &distance);\n if (tp2 >= 0) {\n#pragma omp critical\n if (distance > bound) {\n bound = distance;\n indexes[0] = start;\n indexes[1] = tp1;\n indexes[2] = tp2;\n indexes[3] = finish;\n }\n }\n }\n return 2.0 * bound;\n}\n\n static double\ntrack_frcfd_triangle_fai(const track_t *track, double bound, int *indexes)\n{\n indexes[0] = indexes[1] = indexes[2] = indexes[3] = indexes[4] = -1;\n double legbound = 0.28 * bound;\n int tp1;\n for (tp1 = 0; tp1 < track->ntrkpts - 2; ++tp1) {\n int start = track->best_start[tp1];\n int finish = track->last_finish[start];\n if (finish < 0)\n continue;\n int tp3first = track_first_at_least(track, tp1, tp1 + 2, finish + 1, legbound);\n if (tp3first < 0)\n continue;\n int tp3last = track_last_at_least(track, tp1, tp3first, finish + 1, legbound);\n if (tp3last < 0)\n continue;\n int tp3;\n for (tp3 = tp3last; tp3 >= tp3first; ) {\n double leg3 = track_delta(track, tp3, tp1);\n if (leg3 < legbound) {\n tp3 = track_fast_backward(track, tp3, legbound - leg3);\n continue;\n }\n double shortestlegbound = 0.28 * leg3 / 0.44;\n int tp2first = track_first_at_least(track, tp1, tp1 + 1, tp3 - 1, shortestlegbound);\n if (tp2first < 0) {\n --tp3;\n continue;\n }\n int tp2last = track_last_at_least(track, tp3, tp2first, tp3, shortestlegbound);\n if (tp2last < 0) {\n --tp3;\n continue;\n }\n double longestlegbound = 0.44 * leg3 / 0.28;\n int tp2;\n for (tp2 = tp2first; tp2 <= tp2last; ) {\n double d = 0.0;\n double leg1 = track_delta(track, tp1, tp2);\n if (leg1 < shortestlegbound)\n d = shortestlegbound - leg1;\n if (leg1 > longestlegbound && leg1 - longestlegbound > d)\n d = leg1 - longestlegbound;\n double leg2 = track_delta(track, tp2, tp3);\n if (leg2 < shortestlegbound && shortestlegbound - leg2 > d)\n d = shortestlegbound - leg2;\n if (leg2 > longestlegbound && leg2 - longestlegbound > d)\n d = leg2 - longestlegbound;\n if (d > 0.0) {\n tp2 = track_fast_forward(track, tp2, d);\n continue;\n }\n double total = leg1 + leg2 + leg3;\n double thislegbound = 0.28 * total;\n if (leg1 < thislegbound)\n d = thislegbound - leg1;\n if (leg2 < thislegbound && thislegbound - leg2 > d)\n d = thislegbound - leg2;\n if (leg3 < thislegbound && thislegbound - leg3 > d)\n d = thislegbound - leg3;\n if (d > 0.0) {\n tp2 = track_fast_forward(track, tp2, 0.5 * d);\n continue;\n }\n if (total < bound) {\n tp2 = track_fast_forward(track, tp2, 0.5 * (bound - total));\n continue;\n }\n bound = total;\n legbound = thislegbound;\n indexes[0] = start;\n indexes[1] = tp1;\n indexes[2] = tp2;\n indexes[3] = tp3;\n indexes[4] = finish;\n ++tp2;\n }\n --tp3;\n }\n }\n return bound;\n}\n\n static double\ntrack_frcfd_triangle_plat(const track_t *track, double bound, int *indexes)\n{\n indexes[0] = indexes[1] = indexes[2] = indexes[3] = indexes[4] = -1;\n for (int tp1 = 0; tp1 < track->ntrkpts - 1; ++tp1) {\n if (track->sigma_delta[track->ntrkpts - 1] - track->sigma_delta[tp1] < bound)\n break;\n int start = track->best_start[tp1];\n int finish = track->last_finish[start];\n if (finish < 0 || track->sigma_delta[finish] - track->sigma_delta[tp1] < bound)\n continue;\n for (int tp3 = finish; tp3 > tp1 + 1; --tp3) {\n double leg31 = track_delta(track, tp3, tp1);\n double bound123 = bound - leg31;\n double legs123 = 0.0;\n int tp2 = track_furthest_from2(track, tp1, tp3, tp1 + 1, tp3, bound123, &legs123);\n if (tp2 > 0) {\n bound = leg31 + legs123;\n indexes[0] = start;\n indexes[1] = tp1;\n indexes[2] = tp2;\n indexes[3] = tp3;\n indexes[4] = finish;\n }\n }\n }\n return bound;\n}\n\n static double\ntrack_frcfd_circuit_distance(const track_t *track, int n, int *indexes)\n{\n double distance = track_delta(track, indexes[n - 2], indexes[1]);\n for (int i = 1; i < n - 2; ++i)\n distance += track_delta(track, indexes[i], indexes[i + 1]);\n return R * distance;\n}\n\n result_t *\ntrack_optimize_frcfd(track_t *track, int complexity, const declaration_t *declaration)\n{\n static const char *league = \"Coupe F\\303\\251d\\303\\251rale de Distance (France)\";\n result_t *result = result_new();\n\n int indexes[6];\n double bound;\n\n bound = track_open_distance(track, 0.0, indexes);\n if (indexes[0] != -1) {\n route_t *route = result_push_new_route(result, league, \"distance libre sans point de contournement\", R * bound, 1.0, 0, 0);\n const char *names[] = { \"BD\", \"BA\" };\n route_push_trkpts(route, track->trkpts, 2, indexes, names);\n }\n\n if (complexity != -1 && complexity < 1)\n return result;\n\n bound = track_open_distance1(track, bound, indexes);\n if (indexes[0] != -1) {\n route_t *route = result_push_new_route(result, league, \"distance libre avec un point de contournement\", R * bound, 1.0, 0, 0);\n const char *names[] = { \"BD\", \"B1\", \"BA\" };\n route_push_trkpts(route, track->trkpts, 3, indexes, names);\n }\n\n if (complexity != -1 && complexity < 2)\n return result;\n\n bound = track_open_distance2(track, bound, indexes);\n if (indexes[0] != -1) {\n route_t *route = result_push_new_route(result, league, \"distance libre avec deux points de contournement\", R * bound, 1.0, 0, 0);\n const char *names[] = { \"BD\", \"B1\", \"B2\", \"BA\" };\n route_push_trkpts(route, track->trkpts, 4, indexes, names);\n }\n\n track_compute_circuit_tables(track, 3.0 / R);\n\n bound = track_frcfd_aller_retour(track, 15.0 / R, indexes);\n if (indexes[0] != -1) {\n double distance = track_frcfd_circuit_distance(track, 4, indexes);\n route_t *route = result_push_new_route(result, league, \"parcours en aller-retour\", distance, 1.2, 1, 0);\n static const char *names[] = { \"BD\", \"B1\", \"B2\", \"BA\" };\n route_push_trkpts(route, track->trkpts, 4, indexes, names);\n }\n\n if (complexity != -1 && complexity < 3)\n return result;\n\n bound = track_frcfd_triangle_fai(track, bound, indexes);\n if (indexes[0] != -1) {\n double distance = track_frcfd_circuit_distance(track, 5, indexes);\n route_t *route = result_push_new_route(result, league, \"triangle FAI\", distance, 1.4, 1, 0);\n static const char *names[] = { \"BD\", \"B1\", \"B2\", \"B3\", \"BA\" };\n route_push_trkpts(route, track->trkpts, 5, indexes, names);\n }\n\n bound = track_frcfd_triangle_plat(track, bound, indexes);\n if (indexes[0] != -1) {\n double distance = track_frcfd_circuit_distance(track, 5, indexes);\n route_t *route = result_push_new_route(result, league, \"triangle plat\", distance, 1.2, 1, 0);\n static const char *names[] = { \"BD\", \"B1\", \"B2\", \"B3\", \"BA\" };\n route_push_trkpts(route, track->trkpts, 5, indexes, names);\n }\n\n /* TODO track_frcfd_quadrilatere */\n\n return result;\n}\n\n result_t *\ntrack_optimize_uknxcl(track_t *track, int complexity, const declaration_t *declaration)\n{\n static const char *league = \"UK National XC League\";\n result_t *result = result_new();\n\n int indexes[6];\n double bound;\n\n bound = track_open_distance(track, 0.0, indexes);\n if (indexes[0] != -1) {\n route_t *route = result_push_new_route(result, league, \"open distance\", R * bound, 1.0, 0, 0);\n const char *names[] = { \"Start\", \"Finish\" };\n route_push_trkpts(route, track->trkpts, 2, indexes, names);\n }\n\n if (complexity != -1 && complexity < 1)\n return result;\n\n bound = track_open_distance1(track, bound, indexes);\n if (indexes[0] != -1) {\n route_t *route = result_push_new_route(result, league, \"open distance via a turnpoint\", R * bound, 1.0, 0, 0);\n const char *names[] = { \"Start\", \"TP1\", \"Finish\" };\n route_push_trkpts(route, track->trkpts, 3, indexes, names);\n }\n\n if (complexity != -1 && complexity < 2)\n return result;\n\n bound = track_open_distance2(track, bound, indexes);\n if (indexes[0] != -1) {\n route_t *route = result_push_new_route(result, league, \"open distance via two turnpoints\", R * bound, 1.0, 0, 0);\n const char *names[] = { \"Start\", \"TP1\", \"TP2\", \"Finish\" };\n route_push_trkpts(route, track->trkpts, 4, indexes, names);\n }\n\n track_compute_circuit_tables(track, 0.4 / R);\n\n bound = track_frcfd_aller_retour(track, 15.0 / R, indexes);\n if (indexes[0] != -1) {\n double distance = track_frcfd_circuit_distance(track, 4, indexes);\n route_t *route = result_push_new_route(result, league, \"out and return via a turnpoint\", distance, 2.0, 1, 0);\n static const char *names[] = { \"Start\", \"TP1\", \"TP2\", \"Finish\" };\n route_push_trkpts(route, track->trkpts, 4, indexes, names);\n }\n\n if (complexity != -1 && complexity < 3)\n return result;\n\n bound = track_frcfd_triangle_fai(track, bound, indexes);\n if (indexes[0] != -1) {\n double distance = track_frcfd_circuit_distance(track, 5, indexes);\n route_t *route = result_push_new_route(result, league, \"FAI triangle\", distance, 2.5, 1, 0);\n static const char *names[] = { \"Start\", \"TP1\", \"TP2\", \"TP3\", \"Finish\" };\n route_push_trkpts(route, track->trkpts, 5, indexes, names);\n }\n\n bound = track_frcfd_triangle_plat(track, bound, indexes);\n if (indexes[0] != -1) {\n double distance = track_frcfd_circuit_distance(track, 5, indexes);\n route_t *route = result_push_new_route(result, league, \"out and return via two turnpoints\", distance, 2.0, 1, 0);\n static const char *names[] = { \"Start\", \"TP1\", \"TP2\", \"TP3\", \"Finish\" };\n route_push_trkpts(route, track->trkpts, 5, indexes, names);\n }\n\n return result;\n}\n\n result_t *\ntrack_optimize_ukxcl(track_t *track, int complexity, const declaration_t *declaration)\n{\n static const char *league = \"Cross Country League (United Kingdom)\";\n result_t *result = result_new();\n\n int indexes[6];\n double bound;\n\n bound = track_open_distance(track, 10.0 / R, indexes);\n if (indexes[0] != -1) {\n route_t *route = result_push_new_route(result, league, \"open distance\", R * bound, 1.0, 0, 0);\n const char *names[] = { \"Start\", \"Finish\" };\n route_push_trkpts(route, track->trkpts, 2, indexes, names);\n }\n\n if (complexity != -1 && complexity < 3)\n return result;\n\n if (bound < 15.0 / R)\n bound = 15.0 / R;\n bound = track_open_distance3(track, bound, indexes);\n if (indexes[0] != -1) {\n route_t *route = result_push_new_route(result, league, \"turnpoint flight\", R * bound, 1.0, 0, 0);\n const char *names[] = { \"Start\", \"TP1\", \"TP2\", \"TP3\", \"Finish\" };\n route_push_trkpts(route, track->trkpts, 5, indexes, names);\n }\n\n#if 0\n track_compute_circuit_tables(track, 0.4 / R);\n#endif\n\n return result;\n}\n" }, { "alpha_fraction": 0.48571428656578064, "alphanum_fraction": 0.48571428656578064, "avg_line_length": 16.25, "blob_id": "363139ff22499a933db39928e242c8a7678f10b5", "content_id": "a8e830835a47f51855d5fd2e6f4281ae753756b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 140, "license_type": "no_license", "max_line_length": 27, "num_lines": 8, "path": "/python/common.py", "repo_name": "gustavo80br/soaring", "src_encoding": "UTF-8", "text": "\nclass Base(object):\n \n def __init__(self):\n None\n\n def verbose(self, str):\n if self.verbose:\n print str\n\n" } ]
5
sellonen/ideakilpailu
https://github.com/sellonen/ideakilpailu
449bad907c25a8d3214b38a411076aa388609d99
7c90effcbb628135d0a20d54b3c19cdd05a39863
de82449c5625d0432e5f107cfef97e632fbe6132
refs/heads/master
2016-02-29T12:15:35.374173
2012-09-26T19:45:34
2012-09-26T19:45:34
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.580520749092102, "alphanum_fraction": 0.5834137201309204, "avg_line_length": 33.56666564941406, "blob_id": "9d3801204fca7477eadab143400de9418945928e", "content_id": "2c570024b8f049ecea32194fc7500a396a07a70f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3114, "license_type": "no_license", "max_line_length": 67, "num_lines": 90, "path": "/views.py", "repo_name": "sellonen/ideakilpailu", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom django.shortcuts import render\nfrom django.http import HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.db.models import Sum\nfrom models import Comment,Feedback,Idea\nfrom forms import CommentForm,FeedbackForm,IdeaForm\nslidernames = [\n ('esthetics','Estetiikka'),\n ('atmosphere','Tunnelma'),\n ('flexibility','Käytännöllisyys')]\n\ndef index(request):\n ideas = Idea.objects.all()\n return render(request,'index.html',\n {'ideas' : ideas})\n\n\ndef addIdea(request):\n if request.method == 'POST':\n form = IdeaForm(request.POST,request.FILES,instance=Idea())\n print request.POST\n print request.FILES\n if form.is_valid():\n idea = form.save()\n return HttpResponseRedirect(reverse('addIdea'))\n else:\n print form.errors\n else:\n form = IdeaForm()\n return render(request,'addIdea.html',{'form' : form})\n\ndef ideas(request, idea_id=\"-1\"):\n idea_id = int(idea_id)\n idea = Idea.objects.get(id=idea_id)\n comments = Comment.objects.filter(idea=idea)\n positive_form = CommentForm(\n request.POST or None,\n instance=Comment(),\n initial={'category' : 'pos'})\n negative_form = CommentForm(\n request.POST or None,\n instance=Comment(),\n initial={'category' : 'neg'})\n form = None\n if positive_form.is_valid():\n form = positive_form\n elif negative_form.is_valid():\n form = negative_form\n if form:\n c = form.save(commit=False)\n c.idea = idea\n c.save()\n return HttpResponseRedirect(reverse('ideas',\n kwargs={'idea_id':idea_id}))\n fform = FeedbackForm(instance=Feedback())\n fb = Feedback.objects.filter(idea__id=idea_id)\n oldfeedback = {}\n for sn in slidernames:\n if fb:\n total = fb.aggregate(Sum(sn[0]))[sn[0]+'__sum']\n oldfeedback[sn[0]] = float(total) / len(fb)\n else:\n oldfeedback[sn[0]] = 20\n negs = Comment.objects.filter(idea__id=idea_id,category='neg')\n poss = Comment.objects.filter(idea__id=idea_id,category='pos')\n return render(request,'ideas.html',\n {'idea' : idea,\n 'positive_comments' : poss,\n 'negative_comments' : negs,\n 'positive_form' : positive_form,\n 'negative_form' : negative_form,\n 'slidernames' : slidernames,\n 'oldfeedback' : oldfeedback,\n 'num_of_feedback' : len(fb),\n 'feedbackform' : fform})\n\ndef saveFeedback(request, idea_id=\"-1\"):\n idea_id = int(idea_id)\n idea = Idea.objects.get(id=idea_id)\n fform = FeedbackForm(request.POST,instance=Feedback())\n if fform.is_valid():\n f = fform.save(commit=False)\n f.idea = idea\n f.save()\n else:\n print fform.errors\n return HttpResponseRedirect(reverse('ideas',\n kwargs={'idea_id':idea_id}))\n" }, { "alpha_fraction": 0.6774390339851379, "alphanum_fraction": 0.6963414549827576, "avg_line_length": 40, "blob_id": "5993bd8f0cb5450ae7329793ad52989981b4edea", "content_id": "bec8bd41d34d92de5e7f46ee4aaf5ec8c3e97cf1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1642, "license_type": "no_license", "max_line_length": 84, "num_lines": 40, "path": "/models.py", "repo_name": "sellonen/ideakilpailu", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom django.db import models\nfrom django.contrib.auth.models import User\nfrom django.core.validators import MaxLengthValidator\n\n\n\n# Create your models here.\n\nclass Idea(models.Model):\n level = models.IntegerField()\n name = models.CharField('Idean nimi', max_length=200)\n issuu_link = models.CharField(max_length=500)\n #issuu_div = models.CharField(max_length=5000)\n intro = models.CharField(max_length=5000)\n img = models.ImageField('Kuvatiedosto',upload_to=\"images\",\n blank=True,null=True)\n def __unicode__(self):\n return self.name + ', '+ self.img.url\n\n\nclass Comment(models.Model):\n categories = ( \n ('pos','Asiat, joista ehdotuksessa pidän'),\n ('neg','Asiat, joista ehdotuksessa en pidä'))\n category = models.CharField(max_length=10,choices=categories,blank=True)\n date = models.DateTimeField(auto_now_add=True)\n username = models.CharField('Nimimerkki',max_length=500)\n# user = models.ForeignKey(User, related_name='comments')\n parent = models.ForeignKey(\"self\", related_name='children',blank=True,null=True)\n idea = models.ForeignKey(Idea, related_name='comments')\n text = models.TextField('Kommentti',validators=[MaxLengthValidator(20000)])\n def __unicode__(self):\n return 'kommentti: '+self.text\n\nclass Feedback(models.Model):\n idea = models.ForeignKey(Idea, related_name='feedbacks')\n esthetics = models.IntegerField('Estetiikka',default=50)\n atmosphere = models.IntegerField('Sosiaalinen ilmapiiri',default=50)\n flexibility = models.IntegerField('Toimintamahdollisuudet',default=50)\n" }, { "alpha_fraction": 0.47999998927116394, "alphanum_fraction": 0.47999998927116394, "avg_line_length": 12, "blob_id": "aa361d44dd76821f4a442f3e368ec25a3952fa1d", "content_id": "e1fa4b88554ff15a25b19771ac9ebf1da0204daf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 25, "license_type": "no_license", "max_line_length": 12, "num_lines": 2, "path": "/README.md", "repo_name": "sellonen/ideakilpailu", "src_encoding": "UTF-8", "text": "ideakilpailu\n============" }, { "alpha_fraction": 0.5311653017997742, "alphanum_fraction": 0.5325203537940979, "avg_line_length": 25.321428298950195, "blob_id": "ca3082510673beb04fac305e9464ac860b31f06e", "content_id": "72f10dc2c42d53f6faaa6f05e3a8b154c9c7ba0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 738, "license_type": "no_license", "max_line_length": 53, "num_lines": 28, "path": "/forms.py", "repo_name": "sellonen/ideakilpailu", "src_encoding": "UTF-8", "text": "from django.forms import ModelForm\nfrom models import Comment,Idea,Feedback\nfrom django.forms.widgets import HiddenInput,Textarea\n\nclass CommentForm(ModelForm):\n class Meta:\n model = Comment\n fields = ('text','category')\n widgets = {\n 'category' : HiddenInput(),\n 'text' : Textarea(attrs={\n 'rows':'4'})\n }\n\n\nclass IdeaForm(ModelForm):\n class Meta:\n model = Idea\n\nclass FeedbackForm(ModelForm):\n class Meta:\n model = Feedback\n exclude = ('idea',)\n widgets = {\n 'esthetics' : HiddenInput(),\n 'atmosphere' : HiddenInput(),\n 'flexibility' : HiddenInput()\n }\n\n" } ]
4
xsf/registrar
https://github.com/xsf/registrar
b6e1d138d3052ebb39003fcab68c3361f6048156
e23a6d65dcbc24cca8d022d1f1deb8340c112679
8fd4886e83dca015c1044a54b29c78401f95c178
refs/heads/master
2023-06-13T01:48:47.674289
2023-05-27T13:14:13
2023-05-27T13:14:13
59,731,273
6
17
null
2016-05-26T07:56:55
2023-03-27T11:34:12
2023-05-27T13:14:13
XSLT
[ { "alpha_fraction": 0.7603305578231812, "alphanum_fraction": 0.7665289044380188, "avg_line_length": 31.266666412353516, "blob_id": "5dbfe8cd1b8b5ebb74ec027ace047f442a3ac00d", "content_id": "e2637bab5781fee5063ad0895b38dd1f42fec118", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 484, "license_type": "no_license", "max_line_length": 79, "num_lines": 15, "path": "/Dockerfile", "repo_name": "xsf/registrar", "src_encoding": "UTF-8", "text": "FROM alpine:edge\nMAINTAINER Sam Whited <[email protected]>\n\nRUN apk update && apk upgrade\nRUN apk add make nginx libxml2-utils libxslt\n\n# Build and copy in place.\nWORKDIR /usr/local/src/registrar\nCOPY . /usr/local/src/registrar\nRUN cd /usr/local/src/registrar && make all\n\nFROM nginx:alpine\nCOPY deploy/registrar.conf /etc/nginx/conf.d/default.conf\nCOPY --from=0 /usr/local/src/registrar/index.html /var/www/registrar/index.html\nCOPY --from=0 /usr/local/src/registrar/registrar /var/www/registrar/\n" }, { "alpha_fraction": 0.5433962345123291, "alphanum_fraction": 0.5446540713310242, "avg_line_length": 23.84375, "blob_id": "f0d0c517aa65c34a36f7743915af040c64b99368", "content_id": "591cab5d6c99869daefce052f8ef11f93c99fdd5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 795, "license_type": "no_license", "max_line_length": 114, "num_lines": 32, "path": "/Makefile", "repo_name": "xsf/registrar", "src_encoding": "UTF-8", "text": ".POSIX:\n.SILENT:\n.PHONY: all build clean validate\n\n\nxsltproc ?= xsltproc\nxmllint ?= xmllint\nOUTDIR ?= registrar\nsrcs != find . -maxdepth 1 -name '*.xml'\nhtml = ${srcs:./%.xml=$(OUTDIR)/%.html}\nxml = ${srcs:./%.xml=$(OUTDIR)/%.xml}\n\nall: validate build\n\nbuild: $(html) $(xml)\n\nvalidate:\n\tfor srcfile in $(srcs); do \\\n\t\t$(xmllint) --nonet --noout --noent --loaddtd --valid \"$${srcfile}\" > /dev/null; \\\n\tdone\n\nclean:\n\trm -rf \"$(OUTDIR)\"\n\n$(OUTDIR):\n\tmkdir -p \"$@\"\n\n$(html): $(OUTDIR) ${@:$(OUTDIR)/%.html=%.xml} ${@:$(OUTDIR)/%.html=%.xsl}\n\t$(xsltproc) --stringparam OUTPUT_FILENAME \"$@\" \"${@:$(OUTDIR)/%.html=%.xsl}\" \"${@:$(OUTDIR)/%.html=%.xml}\" > \"$@\"\n\n$(xml): $(OUTDIR) ${@:$(OUTDIR)/%=%} ${@:$(OUTDIR)/%.xml=%-xml.xsl}\n\t$(xsltproc) \"${@:$(OUTDIR)/%.xml=%-xml.xsl}\" \"${@:$(OUTDIR)/%=%}\" > \"$@\"\n" }, { "alpha_fraction": 0.6740168929100037, "alphanum_fraction": 0.682837188243866, "avg_line_length": 23.95412826538086, "blob_id": "2aaf02cddfbc45e72e7ea3530f1420ecd0e8a172", "content_id": "31185f923646e78dc239d19789f68766499d9049", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2721, "license_type": "no_license", "max_line_length": 65, "num_lines": 109, "path": "/announce.py", "repo_name": "xsf/registrar", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n# File: announce.py\n# Version: 0.1\n# Description: a script for announcing registry changes\n# Last Modified: 2004-10-27\n# Author: Peter Saint-Andre ([email protected])\n# License: public domain\n# HowTo: ./announce.py filename (without extension!)\n\n# IMPORTS:\n#\nimport glob\nimport os\nfrom select import select\nimport smtplib\nimport socket\nfrom string import split,strip,join,find\nimport sys\nimport time\nfrom xml.dom.minidom import parse,parseString,Document\n\ndef getText(nodelist):\n thisText = \"\"\n for node in nodelist:\n if node.nodeType == node.TEXT_NODE:\n thisText = thisText + node.data\n return thisText\n\n# READ IN ARGS: \n#\n# 1. registry file name\nregname = sys.argv[1];\n\nregfile = regname + '.xml'\n\n# PARSE REGISTRY HEADERS:\n#\n# - title\n# - version\n# - initials\n# - remark\n\nthereg = parse(regfile)\nregNode = (thereg.getElementsByTagName(\"registry\")[0])\nheaderNode = (regNode.getElementsByTagName(\"meta\")[0])\ntitleNode = (headerNode.getElementsByTagName(\"title\")[0])\ntitle = getText(titleNode.childNodes)\nrevNode = (headerNode.getElementsByTagName(\"revision\")[0])\nversionNode = (revNode.getElementsByTagName(\"version\")[0])\nversion = getText(versionNode.childNodes)\ninitialsNode = (revNode.getElementsByTagName(\"initials\")[0])\ninitials = getText(initialsNode.childNodes)\nremarkNode = (revNode.getElementsByTagName(\"remark\")[0])\nremark = getText(remarkNode.childNodes)\n\n# what kind of action are we taking?\nregflag = \"\"\nif (version == \"0.1\"):\n regflag = \"new\"\n\n# SEND MAIL:\n#\n# From: [email protected]\n# To: [email protected]\n# Subject: UPDATED REGISTRY: $title\n# [or \"NEW REGISTRY:\" if version 0.1]\n# Body:\n# The $title registry has been updated.\n# Version: $version\n# Changelog: $remark ($initials)\n# URL: http://xmpp.org/registrar/$regname.html\n\nfromaddr = \"[email protected]\"\n# for testing...\n# toaddrs = \"[email protected]\"\n# for real...\ntoaddrs = \"[email protected]\"\n\nif regflag == \"new\":\n thesubject = 'NEW REGISTRY: '\n announceline = 'The ' + title + ' registry has been created.'\nelse:\n thesubject = 'UPDATED REGISTRY: '\n announceline = 'The ' + title + ' registry has been updated.'\nthesubject = thesubject + title\n\nversionline = 'Version: ' + version\nchangelogline = 'Changelog: ' + remark + ' (' + initials + ')'\nurlline = 'URL: http://xmpp.org/registrar/' + regname + '.html'\n\nmsg = \"From: XMPP Registrar <%s>\\r\\n\" % fromaddr\nmsg = msg + \"To: %s\\r\\n\" % toaddrs\nmsg = msg + \"Subject: %s\\r\\n\" % thesubject\nmsg = msg + announceline\nmsg = msg + \"\\r\\n\\n\"\nmsg = msg + versionline\nmsg = msg + \"\\r\\n\\n\"\nmsg = msg + changelogline\nmsg = msg + \"\\r\\n\\n\"\nmsg = msg + urlline\nmsg = msg + \"\\r\\n\"\n\nserver = smtplib.SMTP('localhost')\nserver.set_debuglevel(1)\nserver.sendmail(fromaddr, toaddrs, msg)\nserver.quit()\n\n# END\n\n" } ]
3
Wilque/CodigosPy
https://github.com/Wilque/CodigosPy
c9034d49b8f7ad3c16659d98c4a3191304d0aa0e
befea3d897d24c8a88bbabb076841fa3a8f7f207
32b3e49b3d9e4949700f312fef3f938072ae84a3
refs/heads/master
2020-03-23T11:38:19.789269
2019-02-08T12:55:21
2019-02-08T12:55:21
141,513,378
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6546644568443298, "alphanum_fraction": 0.6759411096572876, "avg_line_length": 37.1875, "blob_id": "6a3039a1f7ff152bca057785486cbf2b1e1bd0ab", "content_id": "792985b709d39e6bc760fc758f4250c75373403a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 611, "license_type": "no_license", "max_line_length": 90, "num_lines": 16, "path": "/1035.py", "repo_name": "Wilque/CodigosPy", "src_encoding": "UTF-8", "text": "#***URI 1035*** calculo basico testando condicionais simples\nval = input()#valores de entrada 4 int\nlisVal = []\nlisVal = val.split(' ')#colocando os valores em lista, pois sao dados em unica linha\na = lisVal[0]#Pegando os valores da lista e transformando-os em strings individuais\nb = lisVal[1]\nc = lisVal[2]\nd = lisVal[3]\nA = int(a)#Agora transforma-os em int, para testar a condicional\nB = int(b)\nC = int(c)\nD = int(d)\nif (B > C) and (D > A) and (C+D > A+B) and (C > 0) and (D > 0) and (A%2 == 0):#Condicional\n print('Valores aceitos')\nelse:#Nao satisfazendo as condicoes.\n print('Valores nao aceitos')\n" }, { "alpha_fraction": 0.4444444477558136, "alphanum_fraction": 0.5659722089767456, "avg_line_length": 15.941176414489746, "blob_id": "1a0cdf2dfd947eb0d257ebfc7581bc2a41de6e61", "content_id": "67506a4e2f44a2e058a062932c67e3eaefaf9613", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 288, "license_type": "no_license", "max_line_length": 31, "num_lines": 17, "path": "/1015.py", "repo_name": "Wilque/CodigosPy", "src_encoding": "UTF-8", "text": "from math import sqrt\np1 = input()\np2 = input()\nlisP1 = []\nlisP2 = []\nlisP1 = p1.split(' ')\nlisP2 = p2.split(' ')\nx1 = lisP1[0]\ny1 = lisP1[1]\nx2 = lisP2[0]\ny2 = lisP2[1]\nX1 = float(x1)\nY1 = float(y1)\nX2 = float(x2)\nY2 = float(y2)\nd = sqrt((X2-X1)**2+(Y2-Y1)**2)\nprint('{:.4f}'.format(d))\n" }, { "alpha_fraction": 0.59375, "alphanum_fraction": 0.625, "avg_line_length": 14.5, "blob_id": "94dee4d054f8244de3fdcece4b6b6c2f1fcfd096", "content_id": "38442d22d8b12fbfab7a8df7d4f4429a6a865108", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 32, "license_type": "no_license", "max_line_length": 15, "num_lines": 2, "path": "/testeString.py", "repo_name": "Wilque/CodigosPy", "src_encoding": "UTF-8", "text": "nome = 'wilque'\nprint(nome[1])\n\n" }, { "alpha_fraction": 0.5269320607185364, "alphanum_fraction": 0.5761123895645142, "avg_line_length": 21.473684310913086, "blob_id": "a0550aabc5e59dfaa62ee75dd6e0dc4a3ca76752", "content_id": "405af67f9c67bac138148c668fdba2c65c8cdf32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 427, "license_type": "no_license", "max_line_length": 67, "num_lines": 19, "path": "/1020.py", "repo_name": "Wilque/CodigosPy", "src_encoding": "UTF-8", "text": "#***URI 1020*** -Calculo de dias para idade-\nIdias = int(input())\n\nanos = int()\nmeses = int()\ndias = int()\n\nwhile (Idias >= 0) and (Idias >=365): #Vendo qnts anos a pessoa tem\n Idias -=365\n anos +=1\nwhile (Idias >= 0) and (Idias >=30):#Meses\n Idias -=30\n meses +=1\nwhile (Idias != 0):#Dias\n Idias -=1\n dias +=1\nprint('{} ano(s)'.format(anos))\nprint('{} mes(es)'.format(meses))\nprint('{} dia(s)'.format(dias))\n" }, { "alpha_fraction": 0.5225303173065186, "alphanum_fraction": 0.5493934154510498, "avg_line_length": 31.05555534362793, "blob_id": "07136cc62bdfc8d6a4c7f9161b586068d45e1e66", "content_id": "e01f894ba71adadba2c278482df8ea168115de8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1154, "license_type": "no_license", "max_line_length": 80, "num_lines": 36, "path": "/Broken.py", "repo_name": "Wilque/CodigosPy", "src_encoding": "UTF-8", "text": "import random\n\nlistaAlfabeto =['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',\n 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\nlistaMaiuscula = []\n\nfor i in listaAlfabeto:\n listaMaiuscula.append(i.upper())\n\nprint(listaAlfabeto)\nprint(listaMaiuscula)\n\nnome = ['witalo']\nwhile nome != 'wilque':\n nome[0] = random.choice(listaAlfabeto)\n nome[1] = random.choice(listaAlfabeto)\n '''if nome[0] == nome[1]:\n while nome[1] == nome[0]:\n nome[1] = random.choice(listaAlfabeto)'''\n \n nome[2] = random.choice(listaAlfabeto)\n '''if nome[2] == nome[0] or nome[1] nome[2]:\n while nome[2] == nome[1] or nome[2] == nome[0]:\n nome[2] = random.choice(listaAlfabeto)'''\n\n nome[3] = random.choice(listaAlfabeto)\n '''if nome[3] == nome[2] or nome[3] == nome[0] or nome[1] nome[2]:\n while nome[2] == nome[1] or nome[2] == nome[0]:\n nome[2] = random.choice(listaAlfabeto)'''\n \n nome[4] = random.choice(listaAlfabeto)\n nome[5] = random.choice(listaAlfabeto)\n print (nome)\n #letras = random.choice(listaAlfabeto)\n\nprint(letras)\n" }, { "alpha_fraction": 0.5023400783538818, "alphanum_fraction": 0.5522620677947998, "avg_line_length": 26.869565963745117, "blob_id": "e6db05d04c489f38432c5a250b45021f59f167cf", "content_id": "7d1358b02cee70f4544dbbaa08b3e07f351f0b5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 641, "license_type": "no_license", "max_line_length": 59, "num_lines": 23, "path": "/1019.py", "repo_name": "Wilque/CodigosPy", "src_encoding": "UTF-8", "text": "#***URI-1019*** Convertendo segundos para H:M:S\nN = int(input())\n\nif (N >= 3600):#Vendo se o valor em s consegue completar 1H\n H = N/3600#dividi-se por 3600 para saber qnts H\n m = H %1#pegando parte do float apos o .\n H = H//1#pegando parte inteira do float\n m = m*60#temos aqui qnts m foram\n H = int(H)#passando a um int\n s = m%1#pegando parte apos o . dos m\n m = m//1#pegando parte inteira do m\n m = int(m)#transformando em int\n s = s*60\n s = int(s)\n print('{}:{}:{}'.format(H, m, s))\nelse:\n m = N/60\n s = m%1\n m = m//1\n s = s*60\n s = int(s)\n m = int(m)\n print('0:{}:{}'.format(m, s))\n" }, { "alpha_fraction": 0.5431952476501465, "alphanum_fraction": 0.5633136034011841, "avg_line_length": 31.5, "blob_id": "1be1a8bc965bbb566a4180076938386e8c4fba81", "content_id": "db422732454fa8fc3a91dbdc1a175fab168f6835", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 853, "license_type": "no_license", "max_line_length": 77, "num_lines": 26, "path": "/CalculaSalario.py", "repo_name": "Wilque/CodigosPy", "src_encoding": "UTF-8", "text": "print('================')\nprint('Calcula Salários')\nprint('================')\n\nfunc = input('Digite o nome do funcionário: ')\nsalario = float(input('Digite o salário atual de {}: '.format(func.title())))\ndep = input('{}, possui dependentes?[S/N] '.format(func.title()))\n\nif dep.upper() == 'N':\n salario = salario+salario*0.05\n print('{}, irá receber R${:.2f}'.format(func.title(), salario))\n\nelif dep.upper() == 'S':\n qtd = int(input('Quantos são?'))\n \n if qtd == 1:\n salario = salario+salario*0.1\n print('{}, irá receber R${:.2f}'.format(func.title(), salario))\n\n elif qtd == 2:\n salario = salario+salario*0.15\n print('{}, irá receber R${:.2f}'.format(func.title(), salario))\n\n else:\n salario = salario+salario*0.18\n print('{}, irá receber R${:.2f}'.format(func.title(), salario))\n" }, { "alpha_fraction": 0.7017995119094849, "alphanum_fraction": 0.7069408893585205, "avg_line_length": 37.900001525878906, "blob_id": "18785bc11cfc301cbd47c4188236a4a748bf69e3", "content_id": "b6043aaa7930d1431f9d332f82082ec16280f6f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 389, "license_type": "no_license", "max_line_length": 78, "num_lines": 10, "path": "/teste.py", "repo_name": "Wilque/CodigosPy", "src_encoding": "UTF-8", "text": "import requests\nfrom bs4 import BeautifulSoup\n\nresposta = requests.get('https://tempo.cptec.inpe.br')\nsopa = BeautifulSoup(resposta.text, \"html.parser\")\ntempm = sopa.find('span', attrs={'class': 'temp-max text-center font-dados' })\ntempb = sopa.find('div', attrs={'class': 'p-1 temp-min font-dados'})\ntempM = tempm.text\ntempB = tempb.text\nprint('Maior: {} Menor: {}'.format(tempM, tempB))\n" }, { "alpha_fraction": 0.5422297120094299, "alphanum_fraction": 0.5641891956329346, "avg_line_length": 30.157894134521484, "blob_id": "07d1b293d4b101c22222033e44732541a60f3b02", "content_id": "3bf3a5ab985400ce62e4c451a1cd98596c6f76fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 601, "license_type": "no_license", "max_line_length": 124, "num_lines": 19, "path": "/FormulaBhaskara.py", "repo_name": "Wilque/CodigosPy", "src_encoding": "UTF-8", "text": "from math import sqrt\n\nprint('Equação do segundo grau')\n\na = float(input('Digite o valor de A: '))\nb = float(input('Digite o valor de B: '))\nc = float(input('Digite o valor de C: '))\n\ndelta = b**2-4*a*c\n\nif delta < 0:\n print('O sistema de equações com A: {}, B: {} e C: {}, não resulta em raízes reais'.format(a, b, c))\nelse:\n x1 = (-b+sqrt(delta))/2*a\n x2 = (-b-sqrt(delta))/2*a\n if delta == 0:\n print('O sistema de equações com A: {}, B: {} e C: {}, resulta em raízes iguais sendo ela = {}'.format(a, b, c, x1))\n else:\n print('X1 = {}, X2 = {}'.format(x1, x2))\n" }, { "alpha_fraction": 0.654321014881134, "alphanum_fraction": 0.654321014881134, "avg_line_length": 25.66666603088379, "blob_id": "8b32f8b09bb34ec34e15bf99ff7ac19f97535e50", "content_id": "2e91f646aeb343d9975582a4025b20aa4fbffb36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 81, "license_type": "no_license", "max_line_length": 30, "num_lines": 3, "path": "/FazendoSnduiches.py", "repo_name": "Wilque/CodigosPy", "src_encoding": "UTF-8", "text": "\ndef fazsanduiche (*sanduiche):\n for i in sanduiche:\n print(sanduiche)\n" }, { "alpha_fraction": 0.5364372730255127, "alphanum_fraction": 0.5850202441215515, "avg_line_length": 22.33333396911621, "blob_id": "bc51344751cc9afbdd7e4496a9495ed37ad98b46", "content_id": "d3393905c32b07bbed04d01775203430f62347b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 495, "license_type": "no_license", "max_line_length": 49, "num_lines": 21, "path": "/Imc.py", "repo_name": "Wilque/CodigosPy", "src_encoding": "UTF-8", "text": "print('===========')\nprint('Cálculo IMC')\nprint('===========')\n\naltura = float(input('Digite sua altura em M: '))\npeso = float(input('Digite seu peso em KG: '))\n\nimc = peso/(altura*altura)\n\nif imc < 18.5:\n print('Abaixo do peso')\nelif imc > 18.5 and imc < 24.9:\n print('peso ideal')\nelif imc > 25 and imc < 29.9:\n print('Acima do peso')\nelif imc > 30 and imc < 34.9:\n print('Obesidade I')\nelif imc > 35 and imc < 39.9:\n print('Obesidade II')\nelse:\n print('Obesidade III')\n\n\n\n\n" }, { "alpha_fraction": 0.7124999761581421, "alphanum_fraction": 0.7250000238418579, "avg_line_length": 21.85714340209961, "blob_id": "657696fafaa030107d521a27cfe77bf556f7e282", "content_id": "9f4def491a840a983ca2cc2d0fb70826899d8c8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 160, "license_type": "no_license", "max_line_length": 64, "num_lines": 7, "path": "/teste00.py", "repo_name": "Wilque/CodigosPy", "src_encoding": "UTF-8", "text": "from PIL import Image\nimport requests\n\ncat = requests.get('https://api.thecatapi.com/v1/images/search')\nurlCat = cat['0']\nimg = image.open('urlCat')\nerint(img)\n" }, { "alpha_fraction": 0.5125448107719421, "alphanum_fraction": 0.5125448107719421, "avg_line_length": 33.875, "blob_id": "ec1cd1dff8259d2d79e114898979bee7db506ef2", "content_id": "6a34fb8d1e0e517cabb89de12a972544a467eb38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 279, "license_type": "no_license", "max_line_length": 62, "num_lines": 8, "path": "/Album.py", "repo_name": "Wilque/CodigosPy", "src_encoding": "UTF-8", "text": "def dicioAlbum (artista, titulo, faixas = ''):\n while True:\n album = {'artista' : artista, 'Titulo': titulo}\n if faixas:\n album ['faixas'] = faixas\n '''else:\n album = {'artista' : artista, 'Titulo': titulo}'''\n return(album)\n" }, { "alpha_fraction": 0.875, "alphanum_fraction": 0.875, "avg_line_length": 71, "blob_id": "609e4ea9ce3e890b1c723a03ea36f6471b1825aa", "content_id": "d34d13a55c5f125c2724e8313c9ec5123b7b3392", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 72, "license_type": "no_license", "max_line_length": 71, "num_lines": 1, "path": "/README.md", "repo_name": "Wilque/CodigosPy", "src_encoding": "UTF-8", "text": "Codigos cotidianos resolvendo desafios para problemas dos mais variados\n" }, { "alpha_fraction": 0.5935251712799072, "alphanum_fraction": 0.6780575513839722, "avg_line_length": 28.263158798217773, "blob_id": "de48edae4dfcc4b162b92610cb5546320644d063", "content_id": "1e15fc1858ea1b614c3e78262f8619a70d82fa01", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 556, "license_type": "no_license", "max_line_length": 62, "num_lines": 19, "path": "/1010.py", "repo_name": "Wilque/CodigosPy", "src_encoding": "UTF-8", "text": "#***URI 1010*** calculo de compra\nc1 = input()#compra 1\nc2 = input()#compra 2\nlisC1 = []\nlisC2 = []\nlisC1 = c1.split(' ')#passando a string cortada a uma lista\nlisC2 = c2.split(' ')\ncodP1 = lisC1[0]#usando os dados agora por unidade\nnP1 = lisC1[1]#num de pecas 1\nvP1 = lisC1[2]#valor do produto 1\ncodP2 = lisC2[0]\nnP2 = lisC2[1]\nvP2 = lisC2[2]\nNP1 = int(nP1)#tranformando-os em outro tipo para serem usados\nVP1 = float(vP1)\nNP2 = int(nP2)\nVP2 = float(vP2)\nValorPago = NP1*VP1 + NP2*VP2#calculo da compra\nprint('VALOR A PAGAR: R$ {:.2f}'.format(ValorPago))\n" }, { "alpha_fraction": 0.49757280945777893, "alphanum_fraction": 0.5388349294662476, "avg_line_length": 18.619047164916992, "blob_id": "1ed8d3bd500fe664d313d987c8e1bf5c061e42e4", "content_id": "bd9457f502e8ec57cd30f6454af2681f9a6f0211", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 412, "license_type": "no_license", "max_line_length": 35, "num_lines": 21, "path": "/1036.py", "repo_name": "Wilque/CodigosPy", "src_encoding": "UTF-8", "text": "from math import sqrt\n\nval = input()\nlisVal = []\nlisVal = val.split(' ')\na = lisVal[0]\nb = lisVal[1]\nc = lisVal[2]\na = float(a)\nb = float(b)\nc = float(c)\ndelta = float()\ndelta = (b**2)-4*a*c\nif (a == 0) or (delta < 0) :\n print('Impossivel calcular')\nelse:\n print(delta)\n x1 = (-b-sqrt(delta))/(2*a)\n x2 = (-b+sqrt(delta))/(2*a)\n print('R1 = {:.5f}'.format(x1))\n print('R2 = {:.5f}'.format(x2))\n" }, { "alpha_fraction": 0.7125141024589539, "alphanum_fraction": 0.7260428667068481, "avg_line_length": 35.95833206176758, "blob_id": "5ce39815cb2fa0d78c47410f298b57fd934c984b", "content_id": "b7af026ac913994e7c41c6baaca69ea45ec27c00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 887, "license_type": "no_license", "max_line_length": 83, "num_lines": 24, "path": "/Starter_bot.py", "repo_name": "Wilque/CodigosPy", "src_encoding": "UTF-8", "text": "from telegram.ext import Updater, CommandHandler\nimport requests\nimport re\n#Bot criado com intuito de testar conhecimentos basicos\n#Funcao responsavel por pegar a url da api random.dog\ndef get_url():\n contents = requests.get('https://random.dog/woof.json').json()#pegando o json\n url = contents['url']#pegando a url da imagem gerada\n return(url)#retornando-a\n#funcao responsavel por executar ao comando /bop\ndef cachorro(bot, update):\n url = get_url()#chama a anterior\n chat_id = update.message.chat_id#passa a atualizar o envio\n bot.send_photo(chat_id=chat_id, photo=url)#envia\n#construcao da conexao\ndef main():\n updater = Updater('711505407:AAHB7bWRoEVKkvv4HmmAZPEuerImyA2iYRo')#token do bot\n dp = updater.dispatcher\n dp.add_handler(CommandHandler('cachorro', cachorro))\n updater.start_polling()\n updater.idle()\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.7397260069847107, "alphanum_fraction": 0.7465753555297852, "avg_line_length": 19.85714340209961, "blob_id": "036030b3d03ac76cc4e03c6cc5a92adabf15b0b0", "content_id": "5ca47e5da47697d9b3257b5528f71443bf2c3c21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 146, "license_type": "no_license", "max_line_length": 76, "num_lines": 7, "path": "/lendoJson.py", "repo_name": "Wilque/CodigosPy", "src_encoding": "UTF-8", "text": "import json\nimport requests\n\nresposta = requests.get('https://api.thecatapi.com/v1/images/search').json()\n\nimagem = resposta['url']\nprint(imagem)\n" }, { "alpha_fraction": 0.621761679649353, "alphanum_fraction": 0.6632124185562134, "avg_line_length": 20.259260177612305, "blob_id": "034ccc62bf40d9c13340193abe2773de1c68b527", "content_id": "be4d415602c7d633abfed2e38586a5a4f3cf7c6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 579, "license_type": "no_license", "max_line_length": 54, "num_lines": 27, "path": "/ListaChute.py", "repo_name": "Wilque/CodigosPy", "src_encoding": "UTF-8", "text": "from random import randint\n\nprint('TentativasDeAdivinharNumeros')\n\nnum = int(input('Digite um numero entre 0 e 10000: '))\nlistachutes = []\nverificapares = []\nchute = randint(0, 10000)\n\nwhile chute != num:\n chute = randint(0, 10000)\n if chute in listachutes:\n chute = randint(0, 10000)\n else:\n listachutes.append(chute)\n \n\nprint(listachutes)\nprint(len(listachutes))\n\nfor i in listachutes:\n if i not in verificapares:\n verificapares.append(i)\nif len(verificapares) == len(listachutes):\n print('Tudo OK!!!')\nelse:\n print('Vai dormir')\n \n" }, { "alpha_fraction": 0.6757281422615051, "alphanum_fraction": 0.7223300933837891, "avg_line_length": 35.78571319580078, "blob_id": "b9d5ba38a849516e7332749b5e83715dc742a1e5", "content_id": "e7b85f2fa400d16bad4b261c8315bddcb9c964f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 515, "license_type": "no_license", "max_line_length": 84, "num_lines": 14, "path": "/1013.py", "repo_name": "Wilque/CodigosPy", "src_encoding": "UTF-8", "text": "#***URI 1013*** saber qual e o maior numero entre tres\nnum = input()#guardando os tres em unica linha\nlisNum = []\nlisNum = num.split(' ')#separando-os\na = lisNum[0]#usando individualmente\nb = lisNum[1]\nc = lisNum[2]\nnum1 = int(a)#agr sao int\nnum2 = int(b)\nnum3 = int(c)\nmaiorN1N2 = (num1+num2+abs(num1-num2))/2#operacao que descobre qual num e maior\nmaior = (maiorN1N2+num3+abs(maiorN1N2-num3))/2#comparando com o ultimo valor entrado\nmaior = int(maior)#transformando em int ja que ele fica como float\nprint(maior)\n" }, { "alpha_fraction": 0.6370967626571655, "alphanum_fraction": 0.6370967626571655, "avg_line_length": 28.5, "blob_id": "e66cc508647703b4329af964b9e9f1bf0a2b0ccc", "content_id": "55fd260a1ed09728208724bcd0607ab55facedd3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 127, "license_type": "no_license", "max_line_length": 37, "num_lines": 4, "path": "/cidade_pais.py", "repo_name": "Wilque/CodigosPy", "src_encoding": "UTF-8", "text": "#Treinando Funçẽs.\ndef cidadePais (cidade, pais):\n formatacao = cidade + ', ' + pais\n return formatacao.title()\n\n \n" }, { "alpha_fraction": 0.7159090638160706, "alphanum_fraction": 0.7272727489471436, "avg_line_length": 28, "blob_id": "9dca363a7a4add4ce1c1a81871232f336adb6f94", "content_id": "47ab83ffdea4a2530571968428223dfa912e54b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 88, "license_type": "no_license", "max_line_length": 69, "num_lines": 3, "path": "/test.py", "repo_name": "Wilque/CodigosPy", "src_encoding": "UTF-8", "text": "import requests\n\nr = requests.get('https://api.thecatapi.com/v1/images/search').json()\n\n" }, { "alpha_fraction": 0.5677965879440308, "alphanum_fraction": 0.6059321761131287, "avg_line_length": 20.454545974731445, "blob_id": "6d25584944b0e2710f48f8632d26baf7a2e5b1d1", "content_id": "3fe731af287a18ae801ab0598f130afa115600e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 472, "license_type": "no_license", "max_line_length": 37, "num_lines": 22, "path": "/NumerosPrimos.py", "repo_name": "Wilque/CodigosPy", "src_encoding": "UTF-8", "text": "print('numeros primos entre 0 e 100')\n\nnumerosprimos = []\nnumerosimpares = []\ncontdiv = int(0)\n\nfor i in range(0, 101):\n print(i)\n if i%2 == 1:\n numerosimpares.append(i)\ndel numerosimpares[0]\nnumerosimpares.insert(0, 2)\nprint(numerosimpares)\nfor i in numerosimpares:\n print(i)\n for primo in range(i, 1):\n div = i%primo\n if div == 0:\n contdiv +=1\n if contdiv == 2:\n numerosprimos.append(i)\nprint(numerosprimos)\n" }, { "alpha_fraction": 0.4713114798069, "alphanum_fraction": 0.4713114798069, "avg_line_length": 26.11111068725586, "blob_id": "dd5dc2433d114a468c5a8a65445be56296609d80", "content_id": "0defeb467f726c11a43911cb76e810913abf32bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 244, "license_type": "no_license", "max_line_length": 56, "num_lines": 9, "path": "/NomesMagicos.py", "repo_name": "Wilque/CodigosPy", "src_encoding": "UTF-8", "text": "nomes_magicos = ['howard thurston', 'david copperfield', 'lance burton',\n 'harry houdini', 'david blaine', 'dynamo', 'derren brown',\n 'criss angel']\n\ndef vermagicos (nomes):\n for i in nomes:\n print('Grande {}'.format(i))\n\nvermagicos (nomes_magicos[:])\n" } ]
24
srikanthreddybms/railml_to_rbc
https://github.com/srikanthreddybms/railml_to_rbc
71e8b28d1133ffbfece9da64f3a9ca3d0cbaa007
244efdb4c8a0f779d1a4072fe5f2ed94a94db1e9
a8b3b4a2c4d9c40ada5ae04562995efb8195c7fd
refs/heads/master
2020-02-26T11:58:00.757293
2016-07-21T14:11:05
2016-07-21T14:11:05
63,873,320
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5821141600608826, "alphanum_fraction": 0.5882661938667297, "avg_line_length": 43.731544494628906, "blob_id": "4fff38e59486f2629448e80a37ba46f1133b51c0", "content_id": "635464e4cdf14343631e4277b3f71fd057bf1715", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13330, "license_type": "no_license", "max_line_length": 192, "num_lines": 298, "path": "/src/rules_manager/rules_processor.py", "repo_name": "srikanthreddybms/railml_to_rbc", "src_encoding": "UTF-8", "text": "\"\"\"\nRules for Define Nodes and Connector module\nThis module is used to initiate the rules manipulations of rules manager component of RailMl to RBC route map\nconversion tool\n\n@copyright:\nAll rights reserved. ©2016. ALSTOM (Bangalore, India).\nThis computer program may not be used, copied, distributed, corrected,\nmodified, translated, transmitted or assigned without ALSTOM's prior\nwritten authorization.\n\n@date : 18th July 2016\n@author: Sanjay Kalshetty, Srikanth Reddy\n\"\"\"\n\nfrom collections import OrderedDict\nfrom configparser import ConfigParser\nfrom lxml import etree\nimport src.globals.globalds as globalds\nimport os\nimport re\nimport sys\n\nimport src.rules_manager.rules_to_define_node_and_connectors as node_and_connectors\nimport src.rules_manager.rules_to_define_segments as segments\nimport src.rules_manager.rules_to_define_buffer_stops as buffer_stops\nimport src.rules_manager.rules_to_define_track_occupations as track_occupations\n\nclass rules_proc:\n\n def __init__(self,files_int_inp,logger):\n self.input_railml = files_int_inp['railml']\n self.config = files_int_inp['config']\n self.input_rbc_genparmas = files_int_inp['rbcgen']\n self.logger = logger\n self.rules_info = self.extract_ruleinfo_from_config_file()\n\n\n def extract_ruleinfo_from_config_file(self):\n rules_info = []\n rules_dict_info = OrderedDict()\n parser = ConfigParser()\n parser.optionxform = str\n parser.read(self.config)\n params = list()\n self.logger.log_progress(\"GET_XPATH_INFO_STARTED\", params)\n\n\n parser._defaults = {}\n for section_name in parser.sections():\n rules_dict_info.update({'Rule': section_name})\n for name, value in parser.items(section_name):\n rules_dict_info.update({name: value})\n rules_info.append(rules_dict_info)\n rules_dict_info = OrderedDict()\n\n self.logger.log_progress(\"GET_XPATH_INFO_DONE\", params)\n\n return rules_info\n\n def extract_rbc_general_parameters(self):\n general_params_dict = OrderedDict()\n genParams_tree = etree.parse(self.input_rbc_genparmas)\n static_size_params = genParams_tree.xpath(\"/mainNS:rbcGeneralParameters/mainNS:staticSizingParameters\",\n namespaces= globalds.NSMAP_genParams)\n conversion_parameters = genParams_tree.xpath(\"/mainNS:rbcGeneralParameters/mainNS:conversionParameters\",\n namespaces=globalds.NSMAP_genParams)\n default_parameters = genParams_tree.xpath(\"/mainNS:rbcGeneralParameters/mainNS:defaultValues\",\n namespaces=globalds.NSMAP_genParams)\n params_required = list([static_size_params, conversion_parameters,default_parameters])\n for item in params_required:\n for node in item:\n for child in node.findall('.//'):\n tag = etree.QName(child)\n if tag.localname in [\"nMaxNodes\", \"nMaxConnectors\", \"nMaxSegments\", \"nMaxConnections\",\n \"roundTo10cm\", \"roundTo1m\", \"roundTo10m\", \"nMaxTrackOccupations\", \"nMaxLimitsInTrackOccupation\", \"nMaxConnectorsInTrackOccupation\", \"nMaxBufferStops\"]:\n general_params_dict.update({tag.localname: child.text})\n elif tag.localname == \"segment\":\n general_params_dict.update(OrderedDict(child.attrib))\n elif tag.localname == \"trackOccupation\":\n general_params_dict.update(OrderedDict(child.attrib))\n\n\n return general_params_dict\n\n @staticmethod\n def get_input_railml():\n return rules_proc().input_railml\n\n def get_input_rbc_genparams(self):\n return self.input_rbc_genparmas\n\n\n\nclass rule_engine():\n\n\n NSMAP = {'mainNS': \"http://www.railml.org/schemas/2013\", \\\n 'xsNS': 'http://www.w3.org/2001/XMLSchema', \\\n 'dcNS': 'http://purl.org/dc/elements/1.1/', \\\n 'ATLASbasic': 'http://www.transport.alstom.com/ATLAS/basic/1', \\\n 'ATLASetcs2': 'http://www.transport.alstom.com/ATLAS/etcs2/1'}\n\n NSMAP_genParams = {'mainNS': \"http://www.transport.alstom.com/ATLAS/rbcGeneralParameters/1/\", \\\n 'xsNS': \"http://www.w3.org/2001/XMLSchema\"}\n\n def __init__(self, files_int_inp, xpaths, logger):\n\n self.input_railml = files_int_inp['railml']\n self.config = files_int_inp['config']\n self.input_rbc_genparmas = files_int_inp['rbcgen']\n self.xpaths = xpaths\n self.logger = logger\n self.rules_info = self.extract_trackinfo()\n\n def extract_trackinfo(self):\n total_data = []\n\n for rule in self.xpaths:\n data_info = []\n rule_name = rule['Rule']\n num_xpath = int(rule['NumXPath'])\n xpath = rule['xPath']\n output_info_dict = rule_engine.get_output_info(rule, \"OutputNodes\")\n\n if num_xpath > 0:\n xpath_list = xpath.split(\",\")\n\n for each_xpath in xpath_list:\n x_path, required_nodes, required_sub_nodes = \"\", \"\", \"\"\n if (len(each_xpath.split(\"#\")) == 3):\n x_path, required_nodes, required_sub_nodes = each_xpath.split(\"#\")\n data_info.append(\n rule_engine.extract_data_required(self, rule_name, x_path, required_nodes, required_sub_nodes, output_info_dict, self.logger))\n\n total_data.append(data_info)\n\n return total_data\n\n def extract_data_required(self, rule_name, xPath, required_nodes, required_sub_nodes, output_info_dict,logger):\n tree = etree.parse(self.input_railml)\n\n data_required = []\n data_required_dict = OrderedDict()\n\n required_nodes = required_nodes.split(\"|\")\n required_sub_nodes = required_sub_nodes.split(\"|\")\n\n required_nodes = [re.sub(r'''[']''', \"\", node) for node in required_nodes]\n required_sub_nodes = [re.sub(r'''[']''', \"\", node) for node in required_sub_nodes]\n\n temp = re.subn(r\"[a-zA-Z0-9]+?:\", \"\", xPath)\n xPath1 = re.sub(r'''['\"]''', \"\", xPath)\n xPath = xPath.replace(\"'\", \"\")\n\n if (temp[1] == 0):\n\n params = list()\n params.append(\", Provide the proper xpath with namespaces for %s, in Rules.ini\" %rule_name)\n logger.log_error(\"ERR_WRONG_INI_SECTION\", params)\n\n else:\n\n matched_nodes = tree.xpath(xPath, namespaces=rule_engine.NSMAP) # we can say this mainNode\n for m_node in matched_nodes:\n relation_ship_nodes_list = []\n relation_ship_nodes_dict = OrderedDict()\n tag = etree.QName(m_node)\n data_required_dict.update({tag.localname: OrderedDict(m_node.attrib)})\n for child in m_node.findall('.//'):\n tag = etree.QName(child)\n node_name = tag.localname\n g_child_name = \"\"\n matched_sub_child = \"\"\n if node_name in required_nodes:\n data_required_dict.update({node_name: OrderedDict(child.attrib)})\n for g_child in child.findall(\".//\"):\n g_child_tag = etree.QName(g_child)\n g_child_name = g_child_tag.localname\n if g_child_name in required_sub_nodes:\n relation_ship_nodes_dict[g_child_name] = OrderedDict(g_child.attrib)\n relation_ship_nodes_list.append({g_child_name: OrderedDict(g_child.attrib)})\n matched_sub_child = g_child_name\n\n if len(relation_ship_nodes_list) >= 1:\n data_required_dict[node_name][matched_sub_child] = relation_ship_nodes_list\n\n relation_ship_nodes_dict = OrderedDict()\n relation_ship_nodes_list = []\n\n data_required_dict.update(output_info_dict)\n data_required.append(data_required_dict)\n data_required_dict = OrderedDict()\n\n if rule_name == \"Segments\":\n data_required_dict.update(OrderedDict(output_info_dict))\n data_required.append(data_required_dict)\n data_required_dict = OrderedDict()\n # elif rule_name == \"BufferStops\":\n # data_required_dict.update(OrderedDict(output_info_dict))\n # data_required.append(data_required_dict)\n # data_required_dict = OrderedDict()\n\n return rule_name, data_required\n\n @staticmethod\n def get_output_info(dictn,strng):\n output_info_dict = OrderedDict()\n num_outputs = dictn[strng].split(\",\")\n for each_output_info in num_outputs:\n output_info = [re.sub(r'''['\"]''', \"\", v) for v in each_output_info.split(\"#\")]\n output_info_dict[output_info[0]] = list(output_info[1:])\n return output_info_dict\n\n# class to manage the execution sequence in order\nclass execute_rules():\n\n def __init__(self, tracks_info_for_rules, genparams, logger):\n self.rules_info = tracks_info_for_rules\n self.logger = logger\n self.genparams = genparams\n\n def rules_scheduler(self):\n\n for rule_data in self.rules_info:\n\n if rule_data[0][0] == \"NodesAndConnectorsAtBufferStop\":\n params = list()\n params.append(rule_data[0][0])\n self.logger.log_progress(\"RULES_EXECUTION_STARTED\", params)\n # call the routine related to bufferstop\n node_and_connectors.nc_buffer_stop.execute(rule_data, self.logger)\n self.logger.log_progress(\"RULES_EXECUTION_END\", params)\n\n elif rule_data[0][0] == \"NodesAndConnectorsAtBoundaries\":\n params = list()\n params.append(rule_data[0][0])\n self.logger.log_progress(\"RULES_EXECUTION_STARTED\", params)\n # call the routine to compute nodes/connectors related to boundary\n node_and_connectors.nc_boundries.execute(rule_data, self.logger)\n self.logger.log_progress(\"RULES_EXECUTION_END\", params)\n\n elif rule_data[0][0] == \"NodesAndConnectorsAtSignalsSubstopLocationsAndVirtualSignals\":\n params = list()\n params.append(rule_data[0][0])\n self.logger.log_progress(\"RULES_EXECUTION_STARTED\", params)\n # call the routine related to signals/virtualsignals\n node_and_connectors.nc_signals_substoplocations_virtualsignals.execute(rule_data)\n self.logger.log_progress(\"RULES_EXECUTION_END\", params)\n\n elif rule_data[0][0] == \"NodesAndConnectorsAtCrossings\":\n params = list()\n params.append(rule_data[0][0])\n self.logger.log_progress(\"RULES_EXECUTION_STARTED\", params)\n # call the routine related to crossing\n node_and_connectors.nc_crossing.execute(rule_data)\n self.logger.log_progress(\"RULES_EXECUTION_END\", params)\n\n elif rule_data[0][0] == \"NodesAndConnectorsAtSwitches\":\n params = list()\n params.append(rule_data[0][0])\n self.logger.log_progress(\"RULES_EXECUTION_STARTED\", params)\n # call the routine related to switch\n node_and_connectors.nc_switch.execute(rule_data)\n self.logger.log_progress(\"RULES_EXECUTION_END\", params)\n\n elif rule_data[0][0] == \"NodesAndConnectorsAtKpJump\":\n params = list()\n params.append(rule_data[0][0])\n self.logger.log_progress(\"RULES_EXECUTION_STARTED\", params)\n # call the routine related to kpjump\n node_and_connectors.nc_kpjump.execute(rule_data, self.logger)\n self.logger.log_progress(\"RULES_EXECUTION_END\", params)\n\n\n elif rule_data[0][0] == \"Segments\":\n params = list()\n params.append(rule_data[0][0])\n self.logger.log_progress(\"RULES_EXECUTION_STARTED\", params)\n # call the routine related to segments\n segments.segments.execute(rule_data,self.genparams, self.logger)\n self.logger.log_progress(\"RULES_EXECUTION_END\", params)\n\n elif rule_data[0][0] == \"BufferStops\":\n params = list()\n params.append(rule_data[0][0])\n self.logger.log_progress(\"RULES_EXECUTION_STARTED\", params)\n # call the routine related to segments\n buffer_stops.buffer_stops.execute(rule_data, self.genparams, self.logger)\n self.logger.log_progress(\"RULES_EXECUTION_END\", params)\n\n elif rule_data[0][0] == \"TrackOccupations\":\n params = list()\n params.append(rule_data[0][0])\n self.logger.log_progress(\"RULES_EXECUTION_STARTED\", params)\n # call the routine related to segments\n track_occupations.track_occupations.execute(rule_data, self.genparams, self.logger)\n self.logger.log_progress(\"RULES_EXECUTION_END\", params)" }, { "alpha_fraction": 0.5422658324241638, "alphanum_fraction": 0.5477758646011353, "avg_line_length": 47.93421173095703, "blob_id": "828858976480d5537d2e048931534bfcda462cd1", "content_id": "d2e5fe1e2cae0d6f99596eda4fc636e7d79f3de2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7442, "license_type": "no_license", "max_line_length": 204, "num_lines": 152, "path": "/src/rules_manager/rules_to_define_track_occupations.py", "repo_name": "srikanthreddybms/railml_to_rbc", "src_encoding": "UTF-8", "text": "\"\"\"\nRules for Define track occupations\nThis module is used to initiate the rules manipulations of rules related to track occupations\ncreation under rules manager component of RailMl to RBC route map conversion tool\n\n@copyright:\nAll rights reserved. ©2016. ALSTOM (Bangalore, India).\nThis computer program may not be used, copied, distributed, corrected,\nmodified, translated, transmitted or assigned without ALSTOM's prior\nwritten authorization.\n\n@date : 18th July 2016\n@author: Sanjay Kalshetty, Srikanth Reddy\n\"\"\"\n\nimport re\nfrom collections import OrderedDict\nfrom collections import Counter\nimport collections\nfrom lxml import etree\nfrom itertools import groupby\nimport src.globals.globalds as globalds\n\n\nclass track_occupations():\n \"\"\"\n This class used to manage creation of track occupations in RBC output file\n \"\"\"\n separator_nodes = []\n non_separator_nodes = []\n @staticmethod\n def execute(rule_data, genparams, logger):\n print(rule_data)\n track_occupations.separator_nodes, track_occupations.non_separator_nodes = track_occupations.get_separator_nonseparator_nodes(rule_data)\n for each_track in track_occupations.separator_nodes:\n # for each_track in each_item[1]:\n down_section_name = \"\"\n track_occupation_found = False\n down_section_names = []\n up_section_names = []\n separator_abs_pos = []\n up_down_section_names = []\n if 'separators' in each_track:\n for each_separator in each_track['separators']:\n if 'upSectionName' in each_separator:\n up_section_name = each_separator['upSectionName']\n up_section_names.append(up_section_name)\n separator_abs_pos.append(each_separator['absPos'])\n continue\n elif 'downSectionName' in each_separator:\n down_section_name = each_separator['downSectionName']\n down_section_names.append(down_section_name)\n separator_abs_pos.append(each_separator['absPos'])\n continue\n up_down_section_names = up_section_names + down_section_names\n for each_node in globalds.nodes:\n node_id = each_node[0].find(\"./id\").text\n last_underscore = node_id.rfind(\"_\")\n if last_underscore != -1:\n node_id = node_id[:last_underscore]\n else:\n node_id = node_id\n if node_id == down_section_name:\n track_occupation_found = True\n break\n if track_occupation_found is False:\n if len(up_down_section_names) >= 2:\n check_up_down_section_names = [item for item,count in Counter(up_down_section_names).items() if count >= 2]\n if len(check_up_down_section_names) >= 1:\n check_node_exist = track_occupations.check_node_exists_between_separators(separator_abs_pos)\n if check_node_exist is False:\n pass # track_occupation shall end at the separator(2)\n else:\n if 'trackEnd' in each_track:\n track_end_flag = True\n check_node_exist_between_separator_and_te = track_occupations.check_node_exists_between_separators(separator_abs_pos,(track_end_flag,each_track['trackEnd']['absPos']))\n if check_node_exist_between_separator_and_te is False:\n pass\n if 'connections' in each_track:\n switch_crossing_link = track_occupations.check_switch_crossing_link(each_track)\n\n\n @staticmethod\n def check_node_exists_between_separators(separator_abs_positions,track_end_flag=False):\n separator_abs_pos = sorted(separator_abs_positions)\n for each_node in globalds.nodes:\n if track_end_flag is False:\n if each_node[0].find(\"./kilometric_point\") is not None:\n km_point = each_node[0].find(\"./kilometric_point\").text\n if separator_abs_pos[0] < km_point < separator_abs_pos[len(separator_abs_pos) - 1] or separator_abs_pos[len(separator_abs_pos) - 1] < km_point < separator_abs_pos[0]:\n return True\n else:\n return False\n else:\n if track_end_flag[0] is True:\n if separator_abs_pos[0] < track_end_flag[1] < separator_abs_pos[len(separator_abs_pos) - 1] or separator_abs_pos[len(separator_abs_pos) - 1] < track_end_flag[1] < separator_abs_pos[0]:\n return True\n else:\n return False\n\n\n @staticmethod\n def get_separator_nonseparator_nodes(tracks):\n for track_info in tracks:\n for each_track in track_info[1]:\n if 'separators' in each_track:\n track_occupations.separator_nodes.append(each_track)\n else:\n track_occupations.non_separator_nodes.append(each_track)\n return track_occupations.separator_nodes, track_occupations.non_separator_nodes\n\n\n @staticmethod\n def check_switch_crossing_link(track):\n check_link_crossing_switch = False\n switch_id = \"\"\n switch_defined_at_track_end = False\n crossing_defined_at_track_end = False\n if 'connections' in track:\n if type(track['connections']['connection']) is list:\n for value1 in track['connections']['connection']:\n if 'crossing' in value1:\n crossing_abs_position = int(value1['crossing']['absPos'])\n if crossing_abs_position == int(track['trackEnd']['absPos']):\n crossing_defined_at_track_end = True\n break\n if 'switch' in value1:\n switch_id = value1['switch']['id']\n switch_abs_position = int(value1['switch']['absPos'])\n if switch_defined_at_track_end is False:\n if switch_abs_position == int(track['trackEnd']['absPos']):\n switch_defined_at_track_end = True\n break\n if 'crossingAdditionalInfo' in track and 'switch' in track[\n 'crossingAdditionalInfo'] and type(track['crossingAdditionalInfo']['switch']) is list:\n for value2 in track['crossingAdditionalInfo']['switch']:\n if switch_id == value2['switch']['switchRef']:\n check_link_crossing_switch = True\n break\n if crossing_defined_at_track_end is True or switch_defined_at_track_end is True or check_link_crossing_switch is True:\n return True\n else:\n return False\n\n\n @staticmethod\n def create_track_occupations():\n pass\n\n @staticmethod\n def create_track_occupation_at_rule98():\n pass\n\n\n\n" }, { "alpha_fraction": 0.5766299962997437, "alphanum_fraction": 0.5863674879074097, "avg_line_length": 41.19643020629883, "blob_id": "2dc3cf2d069315b398f37d9e6352ba6730033cdd", "content_id": "610dd0e3bbcb7eadf21068113ea42c8775903dad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2363, "license_type": "no_license", "max_line_length": 131, "num_lines": 56, "path": "/src/rules_manager/rules_utility.py", "repo_name": "srikanthreddybms/railml_to_rbc", "src_encoding": "UTF-8", "text": "\"\"\"\nThis module to be used as utility (to store frequently/common used services) RailMl to RBC route map\nconversion tool\n\n@copyright:\nAll rights reserved. ©2016. ALSTOM (Bangalore, India).\nThis computer program may not be used, copied, distributed, corrected,\nmodified, translated, transmitted or assigned without ALSTOM's prior\nwritten authorization.\n\n@date : 18th July 2016\n@author: Sanjay Kalshetty, Srikanth Reddy\n\"\"\"\n\nfrom collections import OrderedDict\nfrom configparser import ConfigParser\nfrom lxml import etree\nimport src.globals.globalds as globalds\nimport os\nimport re\n\n\n# import of all rules script\n\nimport src.rules_manager.rules_to_define_node_and_connectors as node_and_connectors\n\n\nclass node ():\n @staticmethod\n def create_nodes(track, rule_name, num, element_ref=\"\"):\n if rule_name == \"NodesAndConnectorsAtBufferStop\" or rule_name == \"NodesAndConnectorsAtBoundaries\":\n if num == 1:\n if rule_name == \"NodesAndConnectorsAtBufferStop\":\n globalds.nodes.append(node_and_connectors.nc_buffer_stop.create_node_at_bufferstop_table8(track, 's'))\n elif rule_name == \"NodesAndConnectorsAtBoundaries\":\n globalds.nodes.append(\n node_and_connectors.nc_boundries.create_node_at_boundries_table10(track, 's',element_ref))\n\n\n globalds.TOTAL_NODES = globalds.TOTAL_NODES + 1\n else:\n letter_iter = globalds.LetterIter()\n node_counter = 0\n while num > 0:\n globalds.TOTAL_NODES = globalds.TOTAL_NODES + 1\n node_counter = node_counter + 1\n if num == 1:\n if rule_name == \"NodesAndConnectorsAtBufferStop\":\n globalds.nodes.append(\n node_and_connectors.nc_buffer_stop.create_node_at_bufferstop_table8(track, 's', node_counter))\n else:\n if rule_name == \"NodesAndConnectorsAtBufferStop\":\n globalds.nodes.append(\n node_and_connectors.nc_buffer_stop.create_node_at_bufferstop_table8(track, letter_iter.__next__(),\\\n node_counter))\n num = num - 1" }, { "alpha_fraction": 0.5545823574066162, "alphanum_fraction": 0.5661278963088989, "avg_line_length": 27.035715103149414, "blob_id": "6295cf837f64f8d4f258bed8a501a48e6bbe5e4a", "content_id": "ce58f9fa4fb19b63bec9a049f1d8fd48266f57f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12560, "license_type": "no_license", "max_line_length": 77, "num_lines": 448, "path": "/src/utility/utility.py", "repo_name": "srikanthreddybms/railml_to_rbc", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n\"\"\"\nUtilty for CRC32 calculation, SHA1Validation and Filehandler classes\n\n@copyright:\nAll rights reserved. ©2016. ALSTOM (Bangalore, India).\nThis computer program may not be used, copied, distributed, corrected,\nmodified, translated, transmitted or assigned without ALSTOM's prior\nwritten authorization.\n\n@author:\nSrikanth Reddy, Sanjay Kalshetty\n\"\"\"\n\nimport hashlib\n#import crc_algorithms\n\n\nclass CRC32Calculation:\n \"\"\"\n Used for crc32 calculation\n \"\"\"\n def __init__(self):\n \"\"\"\n Initialization method\n \"\"\"\n pass\n\n @staticmethod\n def calculate_crc2_file(f_path, logger):\n \"\"\"\n calculate crc2 for a file pointed by f_path\n and return it\n\n @type f_path: string\n @param f_path: File path whose crc needs to be calculated\n\n @type logger: Logger\n @param logger: Logger instance\n \"\"\"\n return CRC32Calculation.__check_file(\\\n f_path, 0x0FC22F87, 0xFFFFFFFF, 0x00000000, logger)\n\n @staticmethod\n def calculate_crcg_file(f_path, logger):\n \"\"\"\n calculate the crcg of the file pointed by f_path and\n return it\n\n @type f_path: string\n @param f_path: File path whose crc needs to be calculated\n\n @type logger: Logger\n @param logger: Logger instance\n \"\"\"\n return CRC32Calculation.__check_file(\\\n f_path, 0x1EDC6F41, 0xFFFFFFFF, 0x00000000, logger)\n\n @staticmethod\n def calculate_crc2(data, init_val=0xFFFFFFFF):\n \"\"\"\n calculate crc2 of binary data provided by data and return it\n\n @type data: string\n @param data: data whose crc needs to be calculated.\n\n @type init_val: integer\n @param init_val: Initial value used for crc calculation.\n \"\"\"\n if(data is None or init_val is None or data is \"\" or init_val is \"\"):\n return None\n\n return CRC32Calculation.__check_string(\\\n 0x0FC22F87, init_val, 0x00000000, data)\n\n @staticmethod\n def calculate_crcg(data, init_val=0xFFFFFFFF):\n \"\"\"\n calculate crcg of the binary data provided by data and return it\n\n @type data: string\n @param data: Data for which crcg needs to be calculated\n\n @type init_val: integer\n @param init_val: Initial value used for crc calculation.\n \"\"\"\n if(data is None or init_val is None or data is \"\" or init_val is \"\"):\n return None\n\n return CRC32Calculation.__check_string(\\\n 0x1EDC6F41, init_val, 0x00000000, data)\n\n @staticmethod\n def __check_string(in_poly, in_xor, in_xor_out, data):\n \"\"\"\n apply the crc32 algorithm on data and return it\n\n @type in_poly: int\n @param in_poly: Input polynomial\n\n @type in_xor: int\n @param in_xor: Input XOR\n\n @type in_xor_out: int\n @param in_xor_out: Output XOR\n\n @type data: string\n @param data: input data\n \"\"\"\n\n alg = crc_algorithms.Crc(width=32, poly=in_poly,\n reflect_in=False, xor_in=in_xor,\n reflect_out=False, xor_out=in_xor_out,\n table_idx_width=8)\n\n return alg.bit_by_bit(data)\n\n @staticmethod\n def __check_file(file_in, poly_in, in_xor, out_xor, logger):\n \"\"\"\n Calculate the CRC of a file.\n This algorithm uses the table_driven CRC algorithm.\n\n @type file_in: string\n @param file_in: Input file whose crc to calculate\n\n @type poly_in: int\n @param file_in: Input polynomial\n\n @type in_xor: int\n @param in_xor: Input XOR\n\n @type out_xor: int\n @param out_xor: Output XOR\n\n @type logger: Logger\n @param logger: Logger instance\n\n \"\"\"\n alg = crc_algorithms.Crc(width=32, poly=poly_in,\n reflect_in=False, xor_in=in_xor,\n reflect_out=False, xor_out=out_xor,\n table_idx_width=8)\n\n fdesc = FileHandler.open(file_in, 'rb', logger)\n\n data_read = FileHandler.read_single(fdesc, file_in, logger)\n prev_data = in_xor\n\n while data_read:\n prev_data = CRC32Calculation.__update_crc(\\\n alg, prev_data, data_read)\n data_read = FileHandler.read_single(fdesc, file_in, logger)\n\n FileHandler.close(file_in, fdesc, logger)\n\n return_data = prev_data ^ out_xor\n\n return return_data\n\n @staticmethod\n def __update_crc(alg, prev_data, inp_data):\n \"\"\"\n Update the CRC using the bit-by-bit-fast CRC algorithm.\n\n @type alg: crc_algorithms.Crc\n @param alg: crc_algorithm.Crc instance\n\n @type prev_data: int\n @param prev_data: input value to be used for next crc\n\n @type inp_data: str\n @param inp_data: Input data for which crc needs to be calculate\n \"\"\"\n for octet in inp_data:\n if not isinstance(octet, int):\n octet = ord(octet)\n for num in range(8):\n bit = prev_data & alg.MSB_Mask\n prev_data <<= 1\n if octet & (0x80 >> num):\n bit ^= alg.MSB_Mask\n if bit:\n prev_data ^= alg.Poly\n prev_data &= alg.Mask\n return prev_data\n\n\nclass SHA1Validation:\n \"\"\"\n Methods to validate/calculate sha1\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialization method\n \"\"\"\n self. __dummy = None\n\n @staticmethod\n def check_sha1(fpath, sha1_path, logger):\n \"\"\"\n check for sha1 of the filepath with the sha1 given in the filepath\n described by sha1_path returns True if sha1 is validated\n\n @type fpath: string\n @param fpath: file path whose crc needs to be calculated\n\n @type sha1_path: string\n @param sha1_path: path of file which contains sha1\n\n @type logger: Logger\n @param logger: Logger instance\n \"\"\"\n\n hex_sha = SHA1Validation.get_sha_string(fpath, logger)\n\n read_sha = str()\n sha_fd = FileHandler.open(sha1_path, 'r', logger)\n\n read_sha = read_sha.join((FileHandler.read_single(\\\n sha_fd, sha1_path, logger)).splitlines())\n\n read_sha = read_sha.replace(\" \", \"\")\n read_sha = read_sha.replace(\"\\t\", \"\")\n\n read_sha = read_sha.upper()\n\n FileHandler.close(sha1_path, sha_fd, logger)\n\n if(hex_sha == read_sha):\n params = list()\n params.append(hex_sha)\n params.append(read_sha)\n params.append(fpath)\n logger.log_progress(\"SHA1_VALIDATED\", params)\n return True\n else:\n params = list()\n params.append(hex_sha)\n params.append(read_sha)\n params.append(fpath)\n logger.log_error(\"ERR_SHA1_VALIDATION\", params)\n\n @staticmethod\n def check_multi_file_sha(fpath_list, sha1_path, logger):\n \"\"\"\n check sha1 for multiple files with the sha1 given in the\n sha1_path, returns True if SHA1 is validated\n\n @type fpath_list: list[string]\n @param fpath_list: paths of the files whose sha1 needs to be\n calculated\n\n @type sha1_path: string\n @param sha1_path: path of the file containing sha1\n\n @type logger: Logger\n @param logger: Logger instance\n \"\"\"\n hash_lib = hashlib.sha1()\n hex_sha1_file = \"\"\n hex_sha1 = None\n\n for file_inst in fpath_list:\n hex_sha1_file += SHA1Validation.get_sha_string(file_inst, logger)\n\n hash_lib.update(hex_sha1_file)\n hex_sha1 = (hash_lib.hexdigest()).upper()\n\n read_sha = str()\n\n file_fd = FileHandler.open(sha1_path, 'r', logger)\n\n read_sha = read_sha.join((FileHandler.read_single(\\\n file_fd, sha1_path, logger)).splitlines())\n\n read_sha = read_sha.replace(\" \", \"\")\n read_sha = read_sha.replace(\"\\t\", \"\")\n read_sha = read_sha.upper()\n\n FileHandler.close(sha1_path, file_fd, logger)\n\n if(hex_sha1 == read_sha):\n params = list()\n params.append(hex_sha1)\n params.append(read_sha)\n logger.log_progress(\"COMPLETENESS_SHA1_VALIDATED\", params)\n return True\n else:\n params = list()\n params.append(hex_sha1)\n params.append(read_sha)\n logger.log_error(\"ERR_COMPLETENESS_SHA1_VALIDATION\", params)\n\n @staticmethod\n def get_sha_string(f_path, logger):\n \"\"\"\n Get the SHA1 string of file pointed by f_path\n\n @type f_path: string\n @param f_path: File path for which the SHA1 is to be calculated\n\n @type logger: Logger\n @param logger: Logger instance\n \"\"\"\n f_desc = FileHandler.open(f_path, 'rb', logger)\n hash_lib = hashlib.sha1()\n\n file_data = FileHandler.read_single(f_desc, f_path, logger)\n while(file_data):\n hash_lib.update(file_data)\n file_data = FileHandler.read_single(f_desc, f_path, logger)\n\n FileHandler.close(f_path, f_desc, logger)\n hex_data = hash_lib.hexdigest()\n return hex_data.upper()\n\n\nclass FileHandler:\n \"\"\"\n FileHandler is class used to do file handling operations\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialization method\n \"\"\"\n self. __dummy = None\n\n @staticmethod\n def open(fpath, mode, logger):\n \"\"\"\n Helper method to open a file, default mode is 'r'\n Only r, rb, w and wb modes are supported\n\n @type fpath: string\n @param fpath: File to open\n\n @type mode: string\n @param mode: mode of file to open\n\n @type logger: Logger\n @param logger: Logger instance\n \"\"\"\n if(mode is None):\n mode = \"r\"\n\n elif(mode != 'r' and mode != 'rb' and mode != 'w' and mode != 'wb'):\n params = list()\n params.append(mode)\n params.append(fpath)\n logger.log_error(\"ERR_INTERNAL_FILEMODE_INVALID\", params)\n\n try:\n file_fd = open(fpath, mode)\n except IOError as err:\n params = list()\n params.append(str(err))\n params.append(fpath)\n logger.log_error(\"ERR_FILE_IO_OPEN\", params)\n\n return file_fd\n\n @staticmethod\n def read_single(file_desc, f_path, logger):\n \"\"\"\n Helper method to make a single read operation\n\n @type file_desc: File descriptor\n @param file_desc: File descriptor\n\n @type f_path: string\n @param f_path: File path needed to log an error\n\n @type logger: Logger\n @param logger: Logger instance\n \"\"\"\n try:\n return file_desc.read()\n except IOError as err:\n FileHandler.close_noex(file_desc)\n params = list()\n params.append(str(err))\n params.append(f_path)\n logger.log_error(\"ERR_FILE_IO_READ\", params)\n\n @staticmethod\n def write(file_desc, data, f_path, logger):\n \"\"\"\n Helper method to write to file\n\n @type file_desc: File descriptor\n @param file_desc: File descriptor\n\n @type data: string\n @param data: data to write\n\n @type f_path: string\n @param f_path: File path, needed to log an error\n\n @type logger: Logger\n @param logger: Logger instance\n \"\"\"\n try:\n return file_desc.write(data)\n except IOError as err:\n FileHandler.close_noex(file_desc)\n params = list()\n params.append(str(err))\n params.append(f_path)\n logger.log_error(\"ERR_FILE_IO_WRITE\", params)\n\n @staticmethod\n def close(file_path, file_des, logger):\n \"\"\"\n Helper method to close a file\n\n @type file_path: string\n @param file_path: File to close\n\n @type file_des: File descriptor\n @param file_des: File descriptor\n\n @type logger: Logger\n @param logger: Logger instance\n \"\"\"\n\n try:\n file_des.close()\n except IOError as err:\n params = list()\n params.append(str(err))\n params.append(str(file_path))\n logger.log_error(\"ERR_FILE_IO_CLOSE\", params)\n\n @staticmethod\n def close_noex(file_des):\n \"\"\"\n close without exception\n\n @type file_des: File descriptor\n @param file_des: File descriptor\n \"\"\"\n try:\n file_des.close()\n except BaseException:\n pass" }, { "alpha_fraction": 0.72273188829422, "alphanum_fraction": 0.7329255938529968, "avg_line_length": 27.05714225769043, "blob_id": "8bdd17cc0c9a0534704e85c6887ce33cdb391586", "content_id": "0da44523406811da37e2d174ef178ac49d2762c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 982, "license_type": "no_license", "max_line_length": 93, "num_lines": 35, "path": "/src/rules_manager/rules_to_define_buffer_stops.py", "repo_name": "srikanthreddybms/railml_to_rbc", "src_encoding": "UTF-8", "text": "\"\"\"\nRules for Define track occupations\nThis module is used to initiate the rules manipulations of rules related to track occupations\ncreation under rules manager component of RailMl to RBC route map conversion tool\n\n@copyright:\nAll rights reserved. ©2016. ALSTOM (Bangalore, India).\nThis computer program may not be used, copied, distributed, corrected,\nmodified, translated, transmitted or assigned without ALSTOM's prior\nwritten authorization.\n\n@date : 18th July 2016\n@author: Sanjay Kalshetty, Srikanth Reddy\n\"\"\"\n\nimport re\nfrom collections import OrderedDict\nimport collections\nfrom lxml import etree\nfrom itertools import groupby\nimport src.globals.globalds as globalds\n\n\nclass buffer_stops():\n \"\"\"\n This class used to manage creation of buffer stops in RBC output file\n \"\"\"\n\n @staticmethod\n def execute(rule_data, genparams, logger):\n # print(rule_data, genparams, logger)\n for each_track in rule_data:\n #print(each_track)\n pass\n pass" }, { "alpha_fraction": 0.5645569562911987, "alphanum_fraction": 0.5688969492912292, "avg_line_length": 31.162790298461914, "blob_id": "147e7134f8fea81c5e2a711c8220d114ce52ed56", "content_id": "fa209efd0bb48326260799ad3891c74a079758e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2766, "license_type": "no_license", "max_line_length": 78, "num_lines": 86, "path": "/src/parser_engine/parser.py", "repo_name": "srikanthreddybms/railml_to_rbc", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n\"\"\"\nThis file is used for different types of parsing activities.\nIt is used to read and read lxml.doc type objects\n\n@copyright:\nAll rights reserved. ©2016. ALSTOM (Bangalore, India).\nThis computer program may not be used, copied, distributed, corrected,\nmodified, translated, transmitted or assigned without ALSTOM's prior\nwritten authorization.\n\n@date : 18th July 2016\n@author: Sanjay Kalshetty, Srikanth Reddy\n\"\"\"\n\nimport os\nimport re\nfrom collections import OrderedDict\nfrom lxml import etree\n\n\n\nclass XMLFileParser:\n \"\"\"\n This class is used to validate a list of xml files against a list of xsd\n files\n \"\"\"\n\n def __init__(self, ip_xml_path, logger, validate=True):\n \"\"\"\n This initializer takes in the list of xml paths and list of xsd paths.\n It then parses each xml file and validates each xml file against each\n xsd file if validate is True. If no xsd files are specified then no\n validation against xsd is done.\n\n @type ip_xml_path: list[string]\n @param ip_xml_path: Input xml path\n\n @type ip_xsd_file: list[string]\n @param ip_xsd_file: Input XSD path\n\n @type logger: Logger\n @param logger: Logger instance\n\n @type validate: boolean\n @param validate: if true, then validate the xml files against xsd\n files.\n \"\"\"\n\n try:\n\n # check whether the file exists\n if (not os.path.isfile(ip_xml_path) or \\\n not os.path.exists(ip_xml_path)):\n params = list()\n params.append(ip_xml_path)\n params.append(\"XML path\")\n logger.log_error(\"ERR_INVALID_FILE_PATH\", params)\n\n try:\n params = list()\n params.append(ip_xml_path)\n logger.log_progress(\"PARSING_XML_FILE_INFO\", params)\n # doc = libxml2.parseFile(ip_xml_path[xml_counter])\n self._xml_file = etree.parse(ip_xml_path)\n # root = tree.getroot()\n\n except BaseException:\n params = list()\n error = XMLFileParser.__get_error()\n\n if error is not None:\n params.append(ip_xml_path)\n params.append(error.line())\n params.append(error.message())\n logger.log_error(\"ERR_XML_PARSE\", params)\n else:\n params.append(ip_xml_path)\n params.append('Not Available')\n params.append('Not Available')\n print(\"Sanjay\")\n logger.log_error(\"ERR_XML_PARSE\", params)\n\n except BaseException:\n # free up resources and re raise exception\n raise" }, { "alpha_fraction": 0.6443958282470703, "alphanum_fraction": 0.6470885276794434, "avg_line_length": 37.34193420410156, "blob_id": "68aaf6e5712fe7b0a0eb8399072404dc1a1b0d42", "content_id": "48d6abc50b199aea3939a9260d373b7a33332d3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5945, "license_type": "no_license", "max_line_length": 95, "num_lines": 155, "path": "/src/processor_engine/processorengine.py", "repo_name": "srikanthreddybms/railml_to_rbc", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n\"\"\"\n\nThe Processor Engine is designed using Façade Design pattern.\nThe complex implementation lies hidden within the context of one member method\nbegin_operation ().\nThe Processor Engine makes use of Interface Engine to run the tool in 2 stages.\n-The first stage gets the input file names, then it makes use of Interface Engine to\n read the input configuration file and apply the constraints on the input railMl xml\n-The second stage execute the rules of each sections\n\n@copyright:\nAll rights reserved. ©2016. ALSTOM (Bangalore, India).\nThis computer program may not be used, copied, distributed, corrected,\nmodified, translated, transmitted or assigned without ALSTOM's prior\nwritten authorization.\n\n@date : 18th July 2016\n@author: Sanjay Kalshetty, Srikanth Reddy\n\"\"\"\n\nimport os\n\nfrom ..globals import paths\nfrom ..globals import globalds\nimport src.rules_manager.rules_processor as rules_processor\nimport src.parser_engine.write_output as output_rbc\nimport src.constraint_manager.constraint_processor as cstr_proc\nimport src.rules_manager.complementary_rules as compltr_rules\nclass ProcessorEngine:\n \"\"\"\n Processor Engine is the entry point to the diamond compiler. This class\n knows what are the upper layers to be executed, but does not know how to\n do it. It gets the command line options and initiates the stages to be\n executed.It then commands the Interface Engine to initiate the necessary\n process.\n\n \"\"\"\n\n \"\"\"List of output identifiers to be written\"\"\"\n\n def __get_sorted_list(self, file_list):\n \"\"\"\n This is the first stage of the tool. It is used to check SHA1 for all\n the input files and generate the Middleware bin and temp files\n\n @type file_list: list[string]\n @param file_list: list of file paths\n \"\"\"\n if(file_list is not None and len(file_list) > 1):\n ret_file_list = list()\n dict_file_path = dict()\n\n for file_path in file_list:\n file_name = os.path.basename(file_path)\n if(file_name not in dict_file_path.keys()):\n dict_file_path[file_name] = file_path\n else:\n logger = self.__global_ds.get_instances(\\\n globalds.GlobalInstanceIden.E_INST_LOGGER)\n params = list()\n params.append(file_name)\n logger.log_error(\"ERR_DUPLICATE_FILENAME\", params)\n\n filelist_sort = dict_file_path.keys()\n filelist_sort.sort()\n\n for file_path in filelist_sort:\n ret_file_list.append(dict_file_path[file_path])\n\n return ret_file_list\n else:\n return file_list\n\n def __init__(self, global_ds):\n \"\"\"\n Initialization method\n\n @type global_ds: Global\n @param global_ds: global datastructure\n \"\"\"\n self.__global_ds = global_ds\n \"\"\"Global data structure\"\"\"\n\n logger = global_ds.get_instances(globalds.GlobalInstanceIden.\\\n E_INST_LOGGER)\n\n def begin_operation(self):\n \"\"\"\n This method is entry point to the process. It will initiate the process\n within Processor Engine. If success it will return true. On any of the\n failures the method will throw NotSuccessfulException. The Processor\n Engine follows the façade design pattern. All the algorithm for the\n tool is implemented in the ProcessorEngine. It makes use of different\n classes to complete the work of the tool\n \"\"\"\n self.generate_rbc_data()\n\n def generate_rbc_data(self):\n \"\"\"\n start the process of the middleware file generation and output file\n generation\n \"\"\"\n\n app_paths = self.__global_ds.get_instances(\\\n globalds.GlobalInstanceIden.E_INST_APP_PATHS)\n\n # get internal file paths\n app_file_paths = app_paths.get_instances( \\\n paths.ApplicationInstanceIDEnum.INST_INT)\n\n # get internal config xml file\n config_path = app_file_paths.get_internal_file_path( \\\n paths.InternalFileIDEnum.E_INT_CONFIG_FILE)\n # get internal RBC default xml file\n rbc_default_path = app_file_paths.get__rbc_default_file( \\\n paths.InternalFileIDEnum.E_INT_RBC_DEFAULT_OUT_FILE)\n\n\n # Get Input railaml parameter xml\n input_file_paths = self.__global_ds.get_instances( \\\n globalds.GlobalInstanceIden.E_INST_INIT)\n\n inputs_file_path = input_file_paths.get_conf_desc_path()\n\n output_path = input_file_paths.get_op_file_path()\n\n logger = self.__global_ds.get_instances(\\\n globalds.GlobalInstanceIden.E_INST_LOGGER)\n\n files_path_all = {'railml':inputs_file_path[0],\\\n 'rbcgen':inputs_file_path[1],\\\n 'config':config_path,\\\n 'rbcdefault':rbc_default_path, \\\n 'rbcoutput': output_path}\n\n\n rules_proc = rules_processor.rules_proc (files_path_all, logger)\n xpaths = rules_proc.extract_ruleinfo_from_config_file()\n genparams = rules_proc.extract_rbc_general_parameters()\n\n rule_eng = rules_processor.rule_engine(files_path_all, xpaths, logger)\n tracks_info_for_rules = rule_eng.extract_trackinfo()\n\n # Apply constraint on input railMl b calling constraint scheculer\n cstr_mgr= cstr_proc.constraint_proc(tracks_info_for_rules,logger)\n cstr_mgr.cstr_scheduler()\n\n #Execute the rules by calling rule scheduler\n rule_executer = rules_processor.execute_rules(tracks_info_for_rules, genparams, logger)\n rule_executer.rules_scheduler()\n\n compltr_rules.apply_complementary_rules.complementary_rules_nodes_and_connectors()\n Rbc_output_rbc = output_rbc.write_output(files_path_all, genparams, logger)\n Rbc_output_rbc.write_nodes_to_output_rbc(globalds.nodes)" }, { "alpha_fraction": 0.5607461929321289, "alphanum_fraction": 0.5643517971038818, "avg_line_length": 30.8799991607666, "blob_id": "e68ce13d3e88649416c85f2a11ceb3312e3be320", "content_id": "3a9ff63f80934f1d7dca2273f2190ed1177be890", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6380, "license_type": "no_license", "max_line_length": 80, "num_lines": 200, "path": "/src/interface_engine/interfaces.py", "repo_name": "srikanthreddybms/railml_to_rbc", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n\"\"\"\nThe Interface Engine deals with specific parsing of files and retrieving data:\n 1. It knows how to parse different specific files like internal\n configuration xml files or input xml files or writing to output RBC file or\n temporary files.\n 2. It uses generic classes present within Parser Engine to complete its job\n 3. It is responsible for retrieving the paths of all the input files\n required for the system.\n\n@copyright:\nAll rights reserved. ©2016. ALSTOM (Bangalore, India).\nThis computer program may not be used, copied, distributed, corrected,\nmodified, translated, transmitted or assigned without ALSTOM's prior\nwritten authorization.\n\n@date : 18th July 2016\n@author: Sanjay Kalshetty, Srikanth Reddy\n\"\"\"\n\nimport os\nimport time\n\nfrom ..parser_engine import parser\nfrom ..globals import paths\nfrom ..globals import globalds\nfrom ..utility import utility\n\n\nclass InputFilePathCreator:\n \"\"\"\n This class is used to parse the input config xml files\n UserSafeConfDescriptor[_index].xml to create the InputFilePaths instance.\n \"\"\"\n\n def __init__(self, inp_xml_path, logger):\n \"\"\"\n Initialization methods\n\n @type inp_xml_path: list[string]\n @param inp_xml_path: input xml file paths\n\n @type inp_xsd_path: string\n @param inp_xsd_path: input xsd file path\n\n @type logger: Logger\n @param logger: logger instance used for logging messages\n \"\"\"\n\n self.__logger = logger\n \"\"\"Logger instance\"\"\"\n\n self.inp_xml_path = inp_xml_path\n\n self.__inp_parser = list()\n \"\"\"XML File parser instance\"\"\"\n\n self.__input_file_path_instance = None\n \"\"\"storage for input file path\"\"\"\n\n for inp_xml in inp_xml_path:\n if(inp_xml_path is None or len(inp_xml_path) == 0):\n params = list()\n params.append(\"Input RailMl file\")\n logger.log_error(\"ERR_INTERNAL_MISSING_PARAM\", params)\n\n xml_parser = parser.XMLFileParser(inp_xml, \\\n logger)\n self.__inp_parser.append(xml_parser._xml_file)\n\n def get_input_file_paths(self):\n \"\"\"\n This method returns a globals.InputFilePaths type object from the\n internal input configuration file specified.\n \"\"\"\n\n params = list()\n self.__logger.log_progress(\"GET_INPUT_FILE_PATHS_STARTED\", params)\n\n if(self.__input_file_path_instance is None):\n self.make_input_file_paths()\n\n params = list()\n self.__logger.log_progress(\"GET_INPUT_FILE_PATHS_DONE\", params)\n\n return self.__input_file_path_instance\n\n def make_input_file_paths(self):\n \"\"\"\n This method makes a globals.InputFilePaths type object from the\n internal input configuration file specified.\n \"\"\"\n\n inp_file_paths = paths.InputFilePaths(self.__logger)\n\n file_id_list = [\\\n paths.InputFileIdentifierEnum.E_INP_RAIML,\\\n paths.InputFileIdentifierEnum.E_INP_RBC_GEN_PARAM\\\n ]\n\n #below are the list of file identifiers which needs to be fetched\n #within the configuration descriptor files\n\n list_of_file_id = [\\\n paths.InputFileIdentifierEnum.E_INP_RAIML,\\\n paths.InputFileIdentifierEnum.E_INP_RBC_GEN_PARAM\\\n ]\n\n for file_id in list_of_file_id:\n file_path_id = 0\n sha_path_list = list()\n file_path_list = list()\n\n inp_file_paths.set_input_file_path(file_id, \\\n self.inp_xml_path, sha_path_list)\n\n self.__input_file_path_instance = inp_file_paths\n\n def __sort_file_name(self, file_list):\n \"\"\"\n Gets sorted list of file names\n\n @type file_list: list[string]\n @param file_list: input file paths\n \"\"\"\n\n if(len(file_list) > 1):\n ret_file_list = list()\n dict_file_path = dict()\n\n for file_path in file_list:\n file_name = os.path.basename(file_path)\n if(file_name not in dict_file_path.keys()):\n dict_file_path[file_name] = file_path\n else:\n params = list()\n params.append(file_name)\n self.__logger.log_error(\"ERR_DUPLICATE_FILENAME\", params)\n\n filelist_sort = dict_file_path.keys()\n filelist_sort.sort()\n\n for file_path in filelist_sort:\n ret_file_list.append(dict_file_path[file_path])\n\n return ret_file_list\n else:\n return file_list\n\n def __get_file_path(self, ret, join_path, sha_path_list, \\\n file_path_list):\n \"\"\"\n Gets the file path\n\n @type ret: list[string]\n @param ret: input xml file paths\n\n @type join_path: string\n @param join_path: path to join if path is not absolute\n\n @type file_path_list: list[string]\n @param file_path_list: input file paths\n\n @type sha_path_list: list[string]\n @param sha_path_list: paths list for sha1 files\n \"\"\"\n\n for i in range(0, len(ret)):\n path = ret[i].content\n path = path.strip()\n\n if(not os.path.isabs(path)):\n path = os.path.join(join_path, path)\n path = os.path.abspath(path)\n\n path = os.path.normpath(path)\n path = path.replace(\"\\\\\", \"/\")\n\n if(not os.path.exists(path)):\n params = list()\n params.append(path)\n self.__logger.log_error(\"ERR_INVALID_USERSAFE_FILE_PATH\", \\\n params)\n else:\n params = list()\n params.append(path)\n self.__logger.log_progress(\"INP_FILE_PARSE\", params)\n\n if(not os.path.exists(path + \".sha1\")):\n params = list()\n params.append(str(path) + \".sha1\")\n self.__logger.log_error(\"ERR_INVALID_USERSAFE_FILE_PATH\", \\\n params)\n else:\n params = list()\n params.append(path + \".sha1\")\n self.__logger.log_progress(\"INP_FILE_PARSE\", params)\n\n file_path_list.append(path)\n sha_path_list.append(path + \".sha1\")\n\n\n\n" }, { "alpha_fraction": 0.576583206653595, "alphanum_fraction": 0.5791605114936829, "avg_line_length": 30.040000915527344, "blob_id": "3e2727147249df3e977f48c22032e2abbb0afcd8", "content_id": "2ba9154e67a2625286741e25945a7779990baabf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5433, "license_type": "no_license", "max_line_length": 79, "num_lines": 175, "path": "/src/interface_engine/commandlineinterface.py", "repo_name": "srikanthreddybms/railml_to_rbc", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n\"\"\"\nCommand Line interface takes care of interfacing the command line parameters\nThis file contains classes to read the command line interface\n\n@copyright:\nAll rights reserved. ©2016. ALSTOM (Bangalore, India).\nThis computer program may not be used, copied, distributed, corrected,\nmodified, translated, transnew_path\n\n@date : 18th July 2016\n@author: Sanjay Kalshetty, Srikanth Reddy\n\"\"\"\n\nimport re\nimport os\n\nimport optparse\n\nfrom ..globals import globalds\nfrom ..globals import logger as logger_ns\n\n\nclass CommandLineInterfacer:\n \"\"\"\n CommandLineInterface class is used to parse the command line and\n get the various options\n \"\"\"\n\n def __init__(self, logger):\n \"\"\"\n Initialization module\n\n @type logger: Logger\n @param logger: Logger instance\n \"\"\"\n parser = optparse.OptionParser()\n\n parser.add_option(\"-i\", \"--id\", dest=\"file_inputs\",\\\n help=\"Specify input directory paths. The paths must be given\\\n in inverted commas and each path seperated by space\\\n and each path must have read/write permissions\")\n\n parser.add_option(\"-o\", \"--od\", dest=\"output_path\",\n help=\"Specify output directory. This must be a single\\\n directory path and must have read/write permissions\")\n\n parser.add_option(\"-c\", \"--comp\", dest=\"completeness_file\",\n help=\"Specify completeness file.\")\n\n parser.add_option(\"-l\", \"--lang\", dest=\"lang\",\n help=\"Specify the language, default language is 'eng'\")\n\n self.__parser = parser\n \"\"\"Parser instance\"\"\"\n\n self.__logger = logger\n \"\"\"Logger instance\"\"\"\n\n self.__clo = None\n \"\"\"CommandLineOptions instance\"\"\"\n\n @staticmethod\n def __get_full_path(path):\n \"\"\"\n gets the full path from path\n\n @type path: string\n @param path: file path\n \"\"\"\n path = str.strip(path)\n if(not os.path.isabs(path)):\n path = os.path.abspath(path)\n\n path = os.path.normpath(path)\n path = path.replace(\"\\\\\", \"/\")\n\n return path\n\n @staticmethod\n def __check_opt_val_validity(path):\n \"\"\"\n Check validity of the path\n\n @type path: string\n @param path: file path\n \"\"\"\n if(path[0] == ' ' or \\\n path[0] == '-'):\n return False\n\n return True\n\n def fill_cmd_line_options(self, logger):\n \"\"\"\n This class provides methods to retrieve data from command line\n interface.\n\n @type logger: Logger\n @param logger: Logger instance\n \"\"\"\n try:\n inst_options = self.__parser.parse_args()\n options = inst_options[0]\n except BaseException:\n params = list()\n logger.log_error(\"ERR_CMD_LINE_PARSE\", params)\n raise logger_ns.NotSuccessfulException(\"Cannot parse command line\")\n\n clo = globalds.CommandLineOptions(logger)\n\n #fill input file paths\n input_file_paths_list = list()\n\n if options.file_inputs is None or \\\n options.file_inputs == '' or \\\n CommandLineInterfacer.__check_opt_val_validity(\\\n options.file_inputs) is False:\n input_file_paths_list.append(\"INVALID_PATH\")\n else:\n file_paths = re.split(',', options.file_inputs)\n\n for path in file_paths:\n if(path is not ' '):\n path = CommandLineInterfacer.__get_full_path(path)\n input_file_paths_list.append(path)\n\n #fill output file paths\n output_file_path_list = list()\n if options.output_path is not None and \\\n options.output_path != '' and \\\n CommandLineInterfacer.__check_opt_val_validity(\\\n options.output_path):\n output_path = options.output_path\n output_path = CommandLineInterfacer.__get_full_path(output_path)\n\n output_file_path_list.append(output_path)\n else:\n output_file_path_list.append(\"INVALID_PATH\")\n\n #fill language\n lang = list()\n if options.lang is not None:\n lang.append(options.lang)\n else:\n lang.append(\"NO_LANG\")\n\n #fill completeness path\n completeness_file_path_list = list()\n if (options.completeness_file is not None and \\\n options.completeness_file is not '' and \\\n CommandLineInterfacer.__check_opt_val_validity(\\\n options.completeness_file)):\n completeness_file = CommandLineInterfacer.\\\n __get_full_path(options.completeness_file)\n completeness_file_path_list.append(completeness_file)\n else:\n completeness_file_path_list.append(\"INVALID_PATH\")\n\n #Now set the command line options\n clo.set_option_value(globalds.OptionsEnum.E_OPT_LANG, lang)\n clo.set_option_value(globalds.OptionsEnum.E_OPT_INP_DIR, \\\n input_file_paths_list)\n clo.set_option_value(globalds.OptionsEnum.E_OPT_OP_DIR, \\\n output_file_path_list)\n clo.set_option_value(globalds.OptionsEnum.E_OPT_COMP, \\\n completeness_file_path_list)\n\n self.__clo = clo\n\n def get_cmd_line_options(self):\n \"\"\"\n Gets the command line options\n \"\"\"\n return self.__clo\n" }, { "alpha_fraction": 0.5711869597434998, "alphanum_fraction": 0.5724977850914001, "avg_line_length": 32.88252258300781, "blob_id": "4137bf3cf43c97649ddf9ef5b0e9efaadeb53e0c", "content_id": "e6b95bd09095dffb4ccd55828669711554afded1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 23650, "license_type": "no_license", "max_line_length": 109, "num_lines": 698, "path": "/src/globals/logger.py", "repo_name": "srikanthreddybms/railml_to_rbc", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n\"\"\"\nThis module is used for storing and managing log messages such as warning, informationa and errors\n\n@copyright:\nAll rights reserved. ©2016. ALSTOM (Bangalore, India).\nThis computer program may not be used, copied, distributed, corrected,\nmodified, translated, transmitted or assigned without ALSTOM's prior\nwritten authorization.\n\n@date : 18th July 2016\n@author: Sanjay Kalshetty, Srikanth Reddy\n\"\"\"\n\nimport os\nimport sys\nimport datetime\n\nimport src.globals.loggerdict as loggerdict\nimport src.globals.globalconstants as globalconstants\n\n\nclass NotSuccessfulException(Exception):\n \"\"\"\n This class contains the log message id, type(error, warning or progress)\n and input parameters required to output the messages\n \"\"\"\n\n def __init__(self, msg):\n \"\"\"\n Initialization module\n\n @type msg: string\n @param msg: message stored\n \"\"\"\n Exception.__init__(self, msg)\n self.__msg = msg\n \"\"\"Message stored\"\"\"\n\n def get_msg(self):\n \"\"\"\n returns the stored message\n \"\"\"\n return self.__msg\n\n def set_msg(self, msg):\n \"\"\"\n changes the original message\n\n @type msg: string\n @param msg: The message stored\n \"\"\"\n self.__msg = msg\n\n\nclass LogMsg:\n \"\"\"\n This class contains the log message id, type(error, warning or progress)\n and input parameters required to output the messages\n \"\"\"\n\n def getTimeStamp(self):\n tStamp = datetime.datetime.now()\n tStamp = str(tStamp).replace(\"-\", \"/\")\n tStamp = str(tStamp).replace(\" \", \"-\")\n tStamp = tStamp.split(\".\")[0]\n return tStamp\n\n def __init__(self, msg_type, params, msg_id):\n self.__timestamp = None\n\n \"\"\"\n Initialization module\n\n @type msg_type: string\n @param msg_type: Type of the message(err, warn or prog)\n\n @type params: list\n @param params: List of parameters required for the message\n\n @type msg_id: string\n @param msg_id: message identifier\n \"\"\"\n self.__msg_type = None\n \"\"\"Type of the message(err, warn or prog)\"\"\"\n\n self.__params = None\n \"\"\"List of input parameters required for writing the message\"\"\"\n\n self.__msg_id = None\n \"\"\"This contains the unique msg id\"\"\"\n\n self.set_msg(msg_type, params, msg_id)\n\n def set_msg(self, msg_type, params, msg_id):\n \"\"\"\n sets the message\n\n @type msg_type: string\n @param msg_type: Type of the message(err, warn or prog)\n\n @type params: list[string]\n @param params: List of parameters required for the message\n\n @type msg_id: string\n @param msg_id: message identifier\n \"\"\"\n self.__msg_type = msg_type\n \"\"\"Type of the message(err, warn, prog)\"\"\"\n\n self.__params = params\n \"\"\"Parameters required for printing the message\"\"\"\n\n self.__msg_id = msg_id\n \"\"\"The message identifier\"\"\"\n\n self.__timestamp = self.getTimeStamp()\n\n def get_msg(self):\n \"\"\"\n Get the message stored in a tuple(msg_type, msg_id, params)\n \"\"\"\n return (self.__timestamp, self.__msg_type, self.__msg_id, self.__params)\n\n\nclass LoggerEngine:\n \"\"\"\n LoggerEngine is used to do logger activities like checking if any specific\n language is supported and to get the various dictionaries associated with\n that.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialization module\n \"\"\"\n\n self.logger_store = loggerdict.LoggerStore()\n \"\"\"Logger store instance for retrieving the log message dictionaries\"\"\"\n\n def is_lang_supported(self, lang):\n \"\"\"\n Check if the passed language is supported using LoggerStore\n\n @type lang: string\n @param lang: language string\n \"\"\"\n list_supported_lang = self.logger_store.get_lang_list()\n\n for supported_lang in list_supported_lang:\n if supported_lang == lang:\n return True\n\n return False\n\n def get_dict(self, lang):\n \"\"\"\n This method gets the dictionaries error, warning and progress for the\n passed language identifier\n\n @type lang: string\n @param lang: The language for which the dictionary needs to be\n retrieved\n \"\"\"\n dict_list = list()\n\n #see if the language is supported\n #if not supported return empty list\n if self.is_lang_supported(lang):\n log_dict = self.logger_store.get_lang_dict(lang)\n dict_list.append(log_dict.get_err_dict())\n dict_list.append(log_dict.get_warn_dict())\n dict_list.append(log_dict.get_prog_dict())\n\n return dict_list\n\n\nclass Logger:\n \"\"\"\n This is base class for all type of error classes. It will be used to\n log messages. It contains err_msg, warn_msg and progress_msg which is a\n pre-defined dictionary which contains predefined messages for specific\n messages. It also provides the errors in different languages.\n \"\"\"\n\n @staticmethod\n def _fill_msg(str_to_replace, replace_str, params):\n \"\"\"\n Internal method to replace all occurences of str_to_replace within\n replace_str with values from params[]. so the 1st occurence of\n replace_str is replaced with params[0], second with params[1] and\n so on.\n\n @type str_to_replace: string\n @param str_to_replace: string that needs to be replaced\n\n @type replace_str: string\n @param replace_str: sub string that needs to be modified\n\n @type params: list[string]\n @param params: list of parameters\n \"\"\"\n new_str = replace_str\n\n if(params is not None):\n if(len(params) > 0):\n for param in params:\n new_str = new_str.replace(str_to_replace, str(param), 1)\n\n return new_str\n\n def __init__(self):\n \"\"\"\n Initialization module\n \"\"\"\n self._logger_engine = LoggerEngine()\n \"\"\"Logger engine instance\"\"\"\n\n #initialize the log file name\n self._log_file_name = \"log.txt\"\n \"\"\"Log file name\"\"\"\n\n glob_const = globalconstants.GlobalConstants()\n\n #initialize the message dictionaries\n dict_list = self._logger_engine.get_dict(glob_const.get_lang())\n\n if(len(dict_list) != 3):\n print (self.getTimeStamp() + \": \" + \"Error :: STDIO_INTERNAL_APPLICATION_ERR: Logger \" + \\\n \"messages not available for lang:\" + str(glob_const.get_lang()))\n\n raise NotSuccessfulException(\"Execution Failed\")\n\n #initialize the message dictionaries\n self._err_msg = dict_list[0]\n \"\"\"Error message dictionary\"\"\"\n self._warn_msg = dict_list[1]\n \"\"\"Warning message dictionary\"\"\"\n self._prog_msg = dict_list[2]\n \"\"\"Progress message dictionary\"\"\"\n\n #default current language\n self._current_language = glob_const.get_lang()\n \"\"\"Current language\"\"\"\n\n def get_lang(self):\n \"\"\"\n return the language string\n \"\"\"\n return self._current_language\n\n def change_lang(self, language):\n \"\"\"\n change the language to the specified \"language\" if possible\n\n @type language: string\n @param language: language to be used\n \"\"\"\n if(language is not \"NO_LANG\"):\n if not self._logger_engine.is_lang_supported(language):\n return False\n elif(language != self._current_language):\n #initialize the message dictionaries\n dict_list = self._logger_engine.get_dict(language)\n #initialize the message dictionaries\n self._err_msg = dict_list[0]\n self._warn_msg = dict_list[1]\n self._prog_msg = dict_list[2]\n\n return True\n\n return True\n\n def close(self):\n \"\"\"\n method, to be overridden by derived classes\n \"\"\"\n self._err_msg = None\n self._prog_msg = None\n self._warn_msg = None\n\n\nclass ListLogger(Logger):\n \"\"\"\n This class is used to store log messages to an internal list. The messages\n are in LogMsg format. This class is used as a pre-logger, meaning till such\n time the FileLogger instance is not successfully created. On unsuccessful\n creation of the FileLogger the log messages are output on to the screen\n as well as an internal log file log_backup.txt which will get stored at\n the same location where the diamond.exe is present\"\"\"\n\n def getTimeStamp(self):\n tStamp = datetime.datetime.now()\n tStamp = str(tStamp).replace(\"-\", \"/\")\n tStamp = str(tStamp).replace(\" \", \"-\")\n # tStamp = tStamp.replace(\":\", \"-\")\n tStamp = tStamp.split(\".\")[0]\n return tStamp\n\n def __init__(self):\n \"\"\"\n Initialization method\n \"\"\"\n Logger.__init__(self)\n self.__log_list = list()\n \"\"\"List of Log instances\"\"\"\n\n param = list()\n\n glob_constants = globalconstants.GlobalConstants()\n\n param.append(glob_constants.get_tool_name())\n param.append(glob_constants.get_tool_version())\n self.log_progress(\"HEADER_INFO\", param)\n\n def log_error(self, msg_id, params):\n \"\"\"\n method used to log errors. It takes in the message id which is a\n unique id for all types of errors, warnings and progress.\n It also takes in a list of strings as input which is used in output of\n the messages.\n\n @type msg_id: string\n @param msg_id: message identifier\n\n @type params: list[string]\n @param params: list of parameters used for logging\n \"\"\"\n self.__log_list.append(LogMsg(\"err\", params, msg_id))\n\n def log_warning(self, msg_id, params):\n \"\"\"\n Method used to log warnings. It takes in the message id which is a\n unique id for all types of errors, warnings and progress. It also takes\n in a list of strings as input which is used in output of the messages.\n\n @type msg_id: string\n @param msg_id: message identifier\n\n @type params: list[string]\n @param params: list of parameters used for logging\n \"\"\"\n self.__log_list.append(LogMsg(\"warn\", params, msg_id))\n\n def log_progress(self, msg_id, params):\n \"\"\"\n method used to log progress message which indicates the progress stage.\n It takes in the message id which is a unique id for all types of\n errors, warnings and progress. It also takes in a list of strings as\n input which is used in output of the messages.\n\n @type msg_id: string\n @param msg_id: message identifier\n\n @type params: list[string]\n @param params: list of parameters used for logging\n \"\"\"\n self.__log_list.append(LogMsg(\"prog\", params, msg_id))\n\n def get_log_list(self):\n \"\"\"\n returns log_list\n \"\"\"\n return self.__log_list\n\n def __get_msg(self, msg):\n \"\"\"\n get the string to write from msg and send back, returns string\n\n @type msg: string\n @param msg: message to be retrieved\n \"\"\"\n (timestamp, msg_type, msg_id, msg_params) = msg.get_msg()\n str_to_write = None\n msg_type_id = \"Error ::: \"\n\n if msg_type == \"warn\":\n str_err = self._warn_msg[msg_id]\n str_to_write = Logger._fill_msg(loggerdict.Log.param_to_print, \\\n str_err, msg_params)\n msg_type_id = \"Warning ::: \"\n elif msg_type == \"err\":\n str_err = self._err_msg[msg_id]\n str_to_write = Logger._fill_msg(loggerdict.Log.param_to_print, \\\n str_err, msg_params)\n msg_type_id = \"Error ::: \"\n elif msg_type == \"prog\":\n str_err = self._prog_msg[msg_id]\n str_to_write = Logger._fill_msg(loggerdict.Log.param_to_print, \\\n str_err, msg_params)\n msg_type_id = \"Information ::: \"\n\n return timestamp + \": \" + msg_type_id + msg_id + \": \" + str(str_to_write)\n\n def dump(self, language):\n \"\"\"\n This method is used to output all the messages on to the log_backup.txt\n and the screen. This is subject to creation of log_backup.txt\n This method will be used in case we have fatal error creating\n FileLogger instance. In the end this method will raise\n NotSuccessfulException\n\n @type language: string\n @param language: language to be used\n \"\"\"\n\n log_backup_exists = False\n fd_log = None\n\n\n glob_constants = globalconstants.GlobalConstants()\n\n dir_path = \"\"\n\n try:\n if hasattr(sys, 'frozen'):\n dir_path = sys.executable\n else:\n dir_path = sys.argv[0]\n\n dir_path = os.path.split(dir_path)[0]\n dir_path = os.path.join(dir_path, \"log_backup.txt\")\n dir_path = os.path.normpath(dir_path)\n dir_path = dir_path.replace(\"\\\\\", \"/\")\n fd_log = open(dir_path, \"w\")\n print (self.getTimeStamp() + \": \" + \"Information ::: STDIO_LGBKUP_WRITE: Writing all \" /\n + \"messages to backup log file: \" + dir_path)\n\n log_backup_exists = True\n\n except BaseException:\n print (self.getTimeStamp() + \": \" + \"Error ::: STDIO_LOGBKUP_CREATION_ERR: Not able to open \" + \\\n \"log file: \" + dir_path)\n\n if self.__log_list is not None:\n for msg in self.__log_list:\n str_to_write = self.__get_msg(msg)\n print (str_to_write)\n\n if(fd_log is not None):\n fd_log.write(str_to_write)\n fd_log.write(\"\\n\")\n fd_log.flush()\n\n if(msg.get_msg()[0] == 'err'):\n break\n\n if(fd_log is not None):\n params = list()\n params.append(\"FAIL\")\n str_to_write = self.__get_msg(LogMsg(\\\n \"prog\", params, \"GLOBAL_STATUS\"))\n fd_log.write(str_to_write)\n fd_log.write(\"\\n\")\n fd_log.flush()\n fd_log.close()\n fd_log = None\n\n raise NotSuccessfulException(\"Execution Failed\")\n\n\nclass FileLogger(Logger):\n \"\"\"\n This class is used to log messages to a log file\n \"\"\"\n\n def getTimeStamp(self):\n tStamp = datetime.datetime.now()\n tStamp = str(tStamp).replace(\"-\", \"/\")\n tStamp = str(tStamp).replace(\" \", \"-\")\n # tStamp = tStamp.replace(\":\", \"-\")\n tStamp = tStamp.split(\".\")[0]\n return tStamp\n\n def getTimeStampFileName(self):\n tStamp = datetime.datetime.now()\n # tStamp = str(tStamp).replace(\"-\", \"/\")\n tStamp = str(tStamp).replace(\" \", \"_\")\n tStamp = tStamp.replace(\":\", \"-\")\n tStamp = tStamp.split(\".\")[0]\n return tStamp\n\n log_file_name = \"RailMl_to_RBC_Route_Map_Log.log\"\n \"\"\"This is the log file name used for logging messages\"\"\"\n\n def createLogfile(self):\n bName = \"RailML2RBC-branchB\"\n fName = bName + \"_\" + self.getTimeStampFileName() + \".log\"\n return fName\n\n def __init__(self, op_path, language, prev_logger):\n \"\"\"\n Initialization module, takes in the output path where the log file\n needs to be placed, and the language that needs to be used. If the\n language doesnot exist then a warning is placed into the log file and\n the default language is used\n\n @type op_path: string\n @param op_path: output path\n\n @type language: string\n @param language: language to be used\n\n @type prev_logger: ListLogger\n @param prev_logger: Logger instance used to log messages until the\n instantiation of FileLogger was completed\n \"\"\"\n Logger.__init__(self)\n\n self._log_file_name = self.createLogfile()\n # FileLogger.log_file_name\n \"\"\"Name of the log file\"\"\"\n\n self._log_file = None\n \"\"\"File object\"\"\"\n\n if(not os.path.exists(op_path)):\n params = list()\n params.append(op_path)\n params.append(\"Output directory path\")\n prev_logger.log_error(\"ERR_INVALID_DIR_PATH\", params)\n\n raise NotSuccessfulException(\"Output Directory path not opening\")\n\n full_op_path = os.path.join(op_path, self._log_file_name)\n full_op_path = os.path.normpath(full_op_path)\n full_op_path = full_op_path.replace(\"\\\\\", \"/\")\n\n try:\n self._log_file = open(full_op_path, \"w\")\n\n except IOError as err:\n params = list()\n params.append(str(err))\n params.append(full_op_path)\n prev_logger.log_error(\"ERR_FILE_IO_OPEN\", params)\n\n raise NotSuccessfulException(\"Log file not opening\")\n\n def close(self):\n \"\"\"\n close the files and set the file instances to None\n \"\"\"\n if self._log_file is not None:\n self._log_file.close()\n self._log_file = None\n\n def log_error_no_stop(self, msg_id, params):\n \"\"\"\n This method is used to log errors. This method will write the Global\n Result: FAIL in the log file and then throws a NotSuccessful exception\n which directly propogates to the top layer using which the application\n exits.\n This method should be overridden by the derived classes. It takes in\n the message id which is a unique id for all types of errors, warnings\n and progress. It also takes in a list of strings as input which is used\n in output of the messages\n\n @type msg_id: string\n @param msg_id: id of the message to be written\n\n @type params: list[string]\n @param params: parameters required within the message\n \"\"\"\n\n str_err = self._err_msg[msg_id]\n str_to_write = Logger._fill_msg(loggerdict.Log.param_to_print, \\\n str_err, params)\n\n try:\n print (self.getTimeStamp() + \": \" + \"Error ::: \" + msg_id + \": \" + str_to_write)\n self._log_file.write(self.getTimeStamp() + \": \" + \"Error ::: \" + msg_id + \": \" + str_to_write)\n self._log_file.write(\"\\n\")\n self._log_file.flush()\n except BaseException:\n print (\"Error ::: STDIO_LOGWRITE_ERR: Not able to write \" + \\\n \"message to log file, Original message: Error ::: \" + \\\n msg_id + \": \" + str_to_write)\n\n raise NotSuccessfulException(\"File writing unsuccessful\")\n\n\n def log_error(self, msg_id, params):\n \"\"\"\n This method is used to log errors. This method will write the Global\n Result: FAIL in the log file and then throws a NotSuccessful exception\n which directly propogates to the top layer using which the application\n exits.\n This method should be overridden by the derived classes. It takes in\n the message id which is a unique id for all types of errors, warnings\n and progress. It also takes in a list of strings as input which is used\n in output of the messages\n\n @type msg_id: string\n @param msg_id: id of the message to be written\n\n @type params: list[string]\n @param params: parameters required within the message\n \"\"\"\n\n str_err = self._err_msg[msg_id]\n str_to_write = Logger._fill_msg(loggerdict.Log.param_to_print, \\\n str_err, params)\n\n try:\n print(self.getTimeStamp() + \": \" + \"Error ::: \" + msg_id + \": \" + str_to_write)\n self._log_file.write(self.getTimeStamp() + \": \" + \"Error ::: \" + msg_id + \": \" + str_to_write)\n self._log_file.write(\"\\n\")\n self._log_file.flush()\n except BaseException:\n print(\"Error ::: STDIO_LOGWRITE_ERR: Not able to write \" + \\\n \"message to log file, Original message: Error ::: \" + \\\n msg_id + \": \" + str_to_write)\n\n raise NotSuccessfulException(\"File writing unsuccessful\")\n\n raise NotSuccessfulException(\"Execution Failed\")\n\n def log_warning(self, msg_id, params):\n \"\"\"\n method used to log warnings. It takes in the message id which is a\n unique id for all types of errors,warnings and progress. It also takes\n in a list of strings as input which is used in output of the messages\n\n @type msg_id: string\n @param msg_id: id of the message to be written\n\n @type params: list[string]\n @param params: parameters required within the message\n \"\"\"\n str_warn = self._warn_msg[msg_id]\n str_to_write = Logger._fill_msg(loggerdict.Log.param_to_print, \\\n str_warn, params)\n\n try:\n print (self.getTimeStamp() + \": \" + \"Warning ::: \" + msg_id + \": \" + str_to_write)\n self._log_file.write(self.getTimeStamp() + \": \" + \"Warning ::: \" + msg_id + \": \" + str_to_write)\n self._log_file.write(\"\\n\")\n self._log_file.flush()\n except BaseException:\n print (self.getTimeStamp() + \": \" + \"Error ::: STDIO_LOGWRITE_ERR: Not able to write \" + \\\n \"message to log file, Original message: Warning ::: \" + \\\n msg_id + \": \" + str_to_write)\n\n raise NotSuccessfulException(\"File writing unsuccessful\")\n\n def log_progress(self, msg_id, params):\n \"\"\"\n method used to log progress message which indicates the progress stage.\n It takes in the message id which is a unique id for all types of errors\n , warnings and progress. It also takes in a list of strings as input\n which is used in output of the messages\n\n @type msg_id: string\n @param msg_id: id of the message to be written\n\n @type params: list[string]\n @param params: parameters required within the message\n \"\"\"\n str_prog = self._prog_msg[msg_id]\n str_to_write = Logger._fill_msg(loggerdict.Log.param_to_print, \\\n str_prog, params)\n\n try:\n print (self.getTimeStamp() + \": \"+\"Information ::: \" + msg_id + \": \" + str_to_write)\n self._log_file.write(self.getTimeStamp() + \": \" + \"Information ::: \" + msg_id + \": \" + \\\n str_to_write)\n self._log_file.write(\"\\n\")\n self._log_file.flush()\n except BaseException:\n print (self.getTimeStamp() + \": \" + \"Error ::: STDIO_LOGWRITE_ERR: Not able to write \" + \\\n \"message to log file, Original message: Information ::: \" + \\\n msg_id + \": \" + str_to_write)\n\n raise NotSuccessfulException(\"File writing unsuccessful\")\n\n def transfer(self, data_list):\n \"\"\"\n transfers the messages in list[LogMsg] Format\n\n @type data_list: list[LogMsg]\n @param data_list: list of data messages\n \"\"\"\n\n if(data_list is not None):\n for msg in data_list:\n (timestamp, msg_type, msg_id, msg_params) = msg.get_msg()\n if msg_type == \"warn\":\n self.log_warning( msg_id, msg_params)\n elif msg_type == \"err\":\n self.log_error( msg_id, msg_params)\n elif msg_type == \"prog\":\n self.log_progress( msg_id, msg_params)\n else:\n params = list()\n params.append(msg_id)\n params.append(\"FileLogger.transfer\")\n self.log_error(\"ERR_INTERNAL_INVALID_ID\", params)" }, { "alpha_fraction": 0.6634920835494995, "alphanum_fraction": 0.6761904954910278, "avg_line_length": 31.620689392089844, "blob_id": "3e31c99a8bd7d260140d6bd5152980aca39eef59", "content_id": "fde424f9b135b979b3ce9bd450173cc04d6a4e38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 946, "license_type": "no_license", "max_line_length": 98, "num_lines": 29, "path": "/src/rules_manager/complementary_rules.py", "repo_name": "srikanthreddybms/railml_to_rbc", "src_encoding": "UTF-8", "text": "\"\"\"\nThis module is used to appy complementary rules to the computed nodes, connectors and segments.\nof RailMl to RBC route map conversion tool\n\n@copyright:\nAll rights reserved. ©2016. ALSTOM (Bangalore, India).\nThis computer program may not be used, copied, distributed, corrected,\nmodified, translated, transmitted or assigned without ALSTOM's prior\nwritten authorization.\n\n@date : 18th July 2016\n@author: Sanjay Kalshetty, Srikanth Reddy\n\"\"\"\n\nimport src.globals.globalds as globalds\nclass apply_complementary_rules():\n\n @staticmethod\n def complementary_rules_nodes_and_connectors():\n # global globalds.nodes\n sorted_nodes = []\n sort_by_id = sorted([node[0].find(\"./id\").text for node in globalds.nodes], key=str.lower)\n\n for item in sort_by_id:\n for node in globalds.nodes:\n if node[0].find(\"./id\").text == item:\n sorted_nodes.append(node)\n\n globalds.nodes = sorted_nodes[:]" }, { "alpha_fraction": 0.5833755135536194, "alphanum_fraction": 0.5849438309669495, "avg_line_length": 36.08442687988281, "blob_id": "52011bbe819349d3f931e7756369d99783c17904", "content_id": "f797ed87d891cb13ca51e94421e08d850aaf795c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19767, "license_type": "no_license", "max_line_length": 115, "num_lines": 533, "path": "/src/globals/loggerdict.py", "repo_name": "srikanthreddybms/railml_to_rbc", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n\"\"\"\nContains the datastructures needed to do logging, it basically contains dictionary of message for\nerror/warning/information etc.\n\n@copyright:\nAll rights reserved. ©2016. ALSTOM (Bangalore, India).\nThis computer program may not be used, copied, distributed, corrected,\nmodified, translated, transmitted or assigned without ALSTOM's prior\nwritten authorization.\n\n@date : 18th July 2016\n@author: Sanjay Kalshetty, Srikanth Reddy\n\"\"\"\n\n\nclass LoggerDict:\n \"\"\"\n Logger Dict is used to store the error, progress and warning\n dictionary\n \"\"\"\n\n def __init__(self, err_dict, warn_dict, prog_dict):\n \"\"\"\n Initialization module\n\n @type err_dict: dictionary\n @param err_dict: error dictionary\n\n @type warn_dict: dictionary\n @param warn_dict: warning dictionary\n\n @type prog_dict: dictionary\n @param prog_dict: progress dictionary\n \"\"\"\n self.__err_dict = err_dict\n \"\"\"Stores the error dictionary\"\"\"\n\n self.__warn_dict = warn_dict\n \"\"\"Stores the warning dictionary\"\"\"\n\n self.__prog_dict = prog_dict\n \"\"\"Stores the progress dictionary\"\"\"\n\n def get_err_dict(self):\n \"\"\"\n returns error dictionary\n \"\"\"\n return self.__err_dict\n\n def get_warn_dict(self):\n \"\"\"\n returns warning dictionary\n \"\"\"\n return self.__warn_dict\n\n def get_prog_dict(self):\n \"\"\"\n returns progress dictionary\n \"\"\"\n return self.__prog_dict\n\n\nclass LoggerStore:\n \"\"\"\n LoggerStore is storage for various languages\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialization module\n \"\"\"\n self.__list_supported_lang = list()\n \"\"\"List of supported languages\"\"\"\n\n self.__dict_supported_lang = dict()\n \"\"\"Dictionary of languages mapped to its corresponding LoggerDict\"\"\"\n\n #english language support\n english_log_store = EnglishLog()\n\n self.__list_supported_lang.append(english_log_store.get_lang())\n\n self.__dict_supported_lang[english_log_store.get_lang()] = \\\n LoggerDict(english_log_store.get_dict_err(),\\\n english_log_store.get_dict_warn(), \\\n english_log_store.get_dict_prog())\n\n #Add other language support here as shown above\n\n def get_lang_dict(self, lang):\n \"\"\"\n Get the dictionary containing the language to its LoggerDict mapping\n use this method after checking the list of supported languages since\n this method doesnot return any error.\n\n @type lang: string\n @param lang: The language for which the dictionary needs to be\n retrieved\n \"\"\"\n return self.__dict_supported_lang[lang]\n\n def get_lang_list(self):\n \"\"\"\n Get the list of supported languages\n \"\"\"\n return self.__list_supported_lang\n\n\nclass Log:\n \"\"\"\n Log store\n \"\"\"\n param_to_print = \"param_replace_val\"\n \"\"\"string to be replaced with input parameter\"\"\"\n\n def __init__(self):\n \"\"\"\n Initialization method\n \"\"\"\n self._lang = None\n \"\"\"Language used\"\"\"\n\n self._dict_error = None\n \"\"\"Error dictionary\"\"\"\n\n self._dict_warn = None\n \"\"\"Warning dictionary\"\"\"\n\n self._dict_progress = None\n \"\"\"Progress dictionary\"\"\"\n\n def get_dict_err(self):\n \"\"\"\n Get error dictionary\n \"\"\"\n return self._dict_error\n\n def get_dict_prog(self):\n \"\"\"\n Get progress dictionary\n \"\"\"\n return self._dict_progress\n\n def get_dict_warn(self):\n \"\"\"\n Get warning dictionary\n \"\"\"\n return self._dict_warn\n\n def get_lang(self):\n \"\"\"\n Get Language used\n \"\"\"\n return self._lang\n\n\nclass EnglishLog(Log):\n \"\"\"\n Language support for english\n \"\"\"\n def __init__(self):\n\n Log.__init__(self)\n\n param_to_print = Log.param_to_print\n\n self._lang = \"eng\"\n \"\"\"Language identifier for this class\"\"\"\n\n self._dict_error = { \\\n\n \"ERR_DIR_CREATION\": \"Error in creating directory: \" + \\\n param_to_print + \" Path type = \" + param_to_print,\\\n\n \"ERR_MISSING_CMD_LINE_PARAM\": \"Command Line parameter \" +\\\n \"missing: \" + param_to_print,\n\n \"ERR_FILE_IO_OPEN\": \"Cannot open file, system msg = \" + \\\n param_to_print + \", File = \" + param_to_print,\\\n\n \"ERR_FILE_IO_CLOSE\": \"Cannot close file, system msg = \" + \\\n param_to_print + \", File = \" + param_to_print,\\\n\n \"ERR_FILE_IO_READ\": \"Cannot read file, system msg = \" + \\\n param_to_print + \", File = \" + param_to_print,\\\n\n \"ERR_FILE_IO_WRITE\": \"Cannot write file, system msg = \" + \\\n param_to_print + \", File = \" + param_to_print,\\\n\n \"ERR_SHA1_VALIDATION\": \"SHA1 Validation Error Calculated \" + \\\n \"SHA1 = \" + param_to_print + \", SHA1 Read from file = \" + \\\n param_to_print + \", File = \" + param_to_print,\\\n\n \"ERR_COMPLETENESS_SHA1_VALIDATION\": \"SHA1 Validation\" + \\\n \" Error for Configuration completeness file, Calculated SHA1 = \" + \\\n param_to_print + \", SHA1 Read from file = \" + param_to_print,\\\n\n \"ERR_MISSING_XML_PARAM\": \"Missing xml parameter, \" + \\\n \"File name = \" + param_to_print + \", Parameter = \" + param_to_print,\\\n\n \"ERR_MISSING_USP_MOON_GID\": \"Missing parameter, USP_MOON_GID\",\n\n \"ERR_CONSTRAINT_FAIL_ABORT\": \"Execution stopped due to constraint on input RAILML Failed\",\\\n\n \"ERR_CONSTRAINT_FAIL\": \"CONSTRAINT Fail\" + \", CONSTRAINT = \" + param_to_print,\\\n\n \"ERR_CMD_LINE_PARSE\": \"Occured during parsing command \" + \\\n \"line\",\\\n\n \"ERR_XML_PARSE\": \"XML Parsing error , file = \" + \\\n param_to_print + \" line = \" + param_to_print + \" cause = \" +\\\n param_to_print,\\\n\n \"ERR_XMLSCHEMA_PARSE\": \"XSD Parsing error , file = \" + \\\n param_to_print + \" cause = \" + param_to_print,\\\n\n \"ERR_INVALID_FILE_PATH\": \"File path is invalid, file = \" + \\\n param_to_print + \", type = \" + param_to_print,\\\n\n \"ERR_INVALID_DIR_PATH\": \"Directory path is invalid, dir = \"\\\n + param_to_print + \", directory type = \" + param_to_print,\\\n\n \"ERR_XML_DEFAULT_VALIDATION\": \"XML Validation error , file = \" + \\\n param_to_print + \", xsd file = \" + param_to_print + \\\n \", line number = \" + param_to_print + \", column number = \" + \\\n param_to_print + \", cause = \" + param_to_print,\\\n\n \"ERR_XML_VALIDATION\": \"XML Validation error , file = \" + \\\n param_to_print + \", xsd file = \" + param_to_print + \\\n \", line number = \" + param_to_print + \", column number = \" + \\\n param_to_print + \", cause = \" + param_to_print,\\\n\n \"ERR_EMPTY_FILE_PATH\": \"Could not find files of type \" + \\\n param_to_print + \" in the directories \" + param_to_print,\\\n\n \"ERR_INBUILTFN_INVALID_VAL\": \"Invalid value: \" + \\\n param_to_print + \" received for \" + param_to_print,\\\n\n \"ERR_INVALID_OPERATOR_VALUE\": \"Invalid value for operator\" + \\\n \": \" + param_to_print + \", value: \" + param_to_print,\\\n\n \"ERR_MISIING_ATTR\": \"Missing attribute \" + param_to_print,\\\n\n \"ERR_NO_PATH\": \"No path for: \" + param_to_print,\\\n\n \"ERR_MISSING_INP_PARAMETER\": \"Missing Input parameter in \" + \\\n \"xml file, xpath(file identifier//xpath) is : \" + param_to_print, \\\n\n \"ERR_MISSING_ALLINP_FILES\": \"Error:: No input files present for \" + \\\n \"User Safe Configuration Completeness\",\\\n\n \"ERR_INVALID_USERSAFE_FILE_DATALENGTH\": \"Invalid number of \"\\\n \"files found in user safe conf description file, expected: \" \\\n + param_to_print + \", Detected: \" + param_to_print + \\\n \" File Role: \" + param_to_print,\\\n\n \"ERR_INVALID_INTERNAL_CONF_FILE\": \"Invalid Internal \" + \\\n \"config file, Signature mismatch\",\\\n\n \"ERR_INVALID_HEX_VAL\": \"Invalid hex string value\" + \\\n \", value = \" + param_to_print,\\\n\n \"ERR_DUPLICATE_FILENAME\": \"Input files with same name detected \" + \\\n \"in two different paths, filename: \" + param_to_print,\\\n\n \"ERR_INVALID_DIR_WRITE_ACCESS\": \"Directory path doesnot \" + \\\n \"have write options: \" + param_to_print,\\\n\n \"ERR_VAL_OUT_OF_RANGE\": \"Value to write is out of range: \" + \\\n \"size(bytes): \" + param_to_print + \", value: \" + param_to_print,\\\n\n \"ERR_WRONG_INI_SECTION\": \"Invalid xpath in internal config file\" + \\\n param_to_print, \\\n\n \"ERR_SEGMENT_CREATION_ABORT\": \"Segment creation aborted\" + \\\n param_to_print, \\\n\n ##Internal debug id's for internal xml file\n\n \"ERR_COMPLEMENTRY_RULE_FAIL\": \"Complementry rule failed\" + param_to_print,\\\n\n \"ERR_INCORRECT_INTXML_INVALID_ID\": \"Incorrect internal \" +\n \"configuration xml file present, invalid file identifier: \" + \\\n param_to_print,\\\n\n \"ERR_INCORRECT_INTXML_NO_CONFIG\": \"Incorrect internal \" +\n \"configuration xml file present, No configurations present\",\\\n\n \"ERR_INCORRECT_INTXML_NO_NODE\": \"Incorrect internal \" +\n \"configuration xml file present, No node present: \" + param_to_print,\\\n\n \"ERR_SEGMENT_CREATION__NO_ABORT\": \"Unused node or node used more than once during segment creation \" +\\\n param_to_print, \\\n\n \"ERR_INCORRECT_INTXML_INVNO_OF_CONF\": \"Incorrect internal\" + \\\n \" configuration xml file present, Invalid integer present in \" + \\\n \"place of number of configurations (\" + param_to_print + \") \" + \\\n \"for node: \" + param_to_print + \", must be an integer\",\n\n \"ERR_INCORRECT_INTXML_XPATHPARAM\": \"Incorrect internal\" + \\\n \" configuration xml file present, Invalid \" + param_to_print,\\\n\n \"ERR_INCORRECT_INTXML_INCORRECT_XPATH\": \\\n \"Incorrect internal configuration xml file present, \" + \\\n \"Incorrect XPath: \" + param_to_print,\\\n\n \"ERR_INCORRECT_INTXML_INCORRECT_XPATH_REPLACE\": \\\n \"Incorrect internal configuration xml file present, \" + \\\n \"Incorrect XPath: \" + param_to_print + \", Extracted xpath = \" + \\\n param_to_print + \", Function detected = \" + param_to_print,\\\n\n \"ERR_INCORRECT_INTXML_BASISPARAM\": \"Incorrect internal\" + \\\n \" configuration xml file present, Invalid basis param name: \" + \\\n param_to_print,\\\n\n \"ERR_INCORRECT_INTXML_EMPTYCONF\": \"Incorrect internal\" + \\\n \" configuration xml file present, Empty configuration <config>\" + \\\n \" for config number: \" + param_to_print,\n\n \"ERR_INCORRECT_INTXML_NOCONF\": \"Incorrect internal\" + \\\n \" configuration xml file present, No configuration <config> present\",\\\n\n \"ERR_INCORRECT_INTXML_INVVAL\": \"Incorrect internal\" + \\\n \" configuration xml file present, Invalid type/value of data, \" + \\\n \"value = \" + param_to_print + \", type = \" + param_to_print,\\\n\n \"ERR_INCORRECT_INTXML_INVSIZE\": \"Incorrect internal\" + \\\n \" configuration xml file present, Invalid size, size= \" + \\\n param_to_print,\\\n\n \"ERR_INCORRECT_INTXML_INVTYPE\": \"Incorrect internal\" + \\\n \" configuration xml file present, Invalid type, type= \" + \\\n param_to_print,\\\n\n \"ERR_INCORRECT_INTXML_INVFUNC\": \"Incorrect internal\" + \\\n \" configuration xml file present, Invalid Function, function = \" + \\\n param_to_print,\\\n\n \"ERR_INCORRECT_INTXML_INVFUNC_TOKEN\": \"Incorrect internal\" + \\\n \" configuration xml file present, Invalid Function, function= \" + \\\n param_to_print + \", Invalid token detected '\" + param_to_print + \"'\",\\\n\n \"ERR_INCORRECT_INTXML_FUNCBRACE\": \"Incorrect internal\" + \\\n \" configuration xml file present, Invalid Function, function= \" + \\\n param_to_print + \", Unmatched braces at \" + param_to_print + \"'\",\\\n\n ##Internal debug id's for internal application errors\n\n \"ERR_INTERNAL_MISSING_PARAM\": \"Missing input parameters, \" + \\\n param_to_print,\\\n\n \"ERR_INTERNAL_UNHANDLED_EXCEPTION\": \"Internal Error, + \"\\\n \"Unhandled exception: Extra Info(Location,\" + \\\n \"Reason or stack trace):\\n\" + param_to_print,\n\n \"ERR_INTERNAL_INVALID_ID\": \"Internal Application Error, \" + \\\n \"Invalid identifier detected, id =\" + param_to_print + \\\n \", Function = \" + param_to_print,\\\n\n \"ERR_INTERNAL_NO_PATH\": \"Internal Application Error, \" + \\\n \"No path present for \" + param_to_print + \\\n \", Function detected = \" + param_to_print,\\\n\n \"ERR_INTERNAL_EMPTY_LIST\": \"Internal Application Error, \" + \\\n \"Empty list detected in function \" + param_to_print,\\\n\n \"ERR_INTERNAL_MISSING_KEYVAL\": \"Internal Application \" + \\\n \"Error Missing val, key: \" + param_to_print + \", dict: \" + \\\n param_to_print + \", function = \" + param_to_print,\\\n\n \"ERR_INTERNAL_INVALID_KEY\": \"Internal Application Error, \" + \\\n \"Invalid key, key: \" + param_to_print + \\\n \", dict: \" + param_to_print + \", function = \" + param_to_print,\\\n\n \"ERR_INTERNAL_INVALID_HEX\": \"Internal Application Error, \" + \\\n \"Invalid hex value, data: \" + param_to_print + \\\n \", Function = \" + param_to_print,\\\n\n \"ERR_INTERNAL_EMPTY_INPUT\": \"Internal Application Error, \" + \\\n \"Empty value received in function: \" + param_to_print,\\\n\n \"ERR_INTERNAL_INVALID_INPUT\": \"Internal Application Error\" + \\\n \", Invalid value received, value: \" + param_to_print + \\\n \", Function detected: \" + param_to_print,\\\n\n \"ERR_INTERNAL_PATH\": \"Internal Application Error, \" + \\\n \"Invalid file path detected: \" + param_to_print + \\\n \", Function detected: \" + param_to_print,\n\n \"ERR_INTERNAL_INVALID_CONF\": \"Internal Application Error, \"\n + \"Invalid config number passed: \" + param_to_print + \\\n \", Total number of configurations present: \" + param_to_print + \\\n \", Function detected: \" + param_to_print,\n\n \"ERR_INTERNAL_UNEXPECTED_NODE\": \"Internal Application Error,\"\\\n + \"Invalid node detected, node_name: \" + param_to_print + \\\n \", Function detected = \" + param_to_print,\n\n \"ERR_INTERNAL_MISSING_INST\": \"Missing instance: \"\\\n + param_to_print + \"Function detected: \" + param_to_print,\\\n\n \"ERR_INTERNAL_MISSING_FILE\": \"Missing file: \"\\\n + param_to_print + \"Function detected: \" + param_to_print,\\\n\n \"ERR_INTERNAL_INVALID_XPATH\": \"Internal error, \" + \\\n \"Invalid xpath \" + param_to_print,\\\n\n \"ERR_INTERNAL_FILEMODE_INVALID\": \"Invalid file mode: \" + \\\n param_to_print + \", for file = \" + param_to_print,\\\n\n \"ERR_INTERNAL_INVALID_FILES_SHA\": \"Invalid files received\" + \\\n \" for calculating SHA1\",\\\n }\n \"\"\"Error dictionary\"\"\"\n\n self._dict_warn = {\\\n\n \"WARN_UNDEFINED_LANGUAGE\": \"Undefined language: \"\n \"language specified = \" + param_to_print + \". Using default language\"\n \" = \" + param_to_print + \".\",\n\n \"WARN_INTERNAL_INVALID_ID\": \"Internal Application \" + \\\n \" Identifier = \" + param_to_print + \", Function = \" + param_to_print,\\\n\n \"WARN_INTERNAL_DIVERSE_SAFE_MISSING_INP\": \"Internal, \" + \\\n \"Missing output parameter: \" + param_to_print,\\\n \\\n \"WARN_CONSTRAINT_FAIL\": \"CONSTRAINT Fail\" + \\\n \", CONSTRAINT = \" + param_to_print, \\\n \"WARN_MISIING_ATTR\": \"Missing attribute \" + param_to_print, \\\n\n \"WARN_SEGMENT_CREATION_ABORT\": \"Segment creation aborted\" + \\\n param_to_print, \\\n\n \"WARN_SEGMENT_CREATION\": \"Unused node or node used more than once during segment creation \" + \\\n param_to_print, \\\n }\n \"\"\"Warning dictionary\"\"\"\n\n self._dict_progress = {\\\n\n \"GLOBAL_STATUS\": param_to_print,\\\n\n \"HEADER_INFO\": \"Tool Information:\\n\" + \"Tool Name : \" + param_to_print\\\n + \"\\nTool Version : \" + param_to_print + \"\\n\",\\\n\n \"CMD_LINE_PARAM_READ\": \"Command line parameter read successfully.\" +\\\n \"Parameter Read: \" + param_to_print,\\\n\n \"LANGUAGE_CHANGED\": \"Selected Lang = \" + param_to_print +\\\n \", Previous Lang = \" + param_to_print,\\\n\n \"SHA1_VALIDATED\": \"SHA1 Validation passed:: Calculated SHA1 = \"\\\n + param_to_print + \", SHA1 Read from file = \" + param_to_print + \\\n \", File = \" + param_to_print,\\\n\n \"COMPLETENESS_SHA1_VALIDATED\": \"Configuration completeness SHA1 \" +\n \"validation passed:: Calculated SHA1 = \" + param_to_print +\n \", SHA1 Read from file = \" + param_to_print,\\\n\n \"GLOBALDS_INIT_DONE\": \"Global Data structure created\",\\\n\n \"CONFIG_INFO\": \"Config information read: \" + param_to_print,\\\n\n \"PARAM_VAL_GENERATION\": \"Value generation: \" + \\\n \"Parameter = \" + param_to_print + \", Function = \" + param_to_print + \\\n \", Input Parameters XPath(file identifier//XPath): \" + \\\n param_to_print,\n\n \"PARAM_LIST_VAL_GENERATION\": \"Value generation: \" + \\\n \"Parameter List, Parameter = \" + param_to_print + \\\n \", Function = \" + param_to_print + \\\n \", Input Parameters XPath(file identifier//XPath): \" + param_to_print,\n\n \"PARAM_VAL_BASIS_PARAM_GENERATION\": \"Generating structure\",\\\n\n \"PARSING_XML_FILE_INFO\": \"Parsing xml file \" + param_to_print,\\\n\n \"VALIDATING_XSD_FILE_INFO\": \"Validating file \" + param_to_print\\\n + \", against schema file ...\" + param_to_print,\\\n\n \"GET_XPATH_INFO_STARTED\": \"Getting the Xpaths information for rules from config file , status = Started\", \\\n\n \"GET_XPATH_INFO_DONE\": \"Getting the Xpaths information for rules from config file, status = DONE \", \\\n\n \"GET_INPUT_FILE_PATHS_STARTED\": \"Getting input file paths from user \" \\\n + \"safe configuration file, status = Started\",\\\n\n \"GET_INPUT_FILE_PATHS_DONE\": \"Getting input file paths from user \" \\\n + \"safe configuration file, status = Done\",\\\n\n \"INP_FILE_PARSE\": \"Retrieved path: \" + param_to_print,\\\n\n \"PARSING_INPUT_XML_FILES_STARTED\": \"Parsing of input xml files... \" + \\\n \"Started\",\\\n\n \"PARSING_INPUT_XML_FILES_SUCCESS\": \"Parsing of input xml files... \" + \\\n \"GLOBAL RESULT: SUCCESS\",\\\n\n \"INPUT_CNFG_FILES\": \"Info of input files used for creating \" + \\\n \"middleware files:\",\\\n\n \"INP_CNFG_FILE_INFO\": \"Input Configuration file, filename: \" + \\\n param_to_print + \", Location: \" + param_to_print + \\\n \", Last modified time: \" + param_to_print + \", File Role: \" + \\\n param_to_print + \", Safety Code:\" + param_to_print,\\\n\n \"FILES_FOR_USERSAFE_COMPLETENESS\": \"Calculating sha1 for \" + \\\n \"user safe configuration completeness, Files in following \" + \\\n \"order :\\n\" + param_to_print, \\\n\n \"RULES_EXECUTION_STARTED\": \"Executing rules related to \" + \\\n param_to_print + \", status = Started\",\\\n\n \"RULES_EXECUTION_END\": \"Completed successfully rule execution related to \" + \\\n param_to_print + \" , status = Done\",\\\n\n \"CONSTRAINT_EXECUTION_STARTED\": \"Constarint checks on input railml file: STARTED \" + param_to_print, \\\n\n \"CONSTRAINT_EXECUTION_FINISHED\": \"Constarint checks on input railml file: FINISHED \" + param_to_print, \\\n\n \"WRITTING_OUTPUT_STARTED\": \"Started writing computed RBC data to output file, \" + \\\n param_to_print,\\\n\n \"WRITTING_OUTPUT_FINISHED\": \"Completed successfully writing computed RBC data to output file, \" + \\\n param_to_print, \\\n\n \"SHA1VALIDATION_SUCCESS\": \"SHA1 Validation is successful, \" + \\\n \"GLOBAL RESULT: SUCCESS\"\n\n }\n \"\"\"Progress dictionary\"\"\"\n" }, { "alpha_fraction": 0.638118326663971, "alphanum_fraction": 0.6401236653327942, "avg_line_length": 28.05097007751465, "blob_id": "1991491b71df79e78f7eedc308f035949720996d", "content_id": "6e56f37382c3daf9837dd21150f8f079ceb298b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11969, "license_type": "no_license", "max_line_length": 97, "num_lines": 412, "path": "/main.py", "repo_name": "srikanthreddybms/railml_to_rbc", "src_encoding": "UTF-8", "text": "\"\"\"\nMain module\nUsed to initialize global data structure and initiate the rules manager, constraint manager, this\nmodule is the main file for the RailMl to RBC route map conversion tool.\n\n@copyright:\nAll rights reserved. ©2016. ALSTOM (Bangalore, India).\nThis computer program may not be used, copied, distributed, corrected,\nmodified, translated, transmitted or assigned without ALSTOM's prior\nwritten authorization.\n\n@date : 18th July 2016\n@author: Sanjay Kalshetty, Srikanth Reddy\n\"\"\"\n\n#system imports\nimport os\nimport sys\nimport traceback\nfrom io import StringIO\n\n#Library imports\nimport src.globals.globalds as globalds\nimport src.interface_engine.commandlineinterface as commandlineinterface\nimport src.interface_engine.interfaces as interfaces\nimport src.globals.paths as paths\nimport src.globals.logger as logger_ns\nimport src.processor_engine.processorengine as processorengine\n\n\ndef log_internal_error(msg1, function_detected, err_type, logger_inst):\n \"\"\"\n Log internal error\n\n @type msg1: string\n @param msg1: string to be logged\n\n @type function_detected: string\n @param function_detected: function where the error is detected\n\n @type err_type: string\n @param err_type: type of error to be logged\n\n @type logger_inst: Logger\n @param logger_inst: Logger instance\n \"\"\"\n params = list()\n params.append(str(msg1))\n params.append(str(function_detected))\n logger_inst.log_error(err_type, params)\n\n\ndef get_traceback_data():\n \"\"\"\n Returns the traceback data and reason for error\n \"\"\"\n msg_handler = StringIO()\n traceback.print_exc(None, msg_handler)\n msg_handler.seek(0)\n str_msg = msg_handler.read()\n return str_msg\n\n\ndef register_fail_status(global_ds):\n \"\"\"\n Registers Global status as fail in logger and close logger instance\n\n @type global_ds: Global\n @param global_ds: instance of Global\n \"\"\"\n if(global_ds is not None):\n logger_ins = global_ds.get_instances(globalds.\\\n GlobalInstanceIden.E_INST_LOGGER)\n\n if(logger_ins is not None):\n params = list()\n params.append(\"FAIL\")\n logger_ins.log_progress(\"GLOBAL_STATUS\", params)\n logger_ins.close()\n else:\n print (\"Information ::: GLOBAL_STATUS: FAIL\")\n else:\n print (\"Information ::: GLOBAL_STATUS: FAIL\")\n\n\ndef register_failure_and_exit(global_ds=None):\n \"\"\"\n Release the global resources if taken.\n Then do the system exit with failure code(1)\n\n @type global_ds: Global\n @param global_ds: instance of Global\n \"\"\"\n ##free up all the resources\n if(global_ds is not None):\n global_ds.release()\n\n sys.exit(1)\n\n\ndef register_success_and_exit(logger, global_ds):\n \"\"\"\n Registers SUCCESS with the logger and writes the GLOBAL_STATUS to the\n logger and then does the system exit\n\n @type logger: Logger\n @param logger: Logger instance\n\n @type global_ds: Global\n @param global_ds: instance of Global\n \"\"\"\n\n ##free up all the resources\n if(global_ds is not None):\n global_ds.release()\n\n #no need to check for logger instance\n params = list()\n params.append(\"SUCCESS\")\n logger.log_progress(\"GLOBAL_STATUS\", params)\n logger.close()\n sys.exit(0)\n\n\ndef get_cmdline_optval(logger):\n \"\"\"\n gets the command line values from command line\n\n @type logger: Logger\n @param logger: Logger instance\n \"\"\"\n\n try:\n inp_dir_list = None\n # conf_comp_path = None\n op_dir = None\n op_lang = None\n\n #create command line options\n cmd_int = commandlineinterface.CommandLineInterfacer(logger)\n cmd_int.fill_cmd_line_options(logger)\n\n cl_opts = cmd_int.get_cmd_line_options()\n\n #get the output directory file list\n op_dir_list = cl_opts.get_option_value(\\\n globalds.OptionsEnum.E_OPT_OP_DIR)\n\n param = list()\n\n if(len(op_dir_list) > 0) and \\\n op_dir_list[0] != 'INVALID_PATH':\n op_dir = op_dir_list[0]\n param.append(\"Output directory: \" + op_dir)\n logger.log_progress(\"CMD_LINE_PARAM_READ\", param)\n else:\n logger.log_error(\"ERR_MISSING_CMD_LINE_PARAM\", \\\n [\"Output Directory\"])\n\n #get the list of input directories\n inp_dir_list = cl_opts.get_option_value(\\\n globalds.OptionsEnum.E_OPT_INP_DIR)\n\n param = list()\n\n if (len(inp_dir_list) > 0) and \\\n inp_dir_list[0] != 'INVALID_PATH':\n param = list()\n param.append(\"Input Files list: \" + \", \".join(inp_dir_list))\n logger.log_progress(\"CMD_LINE_PARAM_READ\", param)\n else:\n logger.log_error(\"ERR_MISSING_CMD_LINE_PARAM\", \\\n [\"Input Files\"])\n\n\n if (len(inp_dir_list) != 2):\n param = list()\n param.append(\"Missing Input Files: \" + \", \".join(inp_dir_list))\n logger.log_error(\"ERR_MISSING_CMD_LINE_PARAM\", \\\n [\"Input Files\"])\n\n except logger_ns.NotSuccessfulException:\n dummy = None\n #do nothing let it fall\n except BaseException:\n logger.log_error(\"ERR_INTERNAL_UNHANDLED_EXCEPTION\", \\\n [get_traceback_data()])\n #do nothing let it fall\n\n if(op_dir is None):\n op_dir = 'INVALID_PATH'\n\n return (inp_dir_list, op_dir, op_lang)\n\n\n\ndef init_global_ds(global_ds, op_dir, inp_dir_list, op_lang, logger):\n \"\"\"\n initialize global datastructure\n\n @type global_ds: Global\n @param global_ds: Global instance\n\n @type op_dir: string\n @param op_dir: Output directory passed through --od or -o\n\n @type inp_dir_list: list[string]\n @param inp_dir_list: input directory paths passed through --id or -i option\n\n @type op_lang: string\n @param op_lang: Output Language to be used\n\n @type logger: Logger\n @param logger: Logger instance\n \"\"\"\n\n file_logger = None\n\n if(op_dir != 'INVALID_PATH'):\n try:\n file_logger = logger_ns.FileLogger(op_dir, op_lang, logger)\n except BaseException:\n logger = logger.dump(\"DEFAULT\")\n raise logger_ns.NotSuccessfulException(\"Execution Failed\")\n else:\n logger = logger.dump(\"DEFAULT\")\n raise logger_ns.NotSuccessfulException(\"Execution Failed\")\n\n try:\n file_logger.transfer(logger.get_log_list())\n except logger_ns.NotSuccessfulException:\n #No problem with logger, so set it before raising exception\n global_ds.set_instances(globalds.GlobalInstanceIden.E_INST_LOGGER, \\\n file_logger)\n raise\n except BaseException:\n trace_data = get_traceback_data()\n print (\"Error ::: STDIO_UNHANDLED_EXCEPTION_ERR: Exit during \" + \\\n \"transfer of messages: stacktrace,Reason:\\n\" + trace_data + \"\\n\")\n raise logger_ns.NotSuccessfulException(\"Execution Failed\")\n\n global_ds.set_instances(globalds.GlobalInstanceIden.E_INST_LOGGER, \\\n file_logger)\n\n try:\n global_ds.set_instances(globalds.GlobalInstanceIden.E_INST_INIT, \\\n paths.InitPaths(inp_dir_list, op_dir, file_logger))\n global_ds.set_instances(globalds.GlobalInstanceIden.E_INST_APP_PATHS, \\\n paths.ApplicationPaths(file_logger))\n\n except logger_ns.NotSuccessfulException:\n raise\n #catch other exceptions\n except BaseException:\n params = list()\n trace_data = get_traceback_data()\n params.append(trace_data)\n file_logger.log_error(\"ERR_INTERNAL_UNHANDLED_EXCEPTION\", params)\n\n\ndef init_app_paths(app_paths, global_ds, op_dir):\n \"\"\"\n initialize globalds\n\n @type app_paths: ApplicationPaths\n @param app_paths: ApplicationPaths instance\n\n @type global_ds: Global\n @param global_ds: Global instance\n\n @type conf_comp_path: string\n @param conf_comp_path: path of configuration completeness file\n\n @type op_dir: string\n @param op_dir: Output directory\n \"\"\"\n\n #File logger\n file_logger = global_ds.get_instances(globalds.GlobalInstanceIden.\\\n E_INST_LOGGER)\n\n inp_file_paths = None\n int_file_paths = None\n mw_file_paths = None\n op_file_paths = None\n\n try:\n #retrieve the parameters\n init_paths = global_ds.get_instances(\\\n globalds.GlobalInstanceIden.E_INST_INIT)\n\n inputs_xml_list = init_paths.get_conf_desc_path()\n\n inp_file_path_creator = interfaces.InputFilePathCreator( \\\n inputs_xml_list, file_logger)\n inp_file_paths = inp_file_path_creator.get_input_file_paths()\n\n int_file_paths = paths.InternalConfigFilePaths(file_logger)\n\n op_file_paths = paths.OutputFilePaths(op_dir, file_logger)\n\n except logger_ns.NotSuccessfulException:\n raise\n except BaseException:\n params = list()\n trace_data = get_traceback_data()\n params.append(trace_data)\n file_logger.log_error(\"ERR_INTERNAL_UNHANDLED_EXCEPTION\", params)\n\n #everything is okay, now set the instances\n app_paths.set_instances(paths.ApplicationInstanceIDEnum.INST_INP, \\\n inp_file_paths)\n app_paths.set_instances(paths.ApplicationInstanceIDEnum.INST_INT, \\\n int_file_paths)\n\n app_paths.set_instances(paths.ApplicationInstanceIDEnum.INST_OP, \\\n op_file_paths)\ndef init():\n \"\"\"\n Initialization method, Initializes and returns global data structure\n \"\"\"\n\n #create temporary in-memory logger.\n temp_logger = None\n\n try:\n temp_logger = logger_ns.ListLogger()\n\n\n except logger_ns.NotSuccessfulException:\n raise\n except BaseException:\n #handle an exception\n trace_data = get_traceback_data()\n print (\"Error ::: STDIO_UNHANDLED_EXCEPTION_ERR: \" + trace_data)\n register_fail_status(None)\n raise logger_ns.NotSuccessfulException(\"Execution Failed\")\n\n #Creation of Global Data structure and its internal structure\n #initialization\n\n inp_dir_list = None\n op_dir = None\n op_lang = None\n\n (inp_dir_list, op_dir, op_lang) = \\\n get_cmdline_optval(temp_logger)\n\n #create global datastructure\n global_ds = globalds.Global()\n\n try:\n #initialize global datastructure\n init_global_ds(global_ds, op_dir, inp_dir_list, op_lang, temp_logger)\n\n #Application paths\n app_paths = global_ds.get_instances(globalds.GlobalInstanceIden.\\\n E_INST_APP_PATHS)\n init_app_paths(app_paths, global_ds, op_dir)\n\n except BaseException:\n register_fail_status(global_ds)\n raise\n\n #return global data structure\n return global_ds\n\n\ndef main():\n \"\"\"\n Main module\n \"\"\"\n logger = None\n global_ds = None\n try:\n global_ds = init()\n params = list()\n logger = global_ds.get_instances(globalds.GlobalInstanceIden.\\\n E_INST_LOGGER)\n logger.log_progress(\"GLOBALDS_INIT_DONE\", params)\n #exception\n except logger_ns.NotSuccessfulException:\n register_failure_and_exit(global_ds)\n except BaseException:\n trace_data = get_traceback_data()\n print (\"Error ::: STDIO_ERR_UNHANDLED_EXCEPTION: \" + trace_data)\n register_failure_and_exit(global_ds)\n\n try:\n processor_engine = processorengine.ProcessorEngine(global_ds)\n processor_engine.begin_operation()\n\n except logger_ns.NotSuccessfulException:\n register_fail_status(global_ds)\n register_failure_and_exit(global_ds)\n except BaseException:\n logger = global_ds.get_instances(globalds.GlobalInstanceIden.\\\n E_INST_LOGGER)\n params = list()\n msg = get_traceback_data()\n params.append(msg)\n\n try:\n logger.log_error(\"ERR_INTERNAL_UNHANDLED_EXCEPTION\", params)\n except BaseException:\n register_fail_status(global_ds)\n register_failure_and_exit(global_ds)\n\n register_success_and_exit(logger, global_ds)\n \nif __name__ == '__main__':\n main()" }, { "alpha_fraction": 0.5908501148223877, "alphanum_fraction": 0.596582293510437, "avg_line_length": 30.134679794311523, "blob_id": "1ad4a175103a9604854b1b38341127f3a271c606", "content_id": "fc3c673ab310954b1f2de3179bb006b2869a41c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9257, "license_type": "no_license", "max_line_length": 95, "num_lines": 297, "path": "/src/globals/globalds.py", "repo_name": "srikanthreddybms/railml_to_rbc", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n\"\"\"\nGlobal data structure is which holds all the global data that needs\nto be shared across all the packages. The global data structure is\npropagated within the system to be used across packages\n\n@copyright:\nAll rights reserved. ©2016. ALSTOM (Bangalore, India).\nThis computer program may not be used, copied, distributed, corrected,\nmodified, translated, transmitted or assigned without ALSTOM's prior\nwritten authorization.\n\n@date : 18th July 2016\n@author: Sanjay Kalshetty, Srikanth Reddy\n\"\"\"\nnodes = []\nconnectors = []\n\n\nNODES_INFO = []\nTOTAL_NODES = 0\nTOTAL_CONNECTORS = 0\n\ncount_nodes = 0\ncount_connectors = 0\ncount_segments = 0\n\n\nNSMAP = {'mainNS': \"http://www.railml.org/schemas/2013\", \\\n 'xsNS': 'http://www.w3.org/2001/XMLSchema', \\\n 'dcNS': 'http://purl.org/dc/elements/1.1/', \\\n 'atlasBasicNS': 'http://www.transport.alstom.com/ATLAS/basic/1', \\\n 'atlasEtcs2': 'http://www.transport.alstom.com/ATLAS/etcs2/1'}\n\nNSMAP_genParams = {'mainNS': \"http://www.transport.alstom.com/ATLAS/rbcGeneralParameters/1/\", \\\n 'xsNS': \"http://www.w3.org/2001/XMLSchema\"}\n\nclass LetterIter:\n \"\"\"An iterator over letters of the alphabet in ASCII order.\"\"\"\n\n def __init__(self, start='a', end='z'):\n self.next_letter = start\n self.end = end\n\n def __next__(self):\n if self.next_letter == self.end:\n raise StopIteration\n letter = self.next_letter\n self.next_letter = chr(ord(letter) + 1)\n return letter\n\nclass OptionsEnum:\n \"\"\"\n Option identifiers\n \"\"\"\n E_OPT_NONE = 0\n \"\"\"None\"\"\"\n E_OPT_OP_DIR = 1\n \"\"\"Output directory option\"\"\"\n E_OPT_INP_DIR = 2\n \"\"\"Input directory option\"\"\"\n E_OPT_LANG = 3\n \"\"\"Language option\"\"\"\n E_OPT_COMP = 4\n \"\"\"configurationcompleteness option\"\"\"\n\n\nclass CommandLineOptions:\n \"\"\"\n This DS is for any future command line options.\n It contains the dictionary of options which contain the option to the\n list of option value mapping.\n Feg: options like -o is output directory and the option value is the\n directory\n The current options available are:\n --id or -i <list of input directories>\n --od or -o <output directory>\n \"\"\"\n\n def __init__(self, logger):\n \"\"\"\n Initialization module\n\n @type logger: Logger\n @param logger: logger instance\n \"\"\"\n self.__logger = logger\n \"\"\"Logger instance\"\"\"\n self.__options = dict()\n \"\"\"Options mapped to its value\"\"\"\n\n def set_option_value(self, option, option_val):\n \"\"\"\n Set the option values against an option identifier\n\n @type option: int\n @param option: option identifiers\n\n @type option_val: list[string]\n @param option_val: corresponding option values\n \"\"\"\n if(option > OptionsEnum.E_OPT_NONE and option <= \\\n OptionsEnum.E_OPT_COMP):\n self.__options[option] = option_val\n else:\n fn_name = 'CommandLineOptions.set_option_value'\n fn_params = str(option)\n params = list()\n params.append(str(fn_params))\n params.append(fn_name)\n self.__logger.log_error(\"ERR_INTERNAL_INVALID_ID\", params)\n\n def get_option_value(self, option):\n \"\"\"\n get the option values against an option identifier\n\n @type option: int\n @param option: option identifier\n \"\"\"\n if(option in self.__options):\n return self.__options[option]\n else:\n fn_name = 'CommandLineOptions.get_option_value'\n fn_params = str(option)\n params = list()\n params.append(str(fn_params))\n params.append(fn_name)\n self.__logger.log_error(\"ERR_INTERNAL_INVALID_ID\", params)\n\n\nclass ParamDS:\n \"\"\"\n ParamDS is a datastructure to hold all the parsed libxml2.xmlDoc objects\n \"\"\"\n\n def __init__(self, logger):\n \"\"\"\n Initialization module\n\n @type logger: Logger\n @param logger: Logger instance\n \"\"\"\n\n self.__param_root = dict()\n \"\"\"Param root containing xml identifier to its libxml2.xmlDoc object\"\"\"\n\n self.__logger = logger\n \"\"\"Logger instance\"\"\"\n\n self.__list_doc = list()\n \"\"\"List maintained to aid in freeing\"\"\"\n\n def set_doc(self, file_identifier, tree_node):\n \"\"\"\n sets the libxml2.xmlDoc object against the identifier\n\n @type file_identifier: string\n @param file_identifier: file identifier to use to place the xmlDoc\n object\n\n @type tree_node: libxml2.xmlDoc\n @param tree_node: xmlDoc object\n \"\"\"\n self.__param_root[file_identifier] = tree_node\n self.__list_doc.append(tree_node)\n\n def get_doc(self, file_identifier):\n \"\"\"\n gets the libxml2.xmlDoc object against the identifier\n\n @type file_identifier: string\n @param file_identifier: file identifier\n \"\"\"\n if file_identifier in self.__param_root:\n return self.__param_root[file_identifier]\n else:\n params = list()\n params.append(str(file_identifier))\n params.append(\"ParamDS.get_doc\")\n self.__logger.log_error(\"ERR_INTERNAL_INVALID_ID\", params)\n\n def free(self):\n \"\"\"\n free the data structure\n \"\"\"\n if self.__list_doc is not None:\n for xml_doc in self.__list_doc:\n if xml_doc is not None:\n xml_doc.freeDoc()\n\n self.__param_root = None\n self.__list_doc = None\n\n\nclass GlobalInstanceIden:\n \"\"\"\n instance identifiers for Global datastructure\n \"\"\"\n E_INST_INIT = 0\n \"\"\"InitPaths instance\"\"\"\n E_INST_CL_OPT = 1\n \"\"\"CommandLineOptions instance\"\"\"\n E_INST_LOGGER = 2\n \"\"\"Logger instance\"\"\"\n E_INST_APP_PATHS = 3\n \"\"\"ApplicationPaths instance\"\"\"\n E_INST_PARAM_DS = 4\n \"\"\"ParamDS instance\"\"\"\n\n\nclass Global:\n \"\"\"\n This is the Data structure which holds all the global data that needs to\n be shared across all the packages. The global data structure is propagated\n within the system to be used across packages\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialization method\n \"\"\"\n self.__init_paths = None\n \"\"\"This variable contains all the input and output paths mentioned\n with the options –id or -i, -od or –o and –comp or ‘-c’\"\"\"\n\n self.__cl_opts = None\n \"\"\"CommandLineOptions instance\"\"\"\n\n self.__logger = None\n \"\"\"This instance will be used to log messages to the log file. It\n contains err_msg and progress_messages which is a pre-defined\n dictionary which contains predefined messages for specific messages\"\"\"\n\n self.__app_paths = None\n \"\"\"This member instance contains all the application paths used in the\n application, other than the paths specified through command line \"\"\"\n\n self.__param_ds = None\n \"\"\"ParamDS instance\"\"\"\n\n def release(self):\n \"\"\"\n release the resources\n \"\"\"\n if(self.__param_ds is not None):\n self.__param_ds.free()\n\n def set_instances(self, instance_id, instance):\n \"\"\"\n set_instances is used to set the instance of object in Global\n based on the instance id\n\n @type instance_id: int\n @param instance_id: instance identifier\n\n @type instance: instance object\n @param instance: instance object to be set\n \"\"\"\n if(instance_id == GlobalInstanceIden.E_INST_INIT):\n self.__init_paths = instance\n elif(instance_id == GlobalInstanceIden.E_INST_CL_OPT):\n self.__cl_opts = instance\n elif(instance_id == GlobalInstanceIden.E_INST_LOGGER):\n self.__logger = instance\n elif(instance_id == GlobalInstanceIden.E_INST_APP_PATHS):\n self.__app_paths = instance\n elif(instance_id == GlobalInstanceIden.E_INST_PARAM_DS):\n self.__param_ds = instance\n else:\n params = list()\n params.append(str(instance_id))\n params.append(\"Global.set_instances\")\n self.__logger.log_error(\"ERR_INTERNAL_INVALID_ID\", params)\n\n def get_instances(self, instance_id):\n \"\"\"\n get_instances is used to get the instance of object in Global\n based on the instance id\n\n @type instance_id: int\n @param instance_id: identifier for instances which needs to be returned\n \"\"\"\n if(instance_id == GlobalInstanceIden.E_INST_INIT):\n return self.__init_paths\n elif(instance_id == GlobalInstanceIden.E_INST_CL_OPT):\n return self.__cl_opts\n elif(instance_id == GlobalInstanceIden.E_INST_LOGGER):\n return self.__logger\n elif(instance_id == GlobalInstanceIden.E_INST_APP_PATHS):\n return self.__app_paths\n elif(instance_id == GlobalInstanceIden.E_INST_PARAM_DS):\n return self.__param_ds\n else:\n params = list()\n params.append(str(instance_id))\n params.append(\"Global.get_instances\")\n self.__logger.log_error(\"ERR_INTERNAL_INVALID_ID\", params)" }, { "alpha_fraction": 0.5799820423126221, "alphanum_fraction": 0.5821995735168457, "avg_line_length": 29.560440063476562, "blob_id": "3ea9968d73326c1931218478c0200499721555b6", "content_id": "65ed1a171a93d3d40fd43ab0dfb255d73bf65ca0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16686, "license_type": "no_license", "max_line_length": 92, "num_lines": 546, "path": "/src/globals/paths.py", "repo_name": "srikanthreddybms/railml_to_rbc", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n\"\"\"\nStorage module for paths used in the application related to RailMl to RBC route map\nconversion tool\n\n@copyright:\nAll rights reserved. ©2016. ALSTOM (Bangalore, India).\nThis computer program may not be used, copied, distributed, corrected,\nmodified, translated, transmitted or assigned without ALSTOM's prior\nwritten authorization.\n\n@date : 18th July 2016\n@author: Sanjay Kalshetty, Srikanth Reddy\n\"\"\"\n\nimport sys\nimport os\nimport glob\n\n\nclass InputFileIdentifierEnum:\n \"\"\"\n Input File type identifiers\n \"\"\"\n\n E_INP_UNDEF = 0\n \"\"\"Undefined inputs\"\"\"\n\n E_INP_RAIML = 1\n \"\"\"Railml data input Xml File\"\"\"\n\n E_INP_RBC_GEN_PARAM = 2\n \"\"\"RBC General parameter Xml file\"\"\"\n\nclass InputFilePaths:\n \"\"\"\n This class contains all methods required to get the information about all\n the input files for the application. This information is extracted from\n UserSafeConfDescriptor.xml file\n \"\"\"\n\n def __init__(self, logger):\n \"\"\"\n initialization module:\n\n @type logger: Logger\n @param logger: For logging messages\n \"\"\"\n\n self.__d_input_file_identifier = \\\n { \\\n InputFileIdentifierEnum.E_INP_RAIML:\\\n 'RailMl_Input_Data.xml',\\\n InputFileIdentifierEnum.E_INP_RBC_GEN_PARAM:\\\n 'rbcGeneralParameters.xml'}\n\n \"\"\"Mapping of file identifier integers to file identifier strings(or\n file roles\"\"\"\n\n self.__d_input_files = dict()\n \"\"\"dictionary mapping of InputIdentifierEnum to File Paths\"\"\"\n\n self.__d_input_sha1_files = dict()\n \"\"\"dictionary mapping of InputIdentifierEnum to SHA1 Paths\"\"\"\n\n self.__s_conf_completion_path = None\n \"\"\"Configuration completeness paths\"\"\"\n\n self.__logger = logger\n \"\"\"logger instance to log messages\"\"\"\n\n def set_input_file_path(self, identifier, xml_path, sha_path):\n \"\"\"\n This method sets the input file paths using the file identifier\n\n @type identifier: int\n @param identifier: identifier\n\n @type xml_path: list[string]\n @param xml_path: list of paths to xml file\n\n @type sha_path: list[string]\n @param sha_path: list of paths to sha1 file\n \"\"\"\n if(identifier is not None and \\\n identifier in self.__d_input_file_identifier):\n self.__d_input_files[identifier] = xml_path\n return\n\n def get_file_identifier(self, file_id):\n \"\"\"\n This method is used to get the file identifier for the file_id\n The file identifier is a string representation of the file_id\n\n @type file_id: int\n @param file_id: file identifier\n \"\"\"\n if file_id is not None and file_id in self.__d_input_file_identifier:\n return self.__d_input_file_identifier[file_id]\n\n #problem\n fn_name = 'InputFilePaths.get_file_identifier'\n fn_params = str(file_id)\n params = list()\n params.append(fn_params)\n params.append(fn_name)\n self.__logger.log_error(\"ERR_INTERNAL_INVALID_ID\", params)\n\n def get_file_path(self, e_id):\n \"\"\"\n Get the file path for the particular file identifier in form of\n list[string]\n\n @type e_id: integer\n @param e_id: identifier\n \"\"\"\n if e_id is not None and e_id in self.__d_input_files:\n paths_obj = self.__d_input_files[e_id]\n return paths_obj\n\n #Problem! handle error\n fn_name = 'InputFilePaths.get_file_path'\n fn_params = str(e_id)\n params = list()\n params.append(fn_params)\n params.append(fn_name)\n\n if e_id is not None and e_id in self.__d_input_file_identifier:\n self.__logger.log_warning(\"WARN_INTERNAL_INVALID_ID\", params)\n else:\n self.__logger.log_error(\"ERR_INTERNAL_INVALID_ID\", params)\n\n return None\n\n def get_sha_path(self, e_id):\n \"\"\"\n get the sha1 file path for the particular identifier in form of\n list[string]\n\n @type e_id: int\n @param e_id: file identifier\n \"\"\"\n\n if e_id is not None and e_id in self.__d_input_sha1_files:\n return self.__d_input_sha1_files[e_id]\n\n #Problem! handle error\n fn_name = 'InputFilePaths.get_sha_path'\n fn_params = str(e_id)\n params = list()\n params.append(fn_params)\n params.append(fn_name)\n\n if e_id is not None and e_id in self.__d_input_file_identifier:\n self.__logger.log_warning(\"WARN_INTERNAL_INVALID_ID\", params)\n else:\n self.__logger.log_error(\"ERR_INTERNAL_INVALID_ID\", params)\n\n def set_conf_completeness_path(self, path):\n \"\"\"\n set the configuration completeness path\n\n @type path: string\n @param path: configuration completeness path\n \"\"\"\n self.__s_conf_completion_path = path\n \"\"\"configuration completeness path\"\"\"\n\n def get_conf_completeness_file_path(self):\n \"\"\"\n This method returns string path of the configurationCompleteness file\n which contains the global sha1\n \"\"\"\n return self.__s_conf_completion_path\n\n\nclass InitPaths:\n \"\"\"\n This class holds the application paths which are input paths specified by\n --id option and output paths specified by --od option\n \"\"\"\n\n def __init__(self, inp_paths, out_path, logger):\n \"\"\"\n initialization module\n\n @type inp_paths: list[string]\n @param inp_paths: list of input paths\n\n @type out_path: string\n @param out_path: output path\n\n @type logger: Logger\n @param logger: Logger instance\n \"\"\"\n\n self.__logger = logger\n \"\"\"Logger instance\"\"\"\n\n #start\n if(not os.path.exists(out_path) or not os.path.isdir(out_path)):\n params = list()\n params.append(out_path)\n params.append(\"Output directory path\")\n logger.log_error(\"ERR_INVALID_DIR_PATH\", params)\n\n self.out_path = out_path\n \"\"\"output path\"\"\"\n\n self.conf_desc_xml = list()\n \"\"\"configuration descriptor xml paths\"\"\"\n\n #inp paths len are checked before being sent, so no need of error\n #checking\n for path in inp_paths:\n if(not os.path.isabs(path)):\n path = os.path.abspath(path)\n\n #construct the file_path to search for all xml files starting with\n # self.__d_input_sha1_files[identifier] = sha_path\n if (not os.path.isfile(path)):\n params = list()\n params.append(path)\n params.append(\"one of (RailML or RBC Generalparma or RBC Default).xml\")\n logger.log_error(\"ERR_INVALID_FILE_PATH\", params)\n\n file_path = os.path.normpath(path)\n\n #normalize all paths\n file_path = os.path.normpath(file_path)\n file_path = file_path.replace(\"\\\\\", \"/\")\n\n #search for conf descriptor files\n file_list = glob.glob(file_path)\n\n if((file_list is not None) and\\\n (len(file_list) > 0)):\n for _file in file_list:\n _file = os.path.normpath(_file)\n _file = _file.replace(\"\\\\\", \"/\")\n\n self.conf_desc_xml.append(_file)\n\n if(len(self.conf_desc_xml) != 2):\n params = list()\n params.append(\"Missing inputs files one of(RailML or RBC General parameter Xml\")\n params.append(\", \".join(inp_paths))\n logger.log_error(\"ERR_EMPTY_FILE_PATH\", params)\n\n def get_op_file_path(self):\n \"\"\"\n get the output file path\n \"\"\"\n return self.out_path\n\n def get_conf_desc_path(self):\n \"\"\"\n get the configuration descriptor xml paths list\n \"\"\"\n return self.conf_desc_xml\n\n\nclass InternalFileIDEnum:\n \"\"\"\n file identifier for the internal configuration file\n \"\"\"\n E_INT_UNDEF_FILE = 0\n \"\"\"Undefined file\"\"\"\n E_INT_CONFIG_FILE = 1\n \"\"\"InternalConfiguration file\"\"\"\n E_INT_RBC_DEFAULT_OUT_FILE = 2\n \"\"\"InternalConfiguration file\"\"\"\n\n\nclass InternalConfigFilePaths:\n \"\"\"\n This class stores the paths of internal configuration files used by the\n application\n \"\"\"\n\n def __init__(self, logger):\n \"\"\"\n initialization method\n\n @type logger: Logger\n @param logger: Logger instance\n \"\"\"\n #fill os_file_path\n\n if hasattr(sys, 'frozen'):\n dir_path = sys.executable\n new_path = os.path.split(dir_path)\n dir_path = new_path[0]\n else:\n dir_path = sys.argv[0]\n new_path = os.path.split(dir_path)\n dir_path = new_path[0]\n\n int_config_file_path = os.path.join(\\\n dir_path, \"config/Rules.ini\")\n int_config_file_path = os.path.normpath(int_config_file_path)\n int_config_file_path = int_config_file_path.replace(\"\\\\\", \"/\")\n\n int_rbc_default_file = os.path.join(\\\n dir_path, \"config/RBC_output_Default.xml\")\n int_rbc_default_file = os.path.normpath(int_rbc_default_file)\n int_rbc_default_file = int_rbc_default_file.replace(\"\\\\\", \"/\")\n\n try:\n fdesc_xml = open(int_config_file_path, \"r\")\n except BaseException:\n params = list()\n params.append(int_config_file_path)\n params.append(\"Internal Config file Rules.ini path\")\n logger.log_error(\"ERR_INVALID_FILE_PATH\", params)\n\n try:\n fdesc_xml.close()\n except BaseException:\n pass\n\n try:\n fdesc_rbc_default = open(int_rbc_default_file, \"r\")\n except BaseException:\n params = list()\n params.append(int_rbc_default_file)\n params.append(\"Internal config RBC Default file path\")\n logger.log_error(\"ERR_INVALID_FILE_PATH\", params)\n\n try:\n fdesc_rbc_default.close()\n except BaseException:\n pass\n\n self.__internal_config_file = \\\n {InternalFileIDEnum.E_INT_CONFIG_FILE: int_config_file_path}\n \"\"\"Internal config file path\"\"\"\n self.__internal_rbc_default_file = \\\n {InternalFileIDEnum.E_INT_RBC_DEFAULT_OUT_FILE: int_rbc_default_file}\n \"\"\"Internal rbc default file path\"\"\"\n\n self.__logger = logger\n \"\"\"Logger instance\"\"\"\n\n def get_internal_file_path(self, file_id):\n \"\"\"\n gets the path of the internal config xml file mapped with the passed\n identifier, in form of string\n\n @type file_id: int\n @param file_id: file identifier\n \"\"\"\n\n if file_id in self.__internal_config_file:\n return self.__internal_config_file[file_id]\n else:\n params = list()\n params.append(str(file_id))\n params.append(\"InternalConfigFilePaths.get_internal_file_path\")\n self.__logger.log_error(\"ERR_INTERNAL_INVALID_ID\", params)\n\n def get__rbc_default_file(self, file_id):\n \"\"\"\n gets the path of the xsd of internal config file mapped with the passed\n identifier, in form of string\n\n @type file_id: int\n @param file_id: file identifier\n \"\"\"\n if file_id in self.__internal_rbc_default_file:\n return self.__internal_rbc_default_file[file_id]\n else:\n params = list()\n params.append(str(file_id))\n params.append(\"InternalConfigFilePaths.get__rbc_default_file\")\n self.__logger.log_error(\"ERR_INTERNAL_INVALID_ID\", params)\n\nclass OutputFilePathsIdEnum:\n \"\"\"\n Identifiers for Output files\n \"\"\"\n E_OP_UNDEF = 0\n \"\"\"Output undefined file\"\"\"\n E_OP = 1\n \"\"\"RBC Route map xml output file\"\"\"\n\n\nclass OutputFilePaths:\n \"\"\"\n This class contains the list of all the output files generated by the\n application\n \"\"\"\n\n def __init__(self, op_path, logger):\n \"\"\"\n initialization module\n\n @type op_path: string\n @param op_path: output file path\n\n @type logger: Logger\n @param logger: Logger instance\n \"\"\"\n self.__op_paths = dict()\n \"\"\"output file paths mapped to their identifier\"\"\"\n\n self.__logger = logger\n \"\"\"Logger instance\"\"\"\n\n self.set_path(op_path)\n\n def set_path(self, op_path):\n \"\"\"\n Setter for the file paths based on the input file identifieroutput path\n\n @type op_path: string\n @param op_path: output file path\n \"\"\"\n path_list = list()\n new_path = op_path\n\n if(not os.path.isabs(op_path)):\n new_path = os.path.abspath(new_path)\n\n if(not os.path.exists(new_path)):\n params = list()\n params.append(new_path)\n params.append(\"Output directory\")\n self.__logger.log_error(\"ERR_INVALID_DIR_PATH\", params)\n\n self.__op_paths = \\\n {\n OutputFilePathsIdEnum.E_OP: \\\n op_path\n }\n\n def get_path(self, iden):\n \"\"\"\n getter for the file path using the file identifier,\n returns list[string]\n\n @type iden: string\n @param iden: identifier\n \"\"\"\n\n if iden not in self.__op_paths:\n params = list()\n params.append(str(iden))\n params.append(\"OutputFilePaths.get_path\")\n self.__logger.log_error(\"ERR_INTERNAL_INVALID_ID\", params)\n\n path = self.__op_paths[iden]\n\n return path\n\n\nclass ApplicationInstanceIDEnum:\n \"\"\"\n Application Instance identifiers\n \"\"\"\n INST_UNDEF = 0\n \"\"\"Undefined instance\"\"\"\n INST_OP = 1\n \"\"\"OutputFilePaths instance\"\"\"\n INST_MW = 2\n \"\"\"MWFilePaths instance\"\"\"\n INST_INT = 3\n \"\"\"InternalFilePaths instance\"\"\"\n INST_INP = 4\n \"\"\"InputFilePaths instance\"\"\"\n\n\nclass ApplicationPaths:\n \"\"\"\n This is global storage location of instances which store all file paths\n for all types of files used in the application. This is the common\n interface through which the application can get the input, output,\n middleware and internal configuration file paths.\n \"\"\"\n\n def __init__(self, logger):\n \"\"\"\n Initialization method\n\n @type logger: Logger\n @param logger: Logger instance\n \"\"\"\n\n self.__logger = logger\n \"\"\"logger instance\"\"\"\n # self.__mw_file_paths = None\n # \"\"\"middleware file paths\"\"\"\n self.__op_f_paths = None\n \"\"\"output file paths\"\"\"\n self.__inp_file_paths = None\n \"\"\"input file paths\"\"\"\n self.__int_file_paths = None\n \"\"\"Internal file paths\"\"\"\n\n def set_instances(self, instance_id, instance):\n \"\"\"\n set_instances is used to set the instance of object in ApplicationPaths\n based on the instance id\n\n @type instance_id: int\n @param instance_id: instance identifier\n\n @type instance: instance object\n @param instance: instance object to be set\n \"\"\"\n if(instance_id == ApplicationInstanceIDEnum.INST_INP):\n self.__inp_file_paths = instance\n \"\"\"InputFilePaths class instance\"\"\"\n elif(instance_id == ApplicationInstanceIDEnum.INST_INT):\n self.__int_file_paths = instance\n \"\"\"InternalConfigFilePaths instance\"\"\"\n elif(instance_id == ApplicationInstanceIDEnum.INST_OP):\n self.__op_f_paths = instance\n \"\"\"OutputFilePaths instance\"\"\"\n else:\n params = list()\n params.append(str(instance_id))\n params.append(\"ApplicationPaths.set_instances\")\n self.__logger.log_error(\"ERR_INTERNAL_INVALID_ID\", params)\n\n def get_instances(self, instance_id):\n \"\"\"\n get_instances is used to get the instance of object in ApplicationPaths\n based on the instance id\n\n @type instance_id: int\n @param instance_id: identifier for instances which needs to be returned\n \"\"\"\n if(instance_id == ApplicationInstanceIDEnum.INST_INP):\n return self.__inp_file_paths\n elif(instance_id == ApplicationInstanceIDEnum.INST_INT):\n return self.__int_file_paths\n elif(instance_id == ApplicationInstanceIDEnum.INST_MW):\n return self.__mw_file_paths\n elif(instance_id == ApplicationInstanceIDEnum.INST_OP):\n return self.__op_f_paths\n else:\n params = list()\n params.append(str(instance_id))\n params.append(\"ApplicationPaths.get_instances\")\n self.__logger.log_error(\"ERR_INTERNAL_INVALID_ID\", params)" }, { "alpha_fraction": 0.5016965866088867, "alphanum_fraction": 0.5071104168891907, "avg_line_length": 61.35916519165039, "blob_id": "6c71c706a7a4e8160941a9aadb2e75d69adf3fda", "content_id": "2c56f7dbb752c1e433f4f6ac7698afb210d69cde", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 92541, "license_type": "no_license", "max_line_length": 370, "num_lines": 1484, "path": "/src/rules_manager/rules_to_define_node_and_connectors.py", "repo_name": "srikanthreddybms/railml_to_rbc", "src_encoding": "UTF-8", "text": "\"\"\"\nRules for Define Nodes and Connector module, and also Segments\nThis module is used to initiate the rules manipulations of rules related to nodes and\nconnectors creation under rules manager component of RailMl to RBC route map\nconversion tool\n\n@copyright:\nAll rights reserved. ©2016. ALSTOM (Bangalore, India).\nThis computer program may not be used, copied, distributed, corrected,\nmodified, translated, transmitted or assigned without ALSTOM's prior\nwritten authorization.\n\n@date : 18th July 2016\n@author: Sanjay Kalshetty, Srikanth Reddy, Muhammed Sabith\n\"\"\"\n\nimport re\nfrom collections import OrderedDict\nimport collections\nfrom lxml import etree\nfrom itertools import groupby\nimport src.globals.globalds as globalds\nimport src.rules_manager.complementary_rules as compltr_rules\n\nclass node ():\n \"\"\"\n This class to handle all generic task of node creation.\n\n \"\"\"\n @staticmethod\n def create_nodes(track, rule_name, num, logger, element_ref=\"\", tb_te=\"\"):\n temp_node = num\n if rule_name == \"NodesAndConnectorsAtBufferStop\" or rule_name == \"NodesAndConnectorsAtBoundaries\":\n if num == 1:\n if rule_name == \"NodesAndConnectorsAtBufferStop\":\n globalds.nodes.append(nc_buffer_stop.create_node_at_bufferstop_table8(track, 's'))\n globalds.TOTAL_NODES = globalds.TOTAL_NODES + 1\n elif rule_name == \"NodesAndConnectorsAtBoundaries\":\n globalds.nodes.append(\n nc_boundries.create_node_at_boundries_table10(track, 's', logger,temp_node, element_ref, tb_te))\n globalds.TOTAL_NODES = globalds.TOTAL_NODES + 1\n else:\n letter_iter = globalds.LetterIter()\n node_counter = 0\n while num > 0:\n globalds.TOTAL_NODES = globalds.TOTAL_NODES + 1\n node_counter = node_counter + 1\n if num == 1:\n if rule_name == \"NodesAndConnectorsAtBufferStop\":\n globalds.nodes.append(\n nc_buffer_stop.create_node_at_bufferstop_table8(track, 's', node_counter))\n elif rule_name == \"NodesAndConnectorsAtBoundaries\":\n globalds.nodes.append(\n nc_boundries.create_node_at_boundries_table10(track, 's', logger,temp_node, element_ref, tb_te ))\n\n\n else:\n if rule_name == \"NodesAndConnectorsAtBufferStop\":\n globalds.nodes.append(\n nc_buffer_stop.create_node_at_bufferstop_table8(track, letter_iter.__next__(),\\\n node_counter))\n elif rule_name == \"NodesAndConnectorsAtBoundaries\":\n globalds.nodes.append(\n nc_boundries.create_node_at_boundries_table10(track, letter_iter.__next__(),logger, temp_node, \\\n element_ref,tb_te ))\n\n num = num - 1\n\nclass nc_buffer_stop():\n \"\"\"\n This class to manage creation of nodes and connectors at bufferStop points\n\n \"\"\"\n\n @staticmethod\n def execute(rule_data, logger):\n bs_add_info_params = ['releaseSpeed', 'distanceEoADp', 'endSectionTimer']\n for each_track in rule_data:\n for track in each_track[1]:\n if 'bufferStop' in track['trackBegin']:\n bufferstop_id = track['trackBegin']['bufferStop'][0]['bufferStop']['id']\n elif 'bufferStop' in track['trackEnd']:\n bufferstop_id = track['trackEnd']['bufferStop'][0]['bufferStop']['id']\n if ('bufferStop' in track['trackBegin'] or 'bufferStop' in track[\n 'trackEnd']) and 'bufferStopAdditionalInfo' in track:\n if bufferstop_id == track['bufferStopAdditionalInfo']['ref']:\n if ((not (all(name in track['bufferStopAdditionalInfo'] for name in bs_add_info_params)))\n or (track['bufferStopAdditionalInfo']['releaseSpeed'] == 0 \\\n and track['bufferStopAdditionalInfo']['distanceEoADp'] == 0 \\\n and track['bufferStopAdditionalInfo']['endSectionTimer'] == 0)):\n node.create_nodes(track, rule_data[0][0], 1, logger)\n else:\n node.create_nodes(track, rule_data[0][0], 3, logger)\n nc_buffer_stop.create_connectors(track, rule_data[0][0], 1)\n else:\n node.create_nodes(track, rule_data[0][0], 3, logger)\n nc_buffer_stop.create_connectors(track, rule_data[0][0], 1)\n elif 'bufferStopAdditionalInfo' not in track:\n if 'exitBoundary' in track:\n if 'trackBegin' in track and 'bufferStop' in track['trackBegin']:\n if 'dir' in track['exitBoundary'] == 'down':\n node.create_nodes(track, rule_data[0][0], 3, logger)\n nc_buffer_stop.create_connectors(track, rule_data[0][0], 1)\n elif 'trackEnd' in track and 'bufferStop' in track['trackEnd']:\n if 'dir' in track['exitBoundary'] == 'up':\n node.create_nodes(track, rule_data[0][0], 3, logger)\n nc_buffer_stop.create_connectors(track, rule_data[0][0], 1)\n else:\n node.create_nodes(track, rule_data[0][0], 1, logger)\n else:\n node.create_nodes(track,rule_data[0][0],1, logger)\n else:\n node.create_nodes(track, rule_data[0][0], 3, logger)\n nc_buffer_stop.create_connectors(track, rule_data[0][0], 1)\n\n\n @staticmethod\n def create_node_at_bufferstop_table8(track, node_name, node_counter=0):\n output_element_nodes = track['node'][0].split(\"|\")\n output_xpath = track['node'][1]\n root_element = output_xpath.split(\"/\")[-1]\n root_node = etree.Element(root_element)\n node = etree.SubElement(root_node, 'node')\n node_id = etree.SubElement(node, output_element_nodes[0])\n if 'bufferStop' in track['trackBegin']:\n node_id.text = \"nod%s_%s\" % (track['trackBegin']['bufferStop'][0]['bufferStop']['name'], node_name)\n elif 'bufferStop' in track['trackEnd']:\n node_id.text = \"nod%s_%s\" % (track['trackEnd']['bufferStop'][0]['bufferStop']['name'], node_name)\n node_km_point = etree.SubElement(node, output_element_nodes[1])\n if node_name == 's' and 'bufferStop' in track['trackBegin'] and node_counter > 1:\n last_node = globalds.nodes[-1][0]\n node_km_point.text = str(int(last_node.find(\"./kilometric_point\").text) - 1)\n elif node_name == 's' and 'bufferStop' in track['trackEnd'] and node_counter > 1:\n last_node = globalds.nodes[-1][0]\n node_km_point.text = str(int(last_node.find(\"./kilometric_point\").text) + 1)\n else:\n if 'bufferStop' in track['trackBegin'] and 'bufferStopAdditionalInfo' in track:\n if 'absPos' in track['trackBegin'] and all(name in track['bufferStopAdditionalInfo'] for name in\n ['distanceToEoA', 'distanceEoADp']):\n node_km_point.text = str(int(track['trackBegin']['absPos']) \\\n - (int(track['bufferStopAdditionalInfo']['distanceToEoA']) \\\n + int(track['bufferStopAdditionalInfo']['distanceEoADp'])))\n elif 'distanceEoADp' not in track['bufferStopAdditionalInfo'] and 'distanceToEoA' in track[\n 'bufferStopAdditionalInfo']:\n node_km_point.text = str(\n int(track['trackBegin']['absPos'] - track['bufferStopAdditionalInfo']['distanceToEoA']))\n elif 'distanceToEoA' not in track['bufferStopAdditionalInfo']:\n node_km_point.text = str(int(track['trackBegin']['absPos']))\n elif 'bufferStop' in track['trackEnd'] and 'bufferStopAdditionalInfo' in track:\n if 'absPos' in track['trackEnd'] and all(name in track['bufferStopAdditionalInfo'] for name in\n ['distanceToEoA', 'distanceEoADp']):\n node_km_point.text = str(int(track['trackEnd']['absPos']) \\\n + (int(track['bufferStopAdditionalInfo']['distanceToEoA']) \\\n + int(track['bufferStopAdditionalInfo']['distanceEoADp'])))\n elif 'distanceEoADp' not in track['bufferStopAdditionalInfo'] and 'distanceToEoA' in track[\n 'bufferStopAdditionalInfo']:\n node_km_point.text = str(\n int(track['trackEnd']['absPos'] + track['bufferStopAdditionalInfo']['distanceToEoA']))\n elif 'distanceToEoA' not in track['bufferStopAdditionalInfo']:\n node_km_point.text = track['trackEnd']['absPos']\n else:\n if 'bufferStop' in track['trackBegin']:\n node_km_point.text = track['trackBegin']['absPos']\n elif 'bufferStop' in track['trackEnd']:\n node_km_point.text = track['trackEnd']['absPos']\n\n node_line_id = etree.SubElement(node, output_element_nodes[2])\n node_line_id.text = '0'\n node_track_ref = etree.SubElement(node, output_element_nodes[3])\n node_track_ref.text = track['track']['id']\n # globals.NODES_INFO.append(node)\n return node, root_node, output_xpath\n\n @staticmethod\n def create_connectors(track, num, element_ref=\"\"):\n\n globalds.TOTAL_CONNECTORS = globalds.TOTAL_CONNECTORS + 1\n globalds.nodes.append(nc_buffer_stop.create_connector_at_bufferstop_table9(track))\n\n @staticmethod\n def create_connector_at_bufferstop_table9(track):\n output_element_nodes = track['connector'][0].split(\"|\")\n output_xpath = track['connector'][1]\n root_element = output_xpath.split(\"/\")[-1]\n connector_node = etree.Element(root_element)\n connector = etree.SubElement(connector_node, 'connector')\n connector_id = etree.SubElement(connector, output_element_nodes[0])\n if 'bufferStop' in track['trackBegin']:\n connector_id.text = \"cnr%s\" % (track['trackBegin']['bufferStop'][0]['bufferStop']['name'])\n elif 'bufferStop' in track['trackEnd']:\n connector_id.text = \"cnr%s\" % (track['trackEnd']['bufferStop'][0]['bufferStop']['name'])\n norm_dir_node_id = etree.SubElement(connector, output_element_nodes[1])\n if 'bufferStop' in track['trackBegin']:\n norm_dir_node_id.text = \"nod%s_b\" % (track['trackBegin']['bufferStop'][0]['bufferStop']['name'])\n elif 'bufferStop' in track['trackEnd']:\n norm_dir_node_id.text = \"nod%s_b\" % (track['trackEnd']['bufferStop'][0]['bufferStop']['name'])\n rev_dir_node_id = etree.SubElement(connector, output_element_nodes[2])\n if 'bufferStop' in track['trackBegin']:\n rev_dir_node_id.text = \"nod%s_a\" % (track['trackBegin']['bufferStop'][0]['bufferStop']['name'])\n elif 'bufferStop' in track['trackEnd']:\n rev_dir_node_id.text = \"nod%s_a\" % (track['trackEnd']['bufferStop'][0]['bufferStop']['name'])\n conn_object_ref = etree.SubElement(connector, output_element_nodes[3])\n conn_object_ref.text = track['track']['id']\n return connector, connector_node, output_xpath\n\nclass nc_boundries():\n \"\"\"\n This class to manage creation of nodes and connectors at boundaries\n\n \"\"\"\n\n @staticmethod\n def execute(rule_data,logger ):\n for each_track in rule_data:\n for track in each_track[1]:\n\n if ('entryBoundary' in track and (track['entryBoundary'].get('dummyPoint', None) == None))or \\\n ('exitBoundary' in track and (track['exitBoundary'].get('dummyPoint', None) == None)):\n\n # raise an warning message to indicate if dunmmyPoint absent\n param = list()\n param.append(\",'dummyPoint' attribute for entry/exit Boundary is missing, Track = %s\" \\\n % ( track['track']['id']))\n logger.log_error (\"ERR_MISIING_ATTR\", param)\n\n if (('entryBoundary' in track and track['entryBoundary'].get('dummyPoint', None) == 'false') and \\\n ('exitBoundary' not in track or ('exitBoundary' in track and \\\n track['exitBoundary']['dummyPoint'] == 'true'))):\n\n #Boundry case with one entryBoundary dummyPoint as False and exitBoundary dummyPoint as\n # True and vice versa\n element_ref = \"WithDummyPoint\"\n tb_te = 'entryBoundary'\n # Create only one node and with No connector\n node.create_nodes(track, rule_data[0][0],1, logger, element_ref,tb_te )\n\n elif (('exitBoundary' in track and track['exitBoundary']['dummyPoint'] == 'false') and \\\n ('entryBoundary' not in track or (\n 'entryBoundary' in track and track['entryBoundary']['dummyPoint'] == 'true'))):\n\n element_ref = \"WithDummyPoint\"\n tb_te = 'exitBoundary'\n # Create only one node and with No connector\n node.create_nodes(track, rule_data[0][0], 1, logger, element_ref, tb_te)\n\n elif (('entryBoundary' in track and track['entryBoundary'].get('dummyPoint', None) == 'false') and \\\n ('exitBoundary' in track and track['exitBoundary']['dummyPoint'] == 'false')):\n\n # case with two boundaries on the same track without dummy point\n element_ref = \"NoDummyPoint\"\n tb_te = 'entryBoundary'\n # Create only one node and with No connector\n node.create_nodes(track, rule_data[0][0], 1, logger, element_ref, tb_te)\n\n elif 'entryBoundary' in track and track['entryBoundary'].get('dummyPoint', None) == 'true':\n\n # Case for one entry/Exit Boundary dummyPoint True\n element_ref = \"WithDummyPoint\"\n tb_te = 'entryBoundary'\n # Create 4 nodes with 2 connectors\n\n node.create_nodes(track, rule_data[0][0], 4, logger, element_ref, tb_te)\n nc_boundries.create_connectors(track,2, logger, tb_te)\n\n elif 'exitBoundary' in track and track['exitBoundary']['dummyPoint'] == 'true':\n\n # Case for one entry/Exit Boundary dummyPoint True\n element_ref = \"WithDummyPoint\"\n tb_te = 'exitBoundary'\n # Create 4 nodes with 2 connectors\n node.create_nodes(track, rule_data[0][0], 4, logger, element_ref, tb_te)\n nc_boundries.create_connectors(track, 2, logger, tb_te)\n\n @staticmethod\n def create_nodes(track, num, element_ref=\"\"):\n if num == 1:\n globalds.nodes.append(node.create_node_at_boundries_table10(track, 's', element_ref))\n globalds.TOTAL_NODES = globalds.TOTAL_NODES + 1\n else:\n letter_iter = globalds.LetterIter()\n node_counter = 0\n while num > 0:\n globalds.TOTAL_NODES = globalds.TOTAL_NODES + 1\n node_counter = node_counter + 1\n if num == 1:\n globalds.nodes.append(node.create_node_at_boundries_table10(track, 's', node_counter, element_ref))\n else:\n globalds.nodes.append(\n node.create_node_at_boundries_table10(track, letter_iter.__next__(), node_counter, element_ref))\n num = num - 1\n\n @staticmethod\n def create_node_at_boundries_table10(track, node_name, logger, node_counter=0, element_ref=\"\", tb_te=\"\"):\n output_element_nodes = track['node'][0].split(\"|\")\n output_xpath = track['node'][1]\n root_element = output_xpath.split(\"/\")[-1]\n root_node = etree.Element(root_element)\n node = etree.SubElement(root_node, 'node')\n node_id = etree.SubElement(node, output_element_nodes[0])\n list_boudary = ['entryBoundary','exitBoundary' ]\n\n for boundary in list_boudary:\n\n if (boundary in track and (track[boundary].get('name', None) == None or \\\n track[boundary].get('absPos', None) == None or \\\n track[boundary].get('distanceToSingleNode', None) == None or \\\n track[boundary].get('dir', None) == None)):\n\n # raise an warning message to indicate if dunmmyPoint absent\n param = list()\n param.append(\",'absPos' or 'distanceToSingleNode' or 'dir' attributes for %s missing, Track = %s\" \\\n % (boundary, track['track']['id']))\n logger.log_error (\"ERR_MISIING_ATTR\", param)\n\n node_id.text = \"nod%s_%s\" % (track[tb_te]['name'], node_name)\n node_km_point = etree.SubElement(node, output_element_nodes[1])\n if element_ref == \"WithDummyPoint\" :\n if node_name != 's':\n node_km_point.text = str(int(track[tb_te]['absPos']))\n elif node_name == 's':\n if tb_te == 'entryBoundary':\n if track[tb_te]['dir'] == 'up':\n node_km_point.text = str(int(track['entryBoundary']['absPos']) - int(track['entryBoundary'] \\\n ['distanceToSingleNode']))\n elif track[tb_te]['dir'] == 'down':\n node_km_point.text = str(int(track['entryBoundary']['absPos']) + int(track['entryBoundary'] \\\n ['distanceToSingleNode']))\n\n elif tb_te == 'exitBoundary':\n if track[tb_te]['dir'] == 'up':\n node_km_point.text = str(int(track['exitBoundary']['absPos']) + int(track['exitBoundary'] \\\n ['distanceToSingleNode']))\n elif track[tb_te]['dir'] == 'down':\n node_km_point.text = str(int(track['exitBoundary']['absPos']) - int(track['exitBoundary'] \\\n ['distanceToSingleNode']))\n\n elif element_ref == \"NoDummyPoint\":\n if node_name != 's':\n node_km_point.text = str(int(track[tb_te]['absPos']))\n\n elif node_name == 's':\n if tb_te == 'entryBoundary':\n if track[tb_te]['dir'] == 'up':\n node_km_point.text = str(min( \\\n (int(track['entryBoundary']['absPos']) - int(track['entryBoundary']['distanceToSingleNode'])), \\\n (int(track['exitBoundary']['absPos']) - int(track['exitBoundary']['distanceToSingleNode']))))\n elif track[tb_te]['dir'] == 'down':\n node_km_point.text = str(max( \\\n (int(track['entryBoundary']['absPos']) + int(track['entryBoundary']['distanceToSingleNode'])), \\\n (int(track['exitBoundary']['absPos']) + int(track['exitBoundary']['distanceToSingleNode']))))\n\n\n node_line_id = etree.SubElement(node, output_element_nodes[2])\n node_line_id.text = '0'\n node_track_ref = etree.SubElement(node, output_element_nodes[3])\n\n if (node_counter > 1 and node_name == 'c') or (node_counter > 1 and node_name == 's'):\n node_track_ref.text = \"xxxtrack_%s\" % (track[tb_te]['name'])\n\n elif (node_counter == 1 and node_name == 's') or ((node_counter > 1 and node_name == 'a') or\n (node_counter > 1 and node_name == 'b')) :\n\n node_track_ref.text = track['track']['id']\n\n return node, root_node, output_xpath\n\n @staticmethod\n def create_connectors(track,nb_conctr, logger, tb_te, element_ref=\"\"):\n\n if tb_te == 'entryBoundary' and track[tb_te]['dir']=='up' or tb_te == 'exitBoundary' and track[tb_te]['dir']=='down' :\n\n globalds.nodes.append(nc_boundries.create_connector_at_boundries_table12(track, tb_te, \"ab\"))\n globalds.nodes.append(nc_boundries.create_connector_at_boundries_table12(track, tb_te, \"cb\"))\n globalds.TOTAL_CONNECTORS = globalds.TOTAL_CONNECTORS + 2\n\n elif tb_te == 'entryBoundary' and track[tb_te]['dir']=='down' or tb_te == 'exitBoundary' and track[tb_te]['dir']=='up' :\n\n globalds.nodes.append(nc_boundries.create_connector_at_boundries_table12(track, tb_te, \"ab\"))\n globalds.nodes.append(nc_boundries.create_connector_at_boundries_table12(track, tb_te, \"ac\"))\n globalds.TOTAL_CONNECTORS = globalds.TOTAL_CONNECTORS + 2\n\n @staticmethod\n def create_connector_at_boundries_table12(track,tb_te, comb):\n output_element_nodes = track['connector'][0].split(\"|\")\n output_xpath = track['connector'][1]\n root_element = output_xpath.split(\"/\")[-1]\n connector_node = etree.Element(root_element)\n connector = etree.SubElement(connector_node, 'connector')\n connector_id = etree.SubElement(connector, output_element_nodes[0])\n norm_dir_node_id = etree.SubElement(connector, output_element_nodes[1])\n rev_dir_node_id = etree.SubElement(connector, output_element_nodes[2])\n conn_object_ref = etree.SubElement(connector, output_element_nodes[3])\n\n\n connector_id.text = \"cnr%s_%s\" % (track[tb_te]['name'],comb)\n norm_dir_node_id.text = \"nod%s_%s\" % (track[tb_te]['name'],comb[1])\n rev_dir_node_id.text = \"nod%s_%s\" % (track[tb_te]['name'],comb[0])\n conn_object_ref.text = track[tb_te]['id']\n\n return connector, connector_node, output_xpath\n\nclass nc_kpjump():\n \"\"\"\n This class to manage creation of nodes and connectors at Killometric point Jump point\n\n \"\"\"\n\n @staticmethod\n def check_if_kpjump_req(Tb_or_Te, track,logger):\n\n create_node = True\n\n if not any (name in track for name in ['connections', 'separators']):\n\n create_node = True\n\n if 'separators' in track:\n for seprtr in track['separators']['separator']:\n if 'signalAdditionalInfos' in track:\n\n for signal_info in track['signalAdditionalInfos']['signalAdditionalInfo']:\n if signal_info['signalAdditionalInfo'].get('associatedSeparator', None) == seprtr['separator']['id']:\n\n if track[Tb_or_Te].get('absPos', None) is not None and seprtr['separator'].get('absPos',None) is not None:\n # Do not create any node when separator is at the location of TrackBegin/End\n #This is achived by setting create_node = False\n if track[Tb_or_Te]['absPos'] == seprtr['separator']['absPos']:\n create_node = False\n else:\n param = list()\n param.append(\", 'absPos' attribute for '%s' or 'separator' with id = %s missing, Track = %s\" \\\n %(Tb_or_Te,seprtr['separator']['id'], track['track']['id']))\n logger.log_error(\"ERR_MISIING_ATTR\", param)\n\n\n if 'subStopLocations' in track:\n for substop in track['subStopLocations']['subStopLocation']:\n if substop['subStopLocation'].get('associatedObject', None) == seprtr['separator']['id']:\n if track[Tb_or_Te].get('absPos', None) is not None and seprtr['separator'].get('absPos',\n None) is not None:\n # Do not create any node when separator is at the location of TrackBegin/End\n # This is achived by setting create_node = False\n if track[Tb_or_Te]['absPos'] == seprtr['separator']['absPos']:\n create_node = False\n\n else:\n param = list()\n param.append(\n \", 'absPos' attribute for '%s' or 'separator' with id = %s missing, Track = %s\" \\\n % (Tb_or_Te, seprtr['separator']['id'], track['track']['id']))\n logger.log_error(\"ERR_MISIING_ATTR\", param)\n\n\n if 'virtualSignals' in track:\n for virtsignal in track['virtualSignals']['virtualSignal']:\n if substop['virtualSignal'].get('associatedObject', None) == seprtr['separator']['id']:\n if track[Tb_or_Te].get('absPos', None) is not None and seprtr['separator'].get('absPos',\n None) is not None:\n # Do not create any node when separator is at the location of TrackBegin/End\n # This is achived by setting create_node = False\n if track[Tb_or_Te]['absPos'] == seprtr['separator']['absPos']:\n create_node = False\n\n else:\n param = list()\n param.append(\n \", 'absPos' attribute for '%s' or 'separator' with id = %s missing, Track = %s\" \\\n % (Tb_or_Te, seprtr['separator']['id'], track['track']['id']))\n logger.log_error(\"ERR_MISIING_ATTR\", param)\n\n if 'connections' in track:\n\n for switch_cross in track['connections']['connection']:\n\n if 'switch' in switch_cross:\n if track[Tb_or_Te].get('absPos', None) is not None and switch_cross['switch'].get('absPos', None) is not None:\n\n if track[Tb_or_Te]['absPos'] == switch_cross['switch']['absPos']:\n create_node = False\n else:\n param = list()\n param.append(\n \", 'absPos' attribute for '%s' or 'switch' with id = %s missing, Track = %s\" \\\n % (Tb_or_Te, seprtr['switch']['id'], track['track']['id']))\n logger.log_error(\"ERR_MISIING_ATTR\", param)\n\n if 'crossing' in switch_cross:\n if track[Tb_or_Te].get('absPos', None) is not None and \\\n switch_cross['crossing'].get('absPos', None) is not None:\n\n if track[Tb_or_Te]['absPos'] == switch_cross['crossing']['absPos']:\n create_node = False\n else:\n param = list()\n param.append(\n \", 'absPos' attribute for '%s' or 'crossing' with id = %s missing, Track = %s\" \\\n % (Tb_or_Te, seprtr['crossing']['id'], track['track']['id']))\n logger.log_error(\"ERR_MISIING_ATTR\", param)\n\n return create_node\n\n\n @staticmethod\n def execute(rule_data, logger):\n\n is_node_required = False\n conn_ref_temp = \"\"\n\n list_track_extrmty = list()\n list_track_extrmty = ['trackBegin', 'trackEnd']\n for each_track in rule_data:\n for track1 in each_track[1]:\n for track_extr in list_track_extrmty:\n con_in_track_begin = \"\"\n\n if 'connection' in track1[track_extr]:\n conn_ref= track1[track_extr]['connection'][0]['connection']['ref']\n\n for track2 in each_track[1]:\n\n for track_intr in list_track_extrmty:\n\n if 'connection' in track2[track_intr]and (conn_ref == track2[track_intr]['connection'][0]['connection']['id'] \\\n and conn_ref_temp != track2[track_intr]['connection'][0]['connection']['ref'] ):\n\n conn_ref_temp = conn_ref\n is_node_required = nc_kpjump.check_if_kpjump_req(track_extr, track1, logger)\n is_node_required = is_node_required and nc_kpjump.check_if_kpjump_req(track_intr, track2, logger)\n if is_node_required == True:\n nc_kpjump.create_node(track1,track_extr, track2,track_intr )\n nc_kpjump.create_connectors(track1,track_extr, track2,track_intr)\n\n @staticmethod\n def create_node(track_first,extr_first, track_second, extr_second):\n\n globalds.nodes.append(nc_kpjump.create_node_at_kpjump_table22(track_first,extr_first, track_second, extr_second, 'a'))\n globalds.TOTAL_NODES = globalds.TOTAL_NODES + 1\n globalds.nodes.append(nc_kpjump.create_node_at_kpjump_table22(track_first,extr_first, track_second, extr_second, 'b'))\n globalds.TOTAL_NODES = globalds.TOTAL_NODES + 1\n\n @staticmethod\n def create_node_at_kpjump_table22(track_first, extr_first, track_second, extr_second, profix):\n output_element_nodes = track_first['node'][0].split(\"|\")\n output_xpath = track_first['node'][1]\n root_element = output_xpath.split(\"/\")[-1]\n root_node = etree.Element(root_element)\n node = etree.SubElement(root_node, 'node')\n node_id = etree.SubElement(node, output_element_nodes[0])\n node_km_point = etree.SubElement(node, output_element_nodes[1])\n node_track_ref = etree.SubElement(node, output_element_nodes[3])\n\n if track_first[extr_first]['id'] < track_second[extr_second]['id']:\n node_id.text = \"nod%s_%s\" % (track_first[extr_first]['id'], profix)\n else:\n node_id.text = \"nod%s_%s\" % (track_second[extr_second]['id'], profix)\n\n if profix == 'a':\n node_km_point.text = str(int(track_first[extr_first]['absPos']))\n node_track_ref.text = track_first['track']['name']\n elif profix == 'b':\n node_km_point.text = str(int(track_second[extr_second]['absPos']))\n node_track_ref.text = track_second['track']['name']\n\n node_line_id = etree.SubElement(node, output_element_nodes[2])\n node_line_id.text = '0'\n\n return node, root_node, output_xpath\n\n @staticmethod\n def create_connectors(track_first,extr_first, track_second, extr_second, element_ref=\"\"):\n\n globalds.TOTAL_CONNECTORS = globalds.TOTAL_CONNECTORS + 1\n globalds.nodes.append(nc_kpjump.create_connector_at_kpjump_table23(track_first,extr_first, track_second, extr_second))\n\n @staticmethod\n def create_connector_at_kpjump_table23(track_first,extr_first, track_second, extr_second):\n output_element_nodes = track_first['connector'][0].split(\"|\")\n output_xpath = track_first['connector'][1]\n root_element = output_xpath.split(\"/\")[-1]\n connector_node = etree.Element(root_element)\n connector = etree.SubElement(connector_node, 'connector')\n connector_id = etree.SubElement(connector, output_element_nodes[0])\n norm_dir_node_id = etree.SubElement(connector, output_element_nodes[1])\n rev_dir_node_id = etree.SubElement(connector, output_element_nodes[2])\n\n if track_first[extr_first]['id'] < track_second[extr_second]['id']:\n connector_id.text = \"cnr%s\" % (track_first[extr_first]['id'])\n norm_dir_node_id.text = \"nod%s_b\" % (track_first[extr_first]['id'])\n rev_dir_node_id.text = \"nod%s_a\" % (track_first[extr_first]['id'])\n else:\n connector_id.text = \"cnr%s\" % (track_second[extr_second]['id'])\n norm_dir_node_id.text = \"nod%s_b\" % (track_second[extr_second]['id'])\n rev_dir_node_id.text = \"nod%s_a\" % (track_second[extr_second]['id'])\n\n conn_object_ref = etree.SubElement(connector, output_element_nodes[3])\n conn_object_ref.text = \"\"\n return connector, connector_node, output_xpath\n\nclass nc_switch():\n \"\"\"\n This class to manage creation of nodes and connectors at switch points\n \"\"\"\n\n switch_nodes = []\n non_switch_nodes = []\n crossing_additional_info_switch_list = []\n @staticmethod\n def execute(rule_data):\n nc_switch.switch_nodes, nc_switch.non_switch_nodes = nc_switch.get_switch_nonswitch_nodes(rule_data)\n for track in nc_switch.switch_nodes:\n check_link_crossing_switch = False\n check_for_no_create_switch = False\n track_begin_abs_position = None\n track_end_abs_position = None\n entry_boundary_abs_position = None\n exit_boundary_abs_position = None\n switch_id = \"\"\n switch_name = \"\"\n switch_defined_at_track = False\n crossing_found = False\n node_a_km_point = \"\"\n track_name = track['track']['name']\n if 'bufferStop' in track['trackBegin'] or 'openEnd' in track['trackBegin']:\n track_begin_abs_position = int(track['trackBegin']['absPos'])\n if 'bufferStop' in track['trackEnd'] or 'openEnd' in track['trackEnd']:\n track_end_abs_position = int(track['trackEnd']['absPos'])\n if 'entryBoundary' in track:\n entry_boundary_abs_position = int(track['entryBoundary']['absPos'])\n if 'exitBoundary' in track:\n exit_boundary_abs_position = int(track['exitBoundary']['absPos'])\n if 'connections' in track:\n #if 'crossing' not in track:\n if type(track['connections']['connection']) is list:\n for value1 in track['connections']['connection']:\n if 'crossing' in value1:\n crossing_found = True\n continue\n if crossing_found is True:\n if 'connection' in value1:\n continue\n if 'switch' in value1:\n crossing_found = False\n switch_id = value1['switch']['id']\n switch_name = value1['switch']['name']\n switch_abs_position = int(value1['switch']['absPos'])\n check_for_no_create_switch = nc_switch.check_element_position(track_begin_abs_position,\n track_end_abs_position,\n entry_boundary_abs_position,\n exit_boundary_abs_position,\n switch_abs_position)\n continue\n if switch_defined_at_track is False:\n if switch_abs_position == int(track['trackBegin']['absPos']):\n node_a_km_point = int(track['trackBegin']['absPos'])\n switch_defined_at_track = \"trackBegin\"\n elif switch_abs_position == int(track['trackEnd']['absPos']):\n node_a_km_point = int(track['trackEnd']['absPos'])\n switch_defined_at_track = \"trackEnd\"\n if 'connection' in value1:\n connection_orientation = value1['connection']['orientation']\n if 'crossingAdditionalInfo' in track and 'switch' in track[\n 'crossingAdditionalInfo'] and type(track['crossingAdditionalInfo']['switch']) is list:\n for value2 in track['crossingAdditionalInfo']['switch']:\n nc_switch.crossing_additional_info_switch_list.append(value2['switch']['switchRef'])\n # if switch_id == value2['switch']['switchRef']:\n # check_link_crossing_switch = True\n #break\n if switch_id in nc_switch.crossing_additional_info_switch_list:\n check_link_crossing_switch = True\n if check_link_crossing_switch is False and check_for_no_create_switch is False:\n nc_switch.create_nodes(rule_data, track, rule_data[0][0], 3, (switch_name, switch_abs_position, track_name, switch_defined_at_track, node_a_km_point))\n if connection_orientation == \"outgoing\":\n postfix = [\"ab\", \"ac\"]\n elif connection_orientation == \"incoming\":\n postfix = [\"ab\", \"cb\"]\n nc_switch.create_connectors(track, rule_data[0][0], 2, (switch_id, switch_name, postfix))\n switch_defined_at_track = False\n nc_switch.switch_nodes, nc_switch.non_switch_nodes = [], []\n\n @staticmethod\n def create_nodes(rule_data, track, rule_name, num, element_ref=\"\"):\n letter_iter = globalds.LetterIter()\n while num > 0:\n globalds.TOTAL_NODES = globalds.TOTAL_NODES + 1\n node_name = letter_iter.__next__()\n if element_ref[3] is False:\n if node_name == \"a\" or node_name == \"b\":\n globalds.nodes.append(nc_switch.create_node_at_switch_table19(track, node_name, element_ref))\n elif node_name == \"c\":\n km_point, ref_track = nc_switch.calculate_km_point_for_switch_at_c(element_ref[0], node_name)\n node_params = (km_point, ref_track)\n globalds.nodes.append(nc_switch.create_node_at_switch_table19(track, node_name, element_ref, node_params))\n else:\n if node_name == \"a\":\n globalds.nodes.append(\n nc_switch.create_node_at_switch_table19(track, node_name, element_ref))\n if node_name == \"b\":\n km_point, ref_track = nc_switch.calculate_km_point_for_switch_at_a_b(rule_data, element_ref, node_name)\n node_params = (km_point, ref_track)\n globalds.nodes.append(nc_switch.create_node_at_switch_table19(track, node_name, element_ref, node_params))\n elif node_name == \"c\":\n km_point, ref_track = nc_switch.calculate_km_point_for_switch_at_c(element_ref[0], node_name)\n node_params = (km_point, ref_track)\n globalds.nodes.append(nc_switch.create_node_at_switch_table19(track, node_name, element_ref, node_params))\n num = num - 1\n\n\n @staticmethod\n def create_node_at_switch_table19(track,node_name,switch_details,node_params=\"\"):\n output_element_nodes = track['node'][0].split(\"|\")\n output_xpath = track['node'][1]\n root_element = output_xpath.split(\"/\")[-1]\n root_node = etree.Element(root_element)\n node = etree.SubElement(root_node, 'node')\n node_id = etree.SubElement(node, output_element_nodes[0])\n node_id.text = \"nod%s_%s\" % (switch_details[0], node_name)\n node_km_point = etree.SubElement(node, output_element_nodes[1])\n if switch_details[3] is False:\n if node_name == \"a\" or node_name == \"b\":\n node_km_point.text = \"%s\" % str(switch_details[1])\n elif node_name == \"c\":\n node_km_point.text = \"%s\" % str(node_params[0])\n else:\n if node_name == \"a\":\n node_km_point.text = \"%s\" % str(switch_details[4])\n if node_name == \"b\":\n node_km_point.text = \"%s\" % str(node_params[0])\n elif node_name == \"c\":\n node_km_point.text = \"%s\" % str(node_params[0])\n node_line_id = etree.SubElement(node, output_element_nodes[2])\n node_line_id.text = '0'\n node_track_ref = etree.SubElement(node, output_element_nodes[3])\n if switch_details[3] is False:\n if node_name == \"a\" or node_name == \"b\":\n node_track_ref.text = \"%s\" % str(switch_details[2])\n elif node_name == \"c\":\n node_track_ref.text = \"%s\" % str(node_params[1])\n else:\n if node_name == \"a\":\n node_track_ref.text = \"%s\" % str(switch_details[2])\n if node_name == \"b\":\n node_track_ref.text = \"%s\" % str(node_params[1])\n elif node_name == \"c\":\n node_track_ref.text = \"%s\" % str(node_params[1])\n\n return node, root_node, output_xpath\n\n @staticmethod\n def create_connectors(track, rule_name, num, element_ref=\"\"):\n while num > 0:\n globalds.TOTAL_CONNECTORS = globalds.TOTAL_CONNECTORS + 1\n globalds.nodes.append(nc_switch.create_connector_at_switch_table21(track, element_ref[0], element_ref[1],\n element_ref[2][len(element_ref[2]) - num]))\n num = num - 1\n\n @staticmethod\n def create_connector_at_switch_table21(track, switch_id, switch_name, postfix):\n output_element_nodes = track['connector'][0].split(\"|\")\n output_xpath = track['connector'][1]\n root_element = output_xpath.split(\"/\")[-1]\n connector_node = etree.Element(root_element)\n connector = etree.SubElement(connector_node, 'connector')\n connector_id = etree.SubElement(connector, output_element_nodes[0])\n connector_id.text = \"cnr%s_%s\" % (switch_name, postfix)\n norm_dir_node_id = etree.SubElement(connector, output_element_nodes[1])\n if postfix == \"ab\" or postfix == \"cb\":\n norm_dir_node_id.text = \"nod%s_b\" % switch_name\n elif postfix == \"ac\":\n norm_dir_node_id.text = \"nod%s_c\" % switch_name\n rev_dir_node_id = etree.SubElement(connector, output_element_nodes[2])\n if postfix == \"ab\" or postfix == \"ac\":\n rev_dir_node_id.text = \"nod%s_a\" % switch_name\n elif postfix == \"cb\":\n rev_dir_node_id.text = \"nod%s_c\" % switch_name\n conn_object_ref = etree.SubElement(connector, output_element_nodes[3])\n conn_object_ref.text = switch_id\n return connector, connector_node, output_xpath\n\n @staticmethod\n def check_element_position(track_begin_abs_position, track_end_abs_position, entry_boundary_abs_position,\n exit_boundary_abs_position, switch_abs_position):\n check_for_no_create_switch = False\n if track_begin_abs_position is not None:\n if entry_boundary_abs_position is not None:\n if (\n switch_abs_position > track_begin_abs_position and switch_abs_position < entry_boundary_abs_position) or \\\n (\n switch_abs_position > entry_boundary_abs_position and switch_abs_position < track_begin_abs_position):\n check_for_no_create_switch = True\n if exit_boundary_abs_position is not None:\n if (\n switch_abs_position > track_begin_abs_position and switch_abs_position < exit_boundary_abs_position) or \\\n (\n switch_abs_position > exit_boundary_abs_position and switch_abs_position < track_begin_abs_position):\n check_for_no_create_switch = True\n if track_end_abs_position is not None:\n if entry_boundary_abs_position is not None:\n if (\n switch_abs_position >= track_end_abs_position and switch_abs_position <= entry_boundary_abs_position) or \\\n (\n switch_abs_position > entry_boundary_abs_position and switch_abs_position < track_end_abs_position):\n check_for_no_create_switch = True\n if exit_boundary_abs_position is not None:\n if (\n switch_abs_position > track_end_abs_position and switch_abs_position < exit_boundary_abs_position) or \\\n (\n switch_abs_position > exit_boundary_abs_position and switch_abs_position < track_end_abs_position):\n check_for_no_create_switch = True\n return check_for_no_create_switch\n\n @staticmethod\n def get_switch_nonswitch_nodes(tracks):\n for track_info in tracks:\n for each_track in track_info[1]:\n crossing_exists = False\n switch_exists = False\n if 'connections' in each_track:\n for each_element in each_track['connections']['connection']:\n if 'switch' in each_element:\n switch_exists = True\n break\n # if 'crossing' in each_element:\n # crossing_exists = True\n if switch_exists is True and crossing_exists is False:\n nc_switch.switch_nodes.append(each_track)\n else:\n counter = 0\n for each_node in nc_switch.switch_nodes:\n if each_track['track']['name'] == each_node['track']['name']:\n counter = counter + 1\n break\n if counter == 0:\n nc_switch.non_switch_nodes.append(each_track)\n return nc_switch.switch_nodes, nc_switch.non_switch_nodes\n\n @staticmethod\n def calculate_km_point_for_switch_at_a_b(rule_data, switch_details, node_name):\n switch_name = switch_details[0]\n switch_defined_at_track = switch_details[3]\n match_switch_name = False\n km_point, ref_track = \"\", \"\"\n for each_switch_node in nc_switch.switch_nodes:\n if 'connections' in each_switch_node and 'connection' in each_switch_node['connections'] and type(\n each_switch_node['connections']['connection']) is list:\n for each_element in each_switch_node['connections']['connection']:\n if 'switch' in each_element and each_element['switch']['name'] == switch_name:\n match_switch_name = True\n break\n # if match_switch_name is False:\n # continue\n for each_node in rule_data:\n for each_nonswitch_node in each_node[1]:\n if match_switch_name is True:\n if switch_defined_at_track == \"trackBegin\":\n if 'connection' in each_switch_node['trackBegin']:\n if 'connection' in each_nonswitch_node['trackBegin']:\n if each_switch_node['trackBegin']['connection'][0]['connection']['id'] == \\\n each_nonswitch_node['trackBegin']['connection'][0]['connection']['ref']:\n if node_name == \"b\":\n km_point = each_nonswitch_node['trackBegin']['absPos']\n ref_track = each_nonswitch_node['track']['name']\n return km_point, ref_track\n if 'connection' in each_nonswitch_node['trackEnd']:\n if each_switch_node['trackBegin']['connection'][0]['connection']['id'] == \\\n each_nonswitch_node['trackEnd']['connection'][0]['connection']['ref']:\n if node_name == \"b\":\n km_point = each_nonswitch_node['trackEnd']['absPos']\n ref_track = each_nonswitch_node['track']['name']\n return km_point, ref_track\n if switch_defined_at_track == \"trackEnd\":\n if 'connection' in each_switch_node['trackEnd']:\n if 'connection' in each_nonswitch_node['trackBegin']:\n if each_switch_node['trackEnd']['connection'][0]['connection']['id'] == \\\n each_nonswitch_node['trackBegin']['connection'][0]['connection']['ref']:\n if node_name == \"b\":\n km_point = each_nonswitch_node['trackBegin']['absPos']\n ref_track = each_nonswitch_node['track']['name']\n return km_point, ref_track\n if 'connection' in each_nonswitch_node['trackEnd']:\n if each_switch_node['trackEnd']['connection'][0]['connection']['id'] == \\\n each_nonswitch_node['trackEnd']['connection'][0]['connection']['ref']:\n if node_name == \"b\":\n km_point = each_nonswitch_node['trackEnd']['absPos']\n ref_track = each_nonswitch_node['track']['name']\n return km_point, ref_track\n return km_point, ref_track\n\n @staticmethod\n def calculate_km_point_for_switch_at_c(switch_name, node_name):\n km_point, ref_track = \"\", \"\"\n found_switch = False\n for each_switch_node in nc_switch.switch_nodes:\n for each_nonswitch_node in nc_switch.non_switch_nodes:\n if 'connections' in each_switch_node and 'connection' in each_switch_node['connections'] and type(\n each_switch_node['connections']['connection']) is list:\n for each_element in each_switch_node['connections']['connection']:\n if 'switch' in each_element and each_element['switch']['name'] != switch_name:\n continue\n elif 'switch' in each_element and found_switch is False and each_element['switch']['name'] == switch_name:\n found_switch = True\n continue\n if found_switch is True and 'connection' in each_element:\n if 'connection' in each_nonswitch_node['trackBegin']:\n if str(each_element['connection']['id']) == str(each_nonswitch_node['trackBegin']['connection'][0]['connection']['ref']):\n km_point = each_nonswitch_node['trackBegin']['absPos']\n ref_track = each_nonswitch_node['track']['name']\n return km_point, ref_track\n if 'connection' in each_nonswitch_node['trackEnd']:\n if str(each_element['connection']['id']) == str(each_nonswitch_node['trackEnd']['connection'][0]['connection']['ref']):\n km_point = each_nonswitch_node['trackEnd']['absPos']\n ref_track = each_nonswitch_node['track']['name']\n return km_point, ref_track\n found_switch = False\n return km_point, ref_track\n\n\nclass nc_crossing():\n \"\"\"\n This class to manage creation of nodes and connectors at crossings points\n\n \"\"\"\n crossing_nodes = []\n non_crossing_nodes = []\n\n @staticmethod\n def execute(rule_data):\n nc_crossing.crossing_nodes, nc_crossing.non_crossing_nodes = nc_crossing.get_crossing_noncrossing_nodes(rule_data)\n for track in nc_crossing.crossing_nodes:\n check_for_no_create_crossing = False\n track_begin_abs_position = None\n track_end_abs_position = None\n entry_boundary_abs_position = None\n exit_boundary_abs_position = None\n crossing_defined_at_track = False\n crossing_abs_position = track['crossing']['absPos']\n if 'bufferStop' in track['trackBegin'] or 'openEnd' in track['trackBegin']:\n track_begin_abs_position = int(track['trackBegin']['absPos'])\n if 'bufferStop' in track['trackEnd'] or 'openEnd' in track['trackEnd']:\n track_end_abs_position = int(track['trackEnd']['absPos'])\n if 'entryBoundary' in track:\n entry_boundary_abs_position = int(track['entryBoundary']['absPos'])\n if 'exitBoundary' in track:\n exit_boundary_abs_position = int(track['exitBoundary']['absPos'])\n if 'connections' in track:\n if type(track['connections']['connection']) is list:\n connection_ids = []\n connection_counter = 0\n crossing_found = False\n for value1 in track['connections']['connection']:\n if 'crossing' not in value1 and crossing_found is False :\n continue\n if 'crossing' in value1:\n crossing_defined_at_track = True\n crossing_found = True\n crossing_id = value1['crossing']['id']\n crossing_name = value1['crossing']['name']\n crossing_type = value1['crossing']['type']\n crossing_abs_position = int(value1['crossing']['absPos'])\n check_for_no_create_crossing = nc_switch.check_element_position(track_begin_abs_position,\n track_end_abs_position,\n entry_boundary_abs_position,\n exit_boundary_abs_position,\n crossing_abs_position)\n continue\n if crossing_defined_at_track is True:\n if crossing_abs_position == int(track['trackBegin']['absPos']):\n node_a_km_point = int(track['trackBegin']['absPos'])\n crossing_defined_at_track = \"trackBegin\"\n elif crossing_abs_position == int(track['trackEnd']['absPos']):\n node_a_km_point = int(track['trackEnd']['absPos'])\n crossing_defined_at_track = \"trackEnd\"\n if 'connection' in value1:\n connection_counter = connection_counter + 1\n connection_ids.append((value1['connection']['id'],value1['connection']['orientation']))\n continue\n if crossing_type == 'doubleSwitchCrossing' or crossing_type == 'simpleSwitchCrossing':\n if check_for_no_create_crossing is False:\n nc_crossing.create_nodes(track, rule_data[0][0], 4, (crossing_name,crossing_defined_at_track,crossing_abs_position))\n nc_crossing.create_connectors(track, rule_data[0][0], 2, ['ab', 'cd'])\n elif crossing_type == 'simpleCrossing':\n if check_for_no_create_crossing is False:\n if ('virtualSignal' in track and 'associatedObject' in track['virtualSignal'] and track['crossing'][\n 'id'] == track['virtualSignal']['associatedObject']) \\\n or ('subStopLocation' in track and 'associatedObject' in track['subStopLocation'] and\n track['crossing']['id'] == track['subStopLocation']['associatedObject']):\n nc_crossing.create_nodes(track, rule_data[0][0], 4, (crossing_name,crossing_defined_at_track,crossing_abs_position))\n nc_crossing.create_connectors(track, rule_data[0][0], 2, ['ab', 'cd'])\n if crossing_type == 'doubleSwitchCrossing':\n nc_crossing.create_connectors(track, rule_data[0][0], 2, {'add_two_connectors': ['ad', 'cb']})\n elif crossing_type == 'simpleSwitchCrossing':\n check_link_crossing_switch = False\n switch_dict = OrderedDict()\n if 'crossingAdditionalInfo' in track and track['crossingAdditionalInfo']['ref'] == track['crossing'][\n 'id']:\n if type(track['crossing']['connection']) is list:\n for value1 in track['crossing']['connection']:\n if 'switch' in value1:\n if type(track['crossingAdditionalInfo']['switch']) is list:\n for value2 in track['crossingAdditionalInfo']['switch']:\n if value1['switch']['id'] == value2['switch']['switchRef']:\n check_link_crossing_switch = True\n break\n else:\n continue\n if check_link_crossing_switch is True:\n nc_crossing.create_connectors(track, rule_data[0][0], 1, {'add_one_connector': ['ad']})\n else:\n nc_crossing.create_connectors(track, rule_data[0][0], 1, {'add_one_connector': ['cb']})\n crossing_found = False\n crossing_defined_at_track = False\n check_link_crossing_switch = False\n nc_crossing.crossing_nodes = []\n nc_crossing.non_crossing_nodes = []\n\n @staticmethod\n def create_nodes(track, rule_name, num, element_ref=\"\"):\n letter_iter = globalds.LetterIter()\n while num > 0:\n globalds.TOTAL_NODES = globalds.TOTAL_NODES + 1\n node_name = letter_iter.__next__()\n if node_name == \"a\":\n globalds.nodes.append(\n nc_crossing.create_node_at_crossing_table17(track, node_name, element_ref))\n if node_name == \"b\":\n km_point, ref_track = nc_crossing.calculate_crossing_km_point_at_a_b(node_name, element_ref)\n globalds.nodes.append(nc_crossing.create_node_at_crossing_table17(track, node_name, (km_point, ref_track)))\n elif node_name == \"c\" or node_name == \"d\":\n km_point, ref_track = nc_crossing.calculate_crossing_km_point_at_c_d(element_ref[0], node_name)\n globalds.nodes.append(nc_crossing.create_node_at_crossing_table17(track, node_name, (km_point, ref_track)))\n num = num - 1\n\n\n @staticmethod\n def create_node_at_crossing_table17(track, node_name, crossing_details):\n output_element_nodes = track['node'][0].split(\"|\")\n output_xpath = track['node'][1]\n root_element = output_xpath.split(\"/\")[-1]\n root_node = etree.Element(root_element)\n node = etree.SubElement(root_node, 'node')\n node_id = etree.SubElement(node, output_element_nodes[0])\n node_id.text = \"nod%s_%s\" % (track['crossing']['name'], node_name)\n node_km_point = etree.SubElement(node, output_element_nodes[1])\n if node_name == \"a\":\n node_km_point.text = str(crossing_details[2])\n else:\n node_km_point.text = str(crossing_details[0])\n node_line_id = etree.SubElement(node, output_element_nodes[2])\n node_line_id.text = '0'\n node_track_ref = etree.SubElement(node, output_element_nodes[3])\n if node_name == \"a\":\n node_track_ref.text = str(track['track']['name'])\n else:\n node_track_ref.text = str(crossing_details[1])\n # globals.NODES_INFO.append(node)\n return node, root_node, output_xpath\n\n @staticmethod\n def create_connectors(track, rule_name, num, element_ref=\"\"):\n while num > 0:\n globalds.TOTAL_CONNECTORS = globalds.TOTAL_CONNECTORS + 1\n if type(element_ref) is list:\n globalds.nodes.append(nc_crossing.create_connector_at_crossing_table18(track, element_ref[len(element_ref) - num]))\n if type(element_ref) is dict:\n if 'add_two_connectors' in element_ref:\n globalds.nodes.append(nc_crossing.create_connector_at_crossing_table18(track, element_ref['add_two_connectors'][\n len(element_ref['add_two_connectors']) - num]))\n if 'add_one_connector' in element_ref:\n globalds.nodes.append(nc_crossing.create_connector_at_crossing_table18(track, element_ref['add_one_connector'][\n len(element_ref['add_one_connector']) - num]))\n num = num - 1\n\n @staticmethod\n def create_connector_at_crossing_table18(track, postfix):\n output_element_nodes = track['connector'][0].split(\"|\")\n output_xpath = track['connector'][1]\n root_element = output_xpath.split(\"/\")[-1]\n connector_node = etree.Element(root_element)\n connector = etree.SubElement(connector_node, 'connector')\n connector_id = etree.SubElement(connector, output_element_nodes[0])\n if 'crossing' in track:\n connector_id.text = \"cnr%s_%s\" % (track['crossing']['name'], postfix)\n norm_dir_node_id = etree.SubElement(connector, output_element_nodes[1])\n if postfix == \"ab\" or postfix == \"cb\":\n norm_dir_node_id.text = \"nod%s_%s\" % (track['crossing']['name'], 'b')\n elif postfix == \"cd\" or postfix == \"ad\":\n norm_dir_node_id.text = \"nod%s_%s\" % (track['crossing']['name'], 'd')\n rev_dir_node_id = etree.SubElement(connector, output_element_nodes[2])\n if postfix == \"ab\" or postfix == \"ad\":\n rev_dir_node_id.text = \"nod%s_%s\" % (track['crossing']['name'], 'a')\n elif postfix == \"cd\" or postfix == \"cb\":\n rev_dir_node_id.text = \"nod%s_%s\" % (track['crossing']['name'], 'c')\n conn_object_ref = etree.SubElement(connector, output_element_nodes[3])\n conn_object_ref.text = track['crossing']['id']\n return connector, connector_node, output_xpath\n\n @staticmethod\n def get_crossing_noncrossing_nodes(tracks):\n for track_info in tracks:\n for each_track in track_info[1]:\n if 'connections' in each_track:\n for each_element in each_track['connections']['connection']:\n if 'crossing' in each_element:\n nc_crossing.crossing_nodes.append(each_track)\n break\n else:\n counter = 0\n for each_node in nc_crossing.crossing_nodes:\n if each_track['track']['name'] == each_node['track']['name']:\n counter = counter + 1\n break\n if counter == 0:\n nc_crossing.non_crossing_nodes.append(each_track)\n\n return nc_crossing.crossing_nodes, nc_crossing.non_crossing_nodes\n\n @staticmethod\n def check_element_position(track_begin_abs_position, track_end_abs_position, entry_boundary_abs_position,\n exit_boundary_abs_position, switch_abs_position):\n check_for_no_create_switch = False\n if track_begin_abs_position is not None:\n if entry_boundary_abs_position is not None:\n if (\n switch_abs_position >= track_begin_abs_position and switch_abs_position <= entry_boundary_abs_position) or \\\n (\n switch_abs_position >= entry_boundary_abs_position and switch_abs_position <= track_begin_abs_position):\n check_for_no_create_switch = True\n if exit_boundary_abs_position is not None:\n if (\n switch_abs_position >= track_begin_abs_position and switch_abs_position <= exit_boundary_abs_position) or \\\n (\n switch_abs_position >= exit_boundary_abs_position and switch_abs_position <= track_begin_abs_position):\n check_for_no_create_switch = True\n if track_end_abs_position is not None:\n if entry_boundary_abs_position is not None:\n if (\n switch_abs_position >= track_end_abs_position and switch_abs_position <= entry_boundary_abs_position) or \\\n (\n switch_abs_position >= entry_boundary_abs_position and switch_abs_position <= track_end_abs_position):\n check_for_no_create_switch = True\n if exit_boundary_abs_position is not None:\n if (\n switch_abs_position >= track_end_abs_position and switch_abs_position <= exit_boundary_abs_position) or \\\n (\n switch_abs_position >= exit_boundary_abs_position and switch_abs_position <= track_end_abs_position):\n check_for_no_create_switch = True\n return check_for_no_create_switch\n\n\n @staticmethod\n def calculate_crossing_km_point_at_a_b(node_name, crossing_details):\n km_point, ref_track = \"\", \"\"\n crossing_name = crossing_details[0]\n crossing_defined_at_track = crossing_details[1]\n match_crossing_name = False\n km_point, ref_track = \"\", \"\"\n for each_cross_node in nc_crossing.crossing_nodes:\n if 'connections' in each_cross_node and 'connection' in each_cross_node['connections'] and type(\n each_cross_node['connections']['connection']) is list:\n for each_element in each_cross_node['connections']['connection']:\n if 'crossing' in each_element and each_element['crossing']['name'] == crossing_name:\n match_crossing_name = True\n break\n # if match_crossing_name is False:\n # continue\n for each_noncross_node in nc_crossing.non_crossing_nodes:\n if match_crossing_name is True:\n if crossing_defined_at_track == \"trackBegin\":\n if 'connection' in each_cross_node['trackBegin']:\n if 'connection' in each_noncross_node['trackBegin']:\n if each_cross_node['trackBegin']['connection'][0]['connection']['id'] == \\\n each_noncross_node['trackBegin']['connection'][0]['connection']['ref']:\n if node_name == \"b\":\n km_point = each_noncross_node['trackBegin']['absPos']\n ref_track = each_noncross_node['track']['name']\n return km_point, ref_track\n if 'connection' in each_noncross_node['trackEnd']:\n if each_cross_node['trackBegin']['connection'][0]['connection']['id'] == \\\n each_noncross_node['trackEnd']['connection'][0]['connection']['ref']:\n if node_name == \"b\":\n km_point = each_noncross_node['trackEnd']['absPos']\n ref_track = each_noncross_node['track']['name']\n return km_point, ref_track\n if crossing_defined_at_track == \"trackEnd\":\n if 'connection' in each_cross_node['trackEnd']:\n if 'connection' in each_noncross_node['trackBegin']:\n if each_cross_node['trackEnd']['connection'][0]['connection']['id'] == \\\n each_noncross_node['trackBegin']['connection'][0]['connection']['ref']:\n if node_name == \"b\":\n km_point = each_noncross_node['trackBegin']['absPos']\n ref_track = each_noncross_node['track']['name']\n return km_point, ref_track\n if 'connection' in each_noncross_node['trackEnd']:\n if each_cross_node['trackEnd']['connection'][0]['connection']['id'] == \\\n each_noncross_node['trackEnd']['connection'][0]['connection']['ref']:\n if node_name == \"b\":\n km_point = each_noncross_node['trackEnd']['absPos']\n ref_track = each_noncross_node['track']['name']\n return km_point, ref_track\n # match_crossing_name = False\n return km_point, ref_track\n\n @staticmethod\n def calculate_crossing_km_point_at_c_d(crossing_name, node_name):\n km_point, ref_track = \"\", \"\"\n rt_angle_orientation_counter = 0\n found_crossing = False\n for each_cross_node in nc_crossing.crossing_nodes:\n for each_noncross_node in nc_crossing.non_crossing_nodes:\n if 'connections' in each_cross_node and 'connection' in each_cross_node['connections'] and type(\n each_cross_node['connections']['connection']) is list:\n for conn in each_cross_node['crossing']['connection']:\n if 'connection' in conn:\n if conn['connection']['orientation'] == \"rightAngled\":\n rt_angle_orientation_counter = rt_angle_orientation_counter + 1\n for each_element in each_cross_node['connections']['connection']:\n if 'crossing' in each_element and each_element['crossing']['name'] != crossing_name:\n continue\n elif 'crossing' in each_element and found_crossing is False and each_element['crossing'][\n 'name'] == crossing_name:\n found_crossing = True\n continue\n if found_crossing is True and 'connection' in each_element:\n if 'connection' in each_noncross_node['trackBegin'] and not (rt_angle_orientation_counter == 2):\n if str(each_element['connection']['id']) == str(\n each_noncross_node['trackBegin']['connection'][0]['connection']['ref']) and \\\n each_element['connection']['orientation'] == \"incoming\" and node_name == \"c\":\n km_point = each_noncross_node['trackBegin']['absPos']\n ref_track = each_noncross_node['track']['name']\n return km_point, ref_track\n if str(each_element['connection']['id']) == str(\n each_noncross_node['trackBegin']['connection'][0]['connection']['ref']) and \\\n each_element['connection']['orientation'] == \"outgoing\" and node_name == \"d\":\n km_point = each_noncross_node['trackBegin']['absPos']\n ref_track = each_noncross_node['track']['name']\n return km_point, ref_track\n if 'connection' in each_noncross_node['trackEnd'] and not (rt_angle_orientation_counter == 2):\n if str(each_element['connection']['id']) == str(\n each_noncross_node['trackEnd']['connection'][0]['connection']['ref']) and \\\n each_element['connection']['orientation'] == \"incoming\" and node_name == \"c\":\n km_point = each_noncross_node['trackEnd']['absPos']\n ref_track = each_noncross_node['track']['name']\n return km_point, ref_track\n if str(each_element['connection']['id']) == str(\n each_noncross_node['trackEnd']['connection'][0]['connection']['ref']) and \\\n each_element['connection']['orientation'] == \"outgoing\" and node_name == \"d\":\n km_point = each_noncross_node['trackEnd']['absPos']\n ref_track = each_noncross_node['track']['name']\n return km_point, ref_track\n if rt_angle_orientation_counter == 2: # TODO\n if 'connection' in each_noncross_node['trackBegin']:\n if str(each_element['connection']['id']) == str(\n each_noncross_node['trackBegin']['connection'][0]['connection']['ref']):\n km_point = each_noncross_node['trackEnd']['absPos']\n ref_track = each_noncross_node['track']['name']\n return km_point, ref_track\n if 'connection' in each_noncross_node['trackEnd']:\n if str(each_element['connection']['id']) == str(\n each_noncross_node['trackEnd']['connection'][0]['connection']['ref']):\n km_point = each_noncross_node['trackEnd']['absPos']\n ref_track = each_noncross_node['track']['name']\n return km_point, ref_track\n\n found_crossing = False\n return km_point, ref_track\n\nclass nc_signals_substoplocations_virtualsignals():\n \"\"\"\n This class to manage creation of nodes and connectors at signals, substop locations and\n virtual signals\n\n \"\"\"\n\n @staticmethod\n def execute(rule_data):\n # Rules 25 and 26\n for each_track in rule_data:\n for track in each_track[1]:\n signal_ref = []\n sub_stop_loc_ref = []\n virtual_signal_ref = []\n track_begin_abs_position = None\n track_end_abs_position = None\n entry_boundary_abs_position = None\n exit_boundary_abs_position = None\n if 'bufferStop' in track['trackBegin'] or 'openEnd' in track['trackBegin']:\n track_begin_abs_position = int(track['trackBegin']['absPos'])\n if 'bufferStop' in track['trackEnd'] or 'openEnd' in track['trackEnd']:\n track_end_abs_position = int(track['trackEnd']['absPos'])\n if 'entryBoundary' in track:\n entry_boundary_abs_position = int(track['entryBoundary']['absPos'])\n if 'exitBoundary' in track:\n exit_boundary_abs_position = int(track['exitBoundary']['absPos'])\n if 'separators' in track:\n for separator_value in track['separators']['separator']:\n if 'separator' in separator_value:\n separator_abs_position = int(separator_value['separator']['absPos'])\n check_for_no_create_separator = nc_signals_substoplocations_virtualsignals.check_element_position( track_begin_abs_position,track_end_abs_position,entry_boundary_abs_position, exit_boundary_abs_position,separator_abs_position)\n if not check_for_no_create_separator:\n if 'signalAdditionalInfos' in track:\n for signal_add_info_value in track['signalAdditionalInfos']['signalAdditionalInfo']:\n if signal_add_info_value['signalAdditionalInfo']['associatedSeparator'] == \\\n separator_value['separator']['id']:\n signal_ref.append(signal_add_info_value['signalAdditionalInfo']['ref'])\n continue\n for signal_value in track['signals']['signal']:\n if (signal_value['signal']['id'] in signal_ref) and (len(signal_ref) > 1) and (\n signal_value['signal']['dir'] == \"down\"):\n signal_ref.remove(signal_value['signal']['id'])\n for signal_add_info_value in track['signalAdditionalInfos']['signalAdditionalInfo']:\n if 'signals' in track:\n for signal_value in track['signals']['signal']:\n if 'signal' in signal_value:\n if signal_add_info_value['signalAdditionalInfo']['ref'] == \\\n signal_value['signal']['id'] and signal_value['signal'][\n 'id'] in signal_ref:\n if (signal_add_info_value['signalAdditionalInfo'][\n 'typeOfStoppingPoint'] in ['main', 'sub']\n and signal_add_info_value['signalAdditionalInfo'][\n 'associatedSeparator'] == separator_value['separator'][\n 'id']):\n nc_signals_substoplocations_virtualsignals.create_nodes(track, rule_data[0][0], 2, \\\n (signal_value['signal']['name'], separator_abs_position,rule_data))\n nc_signals_substoplocations_virtualsignals.create_connectors(track, 1, \\\n (signal_value['signal']['name'],separator_value['separator']['id']))\n if 'subStopLocations' in track:\n for sub_stop_loc_value in track['subStopLocations']['subStopLocation']:\n if sub_stop_loc_value['subStopLocation']['associatedObject'] == \\\n separator_value['separator']['id']:\n sub_stop_loc_ref.append(sub_stop_loc_value['subStopLocation']['name'])\n for sub_stop_loc_value in track['subStopLocations']['subStopLocation']:\n if (sub_stop_loc_value['subStopLocation']['name'] in sub_stop_loc_ref) and len(\n sub_stop_loc_ref) > 1 and sub_stop_loc_value['subStopLocation'][\n 'dir'] == \"down\":\n sub_stop_loc_ref.remove(sub_stop_loc_value['subStopLocation']['name'])\n for sub_stop_loc_value in track['subStopLocations']['subStopLocation']:\n if sub_stop_loc_value['subStopLocation']['associatedObject'] == \\\n separator_value['separator']['id'] and \\\n sub_stop_loc_value['subStopLocation'][\n 'name'] in sub_stop_loc_ref:\n nc_signals_substoplocations_virtualsignals.create_nodes(track, rule_data[0][0], 2, (\n sub_stop_loc_value['subStopLocation']['name'], separator_abs_position,\n rule_data))\n nc_signals_substoplocations_virtualsignals.create_connectors(track, 1, (\n sub_stop_loc_value['subStopLocation']['name'],\n separator_value['separator']['id']))\n if 'virtualSignals' in track:\n for virtual_signal_value in track['virtualSignals']['virtualSignal']:\n if virtual_signal_value['virtualSignal']['associatedObject'] == \\\n separator_value['separator']['id']:\n virtual_signal_ref.append(virtual_signal_value['virtualSignal']['name'])\n for virtual_signal_value in track['virtualSignals']['virtualSignal']:\n if (virtual_signal_value['virtualSignal'][\n 'name'] in virtual_signal_ref) and len(virtual_signal_ref) > 1 and \\\n virtual_signal_value['virtualSignal']['dir'] == \"down\":\n virtual_signal_ref.remove(virtual_signal_value['virtualSignal']['name'])\n for virtual_signal_value in track['virtualSignals']['virtualSignal']:\n if virtual_signal_value['virtualSignal']['associatedObject'] == \\\n separator_value['separator']['id'] and \\\n virtual_signal_value['virtualSignal'][\n 'name'] in virtual_signal_ref:\n nc_signals_substoplocations_virtualsignals.create_nodes(track, rule_data[0][0], 2, (\n virtual_signal_value['virtualSignal']['name'], separator_abs_position,\n rule_data))\n nc_signals_substoplocations_virtualsignals.create_connectors(track, 1, (\n virtual_signal_value['virtualSignal']['name'],\n separator_value['separator']['id']))\n\n\n @staticmethod\n def check_element_position(track_begin_abs_position, track_end_abs_position, entry_boundary_abs_position,\n exit_boundary_abs_position, separator_abs_position):\n check_for_no_create_separator = False\n if track_begin_abs_position is not None:\n if entry_boundary_abs_position is not None:\n if (separator_abs_position >= track_begin_abs_position and separator_abs_position <= entry_boundary_abs_position) or \\\n (separator_abs_position >= entry_boundary_abs_position and separator_abs_position <= track_begin_abs_position):\n check_for_no_create_separator = True\n if exit_boundary_abs_position is not None:\n if (separator_abs_position >= track_begin_abs_position and separator_abs_position <= exit_boundary_abs_position) or \\\n (separator_abs_position >= exit_boundary_abs_position and separator_abs_position <= track_begin_abs_position):\n check_for_no_create_separator = True\n if track_end_abs_position is not None:\n if entry_boundary_abs_position is not None:\n if (separator_abs_position >= track_end_abs_position and separator_abs_position <= entry_boundary_abs_position) or \\\n (separator_abs_position >= entry_boundary_abs_position and separator_abs_position <= track_end_abs_position):\n check_for_no_create_separator = True\n if exit_boundary_abs_position is not None:\n if (separator_abs_position >= track_end_abs_position and separator_abs_position <= exit_boundary_abs_position) or \\\n (separator_abs_position >= exit_boundary_abs_position and separator_abs_position <= track_end_abs_position):\n check_for_no_create_separator = True\n return check_for_no_create_separator\n\n\n @staticmethod\n def create_nodes(track, rule_name, num, element_ref=\"\"):\n letter_iter = globalds.LetterIter()\n while num > 0:\n globalds.TOTAL_NODES = globalds.TOTAL_NODES + 1\n globalds.nodes.append(\n nc_signals_substoplocations_virtualsignals.create_nodes_table14(track, letter_iter.__next__(), \\\n element_ref[0],element_ref[1], element_ref[2]))\n num = num - 1\n\n @staticmethod\n def create_nodes_table14(track, prefix, element_ref, separator_position, data_required):\n output_element_nodes = track['node'][0].split(\"|\")\n output_xpath = track['node'][1]\n root_element = output_xpath.split(\"/\")[-1]\n root_node = etree.Element(root_element)\n node = etree.SubElement(root_node, 'node')\n node_id = etree.SubElement(node, output_element_nodes[0])\n node_id.text = 'nod' + element_ref + '_' + prefix\n node_km_point = etree.SubElement(node, output_element_nodes[1])\n if separator_position == int(track['trackBegin']['absPos']) or separator_position == int(track['trackEnd']['absPos']):\n node_km_point.text = str(nc_signals_substoplocations_virtualsignals.calculate_km_point_for_separators(track, prefix, data_required))\n else:\n node_km_point.text = str(separator_position)\n node_line_id = etree.SubElement(node, output_element_nodes[2])\n node_line_id.text = '0'\n node_track_ref = etree.SubElement(node, output_element_nodes[3])\n node_track_ref.text = track['track']['id']\n # globals.NODES_INFO.append(node)\n return node, root_node, output_xpath\n\n @staticmethod\n def calculate_km_point_for_separators(track, prefix, data_required):\n connection_id1 = \"\"\n connection_id2 = \"\"\n if 'connection' in track['trackBegin']:\n connection_id1 = track['trackBegin']['connection'][0]['connection']['id']\n if 'connection' in track['trackEnd']:\n connection_id2 = track['trackEnd']['connection'][0]['connection']['id']\n for tracks in data_required:\n for each_track in tracks[1]:\n if track['track']['id'] != each_track['track']['id']:\n connection_ref1 = \"\"\n connection_ref2 = \"\"\n if 'connection' in each_track['trackBegin']:\n connection_ref1 = each_track['trackBegin']['connection'][0]['connection']['ref']\n if 'connection' in each_track['trackEnd']:\n connection_ref2 = each_track['trackEnd']['connection'][0]['connection']['ref']\n if connection_id2 == connection_ref1 and connection_id2 != \"\":\n if prefix == \"a\":\n km_point = track['trackEnd']['absPos']\n if prefix == \"b\":\n km_point = each_track['trackBegin']['absPos']\n if connection_id1 == connection_ref2 and connection_id1 != \"\":\n if prefix == \"a\":\n km_point = each_track['trackEnd']['absPos']\n if prefix == \"b\":\n km_point = track['trackBegin']['absPos']\n if connection_id2 == connection_ref2 and connection_id2 != \"\":\n if prefix == \"a\":\n km_point = track['trackEnd']['absPos']\n if prefix == \"b\":\n km_point = each_track['trackEnd']['absPos']\n if connection_id1 == connection_ref1 and connection_id1 != \"\":\n if prefix == \"a\":\n km_point = track['trackBegin']['absPos']\n if prefix == \"b\":\n km_point = each_track['trackBegin']['absPos']\n return km_point\n\n @staticmethod\n def create_connectors(track, num, element_ref=\"\"):\n globalds.TOTAL_CONNECTORS = globalds.TOTAL_CONNECTORS + 1\n globalds.nodes.append(nc_signals_substoplocations_virtualsignals.create_connector_at_separator_table16(track, element_ref[0], element_ref[1]))\n\n @staticmethod\n def create_connector_at_separator_table16(track, element_ref, separator_id):\n output_element_nodes = track['connector'][0].split(\"|\")\n output_xpath = track['connector'][1]\n root_element = output_xpath.split(\"/\")[-1]\n connector_node = etree.Element(root_element)\n connector = etree.SubElement(connector_node, 'connector')\n connector_id = etree.SubElement(connector, output_element_nodes[0])\n connector_id.text = \"cnr%s\" % element_ref\n norm_dir_node_id = etree.SubElement(connector, output_element_nodes[1])\n norm_dir_node_id.text = \"nod%s_b\" % element_ref\n rev_dir_node_id = etree.SubElement(connector, output_element_nodes[2])\n rev_dir_node_id.text = \"nod%s_a\" % element_ref\n conn_object_ref = etree.SubElement(connector, output_element_nodes[3])\n conn_object_ref.text = separator_id\n return connector, connector_node, output_xpath" }, { "alpha_fraction": 0.45941469073295593, "alphanum_fraction": 0.46291184425354004, "avg_line_length": 55.99300765991211, "blob_id": "5741f3e80b1632496a75212599baec54ef62838b", "content_id": "af184f7b4adbb6afcba4f9f995d6b9be576b93a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16300, "license_type": "no_license", "max_line_length": 170, "num_lines": 286, "path": "/src/constraint_manager/constraint_processor.py", "repo_name": "srikanthreddybms/railml_to_rbc", "src_encoding": "UTF-8", "text": "\"\"\"\nContraints processor\nThis module is used to initiate the constraints check on input railMl\nunder constraint manager component of RailMl to RBC route map conversion tool\n\n@copyright:\nAll rights reserved. ©2016. ALSTOM (Bangalore, India).\nThis computer program may not be used, copied, distributed, corrected,\nmodified, translated, transmitted or assigned without ALSTOM's prior\nwritten authorization.\n\n@date : 18th July 2016\n@author: Sanjay Kalshetty, Srikanth Reddy\n\"\"\"\n\nfrom collections import OrderedDict\nfrom configparser import ConfigParser\n\n\nclass constraint_proc:\n\n def __init__(self, tracks_info_for_rules, logger):\n self.logger = logger\n self.cstr_info = tracks_info_for_rules\n\n def cstr_scheduler(self):\n\n for cstr_data in self.cstr_info:\n\n if cstr_data[0][0] == \"InputRailMlCstr\":\n params = list()\n params.append(\"\")\n self.logger.log_progress(\"CONSTRAINT_EXECUTION_STARTED\", params)\n constraint_proc.constraints_on_input_railml(self, cstr_data)\n self.logger.log_progress(\"CONSTRAINT_EXECUTION_FINISHED\", params)\n\n @staticmethod\n def constraints_on_input_railml(self, cstr_data):\n is_cstr_fail = False\n max_lenth_10 = 10\n max_lenth_9 = 9\n\n for each_track in cstr_data:\n for track in each_track[1]:\n #Constraint to check if no boundaries exist without openEnd and bufferStop\n if 'entryBoundary' in track or 'exitBoundary' in track:\n if not any(name in track for name in ['openEnd', 'bufferStop']):\n is_cstr_fail = True\n param = list()\n param.append(\"Boundary defined on track with NO 'bufferStop' or 'openEnd', Track = %s\" %track['track']['id'])\n self.logger.log_error_no_stop(\"ERR_CONSTRAINT_FAIL\", param)\n\n # Constraint to check if Boundary defined at the location of a track cut\n if ('entryBoundary' in track or 'exitBoundary') in track:\n list_attr = list()\n list_boundary = ['entryBoundary', 'exitBoundary']\n list_tb_te = list()\n list_tb_te = ['trackBegin', 'trackEnd']\n\n for attr in list_attr:\n for tb_te in list_tb_te:\n if track[attr].get('absPos', None)== None or track[tb_te].get('absPos', None)== None:\n param = list()\n param.append(\n \"'absPos' for trackBegin/End or entry/exit Boundary missing, Track = %s\" % track['track'][\n 'id'])\n self.logger.log_warning(\"WARN_MISIING_ATTR\", param)\n\n\n\n elif (track[attr].get('absPos', None) == track[tb_te]['absPos'] or\\\n track[attr].get('absPos', None) == track[tb_te]['absPos']):\n is_cstr_fail = True\n param = list()\n param.append(\n \"Boundary defined on trackcut, Track = %s\" % track['track']['id'])\n self.logger.log_error_no_stop(\"ERR_CONSTRAINT_FAIL\", param)\n\n\n #Constraint to check if No OpenEnd shall exist in the file except Boundaries case\n if 'openEnd' in track:\n if not any(name in track for name in ['entryBoundary', 'exitBoundary']):\n param = list()\n param.append(\"'openEnd' exist for track with NO boundaries defined, Track = %s\" % track['track']['id'])\n # self.logger.log_warning(\"WARN_CONSTRAINT_FAIL\", param)\n self.logger.log_error_no_stop(\"ERR_CONSTRAINT_FAIL\", param)\n is_cstr_fail = True\n\n # Constraint to check of lenth of 'name' attributes within permissible limit\n if ('bufferStop' in track['trackBegin'] and (len(track['trackBegin']['bufferStop'][0]['bufferStop']['name'])> max_lenth_10)) or\\\n ('bufferStop' in track['trackEnd'] and (len(track['trackEnd']['bufferStop'][0]['bufferStop']['name']) > max_lenth_10)):\n param = list()\n param.append(\n \"bufferStop.name length exceeded maximum character limit(max char = %s), Track = %s\" % (\n max_lenth_10, track['track']['id']))\n self.logger.log_error_no_stop(\"ERR_CONSTRAINT_FAIL\", param)\n is_cstr_fail = True\n\n\n if any(name in track for name in ['signals','subStopLocations','virtualSignals', 'entryBoundary','exitBoundary',\\\n 'connections']):\n\n if 'signals' in track:\n for signal_value in track['signals']['signal']:\n if len(signal_value['signal'].get('name', None))> max_lenth_10:\n param = list()\n param.append(\n \"Signal.name length exceeded maximum character limit(max char = %s), Signal id = %s, Track = %s\" % (\n max_lenth_10,signal_value['signal']['id'], track['track']['id']))\n self.logger.log_error_no_stop(\"ERR_CONSTRAINT_FAIL\", param)\n is_cstr_fail = True\n\n if 'connections' in track:\n for connection in track['connections']['connection']:\n param = list()\n if 'switch' in connection and (len(connection['switch'].get('name', None)) > max_lenth_9):\n\n param.append(\n \"switch.name length exceeded maximum character limit(max char = %s), switch id = %s, Track = %s\" % (\n max_lenth_9, connection['switch']['id'], track['track']['id']))\n self.logger.log_error_no_stop(\"ERR_CONSTRAINT_FAIL\", param)\n is_cstr_fail = True\n\n elif 'crossing' in connection and (len(connection['crossing'].get('name', None)) > max_lenth_9):\n\n param.append(\n \"crossing.name length exceeded maximum character limit(max char = %s), crossing id = %s, Track = %s\" % (\n max_lenth_9, connection['crossing']['id'], track['track']['id']))\n self.logger.log_error_no_stop(\"ERR_CONSTRAINT_FAIL\", param)\n is_cstr_fail = True\n\n if 'subStopLocations' in track:\n for sub_stop_loc_value in track['subStopLocations']['subStopLocation']:\n if len(sub_stop_loc_value['subStopLocation']['name'])> max_lenth_10:\n param = list()\n param.append(\n \"subStopLocations.name length exceeded maximum character limit(max char = %s), Track = %s\" % (\n max_lenth_10, track['track']['id']))\n self.logger.log_error_no_stop(\"ERR_CONSTRAINT_FAIL\", param)\n is_cstr_fail = True\n\n if 'virtualSignals' in track:\n for virtual_signal in track['virtualSignals']['virtualSignal']:\n if len(virtual_signal['virtualSignal']['name']) > max_lenth_10:\n param = list()\n param.append(\n \"virtualSignal.name length exceeded maximum character limit(max char = %s), Track = %s\" % (\n max_lenth_10, track['track']['id']))\n self.logger.log_error_no_stop(\"ERR_CONSTRAINT_FAIL\", param)\n is_cstr_fail = True\n\n\n if any(name in track for name in ['entryBoundary','exitBoundary']):\n boundary_list = ['entryBoundary', 'exitBoundary']\n for boundary in boundary_list:\n if boundary in track and len(track[boundary].get('name', None)) > max_lenth_9:\n param = list()\n param.append(\n \"%s.name length exceeded maximum character limit(max char = %s), Track = %s\" %(boundary,max_lenth_9,track['track']['id']))\n self.logger.log_error_no_stop(\"ERR_CONSTRAINT_FAIL\", param)\n is_cstr_fail = True\n\n\n # Constraint to check if AssociatedSeparator and AssociatedObject defined\n if any(name in track for name in ['signalAdditionalInfos', 'subStopLocations', 'virtualSignals']):\n\n if 'signalAdditionalInfos' in track:\n\n for signal_info in track['signalAdditionalInfos']['signalAdditionalInfo']:\n\n if signal_info['signalAdditionalInfo'].get('typeOfStoppingPoint', None) is None :\n param = list()\n param.append(\n \"'typeOfStoppingPoint' for 'signalAdditionalInfo' signal ref =%s missing, Track = %s\" %(signal_info['signalAdditionalInfo']['ref'],\n track['track']['id']))\n self.logger.log_warning(\"WARN_MISIING_ATTR\", param)\n else:\n\n if signal_info['signalAdditionalInfo']['typeOfStoppingPoint'] == 'main' or \\\n signal_info['signalAdditionalInfo']['typeOfStoppingPoint'] == 'sub':\n\n if not 'associatedSeparator' in signal_info['signalAdditionalInfo']:\n param = list()\n param.append(\n \"'associatedSeparator' not defined for 'signalAdditionalInfo' = %s, Track = %s\" %(signal_info['signalAdditionalInfo']['ref'],\\\n track['track']['id']))\n self.logger.log_error_no_stop(\"ERR_CONSTRAINT_FAIL\", param)\n is_cstr_fail = True\n\n if 'subStopLocations' in track:\n for substop in track['subStopLocations']['subStopLocation']:\n if substop['subStopLocation'].get('associatedObject', None) is None:\n param = list()\n param.append(\n \"'AssociatedObject' for 'subStopLocation' with id= %s is not defined, Track = %s\" % (\n substop['subStopLocation']['id'], track['track']['id']))\n self.logger.log_error_no_stop(\"ERR_CONSTRAINT_FAIL\", param)\n is_cstr_fail = True\n\n if 'virtualSignals' in track:\n for virtsignal in track['virtualSignals']['virtualSignal']:\n if virtsignal['virtualSignal'].get('associatedObject', None) is None:\n param = list()\n param.append(\n \"'AssociatedObject' for 'virtualSignal' with id= %s is not defined, Track = %s\" % (\n virtsignal['virtualSignal']['id'], track['track']['id']))\n self.logger.log_error_no_stop(\"ERR_CONSTRAINT_FAIL\", param)\n is_cstr_fail = True\n\n #Constraint to check if No switch defined at location of separators\n if all(name in track for name in ['separators', 'connections']):\n\n for connection in track['connections']['connection']:\n if 'switch' in connection:\n for seperator in track['separators']['separator']:\n\n if connection['switch'].get('absPos', None) is None or \\\n seperator['separator'].get('absPos', None) is None:\n param = list()\n param.append(\n \"'absPos' for 'switch' or 'separator' missing, Track = %s\" % track['track']['id'])\n self.logger.log_warning(\"WARN_MISIING_ATTR\", param)\n\n else:\n\n if connection['switch']['absPos'] == seperator['separator']['absPos']:\n param = list()\n param.append(\n \"'separator' with id= %s defined at location of switch, Track = %s\" % (\n seperator['separator']['id'], track['track']['id']))\n self.logger.log_error_no_stop(\"ERR_CONSTRAINT_FAIL\", param)\n is_cstr_fail = True\n\n\n #Constraint to check if any crossings have incorrect orientations\n if 'connections' in track:\n cross_found = False\n oriantation_list = list()\n counter = 0\n for connect in track['connections']['connection']:\n\n if 'crossing' not in connect and (cross_found is False):\n continue\n elif 'crossing' in connect:\n cross_found = True\n\n if 'connection' in connect and cross_found is True:\n oriantation_list.append(connect['connection']['orientation'])\n conn_id = connect['connection']['id']\n counter = counter + 1\n\n if counter == 2:\n\n if not (((oriantation_list[0] == 'incoming' and oriantation_list[1] == 'outgoing') or \\\n (oriantation_list[1] == 'incoming' and oriantation_list[0] == 'outgoing')) or\n oriantation_list[0] == 'rightAngled' and oriantation_list[1] == 'rightAngled'):\n\n param = list()\n param.append(\"'connection' of 'crossing' with id= %s are not oriented, Track = %s\" % ( \\\n conn_id, track['track']['id']))\n self.logger.log_error_no_stop(\"ERR_CONSTRAINT_FAIL\", param)\n is_cstr_fail = True\n cross_found = False\n counter = 0\n oriantation_list = list()\n\n\n # Constraint to check if No track name starts with \"xxx\"\n if track['track'].get('name',None)is None:\n param = list()\n param.append(\n \"'name' attribute for 'Track' missing, Track = %s\" % track['track']['id'])\n self.logger.log_warning(\"WARN_MISIING_ATTR\", param)\n\n else:\n if track['track'].get('name', None)[0:3] == \"xxx\":\n param = list()\n param.append(\"'Track.name' starting with xxx, Track = %s\" % track['track']['id'])\n self.logger.log_error_no_stop(\"ERR_CONSTRAINT_FAIL\", param)\n is_cstr_fail = True\n\n\n if is_cstr_fail == True:\n param = list()\n param.append(\"\")\n self.logger.log_error(\"ERR_CONSTRAINT_FAIL_ABORT\", param)" }, { "alpha_fraction": 0.5830084085464478, "alphanum_fraction": 0.5887543559074402, "avg_line_length": 40.305084228515625, "blob_id": "7bdfb154fffaaec5e1cd28dba9067c7f1fa006db", "content_id": "faf9c898c546a7313feb42c1d62c6b7ee0ba1129", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4874, "license_type": "no_license", "max_line_length": 133, "num_lines": 118, "path": "/src/parser_engine/write_output.py", "repo_name": "srikanthreddybms/railml_to_rbc", "src_encoding": "UTF-8", "text": "\"\"\"\nThis module is used to write the computed data from rules processing to output RBC route map data file.\nProcess the output RBC the options/values in each section\n\n@copyright:\nAll rights reserved. ©2016. ALSTOM (Bangalore, India).\nThis computer program may not be used, copied, distributed, corrected,\nmodified, translated, transmitted or assigned without ALSTOM's prior\nwritten authorization.\n\n@Date: 18th July 2016\n@authors: Srikanth Reddy, Sanjay Kalshetty\n\"\"\"\n\n\nimport os\nimport sys\nimport shutil\n\nfrom lxml import etree\nimport src.globals.globalds as globalds\n\nclass write_output():\n\n def __init__(self, files_int_inp,genparams, logger):\n\n self.logger = logger\n self.rbc_default = files_int_inp['rbcdefault']\n self.rbc_output_path = files_int_inp['rbcoutput']\n self.genparams = genparams\n\n self.rbc_outfile = os.path.join(self.rbc_output_path,\"RBC_DATA_OUTPUT.xml\")\n\n if os.path.exists(self.rbc_outfile):\n os.remove(self.rbc_outfile)\n\n shutil.copy(self.rbc_default, self.rbc_outfile)\n\n parser = etree.XMLParser(remove_blank_text=True)\n self.outFile = etree.parse(self.rbc_outfile, parser)\n\n #self.outFile = etree.parse(self.rbc_outfile)\n self.rbc_file = open(self.rbc_outfile,'wb')\n\n def write_nodes_to_output_rbc(self, nodes):\n \"\"\"\n This service to manage creation of output RBC xml and write the nodes/connectors/segaments to same\n \"\"\"\n\n global count_nodes\n global count_connectors\n global count_segments\n tree = self.outFile\n\n params = list()\n params.append(self.rbc_outfile)\n self.logger.log_progress(\"WRITTING_OUTPUT_STARTED\", params)\n\n for node in nodes:\n c_node = node[0]\n root_node = node[1]\n output_xpath = node[2]\n element_found = tree.xpath(output_xpath) # \".//\" + rootNode + \"/\" + cNode)\n\n if c_node.tag == \"node\":\n if globalds.count_nodes <= int(self.genparams['nMaxNodes']) - 1:\n globalds.count_nodes = globalds.count_nodes + 1\n if self.genparams['roundTo10cm'] == \"true\": # TO DO\n temp = c_node.find(\"./kilometric_point\").text\n track_ref_element = c_node.find(\"./trackRef\")\n #c_node.remove(track_ref_element)\n element_found[0].append(c_node)\n max_nodes = element_found[0].find(\"./Nmax_node\")\n max_nodes.text = \"%s\" % globalds.count_nodes\n else:\n\n params = list()\n params.append(\"Number of nodes created exceeds Maximum number of nodes limit %s\" % (self.genparams['nMaxNodes']))\n self.logger.log_error(\"ERR_COMPLEMENTRY_RULE_FAIL\", params)\n\n if c_node.tag == \"connector\":\n if globalds.count_connectors <= int(self.genparams['nMaxConnectors']) - 1:\n globalds.count_connectors = globalds.count_connectors + 1\n object_ref_element = c_node.find(\"./objectRef\")\n c_node.remove(object_ref_element)\n element_found[0].append(c_node)\n max_connectors = element_found[0].find(\"./Nmax_connector\")\n max_connectors.text = \"%s\" % globalds.count_connectors\n else:\n params = list()\n params.append(\"Number of connectors created exceeds Maximum number of connectors limit %s\" % (\n self.genparams['nMaxConnectors']))\n self.logger.log_error(\"ERR_COMPLEMENTRY_RULE_FAIL\", params)\n\n if c_node.tag == \"segment\":\n if globalds.count_segments <= int(self.genparams['nMaxSegments']) - 1:\n globalds.count_segments = globalds.count_segments + 1\n element_found[0].append(c_node)\n max_segments = element_found[0].find(\"./Nmax_segment\")\n max_segments.text = \"%s\" % globalds.count_segments\n else:\n\n params = list()\n params.append(\"Number of segments created exceeds Maximum number of sgements limit %s\" % (\n self.genparams['nMaxSegments']))\n self.logger.log_error(\"ERR_COMPLEMENTRY_RULE_FAIL\", params)\n\n\n print(\"Total number of nodes are %d\" % globalds.count_nodes)\n print(\"Total number of connectors are %d\" % globalds.count_connectors)\n print(\"Total number of segments are %d\" % globalds.count_segments)\n\n self.rbc_file.write(etree.tostring(self.outFile, pretty_print=True,encoding='utf-8',xml_declaration=True))\n\n self.rbc_file.close()\n params =list()\n params.append(self.rbc_outfile)\n self.logger.log_progress(\"WRITTING_OUTPUT_FINISHED\", params)" }, { "alpha_fraction": 0.5754197239875793, "alphanum_fraction": 0.5850906372070312, "avg_line_length": 48.63999938964844, "blob_id": "0a2481acdf74f0619e7f921d4b61cdb87c38fba8", "content_id": "f6964ebf9d5a7e54be24e0cf117e134ecdbf7f83", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7446, "license_type": "no_license", "max_line_length": 186, "num_lines": 150, "path": "/src/rules_manager/rules_to_define_segments.py", "repo_name": "srikanthreddybms/railml_to_rbc", "src_encoding": "UTF-8", "text": "\"\"\"\nRules for Define segments\nThis module is used to initiate the rules manipulations of rules related to segments\ncreation under rules manager component of RailMl to RBC route map conversion tool\n\n@copyright:\nAll rights reserved. ©2016. ALSTOM (Bangalore, India).\nThis computer program may not be used, copied, distributed, corrected,\nmodified, translated, transmitted or assigned without ALSTOM's prior\nwritten authorization.\n\n@date : 18th July 2016\n@author: Sanjay Kalshetty, Srikanth Reddy\n\"\"\"\n\nimport re\nfrom collections import OrderedDict\nimport collections\nfrom lxml import etree\nfrom itertools import groupby\nimport src.globals.globalds as globalds\n\n\nclass segments():\n \"\"\"\n This class to manage creation of segments using nodes and connector data generated in previous process\n \"\"\"\n\n @staticmethod\n def execute(rule_data, genparams, logger):\n nodes = globalds.nodes[:]\n nodes_sorted_by_track = segments.sort_by_track(nodes[:])\n group_sorted_nodes = segments.group_by_sorted_nodes(nodes_sorted_by_track)\n segments.create_segments(rule_data, genparams, group_sorted_nodes, logger)\n\n @staticmethod\n def sort_by_track(nodes):\n nodes_sorted_by_track = []\n temp_nodes = []\n sort_nodes = sorted([node[0].find(\"./trackRef\").text for node in nodes \\\n if node[0].find(\"./trackRef\") is not None])\n for node in sort_nodes:\n if node not in temp_nodes:\n temp_nodes.append(node)\n for item in temp_nodes:\n for node in nodes:\n if node[0].find(\"./trackRef\") is not None:\n if node[0].find(\"./trackRef\").text == item:\n nodes_sorted_by_track.append(node)\n return nodes_sorted_by_track\n\n @staticmethod\n def group_by_sorted_nodes(nodes):\n track_by_group = []\n total_track_groups = []\n track_by_group_2 = [list(j) for i, j in groupby(sorted([str(node[0].find(\"./trackRef\").text) for node in nodes \\\n if node[0].find(\"./trackRef\") is not None]))]\n\n print(track_by_group_2)\n\n for each_track_group in track_by_group_2:\n for each_node in nodes:\n if str(each_track_group[0]) == str(each_node[0].find(\"./trackRef\").text):\n track_by_group.append(each_node)\n continue\n else:\n if len(track_by_group) != 0:\n total_track_groups.append(track_by_group)\n track_by_group = []\n continue\n total_track_groups.append(track_by_group)\n return total_track_groups\n\n\n @staticmethod\n def sort_by_kilometric_point(nodes):\n nodes_sorted_by_kp = []\n temp_nodes = []\n sort_by_kp = sorted([node[0].find(\"./kilometric_point\").text for node in nodes \\\n if node[0].find(\"./kilometric_point\") is not None])\n for node in sort_by_kp:\n if node not in temp_nodes:\n temp_nodes.append(node)\n\n for item in temp_nodes:\n for node in nodes:\n if node[0].find(\"./kilometric_point\") is not None:\n if node[0].find(\"./kilometric_point\").text == item:\n nodes_sorted_by_kp.append(node)\n return sort_by_kp, nodes_sorted_by_kp\n\n\n @staticmethod\n def create_segments(rule_data, genparams, nodes, logger):\n for each_track in nodes:\n used_nodes_list = []\n kp_values, nodes_sorted_by_kp = segments.sort_by_kilometric_point(each_track)\n same_kp_more_than_two_nodes = [item for item, count in collections.Counter(kp_values).items() if count > 2]\n if len(same_kp_more_than_two_nodes) > 0: # Not more than two nodes should have same kilometric point\n params = list()\n params.append(\",due to same kilometric point for more than two nodes, Track = %s\" %nodes_sorted_by_kp[0][0].find(\"./trackRef\").text)\n logger.log_warning(\"WARN_SEGMENT_CREATION_ABORT\", params)\n\n for i in range(0, len(nodes_sorted_by_kp), 2):\n if len(nodes_sorted_by_kp[i:]) % 2 == 0:\n for used_node in used_nodes_list:\n if id(nodes_sorted_by_kp[i]) == id(used_node) or id(nodes_sorted_by_kp[i+1]) == id(used_node):\n # print(\"Error: node is used more than once as normal node or reverse node of a segment in track %s\" %str(nodes_sorted_by_kp[i][0].find(\"./trackRef\").text))\n params = list()\n params.append(\",a node is used more than once as normal node or reverse node of a segment in track %s\" %str(nodes_sorted_by_kp[i][0].find(\"./trackRef\").text))\n logger.log_warning(\"WARN_SEGMENT_CREATION\", params)\n\n break\n globalds.nodes.append(segments.create_segment(rule_data, genparams, (nodes_sorted_by_kp[i],nodes_sorted_by_kp[i+1])))\n used_nodes_list.extend([nodes_sorted_by_kp[i], nodes_sorted_by_kp[i + 1]])\n if nodes_sorted_by_kp != used_nodes_list:\n # print(\"Error: Few nodes are never used as normal node or reverse node in a segment in track %s\" %str(\n # nodes_sorted_by_kp[i][0].find(\"./trackRef\").text))\n params = list()\n params.append(\n \",a node at track = %s never used as normal node or reverse node in a segment creation\" %str(\n nodes_sorted_by_kp[i][0].find(\"./trackRef\").text))\n logger.log_warning(\"WARN_SEGMENT_CREATION\", params)\n\n @staticmethod\n def create_segment(rule_data, genparams, nodes):\n output_element_nodes = rule_data[0][1][0]['segment'][0].split(\"|\")\n output_xpath = rule_data[0][1][0]['segment'][1]\n root_element = output_xpath.split(\"/\")[-1]\n root_node = etree.Element(root_element)\n segment = etree.SubElement(root_node, 'segment')\n segment_id = etree.SubElement(segment, output_element_nodes[0])\n rev_dir_nod_id = str(nodes[0][0].find(\"./id\").text).replace(\"nod\",\"\")\n last_underscore = rev_dir_nod_id.rfind(\"_\")\n if last_underscore != -1:\n rev_dir_nod_id = rev_dir_nod_id[:last_underscore]\n norm_dir_nod_id = str(nodes[1][0].find(\"./id\").text).replace(\"nod\",\"\")\n last_underscore1 = norm_dir_nod_id.rfind(\"_\")\n if last_underscore1 != -1:\n norm_dir_nod_id = norm_dir_nod_id[:last_underscore1]\n segment_id.text = 'seg' + rev_dir_nod_id + \"_\" + norm_dir_nod_id\n segment_length = etree.SubElement(segment, output_element_nodes[1])\n segment_length.text = str(int(nodes[1][0].find(\"./kilometric_point\").text) - int(nodes[0][0].find(\"./kilometric_point\").text))\n segment_norm_dir_nod_id = etree.SubElement(segment, output_element_nodes[2])\n segment_norm_dir_nod_id.text = nodes[1][0].find(\"./id\").text\n segment_rev_dir_node_id = etree.SubElement(segment, output_element_nodes[3])\n segment_rev_dir_node_id.text = nodes[0][0].find(\"./id\").text\n segment_validity_status = etree.SubElement(segment, output_element_nodes[4])\n segment_validity_status.text = genparams['validityStatus']\n return segment, root_node, output_xpath" }, { "alpha_fraction": 0.5925925970077515, "alphanum_fraction": 0.6044129133224487, "avg_line_length": 23.423076629638672, "blob_id": "a64b0a953bd295021cfd1274f30fa56f21fcd4d6", "content_id": "07174df73addb9e22dc8f4f13f664855ee145e8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1270, "license_type": "no_license", "max_line_length": 79, "num_lines": 52, "path": "/src/globals/globalconstants.py", "repo_name": "srikanthreddybms/railml_to_rbc", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\n\"\"\"\nGlobal constants of RailMl to RBC route map conversion tool\n\n@copyright:\nAll rights reserved. ©2016. ALSTOM (Bangalore, India).\nThis computer program may not be used, copied, distributed, corrected,\nmodified, translated, transmitted or assigned without ALSTOM's prior\nwritten authorization.\n\n@date : 18th July 2016\n@author: Sanjay Kalshetty, Srikanth Reddy\n\"\"\"\n\n\nclass GlobalConstants:\n \"\"\"\n This class contains all the constants that should be globaly shared between\n modules. Individual constants that are not shared between modules are kept\n in individual classes\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialization method\n \"\"\"\n self.__default_language = \"eng\"\n \"\"\"Default language to be used in log file\"\"\"\n\n self.__tool_version = \"8.1.0\"\n \"\"\"Tool version number\"\"\"\n\n self.__tool_name = \"RailML2RBC-branchB\"\n \"\"\"Tool name\"\"\"\n\n def get_lang(self):\n \"\"\"\n Get the default language\n \"\"\"\n return self.__default_language\n\n def get_tool_version(self):\n \"\"\"\n get the tool version\n \"\"\"\n return self.__tool_version\n\n def get_tool_name(self):\n \"\"\"\n get the tool name\n \"\"\"\n return self.__tool_name" } ]
20
thaiduongx26/Kepco-Bidaf
https://github.com/thaiduongx26/Kepco-Bidaf
a244fd1e90ee28006ba17d4d983a64c166a77276
36c510de364b74e83d4cf85d06929f9588ba955a
0fec1c309dc25519deca9c620ed656f7d82ce1d4
refs/heads/master
2020-06-11T02:52:46.919462
2019-07-01T06:57:04
2019-07-01T06:57:04
193,830,915
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 24, "blob_id": "ed16cf36e9d4f1861892608396fcf98dcb294ce0", "content_id": "85c38c85b5295eca44c7077f9c2f7ee6ef2310fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 52, "license_type": "no_license", "max_line_length": 31, "num_lines": 2, "path": "/data/test_data_ner/九州0347/desktop.ini", "repo_name": "thaiduongx26/Kepco-Bidaf", "src_encoding": "UTF-8", "text": "[.ShellClassInfo]\r\nLocalizedResourceName=@??0347,0\r\n" }, { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 24, "blob_id": "f7811d3b4444daf909055259dd3d0370d2caf9f4", "content_id": "0644e26e72e27215dbb732230517833323c7daab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 52, "license_type": "no_license", "max_line_length": 31, "num_lines": 2, "path": "/data/test_data_ner/中部0033/desktop.ini", "repo_name": "thaiduongx26/Kepco-Bidaf", "src_encoding": "UTF-8", "text": "[.ShellClassInfo]\r\nLocalizedResourceName=@??0033,0\r\n" }, { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 24, "blob_id": "280088d3d10de138527cb5df83c58adee5c9ae66", "content_id": "6dda054420db46a73643e8ca0c8e8b12f6b23431", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 52, "license_type": "no_license", "max_line_length": 31, "num_lines": 2, "path": "/data/test_data_ner/中部0093/desktop.ini", "repo_name": "thaiduongx26/Kepco-Bidaf", "src_encoding": "UTF-8", "text": "[.ShellClassInfo]\r\nLocalizedResourceName=@??0093,0\r\n" }, { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 24, "blob_id": "49ca42892332fdd99060ad248e313492d2769603", "content_id": "4ec47463d457020e707381ecd5a3294603bacf70", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 52, "license_type": "no_license", "max_line_length": 31, "num_lines": 2, "path": "/data/test_data_ner/中部0124/desktop.ini", "repo_name": "thaiduongx26/Kepco-Bidaf", "src_encoding": "UTF-8", "text": "[.ShellClassInfo]\r\nLocalizedResourceName=@??0124,0\r\n" }, { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 24, "blob_id": "9dafeb8d4d05632ec68dd50ec97b1a30968651d9", "content_id": "676f2ab3ecb342ddd0cf779de6444e2a1b73ccb1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 52, "license_type": "no_license", "max_line_length": 31, "num_lines": 2, "path": "/data/test_data_ner/中国0051/desktop.ini", "repo_name": "thaiduongx26/Kepco-Bidaf", "src_encoding": "UTF-8", "text": "[.ShellClassInfo]\r\nLocalizedResourceName=@??0051,0\r\n" }, { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 24, "blob_id": "d5877b842765141dc4cd240789b5be773a2521f2", "content_id": "92028002946a1aeda5c6be97f810da2d5d68acf1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 52, "license_type": "no_license", "max_line_length": 31, "num_lines": 2, "path": "/data/test_data_ner/中部0465/desktop.ini", "repo_name": "thaiduongx26/Kepco-Bidaf", "src_encoding": "UTF-8", "text": "[.ShellClassInfo]\r\nLocalizedResourceName=@??0465,0\r\n" }, { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 24, "blob_id": "e0e22a2496e592ecef0b9f35841195e15ef90a6f", "content_id": "fc29385475381c6ad6c074be58fc23516beedbbe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 52, "license_type": "no_license", "max_line_length": 31, "num_lines": 2, "path": "/data/test_data_ner/九州0041/desktop.ini", "repo_name": "thaiduongx26/Kepco-Bidaf", "src_encoding": "UTF-8", "text": "[.ShellClassInfo]\r\nLocalizedResourceName=@??0041,0\r\n" }, { "alpha_fraction": 0.6698629856109619, "alphanum_fraction": 0.6949771642684937, "avg_line_length": 39.574073791503906, "blob_id": "37105713d3111b1a7678b9938f3d76bb621a693c", "content_id": "352169d46f6890994251e9503b359ac5ebd5c092", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2190, "license_type": "no_license", "max_line_length": 204, "num_lines": 54, "path": "/train.py", "repo_name": "thaiduongx26/Kepco-Bidaf", "src_encoding": "UTF-8", "text": "from tqdm import tqdm\nimport numpy as np\nimport os\nimport io\nimport json\nimport sys\nimport logging\nfrom bidaf.scripts import batch_generator\nimport tensorflow as tf\n\nvocab_size = 1874\nembedding_path = \"data/vocal_vec.txt\"\nembedding_dim = 300\ndata_dir = \"data\"\ntrain_dir = \"model\"\n\ndef get_vec(embedding_path, embedding_dim):\n print(\"Loading embedding vectors from file: %s\" % embedding_path)\n\n emb_matrix = np.zeros((vocab_size, embedding_dim))\n word2id = {}\n id2word = {}\n idx = 0\n\n with open(embedding_path, 'r') as fh:\n for line in tqdm(fh, total=vocab_size):\n line = line.lstrip().rstrip().split(\" \")\n word = line[0]\n# print(word)\n vector = list(map(float, line[1:]))\n if embedding_dim != len(vector):\n raise Exception(\"You set --embedding_path=%s but --embedding_size=%i. If you set --embedding_path yourself then make sure that --embedding_size matches!\" % (embedding_path, embedding_dim))\n emb_matrix[idx, :] = vector\n word2id[word] = idx\n id2word[idx] = word\n idx += 1\n\n final_vocab_size = vocab_size\n assert len(word2id) == final_vocab_size\n assert len(id2word) == final_vocab_size\n assert idx == final_vocab_size\n\n return emb_matrix, word2id, id2word\n\nemb_matrix, word2id, id2word = get_vec('data/vocal_vec.txt', 300)\ntrain_generator = batch_generator.BatchGenerator('train', batch_size=16, emdim=300, word2id=word2id, id2word=id2word, embedding=emb_matrix, max_passage_length=None, max_query_length=None, shuffle=False)\ntest_generator = batch_generator.BatchGenerator('test', batch_size=16, emdim=300, word2id=word2id, id2word=id2word, embedding=emb_matrix, max_passage_length=None, max_query_length=None, shuffle=False)\n\nfrom bidaf.models import BidirectionalAttentionFlow\nfrom bidaf.scripts import load_data_generators\nbidaf_model = BidirectionalAttentionFlow(300)\n# bidaf_model.load_bidaf(\"/path/to/model.h5\") # when you want to resume training\n# train_generator, validation_generator = load_data_generators(24, 400)\nkeras_model = bidaf_model.train_model(train_generator, validation_generator=test_generator, epochs=2000)" }, { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 24, "blob_id": "b691e40998df07fe287d7be9a92e4c2bca5107e3", "content_id": "cc9556cee1cc1859000dbe03fd3e4911eefd69dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 52, "license_type": "no_license", "max_line_length": 31, "num_lines": 2, "path": "/data/test_data_ner/中部0484/desktop.ini", "repo_name": "thaiduongx26/Kepco-Bidaf", "src_encoding": "UTF-8", "text": "[.ShellClassInfo]\r\nLocalizedResourceName=@??0484,0\r\n" }, { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 24, "blob_id": "8a75748a640ba0cc4fec2188afcf203e9da66316", "content_id": "b7178d4670c40a859b3a125cb15bbef5dfcac71f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 52, "license_type": "no_license", "max_line_length": 31, "num_lines": 2, "path": "/data/test_data_ner/中部0371/desktop.ini", "repo_name": "thaiduongx26/Kepco-Bidaf", "src_encoding": "UTF-8", "text": "[.ShellClassInfo]\r\nLocalizedResourceName=@??0371,0\r\n" }, { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 24, "blob_id": "b18a8a4ad426bbed5808f243d7c5cf4c65212abe", "content_id": "2cf9ca2f622edd3ca6510e6aced3594c0c5616ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 52, "license_type": "no_license", "max_line_length": 31, "num_lines": 2, "path": "/data/test_data_ner/九州0376/desktop.ini", "repo_name": "thaiduongx26/Kepco-Bidaf", "src_encoding": "UTF-8", "text": "[.ShellClassInfo]\r\nLocalizedResourceName=@??0376,0\r\n" }, { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 24, "blob_id": "376f7fad6912b8ee78e2c6a129bdaee48bd3bf77", "content_id": "920de9bd71318e7b812136903155e8481e06aa46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 52, "license_type": "no_license", "max_line_length": 31, "num_lines": 2, "path": "/data/test_data_ner/九州0377/desktop.ini", "repo_name": "thaiduongx26/Kepco-Bidaf", "src_encoding": "UTF-8", "text": "[.ShellClassInfo]\r\nLocalizedResourceName=@??0377,0\r\n" }, { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 24, "blob_id": "07cbaf90f0481ecdb408ca9f008362bb3280559a", "content_id": "57e99200471d84e45c020e0d8a55a54652f6f3c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 52, "license_type": "no_license", "max_line_length": 31, "num_lines": 2, "path": "/data/test_data_ner/中部0486/desktop.ini", "repo_name": "thaiduongx26/Kepco-Bidaf", "src_encoding": "UTF-8", "text": "[.ShellClassInfo]\r\nLocalizedResourceName=@??0486,0\r\n" }, { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 24, "blob_id": "346ea8c629684c6f286d6878d320a47d54418ddb", "content_id": "78dd9ec7cae30bd185496e23094150729debb2bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 52, "license_type": "no_license", "max_line_length": 31, "num_lines": 2, "path": "/data/test_data_ner/中国0042/desktop.ini", "repo_name": "thaiduongx26/Kepco-Bidaf", "src_encoding": "UTF-8", "text": "[.ShellClassInfo]\r\nLocalizedResourceName=@??0042,0\r\n" }, { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 24, "blob_id": "61894355b4bb4bfd9a32516426084e0f27d57c91", "content_id": "242091465262a12c4aac90660394e3ed3480825d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 52, "license_type": "no_license", "max_line_length": 31, "num_lines": 2, "path": "/data/test_data_ner/中国0050/desktop.ini", "repo_name": "thaiduongx26/Kepco-Bidaf", "src_encoding": "UTF-8", "text": "[.ShellClassInfo]\r\nLocalizedResourceName=@??0050,0\r\n" }, { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 24, "blob_id": "ac73c7f47b6e04c97d9257c402514953b5de7fa0", "content_id": "c83aad34d0e37a0a57105d0930be3d4776446a72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 52, "license_type": "no_license", "max_line_length": 31, "num_lines": 2, "path": "/data/test_data_ner/中部0310/desktop.ini", "repo_name": "thaiduongx26/Kepco-Bidaf", "src_encoding": "UTF-8", "text": "[.ShellClassInfo]\r\nLocalizedResourceName=@??0310,0\r\n" }, { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 24, "blob_id": "5362ac019744f4f8bc5559d73cb6bb68a35d14cd", "content_id": "c1d92d56180d26f8fda8444c74e39c99363717e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 52, "license_type": "no_license", "max_line_length": 31, "num_lines": 2, "path": "/data/test_data_ner/中国0054/desktop.ini", "repo_name": "thaiduongx26/Kepco-Bidaf", "src_encoding": "UTF-8", "text": "[.ShellClassInfo]\r\nLocalizedResourceName=@??0054,0\r\n" }, { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 24, "blob_id": "52400ee5256a05136974e25d3c32a67ba9a17b1b", "content_id": "201bbdd118bc5204ca8f0eb98865fe90a7c378cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 52, "license_type": "no_license", "max_line_length": 31, "num_lines": 2, "path": "/data/test_data_ner/中国0040/desktop.ini", "repo_name": "thaiduongx26/Kepco-Bidaf", "src_encoding": "UTF-8", "text": "[.ShellClassInfo]\r\nLocalizedResourceName=@??0040,0\r\n" }, { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 24, "blob_id": "f111bd9c006d65893136d7abf3f94e4279c7d985", "content_id": "dd6a5a61308147acb9bde74b7d066437c9e8848c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 52, "license_type": "no_license", "max_line_length": 31, "num_lines": 2, "path": "/data/test_data_ner/中部0186/desktop.ini", "repo_name": "thaiduongx26/Kepco-Bidaf", "src_encoding": "UTF-8", "text": "[.ShellClassInfo]\r\nLocalizedResourceName=@??0186,0\r\n" }, { "alpha_fraction": 0.5775541663169861, "alphanum_fraction": 0.6003096103668213, "avg_line_length": 34.690608978271484, "blob_id": "c9a2215c8f5dbec69f2bcca354dce48f2fb62381", "content_id": "907864c437c62fe20b5eae0b409545771b9cc023", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6460, "license_type": "no_license", "max_line_length": 204, "num_lines": 181, "path": "/evaluate.py", "repo_name": "thaiduongx26/Kepco-Bidaf", "src_encoding": "UTF-8", "text": "from tqdm import tqdm\nimport numpy as np\nimport os\nimport io\nimport json\nimport sys\nimport logging\nfrom bidaf.scripts import batch_generator\nimport tensorflow as tf\n\nvocab_size = 1874\nembedding_path = \"data/vocal_vec.txt\"\nembedding_dim = 300\ndata_dir = \"data\"\ntrain_dir = \"model\"\n\ndef get_vec(embedding_path, embedding_dim):\n print(\"Loading embedding vectors from file: %s\" % embedding_path)\n\n emb_matrix = np.zeros((vocab_size, embedding_dim))\n word2id = {}\n id2word = {}\n idx = 0\n\n with open(embedding_path, 'r') as fh:\n for line in tqdm(fh, total=vocab_size):\n line = line.lstrip().rstrip().split(\" \")\n word = line[0]\n# print(word)\n vector = list(map(float, line[1:]))\n if embedding_dim != len(vector):\n raise Exception(\"You set --embedding_path=%s but --embedding_size=%i. If you set --embedding_path yourself then make sure that --embedding_size matches!\" % (embedding_path, embedding_dim))\n emb_matrix[idx, :] = vector\n word2id[word] = idx\n id2word[idx] = word\n idx += 1\n\n final_vocab_size = vocab_size\n assert len(word2id) == final_vocab_size\n assert len(id2word) == final_vocab_size\n assert idx == final_vocab_size\n\n return emb_matrix, word2id, id2word\n\nemb_matrix, word2id, id2word = get_vec('data/vocal_vec.txt', 300)\n\nfrom bidaf.models import BidirectionalAttentionFlow\n\nbidaf_model = BidirectionalAttentionFlow(300)\nbidaf_model.load_bidaf(\"/content/gdrive/My Drive/Kepco/bidaf_04.h5\")\n\nmax_span_length = 0\nspanfile = open(\"data/span-test.txt\", \"r\")\nline = spanfile.readline()\nwhile(line):\n line = line.replace('\\n', '')\n arrline = line.split(' ')\n \n if(int(arrline[1]) - int(arrline[0]) + 1 > max_span_length):\n max_span_length = int(arrline[1]) - int(arrline[0]) + 1 \n line = spanfile.readline()\nspanfile.close()\nprint(max_span_length)\n\ndef get_best_span(span_begin_probs, span_end_probs, context_length, max_span_length=26):\n if len(span_begin_probs.shape) > 2 or len(span_end_probs.shape) > 2:\n raise ValueError(\"Input shapes must be (X,) or (1,X)\")\n if len(span_begin_probs.shape) == 2:\n assert span_begin_probs.shape[0] == 1, \"2D input must have an initial dimension of 1\"\n span_begin_probs = span_begin_probs.flatten()\n if len(span_end_probs.shape) == 2:\n assert span_end_probs.shape[0] == 1, \"2D input must have an initial dimension of 1\"\n span_end_probs = span_end_probs.flatten()\n\n max_span_probability = 0\n best_word_span = (0, 1)\n\n for i, val1 in enumerate(span_begin_probs):\n for j, val2 in enumerate(span_end_probs):\n if j > context_length - 1:\n break\n\n\n if (j - i) >= max_span_length:\n break\n\n if val1 * val2 > max_span_probability:\n best_word_span = (i, j)\n max_span_probability = val1 * val2\n return best_word_span, max_span_probability\n\nfrom collections import Counter\n\ndef handle_file(file, types):\n data = []\n line = file.readline()\n while(line):\n line = line.replace(\"\\n\", '')\n arr = line.split(' ')\n if(types == \"context\" or types == \"question\"):\n arr.remove('')\n data.append(arr)\n line = file.readline()\n file.close()\n return data\n\ndef check_subarray_in(arr1, arr2):\n if(arr1[0] in arr2):\n ind = arr2.index(arr1[0])\n if(arr1 == arr2[ind:ind+len(arr1)]):\n return True\n return False\n\ndef f1_score(prediction, ground_truth):\n prediction_tokens = prediction.split()\n ground_truth_tokens = ground_truth.split()\n print(\"prediction_tokens: {}\".format(prediction_tokens))\n print(\"ground_truth_tokens: {}\".format(ground_truth_tokens))\n# common = Counter(prediction_tokens) & Counter(ground_truth_tokens)\n# num_same = sum(common.values())\n max_subtoken = 0\n for i in range(len(prediction_tokens)):\n arr = []\n for j in range(i, len(prediction_tokens)):\n arr.append(prediction_tokens[j])\n if(check_subarray_in(arr, ground_truth_tokens) and len(arr) > max_subtoken):\n max_subtoken = len(arr)\n else:\n break\n if(max_subtoken/len(ground_truth_tokens) > 0.95):\n num_same = max_subtoken\n else:\n num_same = 0\n print(\"num_same: {}\".format(num_same))\n if num_same == 0:\n return 0\n precision = 1.0 * num_same / len(prediction_tokens)\n recall = 1.0 * num_same / len(ground_truth_tokens)\n f1 = (2 * precision * recall) / (precision + recall)\n return f1\n\ndef calcu_f1():\n testspan = open(\"data/span-test.txt\", \"r\")\n testfilecon = open(\"data/context-test.txt\", \"r\")\n testfileques = open(\"data/question-test.txt\", \"r\")\n spanarr = handle_file(testspan, types=\"span\")\n conarr = handle_file(testfilecon, types=\"context\")\n quesarr = handle_file(testfileques, types=\"question\")\n pred = []\n answer_true = []\n answer_pred = []\n f1_total = 0\n for i, arr in enumerate(conarr):\n con_emb = np.zeros((1, len(arr), 300))\n ques_emb = np.zeros((1, len(quesarr[i]), 300))\n for j, word in enumerate(arr):\n con_emb[0, j, :] = emb_matrix[word2id[word]]\n for j, word in enumerate(quesarr[i]):\n ques_emb[0, j, :] = emb_matrix[word2id[word]]\n res = bidaf_model.model.predict([con_emb, ques_emb])\n y_pred_start = res[:, 0, :]\n y_pred_end = res[:, 1, :]\n answer_span, confidence_score = get_best_span(y_pred_start[0, :], y_pred_end[0, :], len(conarr))\n pred.append([answer_span[0], answer_span[1]])\n answer_pred.append(\" \".join(arr[answer_span[0]: answer_span[1] + 1]))\n spanarr = np.expand_dims(np.array(spanarr, dtype='float32'), axis=1)\n pred = np.expand_dims(np.array(pred, dtype='float32'), axis=1)\n true = 0\n for i in range(spanarr.shape[0]):\n answer_true.append(\" \".join(conarr[i][int(spanarr[i][0][0]): int(spanarr[i][0][1]) + 1]))\n if(spanarr[i][0][0] == pred[i][0][0] and spanarr[i][0][1] == pred[i][0][1]):\n true = true + 1\n for i in range(len(answer_true)):\n f1 = f1_score(answer_pred[i], answer_true[i])\n f1_total += f1\n print(\"f1-score: {}\".format(f1_total/461))\n print(\"acc: {}\".format(true/461))\n# print(\"answer_true: {}\".format(answer_true))\n# print(\"pred: {}\".format(answer_pred))\n\ncalcu_f1()\n" }, { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 24, "blob_id": "e0c7025d2d9c1f6f5d82723b93b51bec6284423a", "content_id": "05f211dc4af0b73d58c7379e41376bc97f36cae9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 52, "license_type": "no_license", "max_line_length": 31, "num_lines": 2, "path": "/data/test_data_ner/九州0553/desktop.ini", "repo_name": "thaiduongx26/Kepco-Bidaf", "src_encoding": "UTF-8", "text": "[.ShellClassInfo]\r\nLocalizedResourceName=@??0553,0\r\n" }, { "alpha_fraction": 0.5290251970291138, "alphanum_fraction": 0.5377874970436096, "avg_line_length": 40.5, "blob_id": "0c8429d65e89d4660a461d62d67dc6940f2cb2dd", "content_id": "243b88858c31d851ef391f1bdd6d504698283f2b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4565, "license_type": "no_license", "max_line_length": 128, "num_lines": 110, "path": "/bidaf/scripts/batch_generator.py", "repo_name": "thaiduongx26/Kepco-Bidaf", "src_encoding": "UTF-8", "text": "from keras.utils import Sequence\nimport os\nimport numpy as np\n\n# from .magnitude import MagnitudeVectors\n\n\nclass BatchGenerator(Sequence):\n 'Generates data for Keras'\n\n vectors = None\n\n def __init__(self, gen_type, batch_size, emdim, max_passage_length, max_query_length, shuffle, word2id, id2word, embedding):\n 'Initialization'\n\n base_dir = os.path.join(os.path.dirname(__file__), os.pardir, 'data')\n self.emdim = emdim\n self.word2id = word2id\n self.id2word = id2word\n self.embedding = embedding\n self.max_passage_length = max_passage_length\n self.max_query_length = max_query_length\n\n self.context_file = os.path.join(\"data\", \"context\" + '-{}.txt'.format(gen_type))\n self.question_file = os.path.join(\"data\", \"question\" + '-{}.txt'.format(gen_type))\n self.span_file = os.path.join(\"data\", \"span\" + '-{}.txt'.format(gen_type))\n self.batch_size = batch_size\n i = 0\n with open(self.span_file, 'r', encoding='utf-8') as f:\n\n for i, _ in enumerate(f):\n pass\n self.num_of_batches = (i + 1) // self.batch_size\n self.indices = np.arange(i + 1)\n self.shuffle = shuffle\n\n def __len__(self):\n 'Denotes the number of batches per epoch'\n return self.num_of_batches\n\n def __getitem__(self, index):\n 'Generate one batch of data'\n # Generate indexes of the batch\n start_index = (index * self.batch_size) + 1\n end_index = ((index + 1) * self.batch_size) + 1\n\n inds = self.indices[start_index:end_index]\n\n contexts = []\n max_contexts = 0\n with open(self.context_file, 'r', encoding='utf-8') as cf:\n for i, line in enumerate(cf, start=1):\n line = line[:-1]\n if i in inds:\n arr = line.split(' ')\n arr.remove('')\n if(len(arr) > max_contexts):\n max_contexts = len(arr)\n contexts.append(arr)\n# print(\"max context: {}\".format(max_contexts))\n\n questions = []\n max_questions = 0\n with open(self.question_file, 'r', encoding='utf-8') as qf:\n for i, line in enumerate(qf, start=1):\n line = line[:-1]\n if i in inds:\n arr = line.split(' ')\n arr.remove('')\n if(len(arr) > max_questions):\n max_questions = len(arr)\n questions.append(arr)\n# print(\"max_question: {}\".format(max_questions))\n answer_spans = []\n with open(self.span_file, 'r', encoding='utf-8') as sf:\n for i, line in enumerate(sf, start=1):\n line = line[:-1]\n if i in inds:\n answer_spans.append(line.split(' '))\n \n contexts_batch = np.zeros((self.batch_size, max_contexts, self.emdim), dtype='float32')\n questions_batch = np.zeros((self.batch_size, max_questions, self.emdim), dtype='float32')\n for i in range(len(contexts)):\n for w in range(len(contexts[i])):\n if(contexts[i][w] not in self.word2id):\n print(index)\n print(\"OHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH !!!!!!!!\")\n contexts_batch[i, w, :] = self.embedding[self.word2id[contexts[i][w]]]\n \n\n for i in range(len(questions)):\n for w in range(len(questions[i])):\n if(questions[i][w] not in self.word2id):\n print(index)\n print(\"OHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH !!!!!!!!\")\n questions_batch[i, w, :] = self.embedding[self.word2id[questions[i][w]]]\n\n # context_batch = self.vectors.query(contexts, pad_to_length=self.max_passage_length)\n # question_batch = self.vectors.query(questions, pad_to_length=self.max_query_length)\n # print(\"context shape : {}\".format(context_batch.shape))\n if self.max_passage_length is not None:\n span_batch = np.expand_dims(np.array(answer_spans, dtype='float32'), axis=1).clip(0,\n self.max_passage_length - 1)\n else:\n span_batch = np.expand_dims(np.array(answer_spans, dtype='float32'), axis=1)\n return [contexts_batch, questions_batch], [span_batch]\n\n def on_epoch_end(self):\n if self.shuffle:\n np.random.shuffle(self.indices)\n" }, { "alpha_fraction": 0.6730769276618958, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 24, "blob_id": "f049ba1ef8fe9d79930b7dad2d4c9be319d4a641", "content_id": "e8b16139776dece99d4b71adb51fe299f256e928", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 52, "license_type": "no_license", "max_line_length": 31, "num_lines": 2, "path": "/data/test_data_ner/中国0152/desktop.ini", "repo_name": "thaiduongx26/Kepco-Bidaf", "src_encoding": "UTF-8", "text": "[.ShellClassInfo]\r\nLocalizedResourceName=@??0152,0\r\n" } ]
23
marissap/sun-twitter-bot
https://github.com/marissap/sun-twitter-bot
562ec42fb3d8b4d7569dffbe7220ae430fb50827
a9f1e10e0c70af7c5c378daf3f181f6c71816884
04412f3c20fc2f6cd810c3b668e0199da1ec945b
refs/heads/master
2020-04-03T18:42:36.619651
2018-10-31T04:02:00
2018-10-31T04:02:00
155,494,437
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6931818127632141, "alphanum_fraction": 0.7113636136054993, "avg_line_length": 28.366666793823242, "blob_id": "9b7e86ed47d8d0ab5d4aa72a9c880fce6f6474aa", "content_id": "be44a6ec8e93f82fa213c27c19ba3582e39fcc3d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 880, "license_type": "no_license", "max_line_length": 182, "num_lines": 30, "path": "/weather.py", "repo_name": "marissap/sun-twitter-bot", "src_encoding": "UTF-8", "text": "import json\nimport tweepy\nimport requests\n\nimport time\nimport datetime\n\nresponse = requests.get('https://weather.cit.api.here.com/weather/1.0/report.json?product=forecast_astronomy&name=Ottawa&app_id=t883KznRyE8cWLnJaYkn&app_code=MnUR3KfQTWo1MDxu92e1BA')\ndata = json.loads(response.text)\n\nauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)\nauth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)\napi = tweepy.API(auth)\n\nsunStuff = []\n\nsunStuff.append(data[\"astronomy\"][\"astronomy\"][1][\"sunrise\"])\nsunStuff.append(data[\"astronomy\"][\"astronomy\"][1][\"sunset\"])\n\ncount = 0\nts = time.time()\nst = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')\n\nfor change in sunStuff:\n if count == 0:\n change = st + \"\\nHello Today! Sunrise: \" + change\n else:\n change = st + \"\\nGoodbye Today! Sunset: \" + change\n count += 1\n api.update_status(change)" }, { "alpha_fraction": 0.7931034564971924, "alphanum_fraction": 0.7931034564971924, "avg_line_length": 27.66666603088379, "blob_id": "c2c71c98eae71e2e0c3366deb4de22422679b390", "content_id": "ed8e34f8e27767b68b8311f68f43c3944a5fa770", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 87, "license_type": "no_license", "max_line_length": 51, "num_lines": 3, "path": "/README.md", "repo_name": "marissap/sun-twitter-bot", "src_encoding": "UTF-8", "text": "# Sunrise and Sunset Twitter Bot\n\nTwitter bot tweets the sunrise and sunset in Ottawa\n\n" } ]
2
SU-WebClub/swap-site-backend
https://github.com/SU-WebClub/swap-site-backend
f1eecd44b1ce90a7e6f277b9f8cd535daa629e4d
46bbf3ccdf9ee6bf1665dd12cf2c2fb9cd25df10
e304e4b4f00400c2b14a4b411cbcbd39d7bbed90
refs/heads/master
2023-05-13T18:32:42.977979
2021-05-25T23:42:32
2021-05-25T23:42:32
363,307,184
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6480769515037537, "alphanum_fraction": 0.656410276889801, "avg_line_length": 31.852632522583008, "blob_id": "b51606ddf368cb96ebc857fcbe8876ed6ae0b69f", "content_id": "919a15019b434630c578f59805232c83103c4904", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3392, "license_type": "no_license", "max_line_length": 89, "num_lines": 95, "path": "/api/models.py", "repo_name": "SU-WebClub/swap-site-backend", "src_encoding": "UTF-8", "text": "from django.db import models\n\nclass Category(models.Model):\n name = models.CharField('カテゴリー名', max_length=255)\n slug = models.SlugField('英語名', unique=True)\n timestamp = models.DateTimeField(auto_now_add=True)\n thumbnail = models.ImageField('イメージ画像', upload_to='category_thumbnail/', blank=True)\n\n class Meta:\n verbose_name = 'カテゴリー'\n verbose_name_plural = 'カテゴリーリスト'\n\n def __str__(self):\n return self.name\n\nclass Tag(models.Model):\n name = models.CharField('タグ名', max_length=255)\n slug = models.SlugField('英語名', unique=True, blank=True)\n timestamp = models.DateTimeField(auto_now_add=True)\n\n class Meta:\n verbose_name = 'タグ'\n verbose_name_plural = 'タグリスト'\n\n def __str__(self):\n return self.name\n\n\nclass Role(models.Model):\n name = models.CharField('役職名', max_length=30)\n slug = models.SlugField('英語名', unique=True)\n timestamp = models.DateTimeField(auto_now_add=True)\n\n class Meta:\n verbose_name = '役職'\n verbose_name_plural = '役職リスト'\n\n def __str__(self):\n return self.name\n\nclass Author(models.Model):\n role = models.ForeignKey(Role, on_delete=models.PROTECT)\n icon = models.ImageField('アイコン', help_text='正方形の画像にしてください', upload_to='author_icon/')\n name = models.CharField('ニックネーム', max_length=15)\n description = models.TextField('自己紹介', max_length=500)\n HomePage = models.CharField(max_length=100, blank=True)\n GitID = models.CharField(max_length=100, blank=True)\n\n class Meta:\n verbose_name = '記者'\n verbose_name_plural = '記者リスト'\n\n def __str__(self):\n return self.name\n\nclass Blog(models.Model):\n category = models.ForeignKey(Category, on_delete=models.PROTECT)\n tags = models.ManyToManyField(Tag, blank=True)\n thumbnail = models.ImageField('サムネ', upload_to='blog_thumbnail/')\n title = models.CharField('タイトル', max_length=75)\n author = models.ForeignKey(Author, on_delete=models.PROTECT, blank=False)\n description = models.CharField('headタグでの説明', max_length=255, blank=False)\n content = models.TextField('本文')\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n published_at = models.DateTimeField('公開日', blank=False, null=True)\n is_public = models.BooleanField('公開する', default=False)\n\n class Meta:\n ordering = ['-created_at']\n verbose_name = '記事'\n verbose_name_plural = 'ブログ投稿'\n\n def save(self, *args, **kwargs):\n if self.is_public and not self.published_at:\n self.published_at = timezone.now()\n super().save(*args, **kwargs)\n\n def __str__(self):\n return self.title\n\n\nclass News(models.Model):\n thumbnail = models.ImageField('サムネ', upload_to='images/')\n title = models.CharField('タイトル', max_length=75)\n content = models.TextField('本文')\n created_at = models.DateTimeField(auto_now_add=True)\n author = models.ForeignKey(Author, on_delete=models.PROTECT, blank=False)\n\n class Meta:\n verbose_name = 'ニュース'\n verbose_name_plural = 'ニュース投稿'\n\n def __str__(self):\n return self.title" }, { "alpha_fraction": 0.7453703880310059, "alphanum_fraction": 0.7453703880310059, "avg_line_length": 35.878047943115234, "blob_id": "cf1575965fa56152cd13d0db8aaccbbc8df85162", "content_id": "5884db27e35350cee11bd85b3c3a7d07b1f06bc3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1512, "license_type": "no_license", "max_line_length": 126, "num_lines": 41, "path": "/api/views.py", "repo_name": "SU-WebClub/swap-site-backend", "src_encoding": "UTF-8", "text": "from rest_framework.generics import ListAPIView\nfrom rest_framework import viewsets\nfrom django_filters.rest_framework import DjangoFilterBackend\nfrom .models import Blog, Category, Tag, Author, News\nfrom .serializers import BlogSerializer, CategorySerializer, TagSerializer, AuthorSerializer, SearchSerializer, NewsSerializer\nfrom rest_framework import filters\n\n\nclass BlogAPIView(ListAPIView):\n queryset = Blog.objects.all()\n serializer_class = BlogSerializer\n filter_backends = [DjangoFilterBackend]\n filterset_fields = ('id', 'category__slug', 'tags', 'author')\n\nclass CategoryAPIView(ListAPIView):\n queryset = Category.objects.all()\n serializer_class = CategorySerializer\n filter_backends = [DjangoFilterBackend]\n filterset_fields = ('id', 'slug')\n\nclass TagAPIView(ListAPIView):\n queryset = Tag.objects.all()\n serializer_class = TagSerializer\n\nclass AuthorAPIView(ListAPIView):\n queryset = Author.objects.order_by('role')\n serializer_class = AuthorSerializer\n filter_backends = [DjangoFilterBackend]\n filterset_fields = ('id', 'role__name')\n\nclass SearchAPIView(ListAPIView):\n queryset = Blog.objects.all()\n serializer_class = SearchSerializer\n filter_backends = [filters.SearchFilter]\n search_fields = ['title', 'tags__name', 'content', 'author__name', 'category__name']\n\nclass NewsAPIView(ListAPIView):\n queryset = News.objects.all()\n serializer_class = NewsSerializer\n filter_backends = [DjangoFilterBackend]\n filterset_fields = ('id',)\n" }, { "alpha_fraction": 0.6672374606132507, "alphanum_fraction": 0.6672374606132507, "avg_line_length": 22.675676345825195, "blob_id": "7309f906c0bd1fbe4a0adbf683ed1d883cbcc914", "content_id": "849a097d0aca40d29a03519c6884135b85f2696b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1752, "license_type": "no_license", "max_line_length": 106, "num_lines": 74, "path": "/api/serializers.py", "repo_name": "SU-WebClub/swap-site-backend", "src_encoding": "UTF-8", "text": "from rest_framework.serializers import ModelSerializer, CharField, StringRelatedField, MultipleChoiceField\nfrom rest_framework import serializers\nfrom django_filters import rest_framework as filters\nfrom .models import Blog, Category, Role, Tag, Author, News\n\nclass AuthorSenderSerializer(ModelSerializer):\n class Meta:\n model = Author\n fields = '__all__'\n\nclass TagSenderSerializer(ModelSerializer):\n class Meta:\n model = Tag\n fields = '__all__'\n\nclass CategorySenderSerializer(ModelSerializer):\n class Meta:\n model = Category\n fields = '__all__'\n\nclass BlogSerializer(ModelSerializer):\n category = CharField(source='category.name')\n tags = StringRelatedField(many=True, read_only=True)\n author = AuthorSenderSerializer()\n\n class Meta:\n model = Blog\n fields = '__all__'\n\n\nclass CategorySerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Category\n fields = '__all__'\n\n\nclass TagSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Tag\n fields = '__all__'\n\n\nclass RoleSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Role\n fields = '__all__'\n\n\nclass AuthorSerializer(serializers.ModelSerializer):\n role = RoleSerializer\n\n class Meta:\n model = Author\n fields = '__all__'\n\n\nclass SearchSerializer(serializers.ModelSerializer):\n author = AuthorSenderSerializer()\n tags = TagSenderSerializer()\n category = CategorySenderSerializer()\n\n class Meta:\n model = Blog\n fields = '__all__'\n \nclass NewsSerializer(serializers.ModelSerializer):\n author = AuthorSenderSerializer()\n\n class Meta:\n model = News\n fields = '__all__'\n" }, { "alpha_fraction": 0.5632184147834778, "alphanum_fraction": 0.7298850417137146, "avg_line_length": 18.33333396911621, "blob_id": "280bdada73ebc520a9c78f7b022d1f7a8978c06e", "content_id": "1aa9a4671d4a364fdcd20457af9bb3b733ba8f1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 174, "license_type": "no_license", "max_line_length": 27, "num_lines": 9, "path": "/requirements.txt", "repo_name": "SU-WebClub/swap-site-backend", "src_encoding": "UTF-8", "text": "asgiref==3.3.4\nDjango==3.2\ndjango-cors-headers==3.7.0\ndjango-filter==2.4.0\ndjango-restframework==0.0.1\ndjangorestframework==3.12.4\nPillow==8.2.0\npytz==2021.1\nsqlparse==0.4.1\n" }, { "alpha_fraction": 0.6818181872367859, "alphanum_fraction": 0.6887519359588623, "avg_line_length": 27.2391300201416, "blob_id": "f4d888f712e1f774df84d307b7949c5418b887fa", "content_id": "957d5dcfa3419bd67b492c4b49da5e4a829194c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1304, "license_type": "no_license", "max_line_length": 102, "num_lines": 46, "path": "/api/admin.py", "repo_name": "SU-WebClub/swap-site-backend", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom django.utils.safestring import mark_safe\nfrom django.forms import TextInput, Textarea\nfrom django.db import models\nfrom .models import (\n Category,\n Tag,\n Blog,\n Author,\n Role,\n News\n)\n\n\nclass BlogAdmin(admin.ModelAdmin):\n list_display = ('title', 'thumbnail_preview', 'created_at', 'category', 'is_public')\n list_filter = ('is_public',)\n ordering = ('-created_at',)\n filter_horizontal = ('tags',)\n\n def thumbnail_preview(self, obj):\n return mark_safe('<img src=\"{}\" style=\"width:100px; height:auto;\">'.format(obj.thumbnail.url))\n\n thumbnail_preview.short_description = 'サムネ'\n\n\nclass AuthorAdmin(admin.ModelAdmin):\n list_display = ('icon_preview', 'name')\n\n def icon_preview(self, obj):\n return mark_safe('<img src=\"{}\" style=\"width:100px; height:auto;\">'.format(obj.icon.url))\n\n\nclass NewsAdmin(admin.ModelAdmin):\n list_display = ('title', 'thumbnail_preview')\n\n def thumbnail_preview(self, obj):\n return mark_safe('<img src=\"{}\" style=\"width:100px; height:auto;\">'.format(obj.thumbnail.url))\n\n\nadmin.site.register(Blog, BlogAdmin)\nadmin.site.register(News, NewsAdmin)\nadmin.site.register(Category)\nadmin.site.register(Tag)\nadmin.site.register(Role)\nadmin.site.register(Author, AuthorAdmin)" }, { "alpha_fraction": 0.6817102432250977, "alphanum_fraction": 0.6817102432250977, "avg_line_length": 33.83333206176758, "blob_id": "f188ce977b8e3e75a772eddb011598b38d77a0a6", "content_id": "b84e6dae09153bfaf32aed97caf541d0f6600182", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 421, "license_type": "no_license", "max_line_length": 102, "num_lines": 12, "path": "/api/urls.py", "repo_name": "SU-WebClub/swap-site-backend", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom .views import BlogAPIView, CategoryAPIView, TagAPIView, AuthorAPIView, SearchAPIView, NewsAPIView\n\n\nurlpatterns = [\n path('blog/', BlogAPIView.as_view()),\n path('category/', CategoryAPIView.as_view()),\n path('tag/', TagAPIView.as_view()),\n path('author/', AuthorAPIView.as_view()),\n path('search/', SearchAPIView.as_view()),\n path('news/', NewsAPIView.as_view()),\n]\n\n\n\n" }, { "alpha_fraction": 0.5245775580406189, "alphanum_fraction": 0.5337941646575928, "avg_line_length": 45.5, "blob_id": "f43fd5a0df85d48b94ae160c1ca6e46452685113", "content_id": "3412195342ac73756bb668bdb94f7812a7f64154", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5480, "license_type": "no_license", "max_line_length": 118, "num_lines": 112, "path": "/api/migrations/0001_initial.py", "repo_name": "SU-WebClub/swap-site-backend", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2 on 2021-04-27 16:37\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Author',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('icon', models.ImageField(help_text='正方形の画像にしてください', upload_to='author_icon/', verbose_name='アイコン')),\n ('name', models.CharField(max_length=15, verbose_name='ニックネーム')),\n ('description', models.TextField(max_length=500, verbose_name='自己紹介')),\n ('HomePage', models.CharField(blank=True, max_length=100)),\n ('GitID', models.CharField(blank=True, max_length=100)),\n ],\n options={\n 'verbose_name': '記者',\n 'verbose_name_plural': '記者リスト',\n },\n ),\n migrations.CreateModel(\n name='Category',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=255, verbose_name='カテゴリー名')),\n ('slug', models.SlugField(unique=True, verbose_name='英語名')),\n ('timestamp', models.DateTimeField(auto_now_add=True)),\n ('thumbnail', models.ImageField(blank=True, upload_to='category_thumbnail/', verbose_name='イメージ画像')),\n ],\n options={\n 'verbose_name': 'カテゴリー',\n 'verbose_name_plural': 'カテゴリーリスト',\n },\n ),\n migrations.CreateModel(\n name='Role',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=30, verbose_name='役職名')),\n ('slug', models.SlugField(unique=True, verbose_name='英語名')),\n ('timestamp', models.DateTimeField(auto_now_add=True)),\n ],\n options={\n 'verbose_name': '役職',\n 'verbose_name_plural': '役職リスト',\n },\n ),\n migrations.CreateModel(\n name='Tag',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=255, verbose_name='タグ名')),\n ('slug', models.SlugField(blank=True, unique=True, verbose_name='英語名')),\n ('timestamp', models.DateTimeField(auto_now_add=True)),\n ],\n options={\n 'verbose_name': 'タグ',\n 'verbose_name_plural': 'タグリスト',\n },\n ),\n migrations.CreateModel(\n name='News',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('thumbnail', models.ImageField(upload_to='images/', verbose_name='サムネ')),\n ('title', models.CharField(max_length=75, verbose_name='タイトル')),\n ('content', models.CharField(max_length=5000, verbose_name='本文')),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('author', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='api.author')),\n ],\n options={\n 'verbose_name': 'ニュース',\n 'verbose_name_plural': 'ニュース投稿',\n },\n ),\n migrations.CreateModel(\n name='Blog',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('thumbnail', models.ImageField(upload_to='blog_thumbnail/', verbose_name='サムネ')),\n ('title', models.CharField(max_length=75, verbose_name='タイトル')),\n ('description', models.CharField(max_length=255, verbose_name='headタグでの説明')),\n ('content', models.CharField(max_length=5000, verbose_name='本文')),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('updated_at', models.DateTimeField(auto_now=True)),\n ('published_at', models.DateTimeField(null=True, verbose_name='公開日')),\n ('is_public', models.BooleanField(default=False, verbose_name='公開する')),\n ('author', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='api.author')),\n ('category', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='api.category')),\n ('tags', models.ManyToManyField(blank=True, to='api.Tag')),\n ],\n options={\n 'verbose_name': '記事',\n 'verbose_name_plural': 'ブログ投稿',\n 'ordering': ['-created_at'],\n },\n ),\n migrations.AddField(\n model_name='author',\n name='role',\n field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='api.role'),\n ),\n ]\n" } ]
7
redshiftrobotics/2856-CoreClassifier
https://github.com/redshiftrobotics/2856-CoreClassifier
bd3666b9bf656642defdf73d3052ee9894d77a32
9afee34516b63416974faf67ad5f30381428a05a
c2046a8f6fe6f743539e87b407e4eff688f82409
refs/heads/master
2020-04-01T03:32:52.158108
2018-10-21T21:00:20
2018-10-21T21:00:20
152,826,173
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6397058963775635, "alphanum_fraction": 0.6764705777168274, "avg_line_length": 17.133333206176758, "blob_id": "5730be794f2de90223a2722a0dc507c272f96021", "content_id": "564d126c550492d24d901aed12ea7cb206cdfed5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 273, "license_type": "no_license", "max_line_length": 54, "num_lines": 15, "path": "/App/realTimeMineralTester/realTimeMineralTester/Structures/Prediction.swift", "repo_name": "redshiftrobotics/2856-CoreClassifier", "src_encoding": "UTF-8", "text": "//\n// Prediction.swift\n// realTimeMineralTester\n//\n// Created by Zoe IAMZOE.io on 10/16/18.\n// Copyright © 2018 Zoe IAMZOE.io. All rights reserved.\n//\n\nimport UIKit\n\npublic struct Prediction {\n let label: String?\n let confidence: Float\n let boundingBox: CGRect\n}\n" }, { "alpha_fraction": 0.6600162982940674, "alphanum_fraction": 0.6655130386352539, "avg_line_length": 38.28799819946289, "blob_id": "350909c8725de80ef2e5a0fa4a47fc75b0f01439", "content_id": "24e0f26464db36cd6bfed7bed2678ab23e6ae68d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 4915, "license_type": "no_license", "max_line_length": 163, "num_lines": 125, "path": "/App/realTimeMineralTester/realTimeMineralTester/ViewController.swift", "repo_name": "redshiftrobotics/2856-CoreClassifier", "src_encoding": "UTF-8", "text": "//\n// ViewController.swift\n// realTimeMineralTester\n//\n// Created by Zoe IAMZOE.io on 10/16/18.\n// Copyright © 2018 Zoe IAMZOE.io. All rights reserved.\n//\n\nimport UIKit\nimport AVFoundation\n\nimport Vision\nimport CoreML\n\n@available(iOS 12.0, *)\nclass ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate {\n \n @IBOutlet weak var classificationText: UILabel!\n @IBOutlet weak var cameraView: UIView!\n \n private var requests = [VNRequest]()\n\n // for displaying camera frames\n private lazy var cameraLayer: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession)\n \n // caputure session\n private lazy var captureSession: AVCaptureSession = {\n let session = AVCaptureSession()\n session.sessionPreset = AVCaptureSession.Preset.photo\n guard\n let backCamera = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back),\n let input = try? AVCaptureDeviceInput(device: backCamera)\n else { return session }\n session.addInput(input)\n return session\n }()\n \n private lazy var classifier: m = m()\n\n override func viewDidLoad() {\n super.viewDidLoad()\n \n cameraView.layer.addSublayer(cameraLayer)\n cameraLayer.frame = cameraView.bounds\n \n let videoOutput = AVCaptureVideoDataOutput()\n videoOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String: Int(kCVPixelFormatType_32BGRA)]\n videoOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: \"MyQueue\"))\n \n self.captureSession.addOutput(videoOutput)\n self.captureSession.startRunning()\n \n setupVision()\n }\n \n override func viewDidLayoutSubviews() {\n super.viewDidLayoutSubviews()\n self.cameraLayer.frame = self.cameraView?.bounds ?? .zero\n }\n \n private func setupVision() {\n guard let visionModel = try? VNCoreMLModel(for: classifier.model) else {\n fatalError(\"Can’t load VisionML model\")\n }\n \n let classificationRequest = VNCoreMLRequest(model: visionModel, completionHandler: classify)\n classificationRequest.imageCropAndScaleOption = VNImageCropAndScaleOption.scaleFill\n requests = [classificationRequest]\n }\n \n private func classify(request: VNRequest, error: Error?) { \n guard let observations = request.results as? [VNRecognizedObjectObservation]\n else { fatalError(\"unexpected result type from VNCoreMLRequest\") }\n \n let predictions: [Prediction] = observations.map { prediction in\n return Prediction(label: prediction.labels.getGreatest()?.identifier, confidence: prediction.confidence, boundingBox: prediction.boundingBox)\n }\n \n var strings: [String] = []\n for prediction in predictions {\n let pct = Float(Int(prediction.confidence * 10000)) / 100\n strings.append(\"\\(prediction.label ?? \"\"): \\(pct)%\")\n }\n \n DispatchQueue.main.async {\n self.cameraLayer.sublayers?.removeSubrange(1...)\n \n for prediction in predictions {\n self.drawBox(boundingRect: prediction.boundingBox, forPrediction: prediction)\n }\n self.classificationText.text = strings.joined(separator: \", \")\n }\n }\n \n private func drawBox (boundingRect: CGRect, forPrediction prediction: Prediction) {\n let source = self.cameraView.frame\n \n let rectWidth = source.size.width * boundingRect.size.width\n let rectHeight = source.size.height * boundingRect.size.height\n \n let outline = CALayer()\n outline.frame = CGRect(x: boundingRect.origin.x * source.size.width, y:boundingRect.origin.y * source.size.height, width: rectWidth, height: rectHeight)\n \n outline.borderWidth = 5.0\n outline.borderColor = prediction.label == \"block\" ? UIColor.blue.cgColor : UIColor.red.cgColor\n \n self.cameraLayer.addSublayer(outline)\n }\n \n func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {\n guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {\n return\n }\n var requestOptions:[VNImageOption : Any] = [:]\n if let cameraIntrinsicData = CMGetAttachment(sampleBuffer, key: kCMSampleBufferAttachmentKey_CameraIntrinsicMatrix, attachmentModeOut: nil) {\n requestOptions = [.cameraIntrinsics:cameraIntrinsicData]\n }\n let imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: CGImagePropertyOrientation(rawValue: 6)!, options: requestOptions)\n do {\n try imageRequestHandler.perform(self.requests)\n } catch {\n print(error)\n }\n }\n}\n\n" }, { "alpha_fraction": 0.5768194198608398, "alphanum_fraction": 0.5902965068817139, "avg_line_length": 24.586206436157227, "blob_id": "5302841fd390dd423773ada43dd5c3f5d0251c80", "content_id": "424f9515e5d575daf13865d009f6889a387bca64", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Swift", "length_bytes": 743, "license_type": "no_license", "max_line_length": 67, "num_lines": 29, "path": "/App/realTimeMineralTester/realTimeMineralTester/Extentions/VisionExtentions.swift", "repo_name": "redshiftrobotics/2856-CoreClassifier", "src_encoding": "UTF-8", "text": "//\n// VisionExtentions.swift\n// realTimeMineralTester\n//\n// Created by Zoe IAMZOE.io on 10/16/18.\n// Copyright © 2018 Zoe IAMZOE.io. All rights reserved.\n//\n\nimport Vision\n\nextension Array where Element == VNClassificationObservation {\n \n func getGreatest () -> VNClassificationObservation? {\n var greatestElemement: VNClassificationObservation? = nil\n \n for element in self {\n guard greatestElemement != nil else {\n greatestElemement = element\n continue\n }\n \n if element.confidence > greatestElemement!.confidence {\n greatestElemement = element\n }\n }\n \n return greatestElemement\n }\n}\n" }, { "alpha_fraction": 0.6968231797218323, "alphanum_fraction": 0.7030386924743652, "avg_line_length": 25.327272415161133, "blob_id": "8f62b69d306eeb074ee4186f4216253a4502dc05", "content_id": "7853c0f5c253675aab4c25c545cdd8605e6e7bcf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1448, "license_type": "no_license", "max_line_length": 104, "num_lines": 55, "path": "/coreml_to_tensorflow.py", "repo_name": "redshiftrobotics/2856-CoreClassifier", "src_encoding": "UTF-8", "text": "\"\"\"\nDONT USE THIS SCRIPT\nThis script was created to test a possible way to convert coreml models to tensorflow models using onnx.\n\"\"\"\n\nimport onnxmltools\nimport coremltools\nfrom keras.models import model_from_json\nimport onnx\nimport onnx_caffe2.backend\n\n\ndef load_json_model():\n with open('model/plain_model.json', 'r') as file:\n data = file.read()\n print data.split()[:5]\n return data\n\n\n# lode the CoreML model\ncoreml_model = coremltools.utils.load_spec('model/m.mlmodel')\n\n# convert the CoreML model into IR\nonnx_model = onnxmltools.convert_coreml(coreml_model, 'model')\n\nprepared_backend = onnx_caffe2.backend.prepare(onnx_model)\n\n# for printing the model\n# print onnx.helper.printable_graph(onnx_model.graph)\n\n\"\"\" -- mxnet -- \"\"\"\n\n# sym, arg_params, aux_params = onnx_mxnet.import_model('super_resolution.onnx')\n\n\"\"\" -- caff2 -- \"\"\"\n\n# caffe2_model = caffe2.python.onnx.backend.prepare(onnx_model)\n#\n# init_net, predict_net = c2.onnx_graph_to_caffe2_net(caffe2_model)\n#\n# with open(\"model/init_model.pb\", \"wb\") as f:\n# f.write(init_net.SerializeToString())\n# with open(\"model/predict_model.pb\", \"wb\") as f:\n# f.write(predict_net.SerializeToString())\n\n\"\"\" -- tf -- \"\"\"\n\n# save the model in ir\n# onnxmltools.utils.save_model(onnx_model, 'model/ir_model.onnx')\n\n# convert IR to tensorflow model\n# tf_model = prepare(onnx_model)\n\n# then export it as a tensorflow model\n# tf_model.export_graph(\"model/tf_model.ckpt\")\n" }, { "alpha_fraction": 0.7150635123252869, "alphanum_fraction": 0.7150635123252869, "avg_line_length": 24.045454025268555, "blob_id": "a88906fd4d671e43f405fe197793936d6b38be31", "content_id": "050bdb5de4e6d196aeece33aeb26b2edbd604bf3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 551, "license_type": "no_license", "max_line_length": 77, "num_lines": 22, "path": "/test.py", "repo_name": "redshiftrobotics/2856-CoreClassifier", "src_encoding": "UTF-8", "text": "import turicreate as tc\n\nfrom glob import glob\n\n# load image\ntest = tc.SFrame(\n {'image': [tc.Image(image) for image in glob('generator/test/*.JPG')]})\n\n# load the model\nmodel = tc.load_model('m.model')\n\n# make predictions for each image\ntest['predictions'] = model.predict(test)\n\nprint(test['predictions']) # print them out\n\n# tell the visualizer how we want to display boxes on the images\ntest['image_with_predictions'] = tc.object_detector.util.draw_bounding_boxes(\n test['image'], test['predictions'])\n\n# open the visualizer\ntest.explore()\n" }, { "alpha_fraction": 0.6888412237167358, "alphanum_fraction": 0.709227442741394, "avg_line_length": 22.897436141967773, "blob_id": "c8d1c40c6d87c0997e7666ccc0ae797fa657743f", "content_id": "24d63602008d47798188708ea9b7362612ac31ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 932, "license_type": "no_license", "max_line_length": 132, "num_lines": 39, "path": "/README.md", "repo_name": "redshiftrobotics/2856-CoreClassifier", "src_encoding": "UTF-8", "text": "# Object detection\n\n## Structure\n\n- `test.py` test the created model\n- `load_data.py` load the image data and annotations into an sframe\n- `train.py` create and train a model\n- `generator/` generated images annotations and test data\n- `App/` simple iOS app for real time evaluation of the model\n- `model/` location of mlmodel\n- `m.model` turicreate model (download [here](https://drive.google.com/file/d/175a3Nsz4WlwidJI_RDRQKWAJ7qGKxe1e/view?usp=sharing))\n\n## How to run\n\n1. clone this repo\n2. install turicreate\n3. run `test.py`\n\n### Train model\n\nrun `train.py`\n\n### generate sframe\n\nrun `load_data.py`\n\n## Example output images\n\n(notice how it only finds the blocks outside of the crater)\n\n![img](doc/example1.png)\n![img](doc/example2.png)\n![img](doc/example3.png)\n![img](doc/example4.png)\n![img](doc/example5.png)\n![img](doc/example6.png)\n![img](doc/example7.png)\n![img](doc/example8.png)\n![img](doc/example9.png)\n" }, { "alpha_fraction": 0.6601417660713196, "alphanum_fraction": 0.6648666858673096, "avg_line_length": 37.98684310913086, "blob_id": "be5cfea045aab08246ed5dcfb4cd2e95e4cac9e2", "content_id": "d2eb5b8f004a92f5f0c66cabfa1001c38ceefcc4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2963, "license_type": "no_license", "max_line_length": 111, "num_lines": 76, "path": "/load_data.py", "repo_name": "redshiftrobotics/2856-CoreClassifier", "src_encoding": "UTF-8", "text": "import turicreate as tc\nimport xml.etree.ElementTree as ET\nimport glob\nimport os\nimport math\n\n# array for keeping track of the annotations we parse\nunsorted_annotations = [] # the array *must* be in this shape: [[{dict}]]\n\nfor file in glob.glob('generator/annotations/*.xml'): # loop through every xml annotation\n tree = ET.parse(file) # create a tree with the data from the xml file\n root = tree.getroot() # get the root element of the tree\n\n # array for the extracted properties for each object\n object_props = []\n \"\"\"\n the object element is an element containing x, y coordinates and the size\n of the detected object along with some meta-data about the object\n \"\"\"\n for member in root.findall('object'): # get every object element from the tree\n label = member[0].text # class of the detected object (block or ball)\n\n # coordinates are the 6th member of the object\n xmin = int(member[5][0].text)\n ymin = int(member[5][1].text)\n xmax = int(member[5][2].text)\n ymax = int(member[5][3].text)\n\n # get the dementions of the object from the coordinates\n width = xmax - xmin\n height = ymax - ymin\n\n # get the filename so we can map it to an image later\n image_name = root.find('filename').text\n\n # get the x, y points from the coordinates\n x = xmin + math.floor(width / 2)\n y = ymin + math.floor(height / 2)\n\n # basic properies\n props = {'label': label, 'type': 'rectangle', 'filename': image_name}\n # add coordinates to properties\n props['coordinates'] = {'height': height,\n 'width': width, 'x': x, 'y': y}\n\n # add the properies to the array of objects for this annotation\n object_props.append(props)\n\n # add it to the array of all annotations\n unsorted_annotations.append(object_props)\n\n# load all the images in the data folder\ndata = tc.image_analysis.load_images('generator/data')\n\n\"\"\"\nthe unsorted annotations are not in any particular order\nso we have to match them to each image from data\n\"\"\"\nannotations = [] # sored annotations\nfor item in data: # loop through every image object\n for row in unsorted_annotations: # find what annotation coorisponds to it\n if str(row[0]['filename']) == str(os.path.split(item['path'])[1]): # messy if statment\n # match image name in path\n annotations.append(row)\n break\n\ndata['annotations'] = tc.SArray(data=annotations, dtype=list) # set the annotations property in the data object\n\ndata.save('data.sframe') # save it to an sframe (sframe is just a serialized python object)\n\n# this tells the turicreate visualizer how we want it to draw boxes on our images\ndata['image_with_ground_truth'] = tc.object_detector.util.draw_bounding_boxes(\n data['image'], data['annotations'])\n\n# explore the data using the turicreate visulizer - THIS WILL BREAK ON NON-MAC OSs\ndata.explore()\n" }, { "alpha_fraction": 0.7292817831039429, "alphanum_fraction": 0.7292817831039429, "avg_line_length": 19.11111068725586, "blob_id": "1c88bf2c7aa912d797b4255c15f4dfe5446a8d3c", "content_id": "6530a0dd1927d3a23ceae3358577df1ac54056b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 181, "license_type": "no_license", "max_line_length": 73, "num_lines": 9, "path": "/export_coreml.py", "repo_name": "redshiftrobotics/2856-CoreClassifier", "src_encoding": "UTF-8", "text": "\"\"\"\nThis is a simple script to export the created model to coreml for testing\n\"\"\"\n\nimport turicreate as tc\n\nmodel = tc.load_model('m.model')\n\nmodel.export_coreml('model/m.mlmodel')\n" }, { "alpha_fraction": 0.6889985799789429, "alphanum_fraction": 0.696050763130188, "avg_line_length": 29.17021369934082, "blob_id": "71c96b2afd1abf0173930810dec0ae77538733d4", "content_id": "5609013a124139ec98a41d121b8d4e89f636788d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1418, "license_type": "no_license", "max_line_length": 123, "num_lines": 47, "path": "/train.py", "repo_name": "redshiftrobotics/2856-CoreClassifier", "src_encoding": "UTF-8", "text": "import turicreate as tc\nimport os\n\n# creates a model then saves it\ndef create_and_save():\n data = tc.SFrame('data.sframe') # load the image data and annotations from the sframe\n\n train_data, test_data = data.random_split(0.8) # split the data into training data and test data (80% goes to training)\n\n \"\"\"\n create an object detection model with the images and annotations\n if it does not learn within 3 epochs it will terminate early\n training the model takes ~30 minutes\n \"\"\"\n model = tc.object_detector.create(\n train_data, feature='image', annotations='annotations', max_iterations=200)\n\n \"\"\"\n make predictions using the test_data inorder to\n gather statistics about the model\n \"\"\"\n preds = model.predict(test_data)\n\n # general data about the model\n metrics = model.evaluate(test_data)\n print 'Accuracy: ', metrics['accuracy'] # model accuracy\n print metrics\n\n model.save('m.model') # save the created model\n\n return model\n\n# returns a previsouly created model\ndef load_saved():\n return tc.load_model('m.model')\n\n# look for a previsouly saved model\ndef model_exists():\n return os.path.exists('m.model')\n\n\nif model_exists(): # if we already have a model try loading that one\n model = load_saved()\nelse: # otherwise we need to train a new model\n model = create_and_save()\n\nmodel.export_coreml('model/m.mlmodel') # export the model to coreml\n" } ]
9
HuYuzhang/pyIntra
https://github.com/HuYuzhang/pyIntra
eb8a8b38291c3d775445a96404af2bf232ca116f
78b2e610f69edd7154459759ea0aa8a769fc2f74
015d48e9baaf2f4bb55a7641def66fe981754671
refs/heads/master
2020-04-07T02:40:20.267573
2019-01-25T13:59:03
2019-01-25T13:59:03
157,985,084
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.47600871324539185, "alphanum_fraction": 0.48885253071784973, "avg_line_length": 44.22191619873047, "blob_id": "4462cec31562546df0fe086e02ddb0aee8e52171", "content_id": "4e69755736c72962bf31e6adbfdc48446a30105e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16506, "license_type": "no_license", "max_line_length": 186, "num_lines": 365, "path": "/tf64/engine_tornado.py", "repo_name": "HuYuzhang/pyIntra", "src_encoding": "UTF-8", "text": "# Data augmented\nfrom __future__ import print_function\nimport tensorflow as tf\nimport cv2\nimport h5py\nimport numpy as np\nimport sys\nimport os\nimport subprocess as sp\nfrom skimage.measure import compare_ssim as ssim\nfrom skimage.measure import compare_psnr as psnr\nfrom mylib import test_quality\n\nbatch_size = 1024\nepochs = 1000\n\n\ndef tf_build_model(module_name, input_tensor, output_tensor, test=False, freq=False, params=None, _weights_name=None):\n with tf.variable_scope('main_full', reuse=tf.AUTO_REUSE):\n model_module = __import__(module_name)\n if test:\n satd_loss, freq_mse_loss, pixel_mse_loss, pred = model_module.build_model(\n input_tensor, output_tensor, params=params, freq=freq, test=test)\n return satd_loss, freq_mse_loss, pixel_mse_loss, pred\n else:\n train_op, satd_loss, freq_mse_loss, pixel_mse_loss, pred = model_module.build_model(\n input_tensor, output_tensor, params=params, freq=freq, test=test)\n return train_op, satd_loss, freq_mse_loss, pixel_mse_loss, pred\n\n\ndef drive():\n if len(sys.argv) < 8:\n # This is --help mode\n print(\n \"Usage: model_module_name train_mode scale block_size init_lr batch_size [weights_name]\")\n exit(0)\n print(sys.argv)\n model_module_name = sys.argv[2]\n train_mode = sys.argv[3]\n scale = int(sys.argv[4])\n block_size = int(sys.argv[5])\n init_lr = float(sys.argv[6])\n batch_size = int(sys.argv[7])\n weights_name = None\n if len(sys.argv) == 9:\n weights_name = sys.argv[8]\n print(weights_name)\n\n h5_path = '../../train' + str(scale) + '/' + train_mode + '.h5'\n # load data\n h5_path = sys.argv[8]\n hf = None\n\n hf = h5py.File(h5_path)\n\n print(\"Loading data\")\n x = np.array(hf['data'], dtype=np.float32)\n y = np.array(hf['label'], dtype=np.float32)\n\n length = x.shape[0]\n array_list = list(range(0, length))\n np.random.shuffle(array_list)\n bar = int(length*0.95)\n print('-------print the length of bar: %d, and length %d' % (bar, length))\n train_data = x[array_list[:bar], :, :]\n val_data = x[array_list[bar:], :, :]\n train_label = y[array_list[:bar], :, :]\n val_label = y[array_list[bar:], :, :]\n\n def train_generator():\n while True:\n for i in range(0, bar, batch_size)[:-1]:\n yield train_data[i:i+batch_size, :, :], train_label[i:i+batch_size, :, :]\n # np.random.shuffle(train_data)\n\n def val_generator():\n for i in range(0, length-bar, batch_size)[:-1]:\n yield val_data[i:i+batch_size, :, :], val_label[i:i+batch_size, :, :]\n\n inputs = tf.placeholder(\n tf.float32, [batch_size, block_size * scale, block_size * scale])\n targets = tf.placeholder(tf.float32, [batch_size, block_size, block_size])\n\n # build model\n train_op, satd_loss, freq_mse_loss, pixel_mse_loss, pred = tf_build_model(model_module_name,\n inputs,\n targets,\n test=False,\n freq=True,\n params={'learning_rate': init_lr,\n 'batch_size': batch_size,\n 'scale': scale,\n 'block_size': block_size\n },\n _weights_name=weights_name\n )\n\n tensorboard_train_dir = '../../tensorboard' + \\\n str(scale) + '/' + train_mode + '/train'\n tensorboard_valid_dir = '../../tensorboard' + \\\n str(scale) + '/' + train_mode + '/valid'\n checkpoint_dir = '../../model' + str(scale) + '/' + train_mode + '/'\n if not os.path.exists(tensorboard_train_dir):\n os.makedirs(tensorboard_train_dir)\n if not os.path.exists(tensorboard_valid_dir):\n os.makedirs(tensorboard_valid_dir)\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n\n saver = tf.train.Saver(max_to_keep=30)\n\n with tf.Session() as sess:\n if weights_name is not None:\n saver.restore(sess, weights_name)\n print('-----------Sucesfully restoring weights from: ', weights_name)\n else:\n sess.run(tf.global_variables_initializer())\n print('-----------No weights defined, run initializer')\n total_var = 0\n for var in tf.trainable_variables():\n shape = var.get_shape()\n par_num = 1\n for dim in shape:\n par_num *= dim.value\n total_var += par_num\n print(\"----------------Number of total variables: %d\" % (total_var))\n options = tf.RunOptions() # trace_level=tf.RunOptions.FULL_TRACE)\n run_metadata = tf.RunMetadata()\n data_gen = train_generator()\n interval = 500\n metrics = np.zeros((interval, 3))\n\n # --------------- part for tensorboard----------------\n train_writer = tf.summary.FileWriter(tensorboard_train_dir, sess.graph)\n valid_writer = tf.summary.FileWriter(tensorboard_valid_dir, sess.graph)\n train_satd_summary = tf.summary.scalar(\n train_mode + ' SATD loss', satd_loss)\n train_pixel_mse_summary = tf.summary.scalar(\n train_mode + ' pixel_MSE loss', pixel_mse_loss)\n train_freq_mse_summary = tf.summary.scalar(\n train_mode + ' freq_MSE loss', freq_mse_loss)\n merged = tf.summary.merge(\n [train_satd_summary, train_freq_mse_summary, train_pixel_mse_summary])\n\n # sub1--------------------------------here for valid mean\n valid_size = int(len(range(0, length - bar, batch_size)[:-1]))\n print(valid_size)\n valid_pixel_mse_input = tf.placeholder(tf.float32, [valid_size])\n valid_freq_mse_input = tf.placeholder(tf.float32, [valid_size])\n valid_satd_input = tf.placeholder(tf.float32, [valid_size])\n\n valid_pixel_mse_mean = tf.reduce_mean(valid_pixel_mse_input)\n valid_freq_mse_mean = tf.reduce_mean(valid_freq_mse_input)\n valid_satd_mean = tf.reduce_mean(valid_satd_input)\n\n valid_pixel_mse_summary = tf.summary.scalar(\n train_mode + ' pixel_MSE loss', valid_pixel_mse_mean)\n valid_freq_mse_summary = tf.summary.scalar(\n train_mode + ' freq_MSE loss', valid_freq_mse_mean)\n valid_satd_summary = tf.summary.scalar(\n train_mode + ' SATD loss', valid_satd_mean)\n\n valid_merged = tf.summary.merge(\n [valid_satd_summary, valid_pixel_mse_summary, valid_freq_mse_summary])\n # sub1--------------------------------for valid mean\n\n # --------------- part for tensorboard----------------\n\n for i in range(200000):\n if i % interval == 0:\n val_satd_s = []\n val_pixel_mse_s = []\n val_freq_mse_s = []\n val_gen = val_generator()\n psnr_s = []\n ssim_s = []\n for v_data, v_label in val_gen:\n val_satd, val_pixel_mse, val_freq_mse, recon = sess.run([satd_loss, pixel_mse_loss, freq_mse_loss, pred], feed_dict={\n inputs: v_data, targets: v_label})\n val_pixel_mse_s.append(float(val_pixel_mse))\n val_freq_mse_s.append(float(val_freq_mse))\n val_satd_s.append(float(val_satd))\n tmp_psnr, tmp_ssim = test_quality(v_label.reshape(\n [-1, block_size, block_size])[0] * 255.0, recon.reshape([-1, block_size, block_size])[0] * 255.0)\n psnr_s.append(tmp_psnr)\n ssim_s.append(tmp_ssim)\n # print('#########tmp: ', tmp_psnr, tmp_ssim)\n\n # Here is about the tensorboard\n rs = sess.run(valid_merged, feed_dict={\n valid_satd_input: val_satd_s, valid_freq_mse_input: val_freq_mse_s, valid_pixel_mse_input: val_pixel_mse_s\n })\n valid_writer.add_summary(rs, i)\n # Here is about the tensorboard\n\n # now test for psnr\n print('------------->now show the info of PSNR and SSIM')\n print('PSNR is: %f, SSIM is: %f' %\n (np.mean(psnr_s), np.mean(ssim_s)))\n\n # print(val_satd_s)\n print(\"Model name: %s, step %8d, Train SATD %.4f, Train pixel MSE %.4f, Train freq MSE %.4f, Val SATD %.4f, Val freq_MSE %.6f, Val pixel_MSE %.6f\" % (\n model_module_name, i, np.mean(metrics[:, 0]), np.mean(metrics[:, 1]), np.mean(metrics[:, 2]), np.mean(val_satd_s), np.mean(val_freq_mse_s), np.mean(val_pixel_mse_s)))\n\n # ------------------- Here is the training part ---------------\n iter_data, iter_label = next(data_gen)\n # print(iter_data.shape)\n feed_dict = {inputs: iter_data, targets: iter_label}\n _, satd, pixel_mse, freq_mse, rs = sess.run([train_op, satd_loss, pixel_mse_loss, freq_mse_loss, merged],\n feed_dict=feed_dict,\n options=options,\n run_metadata=run_metadata)\n if i % interval == 0:\n train_writer.add_summary(rs, i)\n\n metrics[i % interval, 0] = satd\n metrics[i % interval, 1] = pixel_mse\n metrics[i % interval, 2] = freq_mse\n\n if i % 10000 == 0:\n save_path = saver.save(sess, os.path.join(\n checkpoint_dir, \"%s_%06d.ckpt\" % (model_module_name, i)))\n\n\ndef run_test():\n if len(sys.argv) == 2:\n # This is --help mode\n print(\n \"Usage: model_module_name train_mode scale block_size init_lr batch_size [weights_name]\")\n print(sys.argv)\n block_size = 8\n model_module_name = sys.argv[2]\n train_mode = sys.argv[3]\n scale = int(sys.argv[4])\n block_size = int(sys.argv[5])\n batch_size = int(sys.argv[6])\n weights_name = sys.argv[7]\n\n inputs = tf.placeholder(\n tf.float32, [batch_size, block_size * scale, block_size * scale])\n targets = tf.placeholder(tf.float32, [batch_size, block_size, block_size])\n\n h5_path = '../../train' + str(scale) + '/' + train_mode + '.h5'\n\n hf = None\n\n hf = h5py.File(h5_path)\n\n print(\"Loading data\")\n x = np.array(hf['data'], dtype=np.float32)\n y = np.array(hf['label'], dtype=np.float32)\n\n length = x.shape[0]\n print(\"Finishing loading data and begin to build network from: \", model_module_name)\n satd_loss, freq_mse_loss, pixel_mse_loss, pred = tf_build_model(model_module_name,\n inputs,\n targets,\n test=True,\n freq=True,\n params={'learning_rate': 0,\n 'batch_size': batch_size,\n 'scale': scale,\n 'block_size': block_size\n },\n _weights_name=weights_name\n )\n print('finish build network')\n\n def val_generator():\n for i in range(0, length, batch_size)[:-1]:\n yield x[i:i+batch_size, :, :], y[i:i+batch_size, :, :]\n\n saver = tf.train.Saver()\n\n with tf.Session() as sess:\n if weights_name is None:\n print('error!, no weights_name')\n exit(0)\n else:\n saver.restore(sess, weights_name)\n print('Successfully restore weights from file: ', weights_name)\n # Fore debug\n #import IPython\n # IPython.embed()\n # For debug\n val_satd_s = []\n val_pixel_mse_s = []\n val_freq_mse_s = []\n val_gen = val_generator()\n psnr_s = []\n ssim_s = []\n val_cnt = 0\n for v_data, v_label in val_gen:\n val_satd, val_pixel_mse, val_freq_mse, recon = sess.run([satd_loss, pixel_mse_loss, freq_mse_loss, pred], feed_dict={\n inputs: v_data, targets: v_label})\n val_pixel_mse_s.append(float(val_pixel_mse))\n val_freq_mse_s.append(float(val_freq_mse))\n val_satd_s.append(float(val_mse))\n val_psnr, val_ssim = test_quality(v_label.reshape(\n [-1, block_size, block_size])[0] * 255.0, recon.reshape([-1, block_size, block_size])[0] * 255.0)\n psnr_s.append(tmp_psnr)\n ssim_s.append(tmp_ssim)\n val_cnt = val_cnt + batch_size\n print('-----------> tmp data, now %d sample tested, %d in total, psnr: %f, ssim: %f, pixel mse loss: %f, freq mse loss: %f, satd_loss: %f<------------' %\n (val_cnt, length, val_psnr, val_ssim, val_pixel_mse, val_freq_mse, val_satd))\n print('Finish testing, now psnr is: %f, and ssim is: %f, pixel mse loss: %f, freq mse loss: %f, satd_loss: %f' %\n (np.mean(psnr_s), np.mean(ssim_s), np.mean(val_pixel_mse_s), np.mean(val_freq_mse_s), np.mean(val_satd_s)))\n\n\n # for v_data, v_label in val_gen:\n # val_satd, val_mse, recon = sess.run([satd_loss, mse_loss, pred], feed_dict={\n # inputs: v_data, targets: v_label})\n # val_cnt = val_cnt + batch_size\n # recon = recon.reshape([-1, 32, 32]) * 255.0\n # gt = v_label.reshape([-1, 32, 32]) * 255.0\n # val_psnr, val_ssim = test_quality(gt, recon)\n\n # print('-----------> tmp data, now %d sample tested, %d in total, psnr: %f, ssim: %f, mse loss: %f, satd_loss: %f<------------' %\n # (val_cnt, length, val_psnr, val_ssim, np.mean(val_mse), np.mean(val_satd)))\n # psnr_s.append(val_psnr)\n # ssim_s.append(val_ssim)\n # print('Finish testing, now psnr is: %f, and ssim is: %f' %\n # (np.mean(psnr_s), np.mean(ssim_s)))\n\n\ndef dump_img(filename, targetpath):\n pass\n # model_module_name = sys.argv[2]\n # weights_name = sys.argv[3]\n # filename = sys.argv[4]\n # print(weights_name, model_module_name, filename)\n\n # img = skimage.imread(filename) / 255.0\n # input, gt = img2input(filename)\n\n # inputs = tf.placeholder(tf.float32, [1, 3072, 1, 1])\n # targets = tf.placeholder(tf.float32, [1, 1024, 1, 1])\n # satd_loss, mse_loss, pred = tf_build_model(model_module_name,\n # inputs,\n # targets,\n # test=True,\n # freq=False,\n # _weights_name=weights_name\n # )\n\n # saver = tf.train.Saver()\n\n # with tf.Session() as sess:\n # if weights_name is None:\n # print('error!, no weights_name')\n # exit(0)\n # else:\n # saver.restore(sess, weights_name)\n # print('Successfully restore weights from file: ', weights_name)\n\n # recon = sess.run(pred, feed_dict={inputs: input.reshape(1,3072,1,1), targets: gt.reshape(1,1024,1,1)})\n # img[32:,32:] = recon.reshape([32,32]) * 255.0\n # skimage.imwrite(targetpath, img)\n\n\nif __name__ == '__main__':\n tasks = {'train': drive, 'test': run_test, 'dump': dump_img}\n task = sys.argv[1]\n print('-------------begin task', task)\n tasks[task]()\n" }, { "alpha_fraction": 0.5691443681716919, "alphanum_fraction": 0.5799481272697449, "avg_line_length": 35.15625, "blob_id": "10d90ad80eb1c2a14763453a790450bc12b20d40", "content_id": "6c89af4c39e9e871ded00ca12da277570aac6285", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2314, "license_type": "no_license", "max_line_length": 116, "num_lines": 64, "path": "/DHM/build_graph.py", "repo_name": "HuYuzhang/pyIntra", "src_encoding": "UTF-8", "text": "# Data augmented\nfrom __future__ import print_function\nimport tensorflow as tf\nimport cv2\nimport h5py\nimport numpy as np\nimport sys\nimport os\nimport subprocess as sp\nfrom tensorflow.python.framework.graph_util import convert_variables_to_constants\n\nbatch_size = 1 \nepochs = 1000\n\n\ndef tf_build_model(module_name, weights_name, params, input_tensor, target_tensor):\n with tf.variable_scope('main_full', reuse=tf.AUTO_REUSE):\n model_module = __import__(module_name)\n satd_loss, mse_loss, recon = model_module.build_model(input_tensor, target_tensor, params=params, test=True)\n # model_module.build_model(\n # input_tensor, output_tensor, params, mode=mode)\n return satd_loss, mse_loss, recon\n\n\ndef drive():\n model_module_name = sys.argv[2]\n block_size = int(sys.argv[3])\n scale = int(sys.argv[4])\n weights_name = sys.argv[5]\n \n\n inputs = tf.placeholder(tf.float32, [batch_size, block_size*scale, block_size*scale, 1])\n targets = tf.placeholder(tf.float32, [batch_size, block_size, block_size, 1])\n\n # build model\n satd_loss, mse_loss, recon = tf_build_model(model_module_name,\n weights_name,\n {'learning_rate': 0.0001,\n 'batch_size': batch_size,\n 'block_size': block_size,\n 'scale':scale},\n inputs,\n targets)\n # tensorboard_dir = 'tensorboard'\n # if not os.path.exists(tensorboard_dir):\n # os.makedirs(tensorboard_dir)\n\n # writer = tf.summary.FileWriter(tensorboard_dir)\n saver = tf.train.Saver()\n # checkpoint_dir = './ckpt/'\n with tf.Session() as sess:\n saver.restore(sess, weights_name)\n # import IPython\n # IPython.embed()\n graph = convert_variables_to_constants(sess, sess.graph_def, ['main_full/4_dim_out_pixel'])\n #graph = convert_variables_to_constants(sess, sess.graph_def, ['main_full/Reshape_1'])\n tf.train.write_graph(graph,'../../pb','graph_m%d_s%d.pb' % (scale, block_size),as_text=False)\n\n\n\nif __name__ == '__main__':\n tasks = {'train': drive}\n task = sys.argv[1]\n tasks[task]()\n" }, { "alpha_fraction": 0.5928338766098022, "alphanum_fraction": 0.6775244474411011, "avg_line_length": 21, "blob_id": "f8ece680c30005a186cb570df2a54dd32ff85506", "content_id": "a191c68cb8b0f4b26af1f4857865377064dcec8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 307, "license_type": "no_license", "max_line_length": 46, "num_lines": 14, "path": "/DHM/test_predict.py", "repo_name": "HuYuzhang/pyIntra", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\nimport sys\nimport h5py\nimport cv2\nfrom mylib import test_quality\n\n\nfc = cv2.imread('pred_fc1.png', -1)\nrnn = cv2.imread('pred_fc2.png', -1)\ngt = cv2.imread('gt.png', -1)\n\nprint(test_quality(fc[16:,16:], gt[16:,16:]))\nprint(test_quality(rnn[16:,16:], gt[16:,16:]))" }, { "alpha_fraction": 0.43142858147621155, "alphanum_fraction": 0.4431168735027313, "avg_line_length": 43.252872467041016, "blob_id": "0f75af73e0c7135aa6e62cdd4809c5d3fc1fe0d3", "content_id": "6307bee17588c05aa4f410f4475134acc2fdb3f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3850, "license_type": "no_license", "max_line_length": 106, "num_lines": 87, "path": "/DHM/filter.py", "repo_name": "HuYuzhang/pyIntra", "src_encoding": "UTF-8", "text": "import h5py\nimport sys\nimport numpy as np\nimport tensorflow as tf\nfrom mylib import h5Handler\ndef tf_build_model(module_name, input_tensor, output_tensor, test=False, params=None, _weights_name=None):\n with tf.variable_scope('main_full', reuse=tf.AUTO_REUSE):\n model_module = __import__(module_name)\n if test:\n satd_loss, mse_loss, pred = model_module.build_model(\n input_tensor, output_tensor, params=params, test=test)\n return satd_loss, mse_loss, pred\n else:\n train_op, satd_loss, mse_loss, pred = model_module.build_model(\n input_tensor, output_tensor, params=params, test=test)\n return train_op, satd_loss, mse_loss, pred\n\nif __name__ == '__main__':\n h5_name = sys.argv[1]\n model_module_name = sys.argv[2]\n block_size = int(sys.argv[3])\n scale = int(sys.argv[4])\n\n weights_name = sys.argv[5]\n thres = float(sys.argv[6])\n\n\n f = h5py.File(h5_name, 'r')\n batch_size = 1\n\n x = np.array(f['data'], dtype=np.float32)\n y = np.array(f['label'], dtype=np.float32)\n length = x.shape[0]\n print(\"The total length is : %d\"%(length))\n inputs = tf.placeholder(\n tf.float32, [batch_size, block_size * scale, block_size * scale])\n targets = tf.placeholder(tf.float32, [batch_size, block_size, block_size])\n\n ##################### Cache Part ##########################\n filter_h5_name = \"filter_\" + h5_name\n cache_size = 2000\n input_cache = np.zeros([cache_size, block_size * scale, block_size * scale])\n label_cache = np.zeros([cache_size, block_size, block_size])\n cache_cnt = 0\n fid = 0\n h5er = h5Handler(filter_h5_name)\n ##################### Cache Part ##########################\n\n satd_loss, mse_loss, pred = tf_build_model(model_module_name,\n inputs,\n targets,\n test=True,\n params={'learning_rate': 0,\n 'batch_size': batch_size,\n 'scale': scale,\n 'block_size': block_size\n },\n _weights_name=weights_name\n )\n print('finish build network')\n\n saver = tf.train.Saver()\n with tf.Session() as sess:\n if weights_name is None:\n print('error!, no weights_name')\n exit(0)\n else:\n saver.restore(sess, weights_name)\n print('Successfully restore weights from file: ', weights_name)\n\n for i in range(100):\n #for i in range(length):\n val_satd, val_mse, recon = sess.run([satd_loss, mse_loss, pred], feed_dict={\n inputs: x[i:i+1,:,:], targets: y[i:i+1,:,:]})\n print(\"Print loss in sampe i: %d, loss is %d\", val_mse)\n if val_mse > thres:\n input_cache[cache_cnt,:,:] = x[i,:,:]\n label_cache[cache_cnt,:,:] = y[i,:,:]\n cache_cnt = cache_cnt + 1\n\n if cache_cnt >= cache_size:\n if fid == 0: # create mode\n h5er.write(input_cache, label_cache, create=True)\n fid = 1\n else:\n h5er.write(input_cache, label_cache, create=False)\n cache_cnt = 0\n" }, { "alpha_fraction": 0.35069161653518677, "alphanum_fraction": 0.4609438478946686, "avg_line_length": 35.6716423034668, "blob_id": "477dd527d5ba320269433039629e4e39cd4579aa", "content_id": "2d314c55045ffba448ffb468af4508fc004276ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3494, "license_type": "no_license", "max_line_length": 74, "num_lines": 67, "path": "/README.md", "repo_name": "HuYuzhang/pyIntra", "src_encoding": "UTF-8", "text": "# pyIntra\nIntra analyze with python\n\n## h5.py\n* 用于对hdf5文件进行分析,目前反正只有读取hdf5文件的功能,但是h5py确实用起来很方便(\n\n## apply_mode.py\n* 根据训练得到的模型生成预测图像,将它和原图共同保存下来\n---\n# 其他\n### 11.17\n* 之前得到的预测图像非常奇怪,觉得可能是reshape出了问题,检查了很久,发现是被MATLAB坑到了。MATLAB是\n列优先的,所以reshape会出现问题,必须在这里进行reshape的时候指定order='F'保证列优先。\n* 另外发现了很多非常没有意义的图片,整张图片几乎都是没有任何变化的。所以之后应该要考虑对于方差小于或者\n大于阈值的数据进行过滤(太复杂可能也学不出来?)\n### 11.18\n* 今天加入了预测结果的PSNR和SSIM测试代码,想要检查一下分模式训练是否真的是有效果的,目前每个模式只测试了1000个输入,结果如下,\n暂时就只放PSNR的结果好了(\n#### 以200为方差阈值过滤掉无效输入的结果\n\n| data_type\\model_type |dc | planar | angle |\n| ------------- |:-------------:| -----: | -----: |\n| dc | 19.439 | 19.477 | 19.363 |\n|planar | 19.781 | 19.725 | 19.663 |\n|angle | 19.652 | 19.630 | 19.508 |\n\n#### 不考虑方差统一测试的结果\n| data_type\\model_type |dc | planar | angle |\n| ------------- |:-------------:| -----: | -----: |\n| dc | 21.258 | 21.025 | 20.623 |\n|planar | 24.850 | 24.111 | 23.705 |\n|angle | 21.445 | 21.163 | 20.778 |\n\n* 结果让人很无语,因为基本上每个数据的最佳表现并不总是(甚至很少是)在专门针对于这个模式下进行训练所得到的模型啊摔\n* 于是打算要进行一下过滤,将方差太小的块直接扔掉,因为visualize之后看到很多的几乎纯色图,应该没什么用处\n---\n#### 接下来统计了一下每一个图片的方差,为了之后过滤数据做准备,这里稍微记录一下每一种预测模式的方差情况\n| dc | planar | angle |\n| ------------- |:-------------:| -----: |\n|971.519 | 794.746 | 1074.991 |\n* emmm看来方差还是比较大的,但是除了下界之外是否也需要设置一个上界呢?\n\n## 频域训练对比(12.2)\n![Image text](analyze/freq/dc.png)\n![Image text](analyze/freq/angle.png)\n![Image text](analyze/freq/planar.png)\n\n\n## 5PU下的预测结果统计12.8\n### 频域预测\n|Type | dc | planar | angle |\n| ------------- | ------------- |-------------| ----------- |\n|PSNR |26.446408 | 24.559245 | 24.974869 |\n|SSIM |0.607805 | 0.564917 | 0.617820 |\n\n### 像素域预测\n|Type | dc | planar | angle |\n| ------------- | ------------- |-------------| ----------- |\n|PSNR |26.597131 | 24.023404 | 24.835910 |\n|SSIM |0.616713 | 0.574280 | 0.618581 |\n\n## 3PU结果补录\n### 频域预测\n|Type | dc | planar | angle |\n| ------------- | ------------- |-------------| ----------- |\n|PSNR |26.691607 | 24.605719 | 24.997058 |\n|SSIM |0.613047 | 0.567298 | 0.621948 |\n\n" }, { "alpha_fraction": 0.40916335582733154, "alphanum_fraction": 0.5398406386375427, "avg_line_length": 52.425533294677734, "blob_id": "e89120ff40a65b42c28fbed7a37c71692aabf1a7", "content_id": "2a8e365fcbc89fa0efef494f057708143435e3fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2510, "license_type": "no_license", "max_line_length": 131, "num_lines": 47, "path": "/tailor/libtailor.py", "repo_name": "HuYuzhang/pyIntra", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\n\n# Assume that our video is I420\ndef read_frame(filename, idx, _height, _width, mode=0):\n pixel_num = _height * _width\n byte_num = int(pixel_num * 3 / 2)\n # print(byte_num)\n with open(filename, 'rb') as f:\n f.seek(idx * byte_num, 0)\n # only luma mode\n if mode == 0:\n Y = np.fromfile(f, dtype=np.uint8, count=pixel_num)\n U = np.fromfile(f, dtype=np.uint8, count=pixel_num >> 2)\n V = np.fromfile(f, dtype=np.uint8, count=pixel_num >> 2)\n return Y.reshape([_height, _width]), U.reshape([_height >> 1, _width >> 1]), V.reshape([_height >> 1, _width >> 1])\n\n else:\n # Three color mode\n dataY = np.fromfile(f, dtype=np.uint8, count=pixel_num)\n dataU = np.fromfile(f, dtype=np.uint8, count=int(pixel_num / 4))\n dataV = np.fromfile(f, dtype=np.uint8, count=int(pixel_num / 4))\n img = np.zeros([3, _height, _width])\n img[0,:,:] = dataY.reshape([_height, _width])\n img[1,0::2,0::2] = dataU.reshape([int(_height / 2), int(_width / 2)])\n img[1,0::2,1::2] = img[1,0::2,0::2]\n img[1,1::2,0::2] = img[1,0::2,0::2]\n img[1,1::2,1::2] = img[1,0::2,0::2]\n img[2,0::2,0::2] = dataV.reshape([int(_height / 2), int(_width / 2)])\n img[2,0::2,1::2] = img[2,0::2,0::2]\n img[2,1::2,0::2] = img[2,0::2,0::2]\n img[2,1::2,1::2] = img[2,0::2,0::2]\n img = img.astype(np.uint8)\n img = img.transpose(1,2,0)\n print(img.dtype)\n print('---', img.shape)\n img = cv2.cvtColor(img, cv2.COLOR_YUV2BGR)\n return img\n\ndef write_frame(filename, idx, height, width, Y, U, V, mode=0):\n with open(filename, 'ab') as f:\n Y = Y.reshape([-1]).astype(np.uint8)\n U = U.reshape([-1]).astype(np.uint8)\n V = V.reshape([-1]).astype(np.uint8)\n f.write(Y.tobytes())\n f.write(U.tobytes())\n f.write(V.tobytes())" }, { "alpha_fraction": 0.3967181444168091, "alphanum_fraction": 0.5588803291320801, "avg_line_length": 56.58333206176758, "blob_id": "93d00bfec76e9c402d8710a297142c5a554e1034", "content_id": "ec44a0531cd61be1bb8ea622cbf6341a071d7fff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2072, "license_type": "no_license", "max_line_length": 121, "num_lines": 36, "path": "/preProcess/mylib.py", "repo_name": "HuYuzhang/pyIntra", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\n\n# Assume that our video is I420\ndef read_frame(filename, idx, _height, _width, mode=0):\n pixel_num = _height * _width\n byte_num = int(pixel_num * 3 / 2)\n # print(byte_num)\n with open(filename, 'rb') as f:\n f.seek(idx * byte_num, 0)\n # only luma mode\n if mode == 0:\n data = np.fromfile(f, dtype=np.uint8, count=pixel_num)\n return data.reshape([_height, _width])\n\n else:\n # Three color mode\n dataY = np.fromfile(f, dtype=np.uint8, count=pixel_num)\n dataU = np.fromfile(f, dtype=np.uint8, count=int(pixel_num / 4))\n dataV = np.fromfile(f, dtype=np.uint8, count=int(pixel_num / 4))\n img = np.zeros([3, _height, _width])\n img[0,:,:] = dataY.reshape([_height, _width])\n img[1,0::2,0::2] = dataU.reshape([int(_height / 2), int(_width / 2)])\n img[1,0::2,1::2] = img[1,0::2,0::2]\n img[1,1::2,0::2] = img[1,0::2,0::2]\n img[1,1::2,1::2] = img[1,0::2,0::2]\n img[2,0::2,0::2] = dataV.reshape([int(_height / 2), int(_width / 2)])\n img[2,0::2,1::2] = img[2,0::2,0::2]\n img[2,1::2,0::2] = img[2,0::2,0::2]\n img[2,1::2,1::2] = img[2,0::2,0::2]\n img = img.astype(np.uint8)\n img = img.transpose(1,2,0)\n print(img.dtype)\n print('---', img.shape)\n img = cv2.cvtColor(img, cv2.COLOR_YUV2BGR)\n return img" }, { "alpha_fraction": 0.518006443977356, "alphanum_fraction": 0.5363343954086304, "avg_line_length": 34.58620834350586, "blob_id": "a62eae52394d62636a5a2b1ebfb01ed54a08de2e", "content_id": "37567cecc66543a6ccf3a498d3076aab74cba50d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3110, "license_type": "no_license", "max_line_length": 122, "num_lines": 87, "path": "/DHM/predict.py", "repo_name": "HuYuzhang/pyIntra", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\nimport sys\nimport h5py\nimport cv2\nfrom mylib import read_frame\n\ncu_size = int(sys.argv[1])\nscale = int(sys.argv[2])\nf_cnt = int(sys.argv[3])\ndec_name = sys.argv[4]\ngt_name = sys.argv[5]\nheight = int(sys.argv[6])\nwidth = int(sys.argv[7])\n\ncu_pixel = cu_size * cu_size\ninput_cache = np.zeros([1, cu_size * scale, cu_size * scale])\nlabel_cache = np.zeros([1, cu_size, cu_size])\ninput_size = cu_pixel * (2 * scale - 1)\nmask_mean = True\n\nresult = np.zeros([height, width])\nrnn_flag = False\nhfc = False\nprint(input_cache.shape)\nwith tf.Graph().as_default():\n output_graph_def = tf.GraphDef()\n if rnn_flag:\n with open(\"graph_m2_s8_rev7.pb\", \"rb\") as f:\n output_graph_def.ParseFromString(f.read())\n _ = tf.import_graph_def(output_graph_def, name=\"\")\n else:\n if hfc:\n with open(\"graph_m2_s8_FC.pb\", \"rb\") as f:\n output_graph_def.ParseFromString(f.read())\n _ = tf.import_graph_def(output_graph_def, name=\"\") \n else:\n with open(\"graph_m2_s8.pb\", \"rb\") as f:\n output_graph_def.ParseFromString(f.read())\n _ = tf.import_graph_def(output_graph_def, name=\"\")\n\n with tf.Session() as sess:\n init = tf.global_variables_initializer()\n sess.run(init)\n s = str(sess.graph_def)\n with open('graph.log', 'w') as f:\n f.write(s)\n f.close()\n input_x = sess.graph.get_tensor_by_name(\"Placeholder:0\")\n if rnn_flag:\n pred = sess.graph.get_tensor_by_name(\"main_full/conv11/BiasAdd:0\")\n else:\n if hfc:\n pred = sess.graph.get_tensor_by_name(\"main_full/Reshape_1:0\")\n else:\n pred = sess.graph.get_tensor_by_name(\"main_full/4_dim_out_pixel:0\")\n\n \n \n Y = read_frame(dec_name, 0, height, width)\n YY = read_frame(gt_name, 0, height, width)\n for lx in range(0,width,cu_size):\n for ly in range(0,height,cu_size):\n rx = lx + cu_size * scale\n ry = ly + cu_size * scale\n if rx >= width or ry >= height:\n continue\n input_cache[0, :, :] = Y[ly:ly+cu_size * scale, lx:lx+cu_size*scale] / 255.0\n\n if mask_mean:\n input_cache[0, cu_size:, cu_size:] = 0\n mean = np.sum(input_cache[0, :, :]) / float(input_size)\n input_cache[0, cu_size:, cu_size:] = mean\n else:\n input_cache[0, cu_size:, cu_size:] = 0\n\n recon = sess.run(pred, feed_dict={input_x: input_cache.reshape([1, cu_size * scale, cu_size * scale, 1])})\n recon = np.clip(recon, 0, 1).reshape([cu_size, cu_size]) * 255.0\n result[ly+cu_size:ly+cu_size*2, lx+cu_size:lx+cu_size*2] = recon\n result = result.astype(np.uint8)\nif rnn_flag:\n cv2.imwrite('pred_rnn.png', result)\nelse:\n if hfc:\n cv2.imwrite('pred_hfc.png', result)\n else:\n cv2.imwrite('pred_myfc.png', result)\n \n\n" }, { "alpha_fraction": 0.4513888955116272, "alphanum_fraction": 0.5138888955116272, "avg_line_length": 15.11111068725586, "blob_id": "dc041922534b562324a902f14a450d432939829d", "content_id": "830050b74e1982fee529b9cf14c92cf73332ff96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 144, "license_type": "no_license", "max_line_length": 33, "num_lines": 9, "path": "/tf/test.py", "repo_name": "HuYuzhang/pyIntra", "src_encoding": "UTF-8", "text": "import numpy as np\na = 10\n\nprint('------%d---'%(a))\n\na = np.arange(8).reshape([2,2,2])\nprint(a)\nprint('-------------')\nprint(a.transpose(1,2,0))" }, { "alpha_fraction": 0.4525688886642456, "alphanum_fraction": 0.5202880501747131, "avg_line_length": 36.609375, "blob_id": "9c0874164b939409f36a71556fd230f7b75e05c0", "content_id": "27e9e9db0190cf6b00532126728cbe41f2b28f42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7221, "license_type": "no_license", "max_line_length": 142, "num_lines": 192, "path": "/DHM/model_comp_fc.py", "repo_name": "HuYuzhang/pyIntra", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\n# refined srnn based on rev5 lite\n# try shrink the network\n\ndef stacked_RNN(input_tensor, num, scope, units, batch_size, num_scale):\n with tf.variable_scope(scope):\n cells = [tf.contrib.rnn.GRUCell(num_units=units,name='cell_%d'% (i) )for i in range(num)]\n states = [it.zero_state(batch_size, dtype=tf.float32) for i,it in enumerate(cells)]\n last = input_tensor\n for i in range(num):\n last, _ = tf.nn.static_rnn(cells[i], last, initial_state=states[i], sequence_length=[num_scale,]*batch_size, scope='rnn_%d' % (i))\n return last\n\ndef inter_rnn(input_tensor, num, scope, batch_size, channels=8, units=8):\n with tf.variable_scope(scope):\n # split input tensor to lines\n shaped_conv1 = tf.reshape(input_tensor, [batch_size, num, num, channels], name=\"conv1\")\n\n vertical_form = tf.reshape(shaped_conv1, [batch_size, num, num*channels], name='vertical_form')\n horizontal_form1 = tf.transpose(shaped_conv1, [0, 2, 1, 3], name='horizontal_form1')\n horizontal_form =tf.reshape(horizontal_form1, [batch_size, num, num*channels], name='horizontal_form')\n\n vertical_split = tf.unstack(\n vertical_form,\n num=num,\n axis=1,\n name=\"vertical_split\"\n )\n\n horizontal_split = tf.unstack(\n horizontal_form,\n num=num,\n axis=1,\n name=\"horizontal_split\"\n )\n\n vr4 = stacked_RNN(vertical_split, 1, 'vrnn', num*channels, batch_size, num)\n hr4 = stacked_RNN(horizontal_split, 1, 'hrnn', num*channels, batch_size, num)\n\n stack_h_ = tf.stack(hr4, axis=1, name='from_h')\n\n stack_v_ = tf.stack(vr4, axis=1, name='from_v')\n\n _stack_h = tf.reshape(stack_h_, [batch_size, num, num, channels], name='stack_shape_h')\n stack_v = tf.reshape(stack_v_, [batch_size, num, num, channels], name='stack_shape_v')\n\n stack_h = tf.transpose(_stack_h, [0,2,1,3], name='h_stack_back')\n\n concat2 = tf.concat([stack_v, stack_h], axis=3)\n\n _connect = tf.layers.conv2d(\n inputs=concat2,\n filters=units,\n kernel_size=[1, 1],\n strides=[1,1],\n padding=\"VALID\",\n name=\"connect\"\n )\n\n connect = tf.keras.layers.PReLU(shared_axes=[1,2], name='relu_con')(_connect)\n\n\n return connect\n\n\n\ndef build_model(input_tensor, target_tensor, params=None, test=False):\n if params is not None:\n batch_size = params['batch_size']\n lr = params['learning_rate']\n block_size = params['block_size']\n scale = params['scale']\n else:\n batch_size = input_tensor.shape[0]\n lr = 0.0001\n scale = 2\n block_size = 32\n\n input_layer = tf.reshape(input_tensor, [-1, block_size*scale * block_size*scale])\n target_tensor = tf.reshape(target_tensor, (-1, block_size, block_size, 1))\n\n _fc1 = tf.layers.dense(input_layer, 1024, name='fc1')\n\n fc1 = tf.keras.layers.PReLU(shared_axes=[1], name='relu1')(_fc1)\n\n _fc2 = tf.layers.dense(fc1, 1024, name='fc2')\n\n fc2 = tf.keras.layers.PReLU(shared_axes=[1], name='relu2')(_fc2)\n\n _fc3 = tf.layers.dense(fc2, 1024, name='fc3')\n\n fc3 = tf.keras.layers.PReLU(shared_axes=[1], name='relu3')(_fc3)\n\n _fc4 = tf.layers.dense(fc3, 1024, name='fc4')\n\n fc4 = tf.keras.layers.PReLU(shared_axes=[1], name='relu4')(_fc4)\n\n _fc5 = tf.layers.dense(fc4, 1024, name='fc5')\n\n fc5 = tf.keras.layers.PReLU(shared_axes=[1], name='relu5')(_fc5)\n\n _fc6 = tf.layers.dense(fc5, 1024, name='fc6')\n\n fc6 = tf.keras.layers.PReLU(shared_axes=[1], name='relu6')(_fc6)\n\n _fc7 = tf.layers.dense(fc6, 1024, name='fc7')\n\n fc7 = tf.keras.layers.PReLU(shared_axes=[1], name='relu7')(_fc7)\n\n _fc8 = tf.layers.dense(fc7, 1024, name='fc8')\n\n fc8 = tf.keras.layers.PReLU(shared_axes=[1], name='relu8')(_fc8)\n\n fco = tf.layers.dense(fc8, block_size*block_size, name='fco')\n \n conv11 = tf.reshape(fco, (-1,block_size,block_size,1), name=\"4_dim_out_pixel\")\n\n # def SATD(y_true, y_pred):\n # H_8x8 = np.array(\n # [[1., 1., 1., 1., 1., 1., 1., 1.],\n # [1., -1., 1., -1., 1., -1., 1., -1.],\n # [1., 1., -1., -1., 1., 1., -1., -1.],\n # [1., -1., -1., 1., 1., -1., -1., 1.],\n # [1., 1., 1., 1., -1., -1., -1., -1.],\n # [1., -1., 1., -1., -1., 1., -1., 1.],\n # [1., 1., -1., -1., -1., -1., 1., 1.],\n # [1., -1., -1., 1., -1., 1., 1., -1.]],\n # dtype=np.float32\n # )\n # H_target = np.zeros((1, 32, 32), dtype=np.float32)\n # H_target[0, 0:8, 8:16] = H_8x8\n # H_target[0, 8:16, 0:8] = H_8x8\n # H_target[0, 8:16, 8:16] = H_8x8\n\n # H_target[0, 16:32, 0:16] = H_target[:, 0:16, 0:16]\n # H_target[0, 0:16, 16:32] = H_target[:, 0:16, 0:16]\n # H_target[0, 16:32, 16:32] = H_target[:, 0:16, 0:16]\n\n # TH0 = tf.constant(H_8x8.reshape([1,8,8]))\n\n # TH1 = tf.tile(TH0, (input_tensor.shape[0], 1, 1))\n\n # diff = tf.reshape(y_true - y_pred, (-1, 8, 8))\n # # print('*************', diff.shape, TH1.shape, block_size)\n # return tf.reduce_mean(tf.sqrt(tf.square(tf.matmul(tf.matmul(TH1, diff), TH1)) + 0.0001))\n def SATD(y_true, y_pred, scale):\n H_8x8 = np.array(\n [[1., 1., 1., 1., 1., 1., 1., 1.],\n [1., -1., 1., -1., 1., -1., 1., -1.],\n [1., 1., -1., -1., 1., 1., -1., -1.],\n [1., -1., -1., 1., 1., -1., -1., 1.],\n [1., 1., 1., 1., -1., -1., -1., -1.],\n [1., -1., 1., -1., -1., 1., -1., 1.],\n [1., 1., -1., -1., -1., -1., 1., 1.],\n [1., -1., -1., 1., -1., 1., 1., -1.]],\n dtype=np.float32\n )\n H_target = np.zeros((1, 32,32), dtype=np.float32)\n H_target[0, 0:8,0:8] = H_8x8\n\n H_target[0, 0:8,8:16] = H_8x8\n H_target[0, 8:16,0:8] = H_8x8\n H_target[0, 8:16,8:16] = -H_8x8\n\n H_target[0, 16:32, 0:16] = H_target[0, 0:16, 0:16]\n H_target[0, 0:16, 16:32] = H_target[0, 0:16, 0:16]\n H_target[0, 16:32, 16:32] = -H_target[0, 0:16, 0:16]\n\n TH0 = tf.constant(H_target[:, 0:scale, 0:scale])\n\n TH1 = tf.tile(TH0, (batch_size, 1, 1))\n\n diff = tf.reshape(y_true - y_pred, (-1, scale, scale))\n\n return tf.reduce_mean(tf.square(tf.matmul(tf.matmul(TH1, diff), TH1)))\n\n mse_loss = tf.reduce_mean(tf.square((target_tensor-conv11)))\n satd_loss = SATD(target_tensor, conv11, block_size)\n loss = satd_loss\n # loss = mse_loss\n\n if test:\n return satd_loss, mse_loss, conv11\n\n # global_step = tf.Variable(0, trainable=False)\n # learning_rate = tf.train.exponential_decay(params['learning_rate'], global_step=global_step, decay_steps = 10000, decay_rate=0.7)\n optimizer = tf.train.AdamOptimizer(learning_rate=lr)\n train_op = optimizer.minimize(loss=loss, global_step=tf.train.get_global_step())\n\n\n return train_op, satd_loss, mse_loss, conv11\n" }, { "alpha_fraction": 0.5660015344619751, "alphanum_fraction": 0.5805832743644714, "avg_line_length": 33.28947448730469, "blob_id": "8ceb76a0c1c80ad7c2c90ce1131dc06968aac115", "content_id": "95dfee116e71c637b19056f3533e38d55fd7626b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2606, "license_type": "no_license", "max_line_length": 127, "num_lines": 76, "path": "/tf/build_graph.py", "repo_name": "HuYuzhang/pyIntra", "src_encoding": "UTF-8", "text": "# Data augmented\nfrom __future__ import print_function\nimport tensorflow as tf\nimport cv2\nimport h5py\nimport numpy as np\nimport sys\nimport os\nimport subprocess as sp\nfrom tensorflow.python.framework.graph_util import convert_variables_to_constants\n\nbatch_size = 1 \nepochs = 1000\n\n\ndef tf_build_model(module_name, weights_name, params, input_tensor, target_tensor, mode):\n with tf.variable_scope('main_full', reuse=tf.AUTO_REUSE):\n model_module = __import__(module_name)\n satd_loss, mse_loss, recon = model_module.build_model(input_tensor, target_tensor, params=params, freq=True, test=True)\n # model_module.build_model(\n # input_tensor, output_tensor, params, mode=mode)\n return satd_loss, mse_loss, recon\n\n\ndef drive():\n block_size = 8\n model_module_name = sys.argv[2]\n model_type = sys.argv[3]\n weights_name = None\n mode = int(sys.argv[4])\n num_scale = int(sys.argv[5])\n if len(sys.argv) == 7:\n weights_name = sys.argv[6]\n print(weights_name)\n # load data\n\n # hf = None\n # if mode == 3:\n # hf = h5py.File('./Diverse_dataset_8_full.h5')\n # else:\n # hf = h5py.File('./Diverse_dataset_8_partial.h5')\n \n\n inputs = tf.placeholder(tf.float32, [batch_size, num_scale*mode, num_scale*mode, 1])\n targets = tf.placeholder(tf.float32, [batch_size, num_scale, num_scale, 1])\n\n # build model\n satd_loss, mse_loss, recon = tf_build_model(model_module_name,\n weights_name,\n {'learning_rate': 0.0001,\n 'batch_size': batch_size,\n 'num_scale':num_scale},\n inputs,\n targets,mode)\n # tensorboard_dir = 'tensorboard'\n # if not os.path.exists(tensorboard_dir):\n # os.makedirs(tensorboard_dir)\n\n # writer = tf.summary.FileWriter(tensorboard_dir)\n saver = tf.train.Saver()\n # checkpoint_dir = './ckpt/'\n with tf.Session() as sess:\n saver.restore(sess, weights_name)\n # import IPython\n # IPython.embed()\n # exit(0)\n graph = convert_variables_to_constants(sess, sess.graph_def, ['main_full/4_dim_out_freq'])\n #graph = convert_variables_to_constants(sess, sess.graph_def, ['main_full/Reshape_1'])\n tf.train.write_graph(graph,'../../pb32','graph_m%d_s%d_%s.pb' % (mode, num_scale, model_type),as_text=False)\n\n\n\nif __name__ == '__main__':\n tasks = {'train': drive}\n task = sys.argv[1]\n tasks[task]()\n" }, { "alpha_fraction": 0.49923768639564514, "alphanum_fraction": 0.5514145493507385, "avg_line_length": 32.16292190551758, "blob_id": "5b4ea5905ffa284f9129de9daee2dca1034a13f7", "content_id": "eccc61ff887557bcbd0be03587b22a1d508fe7aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5903, "license_type": "no_license", "max_line_length": 142, "num_lines": 178, "path": "/DHM/model_srnn_rev7_general.py", "repo_name": "HuYuzhang/pyIntra", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\n# refined srnn based on rev8\n# try stack CUDNN GRU\n\ndef stacked_RNN(input_tensor, num, scope, units, batch_size, num_scale):\n with tf.variable_scope(scope):\n cells = [tf.contrib.rnn.GRUCell(num_units=units,name='cell_%d'% (i) )for i in range(num)]\n states = [it.zero_state(batch_size, dtype=tf.float32) for i,it in enumerate(cells)]\n last = input_tensor\n for i in range(num):\n last, _ = tf.nn.static_rnn(cells[i], last, initial_state=states[i], sequence_length=[num_scale,]*batch_size, scope='rnn_%d' % (i))\n return last\n\ndef inter_rnn(input_tensor, num, scope, batch_size, channels=8, units=8):\n with tf.variable_scope(scope):\n # split input tensor to lines\n shaped_conv1 = tf.reshape(input_tensor, [batch_size, num, num, channels], name=\"conv1\")\n\n vertical_form = tf.reshape(shaped_conv1, [batch_size, num, num*channels], name='vertical_form')\n horizontal_form1 = tf.transpose(shaped_conv1, [0, 2, 1, 3], name='horizontal_form1')\n horizontal_form =tf.reshape(horizontal_form1, [batch_size, num, num*channels], name='horizontal_form')\n\n vertical_split = tf.unstack(\n vertical_form,\n num=num,\n axis=1,\n name=\"vertical_split\"\n )\n\n horizontal_split = tf.unstack(\n horizontal_form,\n num=num,\n axis=1,\n name=\"horizontal_split\"\n )\n\n vr4 = stacked_RNN(vertical_split, 1, 'vrnn', num*channels, batch_size, num)\n hr4 = stacked_RNN(horizontal_split, 1, 'hrnn', num*channels, batch_size, num)\n\n stack_h_ = tf.stack(hr4, axis=1, name='from_h')\n\n stack_v_ = tf.stack(vr4, axis=1, name='from_v')\n\n _stack_h = tf.reshape(stack_h_, [batch_size, num, num, channels], name='stack_shape_h')\n stack_v = tf.reshape(stack_v_, [batch_size, num, num, channels], name='stack_shape_v')\n\n stack_h = tf.transpose(_stack_h, [0,2,1,3], name='h_stack_back')\n\n concat2 = tf.concat([stack_v, stack_h], axis=3)\n\n _connect = tf.layers.conv2d(\n inputs=concat2,\n filters=units,\n kernel_size=[1, 1],\n strides=[1,1],\n padding=\"VALID\",\n name=\"connect\"\n )\n\n connect = tf.keras.layers.PReLU(shared_axes=[1,2], name='relu_con')(_connect)\n\n\n return connect\n\n\ndef build_model(input_tensor, target_tensor, params, mode=3):\n\n print(\"mode : %d\" % (mode))\n print(input_tensor.shape)\n batch_size = params['batch_size']\n\n num_scale = params['num_scale']\n\n input_layer = tf.reshape(input_tensor, [-1, num_scale*mode, num_scale*mode, 1])\n\n _convdown = tf.layers.conv2d(\n inputs=input_layer,\n filters=16,\n kernel_size=[1, 1],\n strides=[1,1],\n padding=\"SAME\",\n name=\"convdown\"\n )\n\n convdown = tf.keras.layers.PReLU(shared_axes=[1,2], name='reludown')(_convdown)\n\n _conv1 = tf.layers.conv2d(\n inputs=convdown,\n filters=16,\n kernel_size=[3, 3],\n padding='SAME',\n name=\"conv1\"\n )\n\n conv1 = tf.keras.layers.PReLU(shared_axes=[1,2])(_conv1)\n\n rnn1 = inter_rnn(conv1, num_scale*mode, 'inter1', batch_size, 16, 8)\n print(rnn1.shape)\n\n # rnn2 = inter_rnn(rnn1, num_scale*mode, 'inter2', batch_size, 16, 16)\n # print(rnn2.shape)\n\n _convdown1 = tf.layers.conv2d(\n inputs=rnn1,\n filters=8,\n kernel_size=[mode*2+1, mode*2+1],\n strides=[mode,mode],\n padding=\"SAME\",\n name=\"convdown1\"\n )\n\n convdown1 = tf.keras.layers.PReLU(shared_axes=[1,2], name='reludown1')(_convdown1)\n\n rnn3 = inter_rnn(convdown1, num_scale, 'inter3', batch_size, 8, 8)\n print(rnn3.shape)\n\n rnn4 = inter_rnn(rnn3, num_scale, 'inter4', batch_size, 8, 8)\n print(rnn4.shape)\n\n _conv10 = tf.layers.conv2d(\n rnn4,\n filters=16,\n kernel_size=[3, 3],\n padding=\"SAME\",\n name='conv10'\n )\n\n conv10 = tf.keras.layers.PReLU(shared_axes=[1,2], name='relu10')(_conv10)\n\n conv11 = tf.layers.conv2d(\n conv10,\n filters=1,\n kernel_size=[1, 1],\n padding=\"SAME\", name='conv11'\n )\n\n def SATD(y_true, y_pred, scale):\n H_8x8 = np.array(\n [[1., 1., 1., 1., 1., 1., 1., 1.],\n [1., -1., 1., -1., 1., -1., 1., -1.],\n [1., 1., -1., -1., 1., 1., -1., -1.],\n [1., -1., -1., 1., 1., -1., -1., 1.],\n [1., 1., 1., 1., -1., -1., -1., -1.],\n [1., -1., 1., -1., -1., 1., -1., 1.],\n [1., 1., -1., -1., -1., -1., 1., 1.],\n [1., -1., -1., 1., -1., 1., 1., -1.]],\n dtype=np.float32\n )\n H_target = np.zeros((1, 32,32), dtype=np.float32)\n H_target[0, 0:8,0:8] = H_8x8\n\n H_target[0, 0:8,8:16] = H_8x8\n H_target[0, 8:16,0:8] = H_8x8\n H_target[0, 8:16,8:16] = -H_8x8\n\n H_target[0, 16:32, 0:16] = H_target[0, 0:16, 0:16]\n H_target[0, 0:16, 16:32] = H_target[0, 0:16, 0:16]\n H_target[0, 16:32, 16:32] = -H_target[0, 0:16, 0:16]\n\n TH0 = tf.constant(H_target[:, 0:scale, 0:scale])\n\n TH1 = tf.tile(TH0, (batch_size, 1, 1))\n\n diff = tf.reshape(y_true - y_pred, (-1, scale, scale))\n\n return tf.reduce_mean(tf.square(tf.matmul(tf.matmul(TH1, diff), TH1)))\n\n loss = SATD(target_tensor, conv11, num_scale)\n\n global_step = tf.Variable(0, trainable=False)\n learning_rate = tf.train.exponential_decay(params['learning_rate'], global_step=global_step, decay_steps = 160000, decay_rate=0.1)\n optimizer = tf.train.AdamOptimizer(learning_rate=params['learning_rate'])\n train_op = optimizer.minimize(loss=loss, global_step=tf.train.get_global_step())\n\n mse_loss = tf.reduce_mean(tf.square((target_tensor-conv11)))\n\n return train_op, loss, mse_loss\n" }, { "alpha_fraction": 0.5112468004226685, "alphanum_fraction": 0.561053991317749, "avg_line_length": 35.3684196472168, "blob_id": "df299089c35f15cdb3c575c75e0d456b544ae8a4", "content_id": "5ec96e6af06c6120c6c5128e9a85173d735803f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6224, "license_type": "no_license", "max_line_length": 100, "num_lines": 171, "path": "/analyze/apply_mode.py", "repo_name": "HuYuzhang/pyIntra", "src_encoding": "UTF-8", "text": "import caffe\nimport numpy as np\nimport cv2\nimport os\nfrom h5 import h5Handler\nfrom psnr_test import test_quality\n\nroot_path = '/home/hyz/lab/intra/'\ndeploy_path = root_path + 'network/deploy.prototxt'\ndcmodel_path = root_path + 'network/dc.caffemodel'\nplanarmodel_path = root_path + 'network/planar.caffemodel'\nanglemodel_path = root_path + 'network/angle.caffemodel'\nimg_path = root_path + 'img/'\n# target_path = 'target/'\ngt_path = root_path + 'gt/'\npred_path = root_path + 'pred/'\nh5_path = root_path + 'data_set/dc_test.h5'\nvalid_path = root_path + 'valid/' + 'dc/'# when changing this, remenber to change the h5_path's name\n\n# initilization\ndcnet = caffe.Net(deploy_path, dcmodel_path, caffe.TEST)\nplanarnet = caffe.Net(deploy_path, planarmodel_path, caffe.TEST)\nanglenet = caffe.Net(deploy_path, anglemodel_path, caffe.TEST)\n# finish initilization\n\n#--------------- Abandoned, for img test in a folder-------------------\n# for file_name in os.listdir(img_path):\n# img = cv2.imread(img_path + file_name)\n# img = img[:,:,0]\n# vec = np.zeros([1, 3072, 1, 1], dtype=float)\n# vec[:,:2048,:,:] = img[0:32,0:64].reshape([1,2048,1,1])\n# vec[:,2048:,:,:] = img[32:,0:32].reshape([1,1024,1,1])\n# vec = vec / 255.0\n# net.blobs['data'].data[...] = vec\n# out = net.forward()\n# out = out['efc4'].reshape([32,32], order='F') * 255.0\n# img[32:,32:] = out[...]\n# cv2.imwrite(target_path + file_name, img)\n#--------------- Abandoned, for img test in a folder-------------------\n\n# 1-sampe refer to one picture\n# We store the gt picture in traget_path, and predicted picture in pred_path\nst_id = 0\ned_id = 1000\nsample_number = ed_id - st_id\nstride = 1\nhandler = h5Handler(h5_path)\ndatas = handler.read('data', st_id, ed_id, stride)\nlabels = handler.read('label', st_id, ed_id, stride)\n\nimg = np.zeros([64, 64])\n\n# for weekly report dump\nmax_dump = 5\ncnt_dump = 0\n# for weekly report dump\n\n\n# 0, 1, 2 respond to dc, planar, angle\npsnrs = [[], [], []]\nssims = [[], [], []]\nfor i in range(sample_number):\n data = datas[i:i+1, :, :, :]\n label = labels[i:i+1, :, :, :]\n img[:32, :] = data[:, :2048, :, :].reshape([32, 64], order='F') * 255.0\n img[32:64, :32] = data[:, 2048:, :, :].reshape([32, 32], order='F') * 255.0\n img[32:64, 32:64] = label.reshape([32, 32], order='F') * 255.0\n # write img to the gt directory\n # for normal data, we consider nothing\n print(i)\n if np.var(img) > 200:\n # print(str(i) + '_frame var bigger than 200')\n # cv2.imwrite(gt_path + str(i) + '.png', img)\n label = label.reshape([32, 32], order='F') * 255.0\n dcnet.blobs['data'].data[...] = data\n planarnet.blobs['data'].data[...] = data\n anglenet.blobs['data'].data[...] = data\n\n # test for dcnet\n vec = dcnet.forward()\n vec = vec['efc4'].reshape([32, 32], order='F') * 255.0\n tmp_stat = test_quality(label, vec)\n psnrs[0].append(tmp_stat['psnr'])\n ssims[0].append(tmp_stat['ssim'])\n \n # for weekly report dump\n if cnt_dump < max_dump:\n print('begin_dump')\n img[32:, 32:] = vec\n dump_path = valid_path + str(cnt_dump) + '_dc' + '.png'\n print(dump_path)\n cv2.imwrite(dump_path, img)\n # for weekly report dump\n\n # test for planarnet\n vec = planarnet.forward()\n vec = vec['efc4'].reshape([32, 32], order='F') * 255.0\n tmp_stat = test_quality(label, vec)\n psnrs[1].append(tmp_stat['psnr'])\n ssims[1].append(tmp_stat['ssim'])\n\n # for weekly report dump\n if cnt_dump < max_dump:\n img[32:, 32:] = vec\n dump_path = valid_path + str(cnt_dump) + '_planar' + '.png'\n cv2.imwrite(dump_path, img)\n # for weekly report dump\n\n # test for anglenet\n vec = anglenet.forward()\n vec = vec['efc4'].reshape([32, 32], order='F') * 255.0\n tmp_stat = test_quality(label, vec)\n psnrs[2].append(tmp_stat['psnr'])\n ssims[2].append(tmp_stat['ssim'])\n\n # for weekly report dump\n if cnt_dump < max_dump:\n img[32:, 32:] = vec\n dump_path = valid_path + str(cnt_dump) + '_angle' + '.png'\n cv2.imwrite(dump_path, img)\n cnt_dump = cnt_dump + 1\n # for weekly report dump\n\n \n\n\nprint(np.mean(psnrs[0]), np.mean(psnrs[1]), np.mean(psnrs[2]))\nprint(np.mean(ssims[0]), np.mean(ssims[1]), np.mean(ssims[2]))\n\n# now test without filter\npsnrs = [[], [], []]\nssims = [[], [], []]\nfor i in range(sample_number):\n print(i)\n data = datas[i:i+1, :, :, :]\n label = labels[i:i+1, :, :, :]\n img[:32, :] = data[:, :2048, :, :].reshape([32, 64], order='F') * 255.0\n img[32:64, :32] = data[:, 2048:, :, :].reshape([32, 32], order='F') * 255.0\n img[32:64, 32:64] = label.reshape([32, 32], order='F') * 255.0\n # write img to the gt directory\n # for normal data, we consider nothing\n # print(i)\n # if np.var(img) > 200:\n # cv2.imwrite(gt_path + str(i) + '.png', img)\n label = label.reshape([32, 32], order='F') * 255.0\n dcnet.blobs['data'].data[...] = data\n planarnet.blobs['data'].data[...] = data\n anglenet.blobs['data'].data[...] = data\n # test for dcnet\n vec = dcnet.forward()\n vec = vec['efc4'].reshape([32, 32], order='F') * 255.0\n tmp_stat = test_quality(label, vec)\n psnrs[0].append(tmp_stat['psnr'])\n ssims[0].append(tmp_stat['ssim'])\n # test for planarnet\n vec = planarnet.forward()\n vec = vec['efc4'].reshape([32, 32], order='F') * 255.0\n tmp_stat = test_quality(label, vec)\n psnrs[1].append(tmp_stat['psnr'])\n ssims[1].append(tmp_stat['ssim'])\n # test for anglenet\n vec = anglenet.forward()\n vec = vec['efc4'].reshape([32, 32], order='F') * 255.0\n tmp_stat = test_quality(label, vec)\n psnrs[2].append(tmp_stat['psnr'])\n ssims[2].append(tmp_stat['ssim'])\n # img[32:, 32:] = vec[...]\n # write pred_img to the pred directory\n # cv2.imwrite(pred_path + str(i) + '.png', img)\nprint(np.mean(psnrs[0]), np.mean(psnrs[1]), np.mean(psnrs[2]))\nprint(np.mean(ssims[0]), np.mean(ssims[1]), np.mean(ssims[2]))\n \n" }, { "alpha_fraction": 0.4573444426059723, "alphanum_fraction": 0.49326491355895996, "avg_line_length": 32.156028747558594, "blob_id": "108b911e2ec71aea4748128e4d60b9cd518332c3", "content_id": "2771fa8ff7e446b18863ca6b9f4082a8c7969951", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4677, "license_type": "no_license", "max_line_length": 94, "num_lines": 141, "path": "/tf64/generate_data.py", "repo_name": "HuYuzhang/pyIntra", "src_encoding": "UTF-8", "text": "import numpy as np\nimport cv2 as cv\nfrom mylib import h5Handler\nfrom mylib import read_frame\n\ndump_path = '../preProcess/dump_dir.txt'\ndec_path = '../../raw_data/dec.yuv'\ngt_path = '../../raw_data/video.yuv'\ntarget_path = '../img/'\n\nplanar_h5_path = '../../train64/planar.h5'\ndc_h5_path = '../../train64/dc.h5'\nangle_h5_path = '../../train64/angle.h5'\n\nheight = 1024\nwidth = 1792\nblock_size = 32\n\n# define 3 mode\nplanar_mode = 0\ndc_mode = 1\nangle_mode = 2\n\n\n\ndef filter_sample(img, threshold):\n # var = np.var(img)\n # if var > threshold:\n # return True\n # else:\n # return False\n pass\n\ninput = np.zeros([96, 96])\nlabel = np.zeros([32, 32])\ntest_img = np.zeros([64,64])\ndcvars = []\nplanarvars = []\nanglevars = []\n\nplanarinput = np.zeros([2000, 96, 96])\nplanarlabel = np.zeros([2000, 32, 32])\ndcinput =np.zeros([2000, 96, 96])\ndclabel = np.zeros([2000, 32, 32])\nangleinput = np.zeros([2000, 96, 96])\nanglelabel = np.zeros([2000, 32, 32])\n\nplanar_handler = h5Handler(planar_h5_path)\ndc_handler = h5Handler(dc_h5_path)\nangle_handler = h5Handler(angle_h5_path)\n# # --------------for debug------------------\n# cnt = 0\n# datas = np.zeros([20, 3072, 1, 1])\n# labels = np.zeros([20, 1024, 1, 1])\n# flag = True \n# handler = h5Handler('/home/hyz/lab/intra/train/train.h5') \n# # --------------for debug------------------\n\nwith open(dump_path) as f:\n while True:\n line = f.readline()\n if line == '':\n break\n [f_id, y, x, mode] = line.split()\n y = int(y)\n x = int(x)\n f_id = int(f_id)\n mode = int(mode)\n # --------------for debug------------------\n \t#if f_id > 5:\n # break\n # --------------for debug------------------\n\n if y == 0 and x == 0:\n pc = 0\n dc = 0\n ac = 0\n\n gt_img = read_frame(gt_path, f_id, height, width)\n dec_img = read_frame(dec_path, f_id, height, width)\n print(f_id)\n # Abort the most outsize row and column\n if x == 0 or y == 0 or x == 992 or y == 1760:\n continue\n # print([x, y])\n input = dec_img[x-block_size:x+2*block_size,y-block_size:y+2*block_size] / 255.0\n label = gt_img[x:x+block_size,y:y+block_size] / 255.0\n\n\n # --------------for debug------------------(write data to hdf5 file)\n # datas[cnt:cnt + 1, :, :, :] = input / 255.0\n # labels[cnt:cnt + 1, :, :, :] = label / 255.0\n # cnt += 1\n # if cnt == 20:\n # if flag:\n # handler.write(datas, label, create=True)\n # print('$$$$$$$$$$$ new h5 file constructed $$$$$$$$$$$$')\n # flag = False\n # else:\n # handler.write(datas, labels, create=False)\n # print('$$$$$$$$$$$ add data to existed h5 file constructed $$$$$$$$$$$$')\n # cnt = 0\n # --------------for debug------------------(write data to hdf5 file)\n\n if mode == planar_mode:\n planarinput[pc, :, :] = input\n planarlabel[pc, :, :] = label\n pc = pc + 1\n planarvars.append(np.var(test_img))\n elif mode == dc_mode:\n dcinput[dc, :, :] = input\n dclabel[dc, :, :] = label\n dc = dc + 1\n dcvars.append(np.var(test_img))\n else:\n angleinput[ac, :, :] = input\n anglelabel[ac, :, :] = label\n ac = ac + 1\n anglevars.append(np.var(test_img))\n # cv.imwrite(target_path + str(y) + '_' + str(x) + '.png', test_img)\n\n # Then check if we have arrive the final block of this frame\n if y == 1728 and x == 960:\n # now begin to write data to the h5 file\n if f_id == 0:\n # create mode\n planar_handler.write(planarinput[:pc,:,:], planarlabel[:pc,:,:], create=True)\n dc_handler.write(dcinput[:dc,:,:], dclabel[:dc,:,:], create=True)\n angle_handler.write(angleinput[:ac,:,:], anglelabel[:ac,:,:], create=True)\n else:\n # append mode\n planar_handler.write(planarinput[:pc,:,:], planarlabel[:pc,:,:], create=False)\n dc_handler.write(dcinput[:dc,:,:], dclabel[:dc,:,:], create=False)\n angle_handler.write(angleinput[:ac,:,:], anglelabel[:ac,:,:], create=False)\n print('In this frame %d: planar: %d, dc: %d, angle: %d'%(f_id, pc, dc, ac))\n\n\nprint('------------ print statistic data -------------')\nprint('planar var: ', np.mean(planarvars), len(planarvars))\nprint('dc var: ', np.mean(dcvars), len(dcvars))\nprint('angle var: ', np.mean(anglevars), len(anglevars))\n\n\n" }, { "alpha_fraction": 0.4804506301879883, "alphanum_fraction": 0.5096089839935303, "avg_line_length": 37.71794891357422, "blob_id": "0cc307e8adf5aa3e015a4eaca99b019f0fa20767", "content_id": "c6fc1666634ed5b2c6279020fdc174ed4abe64e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1509, "license_type": "no_license", "max_line_length": 131, "num_lines": 39, "path": "/preProcess/h5.py", "repo_name": "HuYuzhang/pyIntra", "src_encoding": "UTF-8", "text": "import h5py\n\nclass h5Handler(object):\n\n def __init__(self, h5_path):\n self.h5_path = h5_path\n\n def read(self, key, start, end, step):\n fid = h5py.File(self.h5_path, 'r')\n ret = fid[key][start:end:step]\n fid.close()\n return ret\n\n # right now very bad way to assign 3072 and 1024, but not a big problem\n # assume that datas and labels are of size [n, c, h, w]\n def write(self, datas, labels, create=True):\n if create:\n f = h5py.File(self.h5_path, 'w')\n f.create_dataset('data', data=datas, maxshape=(None, datas.shape[1], datas.shape[2]), chunks=True, dtype='float32')\n f.create_dataset('label', data=labels, maxshape=(None, labels.shape[1], labels.shape[2]), chunks=True, dtype='float32')\n f.close()\n else:\n # append mode\n f = h5py.File(self.h5_path, 'a')\n h5data = f['data']\n h5label = f['label']\n cursize = h5data.shape\n addsize = datas.shape\n\n # # --------------for debug------------------\n # print('-------now begin to add data------')\n # print(cursize)\n # # --------------for debug------------------\n\n h5data.resize([cursize[0] + addsize[0], datas.shape[1], datas.shape[2]])\n h5label.resize([cursize[0] + addsize[0], labels.shape[1], labels.shape[2]])\n h5data[-addsize[0]:,:,:] = datas\n h5label[-addsize[0]:,:,:] = labels\n f.close()" }, { "alpha_fraction": 0.5231450200080872, "alphanum_fraction": 0.5629680156707764, "avg_line_length": 42.41872024536133, "blob_id": "b64bf0638bc48debcb11d5d474494fab030b0430", "content_id": "62484ebb23f79b7455d456f0f9fdbc7d1cbabf81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8814, "license_type": "no_license", "max_line_length": 148, "num_lines": 203, "path": "/tf64/model_64.py", "repo_name": "HuYuzhang/pyIntra", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\n# refined srnn based on rev5 lite\n# try shrink the network\n\ndef stacked_RNN(input_tensor, num, scope, units, batch_size, num_scale):\n with tf.variable_scope(scope):\n cells = [tf.contrib.rnn.GRUCell(num_units=units,name='cell_%d'% (i) )for i in range(num)]\n states = [it.zero_state(batch_size, dtype=tf.float32) for i,it in enumerate(cells)]\n last = input_tensor\n for i in range(num):\n last, _ = tf.nn.static_rnn(cells[i], last, initial_state=states[i], sequence_length=[num_scale,]*batch_size, scope='rnn_%d' % (i))\n return last\n\ndef inter_rnn(input_tensor, num, scope, batch_size, channels=8, units=8):\n with tf.variable_scope(scope):\n # split input tensor to lines\n shaped_conv1 = tf.reshape(input_tensor, [batch_size, num, num, channels], name=\"conv1\")\n\n vertical_form = tf.reshape(shaped_conv1, [batch_size, num, num*channels], name='vertical_form')\n horizontal_form1 = tf.transpose(shaped_conv1, [0, 2, 1, 3], name='horizontal_form1')\n horizontal_form =tf.reshape(horizontal_form1, [batch_size, num, num*channels], name='horizontal_form')\n\n vertical_split = tf.unstack(\n vertical_form,\n num=num,\n axis=1,\n name=\"vertical_split\"\n )\n\n horizontal_split = tf.unstack(\n horizontal_form,\n num=num,\n axis=1,\n name=\"horizontal_split\"\n )\n\n vr4 = stacked_RNN(vertical_split, 1, 'vrnn', num*channels, batch_size, num)\n hr4 = stacked_RNN(horizontal_split, 1, 'hrnn', num*channels, batch_size, num)\n\n stack_h_ = tf.stack(hr4, axis=1, name='from_h')\n\n stack_v_ = tf.stack(vr4, axis=1, name='from_v')\n\n _stack_h = tf.reshape(stack_h_, [batch_size, num, num, channels], name='stack_shape_h')\n stack_v = tf.reshape(stack_v_, [batch_size, num, num, channels], name='stack_shape_v')\n\n stack_h = tf.transpose(_stack_h, [0,2,1,3], name='h_stack_back')\n\n concat2 = tf.concat([stack_v, stack_h], axis=3)\n\n _connect = tf.layers.conv2d(\n inputs=concat2,\n filters=units,\n kernel_size=[1, 1],\n strides=[1,1],\n padding=\"VALID\",\n name=\"connect\"\n )\n\n connect = tf.keras.layers.PReLU(shared_axes=[1,2], name='relu_con')(_connect)\n\n\n return connect\n\n\ndef build_model(input_tensor, target_tensor, params=None, freq=False, test=False):\n\n print(input_tensor.shape)\n \n # in fact, in test stage, params is always None\n if params is not None:\n batch_size = params['batch_size']\n lr = params['learning_rate']\n block_size = params['block_size']\n scale = params['scale']\n else:\n batch_size = input_tensor.shape[0]\n lr = 0.0001\n scale = 2\n block_size = 32\n\n # we assume that input_tensor is of size (batch_size * 96 * 96)\n # our target is to (batch_size * 32 * 32)\n input_tensor = tf.reshape(input_tensor,(-1, block_size * scale, block_size * scale))\n target_tensor = tf.reshape(target_tensor, (-1,block_size,block_size))\n # so first slice\n inputs = []\n if scale == 2: # scale 2\n inputs.append(tf.reshape(tf.slice(input_tensor, [0,0,0],[batch_size,block_size,2 * block_size]), [-1,block_size * block_size * 2]))\n inputs.append(tf.reshape(tf.slice(input_tensor, [0,block_size,0],[batch_size,block_size,block_size]), [-1,block_size * block_size]))\n else:# scale 3\n inputs.append(tf.reshape(tf.slice(input_tensor, [0,0,0],[batch_size,block_size,3 * block_size]), [-1,block_size * block_size * 3]))\n inputs.append(tf.reshape(tf.slice(input_tensor, [0,block_size,0],[batch_size,2 * block_size,block_size]), [-1,2 * block_size * block_size]))\n input_layer = tf.concat(inputs, 1)\n # print('---------->For debug, ', inputs[0].shape, inputs[1].shape) \n print('----------> Here is in the model building function, the input_layer size is(after slice and concat): ', input_layer.shape)\n # now the input_payer is of size [batch_size, 5120]\n # For the number of hidden state, we keep same with 3072 input\n\n _fc1 = tf.layers.dense(input_layer, 3072, name='fc1')\n\n fc1 = tf.nn.elu(_fc1, name='relu1')\n\n _fc2 = tf.layers.dense(fc1, 3072, name='fc2')\n\n fc2 = tf.nn.elu(_fc2, name='relu2')\n\n _fc3 = tf.layers.dense(fc2, 3072, name='fc3')\n\n fc3 = tf.nn.elu(_fc3, name='relu3')\n\n _fc4 = tf.layers.dense(fc3, 1024, name='fc4')\n\n fc4 = tf.nn.elu(_fc4, name='relu4')\n \n\n def SATD(y_true, y_pred):\n H_8x8 = np.array(\n [[1., 1., 1., 1., 1., 1., 1., 1.],\n [1., -1., 1., -1., 1., -1., 1., -1.],\n [1., 1., -1., -1., 1., 1., -1., -1.],\n [1., -1., -1., 1., 1., -1., -1., 1.],\n [1., 1., 1., 1., -1., -1., -1., -1.],\n [1., -1., 1., -1., -1., 1., -1., 1.],\n [1., 1., -1., -1., -1., -1., 1., 1.],\n [1., -1., -1., 1., -1., 1., 1., -1.]],\n dtype=np.float32\n )\n H_target = np.zeros((1,32,32), dtype=np.float32)\n H_target[0,0:8,8:16] = H_8x8\n H_target[0,8:16,0:8] = H_8x8\n H_target[0,8:16,8:16] = H_8x8\n\n\n H_target[0,16:32,0:16] = H_target[:, 0:16, 0:16]\n H_target[0,0:16,16:32] = H_target[:, 0:16, 0:16]\n H_target[0,16:32,16:32] = H_target[:, 0:16, 0:16]\n\n TH0 = tf.constant(H_target)\n\n TH1 = tf.tile(TH0, (input_tensor.shape[0], 1, 1))\n\n diff = tf.reshape(y_true - y_pred, (-1, 32, 32))\n\n return tf.reduce_mean(tf.sqrt(tf.square(tf.matmul(tf.matmul(TH1, diff), TH1)) + 0.0001))\n\n\n if freq:\n dct = np.zeros((1,block_size,block_size), dtype=np.float32)\n for i in range(0,block_size):\n for j in range(0,block_size):\n a = 0.0\n if i == 0:\n a = np.sqrt(1/float(block_size))\n else:\n a = np.sqrt(2/float(block_size))\n dct[0,i,j] = a * np.cos(np.pi * (j + 0.5) * i / float(block_size))\n idct = dct.transpose([0, 2, 1])\n tf_dct = tf.constant(dct, name='dct')\n tf_idct = tf.constant(idct, name='idct')\n # ------------------ finish initilize the dct matrix -----------------\n freq_tensor = tf.reshape(fc4, (-1, block_size, block_size), name='3_dim_raw_output_freq')\n batch_dct = tf.tile(tf_dct, [tf.shape(input_tensor)[0],1,1],name='title_dct')\n batch_idct = tf.tile(tf_idct, [tf.shape(input_tensor)[0],1,1],name='title_idct')\n freq_gt = tf.matmul(tf.matmul(batch_dct, target_tensor, name='freq_gt0'), batch_idct, name='freq_gt1')\n recon = tf.matmul(tf.matmul(batch_idct, freq_tensor, name='mul_dct1'), batch_dct, name='mul_idct1')\n # Note that here recon is of size \"batch_size * 32 * 32\"\n freq_mse_loss = tf.reduce_mean(tf.square((freq_gt-freq_tensor)))\n pixel_mse_loss = tf.reduce_mean(tf.square((target_tensor-recon)))\n satd_loss = SATD(recon, target_tensor)\n # loss = satd_loss\n loss = freq_mse_loss\n # now we just end the function because we don't need the train_op\n recon = tf.reshape(recon, (-1, block_size, block_size, 1), name='4_dim_out_freq')\n if test:\n return satd_loss, freq_mse_loss, pixel_mse_loss, recon\n \n # for training, we need the train_op\n global_step = tf.Variable(0, trainable=False)\n # learning_rate = tf.train.exponential_decay(params['learning_rate'], global_step=global_step, decay_steps = 10000, decay_rate=0.7)\n optimizer = tf.train.AdamOptimizer(learning_rate=lr)\n train_op = optimizer.minimize(loss=loss, global_step=tf.train.get_global_step())\n return train_op, satd_loss, freq_mse_loss, pixel_mse_loss, recon\n\n\n else:\n # prediction in pixel domain\n recon = tf.reshape(fc4, (-1, block_size, block_size), name='3_dim_raw_output_pixel')\n mse_loss = tf.reduce_mean(tf.square((target_tensor-recon)))\n satd_loss = SATD(recon, target_tensor)\n # loss = satd_loss\n loss = mse_loss\n \n recon = tf.reshape(recon, (-1, block_size, block_size, 1), name='4_dim_out_pixel')\n if test:\n return satd_loss, mse_loss, recon\n\n global_step = tf.Variable(0, trainable=False)\n # learning_rate = tf.train.exponential_decay(params['learning_rate'], global_step=global_step, decay_steps = 10000, decay_rate=0.7)\n optimizer = tf.train.AdamOptimizer(learning_rate=lr)\n train_op = optimizer.minimize(loss=loss, global_step=tf.train.get_global_step())\n return train_op, satd_loss, mse_loss, recon\n" }, { "alpha_fraction": 0.5809080600738525, "alphanum_fraction": 0.593713641166687, "avg_line_length": 38.09090805053711, "blob_id": "124c18626bc87e5219cd00e70bd71bf84864f395", "content_id": "d48901044cc22a76b5d0d480076847a00344e25d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 859, "license_type": "no_license", "max_line_length": 100, "num_lines": 22, "path": "/analyze/psnr_test.py", "repo_name": "HuYuzhang/pyIntra", "src_encoding": "UTF-8", "text": "from skimage.measure import compare_ssim as ssim\nfrom skimage.measure import compare_psnr as psnr\nimport numpy as np\n\n# gt and pred can be one sample or many sample\ndef test_quality(gt, pred):\n shape = gt.shape\n if len(shape) == 3:\n psnr_s = []\n ssim_s = []\n for i in range(shape[0]):\n qr = psnr(gt[i,:,:].astype(np.uint8), pred[i,:,:].astype(np.uint8))\n sm = ssim(gt[i,:,:].astype(np.uint8), pred[i,:,:].astype(np.uint8), multichannel = True)\n psnr_s.append(qr)\n ssim_s.append(sm)\n # Here we will return the mean of the psnrs and ssims\n return np.mean(psnr_s), np.mean(ssim_s)\n\n else if len(shape) == 2:\n qr = psnr(gt.astype(np.uint8), pred.astype(np.uint8))\n sm = ssim(gt.astype(np.uint8), pred.astype(np.uint8), multichannel = True)\n return qr, sm" }, { "alpha_fraction": 0.49237874150276184, "alphanum_fraction": 0.5224018692970276, "avg_line_length": 34.22950744628906, "blob_id": "ca41b1699d75c9aabcf93df1cd71309696feba09", "content_id": "88bbbcfee70d0e5891e65abd3fb386079f2db7a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2165, "license_type": "no_license", "max_line_length": 115, "num_lines": 61, "path": "/preProcess/power_test.py", "repo_name": "HuYuzhang/pyIntra", "src_encoding": "UTF-8", "text": "import numpy as np\nimport cv2 as cv\nimport sys\nfrom h5 import h5Handler\nfrom mylib import read_frame\nimport h5py\n\ncache_size = 2000\n\ncu_size = int(sys.argv[1])\nscale = int(sys.argv[2])\nf_cnt = int(sys.argv[3])\ndec_name = sys.argv[4]\ngt_name = sys.argv[5]\nheight = int(sys.argv[6])\nwidth = int(sys.argv[7])\nh5_name = \"s\" + str(cu_size) + \"_m\" + str(scale) + '.h5'\n\n\ncu_pixel = cu_size * cu_size\ninput_size = cu_pixel * (2 * scale - 1)\nlabel_size = cu_pixel\nmiddle_size = cu_pixel * scale\ninput_cache = np.zeros([input_size, 1, 1])\nlabel_cache = np.zeros([label_size, 1, 1])\ncache_cnt = 0\n\nf = h5py.File(h5_name, 'r')\ndata = f['/data']\nlabel = f['/label']\nfor i in range(f_cnt):\n Y = read_frame(dec_name, i, height, width)\n YY = read_frame(gt_name, i, height, width)\n for lx in range(0,width,cu_size):\n for ly in range(0,height,cu_size):\n rx = lx + cu_size * scale\n ry = ly + cu_size * scale\n if rx >= width or ry >= height:\n continue\n # import IPython\n # IPython.embed()\n input_cache[0:middle_size, 0, 0] = Y[ly:ly+cu_size, lx:lx+cu_size*scale].reshape([-1])\n input_cache[middle_size:input_size, 0, 0] = Y[ly+cu_size:ly+cu_size*scale, lx:lx+cu_size].reshape([-1])\n label_cache[:, 0, 0] = YY[ly+cu_size:ly+cu_size*2, lx+cu_size:lx+cu_size*2].reshape([-1])\n \n input_h5 = data[cache_cnt]\n label_h5 = label[cache_cnt]\n for k in range(input_size):\n if int(input_cache[k, 0, 0]) != int(input_h5[k, 0, 0]):\n print('label error in i: %d, lx: %d, ly: %d, k: %d'%(i, lx, ly, k))\n print(input_cache[k, 0, 0], input_h5[k, 0, 0])\n exit(0)\n for k in range(label_size):\n if int(label_cache[k, 0, 0]) != int(label_h5[k, 0, 0]):\n print('label error in i: %d, lx: %d, ly: %d, k: %d'%(i, lx, ly, k))\n print(input_cache[k, 0, 0], input_h5[k, 0, 0])\n exit(0)\n cache_cnt = cache_cnt + 1\n\n\n print(\"Finish test data from frame: %d\"%(i)) \n" }, { "alpha_fraction": 0.5174418687820435, "alphanum_fraction": 0.565891444683075, "avg_line_length": 26.157894134521484, "blob_id": "6f759ffe982baaacdcce4c07729069e846027dc6", "content_id": "5dab13e69aa78f3012f9ee7e244f2367270f159d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 516, "license_type": "no_license", "max_line_length": 108, "num_lines": 19, "path": "/analyze/concat_img.py", "repo_name": "HuYuzhang/pyIntra", "src_encoding": "UTF-8", "text": "import cv2 as cv\nimport numpy as np\nimport os\nmode = 'angle'\npath = '/home/hyz/lab/intra/valid/' + mode\ntarget_path = '/home/hyz/lab/intra/weekly/'\nfile_list = os.listdir(path)\ndump_cnt = 5\nimg = np.zeros([dump_cnt * 64, 3 * 64])\n\ncol = {'planar': 0, 'dc': 1, 'angle': 2}\n\nfor f in file_list:\n file_name = f\n f = f[:-4].split('_')\n row = int(f[0])\n img[64*row: 64*(row + 1), 64*(col[f[1]]): 64*(col[f[1]] + 1)] = cv.imread(path + '/' + file_name)[:,:,0]\n \ncv.imwrite(target_path + mode + '.png', img)\n" }, { "alpha_fraction": 0.47811657190322876, "alphanum_fraction": 0.5388923287391663, "avg_line_length": 38.51639175415039, "blob_id": "9dc479263104338dabe5d8b44a2f7601e492c944", "content_id": "3051daf0364ee1e22efa2346e7aa7670f7d614e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4821, "license_type": "no_license", "max_line_length": 135, "num_lines": 122, "path": "/DHM/model_pixel_L1.py", "repo_name": "HuYuzhang/pyIntra", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\n# refined srnn based on rev5 lite\n# try shrink the network\n\n\ndef build_model(input_tensor, target_tensor, params=None, test=False):\n\n print(input_tensor.shape)\n\n # in fact, in test stage, params is always None\n if params is not None:\n batch_size = params['batch_size']\n lr = params['learning_rate']\n block_size = params['block_size']\n scale = params['scale']\n else:\n batch_size = input_tensor.shape[0]\n lr = 0.0001\n scale = 2\n block_size = 32\n\n # we assume that input_tensor is of size (batch_size * 96 * 96)\n # our target is to (batch_size * 32 * 32)\n input_tensor = tf.reshape(\n input_tensor, (-1, block_size * scale, block_size * scale))\n target_tensor = tf.reshape(target_tensor, (-1, block_size, block_size))\n # so first slice\n inputs = []\n if scale == 2: # scale 2\n inputs.append(tf.reshape(tf.slice(input_tensor, [0, 0, 0], [\n batch_size, block_size, 2 * block_size]), [-1, block_size * block_size * 2]))\n inputs.append(tf.reshape(tf.slice(input_tensor, [0, block_size, 0], [\n batch_size, block_size, block_size]), [-1, block_size * block_size]))\n else: # scale 3\n inputs.append(tf.reshape(tf.slice(input_tensor, [0, 0, 0], [\n batch_size, block_size, 3 * block_size]), [-1, block_size * block_size * 3]))\n inputs.append(tf.reshape(tf.slice(input_tensor, [0, block_size, 0], [\n batch_size, 2 * block_size, block_size]), [-1, 2 * block_size * block_size]))\n input_layer = tf.concat(inputs, 1)\n # print('---------->For debug, ', inputs[0].shape, inputs[1].shape)\n print('----------> Here is in the model building function, the input_layer size is(after slice and concat): ', input_layer.shape)\n # now the input_payer is of size [batch_size, 5120]\n # For the number of hidden state, we keep same with 3072 input\n\n _fc1 = tf.layers.dense(input_layer, 512, name='fc1')\n\n fc1 = tf.nn.elu(_fc1, name='relu1')\n\n _fc2 = tf.layers.dense(fc1, 512, name='fc2')\n\n fc2 = tf.nn.elu(_fc2, name='relu2')\n\n _fc3 = tf.layers.dense(fc2, 512, name='fc3')\n\n fc3 = tf.nn.elu(_fc3, name='relu3')\n\n _fc4 = tf.layers.dense(fc3, 512, name='fc4')\n\n fc4 = tf.nn.elu(_fc4, name='relu4')\n\n _fc5 = tf.layers.dense(fc4, 512, name='fc5')\n\n fc5 = tf.nn.elu(_fc5, name='relu5')\n\n _fc6 = tf.layers.dense(fc5, 512, name='fc6')\n\n fc6 = tf.nn.elu(_fc6, name='relu6')\n\n _fc7 = tf.layers.dense(fc6, 512, name='fc7')\n\n fc7 = tf.nn.elu(_fc7, name='relu7')\n\n _fc8 = tf.layers.dense(fc7, block_size*block_size, name='fc8')\n\n # fc4 = tf.nn.relu(_fc4, name='relu4')\n\n def SATD(y_true, y_pred):\n H_8x8 = np.array(\n [[1., 1., 1., 1., 1., 1., 1., 1.],\n [1., -1., 1., -1., 1., -1., 1., -1.],\n [1., 1., -1., -1., 1., 1., -1., -1.],\n [1., -1., -1., 1., 1., -1., -1., 1.],\n [1., 1., 1., 1., -1., -1., -1., -1.],\n [1., -1., 1., -1., -1., 1., -1., 1.],\n [1., 1., -1., -1., -1., -1., 1., 1.],\n [1., -1., -1., 1., -1., 1., 1., -1.]],\n dtype=np.float32\n )\n H_target = np.zeros((1, 32, 32), dtype=np.float32)\n H_target[0, 0:8, 8:16] = H_8x8\n H_target[0, 8:16, 0:8] = H_8x8\n H_target[0, 8:16, 8:16] = H_8x8\n\n H_target[0, 16:32, 0:16] = H_target[:, 0:16, 0:16]\n H_target[0, 0:16, 16:32] = H_target[:, 0:16, 0:16]\n H_target[0, 16:32, 16:32] = H_target[:, 0:16, 0:16]\n\n TH0 = tf.constant(H_target[:, :block_size, :block_size])\n\n TH1 = tf.tile(TH0, (input_tensor.shape[0], 1, 1))\n\n diff = tf.reshape(y_true - y_pred, (-1, block_size, block_size))\n\n return tf.reduce_mean(tf.sqrt(tf.square(tf.matmul(tf.matmul(TH1, diff), TH1)) + 0.0001))\n\n # prediction in pixel domain\n recon = tf.reshape(_fc8, (-1, block_size, block_size), name='3_dim_raw_output_pixel')\n mse_loss = tf.reduce_mean(tf.square((target_tensor-recon)))\n satd_loss = SATD(target_tensor, recon)\n loss = satd_loss\n # loss = mse_loss\n \n recon = tf.reshape(recon, (-1, block_size, block_size, 1), name='4_dim_out_pixel')\n if test:\n return satd_loss, mse_loss, recon\n\n # global_step = tf.Variable(0, trainable=False)\n # learning_rate = tf.train.exponential_decay(params['learning_rate'], global_step=global_step, decay_steps = 10000, decay_rate=0.7)\n optimizer = tf.train.AdamOptimizer(learning_rate=lr)\n train_op = optimizer.minimize(loss=loss, global_step=tf.train.get_global_step())\n return train_op, satd_loss, mse_loss, recon\n" }, { "alpha_fraction": 0.5401396155357361, "alphanum_fraction": 0.5907504558563232, "avg_line_length": 31.742856979370117, "blob_id": "6967e79083357c482ac9e5d3ff4ffd7f0c2b0f64", "content_id": "d322fd7a300f2ccedf493df08e6c40ad4b9026d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1146, "license_type": "no_license", "max_line_length": 100, "num_lines": 35, "path": "/tf/mylib.py", "repo_name": "HuYuzhang/pyIntra", "src_encoding": "UTF-8", "text": "import cv2\nimport h5py\nimport numpy as np\nimport sys\nimport os\nfrom skimage.measure import compare_ssim as ssim\nfrom skimage.measure import compare_psnr as psnr\n\n# gt and pred can be one sample or many sample\ndef test_quality(gt, pred):\n shape = gt.shape\n if len(shape) == 3:\n psnr_s = []\n ssim_s = []\n for i in range(shape[0]):\n qr = psnr(gt[i,:,:].astype(np.uint8), pred[i,:,:].astype(np.uint8))\n sm = ssim(gt[i,:,:].astype(np.uint8), pred[i,:,:].astype(np.uint8), multichannel = True)\n psnr_s.append(qr)\n ssim_s.append(sm)\n # Here we will return the mean of the psnrs and ssims\n return np.mean(psnr_s), np.mean(ssim_s)\n\n elif len(shape) == 2:\n qr = psnr(gt.astype(np.uint8), pred.astype(np.uint8))\n sm = ssim(gt.astype(np.uint8), pred.astype(np.uint8), multichannel = True)\n return qr, sm\n\ndef img2input(img):\n img = img / 255.0\n ret = np.zeros([3072])\n gt = np.zeros([1024])\n ret[:2048] = img[:32,:64].reshape([2048])\n ret[2048:] = img[32:,:32].reshape([1024])\n gt = img[32:,32:].reshape([1024])\n return ret, gt\n" }, { "alpha_fraction": 0.5686695575714111, "alphanum_fraction": 0.6373390555381775, "avg_line_length": 26.47058868408203, "blob_id": "5c93c2890985f04944ec4c3e1d70da6b65fdf4b4", "content_id": "8a815c8ab80a03b57cf7be6e045ceb9d2aeb8bcf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 466, "license_type": "no_license", "max_line_length": 65, "num_lines": 17, "path": "/tailor/tail_video.py", "repo_name": "HuYuzhang/pyIntra", "src_encoding": "UTF-8", "text": "from libtailor import *\n\n\ntot_frame = 30\nraw_height = 240\nraw_weight = 416\nnew_height = 224\nnew_width = 416\nraw_filename = \"RaceHorses_416x240_30.yuv\"\nnew_filename = \"TAIL.yuv\"\n\nfor i in range(tot_frame):\n Y, U, V = read_frame(raw_filename, i, raw_height, raw_weight)\n Y = Y[0:new_height, 0:new_width]\n U = U[0:new_height >> 1, 0:new_width >> 1]\n V = V[0:new_height >> 1, 0:new_width >> 1]\n write_frame(new_filename, i, new_height, new_width, Y, U, V)" }, { "alpha_fraction": 0.47522276639938354, "alphanum_fraction": 0.4964045584201813, "avg_line_length": 39.27096939086914, "blob_id": "630345aa7215f4f7d8d018fcc4ca1bd11f02d509", "content_id": "c01421f60ef44d0dd83ded7d9a47c5f4c7087f0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12794, "license_type": "no_license", "max_line_length": 189, "num_lines": 310, "path": "/tf/engine_tornado.py", "repo_name": "HuYuzhang/pyIntra", "src_encoding": "UTF-8", "text": "# Data augmented\r\nfrom __future__ import print_function\r\nimport tensorflow as tf\r\nimport cv2\r\nimport h5py\r\nimport numpy as np\r\nimport sys\r\nimport os\r\nimport subprocess as sp\r\nfrom skimage.measure import compare_ssim as ssim\r\nfrom skimage.measure import compare_psnr as psnr\r\nfrom mylib import *\r\n\r\nbatch_size = 1024 \r\nepochs = 1000\r\n\r\n\r\ndef tf_build_model(module_name, input_tensor, output_tensor, test=False, freq=False, params=None, _weights_name=None):\r\n with tf.variable_scope('main_full', reuse=tf.AUTO_REUSE):\r\n model_module = __import__(module_name)\r\n if test:\r\n satd_op, mse_op, pred = model_module.build_model(\r\n input_tensor, output_tensor, params=None, freq=freq, test=test)\r\n return satd_op, mse_op, pred\r\n else:\r\n train_op, satd_op, mse_op, pred = model_module.build_model(\r\n input_tensor, output_tensor, params=params, freq=freq, test=test)\r\n return train_op, satd_op, mse_op, pred\r\n\r\ndef drive():\r\n print(sys.argv)\r\n global batch_size\r\n block_size = 8\r\n model_module_name = sys.argv[2]\r\n weights_name = None\r\n train_mode = sys.argv[3]\r\n init_lr = float(sys.argv[4])\r\n batch_size = int(sys.argv[5])\r\n if len(sys.argv) == 7:\r\n weights_name = sys.argv[6]\r\n print(weights_name)\r\n\r\n h5_path = '../../train/' + train_mode + '.h5'\r\n # load data\r\n\r\n hf = None\r\n \r\n hf = h5py.File(h5_path)\r\n \r\n print(\"Loading data\")\r\n x = np.array(hf['data'], dtype=np.float32)\r\n y = np.array(hf['label'], dtype=np.float32)\r\n\r\n length = x.shape[0]\r\n array_list = list(range(0, length))\r\n np.random.shuffle(array_list)\r\n bar = int(length*0.95)\r\n print('-------print the length of bar: %d, and length %d' %(bar, length))\r\n train_data = x[array_list[:bar], :, :, :]\r\n val_data = x[array_list[bar:], :, :, :]\r\n train_label = y[array_list[:bar], :, :, :]\r\n val_label = y[array_list[bar:], :, :, :]\r\n\r\n print(bar)\r\n\r\n def train_generator():\r\n while True:\r\n for i in range(0, bar, batch_size)[:-1]:\r\n yield train_data[i:i+batch_size, :, :, :], train_label[i:i+batch_size, :, :, :]\r\n # np.random.shuffle(train_data)\r\n\r\n def val_generator():\r\n for i in range(0, length-bar, batch_size)[:-1]:\r\n yield val_data[i:i+batch_size, :, :, :], val_label[i:i+batch_size, :, :, :]\r\n\r\n inputs = tf.placeholder(tf.float32, [batch_size, 3072, 1, 1])\r\n targets = tf.placeholder(tf.float32, [batch_size, 1024, 1, 1])\r\n\r\n # build model\r\n train_op, satd_loss, mse_loss, pred = tf_build_model(model_module_name,\r\n inputs,\r\n targets,\r\n test=False,\r\n freq=True,\r\n params=\r\n {'learning_rate': init_lr,\r\n 'batch_size': batch_size\r\n },\r\n _weights_name=weights_name\r\n )\r\n \r\n tensorboard_train_dir = '../../freq_32_tensorboard/' + train_mode + '/train'\r\n tensorboard_valid_dir = '../../freq_32_tensorboard/' + train_mode + '/valid'\r\n if not os.path.exists(tensorboard_train_dir):\r\n os.makedirs(tensorboard_train_dir)\r\n if not os.path.exists(tensorboard_valid_dir):\r\n os.makedirs(tensorboard_valid_dir)\r\n\r\n saver = tf.train.Saver(max_to_keep=30)\r\n checkpoint_dir = '../../freq_32_model/' + train_mode + '/'\r\n if not os.path.exists(checkpoint_dir):\r\n os.makedirs(checkpoint_dir)\r\n with tf.Session() as sess:\r\n if weights_name is not None:\r\n saver.restore(sess, weights_name)\r\n print('-----------Sucesfully restoring weights from: ', weights_name)\r\n else:\r\n sess.run(tf.global_variables_initializer())\r\n print('-----------No weights defined, run initializer')\r\n total_var = 0\r\n for var in tf.trainable_variables():\r\n shape = var.get_shape()\r\n par_num = 1\r\n for dim in shape:\r\n par_num *= dim.value\r\n total_var += par_num\r\n print(\"----------------Number of total variables: %d\" %(total_var))\r\n options = tf.RunOptions() # trace_level=tf.RunOptions.FULL_TRACE)\r\n run_metadata = tf.RunMetadata()\r\n data_gen = train_generator()\r\n interval = 500\r\n metrics = np.zeros((interval,3))\r\n\r\n # --------------- part for tensorboard----------------\r\n train_writer = tf.summary.FileWriter(tensorboard_train_dir, sess.graph)\r\n valid_writer = tf.summary.FileWriter(tensorboard_valid_dir, sess.graph)\r\n train_satd_summary = tf.summary.scalar(train_mode + ' SATD loss', satd_loss)\r\n train_mse_summary = tf.summary.scalar(train_mode + ' MSE loss', mse_loss)\r\n merged = tf.summary.merge([train_satd_summary, train_mse_summary])\r\n\r\n #sub1--------------------------------here for valid mean\r\n valid_size = int(len(range(0, length - bar, batch_size)[:-1]))\r\n print(valid_size)\r\n valid_mse_input = tf.placeholder(tf.float32, [valid_size])\r\n valid_satd_input = tf.placeholder(tf.float32, [valid_size])\r\n valid_mse_mean = tf.reduce_mean(valid_mse_input)\r\n valid_satd_mean = tf.reduce_mean(valid_satd_input)\r\n valid_mse_summary = tf.summary.scalar(train_mode + ' MSE loss', valid_mse_mean)\r\n valid_satd_summary = tf.summary.scalar(train_mode + ' SATD loss', valid_satd_mean)\r\n valid_merged = tf.summary.merge([valid_mse_summary, valid_satd_summary])\r\n #sub1--------------------------------for valid mean\r\n\r\n # --------------- part for tensorboard----------------\r\n\r\n for i in range(200000):\r\n if i % interval == 0:\r\n val_satd_s = []\r\n val_mse_s = []\r\n val_gen = val_generator()\r\n psnr_s = []\r\n ssim_s = []\r\n for v_data, v_label in val_gen:\r\n val_satd, val_mse, recon = sess.run([satd_loss, mse_loss, pred], feed_dict={\r\n inputs: v_data, targets: v_label})\r\n val_satd_s.append(float(val_satd))\r\n val_mse_s.append(float(val_mse))\r\n tmp_psnr, tmp_ssim = test_quality(v_label.reshape([-1, 32, 32])[0] * 255.0, recon.reshape([-1, 32, 32])[0] * 255.0)\r\n psnr_s.append(tmp_psnr)\r\n ssim_s.append(tmp_ssim)\r\n # print('#########tmp: ', tmp_psnr, tmp_ssim)\r\n\r\n # Here is about the tensorboard\r\n rs = sess.run(valid_merged, feed_dict={\r\n valid_mse_input: val_mse_s, valid_satd_input: val_satd_s\r\n })\r\n valid_writer.add_summary(rs, i)\r\n # Here is about the tensorboard\r\n\r\n # now test for psnr\r\n print('------------->now show the info of PSNR and SSIM')\r\n print('PSNR is: %f, SSIM is: %f'%(np.mean(psnr_s), np.mean(ssim_s)))\r\n\r\n\r\n # print(val_satd_s)\r\n print(\"Model name: %s, step %8d, Train SATD %.4f, Train MSE %.4f, Val SATD %.4f, Val MSE %.6f\" % (\r\n model_module_name, i, np.mean(metrics[:,0]), np.mean(metrics[:,1]), np.mean(val_satd_s), np.mean(val_mse_s)))\r\n \r\n # ------------------- Here is the training part ---------------\r\n iter_data, iter_label = next(data_gen)\r\n # print(iter_data.shape)\r\n feed_dict = {inputs: iter_data, targets: iter_label}\r\n _, satd, mse, rs = sess.run([train_op, satd_loss, mse_loss, merged],\r\n feed_dict=feed_dict,\r\n options=options,\r\n run_metadata=run_metadata)\r\n if i % interval == 0:\r\n train_writer.add_summary(rs, i)\r\n\r\n metrics[i%interval,0] = satd\r\n metrics[i%interval,1] = mse\r\n \r\n if i % 10000 == 0:\r\n save_path = saver.save(sess, os.path.join(\r\n checkpoint_dir, \"%s_%06d.ckpt\" % (model_module_name,i)))\r\n\r\ndef run_test():\r\n print(sys.argv)\r\n global batch_size\r\n block_size = 8\r\n batch_size = 64\r\n model_module_name = sys.argv[2]\r\n train_mode = sys.argv[3]\r\n weights_name = sys.argv[4]\r\n print(weights_name, train_mode, model_module_name)\r\n inputs = tf.placeholder(tf.float32, [batch_size, 64, 64, 1])\r\n targets = tf.placeholder(tf.float32, [batch_size, 32, 32, 1])\r\n\r\n h5_path = '../../train/' + train_mode + '.h5'\r\n\r\n hf = None\r\n \r\n hf = h5py.File(h5_path)\r\n \r\n print(\"Loading data\")\r\n x = np.array(hf['data'], dtype=np.float32)\r\n y = np.array(hf['label'], dtype=np.float32)\r\n length = x.shape[0]\r\n print(\"Finishing loading data\")\r\n print(weights_name)\r\n satd_loss, mse_loss, pred = tf_build_model(model_module_name,\r\n inputs,\r\n targets,\r\n test=True,\r\n freq=True,\r\n _weights_name=weights_name\r\n )\r\n print('finish build network')\r\n def val_generator():\r\n for i in range(0, length, batch_size)[:-1]:\r\n yield x[i:i+batch_size, :, :, :], y[i:i+batch_size, :, :, :]\r\n\r\n saver = tf.train.Saver()\r\n \r\n\r\n # Test reshape\r\n tmp_input = np.zeros([batch_size, 64, 64, 1])\r\n tmp_label = np.zeros([batch_size, 32, 32, 1])\r\n # Test reshape\r\n with tf.Session() as sess:\r\n if weights_name is None:\r\n print('error!, no weights_name')\r\n exit(0)\r\n else:\r\n saver.restore(sess, weights_name)\r\n print('Successfully restore weights from file: ', weights_name)\r\n \r\n psnr_s = []\r\n ssim_s = []\r\n val_gen = val_generator()\r\n val_cnt = 0\r\n for v_data, v_label in val_gen:\r\n tmp_input[:,0:32,0:64,:] = v_data[:,:2048,:,:].reshape([-1,32,64,1])\r\n tmp_input[:,32:64,0:32,:] = v_data[:,2048:,:,:].reshape([-1,32,32,1])\r\n tmp_label = v_label.reshape([-1,32,32,1])\r\n val_satd, val_mse, recon = sess.run([satd_loss, mse_loss, pred], feed_dict={\r\n inputs: tmp_input, targets: tmp_label})\r\n\r\n recon = recon.reshape([-1, 32, 32]) * 255.0\r\n gt = v_label.reshape([-1, 32, 32]) * 255.0\r\n val_psnr, val_ssim = test_quality(gt, recon)\r\n val_cnt = val_cnt + batch_size\r\n print('-----------> Step %d, Total: %d, psnr: %f, ssim: %f, mse loss: %f, satd_loss: %f<------------'%(val_cnt, length, val_psnr, val_ssim, np.mean(val_mse), np.mean(val_satd)))\r\n psnr_s.append(val_psnr)\r\n ssim_s.append(val_ssim)\r\n print('Finish testing, now psnr is: %f, and ssim is: %f'%(np.mean(psnr_s), np.mean(ssim_s)))\r\n\r\n\r\ndef dump_img(filename, targetpath):\r\n model_module_name = sys.argv[2]\r\n weights_name = sys.argv[3]\r\n filename = sys.argv[4]\r\n print(weights_name, model_module_name, filename)\r\n \r\n img = skimage.imread(filename) / 255.0\r\n input, gt = img2input(filename)\r\n\r\n\r\n inputs = tf.placeholder(tf.float32, [1, 3072, 1, 1])\r\n targets = tf.placeholder(tf.float32, [1, 1024, 1, 1])\r\n satd_loss, mse_loss, pred = tf_build_model(model_module_name,\r\n inputs,\r\n targets,\r\n test=True,\r\n freq=False,\r\n _weights_name=weights_name\r\n )\r\n\r\n saver = tf.train.Saver()\r\n \r\n with tf.Session() as sess:\r\n if weights_name is None:\r\n print('error!, no weights_name')\r\n exit(0)\r\n else:\r\n saver.restore(sess, weights_name)\r\n print('Successfully restore weights from file: ', weights_name)\r\n \r\n recon = sess.run(pred, feed_dict={inputs: input.reshape(1,3072,1,1), targets: gt.reshape(1,1024,1,1)})\r\n img[32:,32:] = recon.reshape([32,32]) * 255.0\r\n skimage.imwrite(targetpath, img)\r\n\r\n \r\n \r\n\r\n\r\nif __name__ == '__main__':\r\n tasks = {'train': drive, 'test': run_test, 'dump': dump_img}\r\n task = sys.argv[1]\r\n print('-------------begin task', task)\r\n tasks[task]()\r\n" }, { "alpha_fraction": 0.47297295928001404, "alphanum_fraction": 0.5825825929641724, "avg_line_length": 23.66666603088379, "blob_id": "4fc11c6f6903f91aa710634b9ac8f3eb94b05f06", "content_id": "af2117b5f04c04f58d3be9b1556fa7149f822401", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 666, "license_type": "no_license", "max_line_length": 55, "num_lines": 27, "path": "/preProcess/test.py", "repo_name": "HuYuzhang/pyIntra", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\nimport sys\nimport os\nfrom mylib import read_frame\nimport h5py\n \n\n# path = '../../raw_data/dec.yuv'\n# height = 1024\n# width = 1792\n# idx = int(sys.argv[1])\n\n# img = read_frame(path, idx, height, width, mode=1)\n# cv2.imwrite('../../img/' + sys.argv[1] + '.png', img)\n\nh5_path = '../../train/planar.h5'\nf = h5py.File(h5_path, 'r')\ndata = f['/data']\nlabel = f['/label']\ninput = data[2000,:,:,:] * 255.0\ngt = label[2000,:,:,:] * 255.0\nimg = np.zeros([64,64])\nimg[:32,:64] = input[:2048,:,:].reshape([32,64])\nimg[32:64,:32] = input[2048:,:,:].reshape([32,32])\nimg[32:,32:] = gt.reshape([32,32])\ncv2.imwrite('../../img/valid.png', img)\n" }, { "alpha_fraction": 0.5177927017211914, "alphanum_fraction": 0.5461578369140625, "avg_line_length": 33.9636344909668, "blob_id": "55968bfaf4a64a410c8a87db809851cdfce4b851", "content_id": "bf70add772c8f4be219f8e925eb0072598922382", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1939, "license_type": "no_license", "max_line_length": 126, "num_lines": 55, "path": "/preProcess/power_generate_data.py", "repo_name": "HuYuzhang/pyIntra", "src_encoding": "UTF-8", "text": "import numpy as np\nimport cv2 as cv\nimport sys\nfrom h5 import h5Handler\nfrom mylib import read_frame\n\ncache_size = 2000\n\ncu_size = int(sys.argv[1])\nscale = int(sys.argv[2])\nf_cnt = int(sys.argv[3])\ndec_name = sys.argv[4]\ngt_name = sys.argv[5]\nheight = int(sys.argv[6])\nwidth = int(sys.argv[7])\nh5_name = \"s\" + str(cu_size) + \"_m\" + str(scale) + '.h5'\n\n\ncu_pixel = cu_size * cu_size\ninput_size = cu_pixel * (2 * scale - 1)\nlabel_size = cu_pixel\nmiddle_size = cu_pixel * scale\ninput_cache = np.zeros([cache_size, input_size, 1, 1])\nlabel_cache = np.zeros([cache_size, label_size, 1, 1])\ncache_cnt = 0\n\nfid = 0\nh5er = h5Handler(h5_name)\n\nfor i in range(f_cnt):\n Y = read_frame(dec_name, i, height, width)\n YY = read_frame(gt_name, i, height, width)\n for lx in range(0,width,cu_size):\n for ly in range(0,height,cu_size):\n rx = lx + cu_size * scale\n ry = ly + cu_size * scale\n if rx >= width or ry >= height:\n continue\n # import IPython\n # IPython.embed()\n input_cache[cache_cnt, 0:middle_size, 0, 0] = Y[ly:ly+cu_size, lx:lx+cu_size*scale].reshape([-1])\n input_cache[cache_cnt, middle_size:input_size, 0, 0] = Y[ly+cu_size:ly+cu_size*scale, lx:lx+cu_size].reshape([-1])\n label_cache[cache_cnt, :, 0, 0] = YY[ly+cu_size:ly+cu_size*2, lx+cu_size:lx+cu_size*2].reshape([-1])\n\n cache_cnt = cache_cnt + 1\n if cache_cnt == cache_size:\n input_cache = input_cache / 255.0\n label_cache = label_cache / 255.0\n if fid == 0: # create mode\n h5er.write(input_cache[:,:,:,:], label_cache[:,:,:,:], create=True)\n fid = 1\n else:\n h5er.write(input_cache[:,:,:,:], label_cache[:,:,:,:], create=False)\n cache_cnt = 0\n print(\"Finish getting data from frame: %d\"%(i)) \n" }, { "alpha_fraction": 0.5500575304031372, "alphanum_fraction": 0.6242808103561401, "avg_line_length": 25.34848403930664, "blob_id": "5d3ceb1f944873d6bae2ccea6291ae883e13a5a5", "content_id": "934d117002bfbc42e555855d051006db4c79bb9f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1738, "license_type": "no_license", "max_line_length": 66, "num_lines": 66, "path": "/analyze/test_model.py", "repo_name": "HuYuzhang/pyIntra", "src_encoding": "UTF-8", "text": "import caffe\nimport numpy as np\nimport cv2 as cv\nfrom psnr_test import test_quality\n\ndeploy_path ='../network/deploy.prototxt'\ndcmodel_path = '../network/dc.caffemodel'\nplanarmodel_path = '../network/planar.caffemodel'\nanglemodel_path = '../network/angle.caffemodel'\n\nimg = np.zeros([64, 64])\ndcnet = caffe.Net(deploy_path, dcmodel_path, caffe.TEST)\nplanarnet = caffe.Net(deploy_path, planarmodel_path, caffe.TEST)\nanglenet = caffe.Net(deploy_path, anglemodel_path, caffe.TEST)\n\none_block = np.ones([32,32])\ninput = np.zeros([1,3072,1,1])\n\nfor i in range(8, 16):\n for j in range(8, 56):\n img[i][j] = 1\n\nfor i in range(48, 56):\n for j in range(8, 56):\n img[i][j] = 1\n\nfor i in range(8, 56):\n for j in range(8, 16):\n img[i][j] = 1\n\nfor i in range(8, 56):\n for j in range(48, 56):\n img[i][j] = 1\n\n# img[32:,:32] = one_block\n# img[:32,32:] = one_block\ntmp_img = img.copy()\ntmp_img *= 255.0\n\n\ninput[:,:2048,:,:] = img[:32,:].reshape([1,2048,1,1], order='F')\ninput[:,2048:,:,:] = img[32:,:32].reshape([1,1024,1,1], order='F')\ndcnet.blobs['data'].data[...] = input\nplanarnet.blobs['data'].data[...] = input\nanglenet.blobs['data'].data[...] = input\nimg *= 255.0\n\nvec = dcnet.forward()\nvec = vec['efc4']\nimg[32:,32:] = vec.reshape([32,32], order='F') * 255.0\ncv.imwrite('../test/dc.png', img)\nprint(test_quality(tmp_img, img))\n\nvec = planarnet.forward()\nvec = vec['efc4']\nimg[32:,32:] = vec.reshape([32,32], order='F') * 255.0\ncv.imwrite('../test/planar.png', img)\nprint(test_quality(tmp_img, img))\n\nvec = anglenet.forward()\nvec = vec['efc4']\nimg[32:,32:] = vec.reshape([32,32], order='F') * 255.0\ncv.imwrite('../test/angle.png', img)\nprint(test_quality(tmp_img, img))\n\ncv.imwrite('../test/gt.png', tmp_img)" }, { "alpha_fraction": 0.44547462463378906, "alphanum_fraction": 0.5399558544158936, "avg_line_length": 41.345794677734375, "blob_id": "a02aaceb1d3be8a1fd9a6739dcc9d09f11f35deb", "content_id": "0ff5c7f7d8a47c98208f9d315c0637d3a492428b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4530, "license_type": "no_license", "max_line_length": 121, "num_lines": 107, "path": "/tf64/mylib.py", "repo_name": "HuYuzhang/pyIntra", "src_encoding": "UTF-8", "text": "import cv2\nimport h5py\nimport numpy as np\nimport sys\nimport os\nfrom skimage.measure import compare_ssim as ssim\nfrom skimage.measure import compare_psnr as psnr\n\n# gt and pred can be one sample or many sample\ndef test_quality(gt, pred):\n shape = gt.shape\n if len(shape) == 3:\n psnr_s = []\n ssim_s = []\n for i in range(shape[0]):\n qr = psnr(gt[i,:,:].astype(np.uint8), pred[i,:,:].astype(np.uint8))\n sm = ssim(gt[i,:,:].astype(np.uint8), pred[i,:,:].astype(np.uint8), multichannel = True)\n psnr_s.append(qr)\n ssim_s.append(sm)\n # Here we will return the mean of the psnrs and ssims\n return np.mean(psnr_s), np.mean(ssim_s)\n\n elif len(shape) == 2:\n qr = psnr(gt.astype(np.uint8), pred.astype(np.uint8))\n sm = ssim(gt.astype(np.uint8), pred.astype(np.uint8), multichannel = True)\n return qr, sm\n\ndef img2input(img):\n img = img / 255.0\n ret = np.zeros([3072])\n gt = np.zeros([1024])\n ret[:2048] = img[:32,:64].reshape([2048])\n ret[2048:] = img[32:,:32].reshape([1024])\n gt = img[32:,32:].reshape([1024])\n return ret, gt\n\nclass h5Handler(object):\n def __init__(self, h5_path):\n self.h5_path = h5_path\n\n def read(self, key, start, end, step):\n fid = h5py.File(self.h5_path, 'r')\n ret = fid[key][start:end:step]\n fid.close()\n return ret\n\n # right now very bad way to assign 3072 and 1024, but not a big problem\n # assume that datas and labels are of size [n, c, h, w]\n def write(self, datas, labels, create=True):\n if create:\n f = h5py.File(self.h5_path, 'w')\n f.create_dataset('data', data=datas, maxshape=(None, 96, 96), chunks=True, dtype='float32')\n f.create_dataset('label', data=labels, maxshape=(None, 32, 32), chunks=True, dtype='float32')\n f.close()\n else:\n # append mode\n f = h5py.File(self.h5_path, 'a')\n h5data = f['data']\n h5label = f['label']\n cursize = h5data.shape\n addsize = datas.shape\n\n # # --------------for debug------------------\n # print('-------now begin to add data------')\n # print(cursize)\n # # --------------for debug------------------\n\n h5data.resize([cursize[0] + addsize[0], 96, 96])\n h5label.resize([cursize[0] + addsize[0], 32, 32])\n h5data[-addsize[0]:,:,:] = datas\n h5label[-addsize[0]:,:,:] = labels\n f.close()\n\n\n# Assume that our video is I420\ndef read_frame(filename, idx, _height, _width, mode=0):\n pixel_num = _height * _width\n byte_num = int(pixel_num * 3 / 2)\n # print(byte_num)\n with open(filename, 'rb') as f:\n f.seek(idx * byte_num, 0)\n # only luma mode\n if mode == 0:\n data = np.fromfile(f, dtype=np.uint8, count=pixel_num)\n return data.reshape([_height, _width])\n\n else:\n # Three color mode\n dataY = np.fromfile(f, dtype=np.uint8, count=pixel_num)\n dataU = np.fromfile(f, dtype=np.uint8, count=int(pixel_num / 4))\n dataV = np.fromfile(f, dtype=np.uint8, count=int(pixel_num / 4))\n img = np.zeros([3, _height, _width])\n img[0,:,:] = dataY.reshape([_height, _width])\n img[1,0::2,0::2] = dataU.reshape([int(_height / 2), int(_width / 2)])\n img[1,0::2,1::2] = img[1,0::2,0::2]\n img[1,1::2,0::2] = img[1,0::2,0::2]\n img[1,1::2,1::2] = img[1,0::2,0::2]\n img[2,0::2,0::2] = dataV.reshape([int(_height / 2), int(_width / 2)])\n img[2,0::2,1::2] = img[2,0::2,0::2]\n img[2,1::2,0::2] = img[2,0::2,0::2]\n img[2,1::2,1::2] = img[2,0::2,0::2]\n img = img.astype(np.uint8)\n img = img.transpose(1,2,0)\n print(img.dtype)\n print('---', img.shape)\n img = cv2.cvtColor(img, cv2.COLOR_YUV2BGR)\n return img" }, { "alpha_fraction": 0.48408785462379456, "alphanum_fraction": 0.5013446807861328, "avg_line_length": 35.876033782958984, "blob_id": "166364d9ab884bbed787389dbfe6e1b7eb4bea84", "content_id": "e3e58c304d955ecf34e0394d24346d8192de785f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4462, "license_type": "no_license", "max_line_length": 99, "num_lines": 121, "path": "/DHM/power_generate_data_2D.py", "repo_name": "HuYuzhang/pyIntra", "src_encoding": "UTF-8", "text": "import numpy as np\nimport cv2\nimport sys\nfrom mylib import read_frame, h5Handler\nimport random\nimport math\n\n\n####### Configuration ##########\ncache_size = 2000\nrandom_flag = True\nrandom_num = 500\nalign_flag = False\nmask_mean = True\n####### Configuration ##########\n\n\ncu_size = int(sys.argv[1])\nscale = int(sys.argv[2])\nf_cnt = int(sys.argv[3])\ndec_name = sys.argv[4]\ngt_name = sys.argv[5]\nheight = int(sys.argv[6])\nwidth = int(sys.argv[7])\n#h5_name = \"../../train/data/s\" + str(cu_size) + \"_m\" + str(scale) + '.h5'\nh5_name = sys.argv[8]\n\ncu_pixel = cu_size * cu_size\ninput_size = cu_pixel * (2 * scale - 1)\nlabel_size = cu_pixel\nmiddle_size = cu_pixel * scale\ninput_cache = np.zeros([cache_size, cu_size * scale, cu_size * scale])\nlabel_cache = np.zeros([cache_size, cu_size, cu_size])\ncache_cnt = 0\n\n\n####### Configuration ##########\nfid = 0\nh5er = h5Handler(h5_name)\nx_up = math.floor(width / cu_size - 1)\ny_up = math.floor(height / cu_size - 1)\n####### Configuration ##########\nprint(\"Input size: \", input_size)\nif not random_flag:\n for i in range(f_cnt):\n Y = read_frame(dec_name, i, height, width)\n YY = read_frame(gt_name, i, height, width)\n cv2.imwrite('dec.png', Y)\n cv2.imwrite('gt.png', YY)\n for lx in range(0,width,cu_size):\n for ly in range(0,height,cu_size):\n rx = lx + cu_size * scale\n ry = ly + cu_size * scale\n if rx >= width or ry >= height:\n continue\n # import IPython\n # IPython.embed()\n input_cache[cache_cnt, :, :] = Y[ly:ly+cu_size * scale, lx:lx+cu_size*scale]\n\n if mask_mean:\n input_cache[cache_cnt, cu_size:, cu_size:] = 0\n mean = np.sum(input_cache[cache_cnt, :, :]) / float(input_size)\n input_cache[cache_cnt, cu_size:, cu_size:] = mean\n else:\n input_cache[cache_cnt, cu_size:, cu_size:] = 0\n\n label_cache[cache_cnt, :, :] = YY[ly+cu_size:ly+cu_size*2, lx+cu_size:lx+cu_size*2]\n\n cache_cnt = cache_cnt + 1\n if cache_cnt == cache_size:\n input_cache = input_cache / 255.0\n label_cache = label_cache / 255.0\n if fid == 0: # create mode\n h5er.write(input_cache, label_cache, create=True)\n fid = 1\n else:\n h5er.write(input_cache, label_cache, create=False)\n cache_cnt = 0\n # print(\"Finish getting data from frame: %d\"%(i))\nelse: # we will random get some picture from the picture\n for i in range(f_cnt):\n tmp_num = 0\n Y = read_frame(dec_name, i, height, width)\n YY = read_frame(gt_name, i, height, width)\n while tmp_num < random_num:\n if align_flag:\n lx = random.randint(0, x_up) * cu_size\n ly = random.randint(0, y_up) * cu_size\n else:\n lx = random.randint(0, width - 1)\n ly = random.randint(0, height - 1)\n\n rx = lx + cu_size * scale\n ry = ly + cu_size * scale\n if rx >= width or ry >= height:\n continue\n # import IPython\n # IPython.embed()\n input_cache[cache_cnt, :, :] = Y[ly:ly+cu_size * scale, lx:lx+cu_size*scale]\n\n if mask_mean:\n input_cache[cache_cnt, cu_size:, cu_size:] = 0\n mean = np.sum(input_cache[cache_cnt, :, :]) / float(input_size)\n input_cache[cache_cnt, cu_size:, cu_size:] = mean\n else:\n input_cache[cache_cnt, cu_size:, cu_size:] = 0\n \n label_cache[cache_cnt, :, :] = YY[ly+cu_size:ly+cu_size*2, lx+cu_size:lx+cu_size*2]\n tmp_num = tmp_num + 1\n cache_cnt = cache_cnt + 1\n if cache_cnt == cache_size:\n # print(\"-------->Cache fill, frame: %d, tmpnum: %d\"%(i, tmp_num))\n input_cache = input_cache / 255.0\n label_cache = label_cache / 255.0\n if fid == 0: # create mode\n h5er.write(input_cache, label_cache, create=True)\n fid = 1\n else:\n h5er.write(input_cache, label_cache, create=False)\n cache_cnt = 0\n # print(\"Finish getting data from frame: %d\"%(i))\n" } ]
28
epave/macros-tutorial
https://github.com/epave/macros-tutorial
7d3f1a0314d15e228616c027445dcc9df58a2666
37313f5250d7cf6fb33d7b753b3dbbceb1675e40
fa2799789d489b359ec0b90bea34d7e98d2e9b80
refs/heads/master
2018-12-28T22:28:21.441496
2013-07-14T19:20:22
2013-07-14T19:20:22
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6173912882804871, "alphanum_fraction": 0.6173912882804871, "avg_line_length": 37.66666793823242, "blob_id": "04c8887b277c097902e116bf474f23dc95548c22", "content_id": "bb4140b458a3320c904d02b159c780efb5269dfe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 115, "license_type": "no_license", "max_line_length": 65, "num_lines": 3, "path": "/notebooks/tutorials/__init__.py", "repo_name": "epave/macros-tutorial", "src_encoding": "UTF-8", "text": "__all__ = ['gtapprox', 'gtopt', 'gtdr', 'gtive', 'gtdf', 'gtdoe']\n\nimport gtapprox, gtopt, gtdr, gtive, gtdf, gtdoe" }, { "alpha_fraction": 0.6782224774360657, "alphanum_fraction": 0.7011240720748901, "avg_line_length": 32.63250732421875, "blob_id": "ea7748cfee8efd4151cbbc53a1c2a3319dc16572", "content_id": "809341e3b2435d832c4c94ab1b00db505fc54bb2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9519, "license_type": "no_license", "max_line_length": 191, "num_lines": 283, "path": "/notebooks/tutorials/gtdoe.py", "repo_name": "epave/macros-tutorial", "src_encoding": "UTF-8", "text": "from da.macros import gtdoe, gtapprox\nfrom da.macros.loggers import StreamLogger\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport os\nimport random\n\nfrom matplotlib import cm\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom pylab import *\n'''\nDefine the dependency::\n'''\n#[2]\ndef quadraticFunction(points):\n values = []\n for point in points:\n values.append((point[0] - point[1]) ** 2. + 0.3 * (2 * rand() - 1))\n return values\n#[2]\n\n\n'''\nDefine generic function for optimal DoE generation. Note that Model type set to 'quadratic' and the log level set to 'Info'::\n'''\n#[3]\ndef get_doe(number_points, lb, ub, doeType):\n # create generator\n generator = gtdoe.Generator()\n # set logger\n generator.set_logger(StreamLogger())\n\n # set options\n options = {\n 'GTDoE/Technique': 'OptimalDesign',\n 'GTDoE/OptimalDesign/Type': doeType,\n 'GTDoE/OptimalDesign/Model': 'quadratic',\n 'GTDoE/Deterministic': 'yes',\n 'GTDoE/LogLevel': 'Info'\n }\n generator.options.set(options)\n\n result = generator.generate(bounds=(lb, ub), count=number_points)\n points = result.points\n return points\n#[3]\n\n'''\nDefine auxiliary generic function for DoE plotting::\n'''\n\n#[4]\ndef plot_doe(points, technique):\n points = np.array(points)\n\n params = {'legend.fontsize': 26,\n 'legend.linewidth': 2}\n plt.rcParams.update(params)\n\n print \"Plotting figures...\"\n dim = 2\n doeFigure = plt.figure(figsize = (16, 10))\n plt.plot(points[:, 0], points[:, 1], 'o', markersize = 9, label = technique)\n plt.legend(loc = 'best')\n plt.title('Technique: %s' % technique, fontsize = 28)\n plt.xlim(-1.1, 1.1)\n plt.ylim(-1.1, 1.1)\n plt.ylabel('y', fontsize = 26)\n plt.xlabel('x', fontsize = 26)\n name = 'tutorial_gtdoe_' + technique\n plt.savefig(name)\n print 'Plots are saved to %s.png' % os.path.join(os.getcwd(), name)\n#[4]\n\n'''\nDefine function for full grid generation (for plotting purposes)::\n'''\n\n#[5]\n# get test data with 2D-grid\ndef getTestData(targetFunction, meshGrid):\n [x, y] = np.meshgrid(meshGrid, meshGrid)\n points = np.ones((np.prod(y.shape), 2))\n points[:, 0] = np.reshape(x, np.prod(x.shape), 1)\n points[:, 1] = np.reshape(y, np.prod(x.shape), 1)\n\n values = targetFunction(points)\n\n return points, values\n#[5]\n\n'''\nDefine random DoE generation function::\n'''\n\n#[6]\ndef executeRandomDoE(numberPoints, dimension):\n doeGenerator = gtdoe.Generator()\n doeGenerator.options.set('GTDoE/Seed', '101')\n doeGenerator.options.set('GTDoE/Deterministic', True)\n doeGenerator.options.set('GTDoE/Technique', 'RandomSeq')\n\n bounds = ([-1. for _ in xrange(dimension)], [1. for _ in xrange(dimension)])\n\n points = doeGenerator.generate(bounds=bounds, count=numberPoints).points\n\n return np.array(points)\n#[6]\n\n\n'''\nDefine function for plotting and saving the resulting approximations.\nThe first 3D plot corresponds to true function, the second one is approximation abtained using random design, the third -- obtained using I-optimal design, the last -- using D-optimal design.\n'''\n#[7]\ndef plotResults(iOptimalModel, dOptimalModel, randomModel,\n trainPoints1, trainValues1, trainPoints2, trainValues2,randomPoints, randomValues):\n '''\n Generate test set to compare performance:\n '''\n figsize(16,10)\n targetFunction = quadraticFunction\n zeroValues = [0] * len(trainPoints1)\n trainPoints1 = np.array(trainPoints1)\n trainPoints2 = np.array(trainPoints2)\n # Get test set\n meshSize = 30\n meshGrid = np.linspace(-1, 1, meshSize)\n testPoints, testValues = getTestData(targetFunction, meshGrid)\n\n randomTestValues = randomModel.calc(testPoints)\n\n # Get values for test set\n iOptimalValues = iOptimalModel.calc(testPoints)\n dOptimalValues = dOptimalModel.calc(testPoints)\n\n # Plot results using three subplots\n figureHandle = plt.figure(figsize = (16, 10))\n [x, y] = np.meshgrid(meshGrid, meshGrid)\n\n\n # True function\n rect = figureHandle.add_subplot(2, 2, 1).get_position()\n ax = Axes3D(figureHandle, rect)\n z = (np.array(testValues).reshape(meshSize, meshSize)).transpose()\n ax.plot_surface(x, y, z, rstride=1, cstride=1, cmap=cm.jet)\n plt.title('True function')\n\n # Random design and approximation\n rect = figureHandle.add_subplot(2, 2, 2).get_position()\n ax = Axes3D(figureHandle, rect)\n z = (np.array(randomTestValues).reshape(meshSize, meshSize)).transpose()\n ax.plot_surface(x, y, z, rstride=1, cstride=1, cmap=cm.jet)\n ax.plot3D(randomPoints[:, 0], randomPoints[:, 1], zeroValues, 'o', markersize = 6.0)\n plt.title('Random design and approximation')\n\n # D-optimal design and approximation\n rect = figureHandle.add_subplot(2, 2, 3).get_position()\n ax = Axes3D(figureHandle, rect)\n z = (np.array(dOptimalValues).reshape(meshSize, meshSize)).transpose()\n ax.plot_surface(x, y, z, rstride=1, cstride=1, cmap=cm.jet)\n ax.plot3D(trainPoints1[:, 0], trainPoints1[:, 1], zeroValues, 'o', markersize = 6.0)\n plt.title('D-optimal design and approximation')\n\n # IV-optimal design and approximation\n rect = figureHandle.add_subplot(2, 2, 4).get_position()\n ax = Axes3D(figureHandle, rect)\n z = (np.array(iOptimalValues).reshape(meshSize, meshSize)).transpose()\n ax.plot_surface(x, y, z, rstride=1, cstride=1, cmap=cm.jet)\n ax.plot3D(trainPoints2[:, 0], trainPoints2[:, 1], zeroValues, 'o', markersize = 6.0)\n plt.title('IV-optimal design and approximation')\n#[7]\n\n\n# generate initial train data\ndef getInitialData(targetFunction):\n #initialPoints = np.array([0.0111, 0.2718, 0.4383, 0.7511, 0.9652])\n initialPoints = [[0.0111], [0.2718], [0.4383], [0.7511], [0.9652]]\n #initialValues = targetFunction(initialPoints)\n initialValues = targetFunction(initialPoints)\n return initialPoints, initialValues\n\ndef trainGpModel(trainPoints, trainValues):\n # create builder\n builder = gtapprox.Builder()\n # setup options\n options = {\n 'GTApprox/Technique': 'GP',\n 'GTApprox/LogLevel': 'Fatal',\n 'GTApprox/AccuracyEvaluation': 'On'\n }\n builder.options.set(options)\n # train GT Approx GP model\n return builder.build(trainPoints, trainValues)\n\n# build approximation models\ndef executeAdaptiveDoE(initialPoints, initialValues, numberNewPoints, targetFunction):\n '''\n To perform adaptive DoE technique we need to create blackbox for target function\n '''\n\n print 'Create blackbox for target function'\n # set blackbox\n targetFunctionBlackBox = TargetBlackBox(targetFunction)\n\n\n print 'Perform adaptive DoE process using Maximum Variance criterion'\n # perform adaptive DoE process\n doeGenerator = gtdoe.Generator()\n\n trainPoints = doeGenerator.generate(budget=numberNewPoints, bounds=([0.0], [1.0]),\n init_x = initialPoints, init_y = initialValues,\n blackbox = targetFunctionBlackBox,\n options={'GTDoE/Deterministic' : 'on',\n 'GTDoE/Adaptive/Criterion': 'MaximumVariance'}).points #IntegratedMseGainMaxVar\n\n trainValues = targetFunction(trainPoints)\n\n return trainPoints, trainValues\n\n\n# generate test data\ndef getTestDataAdaptive(numberTestPoints, targetFunction):\n points = np.reshape(np.linspace(0., 1., numberTestPoints), (numberTestPoints, 1))\n\n listPoints = []\n for point in points:\n listPoints.append(list(point))\n\n points = listPoints\n values = targetFunction(points)\n\n return points, values\n\n# compare techniques performance\ndef getResults(trainPoints, trainValues, targetFunction, numberTestPoints):\n\n # get test set\n testPoints, testValues = getTestDataAdaptive(numberTestPoints, targetFunction)\n\n print 'Construct approximations using points, obtained by adaptive DoE'\n numberInitialPoints = 5;\n numberPoints = len(trainPoints)\n numberNewPoints = numberPoints - numberInitialPoints\n\n # calculate approximation for test points for each iteration of DoE\n print ('=' * 60), '\\n'\n print 'Compare approximation quality using 1D approximation plot'\n print 'Plot approximations for every iteration of adaptive DoE algorithm...'\n for currentPointIndex in range(numberNewPoints):\n print currentPointIndex\n currentTrainPoints = trainPoints[0:(numberInitialPoints + currentPointIndex)]\n currentTrainValues = trainValues[0:(numberInitialPoints + currentPointIndex)]\n\n currentGpModel = trainGpModel(currentTrainPoints, currentTrainValues)\n\n currentPredictedValues = currentGpModel.calc(testPoints)\n\n currentAe = currentGpModel.calc_ae(testPoints)\n\n\n # plot results\n params = {'legend.fontsize': 20,\n 'legend.linewidth': 2}\n plt.rcParams.update(params)\n\n figureHandle = figure()\n trainPointsLine, = plot(currentTrainPoints, currentTrainValues, 'ob', markersize = 7.0, linewidth = 2.0)\n trueFunctionLine, = plot(testPoints, testValues, 'b', linewidth = 2.0)\n predictedLine, = plot(testPoints, currentPredictedValues, 'r', linewidth = 2.0)\n aeLine, = plot(testPoints, currentAe - 10, 'g', linewidth = 2.0)\n newPointLine, = plot(trainPoints[numberInitialPoints + currentPointIndex],\n trainValues[numberInitialPoints + currentPointIndex],\n 'or', markersize = 7.0, linewidth = 2.0)\n xlabel(r'$x$', fontsize = 30)\n ylabel(r'$y(x)$', fontsize = 30)\n grid(True)\n plt.legend((trainPointsLine, newPointLine, trueFunctionLine, predictedLine, aeLine),\n ('TrainPoints', 'NewPoint', 'TrueFunction', 'Approximation', 'AccuracyEvaluation'), 'upper left')\n\n plt.title(\"$f(x) = (6 x - 2)^2 \\sin(12 x - 4)$, \" + str(currentPointIndex + 1) + \" $iteration$\", fontsize = 26)\n\n" }, { "alpha_fraction": 0.7432432174682617, "alphanum_fraction": 0.7432432174682617, "avg_line_length": 36, "blob_id": "4683ebc2410a96c4ed55d2ef4d5c05e8ee864616", "content_id": "4d2dd61a1d9902829cf7c355957e8858fa604df4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 148, "license_type": "no_license", "max_line_length": 112, "num_lines": 4, "path": "/README.md", "repo_name": "epave/macros-tutorial", "src_encoding": "UTF-8", "text": "Macross Tutorial\n================\n\nTutorial materials for MACROS Training Session. Includes tutorials on Generic Tools and introduction to Python.\n" }, { "alpha_fraction": 0.6419019103050232, "alphanum_fraction": 0.6760772466659546, "avg_line_length": 35.378379821777344, "blob_id": "b9c5a430611bafb344265626f77788a5af5f968a", "content_id": "17d4b7a4b22756549417b744419ad0621795c9dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1346, "license_type": "no_license", "max_line_length": 130, "num_lines": 37, "path": "/notebooks/tutorials/gtopt.py", "repo_name": "epave/macros-tutorial", "src_encoding": "UTF-8", "text": "# Copyright (C) Datadvance, 2012\n# GTOpt Tutorial. Auxilary functions\n\nfrom pylab import *\n\ndef my_plotter(result, my_problem):\n plt.clf()\n fig = plt.figure(figsize = (16, 10))\n title = my_problem.__class__.__name__\n plt.title(title)\n\n # generated solutions; values() method returns transposed table\n plt.plot(result.converged.f.values()[0], result.converged.f.values()[1], 'r.', label='Pareto frontier (GTOpt)', markersize = 11)\n # true Pareto frontier\n f1_sample = np.linspace(0, 1, 1000)\n plt.plot(f1_sample, 1 - np.sqrt(f1_sample), label='Pareto frontier (analytical)')\n plt.xlabel('f1')\n plt.ylabel('f2')\n plt.legend()\n\n\ndef my_plotter_gso(result, my_problem, my_result, my_resultGS, true_function):\n plt.clf()\n fig = plt.figure(figsize = (16, 10))\n title = my_problem.__class__.__name__\n plt.title(title)\n\n # generated solutions; values() method returns transposed table\n plt.plot(my_result.optimal.x[0][0], my_result.optimal.f[0][0], 'g.', label='local optimum', markersize = 11)\n plt.plot(my_resultGS.optimal.x[0][0], my_resultGS.optimal.f[0][0], 'r.', label='global optimum', markersize = 11)\n # true Pareto frontier\n test_sample = np.linspace(0, 1, 1000)\n test_f = [true_function(x) for x in test_sample]\n plt.plot(test_sample, test_f, label='true function')\n plt.xlabel('x')\n plt.ylabel('f(x)')\n plt.legend()\n" }, { "alpha_fraction": 0.6354300379753113, "alphanum_fraction": 0.6562901139259338, "avg_line_length": 34.81609344482422, "blob_id": "2296ddaf81247086c78a0dbee87acb3c1b418476", "content_id": "a9f6a0029b9084aef82f7dcb5728b589ff8f2c66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3116, "license_type": "no_license", "max_line_length": 109, "num_lines": 87, "path": "/notebooks/tutorials/gtdr.py", "repo_name": "epave/macros-tutorial", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport sys\nimport os\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom pylab import *\n\ndef f(x):\n return [np.sum(x) * np.sum(x[0:2]), np.sum(x[0:2])**2]\n\ndef conv57to59(afl):\n afl = np.insert(afl, 30, 0)\n afl = np.insert(afl, 58, -afl[0])\n return afl\n\ndef conv59to57(afl):\n afl = np.delete(afl, 29)\n afl = np.delete(afl, 57)\n return afl\n\ndef gen_random_set(minX, maxX, dimension):\n return np.multiply(np.random.rand(dimension), (maxX - minX)*0.8) + minX + 0.1*(maxX-minX)\n\ndef rms(x_one, x_two):\n \"\"\"\n calculate relative root mean square error\n \"\"\"\n return np.sqrt(np.mean(np.abs(np.power(x_one, 2) - np.power(x_two,2))))\n\ndef calculate_errors(values, values_predicted, train_values):\n mean_values = np.tile(np.mean(train_values, axis = 0), (values.shape[0], 1))\n const_error = (np.mean(np.mean((values - mean_values)**2)))**0.5\n\n residuals = np.abs(values - values_predicted)\n RMS = (np.mean(np.mean(residuals**2)))**0.5\n MAE = np.mean(np.mean(residuals))\n print ' - mean absolute error (MAE) is ' + str(MAE) + ';'\n print ' - root-mean-square error (RMS) is ' + str(RMS) + ';'\n print ' - relative root-mean-square error (RRMS) is ' + str(RMS / const_error) + ';\\n'\n\ndef plot_airfoils(ref_points, test_afl, test_afl_reconstr, compressed_dim, path_to_save):\n plt.figure(figsize=(16,10))\n plt.plot(ref_points, test_afl_reconstr, label = 'Red. dim = ' + str(compressed_dim))\n plt.plot(ref_points, test_afl, label = 'Original')\n plt.legend(loc = 'best')\n plt.title('GTDR Reconstructed Airfoil Example')\n plt.savefig(path_to_save, format='png')\n print ' - Plot is saved to %s' % os.path.join(os.getcwd(), path_to_save)\n if not os.environ.has_key('SUPPRESS_SHOW_PLOTS'):\n print 'Close window to continue script.'\n plt.show()\n\ndef comparison_plot(ref_points, new_afl_reconstr, rand_afl, path_to_save):\n plt.figure(figsize=(16,10))\n plt.plot(ref_points, new_afl_reconstr, label = 'generated airfoil')\n plt.plot(ref_points, rand_afl, label = 'random airfoil')\n plt.legend(loc = 'best')\n plt.title('GTDR Generated Airfoil Example')\n plt.savefig(path_to_save, format='png')\n print ' - Plot is saved to %s' % os.path.join(os.getcwd(), path_to_save)\n if not os.environ.has_key('SUPPRESS_SHOW_PLOTS'):\n print 'Close window to continue script.'\n plt.show()\n\ndef rrms(x_one, x_two):\n \"\"\"\n calculate relative root mean square error\n \"\"\"\n return np.sqrt(np.mean(np.abs(np.power(x_one, 2) - np.power(x_two,2)))) / (np.max(x_two) - np.min(x_two))\n\ndef scatter_plot(xs, ys, zs, path_to_save):\n fig = plt.figure(figsize=(16,10))\n ax = Axes3D(fig)\n\n sc = ax.scatter(xs, ys, zs, c='r', marker='o')\n\n ax.set_xlabel(r'$t_1$', fontsize = 20)\n ax.set_ylabel(r'$t_2$', fontsize = 20)\n ax.set_zlabel('F', fontsize = 20)\n #plt.grid(True)\n\n plt.suptitle('Compressed points space',fontsize = 25)\n plt.savefig(path_to_save, format='png')\n print ' - Plot is saved to %s' % os.path.join(os.getcwd(), path_to_save)\n if not os.environ.has_key('SUPPRESS_SHOW_PLOTS'):\n print 'Close window to continue script.'\n plt.show()\n" } ]
5
tr0bins0n/github_test
https://github.com/tr0bins0n/github_test
11be5007e650b055e7beda7c212d050222545cb9
9f94b3c58176e838f8fbf9bb7b5210568369b0cd
d62efb557babfa48ab40009c9f603d14d5217995
refs/heads/master
2021-01-01T17:24:00.254011
2017-07-22T23:10:00
2017-07-22T23:10:00
98,062,689
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5155807137489319, "alphanum_fraction": 0.5580736398696899, "avg_line_length": 17.61111068725586, "blob_id": "af13af26b4d9bb60ad699494c43cd9c7a2b450c2", "content_id": "2f63490a72fed7098c613ac7d3a17ed40dbcf48a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 353, "license_type": "no_license", "max_line_length": 67, "num_lines": 18, "path": "/github_test.py", "repo_name": "tr0bins0n/github_test", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jul 22 17:59:21 2017\r\n\r\n@author: robin\r\n\"\"\"\r\n\r\n\r\ndef githubtest_func(key):\r\n if key == 1:\r\n print('This is a function for Hello World to github')\r\n else:\r\n print('This is STILL a function for Hello World to github')\r\n \r\ndef main(key):\r\n githubtest_func(key)\r\n \r\nmain(2)\r\n" } ]
1
nobodyh/Project-Euler
https://github.com/nobodyh/Project-Euler
c8fab6d06b882b4400216ecd103e6581a02209e7
0aab22a6ce385e88bcb67e5a08262947a6b8ec73
6771d2f5f1a0925d9b6daa2b9079559f05ff5b95
refs/heads/main
2023-04-07T09:59:55.851851
2021-04-02T08:10:43
2021-04-02T08:10:43
353,947,754
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5611814260482788, "alphanum_fraction": 0.6012658476829529, "avg_line_length": 15.629630088806152, "blob_id": "a614407fc564e1440b8f018b6e62db0b0149288d", "content_id": "fcb5a574209652fe99a300564b756d3a412d1d73", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 474, "license_type": "no_license", "max_line_length": 70, "num_lines": 27, "path": "/17. Number Letter Count.py", "repo_name": "nobodyh/Project-Euler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 30 21:54:21 2021\r\n\r\n@author: Hayagreev\r\n\"\"\"\r\n\r\nimport time\r\nfrom quantiphy import Quantity as q\r\nfrom num2words import num2words\r\n\r\n\r\n\r\nt_o = time.time()\r\n\r\nn = int(input(\"Enter the limit: \"))\r\nresult = 0\r\nfor i in range(1,n + 1):\r\n result+=(len(''.join(''.join(num2words(i).split('-')).split(' '))))\r\n\r\nprint(\"Result: \",result)\r\n\r\nt = time.time()\r\n\r\nexecution_time = t-t_o\r\n\r\nprint(\"Execution Time:\",q(execution_time,'s'))" }, { "alpha_fraction": 0.4404567778110504, "alphanum_fraction": 0.5040783286094666, "avg_line_length": 14.621622085571289, "blob_id": "241411d22ae78c34f8b8791d4b581269200574bf", "content_id": "3e0463668f1a6e86d981400c484ac785f9431f82", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 613, "license_type": "no_license", "max_line_length": 166, "num_lines": 37, "path": "/2. Even Fibonacci numbers.py", "repo_name": "nobodyh/Project-Euler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 30 11:15:44 2021\r\n\r\n@author: Hayagreev\r\n\"\"\"\r\nimport numpy as np\r\n\r\ndef Fn(n):\r\n return int(np.multiply(np.divide(1,np.sqrt(5)),np.subtract(np.power((np.divide(np.add(1,np.sqrt(5)),2)),n),np.power((np.divide(np.subtract(1,np.sqrt(5)),2)),n))))\r\n\r\nsum=0\r\na,b,c,d=1,1,1,0\r\n\r\nF=[[a,b],[c,d]]\r\n\r\n#a: F_(n+1)\r\n#b: F_n\r\n#c: F_n\r\n#d: F_(n-1)\r\n\r\nn=int(input(\"Enter the nth value:\"))\r\n\r\nfor i in range(n-1):\r\n F=np.matmul(F,F)\r\n F_n=Fn(i)\r\n \r\n if F_n%2==0:\r\n sum+=F_n\r\n\r\n#print(\"F_(n):\",F[1,0],\"F_(n-1):\",F[1,1],\"F_(n+1):\",F[0,0])\r\n\r\n\r\n\r\n\r\n\r\nprint(sum)" }, { "alpha_fraction": 0.4688715934753418, "alphanum_fraction": 0.5097275972366333, "avg_line_length": 15.793103218078613, "blob_id": "6345fe3af6fba2181c920d185c7e8377ca11ddae", "content_id": "b47ac15c8fa5814bb7def09f95b17efe93cc2583", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 514, "license_type": "no_license", "max_line_length": 42, "num_lines": 29, "path": "/3. Largest Prime Factor.py", "repo_name": "nobodyh/Project-Euler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 30 13:31:01 2021\r\n\r\n@author: Hayagreev\r\n\"\"\"\r\nimport numpy as np\r\ndef Prime_Factors(x):\r\n factors=[]\r\n \r\n while x%2==0:\r\n factors.append(2)\r\n x/= 2\r\n \r\n for i in range(3,int(np.sqrt(x))+1,2):\r\n \r\n while x%i==0:\r\n factors.append(i)\r\n x/= i\r\n \r\n return factors\r\n\r\nx = int(input(\"Enter a number: \"))\r\n\r\nfactors = Prime_Factors(x)\r\n\r\nmax_factor = max(factors)\r\n\r\nprint(\"Maximum Factor: \",max_factor)" }, { "alpha_fraction": 0.4556961953639984, "alphanum_fraction": 0.47960618138313293, "avg_line_length": 13.5, "blob_id": "0617474a1bbb431d5906e5b70be7b3f74508a17f", "content_id": "3e80fddd5426f8e967e2f6faf107bb39d4e314ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 711, "license_type": "no_license", "max_line_length": 56, "num_lines": 46, "path": "/21. Amicable Numbers.py", "repo_name": "nobodyh/Project-Euler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 30 20:50:03 2021\r\n\r\n@author: Hayagreev\r\n\"\"\"\r\n\r\nimport time\r\nfrom quantiphy import Quantity as q\r\n\r\n\r\ndef SD(x):\r\n \r\n sum = 0\r\n \r\n for i in range(1,x):\r\n if(x%i)==0:\r\n sum+= i\r\n \r\n return sum\r\n\r\nt_o = time.time()\r\n\r\n\r\nresult = []\r\n\r\nn = int(input(\"Enter the limit:\"))\r\n\r\nfor i in range(1,n):\r\n a=i\r\n da=SD(i)\r\n b=da\r\n db=SD(b)\r\n \r\n if (da==b and db==a and a!=b):\r\n if([a,b] not in result and [b,a] not in result):\r\n print(\"a:\",a,\" and b:\",b)\r\n result.append([a,b])\r\n \r\nprint(result)\r\n\r\nt = time.time()\r\n\r\nexecution_time = t-t_o\r\n\r\nprint(\"Execution Time:\",q(execution_time,'s'))" }, { "alpha_fraction": 0.3756345212459564, "alphanum_fraction": 0.4974619150161743, "avg_line_length": 12.214285850524902, "blob_id": "dbc52e3e5407127c3f65b447902bf014193ae9cd", "content_id": "62401eabdfee435768a56e5437fa6a4a250c8cfa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 197, "license_type": "no_license", "max_line_length": 35, "num_lines": 14, "path": "/1. Multiples of 3 and 5.py", "repo_name": "nobodyh/Project-Euler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 30 11:13:40 2021\r\n\r\n@author: Hayagreev\r\n\"\"\"\r\n\r\nsum=0\r\n\r\nfor i in range(1,1000,1):\r\n if (i%3)==0 or (i%5)==0:\r\n sum+=i\r\n\r\nprint('Sum:',sum)" }, { "alpha_fraction": 0.396843284368515, "alphanum_fraction": 0.4284103810787201, "avg_line_length": 13.596490859985352, "blob_id": "95124c081f61d0c1b43876875074d9b5c002c1a3", "content_id": "06eeab9b68252268057f8fab2310c8fce63fe09f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 887, "license_type": "no_license", "max_line_length": 49, "num_lines": 57, "path": "/14. Longest Seq.py", "repo_name": "nobodyh/Project-Euler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Mar 31 09:35:11 2021\r\n\r\n@author: Hayagreev\r\n\"\"\"\r\n\r\nimport time\r\nfrom quantiphy import Quantity as q\r\n\r\n\r\n\r\n\r\nt_o = time.time()\r\n\r\nmaximum = 0\r\nseq = []\r\nl=[]\r\n\r\nn=int(input(\"Enter the limit: \"))\r\n\r\nfor i in range(n,n+1):\r\n x = i\r\n flag = 0\r\n \r\n in_seq = []\r\n \r\n while (flag == 0):\r\n \r\n if x!=1:\r\n if (x%2!=0):\r\n x = 3*x+1\r\n in_seq.append(x)\r\n \r\n elif (x%2==0):\r\n x = x/2\r\n in_seq.append(x)\r\n \r\n if (x==1):\r\n flag = 1\r\n\r\n seq=[i,len(in_seq)]\r\n l.append(seq)\r\n\r\nfor i in range(len(l)):\r\n if l[i]>maximum:\r\n maximum = i\r\n\r\nprint(\"The Largest Collatz Sequence: \",maximum+1)\r\n\r\n\r\n\r\nt = time.time()\r\n\r\nexecution_time = t-t_o\r\n\r\nprint(\"Execution Time:\",q(execution_time,'s'))" }, { "alpha_fraction": 0.5260416865348816, "alphanum_fraction": 0.5833333134651184, "avg_line_length": 12.449999809265137, "blob_id": "1039be470472462e2f079e3483789e00f4695657", "content_id": "f31c549c0685f50c8c6e52827e90b290f87fd44a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 576, "license_type": "no_license", "max_line_length": 46, "num_lines": 40, "path": "/19. Counting Sundays.py", "repo_name": "nobodyh/Project-Euler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 30 21:43:26 2021\r\n\r\n@author: Hayagreev\r\n\"\"\"\r\n\r\nimport time\r\nfrom quantiphy import Quantity as q\r\nfrom datetime import date\r\n\r\n\r\n\r\nt_o = time.time()\r\n\r\ncount = 0\r\nyear = 1901\r\nmonth = 1\r\n\r\ncurr_day = date(year,month,1)\r\n\r\nwhile(curr_day.year < 2001):\r\n\tif(curr_day.weekday() == 6):\r\n\t\tcount += 1\r\n\tif(month+1 == 13):\r\n\t\tmonth = 1\r\n\t\tyear += 1\r\n\telse:\r\n\t\tmonth += 1\r\n\tcurr_day = date(year,month,1)\r\n\r\nprint(\"count: \" + str(count))\r\n\r\n\r\n\r\nt = time.time()\r\n\r\nexecution_time = t-t_o\r\n\r\nprint(\"Execution Time:\",q(execution_time,'s'))" }, { "alpha_fraction": 0.550000011920929, "alphanum_fraction": 0.5863636136054993, "avg_line_length": 12.258064270019531, "blob_id": "7744706cc637097889ea589aec78ead56adc8b01", "content_id": "6be8584128c3fa32d9967c353ce4e25afb1ada74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 440, "license_type": "no_license", "max_line_length": 46, "num_lines": 31, "path": "/10. Summation of Primes.py", "repo_name": "nobodyh/Project-Euler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 30 19:47:42 2021\r\n\r\n@author: Hayagreev\r\n\"\"\"\r\nfrom sympy import *\r\nimport numpy as np\r\nimport time\r\nfrom quantiphy import Quantity as q\r\n\r\n\r\n\r\n\r\nt_o = time.time()\r\n\r\nn = int(input(\"Enter the limit:\"))\r\n\r\nsum=0\r\n\r\nfor i in range(2,int(n+1)):\r\n if isprime(i):\r\n sum+=i\r\n\r\nprint('Sum:',sum)\r\n\r\nt = time.time()\r\n\r\nexecution_time = t-t_o\r\n\r\nprint(\"Execution Time:\",q(execution_time,'s'))" }, { "alpha_fraction": 0.5508317947387695, "alphanum_fraction": 0.5785582065582275, "avg_line_length": 12.675675392150879, "blob_id": "d713fb173e01daa934ee18a2526c19b1b64d3d3f", "content_id": "1f75a29c1837dad856ca630af1bb76997accb3e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 541, "license_type": "no_license", "max_line_length": 48, "num_lines": 37, "path": "/29. Distinct Powers.py", "repo_name": "nobodyh/Project-Euler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 30 20:15:02 2021\r\n\r\n@author: Hayagreev\r\n\"\"\"\r\n\r\nimport time\r\nfrom quantiphy import Quantity as q\r\n\r\n\r\n\r\nt_o = time.time()\r\n\r\na = int(input(\"Enter lower limit: \"))\r\nb = int(input(\"Enter upper limit: \"))\r\n\r\nl=[]\r\n\r\nfor x in range(a,b+1):\r\n for y in range(a,b+1):\r\n l.append(x**y)\r\n\r\nresult=[]\r\n\r\n[result.append(i) for i in l if i not in result]\r\n\r\nresult.sort()\r\n\r\nprint(\"Result:\",result)\r\n\r\n\r\nt = time.time()\r\n\r\nexecution_time = t-t_o\r\n\r\nprint(\"Execution Time:\",q(execution_time,'s'))" }, { "alpha_fraction": 0.5397815704345703, "alphanum_fraction": 0.5803431868553162, "avg_line_length": 16.371429443359375, "blob_id": "b1251191324e76a9dc30c1633ba3b1663fb3e1a4", "content_id": "bc596178dc9084065b690d5ca944cd7158327353", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 641, "license_type": "no_license", "max_line_length": 168, "num_lines": 35, "path": "/25. 1000-digit Fibonacci Number.py", "repo_name": "nobodyh/Project-Euler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 30 20:25:58 2021\r\n\r\n@author: Hayagreev\r\n\"\"\"\r\n\r\nimport time\r\nimport numpy as np\r\nfrom quantiphy import Quantity as q\r\n\r\n\r\ndef Fn(x):\r\n return (int(np.multiply(np.divide(1,np.sqrt(5)),np.subtract(np.power((np.divide(np.add(1,np.sqrt(5)),2)),x),np.power((np.divide(np.subtract(1,np.sqrt(5)),2)),x)))))\r\n\r\nt_o = time.time()\r\n\r\nflag=0\r\ni=1\r\n\r\ndigit=int(input(\"Enter the digit size:\"))\r\n\r\nwhile flag!=1:\r\n if(len(str(Fn(i)))==digit):\r\n flag = 1\r\n break\r\n i+= 1\r\n \r\nprint(i) \r\n\r\nt = time.time()\r\n\r\nexecution_time = t-t_o\r\n\r\nprint(\"Execution Time:\",q(execution_time,'s'))" }, { "alpha_fraction": 0.5279069542884827, "alphanum_fraction": 0.5604650974273682, "avg_line_length": 11.935483932495117, "blob_id": "c99751e596a0a1468b2b646f5d5831d0e6f91181", "content_id": "e84083dfcf60cf35b364b59fceb5be55251b3d92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 430, "license_type": "no_license", "max_line_length": 46, "num_lines": 31, "path": "/16. Power Digit Sum.py", "repo_name": "nobodyh/Project-Euler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 30 21:59:53 2021\r\n\r\n@author: Hayagreev\r\n\"\"\"\r\n\r\nimport time\r\nfrom quantiphy import Quantity as q\r\n\r\n\r\n\r\n\r\nt_o = time.time()\r\n\r\na = int(input(\"Enter a:\"))\r\nb = int(input(\"Enter b:\"))\r\n\r\nsum = 0\r\nx = list(map(int,str(a**b)))\r\n\r\nfor i in range(len(x)):\r\n sum+= x[i]\r\n\r\nprint(\"Sum: \",sum)\r\n\r\nt = time.time()\r\n\r\nexecution_time = t-t_o\r\n\r\nprint(\"Execution Time:\",q(execution_time,'s'))" }, { "alpha_fraction": 0.5120000243186951, "alphanum_fraction": 0.5329999923706055, "avg_line_length": 18.83333396911621, "blob_id": "af0b7077d1b3ab118757e7a0708861170942eca9", "content_id": "70075516d8f19e59003af6d8f1fae5a4f0ddf320", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1000, "license_type": "no_license", "max_line_length": 84, "num_lines": 48, "path": "/36. Double-Base Palindromes.py", "repo_name": "nobodyh/Project-Euler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Mar 31 11:19:07 2021\r\n\r\n@author: Hayagreev\r\n\"\"\"\r\nimport time\r\nfrom quantiphy import Quantity as q\r\n\r\ndef isPalindrome(s):\r\n\r\n # Using predefined function to\r\n # reverse to string print(s)\r\n rev_decimal = ''.join(reversed(str(s)))\r\n rev_binary = ''.join(reversed(bin(int(s)).replace(\"0b\", \"\")))\r\n \r\n #print(\"s:\",s,\" r_s:\",rev_decimal)\r\n #print(\"Binary: \",bin(int(s)).replace(\"0b\", \"\"),\" R_B: \",rev_binary)\r\n # Checking if both string are\r\n # equal or not\r\n if (str(s) == rev_decimal and str(bin(s).replace(\"0b\", \"\")) == str(rev_binary)):\r\n #print(\"Yes\")\r\n return 1\r\n else:\r\n #print(\"No\")\r\n return 0\r\n\r\n\r\nt_o = time.time()\r\n\r\nn = int(input(\"Enter the limit: \"))\r\n\r\nsum = 0\r\n\r\nfor i in range(1,n):\r\n \r\n flag = isPalindrome(i)\r\n \r\n if (flag == 1):\r\n sum+= i\r\n\r\nprint(\"Sum: \",sum)\r\n\r\nt = time.time()\r\n\r\nexecution_time = t-t_o\r\n\r\nprint(\"Execution Time:\",q(execution_time,'s'))\r\n" }, { "alpha_fraction": 0.5493420958518982, "alphanum_fraction": 0.6151315569877625, "avg_line_length": 20.923076629638672, "blob_id": "e0673e5ac586c1d357a14a36818e6058f7926529", "content_id": "e4facb447ce23e07e772652da7b65694d1abffcd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 304, "license_type": "no_license", "max_line_length": 116, "num_lines": 13, "path": "/6. Sum Square Difference.py", "repo_name": "nobodyh/Project-Euler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 30 14:14:26 2021\r\n\r\n@author: Hayagreev\r\n\"\"\"\r\nimport numpy as np\r\n\r\nn=int(input(\"Enter the limit:\"))\r\n\r\nresult = np.subtract(np.power(np.divide(np.multiply(n,n+1),2),2),np.divide(np.multiply(n,np.multiply(n+1,2*n+1)),6))\r\n\r\nprint(\"Result: \",result)\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.4911433160305023, "alphanum_fraction": 0.52173912525177, "avg_line_length": 18.09677505493164, "blob_id": "c643418430af133ec5bd7519e3de3bbf234c94bd", "content_id": "8442a0a1ea8dc4957d741a694439d22ec6d42a25", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 621, "license_type": "no_license", "max_line_length": 56, "num_lines": 31, "path": "/9. Special Pythagorean Triplet.py", "repo_name": "nobodyh/Project-Euler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 30 19:38:45 2021\r\n\r\n@author: Hayagreev\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport time\r\nfrom quantiphy import Quantity as q\r\n\r\nt_o = time.time()\r\n\r\nsum = int(input(\"Enter the sum limit:\"))\r\nresult = int(0)\r\nfor a in range(3,sum):\r\n for b in range(a+1,sum-1):\r\n c = np.sqrt(np.add(np.power(a,2),np.power(b,2)))\r\n \r\n if (a+b+c == sum):\r\n result = a*b*c\r\n break\r\n \r\nprint('a: ',a,' b: ',b,' c: ',c)\r\nprint('Result:',result) \r\n\r\nt = time.time()\r\n\r\nexecution_time = t-t_o\r\n\r\nprint(\"Execution Time:\",q(execution_time,'s'))" }, { "alpha_fraction": 0.4310189485549927, "alphanum_fraction": 0.4679891765117645, "avg_line_length": 18.200000762939453, "blob_id": "36d17fdad36b7cd5f74a837dba8fb5813536217a", "content_id": "ab8b514994af651a4de02c1403d10450bfbc2d83", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1109, "license_type": "no_license", "max_line_length": 54, "num_lines": 55, "path": "/27. Quadratic Primes.py", "repo_name": "nobodyh/Project-Euler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Mar 31 14:09:53 2021\r\n\r\n@author: Hayagreev\r\n\"\"\"\r\nimport time\r\nimport math\r\nfrom quantiphy import Quantity as q\r\n\r\n\r\n\r\n\r\nt_o = time.time()\r\n\r\n\r\n\r\ndef longestPrimeQuadratic(alim, blim):\r\n\r\n def isPrime(k): # checks if a number is prime\r\n if k < 2: return False\r\n elif k == 2: return True\r\n elif k % 2 == 0: return False\r\n else: \r\n for x in range(3, int(math.sqrt(k)+1), 2):\r\n if k % x == 0: return False\r\n\r\n return True \r\n\r\n longest = [0, 0, 0] # length, a, b\r\n for a in range((alim * -1) + 1, alim):\r\n for b in range(2, blim):\r\n if isPrime(b):\r\n count = 0\r\n n = 0\r\n while isPrime((n**2) + (a*n) + b):\r\n count += 1\r\n n += 1\r\n\r\n if count > longest[0]:\r\n longest = [count, a, b]\r\n \r\n print(a*b)\r\n return longest\r\n\r\nans = longestPrimeQuadratic(1000, 1000)\r\n\r\n\r\n\r\n\r\nt = time.time()\r\n\r\nexecution_time = t-t_o\r\n\r\nprint(\"Execution Time:\",q(execution_time,'s'))" }, { "alpha_fraction": 0.5448430776596069, "alphanum_fraction": 0.5762332081794739, "avg_line_length": 12.933333396911621, "blob_id": "2b9818fdd8aa61f4eb2a37087af7b118a3795fb8", "content_id": "dbcff72b897a7a0294e7c116f887fd7f9bb970b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 446, "license_type": "no_license", "max_line_length": 46, "num_lines": 30, "path": "/20. Factorial Digit Sum.py", "repo_name": "nobodyh/Project-Euler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 30 21:33:34 2021\r\n\r\n@author: Hayagreev\r\n\"\"\"\r\n\r\nimport time\r\nfrom quantiphy import Quantity as q\r\nimport math\r\n\r\n\r\n\r\nt_o = time.time()\r\n\r\nn=int(input(\"Enter a number: \"))\r\n\r\nsum = 0\r\n\r\nN = list(map(int,str(math.factorial(n))))\r\n\r\nfor i in range(len(N)):\r\n sum+= N[i]\r\n \r\nprint(\"Sum of \",n,\"!:\",sum)\r\nt = time.time()\r\n\r\nexecution_time = t-t_o\r\n\r\nprint(\"Execution Time:\",q(execution_time,'s'))" }, { "alpha_fraction": 0.3662119507789612, "alphanum_fraction": 0.3997901380062103, "avg_line_length": 19.545454025268555, "blob_id": "6b7959975b5abd3ae8083658f91b6d0b7befa491", "content_id": "e982b978fea336d575f9e609a7f55e37abcb0db2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 953, "license_type": "no_license", "max_line_length": 72, "num_lines": 44, "path": "/4. Largest Palindrome Product.py", "repo_name": "nobodyh/Project-Euler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 30 13:48:24 2021\r\n\r\n@author: Hayagreev\r\n\"\"\"\r\n\r\ndef LP(n):\r\n UL = (10**n)-1\r\n \r\n LL = 1+UL//10\r\n \r\n max_product=0\r\n \r\n for i in range(UL,LL-1,-1):\r\n \r\n for j in range(i,LL-1,-1):\r\n \r\n product = i*j\r\n \r\n if product<max_product:\r\n break\r\n \r\n number = product\r\n \r\n reverse=0\r\n \r\n while(number!=0):\r\n \r\n reverse = reverse*10 + number%10\r\n \r\n number = number//10\r\n \r\n if (product == reverse and product>max_product):\r\n \r\n max_product = product\r\n\r\n return i,j,max_product\r\n\r\nn=int(input(\"Enter the n-digit value to determine Largest Palindrome:\"))\r\n\r\na,b,Result=LP(n)\r\n\r\nprint(\"a:\",a,\"\\nb:\",b,\"\\nProduct:\",Result) " }, { "alpha_fraction": 0.4576856791973114, "alphanum_fraction": 0.4922279715538025, "avg_line_length": 11.833333015441895, "blob_id": "526f05f4aaf2b13a2d0300df3be4e98eff25316a", "content_id": "97eb69532e13adb3040d155decd0d59fbcec2fc2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 579, "license_type": "no_license", "max_line_length": 46, "num_lines": 42, "path": "/30. Digit Fifth Powers.py", "repo_name": "nobodyh/Project-Euler", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 30 20:01:26 2021\r\n\r\n@author: Hayagreev\r\n\"\"\"\r\n\r\nimport time\r\nfrom quantiphy import Quantity as q\r\n\r\n\r\n\r\n\r\nt_o = time.time()\r\n\r\nn = int(input(\"Enter the Digit Power: \"))\r\nsum = 0\r\ni=1\r\nwhile (i<(10**n)):\r\n \r\n digit_sum = 0\r\n \r\n j = list(str(i))\r\n \r\n for k in j:\r\n digit = int(k)**n\r\n digit_sum+= digit\r\n \r\n if digit_sum == i:\r\n sum+=i\r\n print(i)\r\n i+= 1\r\n\r\nsum-= 1\r\n \r\nprint(sum)\r\n\r\nt = time.time()\r\n\r\nexecution_time = t-t_o\r\n\r\nprint(\"Execution Time:\",q(execution_time,'s'))" }, { "alpha_fraction": 0.4114114046096802, "alphanum_fraction": 0.462462455034256, "avg_line_length": 10.884614944458008, "blob_id": "991417cc5ffad8e80ed85342b788ae01c950c91a", "content_id": "4f7096b083bf0e144396f789267ad58c07dcab5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 333, "license_type": "no_license", "max_line_length": 53, "num_lines": 26, "path": "/5. Smallest Multiple.py", "repo_name": "nobodyh/Project-Euler", "src_encoding": "UTF-8", "text": "2# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 30 14:03:24 2021\r\n\r\n@author: Hayagreev\r\n\"\"\"\r\nimport math\r\n\r\ndef LCM(n):\r\n \r\n ans = 1\r\n \r\n for i in range(1,n+1):\r\n \r\n ans = int((ans * i)/math.gcd(ans, i)) \r\n \r\n return ans\r\n\r\n\r\nn=int(input(\"Enter n:\"))\r\n\r\nresult=LCM(n)\r\n\r\n \r\n\r\nprint(result)" } ]
19
lehy/shufflenet-v2-chainer
https://github.com/lehy/shufflenet-v2-chainer
e42feaaf8a480b15730f62a55163793bda92a7c3
1ac313328f30b12d61243daf9e6e5a5fffe82c0d
d82deedbff9587be6d0745101f23152b07c1f518
refs/heads/master
2020-04-04T17:33:56.490012
2019-03-14T08:35:53
2019-03-14T08:35:53
156,125,837
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5341781973838806, "alphanum_fraction": 0.554147481918335, "avg_line_length": 37.29411697387695, "blob_id": "4b6a0b10b7ae526f1ab3ddffc1a6abb95ae9fbbc", "content_id": "a894f6affe55625105069cd6c85f6128ac5c3a46", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2604, "license_type": "permissive", "max_line_length": 96, "num_lines": 68, "path": "/openimages/demo.py", "repo_name": "lehy/shufflenet-v2-chainer", "src_encoding": "UTF-8", "text": "import chainer\nimport shufflenet_v2\nimport chainertools\nimport cv2\nimport numpy as np\nimport time\n\n\ndef main(args):\n with chainer.using_config('train', False):\n with chainer.using_config('enable_backprop', False):\n snapshot_file = args.snapshot\n label_encoder = chainertools.openimages.openimages_label_encoder(\n \".\")\n k = shufflenet_v2.guess_k(snapshot_file)\n net = shufflenet_v2.ShuffleNetV2(k, label_encoder.num_classes())\n chainer.serializers.load_npz(\n snapshot_file, net, \"updater/model:main/predictor/\")\n if args.gpu >= 0:\n net.to_gpu(args.gpu)\n\n camera_id = -1\n camera = cv2.VideoCapture(camera_id)\n dt_filtered = 0.\n alpha = 0.1\n while True:\n success, frame = camera.read()\n if not success:\n raise RuntimeError(\"could not read frame from camera\")\n\n t0 = time.time()\n frame_small_orig = cv2.resize(frame, (224, 224))\n frame_small = cv2.cvtColor(frame_small_orig, cv2.COLOR_BGR2RGB)\n frame_small = np.transpose(frame_small, (2, 0, 1))\n input = net.xp.asarray([frame_small], dtype=np.float32)\n # print(input.shape, input)\n output = net(input)\n output = chainer.functions.sigmoid(output)\n output = chainer.cuda.to_cpu(output.data[0])\n t1 = time.time()\n\n labels_idx = np.where(output > 0.5)[0]\n readable_labels = [label_encoder.readable_label_of_encoded_label(\n lab) for lab in labels_idx]\n\n dt = t1 - t0\n dt_filtered = alpha * dt + (1 - alpha) * dt_filtered\n fps = 1. / dt_filtered\n print(\"{:.2f} fps\".format(fps))\n print(list(zip(readable_labels, output[labels_idx])))\n cv2.imshow(snapshot_file, frame)\n cv2.waitKey(1)\n\n\ndef parse_command_line():\n parser = argparse.ArgumentParser(\n description=\"Demonstration of multilabel classification with Shufflenet v2.\")\n parser.add_argument(\n '--gpu', help='Run on gpu (integer id starting at 0) or cpu (-1)', type=int, default=-1)\n parser.add_argument('--snapshot', help='Model snapshot file',\n default=\"shufflenet-v2-snapshots/x1/snapshot_iter_335305\")\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n import argparse\n args = parse_command_line()\n main(args)\n" }, { "alpha_fraction": 0.8097826242446899, "alphanum_fraction": 0.820652186870575, "avg_line_length": 60.33333206176758, "blob_id": "3d11b1ae3a2d6c079d01f487d05f32ce344f9666", "content_id": "f59bf7f190f56be1d5ef20163e5efe4e52e2d155", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 184, "license_type": "permissive", "max_line_length": 154, "num_lines": 3, "path": "/README.md", "repo_name": "lehy/shufflenet-v2-chainer", "src_encoding": "UTF-8", "text": "# Shufflenet V2 for Chainer\n\nThis is an implementation of ShuffleNet V2 in Chainer, with trained snapshots on OpenImages multilabel classification (on the subset with bounding boxes).\n" }, { "alpha_fraction": 0.7611940503120422, "alphanum_fraction": 0.7636815905570984, "avg_line_length": 39.20000076293945, "blob_id": "1eef235bda9ce17d2b7805474cfe79b1cf5b8ef5", "content_id": "09e376df502a5fdaa7e30f3f15cb0cafce818a35", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 402, "license_type": "permissive", "max_line_length": 75, "num_lines": 10, "path": "/openimages/settings.py", "repo_name": "lehy/shufflenet-v2-chainer", "src_encoding": "UTF-8", "text": "import os\n\npersistent_directory = '/home/paperspace'\npublished_directory = '/home/paperspace/public_html'\nfast_directory = '/home/paperspace/'\n\ncold_data_directory = os.path.join(persistent_directory, 'data')\nhot_data_directory = os.path.join(fast_directory, 'data')\nopenimages_directory = os.path.join(hot_data_directory, \"openimages-v4/bb\")\nlog_directory = os.path.join(persistent_directory, 'logs')\n" }, { "alpha_fraction": 0.5436791777610779, "alphanum_fraction": 0.57419353723526, "avg_line_length": 32.246376037597656, "blob_id": "b5aa8feda631bc7c15aa48abb5243774942dfac8", "content_id": "d7f8bb6e1a782def70ff8019360fe40848b140d9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11470, "license_type": "permissive", "max_line_length": 113, "num_lines": 345, "path": "/shufflenet_v2.py", "repo_name": "lehy/shufflenet-v2-chainer", "src_encoding": "UTF-8", "text": "import chainer\nimport chainer.links as L\nimport chainer.functions as F\nimport functools as fun\nimport collections\nimport logging\nimport numpy as np\nlog = logging.getLogger(__name__)\n\n\ndef describe_variable(name, v):\n try:\n shape = v.shape\n except AttributeError:\n shape = \"(?)\" # \"(shape not yet initialized)\"\n return \"{}{}\".format(name, shape)\n\n\ndef describe_element(elt, prefix):\n if hasattr(elt, 'namedparams'):\n params = [\n describe_variable(name, variable)\n for name, variable in elt.namedparams()\n ]\n if len(params) > 2:\n prefix = prefix + ' '\n str_params = \"\\n{}\".format(prefix) + ',\\n{}'.format(prefix).join(\n params)\n else:\n str_params = ', '.join(params)\n return \"{}({})\".format(elt.__class__.__name__, str_params)\n else:\n return str(elt)\n\n\nclass Seq(chainer.Chain):\n def __init__(self, **named_layers):\n chainer.Chain.__init__(self)\n self._layers = collections.OrderedDict()\n for k, v in named_layers.items():\n self.add(k, v)\n\n def add(self, name, layer):\n with self.init_scope():\n if hasattr(self, name):\n raise KeyError(\"sequence {} already has attribute {}\".format(\n self, name))\n setattr(self, name, layer)\n self._layers[name] = layer\n\n def forward(self, x):\n for layer in self._layers.values():\n x = layer(x)\n return x\n\n def to_string(self, prefix=''):\n buf = ''\n for k, v in self._layers.items():\n if isinstance(v, Seq):\n buf += \"{}{}\\n{}\".format(prefix, k,\n v.to_string(prefix=(prefix + ' ')))\n else:\n buf += \"{}{}\\t{}\\n\".format(prefix, k,\n describe_element(v, prefix))\n return buf\n\n def __str__(self):\n return self.to_string()\n\n\nclass BatchNormalization(L.BatchNormalization):\n def __init__(self, *args, **kwargs):\n L.BatchNormalization.__init__(self, *args, **kwargs)\n\n def __call__(self, *args, **kwargs):\n # log.debug(\"batch norm finetune=%s\", finetune)\n if 'finetune' not in kwargs:\n finetune = getattr(chainer.config, 'finetune', False)\n kwargs['finetune'] = finetune\n return L.BatchNormalization.__call__(self, *args, **kwargs)\n\n # problem:\n # - avg_mean and avg_var are initialized at None\n # - when not giving the size to BatchNormalization, they get\n # initialized at the beginning of forward()\n # - but they are always initialized on the cpu, even if one has called\n # to_gpu() on the BN first\n # - so we get an error when running forward if the BN has been moved\n # to gpu, since avg_mean and avg_var are still on cpu\n def _initialize_params(self, shape):\n dtype = self._dtype\n self.avg_mean = self._init_array(self._initial_avg_mean, 0, shape,\n dtype) # Ronan\n self._initial_avg_mean = None\n self.register_persistent('avg_mean')\n self.avg_var = self._init_array(self._initial_avg_var, 1, shape,\n dtype) # Ronan\n self._initial_avg_var = None\n self.register_persistent('avg_var')\n if self.gamma is not None:\n self.gamma.initialize(shape)\n if self.beta is not None:\n self.beta.initialize(shape)\n\n def _init_array(self, initializer, default_value, size, dtype):\n if initializer is None:\n initializer = default_value\n initializer = chainer.initializers._get_initializer(initializer)\n return chainer.initializers.generate_array(\n initializer, size, self.xp, dtype=dtype)\n\n\ndef _1x1_conv_bn_relu(out_channels):\n \"\"\"1x1 Conv + BN + ReLU.\n \"\"\"\n return Seq(\n conv=L.Convolution2D(\n None, out_channels, ksize=1, stride=1, pad=0, nobias=True),\n bn=BatchNormalization(axis=(0, 2, 3)),\n relu=F.relu)\n\n\ndef _3x3_dwconv_bn(stride):\n \"\"\"3x3 DWConv (depthwise convolution) + BN.\n \"\"\"\n return Seq(\n dwconv=L.DepthwiseConvolution2D(\n None,\n channel_multiplier=1,\n ksize=3,\n stride=stride,\n pad=1,\n nobias=True),\n bn=BatchNormalization(axis=(0, 2, 3)))\n\n\nclass ShuffleNetV2BasicBlock(chainer.Chain):\n \"\"\"ShuffleNet v2 basic unit. Split and concat. Fig 3 (c), page 7.\n\n \"\"\"\n\n def __init__(self, out_channels):\n super().__init__()\n with self.init_scope():\n branch_channels = out_channels // 2\n assert 2 * branch_channels == out_channels, (\n \"ShuffleNetV2BasicBlock out_channels must be divisible by 2\")\n # Note that in the basic block the 3x3 dwconv has stride=1.\n self.branch = Seq(\n conv_bn_relu1=_1x1_conv_bn_relu(branch_channels),\n dwconv_bn=_3x3_dwconv_bn(stride=1),\n conv_bn_relu2=_1x1_conv_bn_relu(branch_channels))\n\n def forward(self, x):\n x1, x2 = F.split_axis(x, 2, axis=1)\n x2 = self.branch(x2)\n return channel_shuffle(F.concat((x1, x2), axis=1))\n\n\ndef channel_shuffle(x, groups=2):\n n, c, h, w = x.shape\n x = x.reshape(n, groups, c // groups, h, w)\n x = x.transpose(0, 2, 1, 3, 4)\n x = x.reshape(n, c, h, w)\n return x\n\n\nclass ShuffleNetV2DownsampleBlock(chainer.Chain):\n \"\"\"ShuffleNet v2 unit for spatial downsampling. Fig 3 (d), page 7.\n\n \"\"\"\n\n def __init__(self, out_channels):\n super().__init__()\n with self.init_scope():\n branch_channels = out_channels // 2\n assert 2 * branch_channels == out_channels, (\n \"ShuffleNetV2BasicBlock out_channels must be divisible by 2\")\n # Note that in the downsampling block the 3x3 dwconv has stride=2.\n self.branch1 = Seq(\n dwconv_bn=_3x3_dwconv_bn(stride=2),\n conv_bn_relu=_1x1_conv_bn_relu(branch_channels))\n self.branch2 = Seq(\n conv_bn_relu1=_1x1_conv_bn_relu(branch_channels),\n dwconv_bn=_3x3_dwconv_bn(stride=2),\n conv_bn_relu2=_1x1_conv_bn_relu(branch_channels))\n\n def forward(self, x):\n x1 = self.branch1(x)\n x2 = self.branch2(x)\n return channel_shuffle(F.concat((x1, x2), axis=1))\n\n\ndef ShuffleNetV2Stage(out_channels, repeat):\n assert repeat > 1, \"ShuffleNetV2Stage: repeat must be > 1\"\n\n stage = Seq()\n stage.add('downsample', ShuffleNetV2DownsampleBlock(out_channels))\n for i in range(repeat - 1):\n stage.add('basic{}'.format(i + 1),\n ShuffleNetV2BasicBlock(out_channels))\n\n return stage\n\n\ndef log_size(x, name):\n \"\"\"Insert this in a Sequential to get a debug output of the input size\n at a point in the sequence.\n\n \"\"\"\n log.info(\"%s: x has shape %s\", name, x.data.shape)\n return x\n\n\ndef run_dummy(model):\n \"\"\"Run a dummy batch through a model.\n\n This is useful to initialize all arrays inside the model. When\n sizes are not specified, some arrays are initialized lazily on the\n first run. This is a problem if you want to load_npz() the\n parameters of the model, since not all parameters are yet created.\n \"\"\"\n with chainer.using_config('train', False):\n with chainer.using_config('enable_backprop', False):\n dummy_batch = (model.xp.random.random(\n (1, 3, 224, 224)) * 255).astype(model.xp.float32)\n model(dummy_batch)\n\n\nCHANNELS = {\n 0.5: [24, 48, 96, 192, 1024],\n 1.: [24, 116, 232, 464, 1024],\n 1.5: [24, 176, 352, 704, 1024],\n 2: [24, 244, 488, 976, 1024],\n}\n\n\ndef guess_k(snapshot_file):\n \"\"\"Guess the k (1, 1.5, 2) from a snapshot file containing a trained\n Shufflenet V2 model. This is useful to load the snapshot, since\n you need to construct a ShuffleNetV2 object with the right k\n before loading it.\n\n \"\"\"\n ko = {v[1]: k for k, v in CHANNELS.items()}\n with np.load(snapshot_file) as snap:\n out_channels = (\n snap['updater/model:main/predictor/features/stage2/basic1/branch/conv_bn_relu1/conv/W'].shape[0] * 2)\n return ko[out_channels]\n\n\ndef ShuffleNetV2Features(k):\n \"\"\"Create a ShuffleNet v2 network that computes a (1024, fw, fh)\n feature tensor.\n\n Parameter k is the multiplier giving the size of the\n network. Supported values are 0.5, 1, 1.5 and 2.\n\n \"\"\"\n stage_repeats = [4, 8, 4]\n try:\n channels = CHANNELS[k]\n except KeyError:\n raise KeyError(\"unsupported k={}, supported values are {}\".format(\n k, CHANNELS.keys()))\n\n net = Seq()\n\n stage1 = Seq(\n conv=L.Convolution2D(\n 3, channels[0], ksize=3, stride=2, pad=1, nobias=True),\n bn=BatchNormalization(axis=(0, 2, 3)),\n relu=F.relu,\n max_pool=fun.partial(\n F.max_pooling_2d, ksize=3, stride=2, pad=1, cover_all=False))\n net.add(\"stage1\", stage1)\n\n # Stage2, Stage3, Stage4.\n for i_stage, stage_repeat in enumerate(stage_repeats):\n out_channels = channels[1 + i_stage]\n stage = ShuffleNetV2Stage(out_channels, stage_repeat)\n net.add(\"stage{}\".format(i_stage + 2), stage)\n\n # Conv5\n net.add(\"stage5\", _1x1_conv_bn_relu(channels[-1]))\n\n run_dummy(net)\n return net\n\n\ndef ShuffleNetV2(k, out_size):\n \"\"\"Create a ShuffleNet v2 network that outputs a vector of size\n out_size. It consists in global average pooling + fully connected\n layer on top of the feature network above.\n\n \"\"\"\n # We do not flatten to ease reuse of features.\n net = Seq(\n features=ShuffleNetV2Features(k),\n head=Seq(\n # Global pooling (compute mean of each channel). We leave\n # keepdims=False to get a NxC array (with H and W removed and not\n # set to 1).\n global_pool=fun.partial(F.mean, axis=(2, 3)),\n fc=L.Linear(None, out_size)))\n run_dummy(net)\n return net\n\n\ndef test_shufflenet_features():\n import numpy as np\n with chainer.using_config('train', False):\n for k in [0.5, 1, 1.5, 2]:\n net = ShuffleNetV2Features(k)\n data = np.random.random((10, 3, 123, 567)).astype(np.float32)\n ret = net(data)\n assert ret.data.shape[:2] == (10, 1024)\n\n data = np.random.random((10, 3, 224, 224)).astype(np.float32)\n ret = net(data)\n assert ret.data.shape == (10, 1024, 7, 7)\n\n\ndef test_shufflenet():\n import numpy as np\n with chainer.using_config('train', False):\n for k in [0.5, 1, 1.5, 2]:\n for out_size in [2, 10, 1000]:\n net = ShuffleNetV2(k, out_size)\n data = np.random.random((10, 3, 123, 567)).astype(np.float32)\n ret = net(data)\n assert ret.data.shape == (10, out_size)\n\n\ndef test_use_features():\n import numpy as np\n with chainer.using_config('train', False):\n net = ShuffleNetV2(1, 2)\n features = net['features']\n data = np.random.random((10, 3, 123, 567)).astype(np.float32)\n ret = features(data)\n assert ret.data.shape[:2] == (10, 1024)\n data = np.random.random((10, 3, 224, 224)).astype(np.float32)\n ret = features(data)\n assert ret.data.shape == (10, 1024, 7, 7)\n" } ]
4
rjose/dovetail
https://github.com/rjose/dovetail
32390576a4ddfe76b3471886c17759af7b051af4
bf7c1f128b8c7dc9c604bc7214656201afba6a1c
0ffe730ab0da26cb59b62379f4ff551aa0265373
refs/heads/master
2020-04-06T04:31:28.457560
2012-12-13T21:11:24
2012-12-13T21:11:24
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5803371071815491, "alphanum_fraction": 0.5926966071128845, "avg_line_length": 34.560001373291016, "blob_id": "bbcd6abac40aa1469d480456600d3778439a1a75", "content_id": "75a081d9939fab1ba82a9c7cb621822f67d04889", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1780, "license_type": "permissive", "max_line_length": 63, "num_lines": 50, "path": "/dovetail/database.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "from datetime import datetime\nfrom sqlalchemy import (create_engine, MetaData, Table, Column,\n Integer, String, Date, Float, Boolean)\n\n# TODO: Use an environment/config variable for this\nengine = create_engine('sqlite:///db/dovetail_dev.db')\nmetadata = MetaData(bind=engine)\n\npeople = Table('people', metadata,\n Column('id', Integer, primary_key=True),\n Column('name', String(50)),\n Column('picture', String(200)),\n Column('team', String(200)),\n Column('title', String(200)))\n\nprojects = Table('projects', metadata,\n Column('id', Integer, primary_key=True),\n Column('name', String(50)),\n Column('is_deleted', Boolean, default = False),\n Column('is_done', Boolean, default = False),\n Column('value', Float),\n Column('completion_date', Date()),\n Column('target_date', Date()),\n Column('est_start_date', Date()),\n Column('est_end_date', Date())\n )\n\nproject_participants = Table('project_participants', metadata,\n Column('project_id', Integer),\n Column('person_id', Integer)\n )\n\nwork = Table('work', metadata,\n Column('id', Integer, primary_key=True),\n Column('title', String(200)),\n Column('is_deleted', Boolean, default = False),\n Column('is_done', Boolean, default = False),\n Column('assignee_id', Integer),\n Column('multiple_assignee_ids', String(200)),\n Column('project_id', Integer),\n Column('effort_left_d', Float),\n\n Column('topo_order', Integer),\n Column('value', Float),\n Column('key_date', Date()),\n Column('start_date', Date()),\n Column('end_date', Date()),\n Column('completion_date', Date()),\n Column('prereqs', String(200))\n )\n\n\n" }, { "alpha_fraction": 0.5792349576950073, "alphanum_fraction": 0.6147540807723999, "avg_line_length": 32.272727966308594, "blob_id": "ffa2bb8dd506a397b611e8af25b8653dcca4b903", "content_id": "587d50bf024b15df1b6dfc63d84e782dfbd86ff2", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1098, "license_type": "permissive", "max_line_length": 87, "num_lines": 33, "path": "/dovetail/tests/test_slot.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "import unittest\nfrom mock import MagicMock\nfrom dovetail.timeline.slot import Slot\n\nclass TestSlot(unittest.TestCase):\n\n def test_contains(self):\n slot = Slot(2, 7) # [2, 7]\n self.assertEqual(slot.contains(1, 2), False)\n self.assertEqual(slot.contains(1, 3), False)\n \n self.assertEqual(slot.contains(2, 3), True)\n self.assertEqual(slot.contains(2, 7), True)\n\n self.assertEqual(slot.contains(2, 7.5), False)\n self.assertEqual(slot.contains(7, 8), False)\n \n def test_fill(self):\n slot = Slot(2, 7) # [2, 7]\n # Should raise exception if trying to fill slot with something that doesn't fit\n self.assertRaises(Exception, slot.fill, 1, 2)\n\n # If fully fills slot, return empty array\n self.assertEqual(slot.fill(2, 7), [])\n\n self.assertEqual(slot.fill(2, 3), [Slot(3, 7)])\n self.assertEqual(slot.fill(3, 4), [Slot(2, 3), Slot(4, 7)])\n self.assertEqual(slot.fill(5, 7), [Slot(2, 5)])\n\n# TODO: Check filling with an infinite end date\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.6141242980957031, "alphanum_fraction": 0.6141242980957031, "avg_line_length": 33.03845977783203, "blob_id": "3c84b40a3b57e090bd9514b7fe5613675246caa8", "content_id": "c625df3c11aa7466ef688e5f6684ed3a50a80a24", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1770, "license_type": "permissive", "max_line_length": 83, "num_lines": 52, "path": "/dovetail/scheduler.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "from datetime import datetime\nfrom dovetail.timeline.timeline import Timeline\nimport dovetail.projects.db as projects_db\n\nclass Scheduler:\n\n def __init__(self, cur_date):\n self.timelines = {}\n self.work_dict = {}\n self.cur_date = cur_date\n return\n\n def get_assignee_timeline(self, person_id):\n if self.timelines.has_key(person_id):\n result = self.timelines[person_id]\n else:\n # TODO: Figure out how to handle user-specific nonworkdays\n result = Timeline(self.cur_date)\n self.timelines[person_id] = result\n return result\n\n def schedule_work(self, work):\n timeline = self.get_assignee_timeline(work.assignee_id)\n if work.key_date:\n slot = timeline.schedule_at_end_date(work.key_date, work.effort_left_d)\n else:\n start_date = work.earliest_start_date(self.work_dict, self.cur_date)\n slot = timeline.schedule_at_start_date(start_date, work.effort_left_d)\n\n work.schedule(slot)\n return\n\n\n def schedule_projects(self, projects):\n for p in projects:\n est_project_end = self.cur_date\n for w in p.work:\n self.work_dict[w.work_id] = w\n self.schedule_work(w)\n w_end_date = w.est_end_date()\n if w_end_date > est_project_end:\n est_project_end = w_end_date\n p.est_end_date = est_project_end\n return projects\n\n\ndef reschedule_world(connection):\n scheduler = Scheduler(datetime.now())\n projects = projects_db.get_projects_for_scheduling(connection)\n projects = scheduler.schedule_projects(projects)\n projects_db.update_project_and_work_dates(connection, projects)\n return\n" }, { "alpha_fraction": 0.6174734234809875, "alphanum_fraction": 0.6210153698921204, "avg_line_length": 22.52777862548828, "blob_id": "6db25d3670dc3a94f121ec098a37280fcf2d6f4b", "content_id": "f51f7aaef76bf1f74d5dc58658ec1fb6fbe7cc3f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 847, "license_type": "permissive", "max_line_length": 54, "num_lines": 36, "path": "/dovetail/util.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "from datetime import datetime\nimport json\n\ndef format_date(date):\n if date == None:\n return ''\n elif type(date) == str:\n return date\n else:\n return datetime.strftime(date, \"%b %d, %Y\")\n\ndef standardize_date(date):\n result = datetime(date.year, date.month, date.day)\n return result\n\ndef parse_date(date_string):\n return datetime.strptime(date_string, \"%b %d, %Y\")\n\ndef condition_date(d):\n if d and type(d) != datetime:\n return datetime.strptime(d, '%Y-%m-%d')\n else:\n return d\n\ndef format_effort_left(effort_left_d, precision=2):\n if not effort_left_d:\n effort_left_d = 0.1\n\n format_string = '%%.%df d' % precision\n return format_string % effort_left_d\n\ndef condition_prereqs(prereqs):\n result = []\n if prereqs:\n result = json.loads(prereqs)\n return result\n" }, { "alpha_fraction": 0.478723406791687, "alphanum_fraction": 0.48404255509376526, "avg_line_length": 21.90243911743164, "blob_id": "d3e732400665b6afe6108711d60ec342b3de94f7", "content_id": "b442ad02a2172d26048104e030742b08815baf39", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 940, "license_type": "permissive", "max_line_length": 71, "num_lines": 41, "path": "/dovetail/templates/people/details.html", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "{% extends \"layout/people/details.html\" %}\n\n{% block content2 %}\n\n<h3>Assigned work</h3>\n<table class='table table-bordered'>\n <tr>\n <th>ID</th>\n <th>Project</th>\n <th>Title</th>\n <th>Effort left (d)</th>\n <th>Est complete</th>\n <th>Key date</th>\n </tr>\n {% for w in person.work %}\n <tr>\n <td>{{ w.work_id }}</td>\n <td><a href='{{ w.project_url }}'>{{ w.project_name }}</a></td>\n <td>{{ w.title }}</td>\n <td>{{ w.effort_left_d }}</td>\n <td>{{ w.est_end_date }}</td>\n <td>{{ w.key_date }}</td>\n </tr>\n {% endfor %}\n</table>\n\n{% if done_work %}\n<h4>Completed work</h4>\n\n<ul>\n {% for w in done_work %}\n <li><button class='btn btn-mini mark-work-undone'\n work_id='{{ w.work_id }}'>Not done</button> {{ w.title }}</li>\n {% endfor %}\n</ul>\n{% endif %}\n\n<script>\n $('#nav-table').addClass('active');\n</script>\n{% endblock %}\n\n" }, { "alpha_fraction": 0.5013290643692017, "alphanum_fraction": 0.5619351267814636, "avg_line_length": 28.841270446777344, "blob_id": "b8cb0ef66dfac3285849d9d56a2270b93235fac3", "content_id": "b5fc1e91e4dc0d6771107c09ac1494297e280617", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1881, "license_type": "permissive", "max_line_length": 98, "num_lines": 63, "path": "/dovetail/tests/test_work.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "import unittest\nfrom mock import MagicMock\nfrom datetime import datetime\nfrom dovetail.timeline.timeline import Timeline\nfrom dovetail.timeline.slot import Slot\nfrom dovetail.work.work import Work\nimport dovetail.work.db as work_db\nimport dovetail.tests.util as util\n\nclass TestWork(unittest.TestCase):\n\n def test_schedule(self):\n timeline = Timeline(util.nov1)\n work_slot, _ = timeline.find_slot(4, 1.5)\n\n w = Work(1)\n w.title = 'Some work'\n w.effort_left_d = 1.5\n w.assignee_id = 100\n\n w.schedule(work_slot)\n self.assertEqual(util.nov7, w.est_start_date())\n self.assertEqual(util.nov8, w.est_end_date())\n return\n\n def test_earliest_start_date(self):\n timeline = Timeline(util.nov1)\n work_slot, _ = timeline.find_slot(4, 1.5)\n\n w1 = Work(1)\n w1.title = 'w1'\n w1.effort_left_d = 1.0\n w1.assignee_id = 100\n w1.schedule(timeline.find_slot(0, 1)[0])\n\n w2 = Work(2)\n w2.title = 'w2'\n w2.effort_left_d = 1.0\n w2.assignee_id = 101\n w2.schedule(timeline.find_slot(1, 3)[0])\n\n w3 = Work(3)\n w3.title = 'w3'\n w3.effort_left_d = 1.0\n w3.prereqs = [1, 2]\n w3.assignee_id = 200\n\n work_dict = {1: w1, 2: w2, 3: w3}\n self.assertEqual(util.nov7, w3.earliest_start_date(work_dict, util.nov1))\n return\n\n def test_fields_to_work_object(self):\n w1 = work_db.fields_to_work_object({\n 'id': 25,\n 'title': 'w1',\n 'effort_left_d': 16.7,\n 'prereqs': '[1, 2]',\n 'assignee_id': 100,\n 'key_date': '2012-12-12'\n })\n self.assertEqual([25, 'w1', 16.7, [1, 2], 100, datetime(2012, 12, 12)],\n [w1.work_id, w1.title, w1.effort_left_d, w1.prereqs, w1.assignee_id, w1.key_date])\n return\n\n" }, { "alpha_fraction": 0.6901408433914185, "alphanum_fraction": 0.6945886015892029, "avg_line_length": 36.47222137451172, "blob_id": "c8b8dc42d7edda469cc1e55bd599c4db2107d21c", "content_id": "2d3bbc0e6ad64904a5221f0a54b01aabe4ac23df", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1349, "license_type": "permissive", "max_line_length": 89, "num_lines": 36, "path": "/dovetail/work/controller.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "from flask import (Blueprint, Response, json, render_template, request,\n redirect, url_for, g)\nfrom datetime import datetime\n\nimport dovetail.database as database\nimport dovetail.projects.db as projects_db\nimport dovetail.people.db as people_db\nimport dovetail.work.db as work_db\nimport dovetail.scheduler\n\nmod = Blueprint('work', __name__)\n\[email protected]('/api/work', methods=['POST'])\ndef api_work():\n # Condition data from request\n title = request.values['title']\n assignee_id = int(request.values['assignee_id'])\n effort_left_d = float(request.values['effort_left_d'])\n project_id = int(request.values['project_id'])\n\n insert_result = g.connection.execute(database.work.insert(),\n title = title,\n assignee_id = assignee_id,\n project_id = project_id,\n effort_left_d = effort_left_d)\n\n response_data = {'work_id': insert_result.inserted_primary_key}\n #dovetail.scheduler.reschedule_world(g.connection)\n return Response(json.dumps(response_data), status=200, mimetype='application/json')\n\[email protected]('/api/work/<int:work_id>/mark_undone', methods=['POST'])\ndef api_mark_work_undone(work_id):\n work_db.mark_work_undone(g.connection, [work_id])\n response_data = {}\n result = Response(json.dumps(response_data), status=200, mimetype='application/json')\n return result\n" }, { "alpha_fraction": 0.6183636784553528, "alphanum_fraction": 0.6460630893707275, "avg_line_length": 35.092594146728516, "blob_id": "49b9eaa1f059688b69521d11624f63fda2d552c1", "content_id": "21adc06b1999a261612b5243ccf437ed86130fd1", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3899, "license_type": "permissive", "max_line_length": 92, "num_lines": 108, "path": "/dovetail/tests/test_timeline.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "import unittest\nfrom mock import MagicMock\nfrom datetime import datetime\nfrom dovetail.timeline.timeline import Timeline\nfrom dovetail.timeline.slot import Slot\nfrom datetime import timedelta\nimport dovetail.tests.util as util\n\nclass TestTimeline(unittest.TestCase):\n\n def test_add_dates_to(self):\n timeline = Timeline(util.nov1)\n timeline.add_dates_to(util.nov1)\n self.assertEqual([util.nov1], timeline.dates)\n\n timeline.add_dates_to(util.nov2)\n self.assertEqual([util.nov1, util.nov2], timeline.dates)\n\n # Check idempotent\n timeline.add_dates_to(util.nov2)\n self.assertEqual([util.nov1, util.nov2], timeline.dates)\n\n # Skip until next workday\n timeline.add_dates_to(util.nov3)\n self.assertEqual([util.nov1, util.nov2, util.nov5], timeline.dates)\n return\n\n def test_day_from_date(self):\n timeline = Timeline(util.nov1)\n self.assertEqual(0, timeline.day_from_date(util.nov1))\n self.assertEqual(1, timeline.day_from_date(util.nov2))\n self.assertEqual(2, timeline.day_from_date(util.nov3))\n self.assertEqual(2, timeline.day_from_date(util.nov4))\n self.assertEqual(2, timeline.day_from_date(util.nov5))\n return\n\n def test_add_days(self):\n timeline = Timeline(util.nov1)\n timeline.add_days_to(0)\n self.assertEqual([util.nov1], timeline.dates)\n\n timeline.add_days_to(2)\n self.assertEqual([util.nov1, util.nov2, util.nov5], timeline.dates)\n return\n\n def test_date_from_day(self):\n timeline = Timeline(util.nov1)\n self.assertEqual(util.nov5, timeline.date_from_day(2))\n self.assertEqual(util.nov5, timeline.date_from_day(2.9))\n return\n\n def test_find_slot(self):\n timeline = Timeline(util.nov1)\n my_slot, containing_slot_index = timeline.find_slot(4, 0.5)\n self.assertEqual(Slot(4, 4.5), my_slot)\n self.assertEqual(0, containing_slot_index)\n\n # Test where prefered slot is not available\n timeline.slots = [Slot(1, 3), Slot(4, float('inf'))]\n my_slot, containing_slot_index = timeline.find_slot(0, 2.5)\n self.assertEqual(Slot(4, 6.5), my_slot)\n self.assertEqual(1, containing_slot_index)\n\n # Check that the slot dates are correct\n self.assertEqual(util.nov7, my_slot.start_date)\n self.assertEqual(util.nov9, my_slot.end_date)\n return\n\n # This tests the case where the final, infinite slot needs to be used\n # but the desired slot does not fit without modification (smoke test)\n def test_find_slot_at_end(self):\n timeline = Timeline(util.nov1)\n timeline.claim_slot(Slot(0, 1.0), 0)\n my_slot, containing_slot_index = timeline.find_slot(0, 1.0)\n return\n\n\n def test_claim_slot(self):\n timeline = Timeline(util.nov1)\n timeline.claim_slot(Slot(4, 4.5), 0)\n self.assertEqual([Slot(0, 4), Slot(4.5, float('inf'))], timeline.slots)\n return\n\n def test_claim_slot_on_partially_filled_days(self):\n timeline = Timeline(util.nov1)\n timeline.claim_slot(Slot(4, 4.5), 0)\n my_slot, containing_slot_index = timeline.find_slot(4.1, 0.5)\n self.assertEqual(Slot(4.5, 5), my_slot)\n return\n\n\n def test_find_slot_with_ending_date(self):\n timeline = Timeline(util.nov1)\n my_slot, containing_slot_index = timeline.find_slot_with_ending_date(util.nov7, 0.1)\n self.assertEqual(Slot(4.4, 4.5), my_slot)\n return\n\n def test_find_slot_with_ending_date2(self):\n # This tests an infinite loop case\n delta1 = timedelta(0.25)\n timeline = Timeline(util.nov1 + delta1)\n my_slot, containing_slot_index = timeline.find_slot_with_ending_date(util.nov7, 0.1)\n self.assertEqual(Slot(4.4, 4.5), my_slot)\n return\n\n \nif __name__ == '__main__':\n unittest.main()\n\n" }, { "alpha_fraction": 0.4936138093471527, "alphanum_fraction": 0.4973703920841217, "avg_line_length": 27.934782028198242, "blob_id": "378acaf475a9ed408ea64816dcc4184b6dc37a9e", "content_id": "e3d3d4595c39ba69c4ef3a1752c58cac1994f099", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1331, "license_type": "permissive", "max_line_length": 62, "num_lines": 46, "path": "/dovetail/charts/project_timeline_chart.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "from datetime import datetime, timedelta\nimport dovetail.util\nfrom dovetail.charts.support.gantt import Gantt\n\nclass ProjectTimelineChart:\n def __init__(self, project_id, cur_day, timelines):\n self.cur_day = dovetail.util.standardize_date(cur_day)\n self.project_id = project_id\n self.data = []\n\n if not timelines:\n return\n\n names = timelines.keys()\n names.sort()\n\n for name in names:\n work = timelines[name]\n row = {\n 'label': name,\n 'bars': self.work_to_bars(work)\n }\n self.data.append(row)\n return\n\n def work_to_bars(self, work):\n result = []\n for w in work:\n if w['project_id'] == self.project_id:\n color = '#08C'\n else:\n color = 'gray'\n result.append({\n 'id': w['work_id'],\n 'start': w['start_date'],\n 'end': w['end_date'],\n 'effort_d': w['effort_left_d'],\n 'color': color\n })\n return result\n\n def as_json(self):\n # Set the end date of the chart to be 3 weeks out\n max_date = self.cur_day + timedelta(21)\n gantt = Gantt(self.cur_day, self.data, max_date)\n return gantt.as_json()\n" }, { "alpha_fraction": 0.6524547934532166, "alphanum_fraction": 0.6524547934532166, "avg_line_length": 35.85714340209961, "blob_id": "fde112235aa6626b4e47976a7da1aaaf5140ae5f", "content_id": "56f93440cb2127727a707cacdfc3284f3a287336", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1548, "license_type": "permissive", "max_line_length": 92, "num_lines": 42, "path": "/dovetail/people/db.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "import dovetail.database as database\nfrom dovetail.people.person import Person\n\ndef fields_to_person_object(fields):\n result = Person(fields['id'])\n\n for f in fields.keys():\n if f == 'name':\n result.name = fields[f]\n elif f == 'title':\n result.title = fields[f]\n elif f == 'team':\n result.team = fields[f]\n elif f == 'picture':\n result.picture = fields[f]\n return result\n\ndef select_people(connection):\n people_data = connection.execute('select id, name from people order by name')\n result = [fields_to_person_object(d) for d in people_data]\n return result\n\ndef select_project_participants(connection, project_id):\n particpants_data = connection.execute(\n '''select id, name, title, team, picture from people\n inner join project_participants on project_participants.person_id = people.id\n where project_participants.project_id= %d\n order by name''' % int(project_id))\n result = [fields_to_person_object(d) for d in particpants_data]\n return result\n\ndef select_person(connection, person_id):\n person_data = connection.execute(database.people.select(\n database.people.c.id == person_id)).first()\n result = fields_to_person_object(person_data)\n return result\n\ndef select_person_by_name(connection, name):\n person_data = connection.execute(database.people.select(\n database.people.c.name == name)).first()\n result = fields_to_person_object(person_data)\n return result\n" }, { "alpha_fraction": 0.7469244003295898, "alphanum_fraction": 0.7469244003295898, "avg_line_length": 23.191490173339844, "blob_id": "eb8972c91e340443d1404d520770214e624cd7af", "content_id": "89c3d825817d51e79a212f6b60e303b4000babd7", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1138, "license_type": "permissive", "max_line_length": 71, "num_lines": 47, "path": "/dovetail/__init__.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, request, redirect, url_for, g\nfrom datetime import datetime\n\nimport dovetail.database as database\n\nimport dovetail.projects.controller\nimport dovetail.people.controller\nimport dovetail.work.controller\nimport os\nfrom werkzeug.wsgi import SharedDataMiddleware\n\ndatabase.metadata.create_all()\n\napp = Flask(__name__)\n\[email protected]_request\ndef open_connection():\n g.connection = database.engine.connect()\n\[email protected]_request\ndef close_connection(exeption=None):\n g.connection.close()\n\n\[email protected]('/')\ndef root():\n return redirect('/projects')\n\[email protected]('/home')\ndef root():\n return render_template('home/index.html')\n\n# Static files\n\n\n# Register blueprints\napp.register_blueprint(dovetail.people.controller.mod)\napp.register_blueprint(dovetail.projects.controller.mod)\napp.register_blueprint(dovetail.work.controller.mod)\n\n# Register middleware\napp.wsgi_app = SharedDataMiddleware(app.wsgi_app, {\n '/assets': os.path.join(os.path.dirname(__file__), 'assets')})\n\nif __name__ == '__main__':\n # TODO: Figure out how to set this via an environment variable\n app.run(debug=True)\n\n" }, { "alpha_fraction": 0.5103825330734253, "alphanum_fraction": 0.5114753842353821, "avg_line_length": 25.114286422729492, "blob_id": "536e6867bca674b942cfc0ebe5f359f37ea80ae9", "content_id": "f59d4df111c69950e274a6173b1f07d63c532ebc", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 915, "license_type": "permissive", "max_line_length": 56, "num_lines": 35, "path": "/dovetail/work/work.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "class Work():\n \n def __init__(self, work_id):\n self.work_id = work_id\n self.title = ''\n self.effort_left_d = 0\n self.prereqs = []\n self.assignee_id = None\n self.key_date = None\n self.slot = None\n\n def schedule(self, slot):\n self.slot = slot\n\n def est_start_date(self):\n if self.slot:\n return self.slot.start_date\n else:\n return None\n\n def est_end_date(self):\n if self.slot:\n return self.slot.end_date\n else:\n return None\n\n def earliest_start_date(self, work_dict, cur_day):\n result = cur_day\n for work_id in self.prereqs:\n if not work_dict.has_key(work_id):\n continue\n end_date = work_dict[work_id].est_end_date()\n if end_date and end_date > result:\n result = end_date\n return result\n\n" }, { "alpha_fraction": 0.5788453817367554, "alphanum_fraction": 0.5788453817367554, "avg_line_length": 35.85714340209961, "blob_id": "4a7f9a7582a45b3597f924b6ee552bff92b128de", "content_id": "abc34dfb587c1aa45ceed5de063cd317dff8e25e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2581, "license_type": "permissive", "max_line_length": 78, "num_lines": 70, "path": "/dovetail/people/controller.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "import json\nfrom flask import Blueprint, render_template, request, redirect, url_for, g\nfrom datetime import datetime\n\nimport dovetail.database as database\nimport dovetail.people.db as people_db\nimport dovetail.work.db as work_db\nimport dovetail.util\n\nfrom dovetail.charts.person_timeline_chart import PersonTimelineChart\n\nmod = Blueprint('people', __name__)\n\[email protected]('/people', methods=['GET', 'POST'])\ndef people():\n if request.method == 'POST':\n g.connection.execute(database.people.insert(),\n name = request.form['name'],\n title = request.form['title'],\n team = request.form['team'],\n picture = request.form['picture'])\n else:\n pass\n people_data = g.connection.execute('select id, name from people')\n people = [{'id': p['id'], 'name': p['name']} for p in people_data]\n return render_template('people/collection.html', people = people)\n\n\[email protected]('/people/<int:person_id>')\ndef person_details(person_id):\n person = people_db.select_person(g.connection, person_id)\n work = work_db.select_work_for_person(g.connection, person_id)\n timeline_aux_data = {}\n for w in work:\n w.est_end_date = dovetail.util.format_date(w.end_date)\n w.key_date = dovetail.util.format_date(w.key_date)\n w.project_url = '/projects/%d' % int(w.project_id)\n timeline_aux_data[w.work_id] = {\n 'title': '[%s] %s' % (w.project_name, w.title),\n 'content': '''\n <p>%s</p>\n <p>Start: %s</p>\n <p>Finish: %s</p>\n ''' % (\n w.effort_left_d,\n dovetail.util.format_date(w.start_date),\n dovetail.util.format_date(w.end_date)\n )\n }\n person.work = work\n\n if request.args.get('timeline'):\n chart = PersonTimelineChart(datetime.now(), person)\n return render_template('people/details_timeline.html',\n person = person,\n details_url = '/people/%d' % person_id,\n details_timeline_url = '/people/%d?timeline=true' % person_id,\n timeline_data = chart.as_json(),\n timeline_aux_data = json.dumps(timeline_aux_data)\n )\n else:\n return render_template('people/details.html',\n person = person,\n details_url = '/people/%d' % person_id,\n details_timeline_url = '/people/%d?timeline=true' % person_id\n )\n\[email protected]('/people/new')\ndef people_new():\n return render_template('people/new.html')\n\n" }, { "alpha_fraction": 0.5564146041870117, "alphanum_fraction": 0.5668035745620728, "avg_line_length": 28.98550796508789, "blob_id": "2bcb942b89d4c2f1a253b744a690b0e4c3bd36b8", "content_id": "3008db11556be5fab199509211837b3a74a78e40", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4139, "license_type": "permissive", "max_line_length": 85, "num_lines": 138, "path": "/dovetail/assets/js/dovetail_chart.js", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "\nfunction DovetailChart(viewerId, data, auxData) {\n // Creates an svg node. The `svgType` should be things like `svg`, `rect`, etc.\n // See [SVG Shapes](http://www.w3.org/TR/SVG11/shapes.html) for more info.\n function createSvgNode(svgType) {\n var result = document.createElementNS(\"http://www.w3.org/2000/svg\", svgType);\n return result;\n }\n\n // Initialization\n var viewerElement = document.getElementById(viewerId);\n var svgViewer = createSvgNode('svg');\n var chartHeight = svgViewer.getAttribute('height');\n viewerElement.appendChild(svgViewer);\n var data = data;\n var auxData = auxData;\n var popover = null;\n\n function addRectangle(x, y, width, height, color) {\n var result = createSvgNode(\"rect\");\n result.x.baseVal.value = x;\n result.y.baseVal.value = y;\n result.width.baseVal.value = width;\n result.height.baseVal.value = height;\n result.style.fill = color;\n svgViewer.appendChild(result);\n return result;\n }\n\n function addText(x, y, text, color) {\n var result = createSvgNode(\"text\");\n result.setAttributeNS(null, \"x\", x);\n result.setAttributeNS(null, \"y\", y);\n result.setAttributeNS(null, \"fill\", color);\n\n var textNode = document.createTextNode(text);\n result.appendChild(textNode);\n\n svgViewer.appendChild(result);\n return result;\n }\n \n function addLine(x1, y1, x2, y2, color) {\n var result = createSvgNode(\"line\");\n result.x1.baseVal.value = x1;\n result.y1.baseVal.value = y1;\n result.x2.baseVal.value = x2;\n result.y2.baseVal.value = y2;\n result.style.stroke = color;\n svgViewer.appendChild(result);\n\n return result;\n }\n\n function hidePopover() {\n if (popover) {\n popover.remove();\n }\n }\n\n function showPopover(x, y, itemId) {\n hidePopover();\n if (!auxData) {\n return;\n }\n\n popover = $(document.createElement('div'));\n popover.addClass('popover fade bottom in');\n\n var popoverInner = $(document.createElement('div'));\n popoverInner.addClass('popover-inner');\n\n var title = $(document.createElement('h3'));\n title.addClass('popover-title');\n title.html(auxData[itemId].title);\n\n var content = $(document.createElement('div'));\n content.addClass('popover-content');\n content.html(auxData[itemId].content);\n\n popoverInner.append(title);\n popoverInner.append(content);\n\n popover.append(popoverInner);\n\n // TODO: Send this ID in\n var chart = $('#timeline-chart');\n var chartX = chart[0].offsetLeft;\n var chartY = chart[0].offsetTop;\n y += chartY;\n x = x + chartX;\n popover.attr('style', 'top: ' + y + 'px; left: ' + x + 'px; display: block;');\n $('#timeline-chart').append(popover);\n\n popover.click(function () {\n hidePopover();\n })\n }\n\n function renderData() {\n // Set chart height from data\n chartHeight = data.chart_height;\n svgViewer.setAttribute('height', chartHeight);\n\n data.rows.forEach(function(r) {\n var textX = 10;\n var textY = r.y + 15;\n addText(textX, textY, r.label, '#333');\n\n r.bars.forEach(function(b) {\n var rect = addRectangle(b.x, r.y, b.width, b.height, b.color);\n rect.onclick = function(event) {\n showPopover(event.offsetX, event.offsetY, b.id);\n }\n });\n });\n data.dates.forEach(function(d) {\n // Add lines going across chart\n addLine(d.x, 0, d.x, chartHeight, 'gray');\n \n // Add labels\n var textX = d.x + 4;\n var textY = 10;\n if (chartHeight > 400) {\n addText(textX, textY, d.label, '#333');\n }\n addText(textX, chartHeight, d.label, '#333');\n });\n }\n\n\n var result = {\n addRectangle: addRectangle,\n addText: addText,\n renderData: renderData\n };\n\n return result;\n}\n" }, { "alpha_fraction": 0.5378151535987854, "alphanum_fraction": 0.5388655662536621, "avg_line_length": 26.200000762939453, "blob_id": "930df804d46c91c7a2f47525413b251bfc87aca6", "content_id": "d26b264525dfd332fc1c12af36b5b1d579fc41fc", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 952, "license_type": "permissive", "max_line_length": 82, "num_lines": 35, "path": "/dovetail/projects/project.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "from pygraph.classes.digraph import digraph\nfrom pygraph.algorithms.sorting import topological_sorting\n\nclass Project:\n\n def __init__(self, project_id):\n self.project_id = project_id\n self.work = []\n self.name = None\n self.participants = []\n self.target_date = None\n self.est_end_date = None\n return\n\n def total_effort(self):\n return reduce(lambda x, y: x + y, [w.effort_left_d for w in self.work], 0)\n\n def topo_sort_work(self):\n my_work = self.work\n\n work_dict = {}\n for w in my_work:\n work_dict[w.work_id] = w\n\n graph = digraph()\n graph.add_nodes(my_work)\n\n for w in my_work:\n for p in w.prereqs:\n if not work_dict.has_key(p):\n continue\n if work_dict[p]:\n graph.add_edge((work_dict[p], w))\n self.work = topological_sorting(graph)\n return\n" }, { "alpha_fraction": 0.5664596557617188, "alphanum_fraction": 0.5689440965652466, "avg_line_length": 32.52083206176758, "blob_id": "608e44a3d95342b0114a04e47a42abbbe549113d", "content_id": "784d817100bcd62b1b99bf88631e5d79de5d803e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1610, "license_type": "permissive", "max_line_length": 84, "num_lines": 48, "path": "/dovetail/timeline/slot.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "def sort_pair(start_day, end_day):\n if start_day > end_day:\n start_day, end_day = end_day, start_day\n return start_day, end_day \n\n\nclass Slot():\n def __init__(self, start_day, end_day):\n self.start_day, self.end_day = sort_pair(start_day, end_day)\n self.start_date = None\n self.end_date = None\n\n def contains(self, start_day, end_day):\n result = False\n\n start_day, end_day = sort_pair(start_day, end_day)\n if start_day < self.start_day:\n result = False\n elif end_day > self.end_day:\n result = False\n else:\n result = True\n return result\n\n # Returns an array of slots that result if this slot were to be filled\n def fill(self, start_day, end_day):\n start_day, end_day = sort_pair(start_day, end_day)\n\n if not self.contains(start_day, end_day):\n raise Exception('Can\\'t fill slot with (%f, %f)' % (start_day, end_day))\n\n #self.assertEqual(slot.fill(2, 3), [Slot(3, 7)])\n result = []\n if start_day == self.start_day and end_day < self.end_day:\n result = [Slot(end_day, self.end_day)]\n elif start_day > self.start_day and end_day < self.end_day:\n result = [Slot(self.start_day, start_day), Slot(end_day, self.end_day)]\n elif start_day > self.start_day and end_day == self.end_day:\n result = [Slot(self.start_day, start_day)]\n else:\n result = []\n\n return result\n\n\n\n def __eq__(self, other):\n return (self.start_day, self.end_day) == (other.start_day, other.end_day)\n\n" }, { "alpha_fraction": 0.6458123326301575, "alphanum_fraction": 0.6569122076034546, "avg_line_length": 34.39285659790039, "blob_id": "811e02bc99ffa454665d07cf5c89a0bb14348733", "content_id": "8383b583f7c88e65367a2a20e4069ee3d4ea6fe3", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 991, "license_type": "permissive", "max_line_length": 78, "num_lines": 28, "path": "/dovetail/tests/test_edit_project_work.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "import unittest\nfrom mock import MagicMock\nfrom dovetail.projects.util import parse_workline\nimport dovetail.people.db as people_db\nfrom dovetail.people.person import Person\n\nclass TestEditProjectWork(unittest.TestCase):\n\n def test_parse_workline(self):\n # Mock out person lookup\n people_db.select_person_by_name = MagicMock(return_value = Person(21))\n connection = None\n\n workline = '[1, \"Borvo Borvison\", \"0.20 d\", \"Make title longer\", [], \"?\"]'\n work_data = parse_workline(connection, workline)\n fields = work_data['fields']\n self.assertEqual(work_data['id'], 1)\n self.assertEqual(fields['assignee_id'], 21)\n self.assertEqual(fields['effort_left_d'], 0.2)\n self.assertEqual(fields['title'], 'Make title longer')\n self.assertEqual(fields['prereqs'], '[]')\n self.assertEqual(fields['key_date'], None)\n\n\n# TODO: Test prereqs and key date\n# TODO: Test invalid input\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.5452054738998413, "alphanum_fraction": 0.6237443089485168, "avg_line_length": 42.7599983215332, "blob_id": "de7041f717c132e0e9174f488e95bf2f588c9074", "content_id": "0a90840744f259ce690da8b6aec2c07bd18dbbc1", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1095, "license_type": "permissive", "max_line_length": 77, "num_lines": 25, "path": "/dovetail/tests/util.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "from datetime import datetime\nfrom dovetail.work.work import Work\n\nnov1 = datetime.strptime(\"Nov 1, 2012\", \"%b %d, %Y\") # Thu\nnov2 = datetime.strptime(\"Nov 2, 2012\", \"%b %d, %Y\")\nnov3 = datetime.strptime(\"Nov 3, 2012\", \"%b %d, %Y\") # Sat\nnov4 = datetime.strptime(\"Nov 4, 2012\", \"%b %d, %Y\") # Sun\nnov5 = datetime.strptime(\"Nov 5, 2012\", \"%b %d, %Y\") # Mon\nnov6 = datetime.strptime(\"Nov 6, 2012\", \"%b %d, %Y\")\nnov7 = datetime.strptime(\"Nov 7, 2012\", \"%b %d, %Y\") # Wed\nnov8 = datetime.strptime(\"Nov 8, 2012\", \"%b %d, %Y\") # Thu\nnov9 = datetime.strptime(\"Nov 9, 2012\", \"%b %d, %Y\") # Fri\nnov12 = datetime.strptime(\"Nov 12, 2012\", \"%b %d, %Y\") # Fri\nnov15 = datetime.strptime(\"Nov 15, 2012\", \"%b %d, %Y\")\nnov19 = datetime.strptime(\"Nov 19, 2012\", \"%b %d, %Y\")\nnov23 = datetime.strptime(\"Nov 23, 2012\", \"%b %d, %Y\")\n\ndef construct_work(id, title, effort_left_d, prereqs, assignee_id, key_date):\n result = Work(id)\n result.title = title\n result.effort_left_d = effort_left_d\n result.prereqs = prereqs\n result.assignee_id = assignee_id\n result.key_date = key_date\n return result\n\n" }, { "alpha_fraction": 0.5188881158828735, "alphanum_fraction": 0.5338560342788696, "avg_line_length": 27.612245559692383, "blob_id": "e175981d47933ebcdb7f04ce60b64f4671ea23b5", "content_id": "f2eec83276149023840a67900bee7593df4a9836", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1403, "license_type": "permissive", "max_line_length": 62, "num_lines": 49, "path": "/dovetail/charts/project_collection_timeline_chart.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "from datetime import datetime, timedelta\nimport dovetail.util\nfrom dovetail.charts.support.gantt import Gantt\n\n\nclass ProjectCollectionTimelineChart:\n def __init__(self, cur_day, projects):\n self.cur_day = dovetail.util.standardize_date(cur_day)\n self.data = []\n\n if not projects:\n return\n\n for p in projects:\n row = {\n 'label': p.name,\n 'bars': [self.project_to_bar(p)]\n }\n self.data.append(row)\n pass\n return\n\n def project_to_bar(self, project):\n result = {\n 'id': project.project_id,\n 'start': project.est_start_date,\n 'end': project.est_end_date,\n 'effort_d': project.total_effort(),\n 'color': self.get_project_color(project)\n }\n return result\n\n def as_json(self):\n max_date = self.cur_day + timedelta(21)\n gantt = Gantt(self.cur_day, self.data, max_date)\n return gantt.as_json()\n\n def get_project_color(self, project):\n if not project.est_end_date:\n return '#000'\n\n delta = project.est_end_date - project.target_date\n if (delta.days <= -5):\n color = '#468847' # Green\n elif (delta.days > -5 and delta.days <= 0):\n color = '#999' # Gray\n else:\n color = '#B94A48' # Red\n return color\n\n" }, { "alpha_fraction": 0.7586206793785095, "alphanum_fraction": 0.7600574493408203, "avg_line_length": 32.14285659790039, "blob_id": "eda1a6029a4b0657821b5565460398283e8ea0d9", "content_id": "87e186c39978351ddbf4de8329404ee6c04378f6", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 696, "license_type": "permissive", "max_line_length": 69, "num_lines": 21, "path": "/run_tests.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "import unittest\nfrom dovetail.tests.test_edit_project_work import TestEditProjectWork\nfrom dovetail.tests.test_slot import TestSlot\nfrom dovetail.tests.test_timeline import TestTimeline\nfrom dovetail.tests.test_work import TestWork\nfrom dovetail.tests.test_scheduler import TestScheduler\nfrom dovetail.tests.test_project import TestProject\nfrom dovetail.tests.test_gantt import TestGantt\n\nalltests = unittest.TestSuite([\n unittest.TestLoader().loadTestsFromTestCase(t) for t in [\n TestEditProjectWork,\n TestSlot,\n TestTimeline,\n TestWork,\n TestScheduler,\n TestProject,\n TestGantt\n ]])\n\nunittest.TextTestRunner(verbosity=2).run(alltests)\n" }, { "alpha_fraction": 0.5067567825317383, "alphanum_fraction": 0.5067567825317383, "avg_line_length": 23.66666603088379, "blob_id": "e331b3b1cda2764d26d723248c651224a8cfc0a2", "content_id": "dbc2093649843a2b97d857fa8368959f5b27a522", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 148, "license_type": "permissive", "max_line_length": 34, "num_lines": 6, "path": "/dovetail/people/person.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "class Person:\n def __init__(self, person_id):\n self.person_id = person_id\n self.name = ''\n self.picture = ''\n return\n" }, { "alpha_fraction": 0.5372973084449768, "alphanum_fraction": 0.6140540838241577, "avg_line_length": 34.53845977783203, "blob_id": "edb31355d8e78b275a21876dbb35048601613342", "content_id": "26ee426803378567ab164386aeb37e2286d48219", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 925, "license_type": "permissive", "max_line_length": 73, "num_lines": 26, "path": "/dovetail/tests/test_project.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "import unittest\nfrom mock import MagicMock\nfrom datetime import datetime\nfrom dovetail.projects.project import Project\nfrom dovetail.work.work import Work\nfrom dovetail.tests.util import construct_work\n\nclass TestProject(unittest.TestCase):\n\n def test_sort_work(self):\n # Assignees\n person_id1 = 101\n person_id2 = 102\n person_id3 = 103\n\n # Projects\n p1 = Project(1)\n p1_w1 = construct_work(1, \"p1 w1\", 1.0, [6], person_id1, None)\n p1_w2 = construct_work(2, \"p1 w2\", 1.0, [], person_id1, None)\n p1_w3 = construct_work(5, \"p1 w3\", 0.1, [2, 1], person_id1, None)\n p1_w4 = construct_work(6, \"p1 w4\", 0.1, [], person_id1, None)\n p1.work = [p1_w1, p1_w2, p1_w3, p1_w4]\n p1.topo_sort_work()\n self.assertTrue(p1.work.index(p1_w1) < p1.work.index(p1_w3))\n self.assertTrue(p1.work.index(p1_w4) < p1.work.index(p1_w1))\n return\n\n" }, { "alpha_fraction": 0.5838916301727295, "alphanum_fraction": 0.5855292677879333, "avg_line_length": 37.82659149169922, "blob_id": "052db017661360aec025b342c847def83de276ce", "content_id": "5fd5cc98eff33fca90be3f39797b860004ea4e28", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6717, "license_type": "permissive", "max_line_length": 103, "num_lines": 173, "path": "/dovetail/work/db.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "from datetime import datetime\nimport json\nimport dovetail.util\nimport dovetail.database as database\nfrom dovetail.work.work import Work\nfrom dovetail.people.person import Person\n\ndef fields_to_work_object(fields):\n result = Work(fields['id'])\n for f in fields.keys():\n if f == 'title':\n result.title = fields[f]\n elif f == 'assignee_id' or f == 'person_id':\n result.assignee_id = fields[f]\n elif f == 'project_name':\n result.project_name = fields[f]\n elif f == 'project_id':\n result.project_id = fields[f]\n\n elif f == 'effort_left_d':\n result.effort_left_d = float(fields[f])\n elif f == 'prereqs':\n result.prereqs = dovetail.util.condition_prereqs(fields[f])\n\n elif f == 'key_date':\n result.key_date = dovetail.util.condition_date(fields[f])\n elif f == 'start_date':\n result.start_date = dovetail.util.condition_date(fields[f])\n elif f == 'end_date':\n result.end_date = dovetail.util.condition_date(fields[f])\n return result\n\ndef work_data_to_work_object(work_data):\n result = []\n for w in work_data:\n work = fields_to_work_object(w)\n work.start_date = dovetail.util.condition_date(w['start_date'])\n work.end_date = dovetail.util.condition_date(w['end_date'])\n\n assignee = Person(w['person_id'])\n assignee.name = w['assignee_name']\n assignee.picture = w['assignee_picture']\n\n # TODO: The controller should do this\n assignee.detail_url = '/people/%d' % w['person_id']\n work.assignee = assignee\n result.append(work)\n return result\n\n# This augments work with an assignee Person object\ndef select_work_for_project(connection, project_id):\n work_data = connection.execute(\n '''select w.id, w.title, w.start_date, w.end_date,\n people.id as person_id, people.name as assignee_name,\n people.picture as assignee_picture, w.effort_left_d, w.key_date, w.prereqs\n from work as w\n inner join people on people.id = w.assignee_id\n where w.project_id = %d and w.is_done = 0\n order by topo_order ASC\n ''' % int(project_id))\n\n result = work_data_to_work_object(work_data)\n return result\n\ndef select_work_for_person(connection, person_id):\n work_data = connection.execute(\n '''select w.id, w.title, w.effort_left_d, w.key_date, w.start_date, w.end_date,\n w.prereqs, w.project_id, w.assignee_id,\n projects.name as project_name\n from work as w\n inner join projects on projects.id = w.project_id\n where w.assignee_id = %d and w.is_done = 0\n order by w.start_date ASC\n ''' % int(person_id))\n result = [fields_to_work_object(w) for w in work_data]\n return result\n\ndef select_timelines_for_people(connection, people_ids):\n # This converts something like 'set([1, 2]) to '1, 2'\n people_id_string = str(people_ids)[5:-2]\n if not people_id_string:\n return []\n work_data = connection.execute(\n '''select w.id, w.title, w.key_date, w.start_date, w.end_date, w.key_date as work_key_date,\n w.project_id, w.effort_left_d,\n projects.name as project_name,\n people.name as assignee_name\n from work as w\n inner join projects on projects.id = w.project_id\n inner join people on people.id = w.assignee_id\n where w.assignee_id in (%s) and w.is_done = 0\n order by w.start_date ASC\n ''' % people_id_string)\n assignments = {}\n for w in work_data:\n items = assignments.get(w['assignee_name'], [])\n items.append({\n 'work_id': w['id'],\n 'label': w['title'],\n 'project_id': w['project_id'],\n 'assignee_name': w['assignee_name'],\n 'project_name': w['project_name'],\n 'effort_left_d': w['effort_left_d'],\n 'key_date': dovetail.util.condition_date(w['work_key_date']),\n 'start_date': dovetail.util.condition_date(w['start_date']),\n 'end_date': dovetail.util.condition_date(w['end_date'])\n })\n assignments[w['assignee_name']] = items\n\n return assignments\n\ndef select_key_work_for_project(connection, project_id):\n work_data = connection.execute(\n '''select id, title, effort_left_d, prereqs, assignee_id, key_date\n from work\n where project_id = %d AND key_date NOT NULL AND work.is_done = 0\n order by key_date ASC\n ''' % int(project_id))\n result = [fields_to_work_object(w) for w in work_data]\n return result\n\ndef select_done_work_for_project(connection, project_id):\n work_data = connection.execute(\n '''select w.id, w.title, w.start_date, w.end_date,\n people.id as person_id, people.name as assignee_name,\n people.picture as assignee_picture, w.effort_left_d, w.key_date, w.prereqs\n from work as w\n inner join people on people.id = w.assignee_id\n where w.project_id = %d and w.is_done = 1\n order by topo_order ASC\n ''' % int(project_id))\n\n result = work_data_to_work_object(work_data)\n return result\n\ndef update_work(connection, work_data):\n statement = database.work.update().\\\n where(database.work.c.id == work_data['id']).\\\n values(work_data['fields'])\n connection.execute(statement)\n return\n\ndef update_work_dates(connection, work_collection):\n for w in work_collection:\n statement = database.work.update().\\\n where(database.work.c.id == w.work_id).\\\n values({'start_date': w.est_start_date(), 'end_date': w.est_end_date()})\n connection.execute(statement)\n return\n\ndef update_work_topo_order(connection, work_collection):\n for i, w in enumerate(work_collection):\n statement = database.work.update().\\\n where(database.work.c.id == w.work_id).\\\n values({'topo_order': i})\n connection.execute(statement)\n return\n\ndef mark_work_done(connection, work_ids):\n for w in work_ids:\n statement = database.work.update().\\\n where(database.work.c.id == w).\\\n values({'is_done': True})\n connection.execute(statement)\n return\n\ndef mark_work_undone(connection, work_ids):\n for w in work_ids:\n statement = database.work.update().\\\n where(database.work.c.id == w).\\\n values({'is_done': False})\n connection.execute(statement)\n return\n" }, { "alpha_fraction": 0.638463020324707, "alphanum_fraction": 0.6388415694236755, "avg_line_length": 33.7565803527832, "blob_id": "a8e9c882d4a0dd5afbc8a8b5c772a008030dd779", "content_id": "117f555383e7d08a04516a232903cabb22772b6a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5283, "license_type": "permissive", "max_line_length": 87, "num_lines": 152, "path": "/dovetail/projects/db.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "import json\nimport dovetail.util\nimport dovetail.database as database\nimport dovetail.work.db as work_db\nimport dovetail.people.db as people_db\n\nfrom dovetail.projects.project import Project\nfrom dovetail.work.work import Work\n\ndef data_to_projects(connection, data):\n result = []\n for row in data:\n p = Project(row['id'])\n p.name = row['name']\n p.target_date = dovetail.util.condition_date(row['target_date'])\n p.est_start_date = dovetail.util.condition_date( row['est_start_date'] )\n p.est_end_date = dovetail.util.condition_date( row['est_end_date'] )\n p.value = row['value']\n p.work = work_db.select_work_for_project(connection, row['id'])\n p.key_work = work_db.select_key_work_for_project(connection, row['id'])\n result.append(p)\n return result\n\n# This adds 'key_work' to each project as well\ndef select_project_collection(connection):\n data = connection.execute('''\n select id, name, target_date, est_end_date, est_start_date, value\n from projects\n where is_done = 0\n order by value desc\n ''')\n result = data_to_projects(connection, data)\n return result\n\ndef select_done_project_collection(connection):\n data = connection.execute('''\n select id, name, target_date, est_end_date, est_start_date, value\n from projects\n where is_done = 1\n order by value desc\n ''')\n result = data_to_projects(connection, data)\n return result\n\n\ndef select_project(connection, project_id):\n result = Project(project_id)\n data = connection.execute(database.projects.select(\n database.projects.c.id == project_id)).first()\n\n result.name = data['name']\n # NOTE: We don't need to condition them because we're not doing an explicit select\n # SqlAlchemy takes care of the date manipulation for us\n result.target_date = data['target_date']\n result.est_end_date = data['est_end_date']\n result.participants = people_db.select_project_participants(connection, project_id)\n result.work = work_db.select_work_for_project(connection, project_id)\n return result\n\ndef insert_project(connection, name, target_date):\n result = connection.execute(database.projects.insert(),\n name = name,\n target_date = target_date)\n return result\n\ndef add_project_participant(connection, project_id, person_id):\n data = connection.execute('''\n select project_id, person_id from project_participants\n where project_id = %d and\n person_id = %d\n ''' % (int(project_id), int(person_id)))\n\n if data.first():\n return\n\n connection.execute(database.project_participants.insert(),\n project_id = project_id,\n person_id = person_id)\n return\n\ndef update_project_and_work_dates(connection, projects):\n for p in projects:\n project_work = ([w.est_start_date() for w in p.work])\n if project_work:\n est_start_date = min(project_work)\n else:\n est_start_date = None\n statement = database.projects.update().\\\n where(database.projects.c.id == p.project_id).\\\n values({'est_end_date': p.est_end_date,\n 'est_start_date': est_start_date})\n connection.execute(statement)\n work_db.update_work_dates(connection, p.work)\n return\n\ndef update_project(connection, project):\n statement = database.projects.update().\\\n where(database.projects.c.id == project.project_id).\\\n values({\n 'name': project.name,\n 'target_date': project.target_date\n })\n result = connection.execute(statement)\n return result\n\ndef update_project_collection_value(connection, projects):\n for p in projects:\n statement = database.projects.update().\\\n where(database.projects.c.id == p.project_id).\\\n values({\n 'value': p.value\n })\n result = connection.execute(statement)\n return\n\ndef select_all_project_ids(connection):\n data = connection.execute('select id from projects order by value desc')\n result = [row['id'] for row in data]\n return result\n\ndef get_projects_for_scheduling(connection):\n project_ids = select_all_project_ids(connection)\n result = []\n for project_id in project_ids:\n p = Project(project_id)\n p.work = work_db.select_work_for_project(connection, p.project_id)\n result.append(p)\n return result\n\ndef mark_projects_done(connection, project_ids):\n for p in project_ids:\n statement = database.projects.update().\\\n where(database.projects.c.id == p).\\\n values({'is_done': True})\n connection.execute(statement)\n return\n\ndef mark_projects_undone(connection, project_ids):\n for p in project_ids:\n statement = database.projects.update().\\\n where(database.projects.c.id == p).\\\n values({'is_done': False})\n connection.execute(statement)\n return\n\ndef remove_participant(connection, project_id, person_id):\n print \"Removing %d from %d\" % (person_id, project_id)\n data = connection.execute('''\n delete from project_participants\n where project_id = %d and person_id = %d\n ''' % (project_id, person_id))\n return\n" }, { "alpha_fraction": 0.6151120662689209, "alphanum_fraction": 0.6176019906997681, "avg_line_length": 40.11023712158203, "blob_id": "a94721e03abd1f679a90f6365af389cab37fca5d", "content_id": "ce4a499626d38ffd0a75945a46e13bcd63f054ee", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10442, "license_type": "permissive", "max_line_length": 95, "num_lines": 254, "path": "/dovetail/projects/controller.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "from datetime import datetime\nfrom flask import (Blueprint, Response, json, render_template, request,\n redirect, g)\n\nimport dovetail.util\nimport dovetail.projects.db as projects_db\nimport dovetail.work.db as work_db\nimport dovetail.people.db as people_db\nimport dovetail.projects.util as projects_util\nimport dovetail.scheduler\n\nfrom dovetail.projects.project import Project\n\nfrom dovetail.charts.project_timeline_chart import ProjectTimelineChart\nfrom dovetail.charts.project_collection_timeline_chart import ProjectCollectionTimelineChart\n\nmod = Blueprint('projects', __name__)\n\n# Projects\[email protected]('/projects')\ndef projects():\n projects = projects_db.select_project_collection(g.connection)\n data = []\n project_rank_data = []\n timeline_aux_data = {}\n for i, p in enumerate(projects):\n status = projects_util.compute_status(p.target_date, p.est_end_date)\n target_date = dovetail.util.format_date(p.target_date)\n est_end_date = dovetail.util.format_date(p.est_end_date)\n effort_left_d = dovetail.util.format_effort_left(p.total_effort(), 0)\n d = {\n 'project_id': p.project_id,\n 'rank': i + 1,\n 'name': p.name,\n 'target_date': target_date,\n 'est_end_date': est_end_date,\n 'status': status,\n 'effort_left_d': effort_left_d,\n 'detail_url': '/projects/%d' % p.project_id\n }\n data.append(d)\n project_rank_data.append('%d %s' % (p.project_id, p.name))\n\n timeline_aux_data[p.project_id] = {\n 'title': p.name,\n 'content': '''\n <p class=\"label %s\">%s</p>\n <p>Total effort left: %s</p>\n <p>%s (estimated)</p>\n <p>%s (target)</p>\n ''' % (status['class'], status['label'], effort_left_d, est_end_date, target_date)\n }\n\n project_ids = json.dumps([p.project_id for p in projects])\n\n # TODO: Only select the most recently completed\n done_projects = projects_db.select_done_project_collection(g.connection)\n\n if request.args.get('timeline'):\n chart = ProjectCollectionTimelineChart(datetime.now(), projects)\n return render_template('projects/collection_timeline.html',\n project_data = data,\n projects_url = '/projects',\n projects_timeline_url = '/projects?timeline=true',\n timeline_data = chart.as_json(),\n timeline_aux_data = json.dumps(timeline_aux_data),\n project_rank_data = '\\n'.join(project_rank_data),\n project_ids = project_ids,\n done_projects = done_projects\n )\n else:\n return render_template('projects/collection.html',\n project_data = data,\n projects_url = '/projects',\n projects_timeline_url = '/projects?timeline=true',\n project_rank_data = '\\n'.join(project_rank_data),\n project_ids = project_ids,\n done_projects = done_projects\n )\n\n\[email protected]('/projects/<int:project_id>')\ndef project(project_id):\n project = projects_db.select_project(g.connection, project_id)\n projects_util.format_work_dates(project.work)\n project_data = {\n 'project_id': project.project_id,\n 'name': project.name,\n 'target_date': dovetail.util.format_date(project.target_date),\n 'est_end_date': dovetail.util.format_date(project.est_end_date),\n 'status': projects_util.compute_status(project.target_date, project.est_end_date),\n 'effort_left_d': dovetail.util.format_effort_left(project.total_effort(), 1),\n 'work': project.work,\n 'work_ids': json.dumps([w.work_id for w in project.work]),\n 'participants': project.participants,\n 'details_url': '/projects/%d' % project_id,\n 'details_timeline_url': '/projects/%d?timeline=true' % project_id\n }\n\n if request.args.get('timeline'):\n assignee_ids = set([w.assignee.person_id for w in project.work])\n timelines = work_db.select_timelines_for_people(g.connection, assignee_ids)\n timeline_aux_data = {}\n for bars in timelines.values():\n for bar in bars:\n timeline_aux_data[bar['work_id']] = {\n 'title': '[%s] %s' % (bar['project_name'], bar['label']),\n 'content': '''\n <p>%s</p>\n <p>%s</p>\n <p>Start: %s</p>\n <p>Finish: %s</p>\n ''' % (\n bar['assignee_name'],\n dovetail.util.format_effort_left(bar['effort_left_d']),\n dovetail.util.format_date(bar['start_date']),\n dovetail.util.format_date(bar['end_date'])\n )\n }\n\n chart = ProjectTimelineChart(project_id, datetime.now(), timelines)\n\n return render_template('projects/details_timeline.html',\n project_data = project_data,\n timeline_data = chart.as_json(),\n timeline_aux_data = json.dumps(timeline_aux_data),\n work_data = projects_util.project_work_to_string(project.work),\n participants = people_db.select_project_participants(g.connection, project_id),\n people = people_db.select_people(g.connection))\n else:\n done_work = work_db.select_done_work_for_project(g.connection, project_id)\n projects_util.format_work_dates(done_work)\n return render_template('projects/details.html',\n project_data = project_data,\n work_data = projects_util.project_work_to_string(project.work),\n participants = people_db.select_project_participants(g.connection, project_id),\n done_work = done_work,\n people = people_db.select_people(g.connection))\n\n\n\[email protected]('/api/projects/<int:project_id>', methods=['POST'])\ndef edit_project(project_id):\n name = request.values['name']\n target_date = dovetail.util.parse_date(request.values['target_date'])\n worklines = request.values['worklines'].split('\\n')\n original_work_ids = set(json.loads(request.values['original_work_ids']))\n\n work = []\n for workline in worklines:\n try:\n work_data = projects_util.parse_workline(g.connection, workline)\n fields = work_data['fields']\n fields.update(project_id = project_id)\n\n # Save any changes to the work items\n # TOOD: Separate topo sort work so we only have to write to database once\n work_db.update_work(g.connection, work_data)\n fields.update(id = work_data['id'])\n work.append(work_db.fields_to_work_object(fields))\n except:\n # TODO: log something\n pass\n\n # Mark missing work as done\n returned_work_ids = set([w.work_id for w in work])\n done_work_ids = original_work_ids - returned_work_ids\n work_db.mark_work_done(g.connection, done_work_ids)\n\n project = Project(project_id)\n project.name = name\n project.target_date = target_date\n project.work = work\n project.topo_sort_work()\n work_db.update_work_topo_order(g.connection, project.work)\n #dovetail.scheduler.reschedule_world(g.connection)\n\n # Update project info\n projects_db.update_project(g.connection, project)\n\n response_data = {}\n result = Response(json.dumps(response_data), status=200, mimetype='application/json')\n return result\n\[email protected]('/api/projects', methods=['POST'])\ndef api_add_project():\n target_date = dovetail.util.parse_date(request.values['target_date'])\n insert_result = projects_db.insert_project(g.connection,\n request.values['name'], target_date)\n response_data = {'project_id': insert_result.inserted_primary_key}\n return Response(json.dumps(response_data), status=200, mimetype='application/json')\n\[email protected]('/api/projects/<int:project_id>/participants', methods=['POST'])\ndef api_add_project_participant(project_id):\n person_id = int(request.values['person_id'])\n projects_db.add_project_participant(g.connection, project_id, person_id)\n response_data = {}\n return Response(json.dumps(response_data), status=200, mimetype='application/json')\n\ndef parse_project_line(line, value):\n parts = line.split()\n result = Project(parts[0])\n result.value = value\n return result\n\[email protected]('/api/projects/rankings', methods=['POST'])\ndef rank_projects():\n project_lines = request.values['project_lines'].split('\\n')\n original_project_ids = set(json.loads(request.values['original_project_ids']))\n\n # TODO: Figure out how to compute project value\n cur_value = 100\n projects = []\n for line in project_lines:\n try:\n p = parse_project_line(line, cur_value)\n cur_value -= 1\n projects.append(p)\n except:\n # TODO: log something\n pass\n\n # Returned project ids\n returned_project_ids = set([int(p.project_id) for p in projects])\n done_project_ids = original_project_ids - returned_project_ids\n projects_db.mark_projects_done(g.connection, done_project_ids)\n\n # Update project info\n projects_db.update_project_collection_value(g.connection, projects)\n #dovetail.scheduler.reschedule_world(g.connection)\n\n response_data = {}\n result = Response(json.dumps(response_data), status=200, mimetype='application/json')\n return result\n\[email protected]('/projects/reschedule', methods=['POST'])\ndef reschedule_projects():\n dovetail.scheduler.reschedule_world(g.connection)\n return redirect('/projects')\n\[email protected]('/api/projects/<int:project_id>/mark_undone', methods=['POST'])\ndef api_mark_projects_undone(project_id):\n projects_db.mark_projects_undone(g.connection, [project_id])\n response_data = {}\n result = Response(json.dumps(response_data), status=200, mimetype='application/json')\n return result\n\[email protected]('/api/projects/<int:project_id>/remove_participant', methods=['POST'])\ndef api_remove_participant(project_id):\n person_id = int(request.values['person_id'])\n projects_db.remove_participant(g.connection, project_id, person_id)\n response_data = {}\n result = Response(json.dumps(response_data), status=200, mimetype='application/json')\n return result\n" }, { "alpha_fraction": 0.5490286946296692, "alphanum_fraction": 0.6091581583023071, "avg_line_length": 32.230770111083984, "blob_id": "c80df8bef1f773e08de6226a0f70299b76c892cf", "content_id": "03ad8ea1696dff0279d37abd1802611ae6987087", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2162, "license_type": "permissive", "max_line_length": 80, "num_lines": 65, "path": "/dovetail/tests/test_scheduler.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "import unittest\nfrom mock import MagicMock\nfrom datetime import datetime\nfrom dovetail.scheduler import Scheduler\nfrom dovetail.projects.project import Project\nfrom dovetail.work.work import Work\nimport dovetail.tests.util as util\n\nclass TestScheduler(unittest.TestCase):\n\n def test_construct_assignee_timelines(self):\n scheduler = Scheduler(util.nov1)\n t101 = scheduler.get_assignee_timeline(101)\n self.assertEqual(0, len(t101.dates))\n self.assertEqual(util.nov1, t101.cur_date)\n return\n \n def test_schedule_project(self):\n # Assignees\n person_id1 = 101\n person_id2 = 102\n person_id3 = 103\n\n # Projects\n p1 = Project(1)\n p1_w1 = util.construct_work(1, \"p1 w1\", 1.0, [], person_id1, None)\n p1_w2 = util.construct_work(2, \"p1 w2\", 1.0, [], person_id1, None)\n p1_w3 = util.construct_work(5, \"p1 w3\", 0.1, [], person_id1, util.nov15)\n p1.work = [p1_w1, p1_w2, p1_w3]\n\n p2 = Project(2)\n p2_w1 = util.construct_work(3, \"p2 w1\", 1.0, [], person_id2, None)\n p2_w2 = util.construct_work(4, \"p2 w2\", 1.0, [2], person_id3, None)\n p2.work = [p2_w1, p2_w2]\n\n # Scheduler\n scheduler = Scheduler(util.nov1)\n projects = scheduler.schedule_projects([p1, p2])\n\n # Check work end dates\n self.assertEqual(util.nov2, p1_w1.est_end_date())\n self.assertEqual(util.nov5, p1_w2.est_end_date())\n self.assertEqual(util.nov2, p2_w1.est_end_date())\n self.assertEqual(util.nov6, p2_w2.est_end_date())\n\n # Check project end dates\n self.assertEqual(util.nov15, p1.est_end_date)\n self.assertEqual(util.nov6, p2.est_end_date)\n return\n\n def test_schedule_with_key_date_in_past(self):\n # Assignees\n person_id1 = 101\n\n # Projects\n p1 = Project(1)\n p1_w3 = util.construct_work(5, \"p1 w3\", 0.1, [], person_id1, util.nov1)\n p1.work = [p1_w3]\n\n # Scheduler\n scheduler = Scheduler(util.nov15)\n projects = scheduler.schedule_projects([p1])\n\n self.assertEqual(util.nov15, p1.est_end_date)\n return\n\n\n" }, { "alpha_fraction": 0.5600505471229553, "alphanum_fraction": 0.5646860599517822, "avg_line_length": 31.054054260253906, "blob_id": "69ff417a15b0eca0e9d0f67504b5a3f49cb9b3e4", "content_id": "d3b1baa4e90fd7164b9902ddefb972bf776d3f9e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2373, "license_type": "permissive", "max_line_length": 109, "num_lines": 74, "path": "/dovetail/projects/util.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "import json\n\n# TODO: Get rid of this import\nimport dovetail.work.db as work_db\nimport dovetail.database as database\nimport dovetail.people.db as people_db\nimport dovetail.util\n\ndef shorten_name(name):\n return name\n\ndef format_prereqs(prereqs):\n if prereqs:\n return prereqs\n else:\n return \"[]\"\n\n\ndef project_work_to_string(work_data):\n result = ''\n for w in work_data:\n result += '[%d, \"%s\", \"%s\", \"%s\", %s, \"%s\"]\\n' % (\n w.work_id,\n shorten_name(w.assignee.name),\n dovetail.util.format_effort_left(w.effort_left_d),\n w.title,\n format_prereqs(w.prereqs),\n dovetail.util.format_date(w.key_date))\n return result\n\ndef parse_workline(connection, workline):\n data = json.loads(workline)\n # TODO: Do some error handling here\n person = people_db.select_person_by_name(connection, data[1])\n effort_left_d = float(data[2].split()[0])\n key_date = None\n if data[5] not in ['?', '']:\n key_date = dovetail.util.parse_date(data[5])\n\n result = {\n 'id': data[0],\n 'fields': {\n 'assignee_id': person.person_id,\n 'effort_left_d': effort_left_d,\n 'title': data[3],\n 'prereqs': str(data[4]),\n 'key_date': key_date\n }\n }\n return result\n\n# TODO: Abstract the early and lateness and use with ProjectCollectionTimelineChart\ndef compute_status(target_date, est_date):\n if not est_date:\n return {'label': 'UNKNOWN', 'class': '', 'date_class': ''}\n\n delta = est_date - target_date\n if (delta.days <= -5):\n result = {'label': 'EARLY', 'class': 'label-success', 'date_class': ''}\n elif (delta.days > -5 and delta.days <= 0):\n result = {'label': 'ON TRACK', 'class': '', 'date_class': ''}\n else:\n result = {'label': 'LATE - %dd' % delta.days, 'class': 'label-important', 'date_class': 'text-error'}\n return result\n\n\ndef format_work_dates(work_collection):\n for w in work_collection:\n if w.key_date and w.end_date and w.end_date > w.key_date:\n w.title_class = 'text-error'\n w.key_date_class = 'text-error'\n w.key_date_str = dovetail.util.format_date(w.key_date)\n w.end_date_str = dovetail.util.format_date(w.end_date)\n return\n\n" }, { "alpha_fraction": 0.5405777096748352, "alphanum_fraction": 0.5632737278938293, "avg_line_length": 33.619049072265625, "blob_id": "bb57f049bce0c96a1e7bbf948b41976859408e5b", "content_id": "e653c1688840b96845e6875225c40465d146b4e7", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1454, "license_type": "permissive", "max_line_length": 91, "num_lines": 42, "path": "/dovetail/charts/person_timeline_chart.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "from datetime import datetime, timedelta\nimport dovetail.util\nfrom dovetail.charts.support.gantt import Gantt\n\nclass PersonTimelineChart:\n def __init__(self, cur_day, person):\n self.cur_day = dovetail.util.standardize_date(cur_day)\n self.data = [{\n 'label': person.name,\n 'bars': self.work_to_bars(person.work)\n }]\n return\n\n def work_to_bars(self, work):\n colors = ['#08C', '#1531AE', '#FF8300', '#024E68', '#2D3C82', '#A65500', '#2D3C82']\n project_color = {}\n\n result = []\n color = '#08C'\n for w in work:\n result.append({\n 'id': w.work_id,\n 'start': w.start_date,\n 'end': w.end_date,\n 'effort_d': w.effort_left_d,\n 'color': self.get_project_color(w.project_id, project_color, colors)\n })\n return result\n\n def get_project_color(self, project_id, project_color_dict, colors):\n if not project_color_dict.has_key(project_id):\n new_color_index = len(project_color_dict) % len(colors)\n project_color_dict[project_id] = new_color_index\n\n result = colors[project_color_dict[project_id]]\n return result\n\n def as_json(self):\n # Set the end date of the chart to be 3 weeks out\n max_date = self.cur_day + timedelta(21)\n gantt = Gantt(self.cur_day, self.data, max_date)\n return gantt.as_json()\n" }, { "alpha_fraction": 0.5661218166351318, "alphanum_fraction": 0.6225854158401489, "avg_line_length": 32.650001525878906, "blob_id": "847720978690943c9c07f3b213d9e44cdb55bcb7", "content_id": "925a07eb2c8bbc88cae6726431d17cf5e0975441", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 673, "license_type": "permissive", "max_line_length": 79, "num_lines": 20, "path": "/dovetail/tests/test_gantt.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "import unittest\nfrom mock import MagicMock\nfrom datetime import datetime\nfrom dovetail.charts.support.gantt import Gantt\nimport dovetail.tests.util as util\n\nclass TestGantt(unittest.TestCase):\n\n def test_compute_dates(self):\n gantt = Gantt(util.nov1, [], util.nov23)\n self.assertEqual([util.nov5, util.nov12, util.nov19], gantt.tick_dates)\n return\n\n def test_compute_date_labels(self):\n gantt = Gantt(util.nov1, [], util.nov23)\n self.assertEqual([\n {'label': 'Nov 05, 2012', 'x': 220},\n {'label': 'Nov 12, 2012', 'x': 430},\n {'label': 'Nov 19, 2012', 'x': 640}], gantt.date_labels())\n return\n" }, { "alpha_fraction": 0.5771756768226624, "alphanum_fraction": 0.5833333134651184, "avg_line_length": 33.06993103027344, "blob_id": "3496130171ddedae2c21bed211eddc3754fc141d", "content_id": "82ee2c1d663cffaeac8016c3b52bf40ce938b26d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4872, "license_type": "permissive", "max_line_length": 78, "num_lines": 143, "path": "/dovetail/timeline/timeline.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "import dovetail.util\nfrom dovetail.timeline.slot import Slot\nfrom datetime import timedelta\n\ndef update_days(start_day, width):\n return start_day, start_day + width\n\ndef increment_date(date):\n delta1 = timedelta(1) # 1 day\n return date + delta1\n\nclass Timeline():\n\n def __init__(self, cur_date):\n self.slots = [Slot(0, float('inf'))]\n self.cur_date = dovetail.util.standardize_date(cur_date)\n self.dates = []\n\n def find_slot(self, earliest_start_day, width):\n # Default to the last, infinite slot\n start_day, end_day = update_days(self.slots[-1].start_day, width)\n new_slot = Slot(start_day, end_day)\n containing_slot_index = len(self.slots) - 1\n\n modify_start_date = False\n start_day, end_day = update_days(earliest_start_day, width)\n for i, s in enumerate(self.slots):\n if modify_start_date:\n start_day, end_day = update_days(s.start_day, width)\n if s.contains(start_day, end_day):\n new_slot = Slot(start_day, end_day)\n containing_slot_index = i\n break\n else:\n modify_start_date = True\n\n # Set slot dates\n new_slot.start_date = self.date_from_day(new_slot.start_day)\n new_slot.end_date = self.date_from_day(new_slot.end_day)\n return new_slot, containing_slot_index\n\n # index is the index of the containing slot\n def claim_slot(self, slot, index):\n new_slots = self.slots[index].fill(slot.start_day, slot.end_day)\n self.slots = self.slots[:index] + new_slots + self.slots[index+1:]\n return slot\n\n def day_from_date(self, date):\n date = dovetail.util.standardize_date(date)\n\n # If date is in the past, return 0 (current date)\n if date < self.cur_date:\n return 0\n if self.need_to_add_dates(date):\n self.add_dates_to(date)\n\n # Keep incrementing date until we find one in the timeline.\n # This is guaranteed because add_dates will add at least one date\n # at or after the specified date.\n while not date in self.dates:\n date = increment_date(date)\n return self.dates.index(date)\n\n def need_to_add_dates(self, date):\n date = dovetail.util.standardize_date(date)\n return self.dates == [] or date > self.dates[-1]\n\n def is_workday(self, date):\n # TODO: Check holiday or OOO\n if date.weekday() in [5, 6]:\n result = False\n else:\n result = True\n return result\n\n def add_dates_to(self, end_date, min_dates_added = 1):\n if end_date < self.cur_date:\n return\n\n end_date = dovetail.util.standardize_date(end_date)\n\n num_dates_added = 0\n delta1 = timedelta(1) # 1 day\n if self.dates == []:\n date = self.cur_date - delta1\n else:\n date = self.dates[-1]\n\n # Push end date out until it's a workday\n while not self.is_workday(end_date):\n end_date += delta1\n\n while date < end_date:\n date += delta1\n if self.is_workday(date):\n self.dates.append(date)\n num_dates_added += 1\n if date == end_date and num_dates_added < min_dates_added:\n end_date += delta1\n return\n\n def add_days_to(self, day):\n num_days_to_add = day - len(self.dates) + 1\n if num_days_to_add <= 0:\n return\n\n if self.dates == []:\n start_date = self.cur_date\n else:\n start_date = increment_date(self.dates[-1])\n\n self.add_dates_to(start_date, num_days_to_add)\n return\n\n def date_from_day(self, day):\n # int() takes the floor of a float. This is what we want here since\n # integers correspond to the start of a day.\n day = int(day)\n if day < 0:\n return\n self.add_days_to(day)\n return self.dates[day]\n\n def find_slot_with_ending_date(self, end_date, width):\n end_date = dovetail.util.standardize_date(end_date)\n\n # Target ending halfway through the end date\n end_day = self.day_from_date(end_date) + 0.5\n start_day = end_day - width\n return self.find_slot(start_day, width)\n\n def schedule_at_start_date(self, start_date, effort_left_d):\n start_date = dovetail.util.standardize_date(start_date)\n day = self.day_from_date(start_date)\n slot, parent_index = self.find_slot(day, effort_left_d)\n slot = self.claim_slot(slot, parent_index)\n return slot\n\n def schedule_at_end_date(self, end_date, effort_left_d):\n end_date = dovetail.util.standardize_date(end_date)\n slot, index = self.find_slot_with_ending_date(end_date, effort_left_d)\n slot = self.claim_slot(slot, index)\n return slot\n" }, { "alpha_fraction": 0.5054054260253906, "alphanum_fraction": 0.5111486315727234, "avg_line_length": 28.009803771972656, "blob_id": "4964c322f36521472f0380fe284f9c6db6dc3b31", "content_id": "ca9099710ddb7b03258daca7f98eaff1b4818aca", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2960, "license_type": "permissive", "max_line_length": 90, "num_lines": 102, "path": "/dovetail/charts/support/gantt.py", "repo_name": "rjose/dovetail", "src_encoding": "UTF-8", "text": "from datetime import datetime, timedelta\nimport dovetail.util\nimport json\n\nclass Gantt:\n # Each row looks like this:\n # [{label: 'Person', bars: [{start: Date, end: Date, effort_d: Float, color: 'blue'}]}\n def __init__(self, cur_day, rows, max_date):\n # Chart params\n self.Y_STEP = 30\n self.START_X = 120\n self.START_Y = 20\n self.BAR_HEIGHT = 25\n self.PIXELS_PER_DAY = 30\n self.X_MARGIN = 2\n\n self.cur_day = dovetail.util.standardize_date(cur_day)\n self.max_date = dovetail.util.standardize_date(max_date)\n self.tick_dates = self.compute_tick_dates(self.cur_day, self.max_date)\n self.data = self.transform(rows)\n return\n\n def date_to_x(self, date):\n delta = date - self.cur_day\n result = self.START_X + delta.days * self.PIXELS_PER_DAY\n return result\n\n def compute_tick_dates(self, start_day, max_day):\n one_day = timedelta(1)\n one_week = timedelta(7)\n\n result = []\n # Find next monday\n cur_day = start_day\n while cur_day.weekday() != 0: # Not monday\n cur_day = cur_day + one_day\n\n result.append(cur_day)\n\n # Add mondays up till the max_day\n cur_day = cur_day + one_week\n while cur_day <= max_day:\n result.append(cur_day)\n cur_day = cur_day + one_week\n\n return result\n\n def date_labels(self):\n return self.data['dates']\n\n def transform_row(self, row, cur_y):\n result = {\n 'label': row['label'],\n 'y': cur_y,\n 'bars': []\n }\n\n for b in row['bars']:\n if not b['start'] or not b['end']:\n continue\n\n # Figure out start and ending x values for each bar\n x_start = self.date_to_x(b['start'])\n x_end = self.date_to_x(b['end'])\n if x_start == x_end:\n x_end = x_start + b['effort_d'] * self.PIXELS_PER_DAY\n x_end -= self.X_MARGIN\n\n result['bars'].append({\n 'id': b['id'],\n 'x': x_start,\n 'width': x_end - x_start,\n 'height': self.BAR_HEIGHT,\n 'color': b['color']\n })\n return result\n\n def compute_chart_height(self, num_rows):\n buffer = 40\n result = num_rows * self.Y_STEP + buffer\n return result\n\n\n def transform(self, rows):\n result = {\n 'rows': [],\n 'dates': [],\n 'chart_height': self.compute_chart_height(len(rows))\n }\n\n cur_y = self.START_Y\n for r in rows:\n result['rows'].append(self.transform_row(r, cur_y))\n cur_y += self.Y_STEP\n\n result['dates'] = [{\n 'label': dovetail.util.format_date(d),\n 'x': self.date_to_x(d)} for d in self.tick_dates]\n return result\n\n def as_json(self):\n return json.dumps(self.data)\n\n" } ]
31
carlclone/python-concurrent-programming-demo
https://github.com/carlclone/python-concurrent-programming-demo
99b9f55792e8e08544a05900919e9d986e0b7cb8
e4ecf0a11d93e8799f053d1e3a4daa13fdbd5ca8
2addff905cb3ff740e05a7785c726450aa880b5a
refs/heads/master
2020-09-28T13:51:25.207058
2019-12-09T05:19:35
2019-12-09T05:19:35
226,790,780
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6548451781272888, "alphanum_fraction": 0.6878122091293335, "avg_line_length": 28.455883026123047, "blob_id": "3cf548df771cfd9ce54c0951c954f18f3f024508", "content_id": "975b21ac394aa72ec1d51acecba520cc263cc084", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2850, "license_type": "no_license", "max_line_length": 124, "num_lines": 68, "path": "/co6.py", "repo_name": "carlclone/python-concurrent-programming-demo", "src_encoding": "UTF-8", "text": "import asyncio\nimport random\n\n# 到这里就能知道 : 线程能实现的,协程都能做到\n# 生产者消费者模型\n\n# 协程和多线程的区别,主要在于两点,一是协程为单线程;二是协程由用户决定,在哪些地方交出控制权,切换到下一个任务。\n# 协程的写法更加简洁清晰,把 async / await 语法和 create_task 结合来用,对于中小级别的并发需求已经毫无压力。\n# 写协程程序的时候,你的脑海中要有清晰的事件循环概念,知道程序在什么时候需要暂停、等待 I/O,什么时候需要一并执行到底。\n\n# 最后的最后,请一定不要轻易炫技。多线程模型也一定有其优点,一个真正牛逼的程序员,应该懂得,在什么时候用什么模型能达到工程上的最优,而不是自觉某个技术非常牛逼,所有项目创造条件也要上。技术是工程,而工程则是时间、资源、人力等纷繁复杂的事情的折衷。\n\n# 思考题 : py的协程怎么实现回调函数?\n# 使用asyncio获取事件循环,将执行的函数使用loop创建一个任务。add_done_callback将回掉函数传进去。\n# 阻塞主要是同步编程中的概念:执行一个系统调用,如果暂时没有返回结果,这个调用就不会返回,那这个系统调用后面的应用代码也不会执行,整个应用被“阻塞”了。\nasync def consumer(queue, id):\n while True:\n val = await queue.get()\n print('{} get a val: {}'.format(id, val))\n await asyncio.sleep(1)\n\nasync def producer(queue, id):\n for i in range(5):\n val = random.randint(1, 10)\n await queue.put(val)\n print('{} put a val: {}'.format(id, val))\n await asyncio.sleep(1)\n\nasync def main():\n queue = asyncio.Queue()\n\n consumer_1 = asyncio.create_task(consumer(queue, 'consumer_1'))\n consumer_2 = asyncio.create_task(consumer(queue, 'consumer_2'))\n\n producer_1 = asyncio.create_task(producer(queue, 'producer_1'))\n producer_2 = asyncio.create_task(producer(queue, 'producer_2'))\n\n await asyncio.sleep(10)\n consumer_1.cancel()\n consumer_2.cancel()\n\n await asyncio.gather(consumer_1, consumer_2, producer_1, producer_2, return_exceptions=True)\n\n%time asyncio.run(main())\n\n########## 输出 ##########\n\n# producer_1 put a val: 5\n# producer_2 put a val: 3\n# consumer_1 get a val: 5\n# consumer_2 get a val: 3\n# producer_1 put a val: 1\n# producer_2 put a val: 3\n# consumer_2 get a val: 1\n# consumer_1 get a val: 3\n# producer_1 put a val: 6\n# producer_2 put a val: 10\n# consumer_1 get a val: 6\n# consumer_2 get a val: 10\n# producer_1 put a val: 4\n# producer_2 put a val: 5\n# consumer_2 get a val: 4\n# consumer_1 get a val: 5\n# producer_1 put a val: 2\n# producer_2 put a val: 8\n# consumer_1 get a val: 2\n# consumer_2 get a val: 8\n# Wall time: 10 s" }, { "alpha_fraction": 0.5314401388168335, "alphanum_fraction": 0.563894510269165, "avg_line_length": 11.350000381469727, "blob_id": "769c678e26970c331c2db38795a374a44eed42e4", "content_id": "cfcd640d762bd460c3c04fbd66b340980dad0890", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 531, "license_type": "no_license", "max_line_length": 42, "num_lines": 40, "path": "/co.py", "repo_name": "carlclone/python-concurrent-programming-demo", "src_encoding": "UTF-8", "text": "# encoding: utf-8\nimport time\n\n\ndef crawl_page(url):\n print('crawling {}'.format(url))\n sleep_time = int(url.split('_')[-1])\n # 阻塞 , cpu有大量闲置时间 , 可以使用并发编程优化\n time.sleep(sleep_time)\n print('OK {}'.format(url))\n\n\ndef main(urls):\n for url in urls:\n crawl_page(url)\n\n# % time\nmain(['url_1', 'url_2', 'url_3', 'url_4'])\n\n\n#\n# crawling\n# url_1\n# OK\n# url_1\n# crawling\n# url_2\n# OK\n# url_2\n# crawling\n# url_3\n# OK\n# url_3\n# crawling\n# url_4\n# OK\n# url_4\n# Wall\n# time: 10\n# s" }, { "alpha_fraction": 0.5939553380012512, "alphanum_fraction": 0.6281208992004395, "avg_line_length": 19.594594955444336, "blob_id": "8cc197d35897df600dc0f74bc48a9cbdf832d936", "content_id": "6bca5a146dcd75ec4e3540e409c4df3e923f0840", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 887, "license_type": "no_license", "max_line_length": 59, "num_lines": 37, "path": "/co4.py", "repo_name": "carlclone/python-concurrent-programming-demo", "src_encoding": "UTF-8", "text": "import asyncio\n\n\nasync def worker_1():\n print('worker_1 start')\n await asyncio.sleep(1) # 任务调度点 , cpu闲置 , 调度到其他任务执行\n print('worker_1 done')\n\n\nasync def worker_2():\n print('worker_2 start')\n await asyncio.sleep(2) # 任务调度点 , cpu闲置 , 调度到其他任务执行\n print('worker_2 done')\n\n\nasync def main():\n task1 = asyncio.create_task(worker_1())\n task2 = asyncio.create_task(worker_2()) # 实际上创建完后就开始调度了\n print('before await')\n await task1 #同步的 , 等待task1完成后执行\n print('awaited worker_1')\n await task2 #同上\n print('awaited worker_2')\n\n% time\nasyncio.run(main()) #启动调度\n\n########## 输出 ##########\n\n# before await\n# worker_1 start\n# worker_2 start\n# worker_1 done\n# awaited worker_1\n# worker_2 done\n# awaited worker_2\n# Wall time: 2.01 s" }, { "alpha_fraction": 0.561904788017273, "alphanum_fraction": 0.6247618794441223, "avg_line_length": 28.16666603088379, "blob_id": "65231f07918ca787a73c3be5c128d69c39cf4fdd", "content_id": "a669e033d07e0ba7bef8746593de463efe2c7c32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 525, "license_type": "no_license", "max_line_length": 108, "num_lines": 18, "path": "/j.py", "repo_name": "carlclone/python-concurrent-programming-demo", "src_encoding": "UTF-8", "text": "import requests\nimport json\n\nmain_url = 'http://210.4.101.11:8081/API/'\n\nheaders = {'Authorization': 'Basic QXBpVXNlckFkbWluOnBlc29xMjAxOA==',\n \"Content-Type\": 'application/json'}\n\n# num = s1.join('%s' %id for id in [8080]*32)\n# port = s1.join('%s' %id for id in list(range(1,33)) )\n\n\ndata = '{\"event\": \"txsms\", \"userid\": \"0\", \"num\": \"8080\", \"port\": \"1\", \"encoding\": \"0\", \"smsinfo\": \"STATUS\"}'\n\nr = requests.post(url=main_url + \"SendSMS\", headers=headers, data=data)\n# data=json.dumps(data)\nprint (data)\nprint (r)\n" }, { "alpha_fraction": 0.6046832203865051, "alphanum_fraction": 0.6267217397689819, "avg_line_length": 15.133333206176758, "blob_id": "db43e6c9929bd4095431c173fcd3041735c85fa3", "content_id": "2c10262227a4933c5af81652b03c84188ae92e7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 930, "license_type": "no_license", "max_line_length": 72, "num_lines": 45, "path": "/co1.py", "repo_name": "carlclone/python-concurrent-programming-demo", "src_encoding": "UTF-8", "text": "# encoding: utf-8\nimport asyncio\n\n# async创建协程object , await调用就和正常顺序执行一样的效果\n# 还可以通过create task 创建任务 , 事件循环+真正的并发\n# 然后使用asyncio.run运行\n# 一个非常好的编程规范是,asyncio.run(main()) 作为主程序的入口函数,在程序运行周期内,只调用一次 asyncio.run。\n\n# await是同步调用\n# 这段是用异步接口写了同步代码\nasync def crawl_page(url):\n print('crawling {}'.format(url))\n sleep_time = int(url.split('_')[-1])\n await asyncio.sleep(sleep_time)\n print('OK {}'.format(url))\n\n\nasync def main(urls):\n for url in urls:\n await crawl_page(url)\n\n# % time\nasyncio.run(main(['url_1', 'url_2', 'url_3', 'url_4']))\n\n########## 输出 ##########\n\n# crawling\n# url_1\n# OK\n# url_1\n# crawling\n# url_2\n# OK\n# url_2\n# crawling\n# url_3\n# OK\n# url_3\n# crawling\n# url_4\n# OK\n# url_4\n# Wall\n# time: 10\n# s\n" }, { "alpha_fraction": 0.5909774303436279, "alphanum_fraction": 0.6270676851272583, "avg_line_length": 20.483871459960938, "blob_id": "19067cf6e01230f8d349fdee12a4edefeb361abc", "content_id": "00ba8cd0338faa172702cf863e193b8b93025f68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 697, "license_type": "no_license", "max_line_length": 78, "num_lines": 31, "path": "/co5.py", "repo_name": "carlclone/python-concurrent-programming-demo", "src_encoding": "UTF-8", "text": "import asyncio\n\nasync def worker_1():\n await asyncio.sleep(1)\n return 1\n\nasync def worker_2():\n await asyncio.sleep(2)\n return 2 / 0\n\nasync def worker_3():\n await asyncio.sleep(3)\n return 3\n\nasync def main():\n task_1 = asyncio.create_task(worker_1())\n task_2 = asyncio.create_task(worker_2())\n task_3 = asyncio.create_task(worker_3())\n\n await asyncio.sleep(2) #设置超时时间 , 每个等2秒\n task_3.cancel() # 取消任务\n\n res = await asyncio.gather(task_1, task_2, task_3, return_exceptions=True)\n print(res)\n\n%time asyncio.run(main())\n\n########## 输出 ##########\n\n# [1, ZeroDivisionError('division by zero'), CancelledError()]\n# Wall time: 2 s" }, { "alpha_fraction": 0.5516666769981384, "alphanum_fraction": 0.5833333134651184, "avg_line_length": 11.520833015441895, "blob_id": "209795a13f03acf41f03264f17309e7c0d8b78be", "content_id": "c20b1f986e93f73bbe2359937bbe8cf833ed6c64", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 604, "license_type": "no_license", "max_line_length": 29, "num_lines": 48, "path": "/co3.py", "repo_name": "carlclone/python-concurrent-programming-demo", "src_encoding": "UTF-8", "text": "import asyncio\n\n\nasync def worker_1():\n print('worker_1 start')\n await\n asyncio.sleep(1)\n print('worker_1 done')\n\n\nasync def worker_2():\n print('worker_2 start')\n await\n asyncio.sleep(2)\n print('worker_2 done')\n\n\nasync def main():\n print('before await')\n await\n worker_1()\n print('awaited worker_1')\n await\n worker_2()\n print('awaited worker_2')\n\n% time\nasyncio.run(main())\n\n########## 输出 ##########\n#\n# before\n# await\n# worker_1\n# start\n# worker_1\n# done\n# awaited\n# worker_1\n# worker_2\n# start\n# worker_2\n# done\n# awaited\n# worker_2\n# Wall\n# time: 3\n# s" } ]
7
akashdeepdeb/Socket-programming-in-Python
https://github.com/akashdeepdeb/Socket-programming-in-Python
df6caf2260f350c4496e7983fbe9dd5fb5372629
d332df721b2fb18e824f58f1b3c7f5aa3866a8de
bb80fffe404eee7796f1cbe68a54d6a24bd1bbb0
refs/heads/master
2021-05-10T19:10:21.627855
2018-01-19T15:59:19
2018-01-19T15:59:19
118,145,912
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8360655903816223, "alphanum_fraction": 0.8360655903816223, "avg_line_length": 29.5, "blob_id": "4e0994320075f27c7cf0d34d46ce811f1705d9cc", "content_id": "a4f005e94613222cdeeb0b70bde06cfbb639af1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 61, "license_type": "no_license", "max_line_length": 30, "num_lines": 2, "path": "/README.md", "repo_name": "akashdeepdeb/Socket-programming-in-Python", "src_encoding": "UTF-8", "text": "# Socket-programming-in-Python\nTrying out socket programming\n" }, { "alpha_fraction": 0.648876428604126, "alphanum_fraction": 0.6769663095474243, "avg_line_length": 16.75, "blob_id": "2565f98e9b24bd60edbb6cd0bb4d83443e8de57b", "content_id": "38f719a3e09b34d8f0b690d0be2cb137dcbe4648", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 356, "license_type": "no_license", "max_line_length": 51, "num_lines": 20, "path": "/server.py", "repo_name": "akashdeepdeb/Socket-programming-in-Python", "src_encoding": "UTF-8", "text": "import socket\n\ns = socket.socket()\nprint('Socket successfully created')\n\nport = 6000\ns.bind(('', port))\nprint(\"socket binded to %s\" %port)\ns.listen(5)\nprint(\"socket is listening\")\n\nmessage = 'Hey'\n\nwhile True:\n\tc, addr = s.accept() #receives address from client\n\tprint(addr)\n\tc.send(message.encode('utf-8'))\n\t#data = c.recv(1024)\n\t#print(data)\n\tc.close()\n\n" }, { "alpha_fraction": 0.6727272868156433, "alphanum_fraction": 0.7116883397102356, "avg_line_length": 18.299999237060547, "blob_id": "9d60b23978cfd8a2c70ba9ab5e0e3ebffaf8c54c", "content_id": "a0ed2752c59a5eb7ab1cb0956422d7b3a1c6292b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 385, "license_type": "no_license", "max_line_length": 54, "num_lines": 20, "path": "/client.py", "repo_name": "akashdeepdeb/Socket-programming-in-Python", "src_encoding": "UTF-8", "text": "import socket\nimport sys\n\ntry:\n\ts = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\tprint(\"Socket successfully created\")\nexcept socket.error as err:\n\tprint('socket creation failed error %s'%(err))\n\nport = 6000\n\ntry: \n\thost_ip = socket.gethostbyaddr('10.193.31.54')[0]\nexcept:\n\tsocket.gaierror()\n\tsys.exit()\n\ns.connect((host_ip, port))\nmessage = 'hey'\ns.send(message.encode('utf-8'))" } ]
3
OneGov/dev
https://github.com/OneGov/dev
892d9229180e6a0c14206fc1ea11788fce5c54ce
04f5fdf3f3f54ea0dd1a795e66915fb78499e0db
2e5095648e017bde02dcc31854a9a85fb7b20a5a
refs/heads/master
2020-04-03T20:23:25.019194
2019-08-26T15:05:07
2019-08-26T15:05:07
30,868,727
3
0
null
2015-02-16T13:07:38
2016-11-03T15:41:28
2017-09-22T12:00:27
Jupyter Notebook
[ { "alpha_fraction": 0.42424243688583374, "alphanum_fraction": 0.7272727489471436, "avg_line_length": 15.5, "blob_id": "00d30f5f8a0eb7bce4aaebcea580ea73c722c806", "content_id": "5b7bd8a6c482ac5a3802537b76a69761b37016c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 33, "license_type": "no_license", "max_line_length": 23, "num_lines": 2, "path": "/.flake8", "repo_name": "OneGov/dev", "src_encoding": "UTF-8", "text": "[flake8]\nignore = E711,E712,W503\n" }, { "alpha_fraction": 0.7415356040000916, "alphanum_fraction": 0.7496667504310608, "avg_line_length": 25.792856216430664, "blob_id": "f708f829aa2d0902bb3d1674d0bc65245bcc4aa5", "content_id": "220f37b3ba4a1188668231219e0c4e4358f35a17", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7502, "license_type": "no_license", "max_line_length": 122, "num_lines": 280, "path": "/README.md", "repo_name": "OneGov/dev", "src_encoding": "UTF-8", "text": "# Development Environment for Onegov\n\nAbout OneGov: http://docs.onegovcloud.ch/\n\nRequirements:\n\n - Python 3.6+\n - Postgres 10+\n - POSIX platform (Linux, FreeBSD, macOS)\n\nOptional:\n\n - Memcached 1.4+\n - Elasticsearch 5.5+\n\n## Install the Development Environment\n\nTo install, create a new virtual environment and run make:\n\n virtualenv -p python3 .\n source bin/activate\n make install\n\n## Update the Development Environment\n\nTo get the latest updates and sources run:\n\n make update\n\nTo apply schema-changes to your database:\n\n onegov-core upgrade\n\n## Fix Build Errors\n\nOneGov requires the following packages:\n\n - libxml2\n - libxslt\n\nThose should be downloaded and built automatically during installation.\n\nFor that to work you need the python development files. On OSX those should\nbe already installed if you installed Python 3 trough homebrew.\n\nOn other POSIX platforms you might have to install them. On Ubuntu for example,\nyou need to run:\n\n sudo apt-get install git python3-dev python-virtualenv\n\nYou also need to have the following header files installed:\n\n sudo apt-get install libcurl4-openssl-dev libffi-dev libjpeg-dev libpq-dev\n libxml2-dev libxslt1-dev zlib1g-dev libev-dev libgnutls28-dev libkrb5-dev\n libpoppler-cpp-dev\n\n## Folder Structure\n\nThe `depot-storage` folder contains the depot based storage.\n\nThe `docs` folder contains onegov's documentation.\n\nThe `eggs` folder contains links to all the sources used by the interpreter.\nThis is very handy if you need to lookup source code from your editor.\n\nThe `file-storage` folder contains the pyfilesystem based storage.\n\nThe `experiments` folder contains Jupyter Notebook files.\n\nThe `profiles` folder contains profiling output.\n\nThe `src` folder contains the source code directly associated with onegov. This\nis where the magic happens ;)\n\n## Setup Database\n\nOneGov supports different applications under different paths. Usually you\nprobably want to run onegov.town though, the first such application. You can\nhave different applications run on the same database though.\n\nTo prepare a database, make sure you have Postgres 9.3+ running locally,\nwith a database designated to running your application.\n\nOnce you do, copy `onegov.yml.example` and edit the dns string inside\nthe resulting `onegov.yml` file:\n\n cp onegov.yml.example onegov.yml\n\nThen edit the following line in `onegov.yml`:\n\n dsn: postgres://user:password@localhost:5432/database\n\n## Setup OneGov Town\n\nTo use OneGov Town you need to define a town first. Run the\nfollowing command to define a new town (there is currently no way to do it\nthrough the web interface).\n\n bin/onegov-town --select /onegov_town/govikon add Govikon\n\nYou also might want to define an admin to manage the site. Run the following\ncommand to define a user with admin role.\n\n bin/onegov-user --select /onegov_town/govikon add admin [email protected] --no-prompt --password test\n\nHaving done that, start the onegov server as follows:\n\n bin/onegov-server\n\nAnd point your browser to\n[http://localhost:8080/onegov_town/govikon](http://localhost:8080/onegov_town/govikon).\n\n## Setup OneGov Election Day\n\nTo use OneGov Election Day you need to define a so called principal. That's\nbasically the canton using the application.\n\nTo do this for the canton of zg for example you create the following directory:\n\n mkdir -p file-storage/onegov_election_day-zg\n\nThen you create a file containing the information about the canton:\n\n touch file-storage/onegov_election_day-zg/principal.yml\n\nInside you configure the principal (example content):\n\n name: Kanton Zug\n logo: logo.svg\n canton: zg\n color: '#234B85'\n\nThe logo points to a file in the same directory as the yml file.\n\nYou also want to add a user, which you can do as follows:\n\n bin/onegov-user --select /onegov_election_day/zg add admin [email protected]\n\nHaving done that, start the onegov server as follows:\n\n bin/onegov-server\n\nAnd point your browser to\n[http://localhost:8080/wahlen/zg](http://localhost:8080/wahlen/zg).\n\n## Transfer Files from live server\n\nTo transfer files from a remote server (e.g. onegov-agency), you can take the following steps:\n\n1. Find out the hostname of the live server, e.g. *staatskalender-ar.onegovcloud.ch*\n2. Use `pet whereis staatskalender-ar.onegovcloud.ch` which returns the server the app was deployed on.\n3. ssh into the remote server to find out where `onegov.yml` is located, in general in `/opt/onegov/onegov.yml` directory.\n4. Launch the command to copy the files: `onegov-core transfer <hostname> /opt/onegov/onegov.yml`\n\n## Run Tests\n\nTo run the tests of a specific module:\n\n py.test src/onegov.core\n py.test src/onegov.town\n py.test src/onegov.user\n\nAnd so on.\n\nTo run a specific test:\n\n py.test src/onegov.core -k test_my_test\n\nTo run tests in parallel (for faster execution):\n\n py.test src/onegov.core --tx='4*popen//python=bin/py' --dist=load\n\nTo run all tests at once:\n\n make test\n\nNote that the following *won't work*:\n\n py.test src/onegov.*\n\n## Run Tests with Tox\n\nTo run the tests with tox:\n\n tox -c src/onegov.core/tox.ini\n tox -c src/onegov.org/tox.ini\n\nAnd so on.\n\nTo run a specific test:\n\n tox -c src/onegov.core -- -k test_my_test\n\n## Add New Development Packages\n\nTo add a package that should only be available in the development environment,\nadd it to requirements.txt\n\nVersion pins should be added to constraints.txt\n\n## Add Your Own Development Packages\n\nTo add your own set of extra packages, create a new file called `extras.txt` and\nadd them there (just like you would in a requirements.txt).\n\n## Profiling\n\nTo profile all requests, set `profile` in the onegov.yml to `true`. This will\nresult in a timestamp profile file in the profiles folder for each request.\n\nYou may then use the pstats profile browser as described here:\nhttp://stefaanlippens.net/python_profiling_with_pstats_interactive_mode\n\nOr convert it to an SVG use gprof2dot\n\n gprof2dot -f pstats profiles/[profile file] | dot -Tsvg -o output.svg\n\nAnother possiblilty is to run `py.test` with `pytest-profiling`, which creates\na nice SVG:\n\n py.test --profile --profile-svg src/onegov.core\n\n## Internationalization (i18n)\n\nTo use i18n, gettext must be installed. On most linux distros this is a given.\nOn OSX it is recommended to install gettext with homebrew:\n\n brew install gettext\n\n### Add a language to a module:\n\n bash i18n.sh onegov.town de\n\n### Extract the messages from a module (update the translation files)\n\n bash i18n.sh onegov.town\n\n## Build Docs\n\nTo build the docs:\n\n cd docs\n make html\n\nTo completely rebuild the docs:\n\n cd docs\n make clean\n make html\n\n## Show Uncommited Changes\n\nTo show what changes (if any) are uncommited:\n\n uncommitted . -nu\n\n## Run Jupyter Notebook\n\nJupyter notebook comes preinstalled:\n\n jupyter notebook\n\n## SCSS Linting\n\nWe use https://github.com/brigade/scss-lint to lint our scss files. The linter\nconfiguration is found in the local directory (`./.scss-lint.yml`).\n\nIn Sublime Text the linter should pick this file up when using the\n`onegov.sublime-project` file. Though it might require a restart.\n\nIn Atom the https://atom.io/packages/linter-scss-lint will pick up the right\nconfiguration file per default.\n\nOther editors are not directly supported, so you are on your own.\n\n## Build Status\n\nTravis tests if this setup actually works. Current status:\n\n[![Build Status](https://travis-ci.org/OneGov/dev.svg?branch=master)](https://travis-ci.org/OneGov/dev)\n" }, { "alpha_fraction": 0.6048060059547424, "alphanum_fraction": 0.6100173592567444, "avg_line_length": 24.776119232177734, "blob_id": "8f7c91aeafd066e7c1c39262e7f7e5c5708dd1e1", "content_id": "e2ce25dca15e8a2346e85d48a36f8eec8f956329", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3454, "license_type": "no_license", "max_line_length": 90, "num_lines": 134, "path": "/i18n.sh", "repo_name": "OneGov/dev", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#\n# This script helps to add and update gettext translations to onegov modules.\n#\nMODULE=\"${1/-/_}\"\nLANGUAGE=\"${2}\"\n\nset -eu\n\nSCRIPTPATH=\"$( cd \"$(dirname \"$0\")\" ; pwd -P )\"\n\nDOMAIN=\"${MODULE}\"\nMODULE_PATH=\"${SCRIPTPATH}/src/${1}\"\nSEARCH_PATH=\"${MODULE_PATH}/${MODULE//.//}\"\nLOCALE_PATH=\"${SEARCH_PATH}/locale\"\nPOT_FILE=\"${LOCALE_PATH}/${DOMAIN}.pot\"\n\nPOT_CREATE=\"${VIRTUAL_ENV}/bin/pot-create\"\n\nif [ \"${LANGUAGE}\" != \"\" ]; then\n if echo \"${LANGUAGE}\" | egrep -v '^[a-z]{2}(_[A-Z]{2})?$' > /dev/null; then\n echo \"Invalid language code, format like this: de_CH, en_GB, en, de, ...\"\n echo \"the language code is lowercased, the optional country code is uppercased\"\n exit 1\n fi\nfi\n\nfunction show_usage() {\n echo \"Usage: bash i18n.sh module-name [language]\"\n echo \"\"\n echo \"Example adding a language to a module:\"\n echo \"bash i18n.sh onegov.town fr\"\n echo \"\"\n echo \"Example updating the pofiles in a module:\"\n echo \"bash i18n.sh onegov.town\"\n echo \"\"\n exit 1\n}\n\nfunction die() {\n echo \"${1}\"\n exit 1\n}\n\ncommand_exists () {\n type \"$1\" &> /dev/null;\n}\n\nif [ \"${MODULE}\" = \"\" ]; then\n show_usage\nfi\n\n# try to find the gettext tools we need - on linux they should be available,\n# on osx we try to get them from homebrew\nif command_exists brew; then\n if brew list | grep gettext -q; then\n BREW_PREFIX=$(brew --prefix)\n GETTEXT_PATH=$(brew info gettext | grep \"${BREW_PREFIX}\" | awk '{print $1; exit}')\n\n MSGINIT=\"${GETTEXT_PATH}/bin/msginit\"\n MSGMERGE=\"${GETTEXT_PATH}/bin/msgmerge\"\n MSGFMT=\"${GETTEXT_PATH}/bin/msgfmt\"\n else\n echo \"Homebrew was found but gettext is not installed\"\n die \"Install gettext using 'brew install gettext'\"\n fi\nelse\n MSGINIT=$(which msginit)\n MSGMERGE=$(which msgmerge)\n MSGFMT=$(which msgfmt)\nfi\n\nif [ ! -e \"${MSGINIT}\" ]; then\n die \"msginit command could not be found, be sure to install gettext\"\nfi\n\nif [ ! -e \"${MSGMERGE}\" ]; then\n die \"msgmerge command could not be found, be sure to install gettext\"\nfi\n\nif [ ! -e \"${MSGFMT}\" ]; then\n die \"msgfmt command could not be found, be sure to install gettext\"\nfi\n\nif [ ! -d \"${MODULE_PATH}\" ]; then\n die \"${MODULE_PATH} does not exist\"\nfi\n\nif [ ! -d \"${SEARCH_PATH}\" ]; then\n die \"${SEARCH_PATH} does not exist\"\nfi\n\nif [ ! -e \"${POT_CREATE}\" ]; then\n die \"${POT_CREATE} does not exist\"\nfi\n\nif [ ! -e \"${LOCALE_PATH}\" ]; then\n echo \"${LOCALE_PATH} does not exist, creating...\"\n mkdir \"${LOCALE_PATH}\"\nfi\n\nif [ ! -e \"${POT_FILE}\" ]; then\n echo \"${POT_FILE} does not exist, creating...\"\n touch \"${POT_FILE}\"\nfi\n\n# language given, create catalog\nif [ -n \"${LANGUAGE}\" ]; then\n echo \"Creating language ${LANGUAGE}\"\n\n if [ -e \"${LOCALE_PATH}/${LANGUAGE}/LC_MESSAGES\" ]; then\n die \"Cannot initialize language '${LANGUAGE}', it exists already!\"\n fi\n\n cd \"${LOCALE_PATH}\"\n mkdir -p \"${LANGUAGE}/LC_MESSAGES\"\n\n domainfile=\"${LANGUAGE}/LC_MESSAGES/${DOMAIN}.po\"\n\n $MSGINIT -i \"${DOMAIN}.pot\" -o \"${domainfile}\" -l \"${LANGUAGE}\"\nfi\n\necho \"Extract messages\"\n$POT_CREATE \"${SEARCH_PATH}\" -o \"${POT_FILE}\"\n\necho \"Update translations\"\nfor po in \"${LOCALE_PATH}\"/*/LC_MESSAGES/$DOMAIN.po; do\n $MSGMERGE --no-location --no-fuzzy-matching -o \"${po}\" \"${po}\" \"${POT_FILE}\"\ndone\n\necho \"Compile message catalogs\"\nfor po in \"${LOCALE_PATH}\"/*/LC_MESSAGES/*.po; do\n $MSGFMT -o \"${po%.*}.mo\" \"$po\"\ndone\n" }, { "alpha_fraction": 0.6856217980384827, "alphanum_fraction": 0.6902450323104858, "avg_line_length": 33.8870964050293, "blob_id": "dd179d55c9e3d75dd15953018ba8b02ba2322052", "content_id": "d20c997d982e2b8d041b78cc194b91b7131a397b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 2163, "license_type": "no_license", "max_line_length": 164, "num_lines": 62, "path": "/makefile", "repo_name": "OneGov/dev", "src_encoding": "UTF-8", "text": "install: in_virtual_env\n\t# use latest pip\n\tpip install --upgrade pip\n\n\t# install requirements\n\tpip install -r requirements.txt -c constraints.txt --src ./src --upgrade-strategy=eager\n\n\t# install custom extra requirements if present\n\ttest -e extras.txt && pip install -r extras.txt -c constraints.txt --src ./src --upgrade-strategy=eager || true\n\n\t# remove install artifacts\n\ttest -e src/pip-delete-this-directory.txt && rm src/pip-delete-this-directory.txt || true\n\n\t# fetch docs\n\ttest -e docs/.git || git clone https://github.com/onegov/onegov-docs docs\n\n\t# ensure required folder structure\n\tmkdir -p ./profiles\n\n\t# gather eggs\n\trm -rf ./eggs\n\tscrambler --target eggs\n\nupdate: in_virtual_env if_all_committed if_all_on_master_branch\n\n\t# update sources\n\tfind src -type d -maxdepth 1 -exec echo \"\"\\; -exec echo \"{}\" \\; -exec git --git-dir={}/.git --work-tree={} pull \\;\n\n\t# update docs\n\tcd docs && git pull\n\n\t# updating all dependencies\n\tpip list --outdated --format=freeze | sed 's/==/>/g' | pip install --upgrade -r /dev/stdin -c constraints.txt\n\n\t# install all dependencies, applying constraints\n\tmake install\n\nin_virtual_env:\n\t@if python -c 'import sys; (hasattr(sys, \"real_prefix\") or (hasattr(sys, \"base_prefix\") and sys.base_prefix != sys.prefix)) and sys.exit(1) or sys.exit(0)'; then \\\n\t\techo \"An active virtual environment is required\"; exit 1; \\\n\t\telse true; fi\n\nif_all_committed:\n\t@ # pip has the nasty habit of overriding local changes when updating\n\t@ if uncommitted -nu src | grep -q Git; then \\\n\t\techo \"Commit and push all your changes before updating\"; exit 1; \\\n\t\telse true; fi\n\nif_all_on_master_branch:\n\t@ # pip will muck with the branches other than master in weird ways\n\t@ for repository in src/*; do \\\n \tif git -C \"$${repository}\" rev-parse --abbrev-ref HEAD | grep -vq master; then\\\n \t\techo \"$${repository} is not on the master branch\";\\\n \t\techo \"Make sure all repositories are on the master branch before updating\";\\\n \t\texit 1;\\\n\t\tfi; done\n\ntest: in_virtual_env\n\tfind src -type d -maxdepth 1 \\\n\t\t-not \\( -path src/onegov-testing -prune \\) \\\n\t\t-not \\( -path src/onegov.applications -prune \\) \\\n\t\t-print0 | xargs -n 1 -0 py.test\n" }, { "alpha_fraction": 0.7771824598312378, "alphanum_fraction": 0.7790734171867371, "avg_line_length": 39.16455841064453, "blob_id": "cd73fbed5d48eccc1f591d0ba0788481382b5a60", "content_id": "445ce2fb810dd38d084cc85e3f34891958d3d720", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 3173, "license_type": "no_license", "max_line_length": 82, "num_lines": 79, "path": "/requirements.txt", "repo_name": "OneGov/dev", "src_encoding": "UTF-8", "text": "# core libraries\n-e git+https://github.com/onegov/onegov.server#egg=onegov.server[test]\n-e git+https://github.com/onegov/onegov.core#egg=onegov.core[test]\n-e git+https://github.com/onegov/onegov_testing#egg=onegov_testing\n-e git+https://github.com/seantis/libres#egg=libres[test]\n-e git+https://github.com/seantis/sedate#egg=sedate[test]\n\n# models\n-e git+https://github.com/onegov/onegov.activity#egg=onegov.activity[test]\n-e git+https://github.com/onegov/onegov.ballot#egg=onegov.ballot[test]\n-e git+https://github.com/onegov/onegov.chat#egg=onegov.chat[test]\n-e git+https://github.com/onegov/onegov.directory#egg=onegov.directory[test]\n-e git+https://github.com/onegov/onegov.event#egg=onegov.event[test]\n-e git+https://github.com/onegov/onegov.file#egg=onegov.file[test]\n-e git+https://github.com/onegov/onegov.form#egg=onegov.form[test]\n-e git+https://github.com/onegov/onegov.foundation#egg=onegov.foundation[test]\n-e git+https://github.com/onegov/onegov.gis#egg=onegov.gis[test]\n-e git+https://github.com/onegov/onegov.newsletter#egg=onegov.newsletter[test]\n-e git+https://github.com/onegov/onegov.notice#egg=onegov.notice[test]\n-e git+https://github.com/onegov/onegov.page#egg=onegov.page[test]\n-e git+https://github.com/onegov/onegov.pay#egg=onegov.pay[test]\n-e git+https://github.com/onegov/onegov.pdf#egg=onegov.pdf[test]\n-e git+https://github.com/onegov/onegov.people#egg=onegov.people[test]\n-e git+https://github.com/onegov/onegov.quill#egg=onegov.quill[test]\n-e git+https://github.com/onegov/onegov.recipient#egg=onegov.recipient[test]\n-e git+https://github.com/onegov/onegov.reservation#egg=onegov.reservation[test]\n-e git+https://github.com/onegov/onegov.search#egg=onegov.search[test]\n-e git+https://github.com/onegov/onegov.shared#egg=onegov.shared[test]\n-e git+https://github.com/onegov/onegov.ticket#egg=onegov.ticket[test]\n-e git+https://github.com/onegov/onegov.user#egg=onegov.user[test]\n\n# applications\n-e git+https://github.com/onegov/onegov.agency#egg=onegov.agency[test]\n-e git+https://github.com/onegov/onegov.election_day#egg=onegov.election_day[test]\n-e git+https://github.com/onegov/onegov.feriennet#egg=onegov.feriennet[test]\n-e git+https://github.com/onegov/onegov.gazette#egg=onegov.gazette[test]\n-e git+https://github.com/onegov/onegov.intranet#egg=onegov.intranet[test]\n-e git+https://github.com/onegov/onegov.onboarding#egg=onegov.onboarding[test]\n-e git+https://github.com/onegov/onegov.org#egg=onegov.org[test]\n-e git+https://github.com/onegov/onegov.swissvotes#egg=onegov.swissvotes[test]\n-e git+https://github.com/onegov/onegov.town#egg=onegov.town[test]\n-e git+https://github.com/onegov/onegov.winterthur#egg=onegov.winterthur[test]\n-e git+https://github.com/onegov/onegov.wtfs#egg=onegov.wtfs[test]\n-e git+https://github.com/onegov/onegov.applications#egg=onegov.applications\n\n# a replacement for buildout's omelette\nscrambler\n\n# to show uncommitted changes\nuncommitted\n\n# profiling tools\ngprof2dot\nprofilehooks\n\n# testing tools\ntox\n\n# build tools\nbumpversion\npunch.py\n\n# pytest plugins\npytest-cov\npytest-xdist\n\n# jupyter notebooks\njupyter\nmatplotlib\nboltons\nsortedcontainers\n\n# sphinx\nsphinx\nalabaster\n\n# i18n\nlingua\njinja2[i18n]\n" }, { "alpha_fraction": 0.5500662922859192, "alphanum_fraction": 0.5560988783836365, "avg_line_length": 30.03687858581543, "blob_id": "77f6a66d55681d748c700a845db2122e2f020609", "content_id": "0fc9334c6047c7e031e84ff8fe754932ffc6c7ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21881, "license_type": "no_license", "max_line_length": 79, "num_lines": 705, "path": "/experiments/deferred-acceptance/experiment.py", "repo_name": "OneGov/dev", "src_encoding": "UTF-8", "text": "import random\nimport transaction\n\nfrom itertools import groupby, tee\nfrom datetime import datetime, timedelta, date\nfrom onegov.activity import Activity, ActivityCollection\nfrom onegov.activity import Attendee, AttendeeCollection\nfrom onegov.activity import Booking, BookingCollection\nfrom onegov.activity import Occasion, OccasionCollection\nfrom onegov.activity import PeriodCollection\nfrom onegov.activity.matching import deferred_acceptance_from_database\nfrom onegov.core.orm import Base\nfrom onegov.core.orm.session_manager import SessionManager\nfrom onegov.user import UserCollection\nfrom sedate import overlaps\nfrom boltons.setutils import IndexedSet\nfrom statistics import mean, stdev\nfrom sqlalchemy import func\nfrom sqlalchemy.orm import joinedload\nfrom sortedcontainers import SortedSet\nfrom uuid import uuid4\n\n\ndef pairwise(iterable):\n a, b = tee(iterable)\n next(b, None)\n return zip(a, b)\n\n\ndef yes_or_no(chance):\n return random.randint(0, 11) <= chance * 10\n\n\ndef weighted_random_choice(choices):\n limit = random.uniform(0, sum(w for c, w in choices))\n running_total = 0\n\n for choice, weight in choices:\n if running_total + weight >= limit:\n return choice\n running_total += weight\n\n\ndef random_spots():\n min_spots = random.randint(3, 6)\n max_spots = random.randint(min_spots, 10)\n\n return min_spots, max_spots\n\n\ndef drop_all_existing_experiments(dsn):\n mgr = SessionManager(dsn=dsn, base=Base)\n\n for schema in mgr.list_schemas(limit_to_namespace=Experiment.namespace):\n mgr.engine.execute('DROP SCHEMA \"{}\" CASCADE'.format(schema))\n\n transaction.commit()\n mgr.dispose()\n\n\nclass Experiment(object):\n\n namespace = 'da'\n\n def __init__(self, dsn, drop_others=True):\n self.mgr = SessionManager(dsn=dsn, base=Base, session_config={\n 'expire_on_commit': False\n })\n\n # create a new one schema\n self.schema = '{}-{}'.format(self.namespace, uuid4().hex[:8])\n self.mgr.set_current_schema(self.schema)\n\n @property\n def session(self):\n return self.mgr.session()\n\n def query(self, *args, **kwargs):\n return self.session.query(*args, **kwargs)\n\n def drop_other_experiments(self):\n\n transaction.commit()\n\n def create_owner(self):\n return UserCollection(self.session).add(\n username=uuid4().hex,\n password=uuid4().hex,\n role='admin')\n\n def create_period(self):\n prebooking = [d.date() for d in (\n datetime.now() - timedelta(days=1),\n datetime.now() + timedelta(days=1)\n )]\n execution = [d.date() for d in (\n datetime.now() + timedelta(days=2),\n datetime.now() + timedelta(days=4)\n )]\n\n return PeriodCollection(self.session).add(\n title=\"Ferienpass 2016\",\n prebooking=prebooking,\n execution=execution,\n active=True)\n\n def create_occasion(self, period, owner, overlap, previous):\n activities = ActivityCollection(self.session)\n\n activity = activities.add(\n title=uuid4().hex,\n username=owner.username\n )\n\n activity.propose().accept()\n\n if previous:\n if overlap:\n start = previous.end - timedelta(seconds=1)\n else:\n start = previous.end + timedelta(seconds=1)\n else:\n start = datetime.now()\n\n end = start + timedelta(seconds=60)\n\n return OccasionCollection(self.session).add(\n activity, period, start, end, 'Europe/Zurich',\n spots=random_spots()\n )\n\n def create_attendee(self, owner, name, birth_date):\n return AttendeeCollection(self.session).add(\n owner, name, birth_date)\n\n def create_booking(self, owner, attendee, occasion, priority):\n return BookingCollection(self.session).add(\n owner, attendee, occasion, priority)\n\n def create_fixtures(self, choices, overlapping_chance, attendee_count,\n distribution):\n\n period = self.create_period()\n owner = self.create_owner()\n\n def in_batches(count, factory):\n result = []\n\n for ix in range(count):\n result.append(factory(result))\n\n if ix % 10 == 0:\n transaction.commit()\n\n return result\n\n # create the occasions\n occasions = in_batches(choices, lambda r: self.create_occasion(\n period,\n owner,\n yes_or_no(overlapping_chance),\n r and r[-1]\n ))\n\n # create the attendees\n attendees = in_batches(attendee_count, lambda r: self.create_attendee(\n owner=owner,\n name=uuid4().hex,\n birth_date=date(2000, 1, 1)\n ))\n\n # create the bookings\n bookings = []\n\n for attendee in attendees:\n number_of_choices = weighted_random_choice(distribution)\n chosen = random.sample(occasions, number_of_choices)\n\n for ix, occasion in enumerate(chosen):\n bookings.append(\n self.create_booking(\n owner,\n attendee,\n occasion,\n priority=ix < 3 and 1 or 0\n )\n )\n\n if ix % 10 == 0:\n transaction.commit()\n\n transaction.commit()\n\n @property\n def activity_count(self):\n return self.session.query(Activity).count()\n\n @property\n def occasion_count(self):\n return self.session.query(Occasion).count()\n\n @property\n def attendee_count(self):\n return self.session.query(Attendee).count()\n\n @property\n def booking_count(self):\n return self.session.query(Booking).count()\n\n @property\n def global_happiness_scores(self):\n return [score for score in (\n self.happiness(a)\n for a in self.session.query(Attendee).with_entities(Attendee.id)\n ) if score is not None]\n\n @property\n def global_happiness(self):\n return mean(self.global_happiness_scores)\n\n @property\n def global_happiness_stdev(self):\n return stdev(self.global_happiness_scores)\n\n def happiness(self, attendee):\n bookings = self.session.query(Booking)\\\n .with_entities(Booking.state, Booking.priority)\\\n .filter(Booking.attendee_id == attendee.id)\n\n bits = []\n\n for booking in bookings:\n bits.extend(\n booking.state == 'accepted' and 1 or 0\n for _ in range(booking.priority + 1)\n )\n\n # attendees without a booking are neither happy nor unhappy\n if not bits:\n return None\n\n return sum(bits) / len(bits)\n\n @property\n def happiness_histogram(self):\n\n # necessary for this code to run directly in the buildout,\n # not just in the jupyter notebook alone\n import matplotlib.pyplot as plt\n from matplotlib.ticker import MaxNLocator\n\n figure = plt.figure(\"Happiness Histogram\")\n subplot = figure.add_subplot(111)\n plt.ylabel('Number of Attendees')\n plt.xlabel('Happiness')\n\n plt.figtext(1.4, 0.875, \"Global happiness: {:.2f}%\".format(\n self.global_happiness * 100\n ), horizontalalignment='right')\n\n plt.figtext(1.4, 0.825, \"Standard Deviation: {:.2f}%\".format(\n self.global_happiness_stdev * 100\n ), horizontalalignment='right')\n\n plt.figtext(1.4, 0.775, \"Operable courses: {:.2f}%\".format(\n self.operable_courses * 100\n ), horizontalalignment='right')\n\n # force the yticks to be integers\n subplot.yaxis.set_major_locator(MaxNLocator(integer=True))\n\n scores = self.global_happiness_scores\n subplot.hist(scores, 10, color='#006fba', alpha=0.8)\n\n return plt.plot()\n\n @property\n def course_bookings_graph(self):\n\n # necessary for this code to run directly in the buildout,\n # not just in the jupyter notebook alone\n import matplotlib.pyplot as plt\n\n plt.ylabel('Number of Bookings')\n plt.xlabel('Course Index')\n\n scores = [\n len(o.bookings) for o in\n self.query(Occasion).options(joinedload(Occasion.bookings))\n ]\n\n plt.bar(list(range(len(scores))), sorted(scores))\n\n return plt.plot()\n\n @property\n def operable_courses(self):\n accepted = self.session.query(Booking)\\\n .with_entities(func.count(Booking.id).label('count'))\\\n .filter(Booking.occasion_id == Occasion.id)\\\n .filter(Booking.state == 'accepted')\\\n .subquery().lateral()\n\n o = self.session.query(Occasion, accepted.c.count)\n\n bits = []\n\n for occasion, count in o:\n bits.append(count >= occasion.spots.lower and 1 or 0)\n\n if not bits:\n return 0\n\n return sum(bits) / len(bits)\n\n @property\n def overlapping_occasions(self):\n count = 0\n\n o = self.session.query(Occasion)\n o = o.order_by(Occasion.start, Occasion.end)\n\n for previous, current in pairwise(o):\n if current is None:\n continue\n\n if previous.end > current.start:\n count += 1\n\n return count / o.count()\n\n def reset_bookings(self):\n q = self.session.query(Booking)\n q = q.filter(Booking.state != 'open')\n q.update({Booking.state: 'open'}, 'fetch')\n\n transaction.commit()\n\n def pick_favorite(self, candidates, *args):\n \"\"\" Will simply pick the favorites first in the entered order. \"\"\"\n return candidates.pop()\n\n def pick_random(self, candidates, *args):\n \"\"\" Will pick completely at random. \"\"\"\n return candidates.pop(random.randint(0, len(candidates) - 1))\n\n def pick_random_but_favorites_first(self, candidates, *args):\n \"\"\" Picks at random, first only considering favorites, then considering\n everyone. \"\"\"\n excited = [c for c in candidates if c.priority]\n\n if excited:\n pick = random.choice(excited)\n else:\n pick = random.choice([c for c in candidates if not c.priority])\n\n candidates.remove(pick)\n return pick\n\n def pick_least_impact_favorites_first(self, candidates, open):\n \"\"\" Picks the favorite with the least impact amongst all open\n bookings. That is the booking which will cause the least other\n bookings to be blocked.\n\n \"\"\"\n\n # yields the number of bookings affected by the given one\n def impact(candidate):\n impacted = 0\n\n for b in open:\n if b.attendee_id == candidate.attendee_id:\n is_impacted = overlaps(\n b.occasion.start, b.occasion.end,\n candidate.occasion.start, candidate.occasion.end\n )\n impacted += is_impacted and 1 or 0\n\n return impacted\n\n excited = [c for c in candidates if c.priority]\n\n if excited:\n pick = min(excited, key=impact)\n else:\n pick = min([c for c in candidates if not c.priority], key=impact)\n\n candidates.remove(pick)\n return pick\n\n def greedy_matching_until_operable(self, pick_function, safety_margin=0,\n matching_round=0):\n\n if matching_round == 0:\n self.reset_bookings()\n\n random.seed(matching_round)\n\n q = self.session.query(Booking)\n\n # higher priority bookings land at the end, since we treat the\n # candidates as a queue -> they end up at the front of the queue\n q = q.order_by(Booking.occasion_id, Booking.priority)\n q = q.options(joinedload(Booking.occasion))\n\n # read as list first, as the order matters for the grouping\n open = list(q.filter(Booking.state == 'open'))\n\n by_occasion = [\n (occasion, IndexedSet(candidates))\n for occasion, candidates\n in groupby(open, key=lambda booking: booking.occasion)\n ]\n\n random.shuffle(by_occasion)\n\n # the order no longer matters\n open = set(open)\n accepted = set(q.filter(Booking.state == 'accepted'))\n blocked = set(q.filter(Booking.state == 'blocked'))\n\n for occasion, candidates in by_occasion:\n\n # remove the already blocked or accepted (this loop operates\n # on a separate copy of the data)\n candidates -= blocked\n candidates -= accepted\n\n # if there are not enough bookings for an occasion we must exit\n if len(candidates) < occasion.spots.lower:\n continue\n\n picks = set()\n collateral = set()\n\n required_picks = occasion.spots.lower + safety_margin\n\n existing_picks = sum(\n 1 for b in occasion.bookings if b.state == 'accepted')\n\n if existing_picks >= (occasion.spots.upper - 1):\n continue\n\n while candidates and len(picks) < required_picks:\n\n if len(picks) + existing_picks == occasion.spots.upper - 1:\n break\n\n # pick the next best spot\n pick = pick_function(candidates, open)\n picks.add(pick)\n\n # keep track of all bookings that would be made impossible\n # if this occasion was able to fill its quota\n collateral |= set(\n b for b in open\n if b.attendee_id == pick.attendee_id and\n b not in picks and\n overlaps(\n b.occasion.start, b.occasion.end,\n pick.occasion.start, pick.occasion.end\n )\n )\n\n # remove affected bookings from possible candidates\n candidates -= collateral\n\n # confirm picks\n accepted |= picks\n open -= picks\n\n # cancel affected bookings\n blocked |= collateral\n open -= collateral\n\n # write the changes to the database\n def update_states(bookings, state):\n ids = set(b.id for b in bookings)\n\n if not ids:\n return\n\n b = self.session.query(Booking)\n b = b.filter(Booking.id.in_(ids))\n b.update({Booking.state: state}, 'fetch')\n\n update_states(open, 'open')\n update_states(accepted, 'accepted')\n update_states(blocked, 'blocked')\n\n transaction.commit()\n\n self.assert_correctness()\n\n def builtin_deferred_acceptance(self,\n stability_check=False,\n validity_check=True):\n self.reset_bookings()\n deferred_acceptance_from_database(\n self.session, PeriodCollection(self.session).query().first().id,\n stability_check=stability_check,\n validity_check=validity_check\n )\n transaction.commit()\n self.assert_correctness()\n\n def deferred_acceptance(self):\n self.reset_bookings()\n\n class AttendeePreferences(object):\n def __init__(self, attendee):\n self.attendee = attendee\n self.wishlist = SortedSet([\n b for b in attendee.bookings\n if b.state == 'open'\n ], key=lambda b: b.priority * -1)\n self.blocked = set()\n self.accepted = set()\n\n def __hash__(self):\n return hash(self.attendee)\n\n def __bool__(self):\n return len(self.wishlist) > 0\n\n def confirm(self, booking):\n self.blocked |= set(\n b for b in self.wishlist\n if hash(b) != hash(booking) and\n overlaps(\n booking.occasion.start, booking.occasion.end,\n b.occasion.start, b.occasion.end\n )\n )\n\n self.wishlist.remove(booking)\n self.accepted.add(booking)\n\n def unconfirm(self, booking):\n self.wishlist.add(booking)\n self.accepted.remove(booking)\n\n for x in self.blocked:\n for y in self.blocked:\n if hash(x) == hash(y):\n break\n if overlaps(x.occasion.start, x.occasion.end,\n y.occasion.start, y.occasion.end):\n break\n else:\n self.wishlist.add(y)\n\n self.blocked -= self.wishlist\n\n def pop(self):\n return self.wishlist.pop(0)\n\n class OccasionPreferences(object):\n def __init__(self, occasion):\n self.occasion = occasion\n self.bookings = set(\n b for b in occasion.bookings\n if b.state == 'accepted'\n )\n self.attendees = {}\n\n def __hash__(self):\n return hash(self.occasion)\n\n @property\n def operable(self):\n return len(self.bookings) >= self.occasion.spots.lower\n\n @property\n def full(self):\n return len(self.bookings) == (self.occasion.spots.upper - 1)\n\n def score(self, booking):\n return booking.priority\n\n def match(self, attendee, booking):\n if not self.full:\n self.attendees[booking] = attendee\n self.bookings.add(booking)\n attendee.confirm(booking)\n return True\n\n for b in self.bookings:\n if self.score(b) < self.score(booking):\n attendee.confirm(booking)\n self.attendees[b].unconfirm(b)\n self.bookings.remove(b)\n self.bookings.add(booking)\n return True\n\n return False\n\n q = self.session.query(Attendee)\n q = q.options(joinedload(Attendee.bookings))\n unmatched = set(AttendeePreferences(a) for a in q)\n\n q = self.session.query(Booking)\n q = q.options(joinedload(Booking.occasion))\n\n all_bookings = q.all()\n\n preferences = {\n o: OccasionPreferences(o)\n for o in set(b.occasion for b in all_bookings)\n }\n occasions = {b: preferences[b.occasion] for b in all_bookings}\n\n while next((u for u in unmatched if u), None):\n\n if all(p.full for p in preferences.values()):\n break\n\n candidates = [u for u in unmatched if u]\n random.shuffle(candidates)\n\n matches = 0\n\n while candidates:\n candidate = candidates.pop()\n\n for booking in candidate.wishlist:\n if occasions[booking].match(candidate, booking):\n matches += 1\n break\n\n if not matches:\n break\n\n # write the changes to the database\n def update_states(bookings, state):\n ids = set(b.id for b in bookings)\n\n if not ids:\n return\n\n b = self.session.query(Booking)\n b = b.filter(Booking.id.in_(ids))\n b.update({Booking.state: state}, 'fetch')\n\n open = set(b for a in unmatched for b in a.wishlist)\n accepted = set(b for a in unmatched for b in a.accepted)\n blocked = set(b for a in unmatched for b in a.blocked)\n\n update_states(open, 'open')\n update_states(accepted, 'accepted')\n update_states(blocked, 'blocked')\n\n transaction.commit()\n\n self.assert_correctness()\n\n def assert_correctness(self):\n # make sure no accepted bookings by attendee overlap\n q = self.query(Booking)\n q = q.filter(Booking.state == 'accepted')\n q = q.options(joinedload(Booking.occasion))\n q = q.order_by(Booking.attendee_id)\n\n for attendee_id, bookings in groupby(q, key=lambda b: b.attendee_id):\n bookings = sorted(list(bookings), key=lambda b: b.occasion.start)\n\n for previous, current in pairwise(bookings):\n if previous and current:\n assert not overlaps(\n previous.occasion.start, previous.occasion.end,\n current.occasion.start, current.occasion.end\n )\n\n # make sure no course is overbooked\n q = self.query(Occasion)\n q = q.options(joinedload(Occasion.bookings))\n\n for occasion in q:\n if not occasion.bookings:\n continue\n\n # we don't want to confirm spots which do not lead to a filled\n # out occasion at this point - though we might have to revisit\n accepted = [\n b for b in occasion.bookings if b.state == 'accepted']\n\n if accepted:\n assert len(accepted) < occasion.spots.upper\n\n\nif __name__ == '__main__':\n experiment = Experiment('postgresql://dev:dev@localhost:15432/onegov')\n experiment.create_fixtures(\n choices=5,\n overlapping_chance=0.5,\n attendee_count=100,\n distribution=[ # (number of choices, chance)\n (1, 1),\n ]\n )\n\n experiment.deferred_acceptance()\n\n print(\"Happiness: {:.2f}%\".format(experiment.global_happiness * 100))\n print(\"Courses: {:.2f}%\".format(experiment.operable_courses * 100))\n" } ]
6
Range-Expansions/particle_populations_in_flow
https://github.com/Range-Expansions/particle_populations_in_flow
228f433e28d22c6e4b1d10ced71e1897eec17f7a
13ec7c2b06601004f8c7f0250313c60cc47dd788
54b622c73636f4eeadb98e93a0ea11767666d791
refs/heads/master
2021-01-17T07:46:33.282060
2016-11-02T21:54:53
2016-11-02T21:54:53
60,371,752
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5584169626235962, "alphanum_fraction": 0.5708199143409729, "avg_line_length": 35.550174713134766, "blob_id": "8aa181a773a1b3e17a49b93af967d36e062192f9", "content_id": "0cad9bd25c7c629c9a9a50a38d212b86fdcc18f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10562, "license_type": "no_license", "max_line_length": 126, "num_lines": 289, "path": "/flow_pop/py_particles.py", "repo_name": "Range-Expansions/particle_populations_in_flow", "src_encoding": "UTF-8", "text": "import numpy as np\n\ntolerance = 10.**-9.\n\nclass Simulation_2d(object):\n\n def __init__(self, Lx=1., Ly=1., z = .1,\n N = 10., R = 4., time_prefactor = 0.1,\n droplet_density=1.0,\n mu_c = 1.0, mu_list = None,\n Dc = 1.0, D_list = None,\n D_nutrient = 1.0):\n\n self.phys_Lx = Lx\n self.phys_Ly = Ly\n self.phys_z = z\n\n self.N = N # Number of particles per unit area\n self.droplet_density = droplet_density # Number of particles per unit area in the droplet\n self.R = R # Resolution: Number of interaction lengths a deme of size Lc is divided into\n self.time_prefactor = time_prefactor\n\n self.phys_muc = mu_c\n self.phys_mu_list = np.array(mu_list, dtype=np.float32)\n self.phys_Dc = Dc\n self.phys_D_list = np.array(D_list, dtype=np.float32)\n\n self.phys_D_nutrient = D_nutrient\n\n #### Define Characteristic Length and Time Scales ####\n self.Lc = 2*np.sqrt(self.phys_Dc/self.phys_muc)\n print 'Lc (effective deme size, physical units):', self.Lc\n self.Tc = 1./self.phys_muc\n print 'Tc (characteristic time scale, physical units):', self.Tc\n\n #### Define Dimensionless Parameters ####\n self.dim_Di_list = self.phys_D_list/(4*self.phys_Dc)\n print 'dim_Di:', self.dim_Di_list\n\n self.dim_D_nutrient = self.phys_D_nutrient/(4*self.phys_Dc)\n print 'dim_D_nutrient:', self.dim_D_nutrient\n\n self.dim_Gi_list = self.phys_mu_list/self.phys_muc\n print 'dim_Gi:', self.dim_Gi_list\n\n self.dim_Dgi_list = self.dim_Gi_list/(self.N*self.Lc**2) # Two-dimensional\n print 'dim_Dgi:', self.dim_Dgi_list\n\n #### Define Simulation Parameters ####\n self.phys_delta = self.Lc/self.R # The interaction length. R should be larger than or equal to 1, always.\n self.dim_delta = self.phys_delta / self.Lc\n\n self.N_delta = self.N * self.phys_delta**2 # Average number of particles inside the interaction radius\n self.N_L = self.N * self.Lc**2 # Average number of particles inside a deme. Controls stochasticity.\n\n self.micro_Gi_list = self.dim_Gi_list / self.N_delta # The microscopic reaction rates. Dimensionless.\n print 'Microscopic Gi:', self.micro_Gi_list\n self.dim_dt = time_prefactor * (1./np.max(self.micro_Gi_list))\n self.dim_dx = 1./self.R # The reaction radius spacing in dimensionless units\n print 'Time step (to resolve microscopic reaction rates):', self.dim_dt\n\n ##### Initialize Particles and Grid #####\n self.dim_Lx = self.phys_Lx / self.Lc\n self.dim_Ly = self.phys_Ly / self.Lc\n\n self.dim_L_array = np.array(self.dim_Lx, self.dim_Ly)\n\n self.num_populations = len(self.phys_mu_list)\n self.nutrient_id = self.num_populations # The ID corresponding to the nutrient field\n\n self.num_fields = self.num_populations + 1 # We need the concentration field\n\n self.num_bins_x = np.int32(self.phys_Lx/self.phys_delta)\n self.num_bins_y = np.int32(self.phys_Ly/self.phys_delta)\n\n #### Create the particle dictionary ####\n particle_id_num = 0\n self.particle_dict = {}\n\n #### Inoculate Nutrients ####\n # Inoculate nutrient particles first. phys_N particles per deme, roughly. The carrying capacity, basically.\n total_num_nutrients = np.int32(self.N * self.phys_Lx * self.phys_Ly)\n\n print 'Total number of nutrients:', total_num_nutrients\n\n for i in range(total_num_nutrients):\n # Scatter randomly in space throughout the system. Positions are stored in NON-DIMENSIONAL SPACE\n particle_id = particle_id_num\n cur_position = np.random.rand(2) * self.dim_L_array\n\n cur_grid = np.int32(cur_position / self.dim_delta)\n\n new_particle = Particle(self, self.nutrient_id, cur_position, cur_grid,\n D=self.dim_D_nutrient, k=0) # k is zero as nutrient decay is correleated with other growth\n\n self.particle_dict[particle_id] = new_particle\n\n particle_id_num += 1\n\n\n #### Inoculate Populations ####\n\n # Inoculate them in a circle of width phys_N. We can do this by drawing a random R and theta\n # over a specified range\n\n # Inoculate a density of phys_N particles all over the circle...\n total_num_population = np.int32(self.droplet_density * np.pi*self.phys_z**2)\n\n print 'Number of particles in initial droplet:', total_num_population\n\n x0 = self.dim_Lx/2.\n y0 = self.dim_Ly/2.\n\n for _ in range(total_num_population):\n\n r = np.random.uniform(0, self.phys_z/self.Lc)\n theta = np.random.uniform(0, 2*np.pi)\n\n x = x0 + r*np.cos(theta)\n y = y0 + r*np.sin(theta)\n\n cur_position = np.array([x, y], dtype=np.float32)\n\n cur_grid = np.int32(cur_position / self.dim_delta)\n\n pop_type = np.random.randint(self.num_populations)\n new_particle = Particle(self, pop_type, cur_position, cur_grid,\n D = self.dim_Di_list[pop_type],\n k = self.micro_Gi_list[pop_type])\n\n self.particle_dict[particle_id_num] = new_particle\n\n particle_id_num += 1\n\n #### Setup the grid ####\n\n self.grid = np.zeros((self.num_bins_x, self.num_bins_y, self.num_fields), dtype=np.int32)\n for cur_particle in self.particle_dict.values():\n xy = cur_particle.grid_point\n pop_num = cur_particle.pop_type\n\n self.grid[xy[0], xy[1], pop_num] += 1\n\n self.total_growth_grid = np.zeros((self.num_bins_x, self.num_bins_y), dtype=np.int32)\n\n def react(self):\n \"\"\"Right now, simple concentration-based growth\"\"\"\n\n ##### REACT POPULATION PARTICLES ####\n\n particles_to_add = []\n positions_to_increase = []\n\n concentration_index = self.num_fields - 1\n\n for cur_key in self.particle_dict:\n cur_particle = self.particle_dict[cur_key]\n x = cur_particle.grid_point[0]\n y = cur_particle.grid_point[1]\n\n if cur_particle.pop_type != concentration_index: # Last type is the concentration field\n\n num_c = self.grid[x, y, concentration_index]\n\n prob = num_c * cur_particle.k * self.dim_dt\n rand = np.random.rand()\n\n if rand < prob: # React!\n new_particle = cur_particle.birth()\n particles_to_add.append(new_particle)\n positions_to_increase.append([x, y, new_particle.pop_type])\n self.total_growth_grid[x, y] += 1\n\n #### ADJUST THE NUTRIENT FIELD APPROPRIATELY ####\n\n keys_to_delete = []\n positions_to_decrease = []\n\n # Adjust the nutrient field appropriately, based on the growth of the others\n for cur_key in self.particle_dict:\n cur_particle = self.particle_dict[cur_key]\n x = cur_particle.grid_point[0]\n y = cur_particle.grid_point[1]\n\n if cur_particle.pop_type == concentration_index: # Last type is the concentration field\n\n if self.total_growth_grid[x, y] > 0:\n positions_to_decrease.append([x, y, cur_particle.pop_type])\n keys_to_delete.append(cur_key)\n self.total_growth_grid[x, y] -= 1\n\n #### UPDATE THE GRIDS AND PARTICLE DICTIONARY ####\n\n # Remove particles that died (nutrients)\n for cur_key in keys_to_delete:\n del self.particle_dict[cur_key]\n\n # Add new particles to the dictionary that were born\n max_key = np.max(self.particle_dict.keys())\n count = 1\n for cur_particle in particles_to_add:\n self.particle_dict[max_key + count] = cur_particle\n count += 1\n\n # Update the grid based on populations\n for xyc in positions_to_increase:\n self.grid[xyc[0], xyc[1], xyc[2]] += 1\n for xyc in positions_to_decrease:\n self.grid[xyc[0], xyc[1], xyc[2]] -= 1\n\n # Reset the growth grid\n self.total_growth_grid[:, :] = 0\n\n def move(self):\n for cur_particle in self.particle_dict.values():\n cur_particle.move()\n\n def run(self, num_iterations):\n for i in range(num_iterations):\n self.move()\n self.react()\n\nclass Particle(object):\n def __init__(self, simulation, pop_type, position, grid_point, D=1.0, k = 1.0):\n\n self.sim = simulation\n\n self.pop_type = np.int32(pop_type)\n self.position = np.float32(position)\n self.grid_point = np.int32(grid_point)\n\n self.D = D\n self.k = k\n\n def move(self):\n\n sim = self.sim\n\n sim.grid[self.grid_point[0], self.grid_point[1], self.pop_type] -= 1\n\n rand2 = np.random.randn(2)\n\n self.position += np.sqrt(2 * self.D * sim.dim_dt) * rand2\n\n # Deal with moving out of the system...bounce back\n # The issue with bounceback is that if you move farther that the system size twice,\n # due to the randn draw, you can run into trouble...\n Lx = sim.dim_Lx\n Ly = sim.dim_Ly\n\n x = self.position[0]\n y = self.position[1]\n\n if (x < 0):\n dx = (-x) % Lx\n x = dx + tolerance\n elif (x > Lx):\n dx = (x - Lx) % Lx # Just to avoid super bounces\n x = Lx - dx - tolerance\n if (y < 0):\n dy = (-y) % Ly\n y = dy + tolerance\n elif (y > Ly):\n dy = (y - Ly) % Ly # Just to avoid super bounces\n y = Ly - dy - tolerance\n\n self.position[0] = x\n self.position[1] = y\n\n gridx = np.int32(x / sim.dim_delta)\n gridy = np.int32(y / sim.dim_delta)\n\n self.grid_point[0] = gridx\n self.grid_point[1] = gridy\n\n xout = (self.grid_point[0] < 0) or (self.grid_point[0] > self.sim.num_bins_x - 1)\n yout = (self.grid_point[1] < 0) or (self.grid_point[1] > self.sim.num_bins_y - 1)\n\n if xout or yout:\n print 'out of bounds, wtf'\n print 'position:', self.position\n print 'random:', rand2\n print\n\n sim.grid[self.grid_point[0], self.grid_point[1], self.pop_type] += 1\n\n def birth(self):\n return Particle(self.sim, self.pop_type, self.position, self.grid_point,\n D=self.D, k=self.k)" }, { "alpha_fraction": 0.6418092846870422, "alphanum_fraction": 0.6442542672157288, "avg_line_length": 28.214284896850586, "blob_id": "de820c8d1bdd52f93e3631a787b64762237f7ba6", "content_id": "fcd16ee5f2d2a01e0f0d9e69d81a8bd2a96ca6cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 818, "license_type": "no_license", "max_line_length": 85, "num_lines": 28, "path": "/setup.py", "repo_name": "Range-Expansions/particle_populations_in_flow", "src_encoding": "UTF-8", "text": "from setuptools import setup\nfrom distutils.extension import Extension\nfrom Cython.Build import cythonize\nimport cython_gsl\nimport numpy as np\nfrom distutils.core import setup\n\nextensions = [\n Extension(\"flow_pop.cy_particles\",\n sources=[\"flow_pop/cy_particles.pyx\"],\n language=\"c++\", libraries = cython_gsl.get_libraries(),\n library_dirs = [cython_gsl.get_library_dir()],\n include_dirs = [cython_gsl.get_cython_include_dir(), np.get_include()])\n]\n\n\nsetup(\n name='particle_populations_in_flow',\n version='0.1',\n packages=['flow_pop'],\n include_dirs = [cython_gsl.get_include(), np.get_include()],\n ext_modules = cythonize(extensions, annotate=True),\n url='',\n license='',\n author='bryan',\n author_email='[email protected]',\n description='',\n)\n" }, { "alpha_fraction": 0.743922233581543, "alphanum_fraction": 0.784440815448761, "avg_line_length": 28.428571701049805, "blob_id": "70cac6243bf618cf9b4b14dc56bc8a9cad2cf5e2", "content_id": "b5b351dde33a41b0cc8d6c0f73537352e2d0898a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 619, "license_type": "no_license", "max_line_length": 92, "num_lines": 21, "path": "/README.md", "repo_name": "Range-Expansions/particle_populations_in_flow", "src_encoding": "UTF-8", "text": "# Particle Populations in Flow\n\nA cython instantiation of the algorithm discussed in \n\nPigolotti S. et al. \n*Growth, competition and cooperation in spatial population genetics*. \nTheoretical Population Biology (2013), 84C, 72–86. https://doi.org/10.1016/j.tpb.2012.12.002\n\nCurrently, an arbitrary number of populations with differing growth rates\ncompete to eat nutrients while they are advected by fluid flow.\n\nTo install, use\n\n```python\npython setup.py develop\n```\n\nInstallation requires Cython and CythonGSL (you can install CythonGSL \nwith pip). \n\nSee the examples folder for ipython notebooks showing how to use the code." } ]
3
AngryBaer/abMaya
https://github.com/AngryBaer/abMaya
b1014ca9cfbf8257b012707cf817609819badbfb
c6b7221f48f7e68c88bc8f15229a54d1de0fd64f
2ca2e040878cf07782d46d15c42f984b1fa7f56f
refs/heads/master
2023-01-21T23:52:03.592719
2020-12-03T02:31:05
2020-12-03T02:31:05
283,690,668
0
0
null
2020-07-30T06:40:35
2020-07-30T07:22:49
2020-12-02T02:50:54
Python
[ { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 11, "blob_id": "1104237a5c2718f58960426eeda7160d1168c4f4", "content_id": "4d5b160ed8790597e4927e2a36cdbeaa3df67d12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12, "license_type": "no_license", "max_line_length": 11, "num_lines": 1, "path": "/plug_ngSkinTools/python/core/__init__.py", "repo_name": "AngryBaer/abMaya", "src_encoding": "UTF-8", "text": "# core init\n" }, { "alpha_fraction": 0.523392379283905, "alphanum_fraction": 0.5249850749969482, "avg_line_length": 36.20000076293945, "blob_id": "80a17ae92fe171ff856e9dc76c5c7bdf089a1a35", "content_id": "5e2615bfa6a116edcbda18ac9ff769d9af181a4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5023, "license_type": "no_license", "max_line_length": 109, "num_lines": 135, "path": "/plug_ngSkinTools/python/api.py", "repo_name": "AngryBaer/abMaya", "src_encoding": "UTF-8", "text": "\n# IMPORTS --------------------------------------------------------------------------------------- #\nimport os\n\nfrom maya import cmds, mel\nfrom ngSkinTools.mllInterface import MllInterface\nfrom ngSkinTools.paint import ngLayerPaintCtxInitialize\nfrom ngSkinTools.utils import Utils\n\nfrom .core import adjust, paint\n# ----------------------------------------------------------------------------------------------- #\n\n\nMEL_SCRIPT = r'mel/brush_utilities.mel'\nCOMMANDS = {\n 'test' : 'ngSkinToolsCustom_Test',\n 'conceal' : 'ngSkinToolsCustom_Conceal',\n 'spread' : 'ngSkinToolsCustom_Spread',\n 'contrast': 'ngSkinToolsCustom_Contrast',\n 'gain' : 'ngSkinToolsCustom_Gain',\n 'equalize': 'ngSkinToolsCustom_VolEq'\n}\n\n\n# ----------------------------------------------------------------------------------------------- #\nclass NgPaintStroke():\n \"\"\" Custom ngSkinTools brush setup class \"\"\"\n\n MODE = 1\n VALUE = 1\n STROKE_ID = None\n\n def __init__(self, surface):\n self.surface = surface\n\n self.mll = MllInterface()\n self.ngs_layer_id = self.mll.getCurrentLayer()\n self.ngs_target = self.mll.getCurrentPaintTarget()\n self.ngs_target_info = self.mll.getTargetInfo()\n self.ngs_weight_list = self.mll.getInfluenceWeights(self.ngs_layer_id, self.ngs_target)\n\n def stroke_initialize(self):\n \"\"\" Executes before each brushstroke \"\"\"\n cmds.undoInfo(openChunk=True, undoName=\"custom_ngPaintStroke\")\n cmds.ngSkinLayer(paintOperation=self.MODE, paintIntensity=self.VALUE)\n\n stroke_id_str = ngLayerPaintCtxInitialize(self.ngs_target_info[0])\n self.STROKE_ID = int(stroke_id_str.split(\" \")[1])\n\n return self.surface, self.STROKE_ID\n\n def paint_contrast(self, vtxID, value):\n \"\"\" sharpen edge of active weight map on brushstroke \"\"\"\n min_weight = min(self.ngs_weight_list)\n max_weight = max(self.ngs_weight_list)\n weight = self.ngs_weight_list[vtxID]\n\n if not max_weight > weight > min_weight:\n return # skip weights with no change\n\n result = paint.contrast(value, weight, min_weight, max_weight)\n cmds.ngSkinLayer(paintIntensity=result)\n cmds.ngLayerPaintCtxSetValue(self.STROKE_ID, vtxID, 1)\n\n def paint_gain(self, vtxID, value):\n \"\"\" increase weight intensity, preserving zero weights \"\"\"\n weight = self.ngs_weight_list[vtxID]\n\n if weight == 0:\n return # skip weights with no change\n\n result = paint.gain(value, weight)\n cmds.ngSkinLayer(paintIntensity=result)\n cmds.ngLayerPaintCtxSetValue(self.STROKE_ID, vtxID, 1)\n\n def paint_test(self, vtxID, value):\n \"\"\" test input of the brush scripts \"\"\"\n print('surface: ', self.surface)\n print('target: ', self.mll.getTargetInfo())\n print('vertex: ', vtxID, value)\n\n def stroke_finalize(self):\n \"\"\" Executes after each brushstroke \"\"\"\n if self.STROKE_ID:\n cmds.ngLayerPaintCtxFinalize(self.STROKE_ID)\n self.STROKE_ID = None\n cmds.undoInfo(closeChunk=True)\n# ----------------------------------------------------------------------------------------------- #\n\n\n# ----------------------------------------------------------------------------------------------- #\nclass NgMapAdjustment():\n \"\"\" Custom operations applied onto entire active ngSkinTools layer \"\"\"\n def __init__(self):\n pass\n# ----------------------------------------------------------------------------------------------- #\n\n\n# ----------------------------------------------------------------------------------------------- #\nclass NgComponent():\n \"\"\" Custom operations applied to selected components \"\"\"\n def __init__(self):\n pass\n# ----------------------------------------------------------------------------------------------- #\n\n\n# SCRIPT BRUSH SETUP ---------------------------------------------------------------------------- #\ndef custom_paint_setup():\n package_path = os.path.dirname(os.path.dirname(__file__))\n mel_cmd = 'source \"{}\"'.format(os.path.join(package_path, MEL_SCRIPT).replace('\\\\', '/'))\n mel.eval(mel_cmd)\n cmds.artUserPaintCtx(\n \"ngSkinToolsLayerPaintCtx\",\n initializeCmd=\"ngSkinToolsCustom_Initialize\",\n finalizeCmd=\"ngSkinToolsCustom_Finalize\",\n e=True,\n )\n\ndef custom_paint_value(valueCommand):\n cmds.artUserPaintCtx(\n \"ngSkinToolsLayerPaintCtx\",\n setValueCommand=COMMANDS[valueCommand],\n e=True\n )\n\ndef custom_paint_exit():\n init_cmd = Utils.createMelProcedure(ngLayerPaintCtxInitialize, [('string', 'mesh')], returnType='string')\n cmds.artUserPaintCtx(\n \"ngSkinToolsLayerPaintCtx\",\n setValueCommand=\"ngLayerPaintCtxSetValue\",\n initializeCmd=init_cmd,\n finalizeCmd=\"ngLayerPaintCtxFinalize\",\n value=1,\n e=True\n )\n# ----------------------------------------------------------------------------------------------- #\n" }, { "alpha_fraction": 0.4207920730113983, "alphanum_fraction": 0.4207920730113983, "avg_line_length": 35.727272033691406, "blob_id": "e156f0d7a556d1b10fcd7b59c649815c1575704a", "content_id": "c752f227a56626371d331aae7c85d300d2a5e887", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1212, "license_type": "no_license", "max_line_length": 99, "num_lines": 33, "path": "/libContext/lib/scene.py", "repo_name": "AngryBaer/abMaya", "src_encoding": "UTF-8", "text": "\"\"\"\nMaya scene specific context managers.\n\"\"\"\n\n\n# IMPORTS --------------------------------------------------------------------------------------- #\nimport os\nfrom maya import cmds\n# ----------------------------------------------------------------------------------------------- #\n\n\n# ----------------------------------------------------------------------------------------------- #\nclass BypassSceneName(object):\n \"\"\"\n Context Manager for temporarily renaming the Maya scene.\n e.g. for saving a copy of the current scene under a different name.\n e.g. for generating animation clip names during FBX export.\n \"\"\"\n def __init__(self, tempName):\n \"\"\"\n :param tempName: temporary name of the Maya scene.\n - str\n \"\"\"\n self.sceneName = cmds.file(sceneName=True, q=True)\n directory = os.path.dirname(self.sceneName)\n self.newName = '{}/{}.ma'.format(directory, tempName)\n\n def __enter__(self):\n cmds.file(rename=self.newName)\n\n def __exit__(self, ex_type, ex_value, ex_traceback):\n cmds.file(rename=self.sceneName)\n# ----------------------------------------------------------------------------------------------- #\n" }, { "alpha_fraction": 0.41309988498687744, "alphanum_fraction": 0.41309988498687744, "avg_line_length": 31.82978630065918, "blob_id": "a2349d8824428c0e873024d034583c88dc4e30aa", "content_id": "8d0ab751e22640cfbcd32058349a2b293e89b1a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1542, "license_type": "no_license", "max_line_length": 99, "num_lines": 47, "path": "/libContext/lib/attributes.py", "repo_name": "AngryBaer/abMaya", "src_encoding": "UTF-8", "text": "\"\"\"\nMaya attribute specific context managers.\n\"\"\"\n\n\n# IMPORTS --------------------------------------------------------------------------------------- #\nimport os\nfrom maya import cmds\n# ----------------------------------------------------------------------------------------------- #\n\n\n# ----------------------------------------------------------------------------------------------- #\nclass BypassValue(object):\n \"\"\"\n Context Manager for temporarily renaming the Maya scene.\n e.g. for saving a copy of the current scene under a different name.\n e.g. for generating animation clip names during FBX export.\n \"\"\"\n def __init__(self, channel, tempValue=None):\n \"\"\"\n :param channel: bypassed channel.\n - str\n :param tempName: temporary value of the channel.\n - bool\n - str\n - int\n - float\n - enum\n\n :return None:\n \"\"\"\n # NOTE: WIP assertions\n self.channel = channel\n self.oldValue = cmds.getAttr(self.channel, q=True)\n self.newvalue = tempValue\n\n def __enter__(self):\n cmds.setAttr(self.channel, self.newvalue)\n\n def __exit__(self, ex_type, ex_value, ex_traceback):\n cmds.setAttr(self.channel, self.oldValue)\n# ----------------------------------------------------------------------------------------------- #\n\n\n# NOTE: WIP, lock/unlock attribute\n# NOTE: WIP, key/unkey\n# NOTE: WIP, all channels" }, { "alpha_fraction": 0.462981253862381, "alphanum_fraction": 0.48420533537864685, "avg_line_length": 36.51852035522461, "blob_id": "e6040fd79b01cd3bc6d1730b4f90c99f1d579def", "content_id": "ecf8c3c729cdcb04a52111f4353ca000ccb34cf2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2026, "license_type": "no_license", "max_line_length": 99, "num_lines": 54, "path": "/plug_ngSkinTools/python/core/paint.py", "repo_name": "AngryBaer/abMaya", "src_encoding": "UTF-8", "text": "\n# IMPORTS --------------------------------------------------------------------------------------- #\nfrom math import pow, sqrt\n\nfrom abMaya.libModel import component\n# ----------------------------------------------------------------------------------------------- #\n\n\n# ----------------------------------------------------------------------------------------------- #\ndef contrast(value, weight, vtxMin, vtxMax):\n \"\"\"\n True contrast operation that preserves minimum and maximum values.\n Applies a curve to the given weight value that increases its distance to the average value.\n\n :param value: intensity value of the brush stroke\n - float 0.0 - 1.0\n :param weight: current weight value of the given vertex\n - float 0.0 - 1.0\n :param vtxMin: minimum weight value of affected vertices\n - float 0.0 - 1.0\n :param vtxMax: maximum weight vlaue of affected vertices\n - float 0.0 - 1.0\n\n :return result: modified weight value\n - float 0.0 - 1.0\n \"\"\"\n average = (vtxMax + vtxMin) / 2.0\n difference = weight - average\n\n if difference == 0:\n return weight\n\n if difference > 0:\n return min(weight + ((vtxMax - weight) * value), vtxMax)\n\n if difference < 0:\n return max(weight - ((weight - vtxMin) * value), vtxMin)\n\n\n\ndef gain(value, weight):\n \"\"\"\n Gain operation that preserves zero weights.\n Applies a gain curve to the given weight value that increases its distance to zero.\n\n :param value: intensity value of the brush stroke\n - float 0.0 - 1.0\n :param weight: current weight value of the given vertex\n - float 0.0 - 1.0\n\n :return result: modified weight value\n - float 0.0 - 1.0\n \"\"\"\n return min(weight + (weight * value), 1.0) # add gain value and clamp between 0.0 and 1.0\n# ----------------------------------------------------------------------------------------------- #" }, { "alpha_fraction": 0.8461538553237915, "alphanum_fraction": 0.8461538553237915, "avg_line_length": 26, "blob_id": "55561e5bc4470e10008072245cd2d48deca22326", "content_id": "66f745763f9a16b3bc20c3498f452654e7cb47f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 26, "license_type": "no_license", "max_line_length": 26, "num_lines": 1, "path": "/libModel/__init__.py", "repo_name": "AngryBaer/abMaya", "src_encoding": "UTF-8", "text": "from .lib import component" }, { "alpha_fraction": 0.5737048387527466, "alphanum_fraction": 0.5869972705841064, "avg_line_length": 39.75, "blob_id": "74e59b6946645cc409f205be756d7ff06ac21e53", "content_id": "028a2c26125036f6a529af678ce00ea526e6c1b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11736, "license_type": "no_license", "max_line_length": 110, "num_lines": 288, "path": "/plug_ngSkinTools/python/temp/ng_equalizer.py", "repo_name": "AngryBaer/abMaya", "src_encoding": "UTF-8", "text": "import maya.cmds as cmds\nimport alex_utils as utils\nfrom ngSkinTools.mllInterface import MllInterface\n\n\nclass Equalize(object):\n def __init__(self):\n self.mll = MllInterface()\n self.ngs_vert_count = -1\n self.ngs_layer_id = -1\n self.intensity = -1\n self.ngs_influence = None\n self.vert_weight_dict = {}\n self.vert_weight_list = []\n self.ngs_weight_dict = {}\n self.ngs_weight_list = []\n self.new_weight_list = []\n self.selection_vert = []\n self.vertex_list = []\n self.id_list = []\n\n self.modes = {\n \"max\": self.vert_max,\n \"min\": self.vert_min,\n \"avg\": self.vert_avg,\n \"first\": self.vert_first,\n \"last\": self.vert_last\n }\n\n def get_data(self, check):\n self.ngs_weight_dict = {}\n self.vert_weight_dict = {}\n self.selection_vert = cmds.ls(os=True)\n if not self.selection_vert:\n return False\n if not check:\n self.ngs_influence = [(\"selected influence:\", self.mll.getCurrentPaintTarget())]\n else:\n self.ngs_influence = self.mll.listLayerInfluences(layerId=None, activeInfluences=True)\n self.mll = MllInterface()\n self.ngs_layer_id = self.mll.getCurrentLayer()\n self.ngs_vert_count = self.mll.getVertCount()\n self.vertex_list = cmds.ls(self.selection_vert, flatten=True)\n self.id_list = list(map(lambda x: x[x.find(\"[\") + 1:x.find(\"]\")], self.vertex_list))\n for influences in self.ngs_influence:\n influence_weights = self.mll.getInfluenceWeights(self.ngs_layer_id, influences[1])\n vert_weights = [influence_weights[int(i)] for i in self.id_list]\n self.ngs_weight_dict[influences] = influence_weights\n self.vert_weight_dict[influences] = vert_weights\n return True\n\n def set_vert(self, mode, intensity):\n self.intensity = intensity\n for influences in self.ngs_influence:\n self.new_weight_list = []\n self.ngs_weight_list = self.ngs_weight_dict[influences]\n self.vert_weight_list = self.vert_weight_dict[influences]\n self.modes[mode]()\n self.mll.setInfluenceWeights(self.ngs_layer_id, influences[1], self.new_weight_list)\n\n def vert_max(self):\n for i in range(self.ngs_vert_count):\n vertex_weight = self.ngs_weight_list[i]\n if str(i) not in self.id_list or vertex_weight == max(self.vert_weight_list):\n self.new_weight_list.append(vertex_weight)\n continue\n new_weight = vertex_weight + ((max(self.vert_weight_list) - vertex_weight) * self.intensity)\n self.new_weight_list.append(new_weight)\n\n def vert_min(self):\n for i in range(self.ngs_vert_count):\n vertex_weight = self.ngs_weight_list[i]\n if str(i) not in self.id_list or vertex_weight == min(self.vert_weight_list):\n self.new_weight_list.append(vertex_weight)\n continue\n new_weight = vertex_weight - ((vertex_weight - min(self.vert_weight_list)) * self.intensity)\n self.new_weight_list.append(new_weight)\n\n def vert_avg(self):\n average = sum(self.vert_weight_list) / float(len(self.vert_weight_list))\n for i in range(self.ngs_vert_count):\n vertex_weight = self.ngs_weight_list[i]\n if str(i) not in self.id_list or vertex_weight == average:\n self.new_weight_list.append(vertex_weight)\n continue\n new_weight = vertex_weight - ((vertex_weight - average) * self.intensity)\n self.new_weight_list.append(new_weight)\n\n def vert_first(self):\n first = self.vert_weight_list[0]\n for i in range(self.ngs_vert_count):\n vertex_weight = self.ngs_weight_list[i]\n if str(i) not in self.id_list or vertex_weight == first:\n self.new_weight_list.append(vertex_weight)\n continue\n new_weight = vertex_weight - ((vertex_weight - first) * self.intensity)\n self.new_weight_list.append(new_weight)\n\n def vert_last(self):\n last = self.vert_weight_list[-1]\n for i in range(self.ngs_vert_count):\n vertex_weight = self.ngs_weight_list[i]\n if str(i) not in self.id_list or vertex_weight == last:\n self.new_weight_list.append(vertex_weight)\n continue\n new_weight = vertex_weight - ((vertex_weight - last) * self.intensity)\n self.new_weight_list.append(new_weight)\n\n\nclass Comparison_UI(object):\n def __init__(self):\n self.window = \"equalizer_ui\"\n self.title = \"ng Vertex Equalizer\"\n self.size = (300, 125)\n self.eq = Equalize()\n\n self.last_call = \"\"\n self.green = utils.rgb_to_float(120, 220, 120)\n self.red = utils.rgb_to_float(220, 120, 120)\n\n self.max_button = \"Max +\"\n self.min_button = \"Min -\"\n self.avg_button = \"Avg =\"\n self.first_button = \"To First\"\n self.last_button = \"To Last\"\n self.scroll_button = \"To List Selection\"\n self.all_check = \"Affect All Influences:\"\n\n self.slider = \"intensity_slider\"\n self.field = \"intensity_field\"\n self.columnForm = \"column_form\"\n self.buttonForm = \"button_form\"\n self.intensityForm = \"intensity_form\"\n\n def button_color(self, *args):\n cmds.button(self.max_button, e=True, backgroundColor=(.361, .361, .361))\n cmds.button(self.min_button, e=True, backgroundColor=(.361, .361, .361))\n cmds.button(self.avg_button, e=True, backgroundColor=(.361, .361, .361))\n cmds.button(self.first_button, e=True, backgroundColor=(.361, .361, .361))\n cmds.button(self.last_button, e=True, backgroundColor=(.361, .361, .361))\n\n def do_first(self, *args):\n all_check = cmds.checkBox(self.all_check, q=True, value=True)\n if not self.eq.get_data(all_check):\n return\n intensity = cmds.floatSlider(self.slider, q=True, value=True)\n self.eq.set_vert(\"first\", intensity)\n self.last_call = \"first\"\n self.button_color()\n cmds.button(self.first_button, e=True, backgroundColor=(self.green[0], self.green[1], self.green[2]))\n\n def do_last(self, *args):\n all_check = cmds.checkBox(self.all_check, q=True, value=True)\n if not self.eq.get_data(all_check):\n return\n intensity = cmds.floatSlider(self.slider, q=True, value=True)\n self.eq.set_vert(\"last\", intensity)\n self.last_call = \"last\"\n self.button_color()\n cmds.button(self.last_button, e=True, backgroundColor=(self.green[0], self.green[1], self.green[2]))\n\n def do_max(self, *args):\n all_check = cmds.checkBox(self.all_check, q=True, value=True)\n if not self.eq.get_data(all_check):\n return\n intensity = cmds.floatSlider(self.slider, q=True, value=True)\n self.eq.set_vert(\"max\", intensity)\n self.last_call = \"max\"\n self.button_color()\n cmds.button(self.max_button, e=True, backgroundColor=(self.green[0], self.green[1], self.green[2]))\n\n def do_min(self, *args):\n all_check = cmds.checkBox(self.all_check, q=True, value=True)\n if not self.eq.get_data(all_check):\n return\n intensity = cmds.floatSlider(self.slider, q=True, value=True)\n self.eq.set_vert(\"min\", intensity)\n self.last_call = \"min\"\n self.button_color()\n cmds.button(self.min_button, e=True, backgroundColor=(self.green[0], self.green[1], self.green[2]))\n\n def do_avg(self, *args):\n all_check = cmds.checkBox(self.all_check, q=True, value=True)\n if not self.eq.get_data(all_check):\n return\n intensity = cmds.floatSlider(self.slider, q=True, value=True)\n self.eq.set_vert(\"avg\", intensity)\n self.last_call = \"avg\"\n self.button_color()\n cmds.button(self.avg_button, e=True, backgroundColor=(self.green[0], self.green[1], self.green[2]))\n\n def do_drag(self, *args):\n self.update_float_field()\n selection_vert = cmds.ls(selection=True)\n if not selection_vert:\n return\n intensity = cmds.floatSlider(self.slider, q=True, value=True)\n if self.last_call == \"max\":\n self.eq.set_vert(\"max\", intensity)\n if self.last_call == \"min\":\n self.eq.set_vert(\"min\", intensity)\n if self.last_call == \"avg\":\n self.eq.set_vert(\"avg\", intensity)\n if self.last_call == \"first\":\n self.eq.set_vert(\"first\", intensity)\n if self.last_call == \"last\":\n self.eq.set_vert(\"last\", intensity)\n\n def update_float_field(self, *args):\n float_intensity = cmds.floatSlider(self.slider, q=True, value=True)\n cmds.floatField(self.field, e=True, value=float_intensity)\n\n def update_float_slider(self, *args):\n field_intensity = cmds.floatField(self.field, q=True, value=True)\n cmds.floatSlider(self.slider, e=True, value=field_intensity)\n\n def create(self):\n if cmds.window(self.window, exists=True):\n cmds.deleteUI(self.window, window=True)\n self.window = cmds.window(\n self.window,\n title=self.title,\n widthHeight=self.size\n )\n cmds.columnLayout(adjustableColumn=True)\n cmds.rowColumnLayout(numberOfColumns=3, columnWidth=[(1, 100), (2, 100), (3, 100)])\n self.min_button = cmds.button(label=self.min_button, command=self.do_min, enableBackground=True)\n self.avg_button = cmds.button(label=self.avg_button, command=self.do_avg, enableBackground=True)\n self.max_button = cmds.button(label=self.max_button, command=self.do_max, enableBackground=True)\n cmds.setParent('..')\n cmds.separator(style='none', height=5)\n cmds.rowColumnLayout(numberOfColumns=2, columnWidth=[(1, 150), (2, 150), ])\n self.first_button = cmds.button(label=self.first_button, command=self.do_first, enableBackground=True)\n self.last_button = cmds.button(label=self.last_button, command=self.do_last, enableBackground=True)\n cmds.setParent('..')\n cmds.separator(style='none', height=5)\n cmds.rowLayout(\n numberOfColumns=3,\n adjustableColumn=3,\n columnAlign=(1, 'right'),\n columnWidth=[(1, 60), (2, 80), (3, 160)],\n columnOffset3=(0, 5, 0),\n columnAttach3=('both', 'left', 'left'),\n )\n cmds.text(label='Intensity:')\n self.field = cmds.floatField()\n self.slider = cmds.floatSlider()\n cmds.floatField(\n self.field,\n e=True,\n width=80,\n minValue=0,\n maxValue=1,\n step=0.001,\n value=1,\n dragCommand=self.do_drag,\n changeCommand=self.update_float_slider\n )\n cmds.floatSlider(\n self.slider,\n e=True,\n minValue=0,\n maxValue=1,\n step=0.001,\n value=1,\n dragCommand=self.do_drag,\n )\n cmds.setParent('..')\n cmds.rowLayout(\n numberOfColumns=1,\n adjustableColumn=1,\n columnAlign=(1, 'left'),\n columnOffset1=25\n )\n self.all_check = cmds.checkBox(\n label=self.all_check,\n value=True,\n )\n cmds.setParent('..')\n cmds.setParent('..')\n cmds.showWindow()\n self.button_color()\n\n\ndef open_equalizer(*args):\n \"\"\" opens the Equalizer UI window \"\"\"\n create_eq = Comparison_UI()\n create_eq.create()\n" }, { "alpha_fraction": 0.5151515007019043, "alphanum_fraction": 0.5151515007019043, "avg_line_length": 15.333333015441895, "blob_id": "a16eb864a16f28e0ccd8b258aeeb4e92ec3bb024", "content_id": "242735daca16211e9e65026260b3d8006fb2a31b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 198, "license_type": "no_license", "max_line_length": 28, "num_lines": 12, "path": "/abNode/python/geo.py", "repo_name": "AngryBaer/abMaya", "src_encoding": "UTF-8", "text": "\n\n\nclass GeoNode():\n\n def __init__():\n pass\n\n def get_mesh(item):\n mesh = None\n return mesh\n\n def get_transform(item):\n transform = None\n return transform" }, { "alpha_fraction": 0.5990626811981201, "alphanum_fraction": 0.6060606241226196, "avg_line_length": 43.31294631958008, "blob_id": "35788b52defe9a39a1e8daa7683837862cfa4f60", "content_id": "430fa41acb4f5e426df1f8ce8af92e6dd14d922d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 31152, "license_type": "no_license", "max_line_length": 119, "num_lines": 703, "path": "/plug_ngSkinTools/python/temp/ng_extra_tools.py", "repo_name": "AngryBaer/abMaya", "src_encoding": "UTF-8", "text": "\"\"\"\n\n Add custom paint operations to the ng skin tools plugin\n\n these operations include:\n - conceal\n - spread\n - contrast\n - gain\n - volume equalize\n\n additionally there are the following options for modifying the entire weight map:\n - shrink map\n - grow map\n - flood brush\n\"\"\"\n\nimport maya.cmds as cmds\nimport maya.mel as mel\nimport ng_equalizer as eq\nfrom math import pow\nfrom math import sqrt\nfrom scipy.stats import norm\nfrom ngSkinTools.mllInterface import MllInterface\nfrom ngSkinTools.utils import Utils\nfrom ngSkinTools.paint import ngLayerPaintCtxInitialize\n\n\ndef get_target_control(ui_path):\n \"\"\" returns a list of controls or layouts within a specified ui path \"\"\"\n UI_list = cmds.lsUI(type=['control', 'controlLayout', 'menu'], long=True)\n target_control = ui_path.split('|')\n number_list = []\n for items in UI_list:\n layouts = items.split('|')\n number = ''.join(i for i in layouts[-1] if i.isdigit())\n target_items = ''.join(i for i in items if not i.isdigit())\n if target_items == ui_path:\n number_list.append(int(number))\n if number_list:\n target_list = [''.join([target_control[-1], str(i)]) for i in sorted(number_list)]\n return target_list\n\n\ndef get_surrounding_verts(vertex):\n \"\"\" returns a list of vertex indices that are connected by edge with the input vertex \"\"\"\n edge_list = cmds.polyListComponentConversion(vertex, toEdge=True)\n vertex_list = cmds.polyListComponentConversion(edge_list, toVertex=True)\n vertex_list = cmds.ls(vertex_list, flatten=True)\n id_list = list(map(lambda x: x[x.find(\"[\") + 1:x.find(\"]\")], vertex_list))\n return id_list\n\n\nclass UseNgBrush(object):\n \"\"\" setup for custom brush operations, a new instance is created on every brush stroke \"\"\"\n def __init__(self, surface_name):\n self.surface = surface_name\n self.stroke_id = None\n self.mode = 1\n self.value = 1\n self.volumeThreshold = -0.1\n\n self.mll = MllInterface()\n self.selection_name = cmds.ls(selection=True)\n self.mesh = cmds.listRelatives(self.selection_name[0], shapes=True)\n self.ngs_layer_id = self.mll.getCurrentLayer()\n self.ngs_influence = self.mll.getCurrentPaintTarget()\n self.ngs_weight_list = self.mll.getInfluenceWeights(self.ngs_layer_id, self.ngs_influence)\n self.max_value = max(self.ngs_weight_list)\n self.min_value = min(self.ngs_weight_list)\n\n def stroke_initialize(self):\n \"\"\" this function is executed before each brush stroke \"\"\"\n cmds.undoInfo(openChunk=True, undoName=\"paint stroke\")\n get_stroke_id = ngLayerPaintCtxInitialize(self.mesh[0])\n self.stroke_id = int(get_stroke_id.split(\" \")[1])\n cmds.ngSkinLayer(paintOperation=self.mode, paintIntensity=self.value)\n self.stroke_update()\n return self.surface, self.stroke_id\n\n def stroke_finalize(self):\n \"\"\" this function is executed after each brush stroke \"\"\"\n if self.stroke_id:\n cmds.ngLayerPaintCtxFinalize(self.stroke_id)\n self.stroke_id = None\n cmds.undoInfo(closeChunk=True)\n\n def stroke_update(self):\n \"\"\" updates certain attributes for the brush instance \"\"\"\n # self.mll = MllInterface()\n # self.selection_name = cmds.ls(selection=True)\n # self.mesh = cmds.listRelatives(self.selection_name[0], shapes=True)\n # self.ngs_layer_id = self.mll.getCurrentLayer()\n # self.ngs_influence = self.mll.getCurrentPaintTarget()\n # self.ngs_weight_list = self.mll.getInfluenceWeights(self.ngs_layer_id, self.ngs_influence)\n # self.max_value = max(self.ngs_weight_list)\n # self.min_value = min(self.ngs_weight_list)\n self.volumeThreshold = cmds.floatSlider(\"volume_slider\", q=True, value=True)\n\n def contrast_paint(self, vert_id, value):\n \"\"\" sharpens the edge of the active weight map \"\"\"\n vertex_weight = self.ngs_weight_list[vert_id]\n if not self.max_value > vertex_weight > self.min_value:\n return\n avg_value = (self.max_value + self.min_value) / 2\n normalized_range = self.max_value - self.min_value\n dist_value = vertex_weight - avg_value\n modifier = norm.cdf(dist_value, loc=0, scale=(0.1 * normalized_range)) - vertex_weight\n contrast_weight = vertex_weight + (modifier * value)\n contrast_weight = max(self.min_value, min(contrast_weight, self.max_value))\n cmds.ngSkinLayer(paintIntensity=contrast_weight)\n cmds.ngLayerPaintCtxSetValue(self.stroke_id, vert_id, 1)\n\n def conceal_paint(self, vert_id, value):\n \"\"\" smooth operation that only lowers weight values \"\"\"\n vertex_weight = self.ngs_weight_list[vert_id]\n if vertex_weight <= self.min_value:\n return\n vertex_name = '{}.vtx[{}]'.format(self.selection_name[0], vert_id)\n area_vertices = get_surrounding_verts(vertex_name)\n weight_list = [self.ngs_weight_list[int(x)] for x in area_vertices]\n weight_avg = sum(weight_list) / float(len(weight_list))\n min_avg = min(weight_list)\n threshold = 0.01 / (value / 0.1)\n if weight_avg >= self.max_value and abs(weight_avg - vertex_weight) <= threshold:\n return\n weight_diff = abs(weight_avg - vertex_weight)\n conceal_weight = vertex_weight * (1 - (weight_diff * value))\n conceal_weight = max(conceal_weight, min_avg)\n cmds.ngSkinLayer(paintIntensity=conceal_weight)\n cmds.ngLayerPaintCtxSetValue(self.stroke_id, vert_id, 1)\n\n def spread_paint(self, vert_id, value):\n \"\"\" smooth operation that only increases weight values \"\"\"\n vertex_weight = self.ngs_weight_list[vert_id]\n if vertex_weight >= self.max_value:\n return\n vertex_name = '.'.join([self.selection_name[0], 'vtx[%d]' % vert_id])\n area_vertices = get_surrounding_verts(vertex_name)\n weight_list = [self.ngs_weight_list[int(x)] for x in area_vertices]\n weight_avg = sum(weight_list) / float(len(weight_list))\n max_avg = max(weight_list)\n threshold = 0.01 / (value / 0.1)\n if weight_avg <= self.min_value and abs(weight_avg - vertex_weight) <= threshold:\n return\n weight_diff = abs(weight_avg - vertex_weight)\n spread_weight = vertex_weight + (weight_diff * value)\n spread_weight = min(spread_weight, max_avg)\n cmds.ngSkinLayer(paintIntensity=spread_weight)\n cmds.ngLayerPaintCtxSetValue(self.stroke_id, vert_id, 1)\n\n def gain_paint(self, vert_id, value):\n \"\"\" increases existing weight values but preserves empty weights \"\"\"\n vertex_weight = self.ngs_weight_list[vert_id]\n if vertex_weight == 0:\n return\n gain_weight = vertex_weight + (vertex_weight * value)\n gain_weight = min(gain_weight, 1)\n cmds.ngSkinLayer(paintIntensity=gain_weight)\n cmds.ngLayerPaintCtxSetValue(self.stroke_id, vert_id, 1)\n\n def volume_equalize(self, vert_id, value):\n \"\"\"\n i.e a volumetric match operation with a falloff.\n applies weight values inside the brush radius onto other vertices inside a spherical volume\n \"\"\"\n origin_vertex = '.'.join([self.selection_name[0], 'vtx[%s]']) % vert_id\n vertex_weight = self.ngs_weight_list[vert_id]\n v1 = cmds.pointPosition(origin_vertex)\n for i in range(len(self.ngs_weight_list)):\n target_weight = self.ngs_weight_list[i]\n if target_weight == vertex_weight:\n continue\n if i == vert_id:\n continue\n target_vertex = '.'.join([self.selection_name[0], 'vtx[%s]']) % i\n v2 = cmds.pointPosition(target_vertex)\n target_distance = sqrt(\n (pow((v1[0]-v2[0]), 2)) +\n (pow((v1[1]-v2[1]), 2)) +\n (pow((v1[2]-v2[2]), 2))\n )\n if target_distance > (self.volumeThreshold * value):\n continue\n falloff = (self.volumeThreshold - target_distance) / self.volumeThreshold\n eq_weight = target_weight - (((target_weight - vertex_weight) * value) * falloff)\n cmds.ngSkinLayer(paintIntensity=eq_weight)\n cmds.ngLayerPaintCtxSetValue(self.stroke_id, i, 1)\n\n\nclass MapOperations(object):\n \"\"\" class that contains operations applied to the entire mesh \"\"\"\n\n def __init__(self):\n self.mll = MllInterface()\n self.selection_name = []\n self.ngs_layer_id = -1\n self.ngs_influence = None\n self.ngs_weight_list = []\n self.ngs_vert_count = -1\n self.max_value = -1.0\n self.min_value = -1.0\n\n def get_data(self):\n self.selection_name = cmds.ls(selection=True)\n self.ngs_layer_id = self.mll.getCurrentLayer()\n self.ngs_influence = self.mll.getCurrentPaintTarget()\n self.ngs_weight_list = self.mll.getInfluenceWeights(self.ngs_layer_id, self.ngs_influence)\n self.ngs_vert_count = self.mll.getVertCount()\n self.max_value = max(self.ngs_weight_list)\n self.min_value = min(self.ngs_weight_list)\n\n def grow_map(self, intensity):\n \"\"\" pushes the border of the active weight map outwards \"\"\"\n self.get_data()\n new_weight_list = []\n for i in range(self.ngs_vert_count):\n vertex_weight = self.ngs_weight_list[i]\n if vertex_weight >= self.max_value:\n new_weight_list.append(vertex_weight)\n continue\n vertex_name = '.'.join([self.selection_name[0], 'vtx[%d]' % i])\n area_vertices = get_surrounding_verts(vertex_name)\n weight_list = [self.ngs_weight_list[int(x)] for x in area_vertices]\n max_avg = max(weight_list)\n if max_avg <= self.min_value:\n new_weight_list.append(vertex_weight)\n continue\n grow_weight = vertex_weight + (abs(vertex_weight - max_avg) * intensity)\n grow_weight = min(grow_weight, self.max_value)\n new_weight_list.append(grow_weight)\n self.mll.setInfluenceWeights(self.ngs_layer_id, self.ngs_influence, new_weight_list)\n\n def shrink_map(self, intensity):\n \"\"\" pulls the border of the active weight map inwards \"\"\"\n self.get_data()\n new_weight_list = []\n for i in range(self.ngs_vert_count):\n vertex_weight = self.ngs_weight_list[i]\n if vertex_weight <= self.min_value:\n new_weight_list.append(vertex_weight)\n continue\n vertex_name = '.'.join([self.selection_name[0], 'vtx[%d]' % i])\n area_vertices = get_surrounding_verts(vertex_name)\n weight_list = [self.ngs_weight_list[int(x)] for x in area_vertices]\n min_avg = min(weight_list)\n if min_avg >= self.max_value:\n new_weight_list.append(vertex_weight)\n continue\n shrink_weight = vertex_weight - (abs(vertex_weight - min_avg) * intensity)\n shrink_weight = max(shrink_weight, self.min_value)\n new_weight_list.append(shrink_weight)\n self.mll.setInfluenceWeights(self.ngs_layer_id, self.ngs_influence, new_weight_list)\n\n def conceal_map(self, intensity):\n \"\"\" smooth operation for the active map by only lowering values \"\"\"\n self.get_data()\n new_weight_list = []\n threshold = 0.01 / (intensity / 0.1)\n for i in range(self.ngs_vert_count):\n vertex_weight = self.ngs_weight_list[i]\n if vertex_weight <= self.min_value:\n new_weight_list.append(vertex_weight)\n continue\n vertex_name = '.'.join([self.selection_name[0], 'vtx[%d]' % i])\n area_vertices = get_surrounding_verts(vertex_name)\n weight_list = [self.ngs_weight_list[int(x)] for x in area_vertices]\n weight_avg = sum(weight_list) / float(len(weight_list))\n min_avg = min(weight_list)\n if weight_avg >= self.max_value and abs(weight_avg - vertex_weight) < threshold:\n new_weight_list.append(vertex_weight)\n continue\n weight_diff = abs(weight_avg - vertex_weight)\n conceal_weight = vertex_weight * (1 - (weight_diff * intensity))\n conceal_weight = max(conceal_weight, min_avg)\n new_weight_list.append(conceal_weight)\n self.mll.setInfluenceWeights(self.ngs_layer_id, self.ngs_influence, new_weight_list)\n\n def spread_map(self, intensity):\n \"\"\" smooth operation for the active map by only increasing values \"\"\"\n self.get_data()\n new_weight_list = []\n threshold = 0.01 / (intensity / 0.1)\n for i in range(self.ngs_vert_count):\n vertex_weight = self.ngs_weight_list[i]\n if vertex_weight >= self.max_value:\n new_weight_list.append(vertex_weight)\n continue\n vertex_name = '.'.join([self.selection_name[0], 'vtx[%d]' % i])\n area_vertices = get_surrounding_verts(vertex_name)\n weight_list = [self.ngs_weight_list[int(x)] for x in area_vertices]\n weight_avg = sum(weight_list) / float(len(weight_list))\n max_avg = max(weight_list)\n if weight_avg <= self.min_value and abs(weight_avg - vertex_weight) < threshold:\n new_weight_list.append(vertex_weight)\n continue\n weight_diff = abs(weight_avg - vertex_weight)\n spread_weight = vertex_weight + weight_diff * intensity\n spread_weight = min(spread_weight, max_avg)\n new_weight_list.append(spread_weight)\n self.mll.setInfluenceWeights(self.ngs_layer_id, self.ngs_influence, new_weight_list)\n\n def gain_map(self, intensity):\n \"\"\" 'reverse scale' tool that only increases weight values above 0 \"\"\"\n self.get_data()\n new_weight_list = []\n for i in range(self.ngs_vert_count):\n vertex_weight = self.ngs_weight_list[i]\n if vertex_weight == 0:\n new_weight_list.append(vertex_weight)\n continue\n gain_weight = vertex_weight + (vertex_weight * intensity)\n gain_weight = min(gain_weight, 1)\n new_weight_list.append(gain_weight)\n self.mll.setInfluenceWeights(self.ngs_layer_id, self.ngs_influence, new_weight_list)\n\n def contrast_map(self, intensity):\n \"\"\" sharpens the edge of the active weight map \"\"\"\n self.get_data()\n new_weight_list = []\n avg_value = (self.max_value + self.min_value) / 2\n normalized_range = self.max_value - self.min_value\n for i in range(self.ngs_vert_count):\n vertex_weight = self.ngs_weight_list[i]\n if not self.max_value > vertex_weight > self.min_value:\n new_weight_list.append(vertex_weight)\n continue\n dist_value = vertex_weight - avg_value\n modifier = norm.cdf(dist_value, loc=0, scale=(0.1 * normalized_range)) - vertex_weight\n contrast_weight = vertex_weight + modifier * intensity\n contrast_weight = max(self.min_value, min(contrast_weight, self.max_value))\n new_weight_list.append(contrast_weight)\n self.mll.setInfluenceWeights(self.ngs_layer_id, self.ngs_influence, new_weight_list)\n\n\nclass PaintExtras(object):\n \"\"\" adds a custom Formlayout inside the Paint Tab of the ngSkinTools UI \"\"\"\n\n def __init__(self):\n self.mll = MllInterface()\n self.ng_color_set = \"\"\n self.check_color_set = 'checkSetBlue'\n self.mo = MapOperations()\n self.radio_text = 'Mode:'\n self.conceal = 'Conceal'\n self.spread = 'Spread'\n self.contrast = 'Contrast'\n self.gain = \"Gain\"\n self.volume = \"Volume EQ\"\n self.defaultOp = 'Conceal'\n self.select_mode = True\n self.intensityField = 'Intensity'\n self.defaultVal = 1\n self.shrinkButton = 'Shrink Map'\n self.growButton = 'Grow Map'\n self.floodButton = 'Quick Flood'\n self.exitButton = 'Exit Tool'\n self.matchButton = 'Match Brush'\n\n self.dividerEQ = \"dividerEQ\"\n self.editMenuEQ = 'Vertex Equalizer Tool'\n\n self.extra_check = \"Use Extra Brushes\"\n self.extra_frame = \"Extra Tools\"\n self.radio_form = \"radio_form\"\n self.intensity_label = \"Intensity:\"\n self.volume_label = \"Volume:\"\n self.intensity_row = \"intensity_row\"\n self.volume_row = \"threshold_row\"\n self.extra_field = \"extra_field\"\n self.extra_slider = \"extra_slider\"\n self.volume_field = \"volume_field\"\n self.volume_slider = \"volume_slider\"\n self.mode_collection = \"mode_collection\"\n self.button_form = \"button_form\"\n # self.brush_display_check = \"Draw Brush while painting\"\n # self.default_brush_display = cmds.artUserPaintCtx(outwhilepaint=True, q=True)\n\n self.ui_paths = {\n \"paint_tab\": \"MayaWindow|horizontalSplit|tabLayout|formLayout|scrollLayout|columnLayout\",\n \"paint_buttons\": \"MayaWindow|horizontalSplit|tabLayout|formLayout|formLayout|button\",\n \"mode_radio\": \"MayaWindow|horizontalSplit|tabLayout|formLayout|scrollLayout|columnLayout|frameLayout\"\n \"|columnLayout|formLayout|rowColumnLayout|radioButton\",\n \"mode_layout\": \"MayaWindow|horizontalSplit|tabLayout|formLayout|scrollLayout|columnLayout\"\n \"|frameLayout|columnLayout|formLayout|rowColumnLayout\",\n \"intensity_slider\": \"MayaWindow|horizontalSplit|tabLayout|formLayout|scrollLayout|columnLayout|frameLayout\"\n \"|columnLayout|formLayout|rowLayout|floatSlider\",\n \"slider_rows\": \"MayaWindow|horizontalSplit|tabLayout|formLayout|scrollLayout|columnLayout|frameLayout\"\n \"|columnLayout|formLayout|rowLayout\",\n \"checkboxes\": \"MayaWindow|horizontalSplit|tabLayout|formLayout|scrollLayout|columnLayout|frameLayout\"\n \"|columnLayout|formLayout|columnLayout|checkBox\",\n \"EA_menu\": \"MayaWindow|horizontalSplit|formLayout|menuBarLayout|menu\"\n }\n\n self.ng_radio_layout = get_target_control(self.ui_paths[\"mode_layout\"])\n self.ng_radio_buttons = get_target_control(self.ui_paths[\"mode_radio\"])\n self.ng_intensity = get_target_control(self.ui_paths[\"intensity_slider\"])\n self.ng_checkboxes = get_target_control(self.ui_paths[\"checkboxes\"])\n self.ng_slider_rows = get_target_control(self.ui_paths[\"slider_rows\"])\n self.ng_paint_buttons = get_target_control(self.ui_paths[\"paint_buttons\"])\n self.ng_menu = get_target_control(self.ui_paths[\"EA_menu\"])\n\n def paint_tool_setup(self, *args):\n \"\"\" changes the initial settings for the paint script tool \"\"\"\n cmds.rowColumnLayout(self.ng_radio_layout[0], e=True, enable=False)\n cmds.checkBox(self.ng_checkboxes[0], e=True, enable=False)\n cmds.checkBox(self.ng_checkboxes[1], e=True, enable=False)\n cmds.rowLayout(self.ng_slider_rows[0], e=True, enable=False)\n cmds.formLayout(self.radio_form, e=True, enable=True)\n cmds.button(self.floodButton, e=True, enable=True)\n cmds.rowLayout(self.intensity_row, e=True, enable=True)\n\n cmds.artUserPaintCtx(\n \"ngSkinToolsLayerPaintCtx\",\n e=True,\n initializeCmd=\"ngSkinAlexUtilInitialize\",\n finalizeCmd=\"ngSkinAlexUtilFinalize\",\n )\n self.intensity()\n self.match_volume()\n self.paint_mode()\n\n def paint_mode(self, *args):\n \"\"\" replaces the set value MEL script in the paint script tool \"\"\"\n paint_mode = cmds.radioCollection(self.mode_collection, q=True, select=True)\n cmds.rowLayout(self.volume_row, e=True, enable=False)\n cmds.button(self.floodButton, e=True, enable=True)\n if paint_mode == \"conceal_radio\":\n cmds.artUserPaintCtx(\"ngSkinToolsLayerPaintCtx\", e=True, setValueCommand=\"ngSkinAlexUtilconceal\")\n if paint_mode == \"spread_radio\":\n cmds.artUserPaintCtx(\"ngSkinToolsLayerPaintCtx\", e=True, setValueCommand=\"ngSkinAlexUtilSpread\")\n if paint_mode == \"contrast_radio\":\n cmds.artUserPaintCtx(\"ngSkinToolsLayerPaintCtx\", e=True, setValueCommand=\"ngSkinAlexUtilContrast\")\n if paint_mode == \"gain_radio\":\n cmds.artUserPaintCtx(\"ngSkinToolsLayerPaintCtx\", e=True, setValueCommand=\"ngSkinAlexUtilGain\")\n if paint_mode == \"volume_radio\":\n cmds.artUserPaintCtx(\"ngSkinToolsLayerPaintCtx\", e=True, setValueCommand=\"ngSkinAlexUtilVolEq\")\n cmds.rowLayout(self.volume_row, e=True, enable=True)\n cmds.button(self.floodButton, e=True, enable=False)\n\n def intensity(self, *args):\n \"\"\" sets the value slider of the paint script tool to this amount \"\"\"\n intensity = cmds.floatSlider(self.extra_slider, q=True, value=True)\n cmds.artUserPaintCtx(\"ngSkinToolsLayerPaintCtx\", e=True, value=intensity)\n\n def flood(self, *args):\n \"\"\" applies selected operation to the entire mesh \"\"\"\n intensity = cmds.floatSlider(self.extra_slider, q=True, value=True)\n paint_mode = cmds.radioCollection(self.mode_collection, q=True, select=True)\n if paint_mode == \"conceal_radio\":\n self.mo.conceal_map(intensity)\n if paint_mode == \"spread_radio\":\n self.mo.spread_map(intensity)\n if paint_mode == \"contrast_radio\":\n self.mo.contrast_map(intensity)\n if paint_mode == \"gain_radio\":\n self.mo.gain_map(intensity)\n\n def grow(self, *args):\n \"\"\" starts the grow map operation \"\"\"\n intensity = cmds.floatSlider(self.ng_intensity[0], q=True, value=True)\n if cmds.checkBox(self.extra_check, q=True, value=True):\n intensity = cmds.floatSlider(self.extra_slider, q=True, value=True)\n self.mo.grow_map(intensity)\n\n def shrink(self, *args):\n \"\"\" starts the shrink map operation \"\"\"\n intensity = cmds.floatSlider(self.ng_intensity[0], q=True, value=True)\n if cmds.checkBox(self.extra_check, q=True, value=True):\n intensity = cmds.floatSlider(self.extra_slider, q=True, value=True)\n self.mo.shrink_map(intensity)\n\n def update_float_field(self, *args):\n float_intensity = cmds.floatSlider(self.extra_slider, q=True, value=True)\n volume_intensity = cmds.floatSlider(self.volume_slider, q=True, value=True)\n cmds.floatField(self.extra_field, e=True, value=float_intensity)\n cmds.floatField(self.volume_field, e=True, value=volume_intensity)\n\n def update_float_slider(self, *args):\n field_intensity = cmds.floatField(self.extra_field, q=True, value=True)\n volume_intensity = cmds.floatField(self.volume_field, q=True, value=True)\n cmds.floatSlider(self.extra_slider, e=True, value=field_intensity)\n cmds.floatSlider(self.volume_slider, e=True, value=volume_intensity)\n\n def match_volume(self, *args):\n radius = cmds.artUserPaintCtx(\"ngSkinToolsLayerPaintCtx\", q=True, radius=True)\n cmds.floatField(self.volume_field, e=True, value=radius)\n cmds.floatSlider(self.volume_slider, e=True, value=radius)\n\n def insert_menu(self):\n \"\"\" adds the equalizer tool to the ngSkin Tools menu bar \"\"\"\n if cmds.menuItem('equalizer_item', exists=True):\n cmds.deleteUI('equalizer_item', menuItem=True)\n cmds.deleteUI('divider_item', menuItem=True)\n self.dividerEQ = cmds.menuItem(\n 'divider_item',\n parent=self.ng_menu[-1],\n divider=True\n )\n self.editMenuEQ = cmds.menuItem(\n 'equalizer_item',\n parent=self.ng_menu[-1],\n label=self.editMenuEQ,\n command=eq.open_equalizer\n )\n\n def insert_ui(self):\n \"\"\" adds the custom brush modes to an existing ngSkinTools UI \"\"\"\n if cmds.frameLayout(\"extra_brushes\", exists=True):\n cmds.deleteUI(\"extra_brushes\")\n parent_layout = get_target_control(self.ui_paths[\"paint_tab\"])\n self.extra_frame = cmds.frameLayout(\n \"extra_brushes\",\n label=self.extra_frame,\n collapsable=True,\n parent=parent_layout[0]\n )\n cmds.columnLayout(adjustableColumn=True)\n cmds.separator(style='none', height=5)\n cmds.rowLayout(\n numberOfColumns=1,\n adjustableColumn=1,\n columnAlign=(1, 'right'),\n )\n self.extra_check = cmds.checkBox(\n label=self.extra_check,\n value=False,\n onCommand=self.paint_tool_setup,\n offCommand=self.exit\n )\n cmds.setParent('..')\n self.radio_form = cmds.formLayout(numberOfDivisions=100)\n column = cmds.columnLayout(adjustableColumn=True)\n cmds.text(label=self.radio_text)\n cmds.setParent('..')\n mode_row = cmds.rowColumnLayout(numberOfColumns=2, columnWidth=[(1, 100), (2, 100)])\n self.mode_collection = cmds.radioCollection()\n cmds.radioButton(\"conceal_radio\", label=self.conceal, onCommand=self.paint_mode, select=True)\n cmds.radioButton(\"spread_radio\", label=self.spread, onCommand=self.paint_mode)\n cmds.radioButton(\"contrast_radio\", label=self.contrast, onCommand=self.paint_mode)\n cmds.radioButton(\"gain_radio\", label=self.gain, onCommand=self.paint_mode)\n cmds.radioButton(\"volume_radio\", label=self.volume, onCommand=self.paint_mode)\n cmds.formLayout(\n self.radio_form,\n edit=True,\n enable=False,\n attachForm=[\n (column, 'top', 15),\n (column, 'left', 85),\n (mode_row, 'top', 5),\n (mode_row, 'left', 125),\n ]\n )\n cmds.setParent('..')\n cmds.setParent('..')\n self.intensity_row = cmds.rowLayout(\n numberOfColumns=3,\n adjustableColumn=3,\n columnAlign=(1, 'right'),\n columnWidth=[(1, 118), (2, 80), (3, 100)],\n columnOffset3=(0, 5, 0),\n columnAttach3=('both', 'left', 'left'),\n enable=False\n )\n cmds.text(label=self.intensity_label)\n self.extra_field = cmds.floatField()\n self.extra_slider = cmds.floatSlider()\n cmds.floatField(\n self.extra_field,\n e=True,\n width=80,\n minValue=0,\n maxValue=1,\n step=0.001,\n value=1,\n changeCommand=self.update_float_slider\n )\n cmds.floatSlider(\n self.extra_slider,\n e=True,\n minValue=0,\n maxValue=1,\n step=0.001,\n value=1,\n dragCommand=self.update_float_field,\n changeCommand=self.intensity\n )\n cmds.setParent('..')\n self.volume_row = cmds.rowLayout(\n numberOfColumns=4,\n adjustableColumn=4,\n columnAlign=(2, 'right'),\n columnWidth=[(1, 75), (2, 41), (3, 80), (4, 100)],\n columnOffset4=(4, 0, 5, 0),\n columnAttach4=('both', 'both', 'left', 'left'),\n enable=False\n )\n self.matchButton = cmds.button(\n label=self.matchButton,\n width=60,\n align='left',\n command=self.match_volume,\n )\n cmds.text(label=self.volume_label)\n self.volume_field = cmds.floatField(self.volume_field)\n self.volume_slider = cmds.floatSlider(self.volume_slider)\n cmds.floatField(\n self.volume_field,\n width=80,\n minValue=0,\n step=0.001,\n value=1,\n e=True,\n changeCommand=self.update_float_slider\n )\n cmds.floatSlider(\n self.volume_slider,\n minValue=0,\n step=0.001,\n value=1,\n e=True,\n dragCommand=self.update_float_field,\n )\n cmds.setParent('..')\n self.button_form = cmds.formLayout(numberOfDivisions=100)\n self.shrinkButton = cmds.button(\n label=self.shrinkButton,\n width=155,\n align='left',\n command=self.shrink\n )\n self.growButton = cmds.button(\n label=self.growButton,\n width=155,\n align='right',\n command=self.grow\n )\n self.floodButton = cmds.button(\n label=self.floodButton,\n width=315,\n command=self.flood,\n enable=False\n )\n cmds.formLayout(\n self.button_form,\n edit=True,\n enable=True,\n attachForm=[\n (self.shrinkButton, 'top', 35),\n (self.shrinkButton, 'left', 5),\n (self.growButton, 'top', 35),\n (self.growButton, 'left', 165),\n (self.floodButton, 'top', 5),\n (self.floodButton, 'left', 5),\n ]\n )\n cmds.setParent('..')\n mel.eval('source \"ngSkinAlexUtilPaint.mel\"')\n \"\"\"\n self.brush_display_check = cmds.checkBox(\n label=self.brush_display_check,\n parent=\n )\n \"\"\"\n\n def exit(self, *args):\n \"\"\" exits tool and resets it to the ngSkinTools settings \"\"\"\n init_mel = Utils.createMelProcedure(ngLayerPaintCtxInitialize, [('string', 'mesh')], returnType='string')\n cmds.artUserPaintCtx(\n \"ngSkinToolsLayerPaintCtx\",\n e=True,\n setValueCommand=\"ngLayerPaintCtxSetValue\",\n initializeCmd=init_mel,\n finalizeCmd=\"ngLayerPaintCtxFinalize\",\n value=self.defaultVal\n )\n cmds.rowColumnLayout(self.ng_radio_layout[0], e=True, enable=True)\n cmds.checkBox(self.ng_checkboxes[0], e=True, enable=True)\n cmds.checkBox(self.ng_checkboxes[1], e=True, enable=True)\n cmds.rowLayout(self.ng_slider_rows[0], e=True, enable=True)\n cmds.formLayout(self.radio_form, e=True, enable=False)\n cmds.button(self.floodButton, e=True, enable=False)\n cmds.rowLayout(self.intensity_row, e=True, enable=False)\n cmds.rowLayout(self.volume_row, e=True, enable=False)\n ng_paint_mode = [\n (self.ng_radio_buttons.index(i) + 1)\n for i in self.ng_radio_buttons\n if cmds.radioButton(i, q=True, select=True) is True\n ]\n ng_intensity_value = cmds.floatSlider(self.ng_intensity[0], q=True, value=True)\n cmds.ngSkinLayer(paintOperation=ng_paint_mode[0], paintIntensity=ng_intensity_value)\n\n\ndef insert_ui_frame(*args):\n PE = PaintExtras()\n PE.insert_ui()\n PE.insert_menu()\n\n\ndef delete_ui_frame(*args):\n cmds.deleteUI('equalizer_item', menuItem=True)\n cmds.deleteUI('divider_item', menuItem=True)\n cmds.deleteUI(\"extra_brushes\")\n" }, { "alpha_fraction": 0.7922077775001526, "alphanum_fraction": 0.7922077775001526, "avg_line_length": 24.66666603088379, "blob_id": "0e1a5d160e20395cc1e2067f0d4f69176863db4a", "content_id": "fb5d08ee8bff186bba2c57d689582844f18b0a02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 77, "license_type": "no_license", "max_line_length": 36, "num_lines": 3, "path": "/plug_ngSkinTools/__init__.py", "repo_name": "AngryBaer/abMaya", "src_encoding": "UTF-8", "text": "# ngSkinTools extension package init\nfrom .python import ui, api\nreload(api)\n" }, { "alpha_fraction": 0.8098360896110535, "alphanum_fraction": 0.8098360896110535, "avg_line_length": 37.125, "blob_id": "4f18c547a9b425f797b5bb22bcf0c32c1da65cc8", "content_id": "f767661c192c950cd2a6c9266660bb4e9bc1517f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 305, "license_type": "no_license", "max_line_length": 123, "num_lines": 8, "path": "/README.md", "repo_name": "AngryBaer/abMaya", "src_encoding": "UTF-8", "text": "# abMaya\nCollection of tools for the Autodesk Maya DCC package.\n\n## context\nContext Managers used to safely make temptorary changes to an open Maya scene.\n\n## ngSkinTools_extension\nAdditional tools, brushes and functions for the ngSkinTools plugin used for skin weight painting in the rigging department.\n" }, { "alpha_fraction": 0.8684210777282715, "alphanum_fraction": 0.8684210777282715, "avg_line_length": 38, "blob_id": "5ba383ab1c84a32eabbb56d552469c9376bf7252", "content_id": "27215867bedde0a7a296d270637587e70e87ce36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 38, "license_type": "no_license", "max_line_length": 38, "num_lines": 1, "path": "/libContext/__init__.py", "repo_name": "AngryBaer/abMaya", "src_encoding": "UTF-8", "text": "from .lib.scene import BypassSceneName" }, { "alpha_fraction": 0.42800676822662354, "alphanum_fraction": 0.4376058578491211, "avg_line_length": 35.875, "blob_id": "31a3a516b57393a41a19eb33b4daf5d171b3cc23", "content_id": "c95ef2ea369a0e8e20df387b6a3daecf6d7ec35e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1771, "license_type": "no_license", "max_line_length": 99, "num_lines": 48, "path": "/plug_ngSkinTools/python/core/adjust.py", "repo_name": "AngryBaer/abMaya", "src_encoding": "UTF-8", "text": "\n# IMPORTS --------------------------------------------------------------------------------------- #\nfrom math import pow, sqrt\n# ----------------------------------------------------------------------------------------------- #\n\n\n# ----------------------------------------------------------------------------------------------- #\ndef contrast(value, weightList, vtxMin, vtxMax):\n \"\"\"\n True contrast operation that preserves minimum and maximum values.\n Applies a curve to the given list of weight values that increases their distance to the\n average value.\n\n :param value: intensity value of the operation\n - float 0.0 - 1.0\n :param weightList: current weight values of all vertices\n - list [float, float, ...]\n :param vtxMin: minimum weight values of all vertices\n - float 0.0 - 1.0\n :param vtxMax: maximum weight values of all vertices\n - float 0.0 - 1.0\n\n :return result: modified weight values\n - list [float, float, ...]\n \"\"\"\n avg = (vtxMax + vtxMin) / 2.0\n norm_range = vtxMax - vtxMin\n\n applied_list = []\n for weight in weightList:\n if not vtxMax > weight > vtxMin:\n applied_list.append(weight)\n continue\n\n difference = weight - avg\n\n if difference == 0:\n result = weight\n\n if difference > 0:\n result = min(weight + ((vtxMax - weight) * value), vtxMax)\n\n if difference < 0:\n result = max(weight - ((weight - vtxMin) * value), vtxMin)\n\n applied_list.append(result)\n\n return applied_list\n# ----------------------------------------------------------------------------------------------- #\n" }, { "alpha_fraction": 0.8421052694320679, "alphanum_fraction": 0.8421052694320679, "avg_line_length": 27.5, "blob_id": "ed4808d4fb7606d187aea291506253077424b578", "content_id": "6c8ccbe826b4f1901729505a641d9e84db91d5b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 57, "license_type": "no_license", "max_line_length": 37, "num_lines": 2, "path": "/libContext/README.md", "repo_name": "AngryBaer/abMaya", "src_encoding": "UTF-8", "text": "# Context Managers\nCollection of Python Context Managers\n" }, { "alpha_fraction": 0.8235294222831726, "alphanum_fraction": 0.8235294222831726, "avg_line_length": 33, "blob_id": "c147b722b5bd3dbcfa50c3478a2984833a5724c8", "content_id": "b02e53d0ae567968369a20125b21aa1b080f9a0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 34, "license_type": "no_license", "max_line_length": 33, "num_lines": 1, "path": "/plug_ngSkinTools/python/__init__.py", "repo_name": "AngryBaer/abMaya", "src_encoding": "UTF-8", "text": "# ngSkinTools python package init\n" }, { "alpha_fraction": 0.4665592312812805, "alphanum_fraction": 0.467365026473999, "avg_line_length": 30.846153259277344, "blob_id": "ee7a29237ee100e9fb1a7dc2bbf8937a6351c29f", "content_id": "f24a72e2d23421a37cb55a08e3248e1b6fa1049f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1241, "license_type": "no_license", "max_line_length": 99, "num_lines": 39, "path": "/libModel/lib/component.py", "repo_name": "AngryBaer/abMaya", "src_encoding": "UTF-8", "text": "\"\"\"\n Component level operations\n\"\"\"\n\n\n# IMPORTS --------------------------------------------------------------------------------------- #\nfrom maya import cmds\nfrom maya.api import OpenMaya\n# ----------------------------------------------------------------------------------------------- #\n\n\n# VERTEX ---------------------------------------------------------------------------------------- #\ndef connected_vertices(vertex):\n \"\"\"\n find vertices that are connected by edge with the given vertex.\n\n :param vertex: MObject or dagPath of the given vertex\n - MObject(component)\n - \"surface.vtx[id]\"\n\n :return vertices: MayaIntArray of vertex IDs\n - MayaIntArray[int, int, ...]\n \"\"\"\n selectionList = OpenMaya.MSelectionList()\n selectionList.add(vertex)\n meshObject, vertexComponent = selectionList.getComponent(0)\n\n vtxIterator = OpenMaya.MItMeshVertex(meshObject, vertexComponent)\n return vtxIterator.getConnectedVertices()\n\n\ndef connected_edges(vertex):\n raise NotImplementedError\n\n\ndef connected_faces(vertex):\n raise NotImplementedError\n\n# ----------------------------------------------------------------------------------------------- #" } ]
16
FUJI-W/lightAR
https://github.com/FUJI-W/lightAR
644b9edc60c3c8e713eec371ecbde9d79b22109c
97061ca029499d7999505ab6ece2accd199fd8cb
40a6653a7ada9fb3b6a7f603277adb9a9b0511ec
refs/heads/main
2023-05-25T08:05:12.669845
2021-06-12T15:12:22
2021-06-12T15:12:22
376,242,983
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5104438662528992, "alphanum_fraction": 0.5413402915000916, "avg_line_length": 28.088607788085938, "blob_id": "f97d038d460910733f06b2777324c8b0e09c903c", "content_id": "fff4315178c92613693b36c281e368fa0184b9b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2298, "license_type": "no_license", "max_line_length": 87, "num_lines": 79, "path": "/tools.py", "repo_name": "FUJI-W/lightAR", "src_encoding": "UTF-8", "text": "import os\nimport time\nfrom functools import wraps\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\n\n\ndef timeit(logfile='out.log'):\n def decorate(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n _t0 = time.time()\n res = func(*args, **kwargs)\n _t1 = time.time()\n with open(logfile, 'a') as opened_file:\n opened_file.write(\"%s: %s seconds\\n\" % (func.__name__, str(_t1 - _t0)))\n return res\n\n return wrapper\n\n return decorate\n\n\ndef chartit(logfile='out.log'):\n with open(logfile, 'r') as f:\n lines = [[i for i in line.split()] for line in f.readlines()]\n words = dict()\n for _l in lines:\n if _l[0] not in words.keys():\n words[_l[0].strip(':')] = []\n words[_l[0].strip(':')].append(float(_l[1]))\n means = dict()\n for _w in words:\n means[_w] = np.mean(np.array(words.get(_w)))\n x = list(means.values())\n y = list(means.keys())\n x.reverse()\n y.reverse()\n\n plt.axes([0.125, 0.1, 0.8, 0.8])\n plt.barh(range(len(x)), x, tick_label=y, facecolor='#9999ff', edgecolor='white')\n plt.xlabel('time/s')\n plt.title('Average Running Time of Each Function')\n for a, b in enumerate(x):\n plt.text(b + 0.1, a, '%.6s s' % b, va='center')\n\n plt.axes([0.65, 0.5, 0.25, 0.25])\n p_means = dict()\n for _m in means:\n if means.get(_m) > 0.1:\n p_means[_m] = means.get(_m)\n else:\n if 'others' not in means:\n p_means['others'] = 0.0\n p_means['others'] = p_means['others'] + means.get(_m)\n\n px = np.asarray(list(p_means.values()))\n px = px / np.sum(px)\n py = list(p_means.keys())\n\n plt.pie(px, labels=py,\n autopct=lambda _x: ('%.2f%%' % _x) if _x > 0.001 else '<0.01%',\n pctdistance=0.5)\n plt.gcf().gca().add_artist(plt.Circle((0, 0), 0.7, color='white'))\n\n fig = plt.gcf()\n fig.set_size_inches((16, 9), forward=False)\n fig.savefig(os.path.join(os.path.dirname(logfile), 'out.log.png'), dpi=120)\n\n # plt.show()\n return fig\n\n\ndef showit(rgbe_path='scene.rgbe'):\n _hdr1 = cv2.imread(rgbe_path, cv2.IMREAD_ANYDEPTH)\n cv2.imshow(\"\", _hdr1.astype(np.float64))\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n" }, { "alpha_fraction": 0.6760563254356384, "alphanum_fraction": 0.6760563254356384, "avg_line_length": 16.75, "blob_id": "81c09b33ed51d910a841ee2bc6a49fda411591e9", "content_id": "b273ed678570375f1100d6b6008d093b36951e3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 213, "license_type": "no_license", "max_line_length": 67, "num_lines": 12, "path": "/server.py", "repo_name": "FUJI-W/lightAR", "src_encoding": "UTF-8", "text": "import dash\n\napp = dash.Dash(\n __name__,\n suppress_callback_exceptions=True,\n external_stylesheets=['css/bootstrap.min.css', 'css/style.css']\n)\n\n# set web title\napp.title = 'ARLight'\n\nserver = app.server\n" }, { "alpha_fraction": 0.5264292359352112, "alphanum_fraction": 0.5440487861633301, "avg_line_length": 29.226966857910156, "blob_id": "229c55ccac463f230cd3f1a6b34f77acb15fb38f", "content_id": "28e8423fd0d15a11762c71feaf37949ccbec79dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13451, "license_type": "no_license", "max_line_length": 116, "num_lines": 445, "path": "/views/index_callbks.py", "repo_name": "FUJI-W/lightAR", "src_encoding": "UTF-8", "text": "import dash_core_components as dcc\nimport dash_uploader as du\nimport dash_bootstrap_components as dbc\nfrom dash.dependencies import Input, Output, State\nfrom server import app, server\n\nimport flask\nimport plotly.express as px\nimport numpy as np\nimport plotly.graph_objs as go\nimport pandas as pd\nimport os.path as osp\n\nfrom paint import *\n\ndu.configure_upload(app, folder='data')\n\n\ndef get_color_picker_figure():\n color_fig = px.imshow(Image.open(os.path.join(PATH_APP, \"assets\", 'color-picker.png')))\n color_fig.update_layout(\n # autosize=True,\n height=200,\n margin=dict(l=5, r=10, b=0, t=0, pad=0),\n paper_bgcolor='rgba(0,0,0,0)',\n plot_bgcolor='rgba(0,0,0,0)',\n showlegend=False,\n xaxis={\n # 'range': [0.2, 1],\n 'showgrid': False, # thin lines in the background\n 'zeroline': False, # thick line at x=0\n 'visible': False, # numbers below\n },\n yaxis={\n # 'range': [0.2, 1],\n 'showgrid': False, # thin lines in the background\n 'zeroline': False, # thick line at x=0\n 'visible': False, # numbers below\n },\n )\n return color_fig\n\n\ndef get_graph_figure(_img):\n fig = px.imshow(_img)\n fig.update_layout(\n autosize=True,\n # height=800,\n margin=dict(l=0, r=0, b=0, t=0, pad=0),\n paper_bgcolor='#f9f9f8',\n plot_bgcolor='#f9f9f8',\n showlegend=False,\n xaxis={\n # 'range': [0.2, 1],\n 'showgrid': False, # thin lines in the background\n 'zeroline': False, # thick line at x=0\n 'visible': False, # numbers below\n },\n yaxis={\n # 'range': [0.2, 1],\n 'showgrid': False, # thin lines in the background\n 'zeroline': False, # thick line at x=0\n 'visible': False, # numbers below\n },\n )\n return fig\n\n\ndef get_dict_from_log(logfile='out.log'):\n with open(logfile, 'r') as f:\n lines = [[i for i in line.split()] for line in f.readlines()]\n words = dict()\n for _l in lines:\n if _l[0] not in words.keys():\n words[_l[0].strip(':')] = []\n words[_l[0].strip(':')].append(float(_l[1]))\n means = dict()\n for _w in words:\n means[_w] = np.mean(np.array(words.get(_w)))\n return means\n\n\ndef get_chart_figure(logfile='out.log'):\n means = get_dict_from_log(logfile)\n y = list(means.values())\n x = list(means.keys())\n\n trace1 = go.Bar(\n x=x,\n y=y,\n name=\"Total Process\"\n )\n\n layout = go.Layout(\n title='Total Process',\n )\n\n return go.Figure(\n data=[trace1],\n layout=layout\n )\n\n\ndef get_sunburst_figure():\n dict_est = get_dict_from_log(osp.join(PATH_OUT, 'out.est.log'))\n dict_gen = get_dict_from_log(osp.join(PATH_OUT, 'out.gen.log'))\n dict_all = get_dict_from_log(osp.join(PATH_OUT, 'out.log'))\n\n methods = list()\n modules = list()\n data = list()\n\n for k in dict_est:\n methods.append(k)\n modules.append('estimate_scene')\n data.append(dict_est[k])\n\n for k in dict_gen:\n methods.append(k)\n modules.append('info_process')\n data.append(dict_gen[k])\n\n for k in dict_all:\n if k == 'estimate_scene' or k == 'render_img' or k == 'generate_render_xml':\n continue\n methods.append(k)\n modules.append('info_process')\n data.append(dict_all[k])\n\n methods.append('render_img')\n modules.append('render_img')\n data.append(dict_all['render_img'])\n\n df = pd.DataFrame(dict(methods=methods, modules=modules, cost_time=data))\n\n fig = px.sunburst(df, path=['modules', 'methods'], values='cost_time', color='methods',\n color_discrete_sequence=px.colors.sequential.haline_r)\n fig.update_traces(hovertemplate='%{label}<br>' + 'cost time: %{value} ms', textinfo=\"label + percent entry\")\n\n fig.update_layout(\n autosize=True,\n # height=400,\n margin=dict(l=0, r=0, b=30, t=30, pad=0),\n paper_bgcolor='#f9f9f8',\n plot_bgcolor='#f9f9f8',\n # showlegend=False,\n )\n\n return fig\n\n\ndef make_tooltip(_label, _target, _placement='top'):\n return dbc.Tooltip(\n _label, target=_target, placement=_placement,\n hide_arrow=True,\n style={\"background-color\": 'rgba(75, 144, 144, 0.2)', \"color\": 'rgba(75, 144, 144, 1)'}\n )\n\n\[email protected](\n Output('knob-obj-size-output', 'value'),\n [Input('knob-obj-size', 'value')]\n)\ndef update_knob_obj_size_output(value):\n value = int(value)\n if value >= 100:\n value = 99\n return str(value).zfill(2)\n\n\[email protected](\n Output('knob-obj-roughness-output', 'value'),\n [Input('knob-obj-roughness', 'value')]\n)\ndef update_knob_obj_size_output(value):\n value = int(value)\n if value >= 100:\n value = 99\n return str(value).zfill(2)\n\n\[email protected](\n [\n Output(\"color-R-output\", \"value\"),\n Output(\"color-G-output\", \"value\"),\n Output(\"color-B-output\", \"value\")\n ],\n [Input(\"color-picker\", \"clickData\")],\n prevent_initial_call=True,\n)\ndef update_color_output(click_data):\n if click_data:\n return str(click_data['points'][0]['color']['0']).zfill(3), \\\n str(click_data['points'][0]['color']['1']).zfill(3), \\\n str(click_data['points'][0]['color']['2']).zfill(3)\n else:\n return '255', '255', '255'\n\n\[email protected](\n Output(\"html-sphere-block-color\", \"style\"),\n [Input(\"html-a-sphere\", \"n_clicks\")]\n)\ndef on_sphere_click(n):\n style = dict()\n if n is None or (n % 2) == 0:\n return style\n else:\n style['box-shadow'] = '2px 2px 2px lightgrey'\n style['background-color'] = '#4b9072'\n return style\n\n\[email protected](\n Output(\"html-bunny-block-color\", \"style\"),\n [Input(\"html-a-bunny\", \"n_clicks\"),\n Input(\"html-a-sphere\", \"n_clicks\")]\n)\ndef on_bunny_click(n_bunny, n_sphere):\n style = dict()\n if n_bunny is None and n_sphere is None:\n style['box-shadow'] = '2px 2px 2px lightgrey'\n style['background-color'] = '#4b9072'\n return style\n elif n_bunny is None or (n_bunny % 2) == 0:\n return style\n else:\n style['box-shadow'] = '2px 2px 2px lightgrey'\n style['background-color'] = '#4b9072'\n return style\n\n\[email protected](\n [Output(\"axios-x-output\", \"value\"), Output(\"axios-y-output\", \"value\")],\n [Input(\"graph-picture\", \"clickData\")],\n prevent_initial_call=True,\n)\ndef update_axios_output(click_data):\n if click_data:\n return str(click_data['points'][0]['x']).zfill(4), str(click_data['points'][0]['y']).zfill(4)\n else:\n return '0000', '0000'\n\n\[email protected](\n Output(\"div-graph-picture\", \"children\"),\n id='uploader',\n)\ndef update_graph_picture(filenames):\n img = Image.open(os.path.join(PATH_APP, filenames[0]))\n fig = get_graph_figure(img)\n return [\n dcc.Graph(\n id='graph-picture',\n figure=fig,\n config={\n # 'displayModeBar': True,\n 'editable': False,\n 'scrollZoom': False,\n 'displaylogo': False,\n 'modeBarButtonsToRemove': ['zoom2d', 'pan2d', 'select2d', 'lasso2d', 'zoomIn2d', 'zoomOut2d',\n 'autoScale2d', 'resetScale2d',\n 'hoverClosestCartesian', 'hoverCompareCartesian',\n 'zoomInGeo', 'zoomOutGeo', 'resetGeo', 'hoverClosestGeo',\n 'hoverClosestGl2d', 'hoverClosestPie', 'toggleHover', 'resetViews',\n 'toggleSpikelines', 'resetViewMapbox']\n }\n )\n ]\n\n\[email protected](\n [Output(\"loading-estimate\", \"children\")],\n [Input(\"bt-start-estimate\", \"n_clicks\")],\n [\n State('uploader', 'fileNames'),\n State(\"powerbt-level-first\", \"on\"),\n State(\"powerbt-level-second\", \"on\"),\n State(\"powerbt-level-third\", \"on\"),\n ]\n)\ndef on_bt_start_estimate_click(\n n, img_name, bt_level1, bt_level2, bt_level3\n):\n if n is None:\n return [\"Start Estimate\"]\n\n inputImg = Image.open(osp.join(PATH_APP, 'data/inputs', img_name[0]))\n inputImg.save(osp.join(PATH_IN, 'im.png'))\n imgH, imgW = inputImg.height, inputImg.width\n\n mode = 1 if bt_level2 else 0\n mode = 2 if bt_level3 else mode\n estimate_scene(\n _root=ROOT, _photo=PHOTO, _h=imgH, _w=imgW, _mode=mode\n )\n return [\"Estimate Done\"]\n\n\nN = 0\nCLICK_TIME = 0\nX_OLD = 0\nY_OLD = 0\n\n\[email protected](\n [\n Output(\"loading-render\", \"children\"),\n Output(\"test-output\", 'children'),\n Output(\"graph-picture\", \"figure\")\n ],\n [\n Input(\"bt-start-render\", 'n_clicks')\n ],\n [\n State('knob-obj-size', 'value'),\n State('knob-obj-roughness', 'value'),\n State(\"color-picker\", \"clickData\"),\n State('uploader', 'fileNames'),\n State(\"html-a-sphere\", \"n_clicks\"),\n State(\"html-a-bunny\", \"n_clicks\"),\n State(\"powerbt-level-first\", \"on\"),\n State(\"powerbt-level-second\", \"on\"),\n State(\"powerbt-level-third\", \"on\"),\n State(\"graph-picture\", \"clickData\"),\n State(\"graph-picture\", \"figure\"),\n State(\"radios-system-mode\", \"value\")\n ]\n)\ndef on_bt_start_render_click(\n n, obj_size, obj_roughness, color_picker,\n img_name, obj_sphere, obj_bunny, bt_level1, bt_level2, bt_level3, img_click, img_fig, radio_value\n):\n global N, CLICK_TIME, X_OLD, Y_OLD\n\n if n is None or n == N:\n # return \"Render\", \"Not Clicked\", img_fig\n return \"Start Render\", \" \", img_fig\n\n N = n\n\n inputImg = Image.open(osp.join(PATH_IN, 'im.png'))\n imgH, imgW = inputImg.height, inputImg.width\n\n out = dict()\n out['obj_size'] = obj_size / 100 if obj_size else SCALE\n out['obj_roughness'] = obj_roughness / 100 if obj_roughness else ROUGHNESS\n out['color_picker'] = [color_picker['points'][0]['color']['0'], color_picker['points'][0]['color']['1'],\n color_picker['points'][0]['color']['2']] if color_picker else COLOR\n out['img_name'] = img_name[0]\n out['obj_sphere'] = obj_sphere % 2 if obj_sphere else 0\n out['obj_bunny'] = obj_bunny % 2 if obj_bunny else 1\n out['obj_name'] = 'sphere.obj' if out['obj_sphere'] else 'bunny.ply'\n out['bt_level'] = {'l0': bt_level1, 'l1': bt_level2, 'l2': bt_level3}\n out['img_click'] = {'x': img_click['points'][0]['x'],\n 'y': img_click['points'][0]['y']} if img_click else {'x': int(imgW / 2), 'y': int(imgH / 2)}\n\n if radio_value == 3:\n if CLICK_TIME % 2 == 0:\n CLICK_TIME += 1\n X_OLD, Y_OLD = out['img_click']['x'], out['img_click']['y']\n # return \"Push Again\", f\"{CLICK_TIME}, {X_OLD},{Y_OLD}\", img_fig\n return \"Push Again\", \"\", img_fig\n\n points = get_equal_dis_points(p1=[X_OLD, Y_OLD],\n p2=[out['img_click']['x'], out['img_click']['y']],\n step=1)\n\n for i in range(points.shape[0]):\n gui_object_insert(\n _img_h=imgH, _img_w=imgW,\n _obj_name=out['obj_name'],\n _obj_x=points[i][0],\n _obj_y=points[i][1],\n _offset=30 * imgW / 640 * out['obj_size'] / 0.2,\n _scale=out['obj_size'],\n _roughness=out['obj_roughness'],\n _diffuse=out['color_picker'],\n _index=i\n )\n\n convert_image_to_video(\n _num=points.shape[0],\n _root=PATH_OUT,\n _out_path=PATH_OUT,\n )\n\n # return \"Render Done\", f\"{CLICK_TIME}, {X_OLD}, {Y_OLD}, {out['img_click']}\", img_fig\n return \"Render Done\", \"\", img_fig\n\n else:\n gui_object_insert(\n _img_h=imgH, _img_w=imgW,\n _obj_name=out['obj_name'],\n _obj_x=out['img_click']['x'],\n _obj_y=out['img_click']['y'],\n _offset=30 * imgW / 640 * out['obj_size'] / 0.2,\n _scale=out['obj_size'],\n _roughness=out['obj_roughness'],\n _diffuse=out['color_picker']\n )\n\n if radio_value == 2:\n os.system('cp ' + osp.join(PATH_OUT, PHOTO) + ' ' + osp.join(PATH_IN, PHOTO))\n\n fig = get_graph_figure(Image.open(os.path.join(PATH_OUT, PHOTO)))\n\n # return \"Render\", str(out), fig\n return f\"Render Done\", \" \", fig\n\n\n# @app.callback(\n# [Output(\"loading-show\", \"children\"),\n# Output(\"graph-picture\", \"figure\")],\n# [Input(\"bt-start-show\", \"n_clicks\")],\n# [State(\"graph-picture\", \"figure\")]\n# )\n# def on_bt_start_show_click(n, fig):\n# if n is None:\n# return \"Show\", fig\n#\n# fig = get_graph_figure(Image.open(os.path.join(PATH_OUT, PHOTO)))\n# return \"Show\", fig\n\n\[email protected]('/inout/outputs/<path:path>')\ndef serve_static(path):\n return flask.send_from_directory(os.path.join(PATH_APP, 'inout/outputs/'), path)\n\n\[email protected](\n Output('movie-player', 'src'),\n Input('view-tabs', 'value')\n)\ndef update_videos(v):\n src = \"inout/outputs/video.webm\"\n return src\n\n\[email protected](\n Output('graph-sunburst', 'figure'),\n Input('sunburst-tabs', 'value')\n)\ndef update_sunburst_figure(v):\n return get_sunburst_figure()\n" }, { "alpha_fraction": 0.6617773771286011, "alphanum_fraction": 0.679033637046814, "avg_line_length": 32.14285659790039, "blob_id": "ef856a4aa1d8b04248d08b2c00a337e4d67a8166", "content_id": "957a95f4d90b91f3ac2f7e2ce767e7dcf7ff1766", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1159, "license_type": "no_license", "max_line_length": 85, "num_lines": 35, "path": "/setting.py", "repo_name": "FUJI-W/lightAR", "src_encoding": "UTF-8", "text": "import os\nimport os.path as osp\nimport pathlib\n\nFOV_X = 63.4149 # the field of view in _x axis\nCOLOR_R, COLOR_G, COLOR_B = 0.8, 0.8, 0.8 # the diffuse color of the inserted object\nCOLOR = [COLOR_R, COLOR_G, COLOR_B]\nROUGHNESS = 0.8 # the roughness value of the inserted object.\nSCALE = 0.2 # the size of the inserted object\nROOT = ''\nPHOTO = 'im.png'\nESTIMATE_MODE = 1 # 0; 1; 2\n\nRENDER = './render/build/bin/optixRenderer'\n\nPATH_APP = str(pathlib.Path(__file__).parent.resolve())\n\nPATH_IN = osp.join(PATH_APP, 'inout/inputs', ROOT)\nPATH_OUT = osp.join(PATH_APP, 'inout/outputs', ROOT)\n\nPATH_ENV_MAP = osp.join(PATH_IN, 'envmap.png.npz')\nPATH_DIFFUSE = osp.join(PATH_IN, 'albedo.png')\nPATH_ROUGH = osp.join(PATH_IN, 'rough.png')\nPATH_NORMAL = osp.join(PATH_IN, 'normal.npy')\n\nPATH_LOG = osp.join(PATH_OUT, 'out.log')\nPATH_LOG_EST = osp.join(PATH_OUT, 'out.est.log')\nPATH_LOG_GEN = osp.join(PATH_OUT, 'out.gen.log')\n\nif not os.path.exists(PATH_IN):\n os.makedirs(PATH_IN)\nif not os.path.exists(PATH_OUT):\n os.makedirs(PATH_OUT)\nif not os.path.exists(os.path.join(PATH_APP, 'data', 'inputs')):\n os.makedirs(os.path.join(PATH_APP, 'data', 'inputs'))" }, { "alpha_fraction": 0.5820333957672119, "alphanum_fraction": 0.604548454284668, "avg_line_length": 46.67509078979492, "blob_id": "b7925201b305e55c635224928fdec852217d83f8", "content_id": "de28a1fa6cdcc4e82c6dfb1fce1961781ec52a10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 39618, "license_type": "no_license", "max_line_length": 118, "num_lines": 831, "path": "/nets/test.py", "repo_name": "FUJI-W/lightAR", "src_encoding": "UTF-8", "text": "import numpy as np\nimport torch\nfrom torch.autograd import Variable\nimport argparse\nimport random\nimport os\nimport models\nimport utils\nimport glob\nimport os.path as osp\nimport cv2\nimport BilateralLayer as bs\nimport torch.nn.functional as F\nimport scipy.io as io\nimport utils\nimport time\nfrom tools import timeit\nfrom setting import *\n\n\n@timeit(PATH_LOG_EST)\ndef get_parser():\n parser = argparse.ArgumentParser()\n\n # Basic dirs setting\n parser.add_argument('--imPath', help='the path to real image')\n parser.add_argument('--outPath', help='the path to save the testing results')\n\n # Basic testing setting\n parser.add_argument('--mode', type=int, default=1, help='the mode of estimate including 0, 1, 2')\n\n parser.add_argument('--cuda', action='store_true', help='enables cuda')\n parser.add_argument('--deviceIds', type=int, nargs='+', default=[0], help='the gpus used for testing network')\n\n parser.add_argument('--level', type=int, default=2, help='the cascade level')\n parser.add_argument('--isLight', action='store_true', help='whether to predict lighting')\n parser.add_argument('--isBS', action='store_true', help='whether to use bilateral solver')\n\n parser.add_argument('--imHeight0', type=int, default=240, help='the height / width of the input image to network')\n parser.add_argument('--imWidth0', type=int, default=320, help='the height / width of the input image to network')\n parser.add_argument('--imHeight1', type=int, default=240, help='the height / width of the input image to network')\n parser.add_argument('--imWidth1', type=int, default=320, help='the height / width of the input image to network')\n\n parser.add_argument('--envRow', type=int, default=120, help='the height /width of the envmap predictions')\n parser.add_argument('--envCol', type=int, default=160, help='the height /width of the envmap predictions')\n parser.add_argument('--envHeight', type=int, default=8, help='the height /width of the envmap predictions')\n parser.add_argument('--envWidth', type=int, default=16, help='the height /width of the envmap predictions')\n\n parser.add_argument('--SGNum', type=int, default=12, help='the number of spherical Gaussian lobes')\n parser.add_argument('--offset', type=float, default=1, help='the offset when train the lighting network')\n\n parser.add_argument('--nepoch0', type=int, default=14, help='the number of epoch for testing')\n parser.add_argument('--nepochLight0', type=int, default=10, help='the number of epoch for testing')\n parser.add_argument('--nepochBS0', type=int, default=15, help='the number of epoch for bilateral solver')\n parser.add_argument('--niterBS0', type=int, default=1000, help='the number of iterations for testing')\n\n parser.add_argument('--nepoch1', type=int, default=7, help='the number of epoch for testing')\n parser.add_argument('--nepochLight1', type=int, default=10, help='the number of epoch for testing')\n parser.add_argument('--nepochBS1', type=int, default=8, help='the number of epoch for bilateral solver')\n parser.add_argument('--niterBS1', type=int, default=4500, help='the number of iterations for testing')\n\n # Models setting\n parser.add_argument('--experiment0', default=None, help='the path to the model of first cascade')\n parser.add_argument('--experimentLight0', default=None, help='the path to the model of first cascade')\n parser.add_argument('--experimentBS0', default=None, help='the path to the model of bilateral solver')\n parser.add_argument('--experiment1', default=None, help='the path to the model of second cascade')\n parser.add_argument('--experimentLight1', default=None, help='the path to the model of second cascade')\n parser.add_argument('--experimentBS1', default=None, help='the path to the model of second bilateral solver')\n\n return parser.parse_args()\n\n\n@timeit(PATH_LOG_EST)\ndef handle_parameters():\n # set im name and dir\n opt.imName = osp.basename(opt.imPath)\n opt.imDir = osp.dirname(opt.imPath)\n # set which GPU to use\n opt.gpuId = opt.deviceIds[0]\n # set Random seed\n opt.seed = 0\n print(\"Random Seed: \", opt.seed)\n random.seed(opt.seed)\n torch.manual_seed(opt.seed)\n # set batchSize\n opt.batchSize = 1\n if torch.cuda.is_available() and not opt.cuda:\n print(\"WARNING: You have a CUDA device, so you should probably run with --cuda\")\n # set paras which have not been init\n if opt.experiment0 is None:\n opt.experiment0 = 'check_cascade0_w%d_h%d' % (opt.imWidth0, opt.imHeight0)\n if opt.experiment1 is None:\n opt.experiment1 = 'check_cascade1_w%d_h%d' % (opt.imWidth1, opt.imHeight1)\n if opt.experimentLight0 is None:\n opt.experimentLight0 = 'check_cascadeLight0_sg%d_offset%.1f' % (opt.SGNum, opt.offset)\n if opt.experimentLight1 is None:\n opt.experimentLight1 = 'check_cascadeLight1_sg%d_offset%.1f' % (opt.SGNum, opt.offset)\n if opt.experimentBS0 is None:\n opt.experimentBS0 = 'checkBs_cascade0_w%d_h%d' % (opt.imWidth0, opt.imHeight0)\n if opt.experimentBS1 is None:\n opt.experimentBS1 = 'checkBs_cascade1_w%d_h%d' % (opt.imWidth1, opt.imHeight1)\n # store paras to list\n opt.imHeights = [opt.imHeight0, opt.imHeight1]\n opt.imWidths = [opt.imWidth0, opt.imWidth1]\n opt.experiments = [opt.experiment0, opt.experiment1]\n opt.experimentsLight = [opt.experimentLight0, opt.experimentLight1]\n opt.experimentsBS = [opt.experimentBS0, opt.experimentBS1]\n opt.nepochs = [opt.nepoch0, opt.nepoch1]\n opt.nepochsLight = [opt.nepochLight0, opt.nepochLight1]\n opt.nepochsBS = [opt.nepochBS0, opt.nepochBS1]\n opt.nitersBS = [opt.niterBS0, opt.niterBS1]\n # TODO: build the required dir structure\n os.system('mkdir -p {0}'.format(opt.outPath))\n\n\n@timeit(PATH_LOG_EST)\ndef load_models():\n imBatchSmall = Variable(torch.FloatTensor(opt.batchSize, 3, opt.envRow, opt.envCol))\n for n in range(0, opt.level):\n # BRDF predictions\n encoders.append(models.encoder0(cascadeLevel=n).eval())\n albedoDecoders.append(models.decoder0(mode=0).eval())\n normalDecoders.append(models.decoder0(mode=1).eval())\n roughDecoders.append(models.decoder0(mode=2).eval())\n depthDecoders.append(models.decoder0(mode=4).eval())\n\n # Load weight\n encoders[n].load_state_dict(\n torch.load('{0}/encoder{1}_{2}.pth'.format(opt.experiments[n], n, opt.nepochs[n] - 1)).state_dict())\n albedoDecoders[n].load_state_dict(\n torch.load('{0}/albedo{1}_{2}.pth'.format(opt.experiments[n], n, opt.nepochs[n] - 1)).state_dict())\n normalDecoders[n].load_state_dict(\n torch.load('{0}/normal{1}_{2}.pth'.format(opt.experiments[n], n, opt.nepochs[n] - 1)).state_dict())\n roughDecoders[n].load_state_dict(\n torch.load('{0}/rough{1}_{2}.pth'.format(opt.experiments[n], n, opt.nepochs[n] - 1)).state_dict())\n depthDecoders[n].load_state_dict(\n torch.load('{0}/depth{1}_{2}.pth'.format(opt.experiments[n], n, opt.nepochs[n] - 1)).state_dict())\n\n for param in encoders[n].parameters():\n param.requires_grad = False\n for param in albedoDecoders[n].parameters():\n param.requires_grad = False\n for param in normalDecoders[n].parameters():\n param.requires_grad = False\n for param in roughDecoders[n].parameters():\n param.requires_grad = False\n for param in depthDecoders[n].parameters():\n param.requires_grad = False\n\n if opt.isLight or (opt.level == 2 and n == 0):\n # Light network\n lightEncoders.append(models.encoderLight(cascadeLevel=n, SGNum=opt.SGNum).eval())\n axisDecoders.append(models.decoderLight(mode=0, SGNum=opt.SGNum).eval())\n lambDecoders.append(models.decoderLight(mode=1, SGNum=opt.SGNum).eval())\n weightDecoders.append(models.decoderLight(mode=2, SGNum=opt.SGNum).eval())\n\n lightEncoders[n].load_state_dict(\n torch.load(\n '{0}/lightEncoder{1}_{2}.pth'.format(opt.experimentsLight[n], n,\n opt.nepochsLight[n] - 1)).state_dict())\n axisDecoders[n].load_state_dict(\n torch.load(\n '{0}/axisDecoder{1}_{2}.pth'.format(opt.experimentsLight[n], n,\n opt.nepochsLight[n] - 1)).state_dict())\n lambDecoders[n].load_state_dict(\n torch.load(\n '{0}/lambDecoder{1}_{2}.pth'.format(opt.experimentsLight[n], n,\n opt.nepochsLight[n] - 1)).state_dict())\n weightDecoders[n].load_state_dict(\n torch.load(\n '{0}/weightDecoder{1}_{2}.pth'.format(opt.experimentsLight[n], n,\n opt.nepochsLight[n] - 1)).state_dict())\n\n for param in lightEncoders[n].parameters():\n param.requires_grad = False\n for param in axisDecoders[n].parameters():\n param.requires_grad = False\n for param in lambDecoders[n].parameters():\n param.requires_grad = False\n for param in weightDecoders[n].parameters():\n param.requires_grad = False\n\n if opt.isBS:\n # BS network\n albedoBSs.append(bs.BilateralLayer(mode=0))\n roughBSs.append(bs.BilateralLayer(mode=2))\n depthBSs.append(bs.BilateralLayer(mode=4))\n\n albedoBSs[n].load_state_dict(\n torch.load(\n '{0}/albedoBs{1}_{2}_{3}.pth'.format(opt.experimentsBS[n], n, opt.nepochsBS[n] - 1,\n opt.nitersBS[n])).state_dict())\n roughBSs[n].load_state_dict(\n torch.load(\n '{0}/roughBs{1}_{2}_{3}.pth'.format(opt.experimentsBS[n], n, opt.nepochsBS[n] - 1,\n opt.nitersBS[n])).state_dict())\n depthBSs[n].load_state_dict(\n torch.load(\n '{0}/depthBs{1}_{2}_{3}.pth'.format(opt.experimentsBS[n], n, opt.nepochsBS[n] - 1,\n opt.nitersBS[n])).state_dict())\n\n for param in albedoBSs[n].parameters():\n param.requires_grad = False\n for param in roughBSs[n].parameters():\n param.requires_grad = False\n for param in depthBSs[n].parameters():\n param.requires_grad = False\n\n\n@timeit(PATH_LOG_EST)\ndef send_models_to_gpu():\n if opt.cuda:\n for n in range(0, opt.level):\n encoders[n] = encoders[n].cuda(opt.gpuId)\n albedoDecoders[n] = albedoDecoders[n].cuda(opt.gpuId)\n normalDecoders[n] = normalDecoders[n].cuda(opt.gpuId)\n roughDecoders[n] = roughDecoders[n].cuda(opt.gpuId)\n depthDecoders[n] = depthDecoders[n].cuda(opt.gpuId)\n\n if opt.isBS:\n albedoBSs[n] = albedoBSs[n].cuda(opt.gpuId)\n roughBSs[n] = roughBSs[n].cuda(opt.gpuId)\n depthBSs[n] = depthBSs[n].cuda(opt.gpuId)\n\n if opt.isLight or (n == 0 and opt.level == 2):\n lightEncoders[n] = lightEncoders[n].cuda(opt.gpuId)\n axisDecoders[n] = axisDecoders[n].cuda(opt.gpuId)\n lambDecoders[n] = lambDecoders[n].cuda(opt.gpuId)\n weightDecoders[n] = weightDecoders[n].cuda(opt.gpuId)\n\n\n@timeit(PATH_LOG_EST)\ndef load_resize_img():\n assert (osp.isfile(opt.imPath))\n im_cpu = cv2.imread(opt.imPath)[:, :, ::-1]\n nh, nw = im_cpu.shape[0], im_cpu.shape[1]\n # Resize Input Images\n opt.newImWidth = []\n opt.newImHeight = []\n for n in range(0, opt.level):\n if nh < nw:\n newW = opt.imWidths[n]\n newH = int(float(opt.imWidths[n]) / float(nw) * nh)\n else:\n newH = opt.imHeights[n]\n newW = int(float(opt.imHeights[n]) / float(nh) * nw)\n\n if nh < newH:\n im = cv2.resize(im_cpu, (newW, newH), interpolation=cv2.INTER_AREA)\n else:\n im = cv2.resize(im_cpu, (newW, newH), interpolation=cv2.INTER_LINEAR)\n\n opt.newImWidth.append(newW)\n opt.newImHeight.append(newH)\n\n im = (np.transpose(im, [2, 0, 1]).astype(np.float32) / 255.0)[np.newaxis, :, :, :]\n im = im / im.max()\n imBatches.append(Variable(torch.from_numpy(im ** (2.2))).cuda())\n\n nh, nw = opt.newImHeight[-1], opt.newImWidth[-1]\n if nh < nw:\n fov = 57\n newW = opt.envCol\n newH = int(float(opt.envCol) / float(nw) * nh)\n else:\n fov = 42.75\n newH = opt.envRow\n newW = int(float(opt.envRow) / float(nh) * nw)\n\n if nh < newH:\n im = cv2.resize(im_cpu, (newW, newH), interpolation=cv2.INTER_AREA)\n else:\n im = cv2.resize(im_cpu, (newW, newH), interpolation=cv2.INTER_LINEAR)\n\n opt.newEnvWidth = newW\n opt.newEnvHeight = newH\n\n im = (np.transpose(im, [2, 0, 1]).astype(np.float32) / 255.0)[np.newaxis, :, :, :]\n im = im / im.max()\n\n return im, fov, im_cpu, nw, nh\n\n\n@timeit(PATH_LOG_EST)\ndef BRDF_predict_0():\n inputBatch = imBatches[0]\n x1, x2, x3, x4, x5, x6 = encoders[0](inputBatch)\n\n albedoPred = 0.5 * (albedoDecoders[0](imBatches[0], x1, x2, x3, x4, x5, x6) + 1)\n normalPred = normalDecoders[0](imBatches[0], x1, x2, x3, x4, x5, x6)\n roughPred = roughDecoders[0](imBatches[0], x1, x2, x3, x4, x5, x6)\n depthPred = 0.5 * (depthDecoders[0](imBatches[0], x1, x2, x3, x4, x5, x6) + 1)\n\n # Normalize Albedo and depth\n bn, ch, nrow, ncol = albedoPred.size()\n albedoPred = albedoPred.view(bn, -1)\n albedoPred = albedoPred / torch.clamp(torch.mean(albedoPred, dim=1), min=1e-10).unsqueeze(1) / 3.0\n albedoPred = albedoPred.view(bn, ch, nrow, ncol)\n\n bn, ch, nrow, ncol = depthPred.size()\n depthPred = depthPred.view(bn, -1)\n depthPred = depthPred / torch.clamp(torch.mean(depthPred, dim=1), min=1e-10).unsqueeze(1) / 3.0\n depthPred = depthPred.view(bn, ch, nrow, ncol)\n\n albedoPreds.append(albedoPred)\n normalPreds.append(normalPred)\n roughPreds.append(roughPred)\n depthPreds.append(depthPred)\n\n\n@timeit(PATH_LOG_EST)\ndef lighting_predict_0():\n if opt.isLight or opt.level == 2:\n # Interpolation\n imBatchLarge = F.interpolate(imBatches[0], [imBatchSmall.size(2) *\n 4, imBatchSmall.size(3) * 4], mode='bilinear')\n albedoPredLarge = F.interpolate(albedoPreds[0], [imBatchSmall.size(2) *\n 4, imBatchSmall.size(3) * 4], mode='bilinear')\n normalPredLarge = F.interpolate(normalPreds[0], [imBatchSmall.size(2) *\n 4, imBatchSmall.size(3) * 4], mode='bilinear')\n roughPredLarge = F.interpolate(roughPreds[0], [imBatchSmall.size(2) *\n 4, imBatchSmall.size(3) * 4], mode='bilinear')\n depthPredLarge = F.interpolate(depthPreds[0], [imBatchSmall.size(2) *\n 4, imBatchSmall.size(3) * 4], mode='bilinear')\n\n inputBatch = torch.cat([imBatchLarge, albedoPredLarge,\n 0.5 * (normalPredLarge + 1), 0.5 * (roughPredLarge + 1), depthPredLarge], dim=1)\n x1, x2, x3, x4, x5, x6 = lightEncoders[0](inputBatch)\n\n # Prediction\n axisPred = axisDecoders[0](x1, x2, x3, x4, x5, x6, imBatchSmall)\n lambPred = lambDecoders[0](x1, x2, x3, x4, x5, x6, imBatchSmall)\n weightPred = weightDecoders[0](x1, x2, x3, x4, x5, x6, imBatchSmall)\n bn, SGNum, _, envRow, envCol = axisPred.size()\n envmapsPred = torch.cat([axisPred.view(bn, SGNum * 3, envRow, envCol), lambPred, weightPred], dim=1)\n envmapsPreds.append(envmapsPred)\n\n envmapsPredImage, axisPred, lambPred, weightPred = output2env.output2env(axisPred, lambPred, weightPred)\n envmapsPredImages.append(envmapsPredImage)\n\n diffusePred, specularPred = renderLayer.forwardEnv(albedoPreds[0], normalPreds[0],\n roughPreds[0], envmapsPredImages[0])\n\n diffusePredNew, specularPredNew = models.LSregressDiffSpec(\n diffusePred,\n specularPred,\n imBatchSmall,\n diffusePred, specularPred)\n renderedPred = diffusePredNew + specularPredNew\n renderedPreds.append(renderedPred)\n\n cDiff, cSpec = (torch.sum(diffusePredNew) / torch.sum(diffusePred)).data.item(), (\n (torch.sum(specularPredNew)) / (torch.sum(specularPred))).data.item()\n if cSpec < 1e-3:\n cAlbedo = 1 / albedoPreds[-1].max().data.item()\n cLight = cDiff / cAlbedo\n else:\n cLight = cSpec\n cAlbedo = cDiff / cLight\n cAlbedo = np.clip(cAlbedo, 1e-3, 1 / albedoPreds[-1].max().data.item())\n cLight = cDiff / cAlbedo\n envmapsPredImages[0] = envmapsPredImages[0] * cLight\n cAlbedos.append(cAlbedo)\n cLights.append(cLight)\n\n diffusePred = diffusePredNew\n specularPred = specularPredNew\n diffusePreds.append(diffusePred)\n specularPreds.append(specularPred)\n\n\n@timeit(PATH_LOG_EST)\ndef BRDF_predict_1():\n if opt.level == 2:\n albedoPredLarge = F.interpolate(albedoPreds[0], [opt.newImHeight[1], opt.newImWidth[1]], mode='bilinear')\n normalPredLarge = F.interpolate(normalPreds[0], [opt.newImHeight[1], opt.newImWidth[1]], mode='bilinear')\n roughPredLarge = F.interpolate(roughPreds[0], [opt.newImHeight[1], opt.newImWidth[1]], mode='bilinear')\n depthPredLarge = F.interpolate(depthPreds[0], [opt.newImHeight[1], opt.newImWidth[1]], mode='bilinear')\n\n diffusePredLarge = F.interpolate(diffusePreds[-1], [opt.newImHeight[1], opt.newImWidth[1]], mode='bilinear')\n specularPredLarge = F.interpolate(specularPreds[-1], [opt.newImHeight[1], opt.newImWidth[1]], mode='bilinear')\n\n inputBatch = torch.cat([imBatches[1], albedoPredLarge,\n 0.5 * (normalPredLarge + 1), 0.5 * (roughPredLarge + 1), depthPredLarge,\n diffusePredLarge, specularPredLarge], dim=1)\n\n x1, x2, x3, x4, x5, x6 = encoders[1](inputBatch)\n albedoPred = 0.5 * (albedoDecoders[1](imBatches[1], x1, x2, x3, x4, x5, x6) + 1)\n normalPred = normalDecoders[1](imBatches[1], x1, x2, x3, x4, x5, x6)\n roughPred = roughDecoders[1](imBatches[1], x1, x2, x3, x4, x5, x6)\n depthPred = 0.5 * (depthDecoders[1](imBatches[1], x1, x2, x3, x4, x5, x6) + 1)\n\n # Normalize Albedo and depth\n bn, ch, nrow, ncol = albedoPred.size()\n albedoPred = albedoPred.view(bn, -1)\n albedoPred = albedoPred / torch.clamp(torch.mean(albedoPred, dim=1), min=1e-10).unsqueeze(1) / 3.0\n albedoPred = albedoPred.view(bn, ch, nrow, ncol)\n\n bn, ch, nrow, ncol = depthPred.size()\n depthPred = depthPred.view(bn, -1)\n depthPred = depthPred / torch.clamp(torch.mean(depthPred, dim=1), min=1e-10).unsqueeze(1) / 3.0\n depthPred = depthPred.view(bn, ch, nrow, ncol)\n\n albedoPreds.append(albedoPred)\n normalPreds.append(normalPred)\n roughPreds.append(roughPred)\n depthPreds.append(depthPred)\n\n\n@timeit(PATH_LOG_EST)\ndef lighting_predict_1():\n if opt.level == 2 and opt.isLight:\n # Interpolation\n imBatchLarge = F.interpolate(imBatches[1], [imBatchSmall.size(2) *\n 4, imBatchSmall.size(3) * 4], mode='bilinear')\n albedoPredLarge = F.interpolate(albedoPreds[1], [imBatchSmall.size(2) *\n 4, imBatchSmall.size(3) * 4], mode='bilinear')\n normalPredLarge = F.interpolate(normalPreds[1], [imBatchSmall.size(2) *\n 4, imBatchSmall.size(3) * 4], mode='bilinear')\n roughPredLarge = F.interpolate(roughPreds[1], [imBatchSmall.size(2) *\n 4, imBatchSmall.size(3) * 4], mode='bilinear')\n depthPredLarge = F.interpolate(depthPreds[1], [imBatchSmall.size(2) *\n 4, imBatchSmall.size(3) * 4], mode='bilinear')\n\n inputBatch = torch.cat([imBatchLarge, albedoPredLarge,\n 0.5 * (normalPredLarge + 1), 0.5 * (roughPredLarge + 1), depthPredLarge], dim=1)\n x1, x2, x3, x4, x5, x6 = lightEncoders[1](inputBatch, envmapsPreds[-1])\n\n # Prediction\n axisPred = axisDecoders[1](x1, x2, x3, x4, x5, x6, imBatchSmall)\n lambPred = lambDecoders[1](x1, x2, x3, x4, x5, x6, imBatchSmall)\n weightPred = weightDecoders[1](x1, x2, x3, x4, x5, x6, imBatchSmall)\n bn, SGNum, _, envRow, envCol = axisPred.size()\n envmapsPred = torch.cat([axisPred.view(bn, SGNum * 3, envRow, envCol), lambPred, weightPred], dim=1)\n envmapsPreds.append(envmapsPred)\n\n envmapsPredImage, axisPred, lambPred, weightPred = output2env.output2env(axisPred, lambPred, weightPred)\n envmapsPredImages.append(envmapsPredImage)\n\n diffusePred, specularPred = renderLayer.forwardEnv(albedoPreds[1], normalPreds[1],\n roughPreds[1], envmapsPredImages[1])\n\n diffusePredNew, specularPredNew = models.LSregressDiffSpec(\n diffusePred,\n specularPred,\n imBatchSmall,\n diffusePred, specularPred)\n\n # TODO: used to be \"renderedPre\"\n renderedPred = diffusePredNew + specularPredNew\n renderedPreds.append(renderedPred)\n\n cDiff, cSpec = (torch.sum(diffusePredNew) / torch.sum(diffusePred)).data.item(), (\n (torch.sum(specularPredNew)) / (torch.sum(specularPred))).data.item()\n if cSpec == 0:\n cAlbedo = 1 / albedoPreds[-1].max().data.item()\n cLight = cDiff / cAlbedo\n else:\n cLight = cSpec\n cAlbedo = cDiff / cLight\n cAlbedo = np.clip(cAlbedo, 1e-3, 1 / albedoPreds[-1].max().data.item())\n cLight = cDiff / cAlbedo\n envmapsPredImages[-1] = envmapsPredImages[-1] * cLight\n cAlbedos.append(cAlbedo)\n cLights.append(cLight)\n\n diffusePred = diffusePredNew\n specularPred = specularPredNew\n diffusePreds.append(diffusePred)\n specularPreds.append(specularPred)\n\n\n@timeit(PATH_LOG_EST)\ndef BilateralLayer_predict():\n if opt.isBS:\n for n in range(0, opt.level):\n albedoBSPred, albedoConf = albedoBSs[n](imBatches[n], albedoPreds[n].detach(), albedoPreds[n])\n albedoBSPreds.append(albedoBSPred)\n roughBSPred, roughConf = roughBSs[n](imBatches[n], albedoPreds[n].detach(), 0.5 * (roughPreds[n] + 1))\n roughBSPred = torch.clamp(2 * roughBSPred - 1, -1, 1)\n roughBSPreds.append(roughBSPred)\n depthBSPred, depthConf = depthBSs[n](imBatches[n], albedoPreds[n].detach(), depthPreds[n])\n depthBSPreds.append(depthBSPred)\n\n\n@timeit(PATH_LOG_EST)\ndef save_results_all():\n albedoNames, albedoImNames = [], []\n normalNames, normalImNames = [], []\n roughNames, roughImNames = [], []\n depthNames, depthImNames = [], []\n imOutputNames = []\n envmapPredNames, envmapPredImNames = [], []\n renderedNames, renderedImNames = [], []\n cLightNames = []\n shadingNames, envmapsPredSGNames = [], []\n\n imOutputNames.append(osp.join(opt.outPath, opt.imName))\n\n for n in range(0, opt.level):\n albedoNames.append(osp.join(opt.outPath, opt.imName.replace('.png', '_albedo%d.npy' % n)))\n albedoImNames.append(osp.join(opt.outPath, opt.imName.replace('.png', '_albedo%d.png' % n)))\n normalNames.append(osp.join(opt.outPath, opt.imName.replace('.png', '_normal%d.npy' % n)))\n normalImNames.append(osp.join(opt.outPath, opt.imName.replace('.png', '_normal%d.png' % n)))\n roughNames.append(osp.join(opt.outPath, opt.imName.replace('.png', '_rough%d.npy' % n)))\n roughImNames.append(osp.join(opt.outPath, opt.imName.replace('.png', '_rough%d.png' % n)))\n depthNames.append(osp.join(opt.outPath, opt.imName.replace('.png', '_depth%d.npy' % n)))\n depthImNames.append(osp.join(opt.outPath, opt.imName.replace('.png', '_depth%d.png' % n)))\n\n albedoBSNames = albedoNames[n].replace('albedo', 'albedoBs')\n albedoImBSNames = albedoImNames[n].replace('albedo', 'albedoBs')\n roughBSNames = roughNames[n].replace('rough', 'roughBs')\n roughImBSNames = roughImNames[n].replace('rough', 'roughBs')\n depthBSNames = depthNames[n].replace('depth', 'depthBs')\n depthImBSNames = depthImNames[n].replace('depth', 'depthBs')\n\n envmapsPredSGNames.append(osp.join(opt.outPath, opt.imName.replace('.png', '_envmapSG%d.npy' % n)))\n shadingNames.append(osp.join(opt.outPath, opt.imName.replace('.png', '_shading%d.png' % n)))\n envmapPredNames.append(osp.join(opt.outPath, opt.imName.replace('.png', '_envmap%d.npz' % n)))\n envmapPredImNames.append(osp.join(opt.outPath, opt.imName.replace('.png', '_envmap%d.png' % n)))\n renderedNames.append(osp.join(opt.outPath, opt.imName.replace('.png', '_rendered%d.npy' % n)))\n renderedImNames.append(osp.join(opt.outPath, opt.imName.replace('.png', '_rendered%d.png' % n)))\n\n cLightNames.append(osp.join(opt.outPath, opt.imName.replace('.png', '_cLight%d.mat' % n)))\n\n # Save the albedo\n for n in range(0, len(albedoPreds)):\n if n < len(cAlbedos):\n albedoPred = (albedoPreds[n] * cAlbedos[n]).data.cpu().numpy().squeeze()\n else:\n albedoPred = albedoPreds[n].data.cpu().numpy().squeeze()\n\n albedoPred = albedoPred.transpose([1, 2, 0])\n albedoPred = albedoPred ** (1.0 / 2.2)\n albedoPred = cv2.resize(albedoPred, (nw, nh), interpolation=cv2.INTER_LINEAR)\n\n albedoPredIm = (np.clip(255 * albedoPred, 0, 255)).astype(np.uint8)\n\n cv2.imwrite(albedoImNames[n], albedoPredIm[:, :, ::-1])\n\n # Save the normal\n for n in range(0, len(normalPreds)):\n normalPred = normalPreds[n].data.cpu().numpy().squeeze()\n normalPred = normalPred.transpose([1, 2, 0])\n normalPred = cv2.resize(normalPred, (nw, nh), interpolation=cv2.INTER_LINEAR)\n\n np.save(normalNames[n], normalPred)\n\n normalPredIm = (255 * 0.5 * (normalPred + 1)).astype(np.uint8)\n cv2.imwrite(normalImNames[n], normalPredIm[:, :, ::-1])\n\n # Save the rough\n for n in range(0, len(roughPreds)):\n roughPred = roughPreds[n].data.cpu().numpy().squeeze()\n roughPred = cv2.resize(roughPred, (nw, nh), interpolation=cv2.INTER_LINEAR)\n\n roughPredIm = (255 * 0.5 * (roughPred + 1)).astype(np.uint8)\n cv2.imwrite(roughImNames[n], roughPredIm)\n\n # Save the depth\n for n in range(0, len(depthPreds)):\n depthPred = depthPreds[n].data.cpu().numpy().squeeze()\n np.save(depthNames[n], depthPred)\n\n depthPred = depthPred / np.maximum(depthPred.mean(), 1e-10) * 3\n depthPred = cv2.resize(depthPred, (nw, nh), interpolation=cv2.INTER_LINEAR)\n\n depthOut = 1 / np.clip(depthPred + 1, 1e-6, 10)\n depthPredIm = (255 * depthOut).astype(np.uint8)\n cv2.imwrite(depthImNames[n], depthPredIm)\n\n if opt.isBS:\n # Save the albedo bs\n for n in range(0, len(albedoBSPreds)):\n if n < len(cAlbedos):\n albedoBSPred = (albedoBSPreds[n] * cAlbedos[n]).data.cpu().numpy().squeeze()\n else:\n albedoBSPred = albedoBSPreds[n].data.cpu().numpy().squeeze()\n albedoBSPred = albedoBSPred.transpose([1, 2, 0])\n albedoBSPred = (albedoBSPred) ** (1.0 / 2.2)\n albedoBSPred = cv2.resize(albedoBSPred, (nw, nh), interpolation=cv2.INTER_LINEAR)\n\n albedoBSPredIm = (np.clip(255 * albedoBSPred, 0, 255)).astype(np.uint8)\n cv2.imwrite(albedoImNames[n].replace('albedo', 'albedoBS'), albedoBSPredIm[:, :, ::-1])\n\n # Save the rough bs\n for n in range(0, len(roughBSPreds)):\n roughBSPred = roughBSPreds[n].data.cpu().numpy().squeeze()\n roughBSPred = cv2.resize(roughBSPred, (nw, nh), interpolation=cv2.INTER_LINEAR)\n\n roughBSPredIm = (255 * 0.5 * (roughBSPred + 1)).astype(np.uint8)\n cv2.imwrite(roughImNames[n].replace('rough', 'roughBS'), roughBSPredIm)\n\n for n in range(0, len(depthBSPreds)):\n depthBSPred = depthBSPreds[n].data.cpu().numpy().squeeze()\n np.save(depthNames[n].replace('depth', 'depthBS'), depthBSPred)\n\n depthBSPred = depthBSPred / np.maximum(depthBSPred.mean(), 1e-10) * 3\n depthBSPred = cv2.resize(depthBSPred, (nw, nh), interpolation=cv2.INTER_LINEAR)\n\n depthOut = 1 / np.clip(depthBSPred + 1, 1e-6, 10)\n depthBSPredIm = (255 * depthOut).astype(np.uint8)\n cv2.imwrite(depthImNames[n].replace('depth', 'depthBS'), depthBSPredIm)\n\n if opt.isLight:\n # Save the envmapImages\n for n in range(0, len(envmapsPredImages)):\n envmapsPredImage = envmapsPredImages[n].data.cpu().numpy().squeeze()\n envmapsPredImage = envmapsPredImage.transpose([1, 2, 3, 4, 0])\n\n # Flip to be conincide with our dataset\n np.savez_compressed(envmapPredImNames[n],\n env=np.ascontiguousarray(envmapsPredImage[:, :, :, :, ::-1]))\n\n utils.writeEnvToFile(envmapsPredImages[n], 0, envmapPredImNames[n], nrows=24, ncols=16)\n\n for n in range(0, len(envmapsPreds)):\n envmapsPred = envmapsPreds[n].data.cpu().numpy()\n np.save(envmapsPredSGNames[n], envmapsPred)\n shading = utils.predToShading(envmapsPred, SGNum=opt.SGNum)\n shading = shading.transpose([1, 2, 0])\n shading = shading / np.mean(shading) / 3.0\n shading = np.clip(shading, 0, 1)\n shading = (255 * shading ** (1.0 / 2.2)).astype(np.uint8)\n cv2.imwrite(shadingNames[n], shading[:, :, ::-1])\n\n for n in range(0, len(cLights)):\n io.savemat(cLightNames[n], {'cLight': cLights[n]})\n\n # Save the rendered image\n for n in range(0, len(renderedPreds)):\n renderedPred = renderedPreds[n].data.cpu().numpy().squeeze()\n renderedPred = renderedPred.transpose([1, 2, 0])\n renderedPred = (renderedPred / renderedPred.max()) ** (1.0 / 2.2)\n renderedPred = cv2.resize(renderedPred, (nw, nh), interpolation=cv2.INTER_LINEAR)\n # np.save(renderedNames[n], renderedPred )\n\n renderedPred = (np.clip(renderedPred, 0, 1) * 255).astype(np.uint8)\n cv2.imwrite(renderedImNames[n], renderedPred[:, :, ::-1])\n\n # Save the image\n cv2.imwrite(imOutputNames[0], im_cpu[:, :, ::-1])\n\n\n@timeit(PATH_LOG_EST)\ndef save_results_of(_mode=0, _albedo=True, _normal=True, _rough=True, _depth=False,\n _envmap=True, _envmapSG=False, _cLight=False, _shading=False, _rendered=False):\n _n = 0\n if _mode == 0:\n _n = 0\n elif _mode == 1:\n _n = 1\n elif _mode == 2:\n _n = 1\n\n # save the origin input image\n originImPath = osp.join(opt.outPath, 'im.png')\n cv2.imwrite(originImPath, im_cpu[:, :, ::-1])\n\n # save the albedo\n if _albedo:\n albedoImPath = osp.join(opt.outPath, 'albedo.png')\n if _n < len(cAlbedos):\n albedoPred = (albedoPreds[_n] * cAlbedos[_n]).data.cpu().numpy().squeeze()\n else:\n albedoPred = albedoPreds[_n].data.cpu().numpy().squeeze()\n albedoPred = albedoPred.transpose([1, 2, 0])\n albedoPred = albedoPred ** (1.0 / 2.2)\n albedoPred = cv2.resize(albedoPred, (nw, nh), interpolation=cv2.INTER_LINEAR)\n albedoPredIm = (np.clip(255 * albedoPred, 0, 255)).astype(np.uint8)\n cv2.imwrite(albedoImPath, albedoPredIm[:, :, ::-1])\n\n if opt.isBS:\n if _n < len(cAlbedos):\n albedoBSPred = (albedoBSPreds[_n] * cAlbedos[_n]).data.cpu().numpy().squeeze()\n else:\n albedoBSPred = albedoBSPreds[_n].data.cpu().numpy().squeeze()\n albedoBSPred = albedoBSPred.transpose([1, 2, 0])\n albedoBSPred = (albedoBSPred) ** (1.0 / 2.2)\n albedoBSPred = cv2.resize(albedoBSPred, (nw, nh), interpolation=cv2.INTER_LINEAR)\n albedoBSPredIm = (np.clip(255 * albedoBSPred, 0, 255)).astype(np.uint8)\n cv2.imwrite(albedoImPath.replace('albedo', 'albedoBS'), albedoBSPredIm[:, :, ::-1])\n if _mode == 2:\n os.system('rm ' + albedoImPath)\n os.system('mv ' + albedoImPath.replace('albedo', 'albedoBS') + ' ' + albedoImPath)\n\n # save the normal\n if _normal:\n normalPath = osp.join(opt.outPath, 'normal.npy')\n normalImPath = osp.join(opt.outPath, 'normal.png')\n normalPred = normalPreds[_n].data.cpu().numpy().squeeze()\n normalPred = normalPred.transpose([1, 2, 0])\n normalPred = cv2.resize(normalPred, (nw, nh), interpolation=cv2.INTER_LINEAR)\n np.save(normalPath, normalPred)\n normalPredIm = (255 * 0.5 * (normalPred + 1)).astype(np.uint8)\n cv2.imwrite(normalImPath, normalPredIm[:, :, ::-1])\n\n # save the rough\n if _rough:\n roughImPath = osp.join(opt.outPath, 'rough.png')\n roughPred = roughPreds[_n].data.cpu().numpy().squeeze()\n roughPred = cv2.resize(roughPred, (nw, nh), interpolation=cv2.INTER_LINEAR)\n roughPredIm = (255 * 0.5 * (roughPred + 1)).astype(np.uint8)\n cv2.imwrite(roughImPath, roughPredIm)\n\n if opt.isBS:\n roughBSPred = roughBSPreds[_n].data.cpu().numpy().squeeze()\n roughBSPred = cv2.resize(roughBSPred, (nw, nh), interpolation=cv2.INTER_LINEAR)\n roughBSPredIm = (255 * 0.5 * (roughBSPred + 1)).astype(np.uint8)\n cv2.imwrite(roughImPath.replace('rough', 'roughBS'), roughBSPredIm)\n if _mode == 2:\n os.system('rm ' + roughImPath)\n os.system('mv ' + roughImPath.replace('rough', 'roughBS') + ' ' + roughImPath)\n\n # save the depth\n if _depth:\n depthPath = osp.join(opt.outPath, 'depth.npy')\n depthImPath = osp.join(opt.outPath, 'depth.png')\n depthPred = depthPreds[_n].data.cpu().numpy().squeeze()\n np.save(depthPath, depthPred)\n depthPred = depthPred / np.maximum(depthPred.mean(), 1e-10) * 3\n depthPred = cv2.resize(depthPred, (nw, nh), interpolation=cv2.INTER_LINEAR)\n depthOut = 1 / np.clip(depthPred + 1, 1e-6, 10)\n depthPredIm = (255 * depthOut).astype(np.uint8)\n cv2.imwrite(depthImPath, depthPredIm)\n\n if opt.isBS:\n depthBSPred = depthBSPreds[_n].data.cpu().numpy().squeeze()\n np.save(depthPath.replace('depth', 'depthBS'), depthBSPred)\n depthBSPred = depthBSPred / np.maximum(depthBSPred.mean(), 1e-10) * 3\n depthBSPred = cv2.resize(depthBSPred, (nw, nh), interpolation=cv2.INTER_LINEAR)\n depthOut = 1 / np.clip(depthBSPred + 1, 1e-6, 10)\n depthBSPredIm = (255 * depthOut).astype(np.uint8)\n cv2.imwrite(depthImPath.replace('depth', 'depthBS'), depthBSPredIm)\n\n if _mode == 2:\n os.system('rm ' + depthImPath)\n os.system('mv ' + depthImPath.replace('depth', 'depthBS') + ' ' + depthImPath)\n\n # save light results\n if opt.isLight:\n envmapPredImPath = osp.join(opt.outPath, 'envmap.png')\n envmapsPredSGPath = osp.join(opt.outPath, 'envmapSG.npy')\n shadingImPath = osp.join(opt.outPath, 'shading.png')\n cLightPath = osp.join(opt.outPath, 'cLight.mat')\n renderedPath = osp.join(opt.outPath, 'render.npy')\n renderedImPath = osp.join(opt.outPath, 'render.png')\n\n # save the envmap\n if _envmap:\n envmapsPredImage = envmapsPredImages[_n].data.cpu().numpy().squeeze()\n envmapsPredImage = envmapsPredImage.transpose([1, 2, 3, 4, 0])\n np.savez_compressed(envmapPredImPath, env=np.ascontiguousarray(envmapsPredImage[:, :, :, :, ::-1]))\n # utils.writeEnvToFile(envmapsPredImages[_n], 0, envmapPredImPath, nrows=24, ncols=16)\n\n # save the envmapSG\n if _envmapSG:\n envmapsPred = envmapsPreds[_n].data.cpu().numpy()\n np.save(envmapsPredSGPath, envmapsPred)\n\n # save the shading\n if _shading:\n shading = utils.predToShading(envmapsPred, SGNum=opt.SGNum)\n shading = shading.transpose([1, 2, 0])\n shading = shading / np.mean(shading) / 3.0\n shading = np.clip(shading, 0, 1)\n shading = (255 * shading ** (1.0 / 2.2)).astype(np.uint8)\n cv2.imwrite(shadingImPath, shading[:, :, ::-1])\n\n # save the clight\n if _cLight:\n io.savemat(cLightPath, {'cLight': cLights[_n]})\n\n # save the rendered image\n if _rendered:\n renderedPred = renderedPreds[_n].data.cpu().numpy().squeeze()\n renderedPred = renderedPred.transpose([1, 2, 0])\n renderedPred = (renderedPred / renderedPred.max()) ** (1.0 / 2.2)\n renderedPred = cv2.resize(renderedPred, (nw, nh), interpolation=cv2.INTER_LINEAR)\n np.save(renderedPath, renderedPred )\n renderedPred = (np.clip(renderedPred, 0, 1) * 255).astype(np.uint8)\n cv2.imwrite(renderedImPath, renderedPred[:, :, ::-1])\n\n\nif __name__ == '__main__':\n # read the parameters and complete them\n opt = get_parser()\n handle_parameters()\n print(opt)\n\n # build the network decoder architecture\n encoders = []\n albedoDecoders, normalDecoders, roughDecoders, depthDecoders = [], [], [], []\n lightEncoders, axisDecoders, lambDecoders, weightDecoders = [], [], [], []\n albedoBSs, depthBSs, roughBSs = [], [], []\n # load the trained models to CPU\n load_models()\n # load models from CPU to GPU\n send_models_to_gpu()\n\n # load the input image to CPU and resize it\n imBatches = []\n im, fov, im_cpu, nw, nh = load_resize_img()\n # load the image from CPU to GPU\n imBatchSmall = Variable(torch.from_numpy(im ** 2.2)).cuda()\n renderLayer = models.renderingLayer(isCuda=opt.cuda,\n imWidth=opt.newEnvWidth, imHeight=opt.newEnvHeight, fov=fov,\n envWidth=opt.envWidth, envHeight=opt.envHeight)\n output2env = models.output2env(isCuda=opt.cuda,\n envWidth=opt.envWidth, envHeight=opt.envHeight, SGNum=opt.SGNum)\n\n # build the cascade network architecture\n albedoPreds, normalPreds, roughPreds, depthPreds = [], [], [], []\n albedoBSPreds, roughBSPreds, depthBSPreds = [], [], []\n envmapsPreds, envmapsPredImages, renderedPreds = [], [], []\n diffusePreds, specularPreds = [], []\n cAlbedos = []\n cLights = []\n # prediction of level 0\n BRDF_predict_0()\n lighting_predict_0()\n # prediction of level 1\n BRDF_predict_1()\n lighting_predict_1()\n # prediction of BS\n BilateralLayer_predict()\n\n # save all the results\n # save_results_all('l2')\n # save specific results\n save_results_of(_mode=opt.mode)\n" }, { "alpha_fraction": 0.512615442276001, "alphanum_fraction": 0.532030463218689, "avg_line_length": 35.532814025878906, "blob_id": "1998894942bca457c4d4e1d2551d6e8922180d54", "content_id": "084685d2affe1439c1bb9cea65e9de4c9d87a0e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 23384, "license_type": "no_license", "max_line_length": 120, "num_lines": 640, "path": "/generate.py", "repo_name": "FUJI-W/lightAR", "src_encoding": "UTF-8", "text": "import os\nimport xml.etree.ElementTree as et\nfrom xml.dom import minidom\nimport numpy as np\nimport argparse\nimport glob\nimport cv2\nimport math\n\nimport numba\nfrom numba import cuda\n\nimport numexpr as ne\n\nfrom setting import *\nfrom tools import *\n\n\n\nclass tex():\n def __init__(self, diffuseName=None, roughnessName=None):\n self.diffuseName = diffuseName\n self.roughnessName = roughnessName\n\n\nclass mat():\n def __init__(self, name='mat', diffuse=None, roughness=None, texture=None):\n self.name = name\n self.diffuse = diffuse\n self.roughness = roughness\n self.texture = texture\n\n\n############################# Code for Generating the Xml file ########################\n@timeit(PATH_LOG_GEN)\ndef addShape(root, name, materials, isAddSpecular=True,\n isAddTransform=False,\n meshTranslate=None, meshRotateAxis=None, meshRotateAngle=None, meshScale=None,\n rotateAxis=None, rotateAngle=None,\n scaleValue=None, translationValue=None):\n shape = et.SubElement(root, 'shape')\n shape.set('id', '{0}_object'.format(name.split('.')[0]))\n\n objType = name.split('.')[-1]\n assert (objType == 'ply' or objType == 'obj')\n shape.set('type', objType)\n stringF = et.SubElement(shape, 'string')\n stringF.set('name', 'filename')\n stringF.set('value', name)\n\n for material in materials:\n bsdf = et.SubElement(shape, 'bsdf')\n\n if isAddSpecular == False:\n bsdf.set('type', 'diffuse')\n if material.texture is None:\n rgb = et.SubElement(bsdf, 'rgb')\n rgb.set('name', 'reflectance')\n rgb.set('value', '%.5f %.5f %.5f'\n % (material.diffuse[0], material.diffuse[1], material.diffuse[2]))\n else:\n diffPath = material.texture.diffuseName\n texture = et.SubElement(bsdf, 'texture')\n texture.set('name', 'reflectance')\n texture.set('type', 'bitmap')\n filename = et.SubElement(texture, 'string')\n filename.set('name', 'filename')\n filename.set('value', diffPath)\n\n elif isAddSpecular == True:\n bsdf.set('type', 'microfacet')\n if material.texture is None:\n rgb = et.SubElement(bsdf, 'rgb')\n rgb.set('name', 'albedo')\n rgb.set('value', '%.5f %.5f %.5f'\n % (material.diffuse[0], material.diffuse[1], material.diffuse[2]))\n rgb = et.SubElement(bsdf, 'float')\n rgb.set('name', 'roughness')\n rgb.set('value', '%.5f' % (material.roughness))\n else:\n diffPath = material.texture.diffuseName\n texture = et.SubElement(bsdf, 'texture')\n texture.set('name', 'albedo')\n texture.set('type', 'bitmap')\n filename = et.SubElement(texture, 'string')\n filename.set('name', 'filename')\n filename.set('value', diffPath)\n\n roughPath = material.texture.roughnessName\n texture = et.SubElement(bsdf, 'texture')\n texture.set('name', 'roughness')\n texture.set('type', 'bitmap')\n filename = et.SubElement(texture, 'string')\n filename.set('name', 'filename')\n filename.set('value', roughPath)\n\n if isAddTransform:\n transform = et.SubElement(shape, 'transform')\n transform.set('name', 'toWorld')\n if not meshTranslate is None:\n translation = et.SubElement(transform, 'translate')\n translation.set('x', '%.5f' % meshTranslate[0])\n translation.set('y', '%.5f' % meshTranslate[1])\n translation.set('z', '%.5f' % meshTranslate[2])\n if not meshRotateAxis is None:\n assert (not meshRotateAngle is None)\n rotation = et.SubElement(transform, 'rotate')\n rotation.set('x', '%.5f' % meshRotateAxis[0])\n rotation.set('y', '%.5f' % meshRotateAxis[1])\n rotation.set('z', '%.5f' % meshRotateAxis[2])\n rotation.set('angle', '%.5f' % meshRotateAngle)\n if not meshScale is None:\n scale = et.SubElement(transform, 'scale')\n scale.set('value', '%.5f' % meshScale)\n if not rotateAxis is None:\n assert (not rotateAngle is None)\n rotation = et.SubElement(transform, 'rotate')\n rotation.set('x', '%.5f' % rotateAxis[0])\n rotation.set('y', '%.5f' % rotateAxis[1])\n rotation.set('z', '%.5f' % rotateAxis[2])\n rotation.set('angle', '%.5f' % rotateAngle)\n if not scaleValue is None:\n scale = et.SubElement(transform, 'scale')\n scale.set('value', '%.5f' % scaleValue)\n if not translationValue is None:\n translation = et.SubElement(transform, 'translate')\n translation.set('x', '%.5f' % translationValue[0])\n translation.set('y', '%.5f' % translationValue[1])\n translation.set('z', '%.5f' % translationValue[2])\n return root\n\n\n@timeit(PATH_LOG_GEN)\ndef addEnv(root, envmapName, scaleFloat):\n emitter = et.SubElement(root, 'emitter')\n emitter.set('type', 'envmap')\n filename = et.SubElement(emitter, 'string')\n filename.set('name', 'filename')\n filename.set('value', envmapName)\n scale = et.SubElement(emitter, 'float')\n scale.set('name', 'scale')\n scale.set('value', '%.4f' % (scaleFloat))\n return root\n\n\n@timeit(PATH_LOG_GEN)\ndef addSensor(root, fovValue, imWidth, imHeight, sampleCount):\n camera = et.SubElement(root, 'sensor')\n camera.set('type', 'perspective')\n fov = et.SubElement(camera, 'float')\n fov.set('name', 'fov')\n fov.set('value', '%.4f' % (fovValue))\n fovAxis = et.SubElement(camera, 'string')\n fovAxis.set('name', 'fovAxis')\n fovAxis.set('value', 'x')\n transform = et.SubElement(camera, 'transform')\n transform.set('name', 'toWorld')\n lookAt = et.SubElement(transform, 'lookAt')\n lookAt.set('origin', '0 0 0')\n lookAt.set('target', '0 0 1.0')\n lookAt.set('up', '0 1.0 0')\n film = et.SubElement(camera, 'film')\n film.set('type', 'hdrfilm')\n width = et.SubElement(film, 'integer')\n width.set('name', 'width')\n width.set('value', '%d' % (imWidth))\n height = et.SubElement(film, 'integer')\n height.set('name', 'height')\n height.set('value', '%d' % (imHeight))\n sampler = et.SubElement(camera, 'sampler')\n sampler.set('type', 'adaptive')\n sampleNum = et.SubElement(sampler, 'integer')\n sampleNum.set('name', 'sampleCount')\n sampleNum.set('value', '%d' % (sampleCount))\n return root\n\n\n@timeit(PATH_LOG_GEN)\ndef transformToXml(root):\n rstring = et.tostring(root, 'utf-8')\n pstring = minidom.parseString(rstring)\n xmlString = pstring.toprettyxml(indent=\" \")\n xmlString = xmlString.split('\\n')\n xmlString = [x for x in xmlString if len(x.strip()) != 0]\n xmlString = '\\n'.join(xmlString)\n return xmlString\n\n\n@timeit(PATH_LOG_GEN)\ndef generateXML(shapes, materials, envmapName, xmlName, sampleCount=1024,\n imWidth=640, imHeight=480, fovValue=63.4149,\n meshTranslate=None, meshRotateAxis=None, meshRotateAngle=None,\n meshScale=None, rotateAxis=None, rotateAngle=None,\n translation=None, scale=None):\n # Build the scene\n root = et.Element('scene')\n root.set('version', '0.5.0')\n integrator = et.SubElement(root, 'integrator')\n integrator.set('type', 'path')\n\n rootObj = et.Element('scene')\n rootObj.set('version', '0.5.0')\n integrator = et.SubElement(rootObj, 'integrator')\n integrator.set('type', 'path')\n\n rootBkg = et.Element('scene')\n rootBkg.set('version', '0.5.0')\n integrator = et.SubElement(rootBkg, 'integrator')\n integrator.set('type', 'path')\n\n ## Create the obj files that is not emitter\n # Write 3D meshes\n root = addShape(root, shapes[0], [materials[0]], True,\n isAddTransform=False)\n rootBkg = addShape(rootBkg, shapes[0], [materials[0]], True,\n isAddTransform=False)\n\n root = addShape(root, shapes[1], [materials[1]], True,\n isAddTransform=True,\n meshTranslate=meshTranslate, meshRotateAxis=meshRotateAxis,\n meshRotateAngle=meshRotateAngle, meshScale=meshScale,\n rotateAxis=rotateAxis, rotateAngle=rotateAngle,\n scaleValue=scale, translationValue=translation)\n rootObj = addShape(rootObj, shapes[1], [materials[1]], True,\n isAddTransform=True,\n meshTranslate=meshTranslate, meshRotateAxis=meshRotateAxis,\n meshRotateAngle=meshRotateAngle, meshScale=meshScale,\n rotateAxis=rotateAxis, rotateAngle=rotateAngle,\n scaleValue=scale, translationValue=translation)\n\n # Add the environmental map lighting\n root = addEnv(root, envmapName, 1)\n rootObj = addEnv(rootObj, envmapName, 1)\n rootBkg = addEnv(rootBkg, envmapName, 1)\n\n # Add the camera\n root = addSensor(root, fovValue, imWidth, imHeight, sampleCount)\n rootObj = addSensor(rootObj, fovValue, imWidth, imHeight, sampleCount)\n rootBkg = addSensor(rootBkg, fovValue, imWidth, imHeight, sampleCount)\n\n xmlString = transformToXml(root)\n xmlStringObj = transformToXml(rootObj)\n xmlStringBkg = transformToXml(rootBkg)\n\n with open(xmlName, 'w') as xmlOut:\n xmlOut.write(xmlString)\n with open(xmlName.replace('.xml', '_obj.xml'), 'w') as xmlOut:\n xmlOut.write(xmlStringObj)\n with open(xmlName.replace('.xml', '_bkg.xml'), 'w') as xmlOut:\n xmlOut.write(xmlStringBkg)\n\n\n# Code for Rotating the Envmap\ndef angleToUV(theta, phi):\n u = (phi + np.pi) / 2 / np.pi\n v = 1 - theta / np.pi\n return u, v\n\n\ndef uvToEnvmap(envmap, u, v):\n height, width = envmap.shape[0], envmap.shape[1]\n c, r = u * (width - 1), (1 - v) * (height - 1)\n cs, rs = int(c), int(r)\n ce = min(width - 1, cs + 1)\n re = min(height - 1, rs + 1)\n wc, wr = c - cs, r - rs\n color1 = (1 - wc) * envmap[rs, cs, :] + wc * envmap[rs, ce, :]\n color2 = (1 - wc) * envmap[re, cs, :] + wc * envmap[re, ce, :]\n color = (1 - wr) * color1 + wr * color2\n return color\n\n\n@timeit(PATH_LOG_GEN)\ndef rotateEnvmap_bkq(envmap, vn):\n up = np.array([0, 1, 0], dtype=np.float32)\n z = vn\n z = z / np.sqrt(np.sum(z * z))\n x = np.cross(up, z)\n x = x / np.sqrt(np.sum(x * x))\n y = np.cross(z, x)\n y = y / np.sqrt(np.sum(y * y))\n\n # x = np.asarray([x[2], x[0], x[1]], dtype = np.float32 )\n # y = np.asarray([y[2], y[0], y[1]], dtype = np.float32 )\n # z = np.asarray([z[2], z[0], z[1]], dtype = np.float32 )\n x, y, z = x[np.newaxis, :], y[np.newaxis, :], z[np.newaxis, :]\n\n R = np.concatenate([x, y, z], axis=0)\n rx, ry, rz = R[:, 0], R[:, 1], R[:, 2]\n print(R)\n\n envmapRot = np.zeros(envmap.shape, dtype=np.float32)\n height, width = envmapRot.shape[0], envmapRot.shape[1]\n for r in range(0, height):\n for c in range(0, width):\n theta = r / float(height - 1) * np.pi\n phi = (c / float(width) * np.pi * 2 - np.pi)\n z = np.sin(theta) * np.cos(phi)\n x = np.sin(theta) * np.sin(phi)\n y = np.cos(theta)\n coord = x * rx + y * ry + z * rz\n nx, ny, nz = coord[0], coord[1], coord[2]\n thetaNew = np.arccos(nz)\n nx = nx / (np.sqrt(1 - nz * nz) + 1e-12)\n ny = ny / (np.sqrt(1 - nz * nz) + 1e-12)\n nx = np.clip(nx, -1, 1)\n ny = np.clip(ny, -1, 1)\n nz = np.clip(nz, -1, 1)\n phiNew = np.arccos(nx)\n if ny < 0:\n phiNew = - phiNew\n u, v = angleToUV(thetaNew, phiNew)\n color = uvToEnvmap(envmap, u, v)\n envmapRot[r, c, :] = color\n\n return envmapRot\n\n\[email protected](nopython=True, parallel=True)\ndef rotate_OPT_NUMBA(envmap, R):\n rx, ry, rz = R[:, 0], R[:, 1], R[:, 2]\n envmapRot = np.zeros(envmap.shape, dtype=np.float32)\n height, width = envmapRot.shape[0], envmapRot.shape[1]\n for r in range(0, height):\n for c in range(0, width):\n theta = r / float(height - 1) * np.pi\n phi = (c / float(width) * np.pi * 2 - np.pi)\n z = np.sin(theta) * np.cos(phi)\n x = np.sin(theta) * np.sin(phi)\n y = np.cos(theta)\n coord = x * rx + y * ry + z * rz\n nx, ny, nz = coord[0], coord[1], coord[2]\n thetaNew = np.arccos(nz)\n nx = nx / (np.sqrt(1 - nz * nz) + 1e-12)\n ny = ny / (np.sqrt(1 - nz * nz) + 1e-12)\n # nx = np.clip(nx, -1, 1)\n # ny = np.clip(ny, -1, 1)\n # nz = np.clip(nz, -1, 1)\n phiNew = np.arccos(nx)\n if ny < 0:\n phiNew = - phiNew\n\n u = (phiNew + np.pi) / 2 / np.pi\n v = 1 - thetaNew / np.pi\n\n _c, _r = u * (width - 1), (1 - v) * (height - 1)\n _cs, _rs = int(_c), int(_r)\n _ce = min(width - 1, _cs + 1)\n _re = min(height - 1, _rs + 1)\n _wc, _wr = _c - _cs, _r - _rs\n _color1 = (1 - _wc) * envmap[_rs, _cs, :] + _wc * envmap[_rs, _ce, :]\n _color2 = (1 - _wc) * envmap[_re, _cs, :] + _wc * envmap[_re, _ce, :]\n color = (1 - _wr) * _color1 + _wr * _color2\n\n envmapRot[r, c, :] = color\n\n return envmapRot\n\n\n@timeit(PATH_LOG_GEN)\ndef rotateEnvmap_OPT_NUMBA(envmap, vn):\n up = np.array([0, 1, 0], dtype=np.float32)\n z = vn\n z = z / np.sqrt(np.sum(z * z))\n x = np.cross(up, z)\n x = x / np.sqrt(np.sum(x * x))\n y = np.cross(z, x)\n y = y / np.sqrt(np.sum(y * y))\n x, y, z = x[np.newaxis, :], y[np.newaxis, :], z[np.newaxis, :]\n R = np.concatenate([x, y, z], axis=0)\n print(R)\n\n return rotate_OPT_NUMBA(envmap, R)\n\n\ndef rotate_OPT_MATRIX(envmap, height, width, _rs, _cs, _re, _ce, _wr, _wc, envmapRot):\n\n one_sub_wc = 1 - _wc\n one_sub_wr = 1 - _wr\n\n envmap_rs_cs = np.empty(shape=envmap.shape)\n envmap_rs_ce = np.empty(shape=envmap.shape)\n envmap_re_cs = np.empty(shape=envmap.shape)\n envmap_re_ce = np.empty(shape=envmap.shape)\n\n for r in range(0, height):\n for c in range(0, width):\n envmap_rs_cs[r, c, :] = envmap[_rs[r, c], _cs[r, c], :]\n envmap_rs_ce[r, c, :] = envmap[_rs[r, c], _ce[r, c], :]\n envmap_re_cs[r, c, :] = envmap[_re[r, c], _cs[r, c], :]\n envmap_re_ce[r, c, :] = envmap[_re[r, c], _ce[r, c], :]\n\n for i in range(3):\n _color1 = one_sub_wc * envmap_rs_cs[:, :, i] + _wc * envmap_rs_ce[:, :, i]\n _color2 = one_sub_wc * envmap_re_cs[:, :, i] + _wc * envmap_re_ce[:, :, i]\n envmapRot[:, :, i] = one_sub_wr * _color1 + _wr * _color2\n\n # for r in range(0, height):\n # for c in range(0, width):\n # _color1 = one_sub_wc[r, c] * envmap[_rs[r, c], _cs[r, c], :] + _wc[r, c] * envmap[_rs[r, c], _ce[r, c], :]\n # _color2 = one_sub_wc[r, c] * envmap[_re[r, c], _cs[r, c], :] + _wc[r, c] * envmap[_re[r, c], _ce[r, c], :]\n # color = one_sub_wr[r, c] * _color1 + _wr[r, c] * _color2\n # envmapRot[r, c, :] = color\n\n return envmapRot\n\n\n@timeit(PATH_LOG_GEN)\ndef rotateEnvmap_OPT_MATRIX(envmap, vn):\n envmapRot = np.zeros(envmap.shape, dtype=np.float32)\n\n up = np.array([0, 1, 0], dtype=np.float32)\n z = vn\n z = z / np.sqrt(np.sum(z * z))\n x = np.cross(up, z)\n x = x / np.sqrt(np.sum(x * x))\n y = np.cross(z, x)\n y = y / np.sqrt(np.sum(y * y))\n x, y, z = x[np.newaxis, :], y[np.newaxis, :], z[np.newaxis, :]\n R = np.concatenate([x, y, z], axis=0)\n print(R)\n\n rx, ry, rz = R[:, 0], R[:, 1], R[:, 2]\n height, width = envmap.shape[0], envmap.shape[1]\n\n theta = np.arange(height) / float(height - 1) * np.pi\n phi = np.arange(width) / float(width) * np.pi * 2 - np.pi\n theta = np.tile(theta.reshape(-1, 1), (1, width))\n phi = np.tile(phi.T, (height, 1))\n\n z = np.sin(theta) * np.cos(phi)\n x = np.sin(theta) * np.sin(phi)\n y = np.cos(theta)\n\n nx = x * rx[0] + y * ry[0] + z * rz[0]\n ny = x * rx[1] + y * ry[1] + z * rz[1]\n nz = x * rx[2] + y * ry[2] + z * rz[2]\n\n nx = nx / (np.sqrt(1 - nz * nz) + 1e-12)\n ny = ny / (np.sqrt(1 - nz * nz) + 1e-12)\n\n nx = np.clip(nx, -1, 1)\n ny = np.clip(ny, -1, 1)\n nz = np.clip(nz, -1, 1)\n\n phiNew = np.arccos(nx)\n phiNew[ny < 0] = - phiNew[ny < 0]\n thetaNew = np.arccos(nz)\n\n u = (phiNew + np.pi) / 2 / np.pi\n v = 1 - thetaNew / np.pi\n\n _c, _r = u * (width - 1), (1 - v) * (height - 1)\n _cs, _rs = _c.astype(int), _r.astype(int)\n _ce, _re = _cs.copy() + 1, _rs.copy() + 1\n _ce[_ce > width - 1] = width - 1\n _re[_re > height - 1] = height - 1\n _wc, _wr = _c - _cs, _r - _rs\n\n return rotate_OPT_MATRIX(envmap, height, width, _rs, _cs, _re, _ce, _wr, _wc, envmapRot)\n\n\ndef rotate_OPT_MATRIX_NE(envmap, height, width, _rs, _cs, _re, _ce, _wr, _wc, envmapRot):\n\n one_sub_wc = 1 - _wc\n one_sub_wr = 1 - _wr\n\n envmap_rs_cs = np.empty(shape=envmap.shape)\n envmap_rs_ce = np.empty(shape=envmap.shape)\n envmap_re_cs = np.empty(shape=envmap.shape)\n envmap_re_ce = np.empty(shape=envmap.shape)\n\n for r in range(0, height):\n for c in range(0, width):\n envmap_rs_cs[r, c, :] = envmap[_rs[r, c], _cs[r, c], :]\n envmap_rs_ce[r, c, :] = envmap[_rs[r, c], _ce[r, c], :]\n envmap_re_cs[r, c, :] = envmap[_re[r, c], _cs[r, c], :]\n envmap_re_ce[r, c, :] = envmap[_re[r, c], _ce[r, c], :]\n\n for i in range(3):\n _color1 = one_sub_wc * envmap_rs_cs[:, :, i] + _wc * envmap_rs_ce[:, :, i]\n _color2 = one_sub_wc * envmap_re_cs[:, :, i] + _wc * envmap_re_ce[:, :, i]\n envmapRot[:, :, i] = ne.evaluate(\"one_sub_wr * _color1 + _wr * _color2\")\n\n # for r in range(0, height):\n # for c in range(0, width):\n # _color1 = one_sub_wc[r, c] * envmap[_rs[r, c], _cs[r, c], :] + _wc[r, c] * envmap[_rs[r, c], _ce[r, c], :]\n # _color2 = one_sub_wc[r, c] * envmap[_re[r, c], _cs[r, c], :] + _wc[r, c] * envmap[_re[r, c], _ce[r, c], :]\n # color = one_sub_wr[r, c] * _color1 + _wr[r, c] * _color2\n # envmapRot[r, c, :] = color\n\n return envmapRot\n\n\n@timeit(PATH_LOG_GEN)\ndef rotateEnvmap_OPT_MATRIX_NE(envmap, vn):\n envmapRot = np.zeros(envmap.shape, dtype=np.float32)\n\n up = np.array([0, 1, 0], dtype=np.float32)\n z = vn\n z = z / np.sqrt(np.sum(z * z))\n x = np.cross(up, z)\n x = x / np.sqrt(np.sum(x * x))\n y = np.cross(z, x)\n y = y / np.sqrt(np.sum(y * y))\n x, y, z = x[np.newaxis, :], y[np.newaxis, :], z[np.newaxis, :]\n R = np.concatenate([x, y, z], axis=0)\n print(R)\n\n rx, ry, rz = R[:, 0], R[:, 1], R[:, 2]\n height, width = envmap.shape[0], envmap.shape[1]\n\n theta = np.arange(height) / float(height - 1) * np.pi\n phi = np.arange(width) / float(width) * np.pi * 2 - np.pi\n theta = np.tile(theta.reshape(-1, 1), (1, width))\n phi = np.tile(phi.T, (height, 1))\n\n z = np.sin(theta) * np.cos(phi)\n x = np.sin(theta) * np.sin(phi)\n y = np.cos(theta)\n\n rx0, rx1, rx2 = rx[0], rx[1], rx[2]\n ry0, ry1, ry2 = ry[0], ry[1], ry[2]\n rz0, rz1, rz2 = rz[0], rz[1], rz[2]\n\n nx = ne.evaluate(\"x * rx0 + y * ry0 + z * rz0\")\n ny = ne.evaluate(\"x * rx1 + y * ry1 + z * rz1\")\n nz = ne.evaluate(\"x * rx2 + y * ry2 + z * rz2\")\n\n nx = nx / (np.sqrt(1 - nz * nz) + 1e-12)\n ny = ny / (np.sqrt(1 - nz * nz) + 1e-12)\n\n nx = np.clip(nx, -1, 1)\n ny = np.clip(ny, -1, 1)\n nz = np.clip(nz, -1, 1)\n\n phiNew = np.arccos(nx)\n phiNew[ny < 0] = - phiNew[ny < 0]\n thetaNew = np.arccos(nz)\n\n pi = np.pi\n u = ne.evaluate(\"(phiNew + pi) / 2 / pi\")\n v = ne.evaluate(\"1 - thetaNew / pi\")\n\n _c, _r = u * (width - 1), (1 - v) * (height - 1)\n _cs, _rs = _c.astype(int), _r.astype(int)\n _ce, _re = _cs.copy() + 1, _rs.copy() + 1\n _ce[_ce > width - 1] = width - 1\n _re[_re > height - 1] = height - 1\n _wc, _wr = _c - _cs, _r - _rs\n\n return rotate_OPT_MATRIX(envmap, height, width, _rs, _cs, _re, _ce, _wr, _wc, envmapRot)\n\n\[email protected]()\ndef rotate_OPT_CUDA(envmap, height, width, _rs, _cs, _re, _ce, _wr, _wc, envmapRot):\n r, c = cuda.grid(2)\n for i in range(3):\n _color1 = (1 - _wc[r, c]) * envmap[_rs[r, c], _cs[r, c], i] + _wc[r, c] * envmap[_rs[r, c], _ce[r, c], i]\n _color2 = (1 - _wc[r, c]) * envmap[_re[r, c], _cs[r, c], i] + _wc[r, c] * envmap[_re[r, c], _ce[r, c], i]\n color = (1 - _wr[r, c]) * _color1 + _wr[r, c] * _color2\n envmapRot[r, c, i] = color\n\n\n@timeit(PATH_LOG_GEN)\ndef rotateEnvmap_OPT_CUDA(envmap, vn):\n envmapRot = np.zeros(envmap.shape, dtype=np.float32)\n\n time1 = time.time()\n\n up = np.array([0, 1, 0], dtype=np.float32)\n z = vn\n z = z / np.sqrt(np.sum(z * z))\n x = np.cross(up, z)\n x = x / np.sqrt(np.sum(x * x))\n y = np.cross(z, x)\n y = y / np.sqrt(np.sum(y * y))\n x, y, z = x[np.newaxis, :], y[np.newaxis, :], z[np.newaxis, :]\n R = np.concatenate([x, y, z], axis=0)\n print(R)\n\n rx, ry, rz = R[:, 0], R[:, 1], R[:, 2]\n height, width = envmap.shape[0], envmap.shape[1]\n\n theta = np.arange(height) / float(height - 1) * np.pi\n phi = np.arange(width) / float(width) * np.pi * 2 - np.pi\n theta = np.tile(theta.reshape(-1, 1), (1, width))\n phi = np.tile(phi.T, (height, 1))\n\n z = np.sin(theta) * np.cos(phi)\n x = np.sin(theta) * np.sin(phi)\n y = np.cos(theta)\n\n nx = x * rx[0] + y * ry[0] + z * rz[0]\n ny = x * rx[1] + y * ry[1] + z * rz[1]\n nz = x * rx[2] + y * ry[2] + z * rz[2]\n nx = nx / (np.sqrt(1 - nz * nz) + 1e-12)\n ny = ny / (np.sqrt(1 - nz * nz) + 1e-12)\n nx = np.clip(nx, -1, 1)\n ny = np.clip(ny, -1, 1)\n nz = np.clip(nz, -1, 1)\n\n phiNew = np.arccos(nx)\n phiNew[ny < 0] = - phiNew[ny < 0]\n thetaNew = np.arccos(nz)\n\n u = (phiNew + np.pi) / 2 / np.pi\n v = 1 - thetaNew / np.pi\n\n _c, _r = u * (width - 1), (1 - v) * (height - 1)\n _cs, _rs = _c.astype(int), _r.astype(int)\n _ce, _re = _cs.copy() + 1, _rs.copy() + 1\n _ce[_ce > width - 1] = width - 1\n _re[_re > height - 1] = height - 1\n _wc, _wr = _c - _cs, _r - _rs\n\n print(\"before CUDA:\", time.time() - time1)\n\n envmap_d = cuda.to_device(envmap)\n\n print(\"before CUDA IO:\", time.time() - time1)\n\n _rs_d, _cs_d = cuda.to_device(_rs), cuda.to_device(_cs)\n _re_d, _ce_d = cuda.to_device(_re), cuda.to_device(_ce)\n _wr_d, _wc_d = cuda.to_device(_wr), cuda.to_device(_wc)\n\n print(\"before CUDA IO:\", time.time() - time1)\n\n height_d, width_d = cuda.to_device(envmap.shape[0]), cuda.to_device(envmap.shape[1])\n envmapRot = cuda.device_array(shape=envmap.shape, dtype=np.float32)\n\n threads_per_block = (16, 16)\n blocks_per_grid_x = int(math.ceil(envmap.shape[0] / threads_per_block[0]))\n blocks_per_grid_y = int(math.ceil(envmap.shape[1] / threads_per_block[1]))\n blocksPerGrid = (blocks_per_grid_x, blocks_per_grid_y)\n\n rotate_OPT_CUDA[blocksPerGrid, threads_per_block](\n envmap_d, height_d, width_d, _rs_d, _cs_d, _re_d, _ce_d, _wr_d, _wc_d, envmapRot)\n\n return envmapRot.copy_to_host()\n\n\n\n" }, { "alpha_fraction": 0.5808619856834412, "alphanum_fraction": 0.6378015279769897, "avg_line_length": 26.78022003173828, "blob_id": "234c419a1caf6991fef05188673a081f2dd3788d", "content_id": "096ee53dabcfacbfd28fb19cff1da778e6db4da6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2529, "license_type": "no_license", "max_line_length": 88, "num_lines": 91, "path": "/estimate.sh", "repo_name": "FUJI-W/lightAR", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nhelp() {\n echo \"Usage:\"\n echo \" run.sh [-i INPUT_IMAGE] [-o OUTPUT_PATH] [-m MODE]\"\n echo \"\"\n echo \"Description:\"\n echo \" INPUT_IMAGE, the path to input image\"\n echo \" OUTPUT_PATH, the path to store results\"\n echo \" MODE, the level of estimate net (0, 1, 2)\"\n echo \"\"\n}\n\nwhile getopts \"m:i:o:h:w:\" OPT; do\n case $OPT in\n m) MODE=\"$OPTARG\";;\n i) INPUT_IMAGE=\"$OPTARG\";;\n o) OUTPUT_PATH=\"$OPTARG\";;\n h) HEIGHT=\"$OPTARG\";;\n w) WIDTH=\"$OPTARG\";;\n ?) help ;;\n esac\ndone\n\n#if [ $# != 3 ]; then\n# echo \"Wrong Input! Try use -h to see the help.\"\n# exit 1\n#fi\n\nif [ -z \"$MODE\" ]; then\n MODE=\"1\"\nfi\n\nif [ -z \"$INPUT_IMAGE\" ]; then\n INPUT_IMAGE=\"inputs/im.png\"\nfi\n\nif [ -z \"$OUTPUT_PATH\" ]; then\n OUTPUT_PATH=\"outputs\"\nfi\n\nif [ -z \"$HEIGHT\" ]; then\n HEIGHT=\"480\"\nfi\n\nif [ -z \"$WIDTH\" ]; then\n WIDTH=\"640\"\nfi\n\necho \"$MODE\"\necho \"$INPUT_IMAGE\"\necho \"$OUTPUT_PATH\"\n\nif [ \"$MODE\" = \"0\" ]; then\n python ./nets/test.py --cuda \\\n --mode $MODE \\\n --imPath \"$INPUT_IMAGE\" \\\n --outPath \"$OUTPUT_PATH\" \\\n --isLight \\\n --level 1 \\\n --experiment0 ./nets/models/check_cascade0_w320_h240 --nepoch0 14 \\\n --experimentLight0 ./nets/models/check_cascadeLight0_sg12_offset1 --nepochLight0 10 \\\n --imHeight0 $HEIGHT --imWidth0 $WIDTH\nelif [ \"$MODE\" = \"1\" ]; then\n python ./nets/test.py --cuda \\\n --mode $MODE \\\n --imPath \"$INPUT_IMAGE\" \\\n --outPath \"$OUTPUT_PATH\" \\\n --isLight \\\n --level 2 \\\n --experiment0 ./nets/models/check_cascade0_w320_h240 --nepoch0 14 \\\n --experimentLight0 ./nets/models/check_cascadeLight0_sg12_offset1 --nepochLight0 10 \\\n --experiment1 ./nets/models/check_cascade1_w320_h240 --nepoch1 7 \\\n --experimentLight1 ./nets/models/check_cascadeLight1_sg12_offset1 --nepochLight1 10 \\\n --imHeight0 $HEIGHT --imWidth0 $WIDTH --imHeight1 $HEIGHT --imWidth1 $WIDTH\nelse\n echo \"22222222\"\n python ./nets/test.py --cuda \\\n --mode $MODE \\\n --imPath \"$INPUT_IMAGE\" \\\n --outPath \"$OUTPUT_PATH\" \\\n --isLight --isBS \\\n --level 2 \\\n --experiment0 ./nets/models/check_cascade0_w320_h240 --nepoch0 14 \\\n --experimentLight0 ./nets/models/check_cascadeLight0_sg12_offset1 --nepochLight0 10 \\\n --experimentBS0 ./nets/models/checkBs_cascade0_w320_h240 \\\n --experiment1 ./nets/models/check_cascade1_w320_h240 --nepoch1 7 \\\n --experimentLight1 ./nets/models/check_cascadeLight1_sg12_offset1 --nepochLight1 10 \\\n --experimentBS1 ./nets/models/checkBs_cascade1_w320_h240 \\\n --imHeight0 $HEIGHT --imWidth0 $WIDTH --imHeight1 $HEIGHT --imWidth1 $WIDTH\nfi\n\n" }, { "alpha_fraction": 0.3361188471317291, "alphanum_fraction": 0.35004642605781555, "avg_line_length": 34.119564056396484, "blob_id": "9d0d052d8ff7e7424953e5ae1913bd2db69519a6", "content_id": "1692a2c3d3b5c1dc3385ab90de59d73831854e35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3251, "license_type": "no_license", "max_line_length": 118, "num_lines": 92, "path": "/app.py", "repo_name": "FUJI-W/lightAR", "src_encoding": "UTF-8", "text": "import dash_html_components as html\nimport dash_core_components as dcc\nimport dash_bootstrap_components as dbc\nfrom dash.dependencies import Input, Output, State\n\nfrom views.index import index_page\nfrom views.data import data_page\n\nfrom server import app\n\napp.layout = html.Div(\n [\n dcc.Location(id='url'),\n dbc.Navbar(\n [\n html.A(\n dbc.Row(\n [\n dbc.Col(html.Img(src=app.get_asset_url(\"home.png\"), height=\"60px\"),\n width={'size': 2, 'offset': 3}),\n dbc.Col(\n dbc.NavbarBrand(\"ARLight\", className=\"ml-1 mt-1\",\n style={'color': 'black',\n 'font-size': '1.6em',\n 'font-weight': 'bold',\n 'font-family': 'ui-monospace'}),\n width={'size': 2, 'offset': 2}\n ),\n ],\n align=\"center\",\n no_gutters=True,\n ),\n href=\"http://ccfcv.ccf.org.cn/ccfcv/wyhdt/dyfc/2018ndwyfc/2020-03-04/695836.shtml\",\n style={'text-decoration': 'none'}\n ),\n\n dbc.Row(\n [\n dbc.Col(dbc.NavLink('Home', href='/', active=\"exact\", className=\"mt-1\",\n style={'color': 'black',\n 'font-size': '1.2em',\n 'font-weight': 'bold',\n 'font-family': 'ui-monospace'}\n )),\n dbc.Col(dbc.NavLink('Data', href='/data', active=\"exact\", className=\"mt-1\", id=\"navlink-data\",\n style={'color': 'black',\n 'font-size': '1.2em',\n 'font-weight': 'bold',\n 'font-family': 'ui-monospace'}\n )\n )\n ],\n align=\"center\",\n no_gutters=True,\n className=\"ml-auto mr-4 flex-nowrap mt-6 md-0\",\n )\n ],\n color=\"#EDEFEB\",\n # color=\"#293a66\",\n # dark=True,\n style={'margin-top': '10px'}\n ),\n\n html.Div(\n id='page-content',\n style={\n 'flex': 'auto'\n }\n ),\n ],\n style={\n\n }\n)\n\n\[email protected](\n Output('page-content', 'children'),\n Input('url', 'pathname')\n)\ndef render_page_content(pathname):\n if pathname == '/':\n return index_page\n\n elif pathname == '/data':\n return data_page\n\n return html.H1('您访问的页面不存在!')\n\n\nif __name__ == '__main__':\n app.run_server(debug=False)\n" }, { "alpha_fraction": 0.5812647342681885, "alphanum_fraction": 0.600652277469635, "avg_line_length": 34.378204345703125, "blob_id": "bdc32413a69e4a1037beac59040089949ed25ecc", "content_id": "af84d47cd00bd18ff709f3b5401fe67e1fb5111e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5519, "license_type": "no_license", "max_line_length": 108, "num_lines": 156, "path": "/views/data_callbks.py", "repo_name": "FUJI-W/lightAR", "src_encoding": "UTF-8", "text": "import dash\nimport dash_html_components as html\nimport dash_bootstrap_components as dbc\nimport dash_core_components as dcc\nimport dash_uploader as du\nimport dash_daq as daq\n\nfrom dash.dependencies import Input, Output, State\nfrom server import app\n\nfrom PIL import Image, ImageFilter, ImageDraw, ImageEnhance\nimport plotly.express as px\nimport pathlib\nimport os.path as osp\nimport numpy as np\nimport cv2\n\nfrom setting import *\n\n\ndef make_data_tooltip(_label, _target, _placement='top'):\n return dbc.Tooltip(\n _label, target=_target, placement=_placement,\n hide_arrow=True,\n style={\"background-color\": 'rgba(75, 144, 144, 0.2)', \"color\": 'rgba(75, 144, 144, 1)'}\n )\n\n\ndata_graph_config = {'displayModeBar': True, 'scrollZoom': False, 'displaylogo': False}\n\n\ndef get_data_graph_figure(_path, _is_gray=False, _height=300, _margin=None):\n if not osp.isfile(_path):\n return None\n _img = Image.open(_path)\n return get_data_graph_image_figure(_img, _is_gray, _height, _margin)\n\n\ndef get_data_graph_image_figure(_img, _is_gray=False, _height=300, _margin=None):\n if _margin is None:\n _margin = dict(l=0, r=0, b=0, t=30)\n if _is_gray:\n fig = px.imshow(_img, color_continuous_scale='gray')\n else:\n fig = px.imshow(_img)\n\n fig.update_layout(\n # autosize=True,\n height=_height,\n margin=_margin,\n paper_bgcolor='#f9f9f8',\n plot_bgcolor='#f9f9f8',\n )\n fig.update_xaxes(showticklabels=False)\n fig.update_yaxes(showticklabels=False)\n if _is_gray:\n fig.update_layout(\n coloraxis_showscale=False,\n )\n return fig\n\n\ndef get_envmap_figure(_path):\n def writeEnvToFile(envmap, envName, nrows=12, ncols=8, envHeight=8, envWidth=16, gap=1):\n envRow, envCol = envmap.shape[0], envmap.shape[1]\n\n interY = int(envRow / nrows)\n interX = int(envCol / ncols)\n\n lnrows = len(np.arange(0, envRow, interY))\n lncols = len(np.arange(0, envCol, interX))\n\n lenvHeight = lnrows * (envHeight + gap) + gap\n lenvWidth = lncols * (envWidth + gap) + gap\n\n envmapLarge = np.zeros([lenvHeight, lenvWidth, 3], dtype=np.float32) + 1.0\n for r in range(0, envRow, interY):\n for c in range(0, envCol, interX):\n rId = int(r / interY)\n cId = int(c / interX)\n\n rs = rId * (envHeight + gap)\n cs = cId * (envWidth + gap)\n envmapLarge[rs: rs + envHeight, cs: cs + envWidth, :] = envmap[r, c, :, :, :]\n\n envmapLarge = np.clip(envmapLarge, 0, 1)\n envmapLarge = (255 * (envmapLarge ** (1.0 / 2.2))).astype(np.uint8)\n cv2.imwrite(envName, envmapLarge[:, :, ::-1])\n return envmapLarge[:, :, ::-1]\n\n if not osp.isfile(_path):\n return None\n npz = np.load(_path)['env']\n _img = writeEnvToFile(envmap=npz, envName=osp.join(PATH_IN, 'envmap.png'),\n nrows=npz.shape[0], ncols=npz.shape[1],\n envHeight=npz.shape[2], envWidth=npz.shape[3])\n return get_data_graph_image_figure(_img, _height=350)\n\n\ndef get_rgbe_figure(_path):\n if not osp.isfile(_path):\n return None\n hdr = cv2.imread(_path, cv2.IMREAD_ANYDEPTH)\n hdr = np.maximum(hdr, 0)\n ldr = hdr ** (1.0 / 2.2)\n ldr = np.minimum(ldr * 255, 255)\n ldr = cv2.cvtColor(ldr, cv2.COLOR_BGR2RGB)\n return get_data_graph_image_figure(ldr, _height=245)\n\n\[email protected](\n [\n Output('graph-input', 'figure'),\n Output('graph-light', 'figure'),\n Output('graph-normal', 'figure'),\n Output('graph-rough', 'figure'),\n Output('graph-albedo', 'figure'),\n Output('graph-output', 'figure'),\n Output('graph-scene-rgbe', 'figure'),\n Output('graph-obj-mask', 'figure'),\n Output('graph-bkg-rgbe', 'figure'),\n Output('graph-scene-mask', 'figure'),\n ],\n [\n Input('navlink-data', 'n_clicks')\n ],\n [\n State('graph-input', 'figure'),\n State('graph-light', 'figure'),\n State('graph-normal', 'figure'),\n State('graph-rough', 'figure'),\n State('graph-albedo', 'figure'),\n State('graph-output', 'figure'),\n State('graph-scene-rgbe', 'figure'),\n State('graph-obj-mask', 'figure'),\n State('graph-bkg-rgbe', 'figure'),\n State('graph-scene-mask', 'figure'),\n ],\n)\ndef update_data_page(\n n, input, light, normal, rough, albedo,\n output, scene_rgbe, obj_mask, bkg_rgbe, scene_mask\n):\n if n is not None:\n input = get_data_graph_figure(Image.open(osp.join(PATH_IN, 'im.png')))\n light = get_envmap_figure(osp.join(PATH_IN, 'envmap.png.npz'))\n normal = get_data_graph_figure(Image.open(osp.join(PATH_IN, 'normal.png')))\n rough = get_data_graph_figure(Image.open(osp.join(PATH_IN, 'rough.png')), True)\n albedo = get_data_graph_figure(Image.open(osp.join(PATH_IN, 'albedo.png')))\n\n output = get_data_graph_figure(Image.open(osp.join(PATH_OUT, 'im.png')), _height=500)\n scene_rgbe = get_rgbe_figure(osp.join(PATH_OUT, 'scene_1.rgbe'))\n obj_mask = get_data_graph_figure(Image.open(osp.join(PATH_OUT, 'scene_objmask_1.png')), _height=245)\n bkg_rgbe = get_rgbe_figure(osp.join(PATH_OUT, 'scene_bkg_1.rgbe'))\n scene_mask = get_data_graph_figure(Image.open(osp.join(PATH_OUT, 'scenemask_1.png')), _height=245)\n return input, light, normal, rough, albedo, output, scene_rgbe, obj_mask, bkg_rgbe, scene_mask\n" }, { "alpha_fraction": 0.5089948177337646, "alphanum_fraction": 0.5416600704193115, "avg_line_length": 37.29003143310547, "blob_id": "3e5d38ac471fbf4403cbffb33be31c7f7c1a47c4", "content_id": "390883dac00162d9aec6720e2a19a00a95d052cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12674, "license_type": "no_license", "max_line_length": 115, "num_lines": 331, "path": "/paint.py", "repo_name": "FUJI-W/lightAR", "src_encoding": "UTF-8", "text": "import math\nimport os\n\nimport numpy as np\n\nos.environ['NUMEXPR_MAX_THREADS'] = '40'\n\nimport scipy.io\nfrom PIL import Image\nfrom setting import *\nfrom generate import *\nfrom tools import *\n\n\n@timeit(PATH_LOG)\ndef estimate_scene(_root, _photo, _h, _w, _mode=ESTIMATE_MODE):\n os.system('sh estimate.sh '\n ' -i inout/inputs' + _root + '/' + _photo +\n ' -o inout/inputs' + _root +\n ' -m ' + str(_mode) +\n ' -h ' + str(_h) +\n ' -w ' + str(_w)\n )\n\n\ndef pick_plane_points(_img):\n # plt.ion()\n plt.imshow(_img)\n _x, _y = zip(*plt.ginput(4))\n plt.close()\n _x = np.array([_x]).T\n _y = np.array([_y]).T\n return _x, _y\n\n\n@timeit(PATH_LOG)\ndef generate_mask(_x, _y, _h, _w):\n _grid_x, _grid_y = np.meshgrid(range(1, _w + 1), range(1, _h + 1))\n _mask = np.ones((_h, _w))\n for i in range(4):\n _seg = [_x[(i + 1) % 4] - _x[i], _y[(i + 1) % 4] - _y[i]]\n _mask = np.multiply(_mask, ((_grid_x - _x[i]) * _seg[1] - (_grid_y - _y[i]) * _seg[0]) > 0)\n return _mask\n\n\n@timeit(PATH_LOG)\ndef generate_3d_points(_x, _y, _mask):\n _normal = np.load(PATH_NORMAL)\n _h, _w = _normal.shape[0], _normal.shape[1]\n _normal_x = _normal[:, :, 0]\n _normal_y = _normal[:, :, 1]\n _normal_z = _normal[:, :, 2]\n # TODO: whether erode or not\n _mask_eroded = _mask\n # _mask_eroded = cv2.erode(mask, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)))\n _normal_x = np.mean(_normal_x[_mask_eroded == 1])\n _normal_y = np.mean(_normal_y[_mask_eroded == 1])\n _normal_z = np.mean(_normal_z[_mask_eroded == 1])\n _vn = np.array([[_normal_x], [_normal_y], [_normal_z]])\n _vn = _vn / np.sum(np.multiply(_vn, _vn)) ** 0.5\n _vn = np.multiply(_vn, [[-1], [1], [-1]])\n\n _atan_fov_x = math.tan(math.radians(FOV_X / 2.0))\n _atan_fov_y = _atan_fov_x / _w * _h\n _v = np.c_[(((_w + 1) / 2.0) - _x) / ((_w - 1) / 2.0) * _atan_fov_x,\n (((_h + 1) / 2.0) - _y) / ((_h - 1) / 2.0) * _atan_fov_y,\n np.ones((4, 1))]\n for i in range(1, 4):\n d = (_v[0] @ _vn) / (_v[i] @ _vn)\n assert d > 0\n _v[i] = d * _v[i]\n\n _vt = np.c_[(_x - 1) / (_w - 1), (_h - _y) / (_h - 1)]\n\n return _vn, _v, _vt\n\n\n@timeit(PATH_LOG)\ndef output_3d_mesh(_vn, _v, _vt):\n _path_mesh = os.path.join(PATH_OUT, 'mesh.obj') # path to plane mesh\n with open(_path_mesh, 'w') as f:\n for i in range(0, 4):\n f.write('v %.5f %.5f %.5f\\n' % (_v[i][0], _v[i][1], _v[i][2]))\n for i in range(0, 4):\n f.write('vt %.5f %.5f\\n' % (_vt[i][0], _vt[i][1]))\n f.write('vn %.5f %.5f %.5f\\n' % (_vn[0], _vn[1], _vn[2]))\n f.write('f 1/1/1 2/2/1 3/3/1\\n')\n f.write('f 1/1/1 3/3/1 4/4/1\\n')\n f.close()\n\n\ndef pick_obj_point(_x, _y, _h, _w):\n _tx, _ty = np.r_[_x, [_x[0]]], np.r_[_y, [_y[0]]]\n plt.ion()\n _img = np.asarray(Image.open(os.path.join(PATH_IN, PHOTO)).resize((_w, _h), Image.ANTIALIAS))\n plt.imshow(_img)\n plt.plot(_tx, _ty, color='r', linestyle='--')\n plt.show()\n (_obj_x, _obj_y) = plt.ginput(1)[0]\n plt.close()\n return _obj_x, _obj_y\n\n\ndef pick_obj_points(_x, _y, _h, _w, _count=1):\n _tx, _ty = np.r_[_x, [_x[0]]], np.r_[_y, [_y[0]]]\n plt.ion()\n _img = np.asarray(Image.open(os.path.join(PATH_IN, PHOTO)).resize((_w, _h), Image.ANTIALIAS))\n plt.imshow(_img)\n plt.plot(_tx, _ty, color='r', linestyle='--')\n plt.show()\n _obj_points = plt.ginput(_count)\n plt.close()\n return _obj_points\n\n\n@timeit(PATH_LOG)\ndef generate_info(_obj_x, _obj_y, _vn, _v, _h, _w, _scale=SCALE):\n _vImg = [(_obj_x - 1) / (_w - 1), (_obj_y - 1) / (_h - 1)]\n\n _atan_fov_x = math.tan(math.radians(FOV_X / 2.0))\n _atan_fov_y = _atan_fov_x / _w * _h\n _vObj = np.array([(((_w + 1) / 2.0) - _obj_x) / ((_w - 1) / 2.0) * _atan_fov_x,\n (((_h + 1) / 2.0) - _obj_y) / ((_h - 1) / 2.0) * _atan_fov_y,\n 1])\n _d = (_v[0] @ _vn) / (_vObj @ _vn)\n assert _d > 0\n _vObj = _vObj * _d\n\n # TODO: check if it is different from the .m\n # _dist = np.c_[np.linalg.norm(_vObj - _v[0]), np.linalg.norm(_vObj - _v[1])]\n # _scale = SCALE * np.min(_dist)\n _scale = _scale * 0.1\n\n _path_info = os.path.join(PATH_OUT, 'info.mat') # the starting point\n scipy.io.savemat(_path_info, {'vn': _vn, 'vObj': _vObj, 'scale': _scale, 'vImg': _vImg})\n\n\n@timeit(PATH_LOG)\ndef generate_render_xml(_path_obj, _h, _w, _roughness=ROUGHNESS, _diffuse=None):\n if _diffuse is None:\n _diffuse = [COLOR_R, COLOR_G, COLOR_B]\n\n _path_env = PATH_ENV_MAP # path to environmental map\n _path_env_mat_origin = os.path.join(PATH_OUT, 'envOrigin.mat')\n _path_env_mat = os.path.join(PATH_OUT, 'env.mat')\n\n # Load information\n _info = scipy.io.loadmat(os.path.join(PATH_OUT, 'info.mat'))\n _vn, _vObj, _vImg, _scale = _info['vn'], _info['vObj'], _info['vImg'], _info['scale']\n _vn, _vObj, _vImg = _vn.flatten(), _vObj.flatten(), _vImg.flatten()\n _vn = _vn / np.sqrt(np.sum(_vn * _vn))\n\n # Load environmental map\n _env = np.load(_path_env)['env']\n _env_row, _env_col = _env.shape[0], _env.shape[1]\n _rId, _cId = (_env_row - 1) * _vImg[1], (_env_col - 1) * _vImg[0]\n _rId = np.clip(np.round(_rId), 0, _env_row - 1)\n _cId = np.clip(np.round(_cId), 0, _env_col - 1)\n _env = _env[int(_rId), int(_cId), :, :, :]\n # _env = cv2.resize(_env, (2048, 512), interpolation=cv2.INTER_LINEAR)\n _env = cv2.resize(_env, (1024, 256), interpolation=cv2.INTER_LINEAR)\n scipy.io.savemat(_path_env_mat_origin, {'env': np.maximum(_env, 0)})\n # TODO: where the time costs\n # _env_balck = np.zeros([512, 2048, 3], dtype=np.float32)\n _env_balck = np.zeros([256, 1024, 3], dtype=np.float32)\n _env = np.concatenate([_env, _env_balck], axis=0)\n # _env = rotateEnvmap_bkq(_env, _vn)\n # _env = rotateEnvmap_OPT_NUMBA(_env, _vn)\n # _env = rotateEnvmap_OPT_MATRIX(_env, _vn)\n # _env = rotateEnvmap_OPT_MATRIX_NE(_env, _vn)\n _env = rotateEnvmap_OPT_CUDA(_env, _vn)\n scipy.io.savemat(_path_env_mat, {'env': np.maximum(_env, 0)})\n\n # Build the materials for the two shapes\n _shapes = [os.path.join(PATH_OUT, 'mesh.obj'),\n os.path.join('models', _path_obj)]\n _mat1 = mat(texture=tex(diffuseName=PATH_DIFFUSE,\n roughnessName=PATH_ROUGH))\n _mat2 = mat(diffuse=_diffuse, roughness=_roughness)\n _materials = [_mat1, _mat2]\n\n _path_obj = os.path.join('models', _path_obj) # path to the new object mesh\n _mesh_info = scipy.io.loadmat(os.path.splitext(_path_obj)[0] + 'Init.mat')\n _mesh_rotateAxis = _mesh_info.get('meshRotateAxis')[0]\n _mesh_rotateAxis = np.array(_mesh_rotateAxis, dtype=np.float32)\n _mesh_rotateAxis = _mesh_rotateAxis / np.sqrt(np.sum(_mesh_rotateAxis * _mesh_rotateAxis))\n\n _up = np.array([0.0, 1.0, 0.0], dtype=np.float32)\n _rotate_axis = np.cross(_up, _vn)\n if np.sum(_rotate_axis * _rotate_axis) <= 1e-6:\n _rotate_axis = None\n _rotate_angle = None\n else:\n _rotate_axis = _rotate_axis / np.sqrt(np.sum(_rotate_axis * _rotate_axis))\n _rotate_angle = np.arccos(np.sum(_vn * _up))\n\n generateXML(\n shapes=_shapes, materials=_materials,\n\n envmapName=os.path.join(PATH_OUT, 'env.hdr'), xmlName='scene.xml',\n sampleCount=1024, imWidth=_w, imHeight=_h, fovValue=FOV_X,\n\n meshRotateAxis=_mesh_rotateAxis,\n meshRotateAngle=_mesh_info.get('meshRotateAngle')[0],\n meshTranslate=_mesh_info.get('meshTranslate')[0],\n meshScale=_mesh_info.get('meshScale')[0],\n\n rotateAxis=_rotate_axis,\n rotateAngle=_rotate_angle,\n translation=_vObj,\n scale=_scale\n )\n\n\n@timeit(PATH_LOG)\ndef render_img():\n _env = scipy.io.loadmat(os.path.join(PATH_OUT, 'env.mat')).get('env')\n # TODO: Whether flip or not\n # _env = cv2.flip(_env, 0, dst=None)\n cv2.imwrite(os.path.join(PATH_OUT, 'env.hdr'), np.maximum(_env, 0))\n\n # TODO: Change the structure of files\n _xml_file1, _output1 = 'scene.xml', 'scene.rgbe'\n _xml_file2, _output2 = 'scene_obj.xml', 'scene_obj.rgbe'\n _xml_file3, _output3 = 'scene_bkg.xml', 'scene_bkg.rgbe'\n\n os.system(RENDER + ' -f %s -o %s -m %d --gpuIds 2' % (_xml_file1, _output1, 0))\n # os.system(RENDER + ' -f %s -o %s -m %d --gpuIds 2' % (_xml_file2, _output2, 0))\n os.system(RENDER + ' -f %s -o %s -m %d --gpuIds 2' % (_xml_file3, _output3, 0))\n os.system(RENDER + ' -f %s -o %s -m %d --gpuIds 2' % (_xml_file1, _output1, 4))\n os.system(RENDER + ' -f %s -o %s -m %d --gpuIds 2' % (_xml_file2, _output2, 4))\n #os.system(RENDER + ' -f %s -o %s -m %d --gpuIds 2' % (PATH_XML1, PATH_RENDER_OUT1, 0))\n #os.system(RENDER + ' -f %s -o %s -m %d --gpuIds 2' % (PATH_XML3, PATH_RENDER_OUT3, 0))\n #os.system(RENDER + ' -f %s -o %s -m %d --gpuIds 2' % (PATH_XML1, PATH_RENDER_OUT1, 4))\n #os.system(RENDER + ' -f %s -o %s -m %d --gpuIds 2' % (PATH_XML2, PATH_RENDER_OUT2, 4))\n\n\n@timeit(PATH_LOG)\ndef mix_up_img(_h, _w):\n #_hdr1 = cv2.imread(PATH_SCENE_RGBE, cv2.IMREAD_ANYDEPTH)\n #_hdr2 = cv2.imread(PATH_BJG_RGBE, cv2.IMREAD_ANYDEPTH)\n #_mask1 = np.asarray(Image.open(PATH_SCENE_MASK)) / 255.0\n #_mask2 = np.asarray(Image.open(PATH_OBJ_MASK)) / 255.0\n \n _hdr1 = cv2.imread('scene_1.rgbe', cv2.IMREAD_ANYDEPTH)\n _hdr2 = cv2.imread('scene_bkg_1.rgbe', cv2.IMREAD_ANYDEPTH)\n _mask1 = np.asarray(Image.open('scenemask_1.png')) / 255.0\n _mask2 = np.asarray(Image.open('scene_objmask_1.png')) / 255.0\n\n _maskBg = np.maximum(_mask1 - _mask2, 0)\n \n _diff = np.maximum(_hdr1, 1e-10) / np.maximum(_hdr2, 1e-10) * _maskBg\n _diff = np.minimum(_diff * 1.01, 1)\n\n _ldr = cv2.resize(cv2.imread(os.path.join(PATH_IN, PHOTO)) / 255.0, (_w, _h))\n _hdr = _ldr ** 2.2\n\n # TODO: whether erode or not\n _mask1 = cv2.erode(_mask1, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (10, 10)))\n\n _hdr_new = _hdr * (1 - _mask1) + (_hdr * _diff) * _mask1\n _hdr_new = _hdr1 * _mask2 + _hdr_new * (1 - _mask2)\n _hdr_new = np.maximum(_hdr_new, 0)\n _ldr_new = _hdr_new ** (1.0 / 2.2)\n\n return _hdr_new, _ldr_new\n\n\n@timeit(PATH_LOG)\ndef mix_up_img_simple(_h, _w, _mask):\n _hdr_scene = cv2.imread('scene_1.rgbe', cv2.IMREAD_ANYDEPTH)\n _ldr = cv2.resize(cv2.imread(os.path.join(PATH_IN, PHOTO)) / 255.0, (_w, _h))\n _hdr = _ldr ** 2.2\n\n _mask = np.repeat(_mask[:, :, np.newaxis], 3, axis=2)\n _hdr_new = _hdr * (1 - _mask) + _hdr_scene * _mask\n _hdr_new = np.maximum(_hdr_new, 0)\n _ldr_new = _hdr_new ** (1.0 / 2.2)\n\n cv2.imshow(\"\", _ldr_new.astype(np.float64))\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n return _hdr_new, _ldr_new\n\n\ndef get_equal_dis_points(p1, p2, step=1):\n parts = int(max(abs(p1[0]-p2[0]), abs(p1[1]-p2[1])) / step)\n points = list(zip(np.linspace(p1[0], p2[0], parts + 1), np.linspace(p1[1], p2[1], parts + 1)))\n return np.asarray(points).astype(int)\n\n\ndef gui_object_insert(_img_h, _img_w, _obj_name, _obj_x, _obj_y, _offset, _scale, _roughness, _diffuse, _index=-1):\n _x = np.array([[_obj_x - 3 * _offset],\n [_obj_x - _offset],\n [_obj_x + 3 * _offset],\n [_obj_x + _offset]])\n _y = np.array([[_obj_y - _offset],\n [_obj_y + 2 * _offset],\n [_obj_y + _offset],\n [_obj_y - 2 * _offset]])\n _mask = generate_mask(_x, _y, _img_h, _img_w)\n _vn, _v, _vt = generate_3d_points(_x, _y, _mask)\n output_3d_mesh(_vn, _v, _vt)\n generate_info(_obj_x, _obj_y, _vn, _v, _img_h, _img_w, _scale=_scale)\n generate_render_xml(_obj_name, _img_h, _img_w, _roughness=_roughness, _diffuse=_diffuse)\n render_img()\n _hdr_New, _ldr_New = mix_up_img(_img_h, _img_w)\n if _index == -1:\n cv2.imwrite(os.path.join(PATH_OUT, 'im.png'), np.minimum(_ldr_New * 255, 255))\n else:\n cv2.imwrite(os.path.join(PATH_OUT, f'im{_index}.png'), np.minimum(_ldr_New * 255, 255))\n\n os.system('mv *.xml *.png *.rgbe ' + PATH_OUT)\n\n return _ldr_New\n\n\ndef convert_image_to_video(_num, _root='', _name='im', _out_path='', _video_name='video', _fps=12):\n img = cv2.imread(osp.join(_root, f'{_name}0.png'))\n size = (img.shape[1], img.shape[0])\n # fourcc = cv2.VideoWriter_fourcc('m','p','4','v')\n # fourcc = cv2.VideoWriter_fourcc(*'avc1')\n fourcc = cv2.VideoWriter_fourcc(*'vp80')\n video = cv2.VideoWriter(osp.join(_out_path, f'{_video_name}.webm'), fourcc, _fps, size)\n\n for i in range(1, _num):\n img = cv2.imread(osp.join(_root, f'{_name}{i}.png'))\n video.write(img)\n\n print('Convert to Video Finished!')\n" }, { "alpha_fraction": 0.2832392156124115, "alphanum_fraction": 0.3034157454967499, "avg_line_length": 56.1755485534668, "blob_id": "4e383dbd19fe9acec46e626349712c392343b892", "content_id": "98130c377ce73084a74684880867d62ba6e9099a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18239, "license_type": "no_license", "max_line_length": 117, "num_lines": 319, "path": "/views/index.py", "repo_name": "FUJI-W/lightAR", "src_encoding": "UTF-8", "text": "import dash\nimport dash_html_components as html\nimport dash_bootstrap_components as dbc\nimport dash_core_components as dcc\nimport dash_uploader as du\nimport dash_daq as daq\n\nfrom views.index_callbks import *\n\nindex_page = html.Div([\n dbc.Container([\n dbc.Row([\n dbc.Col(\n width=3,\n children=[\n html.Div([\n dbc.Row([\n dbc.Col(\n daq.Knob(\n id='knob-obj-size', style={\"background\": \"transparent\"}, size=70,\n # label=\"Object Size (%)\", labelPosition=\"bottom\",\n min=0, max=100, value=int(SCALE * 100),\n color={\"gradient\": True,\n \"ranges\": {\"#e3f7d7\": [0, 80], \"#4b9072\": [80, 100]}},\n ),\n ),\n dbc.Col(\n daq.LEDDisplay(\n id='knob-obj-size-output', color=\"#4b9072\"\n # label=\"Object Size\",\n ),\n )\n ], align=\"center\"),\n ], className='box',\n style={'width': '100%', 'margin-bottom': '20px',\n 'padding-top': '15px', 'padding-bottom': '15px'}),\n html.Div([\n dbc.Row([\n dbc.Col(\n daq.Knob(\n id='knob-obj-roughness', style={\"background\": \"transparent\"}, size=70,\n # label=\"Object Size (%)\", labelPosition=\"bottom\",\n min=0, max=100, value=int(ROUGHNESS * 100),\n color={\"gradient\": True,\n \"ranges\": {\"#e3f7d7\": [0, 80], \"#4b9072\": [80, 100]}},\n ),\n ),\n dbc.Col(\n daq.LEDDisplay(\n id='knob-obj-roughness-output', color=\"#4b9072\",\n # label=\"Object Size\",\n ),\n )\n ], align=\"center\"),\n ], className='box',\n style={'width': '100%', 'margin-bottom': '20px',\n 'padding-top': '15px', 'padding-bottom': '15px'}),\n html.Div([\n dbc.Row([\n dbc.Col([\n html.Div(\n dcc.Graph(id='color-picker', figure=get_color_picker_figure(),\n config={'displayModeBar': False, 'editable': False,\n 'scrollZoom': False}),\n style={'display': 'inline-block', 'width': '85%'}\n ), ], width=8\n ),\n dbc.Col([\n html.Div([\n html.Div(\n daq.LEDDisplay(id='color-R-output', value=int(COLOR_R * 255), size=16,\n color=\"#d27656\", ),\n style={'display': 'inline-block', 'width': '100%', }\n ),\n html.Div(\n daq.LEDDisplay(id='color-G-output', value=int(COLOR_G * 255), size=16,\n color=\"#4b9072\"),\n style={'display': 'inline-block', 'width': '100%', }\n ),\n html.Div(\n daq.LEDDisplay(id='color-B-output', value=int(COLOR_B * 255), size=16,\n color=\"#293a66\"),\n style={'display': 'inline-block', 'width': '100%', }\n ),\n ])], width=4\n ),\n ], align='center'),\n html.Div(id='color-picker-output')\n\n ], className='box',\n style={'width': '100%',\n 'padding-top': '0px', 'padding-bottom': '0px'}),\n ]\n ),\n dbc.Col(\n width=6,\n children=[\n # html.Br(),\n html.Div([\n html.Div([\n dcc.Tabs(\n [\n dcc.Tab([dbc.Container(dcc.Graph(id='graph-picture'), id='div-graph-picture')],\n id=\"image-tabs\",\n value=\"1\",\n style={'padding': '0px',\n 'border': 0,\n 'border-radius': '5px',\n 'border-top-right-radius': '0px',\n 'border-bottom-right-radius': '0px',\n 'backgroundColor': '#edefeb'},\n selected_style={'padding': '0px',\n 'border': 0,\n 'border-radius': '5px',\n 'border-top-right-radius': '0px',\n 'border-bottom-right-radius': '0px',\n 'backgroundColor': '#4b9072'}\n ),\n dcc.Tab([html.Div([\n html.Video(\n controls=True,\n id='movie-player',\n src=\"inout/outputs/video.webm\",\n autoPlay=True,\n width='100%'\n )],\n style={'height': '80%', 'margin': '15px', 'margin-top': '20px'}\n )],\n id=\"view-tabs\",\n value=\"2\",\n style={'padding': '0px',\n 'border': 0,\n 'border-radius': '0px',\n 'backgroundColor': '#edefeb'},\n selected_style={'padding': '0px',\n 'border': 0,\n 'border-radius': '0px',\n 'backgroundColor': '#4b9072'}\n ),\n dcc.Tab([dbc.Container(dcc.Graph(id='graph-sunburst'), id='div-graph-sunburst')],\n id=\"sunburst-tabs\",\n value=\"3\",\n style={'padding': '0px',\n 'border': 0,\n 'border-radius': '5px',\n 'border-top-left-radius': '0px',\n 'border-bottom-left-radius': '0px',\n 'backgroundColor': '#edefeb'},\n selected_style={'padding': '0px',\n 'border': 0,\n 'border-radius': '5px',\n 'border-top-left-radius': '0px',\n 'border-bottom-left-radius': '0px',\n 'backgroundColor': '#4b9072'}\n ),\n ],\n # vertical=True,\n id='tabs',\n value='1',\n style={\n 'height': '5px',\n # 'width': '80%',\n 'border': 0,\n 'margin': '15px',\n 'margin-top': '15px',\n 'margin-bottom': '5px'\n }\n ),\n ], style={'width': '100%', 'height': '100%'})\n ], className='box',\n style={'width': '100%', 'height': '80%',\n 'padding-top': '10px',\n # 'padding-bottom': '15px',\n 'display': 'flex', 'align-items': 'center'}\n ),\n html.Div([\n dbc.Container(\n [\n dbc.RadioItems(\n id=\"radios-system-mode\",\n className=\"btn-group\",\n labelClassName=\"radio-label\",\n labelCheckedClassName=\"radio-checked\",\n options=[\n {\"label\": \"Memory Off\", \"value\": 1},\n {\"label\": \"Memory On\", \"value\": 2},\n {\"label\": \"Multi Obj\", \"value\": 3},\n ],\n value=1,\n ),\n ],\n className=\"radio-group\"\n )\n ], id='radio-container', className='box',\n style={'width': '100%', 'height': '13%', 'margin-top': '20px',\n 'padding-top': '0px', 'padding-bottom': '0px',\n 'display': 'flex', 'align-items': 'center'}\n )\n ]\n ),\n dbc.Col(\n width=3,\n children=[\n html.Div([\n du.Upload(id='uploader', filetypes=['png'], upload_id='inputs',\n default_style={'height': '100%',\n 'minHeight': 1, 'lineHeight': 1,\n 'textAlign': 'center',\n 'outlineColor': '#ea8f32',\n 'font-family': 'Open Sans',\n 'font-size': '15px',\n 'font-weight': '500',\n }),\n ], className='box',\n style={'width': '100%', 'height': '92px', 'margin-bottom': '20px',\n 'padding-top': '15px', 'padding-bottom': '15px'}\n ),\n html.Div(\n dbc.Container([\n dbc.Row([\n dbc.Col([\n html.Div([\n html.Img(src=app.get_asset_url('obj_ball.png'), id='html-a-sphere',\n height=\"80%\", style={'margin': 'auto'}),\n ], id='html-sphere-block-color', className='box_objects'),\n # html.Span(id=\"html-a-sphere-output\")\n ], width={'size': 6, 'offset': 0}),\n dbc.Col([\n html.Div([\n html.Img(src=app.get_asset_url('obj_bunny.png'), id='html-a-bunny',\n height=\"80%\", style={'margin': 'auto'}),\n ], id='html-bunny-block-color', className='box_objects'),\n # html.Span(id=\"html-a-bunny-output\"),\n ], width={'size': 6, 'offset': 0}),\n ], align='center'),\n ]),\n className='box',\n style={'width': '100%', 'margin-bottom': '20px',\n 'padding-top': '15px', 'padding-bottom': '15px'}\n ),\n html.Div([\n dbc.Container([\n dbc.Row([\n dbc.Col([\n daq.PowerButton(on='True', id='powerbt-level-first', size=60, color='#4b9072')\n ], width={'size': 4, 'offset': 0}, style={'padding-left': '15px'}),\n dbc.Col([\n daq.PowerButton(id='powerbt-level-second', size=60, color='#4b9072')\n ], width={'size': 4, 'offset': 0}, id='', style={'padding-left': '15px'}),\n dbc.Col([\n daq.PowerButton(id='powerbt-level-third', size=60, color='#4b9072')\n ], width={'size': 4, 'offset': 0}, style={'padding-left': '15px'}),\n ], align='center'),\n ]),\n dbc.Container([\n dbc.Button([dbc.Spinner(size=\"sm\", children=[html.Div(id=\"loading-estimate\")])],\n color=\"success\", outline=False, id='bt-start-estimate',\n style={'background-color': '#4b9072', 'color': 'white'}, block=True)\n ], fluid=True, style={'margin-top': '20px'}),\n ], className='box',\n style={'width': '100%', 'margin-bottom': '20px',\n 'padding-top': '25px', 'padding-bottom': '25px'}\n ),\n\n html.Div([\n dbc.Container([\n dbc.Row([\n dbc.Col([\n daq.LEDDisplay(id='axios-x-output', value='0000', size=25, color='#4b9072'),\n ], width={'size': 6, 'offset': 0}, style={'padding-left': '15px'}),\n dbc.Col([\n daq.LEDDisplay(id='axios-y-output', value='0000', size=25, color='#4b9072'),\n ], width={'size': 6, 'offset': 0}, style={'padding-left': '15px'}),\n ], align='center'),\n ]),\n dbc.Container([\n dbc.ButtonGroup([\n dbc.Button([dbc.Spinner(size=\"sm\", children=[html.Div(id=\"loading-render\")])],\n color=\"success\", id='bt-start-render',\n style={'background-color': '#4b9072', 'color': 'white'}),\n # dbc.Button([dbc.Spinner(size=\"sm\", children=[html.Div(id=\"loading-show\")])],\n # color=\"success\", id='bt-start-show',\n # style={'background-color': '#4b9072', 'color': 'white'})\n\n ], style={'width': '100%'}),\n ], fluid=True, style={'margin-top': '20px'}),\n ], className='box',\n style={'width': '100%', 'padding-top': '25px', 'padding-bottom': '25px'}\n ),\n\n ]\n ),\n\n ]),\n ], fluid=True, style={'width': '95%', 'margin-top': '5px'}),\n html.Div(id=\"test-output\"),\n html.Div([\n make_tooltip('Size of Object', 'knob-obj-size-output'),\n make_tooltip('Roughness of Object', 'knob-obj-roughness-output'),\n make_tooltip('R', 'color-R-output', 'left'),\n make_tooltip('G', 'color-G-output', 'left'),\n make_tooltip('B', 'color-B-output', 'left'),\n make_tooltip('Sphere', 'html-a-sphere'),\n make_tooltip('Bunny', 'html-a-bunny'),\n make_tooltip('Low', 'powerbt-level-first '),\n make_tooltip('Normal', 'powerbt-level-second'),\n make_tooltip('BS Layer', 'powerbt-level-third'),\n make_tooltip('X of Position', 'axios-x-output'),\n make_tooltip('Y of Position', 'axios-y-output'),\n make_tooltip('Viewer of Video', 'view-tabs'),\n make_tooltip('Viewer of Image', 'image-tabs'),\n make_tooltip('Viewer of Chart', 'sunburst-tabs'),\n make_tooltip('Mode of Rendering', 'radio-container', 'bottom')\n # make_tooltip('Choose the Mode of Rendering: &#013;'\n # 'Memory On/Off: Save or not save results of rendering'\n # 'Multi Obj: Support to render a series of objects between the two points you picked.',\n # 'radio-container', 'bottom'),\n ])\n])\n" }, { "alpha_fraction": 0.4470314383506775, "alphanum_fraction": 0.4586728811264038, "avg_line_length": 51.74561309814453, "blob_id": "5f5c03888fafc466ccc69eb4f9baf74217ac8eba", "content_id": "2e1dc41ded108834fcb36882e58f8fececd964d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6013, "license_type": "no_license", "max_line_length": 130, "num_lines": 114, "path": "/views/data.py", "repo_name": "FUJI-W/lightAR", "src_encoding": "UTF-8", "text": "import dash\nimport dash_html_components as html\nimport dash_bootstrap_components as dbc\nimport dash_core_components as dcc\nimport dash_uploader as du\nimport dash_daq as daq\n\nfrom server import app\n\nfrom views.data_callbks import *\n\ndata_page = html.Div([\n\n dbc.Container([\n html.Div([\n html.Div([\n html.Div([\n html.Div([html.Label(\"Estimated Scene Information\", style={\"color\": \"#edefeb\"})], className='box',\n style={'padding': '0px', \"padding-top\": \"6px\", \"padding-bottom\": \"2px\",\n \"text-align\": \"center\",\n \"background-color\": \"#4b9072\", 'border-radius': '15px', 'box-shadow': '0 0 0',\n 'box-border': 0}),\n html.Div([\n dcc.Graph(id=\"graph-input\", config=data_graph_config,\n figure=get_data_graph_figure(osp.join(PATH_IN, 'im.png')))\n ], className='box', id=\"html-graph-input\"),\n ], style={\"width\": \"33.3%\"}),\n html.Div([\n html.Div([\n dcc.Graph(id=\"graph-light\", config=data_graph_config,\n figure=get_envmap_figure(osp.join(PATH_IN, 'envmap.png.npz')))\n ], className='box', id=\"html-graph-light\"),\n ], style={\"width\": \"66.6%\"}),\n ], className='row'),\n html.Div([\n html.Div([\n html.Div([\n dcc.Graph(id=\"graph-normal\", config=data_graph_config,\n figure=get_data_graph_figure(osp.join(PATH_IN, 'normal.png')))\n ], className='box', id=\"html-graph-normal\"),\n ], style={\"width\": \"33.3%\"}),\n html.Div([\n html.Div([\n dcc.Graph(id=\"graph-rough\", config=data_graph_config,\n figure=get_data_graph_figure(osp.join(PATH_IN, 'rough.png'), True))\n ], className='box', id=\"html-graph-rough\"),\n ], style={\"width\": \"33.3%\"}),\n html.Div([\n html.Div([\n dcc.Graph(id=\"graph-albedo\", config=data_graph_config,\n figure=get_data_graph_figure(osp.join(PATH_IN, 'albedo.png')))\n ], className='box', id=\"html-graph-albedo\"),\n ], style={\"width\": \"33.3%\"}),\n ], className=\"row\")\n ], id=\"Viewer-of-estimate\"),\n html.Br(),\n # html.Hr(style={'borderColor': '#4b9072'}),\n html.Hr(),\n html.Br(),\n html.Div([\n html.Div([\n html.Div([\n html.Div([html.Label(\"Intermediate Files in Rendering Process\", style={\"color\": \"#edefeb\"})], className='box',\n style={'padding': '0px', \"padding-top\": \"6px\", \"padding-bottom\": \"2px\",\n \"text-align\": \"center\",\n \"background-color\": \"#4b9072\", 'border-radius': '15px', 'box-shadow': '0 0 0',\n 'box-border': 0}),\n html.Div([\n dcc.Graph(id=\"graph-output\", config=data_graph_config,\n figure=get_data_graph_figure(osp.join(PATH_OUT, 'im.png'), _height=500))\n ], className='box', id=\"html-graph-output\"),\n ], style={\"width\": \"50%\"}),\n html.Div([\n html.Div([\n dcc.Graph(id=\"graph-scene-rgbe\", config=data_graph_config,\n figure=get_rgbe_figure(osp.join(PATH_OUT, 'scene_1.rgbe')))\n ], className='box', id=\"html-graph-scene-rgbe\"),\n html.Div([\n dcc.Graph(id=\"graph-obj-mask\", config=data_graph_config,\n figure=get_data_graph_figure(osp.join(PATH_OUT, 'scene_objmask_1.png'),\n _height=245))\n ], className='box', id=\"html-graph-obj-mask\"),\n ], style={\"width\": \"25%\"}),\n html.Div([\n html.Div([\n dcc.Graph(id=\"graph-bkg-rgbe\", config=data_graph_config,\n figure=get_rgbe_figure(osp.join(PATH_OUT, 'scene_bkg_1.rgbe')))\n ], className='box', id=\"html-graph-bkg-rgbe\"),\n html.Div([\n dcc.Graph(id=\"graph-scene-mask\", config=data_graph_config,\n figure=get_data_graph_figure(osp.join(PATH_OUT, 'scenemask_1.png'),\n _height=245))\n ], className='box', id=\"html-graph-scene-mask\"),\n ], style={\"width\": \"25%\"}),\n\n ], className='row')\n ], id=\"Viewer-of-render\"),\n html.Br(),\n html.Hr(),\n ], fluid=True, style={'width': '95%', 'margin-top': '5px'}),\n\n html.Div([\n make_data_tooltip('Origin Image of Scene', 'html-graph-input', 'bottom'),\n make_data_tooltip('Lighting (SG)', 'html-graph-light', 'bottom'),\n make_data_tooltip('Normal (vector)', 'html-graph-normal', 'bottom'),\n make_data_tooltip('Roughness (number)', 'html-graph-rough', 'bottom'),\n make_data_tooltip('Albedo (vector)', 'html-graph-albedo', 'bottom'),\n make_data_tooltip('Final Mixed Output Image', 'html-graph-output', 'bottom'),\n make_data_tooltip('Rendered Scene (RGBE)', 'html-graph-scene-rgbe', 'bottom'),\n make_data_tooltip('Mask of Object (PNG)', 'html-graph-obj-mask', 'bottom'),\n make_data_tooltip('Rendered Plane (RGBE)', 'html-graph-bkg-rgbe', 'bottom'),\n make_data_tooltip('Mask of Plane (PNG)', 'html-graph-scene-mask', 'bottom'),\n ])\n])\n" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6769670844078064, "avg_line_length": 21.07594871520996, "blob_id": "afafcd0d57c7dc3895f2d5b417b21ae4b1b5f928", "content_id": "5b62cb5c30e210690e969861d60069860f6d517c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4985, "license_type": "no_license", "max_line_length": 122, "num_lines": 158, "path": "/README.md", "repo_name": "FUJI-W/lightAR", "src_encoding": "UTF-8", "text": "[TOC]\n\n## 构建\n\n> OS Platform:Ubuntu20.04\n\n#### 物体渲染器 \n\n> Nvidia Driver Version:440.44,CUDA Version:10.2,Optix Version:5.1\n\n##### 1. 安装Nvidia显卡驱动和对应版本的CUDA\n\n- 安装Nvidia显卡驱动(本项目必须使用**支持光线追踪**的Nvidia显卡)\n\n- 下载对应版本的CUDA安装文件【[官网地址](https://developer.nvidia.com/cuda-downloads)】\n ```\n wget https://developer.download.nvidia.com/compute/cuda/11.2.2/local_installers/cuda_11.2.2_460.32.03_linux.run\n ```\n\n- 运行安装文件,continue - accept - 取消勾选Driver - install\n\n ```\n sudo sh cuda_11.2.2_460.32.03_linux.run\n ```\n\n - 注意:对于cuda10.x来说,建议添加参数 `--librarypath`,否则可能无法顺利安装\n\n ```\n sudo ./cuda_10.2.89_440.33.01_linux.run --librarypath=/usr/local/cuda-10.2\n ```\n\n- 安装完成后,打开文件 `~/.bashrc ` ,文件末尾添加下列语句(配置环境变量)\n\n ```\n export PATH=/usr/local/cuda-11.2/bin${PATH:+:${PATH}}\n export LD_LIBRARY_PATH=/usr/local/cuda-11.2/lib64${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}\n ```\n\n- 运行 `source ~/.bashrc` 使更改生效,CUDA安装成功\n\n##### 2. 安装Optix光线追踪引擎\n\n- 下载对应版本的Optix安装文件【[官网地址](https://developer.nvidia.com/designworks/optix/download)】,运行安装\n\n ```\n sudo bash NVIDIA-OptiX-SDK-6.5.0-linux64.sh\n ```\n\n##### 3. 编译OptixRenderer\n\n> OptixRenderer **位于项目 `/render` 目录**,项目详细说明可见 `/render/README.md`\n>\n> OptixRenderer 【[源代码](https://github.com/lzqsd/OptixRenderer)】\n\n- 安装依赖包(注意编译的时候选用gcc-7)\n\n ```\n sudo apt install libopencv-dev\n sudo apt install libdevil-dev\n sudo apt install cmake\n sudo apt install cmake-curses-gui\n ```\n\n- 按照项目的说明(位于`/render/INSTALL-LINUX.txt`)进行编译,即可成功\n\n#### 光照估计网络 \n\n> 光照估计网络代码在项目中的位置:`/nets`\n>\n> InverseRenderingNet【[源代码](https://github.com/lzqsd/InverseRenderingOfIndoorScene)】\n\n- 下载预训练模型参数【[地址](http://cseweb.ucsd.edu/~viscomp/projects/CVPR20InverseIndoor/models.zip)】,解压到`/nets/models` 目录下,解压后文件结构如下\n\n ```\n ├── nets\n │   ├── models\n │ │   ├── checkBs_cascade0_w320_h240\n │ │   ├── checkBs_cascade1_w320_h240\n │ │   ├── check_cascade0_w320_h240\n │ │   ├── check_cascade1_w320_h240\n │ │   ├── check_cascadeIIW0\n │ │   ├── check_cascadeLight0_sg12_offset1\n │ │   ├── check_cascadeLight1_sg12_offset1\n │ │   ├── check_cascadeNYU0\n │ │   └── check_cascadeNYU1\n ```\n\n#### 其他环境配置\n\n- 环境以及package版本的要求见 `requirements.txt`\n\n ```\n pip install -r requirements.txt\n ```\n\n------\n\n\n\n## 运行\n\n##### 1. 启动 Dash Server\n\n```\npython app.py\n```\n\n##### 2. 在浏览器访问对应端口\n\n```\n127.0.0.1:8050 \n```\n\n![image-20210612135145460](https://gitee.com/FujiW/pic-bed/raw/master/arlight-init-2021-6-12.png)\n\n------\n\n\n\n## 功能\n\n#### 界面介绍\n\n![image-20210612140126622](https://gitee.com/FujiW/pic-bed/raw/master/20210612140126.png)\n\n![20210612160537](https://gitee.com/FujiW/pic-bed/raw/master/20210612161810.png)\n\n#### 操作流程\n\n> 演示视频1:https://bhpan.buaa.edu.cn:443/link/D4CA3F7525173DBAF1B321F0BCF7800C 访问密码:KItL\n>\n> 演示视频2:https://bhpan.buaa.edu.cn:443/link/12B52053FC8EE512FF8194FA47FE4623 访问密码:K4zP\n\n##### 功能一 插入单个物体\n\n1. 上传图像\n2. 选择光照估计精度\n3. 点击 “Start Estimate”,开始估计,估计完成后显示 “Estimate Done”\n4. 通过各组件设置物体的形状、大小、颜色等参数\n5. 选择 “Memory On” 或 “Memory Off” 模式\n6. 鼠标点击图像中任一点作为插入位置\n7. 点击 “Start Render”,开始渲染,渲染完成后显示 “Render Done”\n8. 选择中间窗口中的 “Viewer of Image” 标签页可以观察输出结果\n9. 选择中间窗口中的 “Viewer of Chart” 标签页可以查看应用运行过程中各函数的耗时情况\n\n##### 功能二 插入多个物体\n\n1. 上传图像\n2. 选择光照估计精度\n3. 点击 “Start Estimate”,开始估计,估计完成后显示 “Estimate Done”\n4. 通过各组件设置物体的形状、大小、颜色等参数\n5. 选择 “Multi Obj” 模式\n6. 鼠标点击图像中任一点作为起始点\n7. 点击 “Start Render”,显示 “Push Again”\n8. 鼠标点击图像中任一点作为终点\n9. 点击 “Start Render”,开始渲染,渲染完成后显示 “Render Done”\n10. 选择中间窗口中的 “Viewer of Video” 标签页可以观察输出结果\n11. 选择中间窗口中的 “Viewer of Chart” 标签页可以查看应用运行过程中各函数的耗时情况\n\n\n\n\n\n\n\n" } ]
13
pyennamp/aws-sfn-generator
https://github.com/pyennamp/aws-sfn-generator
b37c8fa66ea8efcd3c3e3acc492c00b25bea8e63
55696778afaaa11a03526ddf276fb653018715a9
5526d30bc30e1194d9113dd70a61391c4b55c16a
refs/heads/main
2023-06-15T04:47:30.858138
2021-07-10T12:52:54
2021-07-10T12:52:54
384,672,348
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.5827755331993103, "alphanum_fraction": 0.5854529142379761, "avg_line_length": 40.5, "blob_id": "180a731f780c00356d8829e42d5f4468f5d9fc45", "content_id": "4d5cdabc50175e40e0d75d7d86f5b668b3455c7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2241, "license_type": "no_license", "max_line_length": 116, "num_lines": 54, "path": "/aws_sfn_generator.py", "repo_name": "pyennamp/aws-sfn-generator", "src_encoding": "UTF-8", "text": "from utils.logger import log\nimport pandas as pd\nimport sys\n\n\ndef replace_job_holders(data: str, job_name: str):\n \"\"\"Replaces job variables with job values\"\"\"\n job_names = job_name.split(',')\n for index, job in enumerate(job_names):\n job_index = \"$$JOB_NAME_\" + str(index + 1)\n data = data.replace(job_index, job.strip())\n return data\n\n\ndef generate_multi_step_workflow(file: str, region: str, account_number: str):\n \"\"\"Generate Step Functions dynamically\"\"\"\n df = pd.read_excel(file)\n for row in df.itertuples():\n wf_name = row.WF_NAME\n job_name = row.JOB_NAME\n count = row.COUNT\n ind_file_path = row.IND_FILE_PATH\n file_name = \"./output/\" + wf_name + \".json\"\n file_ind = str.lower(wf_name) + \".ind\"\n log.info(\"Generate JSON for \" + str(file_name) + \" has started\")\n file_object = open(file_name, 'w')\n if count == 1:\n template = open(\"./input/one_step_glue_jobs.json\")\n data = template.read()\n replace_job_holders_rslt = replace_job_holders(data, job_name)\n elif count == 2:\n template = open(\"./input/two_step_glue_jobs.json\")\n data = template.read()\n replace_job_holders_rslt = replace_job_holders(data, job_name)\n elif count == 3:\n template = open(\"./input/three_step_glue_jobs.json\")\n data = template.read()\n replace_job_holders_rslt = replace_job_holders(data, job_name)\n elif count == 4:\n template = open(\"./input/four_step_glue_jobs.json\")\n data = template.read()\n replace_job_holders_rslt = replace_job_holders(data, job_name)\n else:\n log.info(\"Template not found\")\n sys.exit(1)\n\n replaced_data = replace_job_holders_rslt.replace(\"$$WF_NAME\", wf_name) \\\n .replace(\"$$REGION\", region).replace(\"$$JOB_NAME\", job_name).replace(\"$$IND_FILE_PATH\", ind_file_path) \\\n .replace(\"$$ACCOUNT_NUMBER\", account_number).replace(\"$$FILE_IND\", file_ind)\n file_object.write(replaced_data)\n file_object.close()\n template.close()\n log.info(\"Generate JSON for \" + str(file_name) + \" has completed\")\n return True\n" }, { "alpha_fraction": 0.694915235042572, "alphanum_fraction": 0.7259886860847473, "avg_line_length": 31.18181800842285, "blob_id": "f59266a14a0b0930ca740418387bc0c54daa50b7", "content_id": "ed3316265540022fb37eb0c92da30063e7da282e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 354, "license_type": "no_license", "max_line_length": 62, "num_lines": 11, "path": "/main.py", "repo_name": "pyennamp/aws-sfn-generator", "src_encoding": "UTF-8", "text": "from utils.logger import log\nfrom aws_sfn_generator import generate_multi_step_workflow\n\nfile = \"./input/metadata.xlsx\"\nregion = \"us-west-1\"\naccount_number = \"1234567890\"\n\nif __name__ == '__main__':\n log.info(\"Generating Workflows started\")\n generate_multi_step_workflow(file, region, account_number)\n log.info(\"Generating Workflows completed\")\n" }, { "alpha_fraction": 0.8062499761581421, "alphanum_fraction": 0.8062499761581421, "avg_line_length": 79.5, "blob_id": "65c310b627fc5c06812a601694dcbd9e8aa1685b", "content_id": "60777f3edf4a37433047ecd9e3bdd0de1ca1b8db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 160, "license_type": "no_license", "max_line_length": 139, "num_lines": 2, "path": "/README.md", "repo_name": "pyennamp/aws-sfn-generator", "src_encoding": "UTF-8", "text": "## aws-sfn-generator\nA template based Step Function utility, that takes an input metadata file and json template to generate 'n' number of Step Function Scripts" }, { "alpha_fraction": 0.5774193406105042, "alphanum_fraction": 0.5911290049552917, "avg_line_length": 31.63157844543457, "blob_id": "c7736df628d5b2654497d2cf387f6101bb2754c6", "content_id": "e41464002f6476aed9c1856785f7862bdbec1b0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1240, "license_type": "no_license", "max_line_length": 85, "num_lines": 38, "path": "/handlers/m_WF_JOB_CREATE_INDICATOR_FILE.py", "repo_name": "pyennamp/aws-sfn-generator", "src_encoding": "UTF-8", "text": "from utils.logger import log\nimport boto3\nimport sys\n\n\ndef split_s3_path(s3_path):\n \"\"\"Returns bucket and key from s3 location\"\"\"\n path_parts = s3_path.replace(\"s3://\", \"\").split(\"/\")\n bucket = path_parts.pop(0)\n key = \"/\".join(path_parts)\n return bucket, key\n\n\ndef create_s3_files(file_list: str, path: str):\n \"\"\"This function checks if a file exists in s3\"\"\"\n files = file_list.split(\";\")\n s3_client = boto3.client('s3')\n for file in files:\n try:\n file_path = path + file\n log.info(\"Checking file_path for - \" + file_path + \" has started\")\n bucket, key = split_s3_path(file_path)\n s3_client.put_object(Body='', Bucket=bucket, Key=key)\n log.info(\"Checking file_path for - \" + file_path + \" has completed\")\n except Exception as e:\n log.error(\"File check failed due to the mentioned exception - \" + str(e))\n sys.exit(1)\n return True\n\n\ndef lambda_handler(event, context):\n try:\n file_list = event['file_list']\n ind_file_path = event['ind_file_path']\n create_s3_files(file_list, ind_file_path)\n except Exception as e:\n log.error('Lambda processor Failed - ' + str(e))\n sys.exit(1)\n" } ]
4
shahpalak489/pythontutorials
https://github.com/shahpalak489/pythontutorials
6567f4695184b0363b028826620ee90515dad4c3
a3b3a9a6ffc59cbbb9d47844f42b91f519e79601
589955aff4808850b1b970f42a0b568923e3e4d5
refs/heads/master
2021-06-21T05:59:30.119692
2020-10-21T03:54:30
2020-10-21T03:54:30
202,822,194
0
0
null
2019-08-17T01:47:40
2020-10-21T03:54:33
2021-03-20T01:31:30
Jupyter Notebook
[ { "alpha_fraction": 0.3529411852359772, "alphanum_fraction": 0.529411792755127, "avg_line_length": 6, "blob_id": "4e3d82a7869aee68e7306b7e32f557ed4c3890fe", "content_id": "acdd1c0b9e2ecac97e69ab806d39eb347299e5dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 34, "license_type": "no_license", "max_line_length": 9, "num_lines": 5, "path": "/app/fibo.py", "repo_name": "shahpalak489/pythontutorials", "src_encoding": "UTF-8", "text": "a = 250\nb =500\n\nc = a%b/b\nprint(c)" }, { "alpha_fraction": 0.591911792755127, "alphanum_fraction": 0.6654411554336548, "avg_line_length": 23.81818199157715, "blob_id": "2f97c82599298bce4d4a59a1bfa4ef04148c4fbf", "content_id": "f3d3bf8e187e013109e01ba4cce6d526f0199abc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 272, "license_type": "no_license", "max_line_length": 88, "num_lines": 11, "path": "/app/first.py", "repo_name": "shahpalak489/pythontutorials", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\nfrom pandas import DataFrame\n\nList11={'Name':['Tom', 'Jack', 'Steve','John','akhil','khan'],'Age':[25,40,35,90,14,92]}\ndf = pd.DataFrame(List11)\nprint(df)\n\ndf['Name'] = df['Name'].str.lower()\ndf16 = df.sort_values('Name')\nprint(df16)" }, { "alpha_fraction": 0.7560096383094788, "alphanum_fraction": 0.8064903616905212, "avg_line_length": 33.66666793823242, "blob_id": "a9bc456dcca03ce904e7d22d8717de7e688167d8", "content_id": "12c0318e3a6694bb49b03f9ca00097a2bd0d9a8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 832, "license_type": "no_license", "max_line_length": 124, "num_lines": 24, "path": "/app/links.py", "repo_name": "shahpalak489/pythontutorials", "src_encoding": "UTF-8", "text": "https://stackoverflow.com/questions/12774827/cant-connect-to-localhost-on-sql-server-express-2012-2016\n\nhttps://www.mssqltips.com/sqlservertip/2495/identify-sql-server-tcp-ip-port-being-used/\n\n\nhttps://datatofish.com/how-to-connect-python-to-sql-server-using-pyodbc/\n\nhttps://stackoverflow.com/questions/40332319/no-driver-name-specified-writing-pandas-data-frame-into-sql-server-table\n\nhttps://towardsdatascience.com/sqlalchemy-python-tutorial-79a577141a91\n\nflask: https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world\n\nuwsgi: https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uwsgi-and-nginx-on-ubuntu-14-04\n\n##source env/Scripts/activate\n\n\nrequirements.txt\n$ pip freeze > requirements.txt - starter\npip install -r requirements.txt - another user\n\ngit init\ngit ignore\n" }, { "alpha_fraction": 0.5199999809265137, "alphanum_fraction": 0.5428571701049805, "avg_line_length": 22.09433937072754, "blob_id": "97b677b73f11f62e267d1c4619b59e705888547f", "content_id": "2b1f0e61ce2bc8451851344ad73f002f5a242eae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1225, "license_type": "no_license", "max_line_length": 57, "num_lines": 53, "path": "/app/Tic_Tac_Toe.py", "repo_name": "shahpalak489/pythontutorials", "src_encoding": "UTF-8", "text": "import sys\n\nprint(\"Welcome to Tic Tac Tow game !!\")\n\ndef display_board(board):\n\tprint(board['7'] + '|' + board['8'] + '|' + board['9'])\n\tprint('-+-+-')\n\tprint(board['4'] + '|' + board['5'] + '|' + board['6'])\n\tprint('-+-+-')\n\tprint(board['1'] + '|' + board['2'] + '|' + board['3'])\n\ntheBoard = {'7': ' ' , '8': ' ' , '9': ' ' ,\n '4': ' ' , '5': ' ' , '6': ' ' ,\n '1': ' ' , '2': ' ' , '3': ' ' }\ndisplay_board(theBoard)\n\nliNames = ['X', 'O']\nname = input(\"Do you want to be X or O? \")\nprint(\"Nice to meet you \" + name + \"!\")\nname = name.upper()\nassert name in liNames, 'It Can be only X or O.'\n\nliProcess = ['YES', 'NO']\ntoProcess = input(\"Are you ready to Play Yes or No? \")\nprint(toProcess)\ntoProcess = toProcess.upper()\nassert toProcess in liProcess, 'Please answer Yes or No.'\n\nif toProcess == 'YES':\n\tprint(\"Let's Play now\")\n\n\tnums = []\n\tfor i in range(10):\n\t\tnum1 = input(\"player1: which numebr you like: \")\n\t\tif num1 not in nums:\n\t\t\tnums.append(num1)\n\t\telse:\n\t\t\tsys.exit()\n\n\n\t\tnum2 = input(\"player2: your turn: \")\n\t\tif num1 not in nums:\n\t\t\tnums.append(num2)\n\t\tprint(nums)\n\n\t# board_keys = []\n\n\t# for key in theBoard:\n\t# board_keys.append(key)\n\nelse:\n\tprint(\"Ok then I'll stop.\")\n\tsys.exit()\n\n" }, { "alpha_fraction": 0.40401145815849304, "alphanum_fraction": 0.467048704624176, "avg_line_length": 13.541666984558105, "blob_id": "ee1ceea46d5fd13b709316cf640f546a7626cf3d", "content_id": "2c00b10531b7e0f2db25946f31cfd6aa3819d53a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 349, "license_type": "no_license", "max_line_length": 42, "num_lines": 24, "path": "/app/swap.py", "repo_name": "shahpalak489/pythontutorials", "src_encoding": "UTF-8", "text": "## Method 1 (Using Arithmetic Operators)\nx = 10\ny = 5\n \n# x now becomes 15 \nx = x + y # x= 15\n \n# y becomes 10 \ny = x - y # y = 10\n \n# x becomes 5 \nx = x - y # x = 5\nprint(\"After Swapping: x =\", x, \" y =\", y)\n\n\n\n## temp var\nx = 10\ny = 5\n'''z temp var'''\nz = x # Z = 10\nx = y # x = 5\ny = z # y = 10\nprint(\"After Swapping: x =\", x, \" y =\", y)\n" }, { "alpha_fraction": 0.5326876640319824, "alphanum_fraction": 0.537530243396759, "avg_line_length": 20.789474487304688, "blob_id": "89b19e2e73585914b4d9d1461afbeeb3495652ba", "content_id": "466e48a79c3fbecb77de4b0670e4b9d21e0bfc46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 413, "license_type": "no_license", "max_line_length": 51, "num_lines": 19, "path": "/app/anagram.py", "repo_name": "shahpalak489/pythontutorials", "src_encoding": "UTF-8", "text": "from collections import Counter \n\ndef isAnagram(s, t):\n if len(s) == len(t):\n print(\"anagram is possible\")\n print(Counter(s))\n print(Counter(t))\n if Counter(s) == Counter(t):\n print(\"it is a anagram\")\n else:\n print(\"length is same but not anagram\")\n else:\n print(\"length is different\")\n\nisAnagram('akh', 'lap')\n# {'p':1, 'a':1,}\n\n# akhil\n# akh" }, { "alpha_fraction": 0.6615384817123413, "alphanum_fraction": 0.6769230961799622, "avg_line_length": 8.428571701049805, "blob_id": "d674fc4be8b50e8e1229244371565f8d14bacbb0", "content_id": "7844b92d01b7b0968131796d1864c658e38a5875", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 65, "license_type": "no_license", "max_line_length": 16, "num_lines": 7, "path": "/app/oops.py", "repo_name": "shahpalak489/pythontutorials", "src_encoding": "UTF-8", "text": "class deck:\n\tdef deal:\n\t\tsinglecard = 1\n\t\tpass\n\nclass card:\n\tpass" }, { "alpha_fraction": 0.6463748216629028, "alphanum_fraction": 0.6846784949302673, "avg_line_length": 19.899999618530273, "blob_id": "d430e4b37c1179c42ecd9f9b371f976ec3859b1b", "content_id": "fe53f071a42138373873b17f8a94fa728666063d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1462, "license_type": "no_license", "max_line_length": 102, "num_lines": 70, "path": "/app/excelfiles.py", "repo_name": "shahpalak489/pythontutorials", "src_encoding": "UTF-8", "text": "import openpyxl\nimport pandas as pd\n\n\n''' \nopenoyxl\nxlsxwriter\nxlrt\nxlwt\nxlutils\nto_excel\nto_csv\n'''\n\n### to_excel https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html\nli = [['Alex',10],['Bob',12],['Clarke',13]]\ndf2 = pd.DataFrame(li, columns=[\"name\", \"age\"]) \ndf2.to_excel(\"output1.xlsx\", index=False, sheet_name='data')\n\n### 2nd way\nwith pd.ExcelWriter('output.xls') as writer: # doctest: +SKIP\n\t# df1.to_excel(writer, sheet_name='Sheet_name_1')\n\tdf2.to_excel(writer, sheet_name='Sheet_name_2')\n\ndf2.to_csv(\"output3.csv\")\n\n###3rd way\nfrom openpyxl import Workbook\nwb = Workbook()\n\n# grab the active worksheet\nws = wb.active\n\n# Data can be assigned directly to cells\nws['A1'] = 42\n\n# Rows can also be appended\nws.append([1, 2, 3])\n\n# Python types will automatically be converted\nimport datetime\nws['A2'] = datetime.datetime.now()\n\n# Save the file\nwb.save(\"sample.xlsx\")\n\n\n###4th way\n# from xlutils.copy import copy\n# w = copy('output.xls')\n# w.get_sheet(0).write(0,0,\"foo\")\n# w.save('output5.xls')\n\nimport xlwt\nfrom datetime import datetime\n\nstyle0 = xlwt.easyxf('font: name Times New Roman, color-index red, bold on',\n num_format_str='#,##0.00')\nstyle1 = xlwt.easyxf(num_format_str='D-MMM-YY')\n\nwb = xlwt.Workbook()\nws = wb.add_sheet('A Test Sheet')\n\nws.write(0, 0, 1234.56, style0)\nws.write(1, 0, datetime.now(), style1)\nws.write(2, 0, 1)\nws.write(2, 1, 1)\nws.write(2, 2, xlwt.Formula(\"A3+B3\"))\n\nwb.save('example.xls')" }, { "alpha_fraction": 0.4396423101425171, "alphanum_fraction": 0.4485841989517212, "avg_line_length": 22.964284896850586, "blob_id": "f615543ad0725f98edb3e79483bc2e504975655f", "content_id": "430872ffec621fb03ff7774ef35e21e72f8154e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 671, "license_type": "no_license", "max_line_length": 51, "num_lines": 28, "path": "/app/reverse.py", "repo_name": "shahpalak489/pythontutorials", "src_encoding": "UTF-8", "text": "# using recursion # function call itself\ndef reverse(s): \n if len(s) == 0: \n return s \n else:\n \t# p = s[1:]\n \t# print(p)\n \tprint(s[0])\n \treturn reverse(s[1:]) + s[0]\n \t # reverse('khil') + 'a'\n \t # reverse('hil') + 'k' + 'a'\n \t # reverse('il') + 'h'+ 'k' + 'a'\n \t # reverse('l') + 'i'+ 'h'+ 'k' + 'a'\n \t # reverse('') + 'l'+'i'+ 'h'+ 'k' + 'a'\n \t # 'lihka'\n\n# # using extended slice syntax \n# def reverse(string): \n# string = string[::-1] \n# return string\n\n# # using reversed()\n# def reverse(string): \n# string = \"\".join(reversed(string)) \n# return string \n\n\nreverse(\"akhil\")\n" }, { "alpha_fraction": 0.5914633870124817, "alphanum_fraction": 0.5975610017776489, "avg_line_length": 10, "blob_id": "8a9b70f68c532066cf3cfc82f614939072353129", "content_id": "c75b3b043cb512b1b49a2f1c1d8489742261ebcd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 164, "license_type": "no_license", "max_line_length": 24, "num_lines": 15, "path": "/app/pali.py", "repo_name": "shahpalak489/pythontutorials", "src_encoding": "UTF-8", "text": "# Input : malayalam\n# Output : Yes\n\n# Input : geeks\n# Output : No\n\n\ns = \"malayalam\"\nrs = s[::-1]\nprint(rs)\n\nif s==rs:\n\tprint(\"string is pali\")\nelse:\n\tprint(\"sorry\")" }, { "alpha_fraction": 0.4102920591831207, "alphanum_fraction": 0.43532684445381165, "avg_line_length": 27.719999313354492, "blob_id": "3881c0ae5cd8a3eddde4939703abca0f89778f7e", "content_id": "fe58b9462a8c7d5d173f9008dd78d6135af6e58d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 719, "license_type": "no_license", "max_line_length": 67, "num_lines": 25, "path": "/app/fizzbuzz.py", "repo_name": "shahpalak489/pythontutorials", "src_encoding": "UTF-8", "text": "#Python program to print Fizz Buzz \n#loop for 100 times i.e. range \nfor i in range(20): \n \n # number divisible by 3, print 'Fizz' \n # in place of the number \n if i % 15 == 0: \n print(\"FizzBuzz\") \n continue\n \n # number divisible by 5, print 'Buzz' \n # in place of the number \n elif i % 3 == 0: \n print(\"Fizz\") \n continue\n \n # number divisible by 15 (divisible \n # by both 3 & 5), print 'FizzBuzz' in \n # place of the number \n elif i % 5 == 0: \n print(\"Buzz\") \n continue\n \n # print numbers \n print(i) \n" }, { "alpha_fraction": 0.6627907156944275, "alphanum_fraction": 0.7441860437393188, "avg_line_length": 27.77777862548828, "blob_id": "ae60f690c4efe1efa674e580e306a311c67f7c27", "content_id": "fa5e38090bef8c7090c7135f30d09108d28e978f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 258, "license_type": "no_license", "max_line_length": 76, "num_lines": 9, "path": "/app/challangephase.py", "repo_name": "shahpalak489/pythontutorials", "src_encoding": "UTF-8", "text": "# Decimal('34.3') -- decimal is not json serializable\n# datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable\n\n\n\n#https://code-maven.com/serialize-datetime-object-as-json-in-python\n\njson.dumps, json.loads karto to\njsonify ma problem thay" } ]
12
BitKnitting/neural-disaggregator
https://github.com/BitKnitting/neural-disaggregator
718e58118d8970c0a11029d521454ace97fb0e6d
d22f9dc6f6284b8bf638207b2e4ca62a57098398
6423f051980975ecdfa86b4f04c5576f93d00a2a
refs/heads/master
2020-10-02T05:56:55.246883
2019-12-14T21:28:15
2019-12-14T21:28:15
227,715,957
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.795918345451355, "alphanum_fraction": 0.8183673620223999, "avg_line_length": 69, "blob_id": "6f0c9eaa43dbfda8884257545607260f2b88ce1d", "content_id": "3d20ff5e8e35e002b1f12b9d22b6ddbd6f6aa4c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 490, "license_type": "no_license", "max_line_length": 223, "num_lines": 7, "path": "/ShortSeq2Point/README.md", "repo_name": "BitKnitting/neural-disaggregator", "src_encoding": "UTF-8", "text": "# Short Sequence to Point Energy Disaggregator\n\nBased on [Sequence-to-point learning with neural networks for nonintrusive load monitoring](https://arxiv.org/abs/1612.09106) by Zhang et al. Sequence-to-point learning with neural networks for nonintrusive load monitoring.\n\nThe main changes are the shorter window size as well as some dropout layers.\n\nSee example experiment [here](https://github.com/OdysseasKr/neural-disaggregator/blob/master/ShortSeq2Point/ShortSeq2Point-example.ipynb).\n" }, { "alpha_fraction": 0.8029045462608337, "alphanum_fraction": 0.817427396774292, "avg_line_length": 67.85713958740234, "blob_id": "1019eb0bf350dc67e2274a1a36efb112571f8fde", "content_id": "981cd7272208ec117f8966474fb83b6d3846290f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 482, "license_type": "no_license", "max_line_length": 190, "num_lines": 7, "path": "/WindowGRU/README.md", "repo_name": "BitKnitting/neural-disaggregator", "src_encoding": "UTF-8", "text": "# GRU with Sliding Window Disaggregator\n\nA Recurrent Neural Network disaggregator that uses a window of data as input instead of one sample of the timeseries.\n\nAs described in [Sliding Window Approach for Online Energy Disaggregation Using Artificial Neural Networks](https://dl.acm.org/citation.cfm?id=3201011) by Krystalakos, Nalmpantis and Vrakas.\n\nSee example experiment [here](https://github.com/OdysseasKr/neural-disaggregator/blob/master/WindowGRU/Window-GRU-example.ipynb).\n" }, { "alpha_fraction": 0.7664071321487427, "alphanum_fraction": 0.7914349436759949, "avg_line_length": 127.42857360839844, "blob_id": "08d8c0a8ad0a3ee542cb9ab736b7509f50ac0f1c", "content_id": "0ffc8d61a3227fe84aab725464710ec6d1031a73", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1798, "license_type": "no_license", "max_line_length": 389, "num_lines": 14, "path": "/README.md", "repo_name": "BitKnitting/neural-disaggregator", "src_encoding": "UTF-8", "text": "# neural-disaggregator\n\nImplementations of NILM disaggegregators using Neural Networks, using [NILMTK](https://github.com/NILMTK/NILMTK) and Keras.\n\nMost of the architectures are based on [Neural NILM: Deep Neural Networks Applied to Energy Disaggregation](https://arxiv.org/pdf/1507.06594.pdf) by Jack Kelly and William Knottenbelt.\n\nThe implemented models are:\n- Denoising autoencoder (DAE) as mentioned in [Neural NILM](https://arxiv.org/pdf/1507.06594.pdf) (see [example](https://github.com/OdysseasKr/neural-disaggregator/blob/master/DAE/DAE-example.ipynb))\n- Recurrent network with LSTM neurons as mentioned in [Neural NILM](https://arxiv.org/pdf/1507.06594.pdf) (see [example](https://github.com/OdysseasKr/neural-disaggregator/tree/master/RNN/RNN-example.ipynb))\n- Recurrent network with GRU. A variation of the LSTM network in order to compare the two types of RNNs (see [example](https://github.com/OdysseasKr/neural-disaggregator/blob/master/GRU/GRU-example.ipynb))\n- Window GRU. A variation of the GRU network in that uses a window of data as input. As described in [Sliding Window Approach for Online Energy Disaggregation Using Artificial Neural Networks](https://dl.acm.org/citation.cfm?id=3201011) by Krystalakos, Nalmpantis and Vrakas (see [example](https://github.com/OdysseasKr/neural-disaggregator/blob/master/WindowGRU/Window-GRU-example.ipynb))\n- Short Sequence to Point Network based on the architecture in [original paper](https://arxiv.org/abs/1612.09106) (see [example](https://github.com/OdysseasKr/neural-disaggregator/blob/master/ShortSeq2Point/ShortSeq2Point-example.ipynb))\n\n_Note: If you are looking for the LookbackGRU folder, it has been moved to http://github.com/OdysseasKr/online-nilm. I try to keep this repo clean by using the same train and test sets for all architectures._\n" }, { "alpha_fraction": 0.7147959470748901, "alphanum_fraction": 0.734183669090271, "avg_line_length": 30.612903594970703, "blob_id": "448d4f32040ba3fda47f74969a4e12d29f76cdae", "content_id": "32e673068cd23fda16140cbf5f59c27730acb8f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1960, "license_type": "no_license", "max_line_length": 92, "num_lines": 62, "path": "/ShortSeq2Point/ukdale-extract.py", "repo_name": "BitKnitting/neural-disaggregator", "src_encoding": "UTF-8", "text": "from __future__ import print_function, division\nimport time\n\nfrom matplotlib import rcParams\nimport matplotlib.pyplot as plt\n\nfrom nilmtk import DataSet, TimeFrame, MeterGroup, HDFDataStore\nfrom shortseq2pointdisaggregator import ShortSeq2PointDisaggregator\nimport metrics\n\n\ndef _normalize(chunk, mmax):\n '''Normalizes timeseries\n\n Parameters\n ----------\n chunk : the timeseries to normalize\n max : max value of the powerseries\n\n Returns: Normalized timeseries\n '''\n tchunk = chunk / mmax\n return tchunk\n\n\nprint(\"========== OPEN DATASETS ============\")\ntrain = DataSet(\n '/Users/mj/Documents/Learning_Stuff/NILM/neural-disaggregator/ShortSeq2Point/ukdale.h5')\ntest = DataSet(\n '/Users/mj/Documents/Learning_Stuff/NILM/neural-disaggregator/ShortSeq2Point/ukdale.h5')\n\ntrain.set_window(start=\"13-4-2013\", end=\"1-1-2014\")\ntest.set_window(start=\"1-1-2014\", end=\"30-3-2014\")\n\nwindow_size = 100\ntrain_building = 1\ntest_building = 1\nsample_period = 6\nmeter_key = 'kettle'\ntrain_elec = train.buildings[train_building].elec\ntest_elec = test.buildings[test_building].elec\n\ntrain_meter = train_elec.submeters()[meter_key]\ntrain_mains = train_elec.mains()\ntest_mains = test_elec.mains()\n# Here we get a generator back...\ntrain_main_power_series = train_mains.power_series(sample_period=sample_period)\ntrain_meter_power_series = train_meter.power_series(\n sample_period=sample_period)\ntest_mains_power_series = test_mains.power_series(sample_period=sample_period)\n# There is only one chunk of data...so next() retrieves it all.\n# We are returned Pandas dataframes.\ndf_main = next(train_main_power_series)\ndf_meter = next(train_meter_power_series)\ndf_test = next(test_mains_power_series)\n#\n\ndf_main.to_pickle(\n 'data/UK_Dale_aggregate_train_Omar.pkl.zip', compression='zip')\ndf_meter.to_pickle('data/UK_Dale_kettle_Omar.pkl.zip', compression='zip')\ndf_test.to_pickle(\n 'data/UK_Dale_aggregate_test_Omar.pkl.zip', compression='zip')\n" } ]
4
Kimmirikwa/bc-13-Inventory_Management
https://github.com/Kimmirikwa/bc-13-Inventory_Management
6849bfdbbbcb857bcf895e2fb9fa89674d52e3b7
1dd100ce1a5c4f09b509487f74d82cd5c90d50e7
509c3aeded2b8a5abf3e536cd3283d97c67a93d9
refs/heads/master
2020-06-13T16:19:53.838733
2016-12-06T14:45:40
2016-12-06T14:45:40
75,712,613
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6672077775001526, "alphanum_fraction": 0.6672077775001526, "avg_line_length": 15.675675392150879, "blob_id": "3d70ab16d2c568cd1c582f59087249c3ee44045e", "content_id": "122568483a763ba300ab6f90882dfdb926fb5463", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 616, "license_type": "no_license", "max_line_length": 68, "num_lines": 37, "path": "/Web/WebProgramming/server.py", "repo_name": "Kimmirikwa/bc-13-Inventory_Management", "src_encoding": "UTF-8", "text": "from functools import wraps\nfrom flask import Flask, url_for, request, render_template, Response\n\n#method to carry out the authentication\napp = Flask(__name__)\n\[email protected](\"/\")\ndef sign_in():\n pass\n\[email protected](\"/addasset\", methods=[\"GET\",\"POST\"])\ndef add_asset():\n pass\n\[email protected](\"/addusers\")\ndef add_users():\n pass\n\[email protected](\"/assignasset\")\ndef assign_asset():\n pass\n\[email protected](\"/unassignasset\")\ndef unassign_asset():\n pass\n\[email protected](\"/viewassigned\")\ndef view_assigned():\n pass\n\[email protected](\"/repportlost\")\ndef report_lost():\n pass\n\[email protected](\"/reportfound\")\ndef report_found():\n pass" }, { "alpha_fraction": 0.7148703932762146, "alphanum_fraction": 0.7305593490600586, "avg_line_length": 34.780487060546875, "blob_id": "8213544855444112d6ecbcb1ff5a347d7ffbf31b", "content_id": "3bc311ed5a7b513ed2858a8fa986d57c6ab07d49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1466, "license_type": "no_license", "max_line_length": 73, "num_lines": 41, "path": "/Backend/database.py", "repo_name": "Kimmirikwa/bc-13-Inventory_Management", "src_encoding": "UTF-8", "text": "import os\nimport sys\nfrom sqlalchemy import Column, ForeignKey, Integer, String\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy import create_engine\n\nBase = declarative_base()\n\n\nclass User(Base):\n __tablename__ = 'user'\n # Here we define columns for the table person\n # Notice that each column is also a normal Python instance attribute.\n id = Column(Integer, primary_key=True)\n first_name = Column(String(20), nullable=False)\n last_name = Column(String(20), nullable=False)\n staff_no = Column(String(10),unique=True, nullable=False)\n staff_role = Column(String(10),nullable=False)\n\n\nclass AssetRecord(Base):\n __tablename__ = 'asset_record'\n # Here we define columns for the table address.\n # Notice that each column is also a normal Python instance attribute.\n id = Column(Integer, primary_key=True)\n asset_name = Column(String(50))\n asset_description = Column(String(250))\n asset_serial_number = Column(String(250), unique=True)\n asset_andela_serial_code = Column(String(250), unique=True)\n asset_date_bought = Column(String(20))\n asset_status = Column(String(20))\n\n\n# Create an engine that stores data in the local directory's\n# sqlalchemy_example.db file.\nengine = create_engine('sqlite:///sqlalchemy_example.db')\n\n# Create all tables in the engine. This is equivalent to \"Create Table\"\n# statements in raw SQL.\nBase.metadata.create_all(engine)" }, { "alpha_fraction": 0.5676100850105286, "alphanum_fraction": 0.5676100850105286, "avg_line_length": 20.233333587646484, "blob_id": "5196ea15ca932b01d3f736705cc4f3f62bd497a1", "content_id": "0fa4e6df0cf11d87ea91540e20f5c53bced0757d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 636, "license_type": "no_license", "max_line_length": 40, "num_lines": 30, "path": "/Web/WebProgramming/Applications_users.py", "repo_name": "Kimmirikwa/bc-13-Inventory_Management", "src_encoding": "UTF-8", "text": "#The class StaffMember is the superclass\nclass StaffMember:\n def __init__(self):\n pass\n def sign_in(self):\n pass\n def report_lost_item(self):\n pass\n def report_found_item(self):\n pass\nclass Admin(StaffMember):\n def __init__(self):\n pass\n def add_asset(self):\n pass\n def assign_asset(self):\n pass\n def unassign_asset(self):\n pass\n def see_assigned(self):\n pass\n def remind_due(self):\n pass\n def view_lost_items(self):\n pass\n def resolve_lost(self):\n pass\nclass SuperAdmin(Admin):\n def add_admin(self):\n pass" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.8214285969734192, "avg_line_length": 28, "blob_id": "cc286ceed5eacc5ff61455ab2f6e476c911e7ccf", "content_id": "3d838b9ac0af6c5de62eaff83d1e296646d94097", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 28, "license_type": "no_license", "max_line_length": 28, "num_lines": 1, "path": "/README.md", "repo_name": "Kimmirikwa/bc-13-Inventory_Management", "src_encoding": "UTF-8", "text": "# bc-13-Inventory_Management" } ]
4
pansfy/web_automation_test_lecture
https://github.com/pansfy/web_automation_test_lecture
4972f6f2b2b8c8e9d9bc43ecdd0a452b393c2a6d
1984a5920298a4f1d2a2bd419c2e99e2c0655e02
43d32f089c78c9eb3d86e495c5f6440f907c66aa
refs/heads/master
2022-06-13T01:55:47.050852
2022-05-26T02:54:20
2022-05-26T02:54:20
248,687,446
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7161152362823486, "alphanum_fraction": 0.7481323480606079, "avg_line_length": 17.019229888916016, "blob_id": "ab8d55428dc607663d9f274f317327e97d274870", "content_id": "be75fc3311ccb46d7e4ac4f46a9a61cfa04e8524", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1835, "license_type": "no_license", "max_line_length": 114, "num_lines": 52, "path": "/README.md", "repo_name": "pansfy/web_automation_test_lecture", "src_encoding": "UTF-8", "text": "# web_automation_test_lecture\n\n> 本仓库用于存放针对 **Python 3.x + Selenium 3.x 自动化讲堂** 的思维导图的案例描述及演示代码。\n\n点击[Python 3.x + Selenium 3.x 自动化讲堂思维导图](https://www.processon.com/u/5ac6d735e4b00dc8a02f3113/profile#pc)可访问完整思维导图。\n\n## 1. 第一节 理论指导\n\n任务:百度一下,你就知道\n\n任务描述:\n\n1. Selenium的测试环境准备\n2. 新建测试脚本文件“baidu_auto_search.py”,用于存放本案例脚本\n3. 编写脚本,实现根据关键字自动进行百度搜索操作\n4. 退出浏览器,结束本次测试\n\n## 2. 第二节 案例驱动(上)\n\n任务:登录增强版\n\n任务描述:针对被测程序的登录模块,应用决策表法编写至少8条用例,并将其脚本化。\n\n项目平台:http://iwebsns.pansaifei.com/\n\n## 3. 第三节 案例驱动(中)\n\n任务:注册OOP\n\n任务描述:针对被测程序的注册场景,编写注册功能的自动化测试脚本,实现测试报告的生成及邮件发送。\n\n项目平台:http://iwebsns.pansaifei.com/\n\n## 4. 第四节 案例驱动(下)\n\n任务:登录&注册POM\n\n任务描述:针对被测程序的登录和注册场景,应用POM设计模式编写自动化测试脚本,实现测试报告的生成及邮件发送。\n\n项目平台:http://iwebsns.pansaifei.com/\n\n## 5. 第五、六节 扩展技能 & 综合案例\n\n阶段任务:大展身手\n\n任务描述:针对被测项目注册模块、登录(登录、注销)模块、日志模块(创建、编辑、删除、查看日志)编写自动化测试脚本,实现测试报告的生成及邮件发送。\n\n项目平台:http://iwebsns.pansaifei.com/\n\n## 7. 第七节 资源推荐\n\n[《Selenium官方文档》](https://www.selenium.dev/selenium/docs/api/py/index.html)\n" }, { "alpha_fraction": 0.7103448510169983, "alphanum_fraction": 0.7126436829566956, "avg_line_length": 17.16666603088379, "blob_id": "993161361b63a6966a1466bbd2b0c969a34b663b", "content_id": "d6fe5f3e6a1eab4838a86c3d15b8a691417e03f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 531, "license_type": "no_license", "max_line_length": 48, "num_lines": 24, "path": "/chapter01/code/baidu_auto_search.py", "repo_name": "pansfy/web_automation_test_lecture", "src_encoding": "UTF-8", "text": "\"\"\"\n 文件名:baidu_auto_search.py\n 用途:百度一下,你就知道,自动化搜索脚本\n\"\"\"\nimport time\nfrom selenium import webdriver\n\n# 创建的是一个全新的浏览器\nbrowser = webdriver.Chrome()\nbrowser.get(\"https://www.baidu.com\")\n\n# 元素定位\nkeyword_input = browser.find_element_by_id(\"kw\")\nsearch_button = browser.find_element_by_id(\"su\")\n\n# 元素操作\nkeyword_input.send_keys(\"selenium\")\nsearch_button.click()\n\ntime.sleep(3)\n\n# 场景还原\nbrowser.get(\"https://www.baidu.com\")\n# browser.quit()" } ]
2
somasekharreddy1119/DS-Algo-with-python
https://github.com/somasekharreddy1119/DS-Algo-with-python
ce00fb11b7a505c907c6585002677d20bee90138
232d2177d722b5a4bc827e099942c18307c06bbf
023f6cf356e88ff98ef5e2d55450fb7fd035910d
refs/heads/master
2023-01-02T01:48:37.171575
2020-10-24T01:13:26
2020-10-24T01:13:26
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.536472737789154, "alphanum_fraction": 0.5604801774024963, "avg_line_length": 22.565217971801758, "blob_id": "1fb923a69643e07203c5eb506dc63b82aa024838", "content_id": "bf34de9a1d41efb95fb4e12dec8ab82731214d65", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1083, "license_type": "no_license", "max_line_length": 84, "num_lines": 46, "path": "/Algorithms/mathematics/sum_factors.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#https://www.geeksforgeeks.org/sum-of-factors-of-a-number-using-prime-factorization/\n'''\nSum of Factors of a Number using Prime Factorization\nGiven a number N. The task is to find the sum of all factors of the given number N.\nEx:\nInput : N = 12\nOutput : 28\nAll factors of 12 are: 1,2,3,4,6,12\n'''\n\n\n\ndef primefactors(num):\n '''\n :param num: int\n :return: list of prime factor\n '''\n from math import sqrt, ceil\n primes = []\n n = num\n while num > 1:\n for i in range(2, ceil(sqrt(n))+1, 1):\n if num % i == 0:\n num = num // i\n primes.append(i)\n break\n return primes\n\ndef sum_primefactors(num):\n '''\n :param num: num\n :return: sum of factors\n '''\n prime_factors = primefactors(num)\n counts = {i:prime_factors.count(i) for i in prime_factors}\n tot_sum = 1\n print(counts)\n for i in counts.keys():\n t = 1\n for j in range(1,counts[i]+1):\n print(i,j)\n t = t + (i**j)\n tot_sum = t * tot_sum\n print(tot_sum)\n\nsum_primefactors(1100)" }, { "alpha_fraction": 0.5303030014038086, "alphanum_fraction": 0.560606062412262, "avg_line_length": 19.517240524291992, "blob_id": "91a7e90b3b041e46437ae85d923d0dd7bac23fb3", "content_id": "e72f50e6ac72d34587d590f55f53f59ab0333237", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 594, "license_type": "no_license", "max_line_length": 41, "num_lines": 29, "path": "/Algorithms/sorting/quick.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "'''\nQuick sort: DIVIDE and CONQURE\ni,j at start and pivot at end\n\nBEST CASE: O(nlogn)\nAVG CASE: O(nlogn)\nWORST CASE: O(n^2)\n'''\narr = [7,2,1,6,8,5,3,4]\nn = len(arr)\n\ndef quicksort(arr,low,high):\n if low < high:\n pi = partition(arr,low,high)\n quicksort(arr,low,pi-1)\n quicksort(arr,pi+1,high)\n\ndef partition(arr,low,high):\n i = low - 1\n pivot = arr[high]\n for j in range(low,high):\n if arr[j] < pivot:\n i = i + 1\n arr[i],arr[j] = arr[j],arr[i]\n arr[i+1],arr[high] = pivot,arr[i+1]\n\n return i + 1\nquicksort(arr,0,n-1)\nprint(arr)" }, { "alpha_fraction": 0.6397228837013245, "alphanum_fraction": 0.6974595785140991, "avg_line_length": 26.967741012573242, "blob_id": "7034885c64f4c27e2277639396111621eae04d93", "content_id": "1132bfd63ca2731262ce18ec816c1f689be8e040", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 866, "license_type": "no_license", "max_line_length": 92, "num_lines": 31, "path": "/Algorithms/dynamic_prog/lonest_subsequence_consecutive.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#RBR Interview Prep-\n#Find the longest subsequence in an array, such that elements in subsequence are consecutive\n'''\nFind the longest subsequence in an array, such that elements in subsequence are consecutive\nExample: [10,4,3,11,13,5,6,12,7]\npossible subsequence are: 1. [4,3,5,6,7] and [10,11,13,12]\nreturn longest subsequence\n\nApproach 1: (Sort)\n1. Sort out the array\n2. Find the length of the longest sub-sequence\nTime: O(nlogn) + O(n)\n\nApproach2: (Hash Table)\n1. Crate hash table with all the elements in the array and key is true.\n2. For a given number in the hash table Check for the series and return longest sequence.\nTIme: O(n) + O(2n) + On()\nSpace: O(n)\n'''\n#approach 2\n\n\n\ndef longest_sub_consecutive_sequence(arr,n):\n dict = {i: False for i in arr}\n processed = 0\n longest = 0\n subseq = []\n\narr = [10, 4, 3, 11, 13, 5, 6, 12, 7]\nn = len(arr)" }, { "alpha_fraction": 0.6151761412620544, "alphanum_fraction": 0.6558265686035156, "avg_line_length": 28.479999542236328, "blob_id": "8a1bffc6c5ad134703ce76c94f4144aa4e25f959", "content_id": "522b8c0fa4a4be7c52ca59a2c50428c958172fa4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 738, "license_type": "no_license", "max_line_length": 120, "num_lines": 25, "path": "/Algorithms/bit_manipulation/Missing_Number.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#https://www.geeksforgeeks.org/find-the-missing-number/\n'''\nYou are given a list of n-1 integers and these integers are in the range of 1 to n. There are no duplicates in the list.\nOne of the integers is missing in the list. Write an efficient code to find the missing integer.\n\nThis can be solved by XOR operation and sum approach.\nUsing XOR:\n1) XOR all the array elements, let the result of XOR be X1.\n2) XOR all numbers from 1 to n, let XOR be X2.\n3) XOR of X1 and X2 gives the missing number.\n'''\n\ndef get_missing(arr):\n n = len(arr)\n x1, x2 = 1, arr[0]\n for i in range(1,n):\n x2 = x2 ^ arr[i]\n\n for i in range(2,n+2):\n x1 = x1 ^ (i)\n\n return x1 ^ x2\n\narr = [1, 2, 4, 6, 3, 7, 8]\nprint(get_missing(arr))\n\n" }, { "alpha_fraction": 0.737864077091217, "alphanum_fraction": 0.7572815418243408, "avg_line_length": 102, "blob_id": "987827beda0987e7a76fcdcbb2a3dcf5a03b3936", "content_id": "025354a1a7e7387c12ed8b855dd8650cb36713ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 103, "license_type": "no_license", "max_line_length": 102, "num_lines": 1, "path": "/Algorithms/bit_manipulation/notes.txt", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "Please note that XOR of two elements is 0 if both elements are same and XOR of a number x with 0 is x.\n" }, { "alpha_fraction": 0.4861495792865753, "alphanum_fraction": 0.5415512323379517, "avg_line_length": 20.235294342041016, "blob_id": "ab52bc9c3bc57fb83613a8e726032a145f5996fe", "content_id": "c1ca4712a8b8181f30affa9988f374bb3941c468", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 722, "license_type": "no_license", "max_line_length": 80, "num_lines": 34, "path": "/arrays/seperate_0's_and_1's.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "# RBR Interview PREP\n# Seperate 0's and 1's in an array\n'''\nGiven a binary array(only 0's and 1's seperate all zero's and ones's in an array\nExample: 1001110\nSol: 0001111\n\nApproach 1: (Count sort)\ncount all 1's and 0's then add all zeros in the front and 1's at the end.\nTIME: O(n)\n\nApproach 2:\nTake left pointer and right pointer do swapping\nTIME: O(N)\n'''\n\n\ndef seperate_zeros_ones(arr):\n n = len(arr) - 1\n l, r = 0, n\n while l <= r:\n if arr[l] == 0:\n l = l + 1\n if arr[r] == 1:\n r = r - 1\n else:\n arr[l], arr[r] = arr[r], arr[l]\n l = l + 1\n r = r - 1\n return arr\n\n\narr = [1, 0, 0, 1, 1, 0, 1, 1, 0]\nprint(seperate_zeros_ones(arr))\n" }, { "alpha_fraction": 0.5250767469406128, "alphanum_fraction": 0.5537359118461609, "avg_line_length": 26.91428565979004, "blob_id": "ef3792c8ea598ecbc7ad4ab5d94df7d72c7c8196", "content_id": "54f7740273dd88d87d2f58f750c0253a54f503ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 977, "license_type": "no_license", "max_line_length": 119, "num_lines": 35, "path": "/Algorithms/greedy/jobseq_with_deadlines.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "'''\nhttps://www.geeksforgeeks.org/job-sequencing-problem/\nGiven an array of jobs where every job has a deadline and associated profit if the job is finished before the deadline.\nIt is also given that every job takes single unit of time, so the minimum possible deadline for any job is 1.\nHow to maximize total profit if only one job can be scheduled at a time.\nTIME Complexity => O(nlogn) + O (n)\n'''\n\n\n\ndef jobseq(arr):\n jobs = {i[2]:[i[0],i[1]] for i in arr}\n jobs = dict(sorted(jobs.items(),reverse=True))\n print(jobs)\n chart = [0 for i in range(len(jobs))]\n profit = 0\n for i in jobs:\n print(i)\n j = jobs[i][1]\n while j > 0:\n if chart[j] == 0:\n chart[j] = jobs[i][0]\n profit = profit + i\n break\n j = j - 1\n print(chart[1:],profit)\n\n\narr = [['a', 2, 100], # Job Array\n ['b', 1, 19],\n ['c', 2, 27],\n ['d', 1, 25],\n ['e', 3, 15]]\n\njobseq(arr)\n" }, { "alpha_fraction": 0.5109170079231262, "alphanum_fraction": 0.5742357969284058, "avg_line_length": 18.913043975830078, "blob_id": "c6f4d3b2fd756970b5ab4580d106606233c13180", "content_id": "ccc4ade5a7ebafe133bbc1db417bae25fd513463", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 458, "license_type": "no_license", "max_line_length": 49, "num_lines": 23, "path": "/Algorithms/bit_manipulation/clear_kth_bit.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#RBR interview prep\n#set kth bit of a number\n'''\nwe assume that index of LSB is 0 here k = 3\nex: 1001010\nand 1110111 (to get this: complement of (1 << k))\n-------------\nans 1000010 ----> return\n-------------\nTIME: O(log n)\n'''\n\n\ndef clear_kth_bit(num, k):\n '''\n :param num: integer, number to test\n :param k: integer, position to test\n :return: integer, with kth bit clear\n '''\n return (num & ~(1 << (k - 1)))\n\n\nprint(clear_kth_bit(32,2))\n" }, { "alpha_fraction": 0.4736842215061188, "alphanum_fraction": 0.4736842215061188, "avg_line_length": 5.666666507720947, "blob_id": "f041286f72171138193d37d2762387af24197c1d", "content_id": "be583f0b318ba957ca8b21ae20c999a69cdcf5e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19, "license_type": "no_license", "max_line_length": 11, "num_lines": 3, "path": "/Algorithms/sorting/radix_sorting.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "'''\nradix sort:\n'''" }, { "alpha_fraction": 0.5215947031974792, "alphanum_fraction": 0.5415282249450684, "avg_line_length": 15.777777671813965, "blob_id": "b7cf73c201098aa453b1b147276649fc0a0881f4", "content_id": "ab1ae95e04f5ab9e291885494bb023ea3e19e577", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 301, "license_type": "no_license", "max_line_length": 48, "num_lines": 18, "path": "/Algorithms/recursion/uppercase_letters.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#FIND OUT ALL THE UPPER CASE LETTERS IN A STRING\nst = 'I am Vishnu from HYD'\n\nfor i in st:\n if i.isupper():\n print(i)\n else:\n pass\n\ndef upper_case(st):\n if st:\n if st[0].isupper():\n print(st[0])\n return upper_case(st[1:])\n\n\nprint('-'*100)\nupper_case(st)" }, { "alpha_fraction": 0.486376017332077, "alphanum_fraction": 0.5136239528656006, "avg_line_length": 23.5, "blob_id": "3d17fadeb9a8d789b758e5387284a30d220c83c1", "content_id": "a2816a34255cf4b9f62a48458d3e3ff8fc1e34d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 734, "license_type": "no_license", "max_line_length": 96, "num_lines": 30, "path": "/Algorithms/greedy/smallestNumber.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#https://practice.geeksforgeeks.org/problems/smallest-number/0\n'''\nThe task is to find the smallest number with given sum of digits as s and number of digits as d.\n\nExpected Time Complexity: O(d)\n\nThis can be solved using greedy algorithm\n'''\n\n\nkases = 3\nnums = [[9,2],[20,3],[63,3]]\nfor i in nums:\n tot_sum = i[0]\n digits = i[1]\n if tot_sum > digits * 9:\n # sum exceeds\n print('-1')\n else:\n dig = []\n while digits > 0:\n digits = digits - 1\n rem = tot_sum - (digits * 9)\n if rem <= 0:\n dig.append(1)\n tot_sum = tot_sum - 1\n else:\n dig.append(rem)\n tot_sum = tot_sum - rem\n print(dig)" }, { "alpha_fraction": 0.5300353169441223, "alphanum_fraction": 0.5742049217224121, "avg_line_length": 23.65217399597168, "blob_id": "35935230aab0e54f5992c8afe8c28cb9db054a31", "content_id": "50b9c09d87b0fdefad89070ee821cf8fe9444a8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 566, "license_type": "no_license", "max_line_length": 67, "num_lines": 23, "path": "/Algorithms/recursion/binary_search.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#BINARY SEARCH\nmy_list = [1,4,8,9,12,16,19,25,29,35]\n\nele = 1\nn = len(my_list)\ndef binarysearch(my_list,ele,low=0,high=n):\n if high >= low:\n mid = low + (high-1) // 2\n if my_list[mid] == ele:\n\n return mid\n elif ele < my_list[mid]:\n return binarysearch(my_list,ele,low=0,high=mid-1)\n else:\n return binarysearch(my_list, ele, low=mid+1, high=high)\n else:\n return False\n\nmid = binarysearch(my_list,ele,0,n-1)\nif mid:\n print(ele,'is found at position',mid)\nelse:\n print('Element fot found')" }, { "alpha_fraction": 0.49080532789230347, "alphanum_fraction": 0.4990488290786743, "avg_line_length": 23.261537551879883, "blob_id": "7e06be95311f729e04f022a4928abb2f675d3511", "content_id": "38ef5ba3f728c879009ba8d3a66d1c08a9c91f3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1577, "license_type": "no_license", "max_line_length": 41, "num_lines": 65, "path": "/circular linked list/circular.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "class Node:\n def __init__(self,data):\n self.data = data\n self.next = None\n\n\nclass circular:\n def __init__(self):\n self.head = None\n\n def append(self,data):\n new_node = Node(data)\n if self.head == None:\n self.head = new_node\n new_node.next = self.head\n else:\n curr = self.head\n while curr.next != self.head:\n curr = curr.next\n curr.next = new_node\n new_node.next = self.head\n\n\n def print_list(self):\n curr = self.head\n while curr.next is not self.head:\n print(curr.data)\n curr = curr.next\n print(curr.data)\n print('-'*100)\n def delete_item(self,item):\n if self.head == None:\n return False\n elif self.head.data == item:\n curr = self.head.next\n prev = self.head\n while curr != self.head:\n prev = curr\n curr = curr.next\n prev.next = curr.next\n self.head = self.head.next\n else:\n curr = self.head\n prev = curr\n while curr.next != self.head:\n if curr.data == item:\n prev.next = curr.next\n prev = curr\n curr = curr.next\n return True\n\nc = circular()\nc.append(10)\nc.append(15)\nc.append(25)\nc.print_list()\nc.delete_item(10)\nc.print_list()\nc.append(10)\nc.print_list()\n\n#print(c.head.data)\n#print(c.head.next.data)\n#print(c.head.next.next.data)\n#print(c.head.next.next.next.data)\n" }, { "alpha_fraction": 0.3360323905944824, "alphanum_fraction": 0.44534412026405334, "avg_line_length": 16.35714340209961, "blob_id": "fa761933429899145bfb8675dcdda87d601de4eb", "content_id": "a7e079a99aaa69dd10a715a484262ffe24a989f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 247, "license_type": "no_license", "max_line_length": 47, "num_lines": 14, "path": "/Algorithms/dynamic_prog/fibonacci.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "'''\nFibonacci series\n0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 + 55 +\n'''\n\ndef fibonacci(n):\n f = [0 for i in range(n+2)]\n f[0], f[1] = 0, 1\n for i in range(2,n+1):\n f[i] = f[i-1] + f[i-2]\n return f[n]\n\n\nprint(fibonacci(15))\n\n\n\n\n" }, { "alpha_fraction": 0.760606050491333, "alphanum_fraction": 0.760606050491333, "avg_line_length": 46, "blob_id": "62c662f91e7fa2d4ac758b2adb872b52b0246e1e", "content_id": "5a566d488a6008999acb4965296a421da5145f66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 330, "license_type": "no_license", "max_line_length": 91, "num_lines": 7, "path": "/Algorithms/bit_manipulation/swap_bits.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#https://www.geeksforgeeks.org/swap-bits-in-a-given-number/\n'''\nSwap bits in a given number\nGiven a number x and two positions (from the right side) in the binary representation of x,\nwrite a function that swaps n bits at given two positions and returns the result.\nIt is also given that the two sets of bits do not overlap.\n'''\n\n" }, { "alpha_fraction": 0.56175297498703, "alphanum_fraction": 0.5836653113365173, "avg_line_length": 32.5, "blob_id": "5850a9cd7a3e0d39f73cbfa18cdc92cd74549276", "content_id": "814f7c0efc482339afdd128941c914396769ce10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1004, "license_type": "no_license", "max_line_length": 184, "num_lines": 30, "path": "/Algorithms/mathematics/prime_factors.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#https://www.geeksforgeeks.org/print-all-prime-factors-of-a-given-number/\n'''\nFollowing are the steps to find all prime factors.\n1) While n is divisible by 2, print 2 and divide n by 2.\n2) After step 1, n must be odd. Now start a loop from i = 3 to square root of n. While i divides n, print i and divide n by i. After i fails to divide n, increment i by 2 and continue.\n3) If n is a prime number and is greater than 2, then n will not become 1 by above two steps. So print n if it is greater than 2.\n'''\n\ndef primefactors(num):\n '''\n :param num: int\n :return: list of prime factor\n '''\n from math import sqrt, ceil\n primes = []\n n = num\n while num != 1:\n for i in range(2, ceil(sqrt(n))+1, 1):\n if num % i == 0:\n num = num // i\n primes.append(i)\n print(i, num)\n break\n '''if num != 1:\n primes.append(num)\n num = num // num'''\n return primes\n\n\nprint(primefactors(2113))" }, { "alpha_fraction": 0.6638655662536621, "alphanum_fraction": 0.6638655662536621, "avg_line_length": 16.071428298950195, "blob_id": "e8b367f00552872da358d9390537003bd0fe2191", "content_id": "053da230ecf3f9d5452fd4ce187f72fa2bd4a90c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 238, "license_type": "no_license", "max_line_length": 43, "num_lines": 14, "path": "/stacks/reverse_string.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "'''\nPerform reversing of a string using stack\n'''\n\nfrom stacks import stack\ns = stack.Stacks()\n\nstring = input(\"Enter a string to reverse\")\nprint(string)\nfor i in string:\n s.push(i)\n\nwhile s.isempty() != True:\n print(s.pop(),end='')" }, { "alpha_fraction": 0.6794520616531372, "alphanum_fraction": 0.6904109716415405, "avg_line_length": 21.8125, "blob_id": "5dd95a0475784f3d61bfb4d44076c4c4078afa4e", "content_id": "97a08854228065c5e9e88785888274c1c7de1495", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 365, "license_type": "no_license", "max_line_length": 85, "num_lines": 16, "path": "/stacks/decimal_binary_stack.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#Convert decimal number into a binary number using stack\n\nfrom stacks.stack import Stacks\n\n\nnum = int(input(\"Enter a number to convert into binary:\"))\ns = Stacks()\n#divide number with 2 and append the remainder to the stack till the num becomes zero\n\n\nwhile num > 0:\n s.push(num % 2)\n num = num //2\n\nprint(\"Binary of\",num,\"is\",end='-->')\nprint(s.get_items())\n" }, { "alpha_fraction": 0.5472972989082336, "alphanum_fraction": 0.5945945978164673, "avg_line_length": 17.5, "blob_id": "24a89a61345a3fe27adbaa337c5d88ebd3c1feee", "content_id": "b2e01fd71a048e801cfe3dc84e5e2a3dc07d63c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 148, "license_type": "no_license", "max_line_length": 52, "num_lines": 8, "path": "/Algorithms/dynamic_prog/backtracking.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#Generate all the possible sub-sets of a given array\n'''\nExample: arr = {1, 2}\nSol: {[], [1], [2], [1,2]}\nApproach:\nBack Tracking\nTIME : O(2^n)\n'''\n" }, { "alpha_fraction": 0.3243243098258972, "alphanum_fraction": 0.4324324429035187, "avg_line_length": 9.941176414489746, "blob_id": "0c03ccd19c24e6dd45f0ef119460f99dfbc6329f", "content_id": "bc5897aae01b2ec5bb015e6b6680cfe93214c9f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 185, "license_type": "no_license", "max_line_length": 34, "num_lines": 17, "path": "/Algorithms/recursion/multiply_two_nums.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "'''\nx = 5\ny = 3\n(5,3)\n5 + (5,2)\n5 + (5,1)\n5 + (5,0)\n'''\nx = 5\ny = 3\ndef multiply(x,y):\n if y == 0:\n return 0\n else:\n return 5 + multiply(5,y-1)\n\nprint(multiply(x,y))" }, { "alpha_fraction": 0.592424213886261, "alphanum_fraction": 0.6015151739120483, "avg_line_length": 25.399999618530273, "blob_id": "2c88fda28523ff8b5967b9def3a412b464d08611", "content_id": "9baf70627679dea0534d2867aa6170e7185caf29", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 662, "license_type": "no_license", "max_line_length": 102, "num_lines": 25, "path": "/mathematics/gcd.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#https://www.geeksforgeeks.org/c-program-find-gcd-hcf-two-numbers/\n'''\nGCD/HCF of two numbers\nGCD of two numbers is the largest number that divides both of them.\nAn efficient solution is to use Euclidean algorithm which is the main algorithm used for this purpose.\nThe idea is, GCD of two numbers doesn’t change if smaller number is subtracted from a bigger number.\n'''\n\n\ndef gcd(a,b):\n if a == 0:\n return b\n if b == 0:\n return a\n if a == b:\n return a\n else:\n if a > b:\n return gcd(a-b,b)\n else:\n return gcd(a,b-a)\n \na = 36\nb = 13\nprint('GCD of %d and %d is %d' % (a, b, gcd(a, b)))\n" }, { "alpha_fraction": 0.48091602325439453, "alphanum_fraction": 0.5190839767456055, "avg_line_length": 17.761905670166016, "blob_id": "cafbfe8d8762e2bf09721a77f188c32310145576", "content_id": "1c3e9c50a972ba444d8a9dd6f69a98bc0d965750", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 393, "license_type": "no_license", "max_line_length": 58, "num_lines": 21, "path": "/Algorithms/sorting/selection.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "'''\nSearch for the least element and place it in the begining.\n\nBEST CASE: O(n*2)\nAVG CASE: O(n^2)\nWORST CASE: O(n^2)\n'''\n\narr = [5, 6, 1, 7, 0, 4, 12, 10, 9]\nn = len(arr)\n\ndef selection(arr,n):\n for i in range(0,n):\n min = i\n for j in range(i,n):\n if arr[j] < arr[min]:\n min = j\n arr[i],arr[min] = arr[min],arr[i]\n\nselection(arr,n)\nprint(arr)" }, { "alpha_fraction": 0.6370967626571655, "alphanum_fraction": 0.6370967626571655, "avg_line_length": 19.33333396911621, "blob_id": "7bf0ad55b8f75003d8f2800d0bcc8713dbc9c84f", "content_id": "3eea6ca96102b3e99d26959662d16ad9911c7558", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 124, "license_type": "no_license", "max_line_length": 66, "num_lines": 6, "path": "/mathematics/lcm.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#LCM of two numbers\n#https://www.geeksforgeeks.org/program-to-find-lcm-of-two-numbers/\n\n'''\nlcm(a,b)*gcd(a,b) = a * b\n'''\n\n\n" }, { "alpha_fraction": 0.6407867670059204, "alphanum_fraction": 0.6552795171737671, "avg_line_length": 22, "blob_id": "fe78f03c815cb6c324a2f9347dfacec171277c6e", "content_id": "327257ae2769d0cb92780faf3bbf58df0ee8fa14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 966, "license_type": "no_license", "max_line_length": 110, "num_lines": 42, "path": "/strings/removeDuplicates.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#remove duplicates from a given string\n'''\nExample: 'abbcccddddeeeee'\nOutput: 'abcde'\n\n\nApproach 1:\n1. create a new array to store output.\n2. add new chars to the output after comparing with previously inserted values\nTime: O(n^2)\nSpace: O(N)\n\nApproach 2:\n1. create a new array to store output and maintain a hash table to store occurances.\n2. add new chars to the output after checking with hash table\nTime: O(n)\nSpace: O(N) + O(k) k = #symbols\n\nApproach 3(inplace of approach 2):\nTime: O(n)\nSpace: O(1) + O(k)\n'''\n\n\ndef removeDuplicates(st):\n '''\n Remove duplicate characters from a given string (for simplicitywe consider only small case alphabets only)\n :param st: string\n :return: string after removing dplicates\n '''\n\n dict = {chr(i):0 for i in range(ord('a'), ord('z')+1)}\n out = ''\n for i in st:\n if dict[i] == 0:\n out = out + i\n dict[i] = 1\n return out\n\n\ns = 'abbcccdddd'\nprint(removeDuplicates(s))\n" }, { "alpha_fraction": 0.609510064125061, "alphanum_fraction": 0.6268011331558228, "avg_line_length": 26.799999237060547, "blob_id": "beeda314c992357259822e2bffbd43e6ff59f500", "content_id": "5624a5356a5b02cbbbe8bebdd0286f391f766f73", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 694, "license_type": "no_license", "max_line_length": 115, "num_lines": 25, "path": "/Algorithms/greedy/min_cost_ropes.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#https://practice.geeksforgeeks.org/problems/minimum-cost-of-ropes/0/?ref=self\n'''\nThere are given N ropes of different lengths, we need to connect these ropes into one rope.\nThe cost to connect two ropes is equal to sum of their lengths. The task is to connect the ropes with minimum cost.\n'''\n\n\ndef min_cost_ropes(ropes,n):\n cost = 0\n while n > 1:\n r1 = min(ropes)\n ropes.remove(r1)\n r2 = min(ropes)\n ropes.remove(r2)\n ropes.append(r1 + r2)\n cost = cost + r1 + r2\n n = n -1\n return cost\n\n\nkases = int(input())\nfor kase in range(kases):\n n = int(input())\n ropes = list(map(int,input().split()))\n print(min_cost_ropes(ropes,n))" }, { "alpha_fraction": 0.48237884044647217, "alphanum_fraction": 0.5212922096252441, "avg_line_length": 28, "blob_id": "9c9045609052a2a6cf3241e04a0bb5eabc49639a", "content_id": "7de4f641d81ef0d406f720aec5da010540d98753", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1362, "license_type": "no_license", "max_line_length": 105, "num_lines": 47, "path": "/Algorithms/dynamic_prog/longest_common_subsequence.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#RBR Interview prep\n#Longest Common sub-sequence\n'''\nApproach: Dynamic Program O(n^2)\n\nconstruct sol matrix. If str[i] = str[j] then sol[i][j] = sol[i-1][j-1] + 1\n else sol[i][j] = max(sol[i-1][j],sol[i][j-1])\n'''\ndef display_mat(mat,size):\n '''\n Display the given matrix\n :param mat: multi dimensional array matrix\n :param size: tuple with size\n :return: None\n '''\n # display mat\n for i in range(size[0]):\n for j in range(size[1]):\n print(mat[i][j], end=' ')\n print(' ')\n\n\ndef longest_common_sub_seq(str1, str2):\n '''\n Computes longest common subsequence of str1 and str2\n :param str1: string1\n :param str2: string2\n :return: Inetger\n '''\n len1, len2 = len(str1), len(str2)\n sol = [[0 for i in range(len1 + 1)] for j in range(len2 + 1)]\n for i in range(len2 + 1):\n for j in range(len1 + 1):\n if i == 0 or j == 0:\n sol[i][j] = 0\n else:\n if str1[j - 1] == str2[i - 1]:\n sol[i][j] = sol[i-1][j-1] + 1\n else:\n sol[i][j] = max(sol[i-1][j], sol[i][j-1])\n\n #display_mat(sol, (len2+1, len1+1))\n return sol[-1][-1]\n\nstr1 = 'gxtxayb'\nstr2 = 'aggtab'\nprint('Lognest common subsequence of %s and %s is %d:' %(str1, str2, longest_common_sub_seq(str1, str2)))" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5091984272003174, "avg_line_length": 19.849315643310547, "blob_id": "4dfce79dcaceb92d604fc199b3b270af4c90ce4f", "content_id": "5fb480a6ec7561a0da4bbc40189dd3e54c2ab7ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1522, "license_type": "no_license", "max_line_length": 47, "num_lines": 73, "path": "/doubly_linked/doubly.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "class Node:\n\n def __init__(self,data):\n self.data = data\n self.next = None\n self.prev = None\n\n\nclass double_linked:\n def __init__(self):\n self.head = None\n\n def append(self,item):\n if self.head is None:\n self.head = Node(item)\n\n else:\n last_node = self.head\n while last_node.next:\n last_node = last_node.next\n last_node.next = Node(item)\n\n def insert_begin(self,item):\n temp = Node(item)\n temp.next = self.head\n self.head = temp\n\n def insert_pos(self,item,pos):\n '''\n Insert at any arbitary position\n :param item: Item to insert\n :param pos: starts from 1 ie., begining\n :return: None\n '''\n\n temp = Node(item)\n i = 2\n curr = self.head\n while i<pos and curr.next != None:\n curr = curr.next\n i = i + 1\n\n temp.prev = curr\n temp.next = curr.next\n curr.next.prev = temp\n curr.next = temp\n\n\n def find_item(self,item):\n curr = self.head\n while curr.next and curr.data != item:\n curr = curr.next\n if curr.data == item:\n return True\n else:\n return False\n\n def print_list(self):\n curr = self.head\n while curr:\n print(curr.data)\n curr = curr.next\n\n\n\nd = double_linked()\nd.append(1)\nd.append(2)\nd.append(10)\nd.insert_begin(0)\nd.append(100)\nd.insert_pos(50,5)\nd.print_list()\n" }, { "alpha_fraction": 0.5274336338043213, "alphanum_fraction": 0.5575221180915833, "avg_line_length": 21.639999389648438, "blob_id": "e0dc7d82401f3c6d6cddd47df698f7cc915863d7", "content_id": "cc839d693b0cf9125139a8e1d61160514360db72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 565, "license_type": "no_license", "max_line_length": 129, "num_lines": 25, "path": "/Algorithms/sorting/bubble_sort.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "# BUBBLE SORT\n'''\nBubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.\n\nBEST CASE: O(n)\nAVG CASE: O(n^2)\nWORST CASE: O(n^2)\n'''\n\narr = [5, 6, 1, 7, 0, 4, 12, 10, 9]\nn = len(arr)\n\n\n# PASS\ndef bubble_search(arr,n):\n for j in range(n):\n swapped = False\n for i in range(n - 1):\n if arr[i] > arr[i + 1]:\n arr[i],arr[i+1] = arr[i+1],arr[i]\n swapped = True\n if swapped == False:\n return arr\n\nprint(bubble_search(arr,n))" }, { "alpha_fraction": 0.5384615659713745, "alphanum_fraction": 0.557692289352417, "avg_line_length": 17.41176414489746, "blob_id": "32220e70fa88cbe0a6a8f008366109576616173d", "content_id": "6468fe8bfaa6161035e64c94ec411ec7754461fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 312, "license_type": "no_license", "max_line_length": 41, "num_lines": 17, "path": "/Algorithms/recursion/count_constants.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#COUNT CONSTANTS in a string\n#we consider ' ' also as a consonent\n\n#recursion\n\nst = 'welcome words'\n\ndef count_cons(st):\n if st:\n if st[0] not in 'aeiou':\n return 1 + count_cons(st[1:])\n else:\n return 0 + count_cons(st[1:])\n else:\n return 0\n\nprint(count_cons(st))" }, { "alpha_fraction": 0.5126262903213501, "alphanum_fraction": 0.5538720488548279, "avg_line_length": 23.77083396911621, "blob_id": "1cdba0bded9503a403c0dcf328c30aabb847d083", "content_id": "f153e9d8b28d1a7858a8da521d4d9dc0637f7b67", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1188, "license_type": "no_license", "max_line_length": 70, "num_lines": 48, "path": "/Algorithms/dynamic_prog/max_sum_subarray.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#RBR Interview Prep\n#Find Max sum sub-array\n'''\nEx: [10, -5, -3, 4, 2, 12, -8, -12, 19]\n\nMax sum is 20([10, -5, -3, 4, 2, 12])\n\nKadan's Algo:(Assumption atleast one element is positive in the array)\nhttps://www.geeksforgeeks.org/largest-sum-contiguous-subarray/\nInitialize:\n max_so_far = 0\n max_ending_here = 0\n\nLoop for each element of the array\n (a) max_ending_here = max_ending_here + a[i]\n (b) if(max_ending_here < 0)\n max_ending_here = 0\n (c) if(max_so_far < max_ending_here)\n max_so_far = max_ending_here\nreturn max_so_far\n\nTime Complexity: O(n)\n'''\n\n\ndef kadane(arr):\n n = len(arr)\n index, max_sum, curr_sum = -1, 0, 0\n for i in range(n):\n curr_sum = curr_sum + arr[i]\n if curr_sum < 0:\n curr_sum = 0\n if curr_sum > max_sum:\n max_sum = curr_sum\n index = i\n\n curr_sum = 0\n print(max_sum, index)\n for start in range(index, -1, -1):\n curr_sum = curr_sum + arr[start]\n if curr_sum == max_sum:\n if start == index:\n return arr[index:index+1]\n return arr[start:index]\n\n\narr = [-10, -5, -3, -4, -2, 12, -8, -12, -19]\nprint(kadane(arr))" }, { "alpha_fraction": 0.47895902395248413, "alphanum_fraction": 0.5221483707427979, "avg_line_length": 27.682538986206055, "blob_id": "7cd8cdfda3a67a84d87ebde7ea83c4e0cf558a9f", "content_id": "0843081a0dd2db4ac139b4c771d7c43d2910866d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1806, "license_type": "no_license", "max_line_length": 91, "num_lines": 63, "path": "/Algorithms/dynamic_prog/largest_square_sub_matrix_binary_array.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#RBR interview prep\n#Finding largest square sub-matrix in a given binary matrix\n'''\n1 1 1 1\n0 0 1 1\n1 1 1 1 ====> max possible sub-square matrix with all 1's = 2\n1 1 1 1\n\nApproach 1 : (Brute Force) => O(N^4)\n1. Find all sub-square matrix O(n^3)\n2. Check weather a sub0matrix contain all 1's\n\nApproach 2 : Dynamic Programing +> O(n ^ 2)\n'''\n\ndef display_mat(mat,size):\n '''\n Display the given matrix\n :param mat: multi dimensional array matrix\n :param size: tuple with size\n :return: None\n '''\n # display mat\n for i in range(size[0]):\n for j in range(size[1]):\n print(mat[i][j], end=' ')\n print(' ')\n\n\ndef largest_sub_matrix(mat, size):\n '''\n Finding largest square sub-matrix in a given binary matrix\n :param mat: Binary matrix\n :param size: tuple, size of matrix\n :return: size of largest square sub-matrix in a given binary matrix\n '''\n sol = [[0 for i in range(size[1])] for j in range(size[0])]\n # display mat\n print('Given matrix is:')\n display_mat(mat, size)\n print('----------------')\n max_sub = 0\n for i in range(size[0]):\n for j in range(size[1]):\n if i == 0 or j == 0:\n sol[i][j] = mat[i][j]\n if mat[i][j] == 1:\n max_sub = 1\n\n for i in range(1, size[0]):\n for j in range(1, size[1]):\n if mat[i][j] == 1:\n sol[i][j] = min(sol[i-1][j-1], sol[i][j-1], sol[i-1][j]) + 1\n if sol[i][j] > max_sub:\n max_sub = sol[i][j]\n else:\n sol[i][j] = 0\n return max_sub\n\nsize = (5,5)\nmat = [[1, 1, 1, 1, 1], [0, 1, 1, 1, 1], [1, 1, 1, 1, 1], [0, 1, 1, 0, 1], [0, 0, 1, 1, 1]]\n\nprint('Max possible square sub matrix with 1\\'s is :',largest_sub_matrix(mat, size))" }, { "alpha_fraction": 0.4931945502758026, "alphanum_fraction": 0.5668534636497498, "avg_line_length": 26.130434036254883, "blob_id": "d5af5650b08427b0cae73eaa37dd1269c749858f", "content_id": "f41619959c2f23ffd0d26449b17392033e8f6e72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1249, "license_type": "no_license", "max_line_length": 78, "num_lines": 46, "path": "/Algorithms/dynamic_prog/longest_increasing_subsequence.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#RBR Interv prep\n#Find the longest increasing subsequence\n'''\nExample: [2,10,13,15,3,11,12]\nlongestincreasing subsequences are: [2,3,11,12], [2,10,13,15], [10,13,15]\nApproach1:\n arr = [2,10,13,15,3,11,12]\n arr1 = [2,3,10,11,12,13,15] ==> sorted array\n Perform Longest common subsequence on arr, arr1\n TIME and Space = O(n^2)\nApproach 2: Bruteforce\n Generate all possible subarrays (2^n).\n Check weather the elements in the subarray are in increasing order or not.\n TIME: O(2^n * n)\nApproach 3: Dynamic Programing\n TIME: O(n^2)\n SPACE : O(n)\n'''\n\n\ndef longest_increasing_subseq(arr):\n '''\n Returns longest increasing sub-sequence from a given array\n :param str: string\n :return: Integer, wit longest increasing sub-sequence\n '''\n\n n = len(arr)\n sol = [1 for i in range(n)]\n for i in range(n):\n print(sol)\n if i == 0:\n sol[0] = 1\n else:\n for j in range(0,i):\n max_sub = sol[i]\n if arr[i] > arr[j]:\n temp = sol[j] + 1\n if temp > max_sub:\n sol[i] = temp\n return max(sol)\n\n\n#arr = [2,10,13,15,3,11,12]\narr = [2,3,1,5,12,10,11]\nprint(longest_increasing_subseq(arr))\n\n" }, { "alpha_fraction": 0.48298215866088867, "alphanum_fraction": 0.5364667773246765, "avg_line_length": 18.3125, "blob_id": "bafafc5d94d944aef14262ec901a58d30caeda6f", "content_id": "c2247952b8baf301d1b639933df32a8aeb99c1eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 617, "license_type": "no_license", "max_line_length": 48, "num_lines": 32, "path": "/Algorithms/bit_manipulation/XOR_from_1-n.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#calculate XOR from 1 to n\n'''\nhttps://www.geeksforgeeks.org/calculate-xor-1-n/\nNAIVE: O(n)\n\nbut can be done in O(1)\n\ncase 1: If n % 4 == 0 then return n\ncase 2: If n % 4 == 1 then return 1\ncase 3: If n % 4 == 2 then return n + 1\ncase 4: If n % 4 == 3 then return 0\n'''\n\n\n\ndef XOR_1_to_n(n):\n '''\n Calculates XOR from 1 to n\n :param n: int\n :return: value of xor from 1 to n\n '''\n if n % 4 == 0:\n return n\n elif n % 4 == 1:\n return 1\n elif n % 4 == 2:\n return n + 1\n elif n % 4 == 3:\n return 0\nn = int(input('Enter n value'))\nresult = XOR_1_to_n(n)\nprint(result)" }, { "alpha_fraction": 0.5123456716537476, "alphanum_fraction": 0.519753098487854, "avg_line_length": 19.769229888916016, "blob_id": "d563cfe3bff3ad402e262ce057e8f85a0bb62895", "content_id": "3c8904e5c10904d56edb8f58f4d0c14149448cd4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 818, "license_type": "no_license", "max_line_length": 103, "num_lines": 39, "path": "/Algorithms/mathematics/LCM.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#https://www.geeksforgeeks.org/program-to-find-lcm-of-two-numbers/\n'''\nLCM (Least Common Multiple) of two numbers is the smallest number which can be divided by both numbers.\nAn efficient solution is based on below formula for LCM of two numbers ‘a’ and ‘b’.\n\n a x b = LCM(a, b) * GCD (a, b)\n\n LCM(a, b) = (a x b) / GCD(a, b)\n'''\n\n\ndef gcd(a,b):\n '''\n :param a: int\n :param b: int\n :return: GCD of a and b\n '''\n if a == 0:\n return b\n if b == 0:\n return a\n if a == b:\n return a\n else:\n if a > b:\n return gcd(a-b,b)\n else:\n return gcd(a,b-a)\ndef lcm(a,b):\n '''\n :param a: int\n :param b: int\n :return: lcm of a and b\n '''\n return (a*b)/gcd(a,b)\n\na = 15\nb = 30\nprint('LCM of %d and %d is %d'%(a,b,lcm(a,b)))\n" }, { "alpha_fraction": 0.5012500286102295, "alphanum_fraction": 0.5637500286102295, "avg_line_length": 17.604650497436523, "blob_id": "7680930b7c416fa6efceaa84f8a2fa491e09bcea", "content_id": "47d7bd2b6b331a25cf255cf343e9b02ea70c792d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 800, "license_type": "no_license", "max_line_length": 91, "num_lines": 43, "path": "/singly_linked/sum two linked lists.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "# Sum of two linked lists\n# Ex1:\n# 126\n# + 987\n# -------\n# 1113\n#---------\n# For simplicity we assume length of both lists are equal and sum of lists in reverse order\nfrom singly_linked.singly import single_linked\ndef sum_list(l1,l2):\n l1 = l1.head\n l2 = l2.head\n s = single_linked()\n carry = 0\n while l1.next and l2.next:\n\n x = l1.data + l2.data + carry\n if x < 10:\n s.append(x)\n carry = 0\n\n else:\n s.append(x % 10)\n carry = 1\n l1 = l1.next\n l2 = l2.next\n\n s.append(a.data+b.data+carry)\n return s\n\nl1 = single_linked()\nl2 = single_linked()\n\nl1.append(6)\nl1.append(2)\nl1.append(1)\nl2.append(7)\nl2.append(8)\nl2.append(9)\nl1.print_reverse()\nl2.print_reverse()\ns = sum_list(l1,l2)\ns.print_reverse()\n" }, { "alpha_fraction": 0.6271777153015137, "alphanum_fraction": 0.6306620240211487, "avg_line_length": 18.200000762939453, "blob_id": "5128830cbdad7c72f20a2fa8507917fc68c627a6", "content_id": "c52600812ec8e05b9a4ede24d03fd0f428c9e322", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 287, "license_type": "no_license", "max_line_length": 59, "num_lines": 15, "path": "/Algorithms/bit_manipulation/number_set_bits.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#count number of setbits\n'''\nhttps://www.geeksforgeeks.org/count-set-bits-in-an-integer/\n'''\ndef count_set_bits(n):\n '''\n :param n: integer \n :return: count as integer\n '''\n return bin(n).count('1')\n\n\nn = int(input('enter a number'))\ncount = count_set_bits(n)\nprint(count)" }, { "alpha_fraction": 0.6504854559898376, "alphanum_fraction": 0.6601941585540771, "avg_line_length": 23.294116973876953, "blob_id": "10bedd8442aee2b91fbaa4fa92ff7b40a574006d", "content_id": "4cae685ad483f521e19825e39fda5c764251f7f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 412, "license_type": "no_license", "max_line_length": 90, "num_lines": 17, "path": "/Algorithms/bit_manipulation/bits_required_to_flip.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#https://www.geeksforgeeks.org/count-number-of-bits-to-be-flipped-to-convert-a-to-b-set-2/\n'''\nCount number of bits to be flipped to convert A to B\n\nApproach:\n1. compute A ^ B\n2. Calculate #set bits in A ^ B\n'''\n\ndef bits_required_to_flip(a,b):\n xor = a ^ b\n return bin(xor).count('1')\n\na = int(input('Enter A:'))\nb = int(input('Enter B:'))\ncount = bits_required_to_flip(a,b)\nprint(count, 'bits required')" }, { "alpha_fraction": 0.5071684718132019, "alphanum_fraction": 0.5179211497306824, "avg_line_length": 28.36842155456543, "blob_id": "83e765f18730334e9f4a2a0af91859faf0ba4df7", "content_id": "27e455a980a42c4e6c8d3bb1412c1eb3fc3cf33b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 558, "license_type": "no_license", "max_line_length": 92, "num_lines": 19, "path": "/Algorithms/mathematics/powerset.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "# https://www.geeksforgeeks.org/power-set/\n'''\nPower set P(S) of a set S is the set of all subsets of S.\nFor example S = {a, b, c} then P(s) = {{}, {a}, {b}, {c}, {a,b}, {a, c}, {b, c}, {a, b, c}}.\n\nIf S has n elements in it then P(s) will have 2^n elements\n'''\n\ndef powerset(set):\n set_size = len(set)\n power_set_size = 2 ** set_size\n for counter in range(0, power_set_size):\n for j in range(0, set_size):\n if (counter & (1 << j)) > 0:\n print(set[j], end='')\n print(' ')\n\nset = ['a', 'b', 'c']\npowerset(set)\n" }, { "alpha_fraction": 0.6470588445663452, "alphanum_fraction": 0.6797385811805725, "avg_line_length": 20.785715103149414, "blob_id": "b404adf61fc5a293acfe23820818ed507358a8f2", "content_id": "b10451fb75b62846dc394dab25d6fa77c82c53ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 306, "license_type": "no_license", "max_line_length": 124, "num_lines": 14, "path": "/arrays/arbitary precision increment.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "'''\nGiven:\n An array(list) of non-negative digits that represent a decimal integer.\n \n \nProblem:\n Add one to the integer. Assume the solution still works even if implemented in a language with finite-precision arithmetic.\n\nExample:\n [1, 4, 9] + 1 = [1,5,0]\n'''\n\nnum = \"149\"\nnum = [int(i) for i in num]\n\n" }, { "alpha_fraction": 0.43905192613601685, "alphanum_fraction": 0.51241534948349, "avg_line_length": 22.342105865478516, "blob_id": "bdb9701962d61a8222060ecb6ffe7cb233c5b32d", "content_id": "ee732722a975b8749ebac5a534e0f730382329c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 886, "license_type": "no_license", "max_line_length": 76, "num_lines": 38, "path": "/Algorithms/dynamic_prog/kth_ugly.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#RBR Interview Prep\n#Find kth ugly number\n'''\nUgly number: A ugly number is a number which contain primes factors as 2,3,5\nEx: 1,2,3,4,5,6,8,9,10,12,15 ..............\n\nApproach 1: Brute Force\n\nApproach 2: Dynamic Programming\n\nif x is an ugly number then next number is always min(x*2, x*3, x*5)\n'''\ndef get_kthugly(kth):\n '''\n :param k: integer\n :return: kth ugly number\n '''\n ugly = [0] * kth\n i2, i3, i5 = 0, 0, 0\n ugly[0] = 1\n next_2, next_3, next_5 = 2, 3, 5\n for i in range(1, kth):\n ugly[i] = min(next_2, next_3, next_5)\n if ugly[i] == next_2:\n i2 = i2 + 1\n next_2 = ugly[i2] * 2\n if ugly[i] == next_3:\n i3 = i3 + 1\n next_3 = ugly[i3] * 3\n if ugly[i] == next_5:\n i5 = i5 + 1\n next_5 = ugly[i5] * 5\n\n print(ugly)\n return ugly[-1]\n\n\nprint(get_kthugly(50))" }, { "alpha_fraction": 0.5596184134483337, "alphanum_fraction": 0.5866454839706421, "avg_line_length": 23.19230842590332, "blob_id": "ac401d5bfaf440c5dc3f72e97219dbdf3369fa46", "content_id": "dd904b30dd198b858de4c1ba0e8ed18010f0dae3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 629, "license_type": "no_license", "max_line_length": 87, "num_lines": 26, "path": "/arrays/two sum problem.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "# Given a sorted array find two indices of the elements that add up to the given number\n# Under a constraint that no two elemets are repeating\n\n#APPROACH 1: O(n^2) BruteForce - Try with all possible combinations\n\n#APPROACH 2: O(n)\n\ndef two_sum(arr,len,s):\n start = 0\n end = len - 1\n while arr[start] + arr[end] != s and start < end:\n if arr[start] + arr[end] < s:\n start = start + 1\n else:\n end = end - 1\n\n if arr[start] + arr[end] == s:\n return start,end, arr[start] + arr[end]\n else:\n return None\n\narr = [-2,1,2,4,7,11]\nlen = 6\ns = 16\n\nprint(two_sum(arr,len,s))\n" }, { "alpha_fraction": 0.823734700679779, "alphanum_fraction": 0.823734700679779, "avg_line_length": 70.75, "blob_id": "4fb73210721220bf5d6b44b452cf67ad7f8848ef", "content_id": "390f2afb09c3162847a9a5c9471b01d7911b95df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 573, "license_type": "no_license", "max_line_length": 132, "num_lines": 8, "path": "/Algorithms/greedy/notes.txt", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "Greedy Algorithms\nhttps://www.geeksforgeeks.org/greedy-algorithms/\nGreedy is an algorithmic paradigm that builds up a solution piece by piece, always choosing the next piece that offers the most\nobvious and immediate benefit. So the problems where choosing locally optimal also leads to global solution are best fit for Greedy.\n\n\nFor example consider the Fractional Knapsack Problem. The local optimal strategy is to choose the item that has maximum value\nvs weight ratio. This strategy also leads to global optimal solution because we allowed to take fractions of an item." }, { "alpha_fraction": 0.6558139324188232, "alphanum_fraction": 0.6604651212692261, "avg_line_length": 22.88888931274414, "blob_id": "ca8d236bb661fd7a110b07bb16465917e0d9533d", "content_id": "ceb0a460972d2797f78a72a027084641f5e635e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 215, "license_type": "no_license", "max_line_length": 70, "num_lines": 9, "path": "/Algorithms/greedy/ishaanLovesChocolates.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#code\n#https://practice.geeksforgeeks.org/problems/ishaan-loves-chocolates/0\n\nkases = int(input())\n\nfor kase in range(kases):\n n = int(input())\n tasty = list(map(int,input().split(' ')))\n print(min(tasty))\n" }, { "alpha_fraction": 0.6115581393241882, "alphanum_fraction": 0.6437454223632812, "avg_line_length": 33.17499923706055, "blob_id": "3a50f61465a154edf95a84ca0e22d2a2329f816c", "content_id": "925b7f26f97e83aed9480ed3f9e5cd39e08b0abe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1367, "license_type": "no_license", "max_line_length": 94, "num_lines": 40, "path": "/Algorithms/greedy/fractional_kapsack.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "'''\nGiven weights and values of n items, we need to put these items in a knapsack of capacity W to\nget the maximum total value in the knapsack.\n\nIn Fractional Knapsack, we can break items for maximizing the total value of knapsack.\nThis problem in which we can break an item is also called the fractional knapsack problem.\n\nInput:\n\n Items as (value, weight) pairs\n arr[] = {{60, 10}, {100, 20}, {120, 30}}\n Knapsack Capacity, W = 50;\nTime Complexity: O(nlogn) + O(n)\n'''\n\ndef fractioanl_knapsack(values, weights,capacity):\n '''\n :param items: two lists values and weight:\n :return: Total value of profits .\n '''\n #take p/e dictionay\n profit_weight = {i/j:[i,j] for i,j in zip(values,weights)}\n #Sort p/e dict in reverse order\n profit_weight = dict(sorted(profit_weight.items(),reverse=True))\n #Fill knapsack\n tot_value = 0\n for i in profit_weight:\n if capacity - profit_weight[i][1] > 0:\n capacity = capacity - profit_weight[i][1]\n tot_value = tot_value + profit_weight[i][0]\n else:\n fraction = capacity / profit_weight[i][1]\n tot_value = tot_value + (profit_weight[i][0] * fraction)\n capacity = capacity - (profit_weight[i][1] * fraction)\n print(tot_value)\n\nwt = [10, 40, 20, 30]\nval = [60, 40, 100, 120]\ncapacity = 50\nfractioanl_knapsack(val, wt, capacity)\n" }, { "alpha_fraction": 0.5303030014038086, "alphanum_fraction": 0.6010100841522217, "avg_line_length": 17, "blob_id": "91c93d7569fdd13ab1cb1f954c04c4cbfe204474", "content_id": "811bf862c8b9cc9fc9337b0ebaf7697a0cdb44c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 198, "license_type": "no_license", "max_line_length": 68, "num_lines": 11, "path": "/Algorithms/greedy/N meetings in one room.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "'''\nhttps://practice.geeksforgeeks.org/problems/n-meetings-in-one-room/0\n'''\n\nn = 6\nstart = [1, 3, 0, 5, 8, 5]\nend = [2, 4, 6, 7, 9, 9]\n\ndef meeting(start,end):\n duration = {}\nmeeting(start,end)\n" }, { "alpha_fraction": 0.6151202917098999, "alphanum_fraction": 0.6323024034500122, "avg_line_length": 11.69565200805664, "blob_id": "19f85a3bf08fcdea4795e7c1c437bdb0bcb5683f", "content_id": "d543e1cf6f2c02a0bddede7232014edf78363e41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 291, "license_type": "no_license", "max_line_length": 37, "num_lines": 23, "path": "/Algorithms/recursion/string_length_recursion.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#calculate lenth of the string\nst = 'Welcome to the world'\n#predefined function\nprint(len(st))\n#Iterative\ncount = 0\nfor i in st:\n count +=1\nprint(count)\n\n#recursive\n\n\n\n\n\ndef word_count(st):\n if st:\n return 1 + word_count(st[1:])\n else:\n return 0\n\nprint(word_count(st))" }, { "alpha_fraction": 0.5515320301055908, "alphanum_fraction": 0.6016713380813599, "avg_line_length": 17.894737243652344, "blob_id": "4b34d5402c539cdc4cb0664355b96ab86386a91f", "content_id": "e15f3fe97c93c9fc350af1489a19df62cdfe3d8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 359, "license_type": "no_license", "max_line_length": 70, "num_lines": 19, "path": "/Algorithms/bit_manipulation/even_odd.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#Find given number is even or odd using bit manipulation\n'''\nApproach: For any odd number least significant bit is always set to 1.\n\nEx:\n 9 --> 1001\n 15 --> 1111\n'''\ndef isodd(n):\n '''\n :param n: Integer\n :return: 1 for odd number, 0 for even\n '''\n return 1 if bin(n)[-1] == '1' else 0\n\n\n\nn = int(input('enter a number'))\nprint(isodd(n))\n" }, { "alpha_fraction": 0.46276596188545227, "alphanum_fraction": 0.4760638177394867, "avg_line_length": 17.725000381469727, "blob_id": "d1f09e7c2921266d711b556b87743cfd5d39a85e", "content_id": "65201c6d1f0be0faf229c61ab88f481fe4c9203a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 752, "license_type": "no_license", "max_line_length": 43, "num_lines": 40, "path": "/stacks/balanced_paranthesis.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "'''\nCheck for balanced paranthesis using stack\nEx:\n1. {{}[]()[[]]} ----> Balanced\n2. [[[[{{{}}}]]]][ --> Not Balanced\n'''\n\n\nfrom stacks.stack import Stacks\ns = Stacks()\ndef is_match(p1,p2):\n if p1 == '{' and p2 == '}':\n return True\n elif p1 == '[' and p2 == ']':\n return True\n elif p1 == '(' and p2 == ')':\n return True\n else:\n return False\n\n\ndef bal_paranthesis(exp):\n for i in exp:\n if i in '{[(':\n s.push(i)\n elif i in '])}':\n if is_match(s.pop(),i) != True:\n return False\n else:\n pass\n\n if s.isempty():\n return True\n else:\n return False\n\nexp = input(\"Enter an Expression\")\n\nprint(exp)\nprint(bal_paranthesis(exp))\n\n\n\n" }, { "alpha_fraction": 0.47786667943000793, "alphanum_fraction": 0.4954666793346405, "avg_line_length": 22.4375, "blob_id": "7b5507054d70144764f02f94860c52c3c6b21a44", "content_id": "8d5b63217893a15bfb763da2c914e2d319d2e536", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1875, "license_type": "no_license", "max_line_length": 80, "num_lines": 80, "path": "/trees/binary.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "class Node:\n def __init__(self,data):\n self.value = data\n self.left = None\n self.right = None\n\nclass BinaryTree:\n def __init__(self,root):\n self.root = Node(root)\n\n\n def preorder(self,start):\n if start:\n print(start.value)\n self.preorder(start.left)\n self.preorder(start.right)\n return\n\n def postorder(self,start):\n if start:\n self.postorder(start.left)\n self.postorder(start.right)\n print(start.value)\n return\n\n def inorder(self,start):\n if start:\n self.inorder(start.left)\n print(start.value)\n self.inorder(start.right)\n def levelorder(self,start):\n if start is None:\n return\n q = []\n q.append(start)\n while len(q) > 0:\n node = q.pop(0)\n print(node.value)\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n def height(self,start):\n h = 0\n if start == None:\n return h\n else:\n return max(self.height(start.left) + 1,self.height(start.right) + 1)\n\n'''\n 10\n / \\\n 15 8\n / \\ \\ \n 20 30 50 \n \\\n 150\n'''\nb = BinaryTree(10)\nb.root.left = Node(15)\nb.root.right = Node(8)\nb.root.left.left = Node(20)\nb.root.left.right = Node(30)\nb.root.right.right = Node(50)\nb.root.right.right.right = Node(150)\n\nprint(\"Pre-order is :\",end=' ')\nb.preorder(b.root)\n\nprint(\"In-order is :\",end=' ')\nb.inorder(b.root)\n\nprint(\"Post-order is :\",end=' ')\nb.postorder(b.root)\n\nprint(\"Level order is :\",end=' ')\nb.levelorder(b.root)\n\nprint(\"Height of tree is :\",end=' ')\nprint(\"height is\",b.height(b.root))\n" }, { "alpha_fraction": 0.3655097484588623, "alphanum_fraction": 0.39804771542549133, "avg_line_length": 19.977272033691406, "blob_id": "0c6dc308e6393d78476cc4fb87ad5a4844f6f107", "content_id": "42bed56960a6e858058a2973a09e4737963f95da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 922, "license_type": "no_license", "max_line_length": 46, "num_lines": 44, "path": "/Algorithms/sorting/merge.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "'''\nsoves with divide and conquer.\n\nBEST CASE: O(nlogn)\nAVG CASE: O(nlogn)\nWORST CASE: O(nlogn)\n\nSPACE : O(n)\n\n'''\n\narr = [5, 6, 1, 7, 0, 4, 12, 10, 9]\nn = len(arr)\ndef mergesort(arr):\n if len(arr) > 1:\n mid = len(arr) // 2\n left_arr = arr[:mid]\n right_arr = arr[mid:]\n mergesort(left_arr)\n mergesort(right_arr)\n\n i, j, k = 0, 0, 0\n\n l1, l2 = len(left_arr), len(right_arr)\n while i < l1 and j < l2:\n if left_arr[i] < right_arr[j]:\n arr[k] = left_arr[i]\n i = i + 1\n k = k + 1\n else:\n arr[k] = right_arr[j]\n j = j + 1\n k = k + 1\n while i < l1:\n arr[k] = left_arr[i]\n i = i + 1\n k = k + 1\n while j < l2:\n arr[k] = right_arr[j]\n j = j + 1\n k = k +1\n\nmergesort(arr)\nprint(arr)" }, { "alpha_fraction": 0.4763636291027069, "alphanum_fraction": 0.5066666603088379, "avg_line_length": 16.1875, "blob_id": "f03ddb4868284be172864c0194fcb7419a2f8cf0", "content_id": "bf83e3b22c8a7cb45512a198059cd7b15576e82f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 825, "license_type": "no_license", "max_line_length": 54, "num_lines": 48, "path": "/arrays/count number of zeros in a factorial.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "# Problem:\n# Count number of zeros in a factorial of large number\n\n# Sol:\n\n\n# Take all the multiplications in an array.\n# Ex:\n# 6! = [7,2,0]\n\ndef get_array(num):\n \"\"\"\n :param num:\n :return:\n \"\"\"\n arr = []\n while num >0:\n arr.append(num % 10)\n num = num //10\n return arr\n\ndef multiply(arr,num):\n carry = 0\n p = []\n for i in arr:\n prod = (i * num) + carry\n carry = prod//10\n p.append(prod%10)\n if carry > 9:\n while carry >= 1:\n p.append(carry % 10)\n carry = carry // 10\n else:\n p.append(carry)\n\n return p\n\nnum = int(input(\"Enter a number\"))\narr = get_array(num)\n\nwhile num > 1:\n num = num - 1\n arr = multiply(arr,num)\n\nres = arr[::-1]\nres = map(str,res)\ns = ''.join(res).lstrip('0')\nprint(s.count('0'))\n" }, { "alpha_fraction": 0.38694268465042114, "alphanum_fraction": 0.493630588054657, "avg_line_length": 20.65517234802246, "blob_id": "0089721ec86fee3751e0b3d25ab42ea2b7f8e935", "content_id": "2f700708635aa7af7486d3b2a97891cdedb9a195", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 628, "license_type": "no_license", "max_line_length": 74, "num_lines": 29, "path": "/arrays/seperate_even_odd.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#RBR Inter Prep\n#Given an array eith even and odd number seperate all even and odd numbers\n'''\nExample: [12,15,10,8,7,10,18,5,4,3,12,16]\nAns : [3, 15, 5, 7, 8, 10, 18, 10, 4, 12, 12, 16]\nApproach:\nTake left and right pointer. do swappings\n\nTIME: O(N)\n'''\n\n\ndef seperate_even_odd(arr):\n n = len(arr) - 1\n l, r = 0, n\n while l <= r:\n if arr[l] % 2 == 1:\n l = l + 1\n if arr[r] % 2 == 0:\n r = r - 1\n else:\n arr[l], arr[r] = arr[r], arr[l]\n l = l + 1\n r = r - 1\n return arr\n\n\narr = [12,15,10,8,7,10,18,5,4,3,12,16]\nprint(seperate_even_odd(arr))\n" }, { "alpha_fraction": 0.5039232969284058, "alphanum_fraction": 0.5074106454849243, "avg_line_length": 19.48214340209961, "blob_id": "00b6a9f872982ba62d185c66911c632e167b16b2", "content_id": "9ac8e5dfe0e475d2d0c3e53757b23aa8b77102e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1147, "license_type": "no_license", "max_line_length": 48, "num_lines": 56, "path": "/stacks/stack.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "\nclass Stacks():\n '''\n Basic operations with stack\n A stack is created with a list\n '''\n def __init__(self):\n '''\n Create a stack with an empty list\n '''\n self.items = []\n\n def push(self,item):\n '''\n Push an item into stack\n :param item: A item to push into stack\n :return: None\n '''\n self.items.append(item)\n\n def pop(self):\n '''\n pops an item\n :return: popped element\n '''\n return self.items.pop()\n\n def peek(self):\n '''\n Get the top most element from the stack\n :return: top most element from the stack\n '''\n return self.items[-1]\n\n def isempty(self):\n '''\n Check wheater a stack is empty or nor\n :return: True/ False\n '''\n return self.items == []\n def get_items(self):\n '''\n Get all the items in the stack\n :return: list of elements in a stack\n '''\n return self.items\n\ns = Stacks()\n\n'''s.push(1)\ns.push(2)\ns.push(3)\nprint(s.get_items())\nprint(s.isempty())\ns.pop()\nprint(s.peek())\nprint(s.get_items())'''" }, { "alpha_fraction": 0.4934210479259491, "alphanum_fraction": 0.5350877046585083, "avg_line_length": 19.772727966308594, "blob_id": "d37f2885864b741f6bf9db9aebce1713946f6fb5", "content_id": "45ce2ae7525ab1bd98f6ecad91b4a5cca18f664b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 456, "license_type": "no_license", "max_line_length": 115, "num_lines": 22, "path": "/Algorithms/sorting/insertion.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "'''\nInsertion Sort: Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands.\nBEST CASE: O(n)\nAVG CASE: O(n^2)\nWORST CASE: O(n^2)\n'''\n\narr = [5, 6, 1, 7, 0, 4, 12, 10, 9]\nn = len(arr)\n\n\ndef insertion(arr,n):\n for i in range(1,n):\n j = i - 1\n key = arr[i]\n while key < arr[j] and j >= 0:\n arr[j+1] = arr[j]\n j = j - 1\n arr[j+1] = key\n\ninsertion(arr,n)\nprint(arr)" }, { "alpha_fraction": 0.4863870441913605, "alphanum_fraction": 0.4883492887020111, "avg_line_length": 24.316770553588867, "blob_id": "0b09b72360a5660753d4e54b1dac89e4b9b24b8f", "content_id": "c423fd54198303540b29fe45b6f7df52fe4db4c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4077, "license_type": "no_license", "max_line_length": 68, "num_lines": 161, "path": "/singly_linked/singly.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "class Node:\n def __init__(self,data):\n self.data = data\n self.next = None\n\nclass single_linked:\n def __init__(self):\n self.head = None\n\n def append(self,item):\n '''\n Append item to the list at the last position\n :param item: item which has to be appended\n :return: None\n '''\n if self.head is None:\n self.head = Node(item)\n\n else:\n last_node = self.head\n while last_node.next is not None:\n last_node = last_node.next\n last_node.next = Node(item)\n\n\n\n def insert_begin(self,item):\n '''\n Inserts an element at the begining of the list\n :param item: item to be inserted\n :return: None\n '''\n temp = Node(item)\n temp.next = self.head\n self.head = temp\n\n \n def insert_pos(self,item,pos):\n '''\n Insert at any arbitary position\n :param item: Item to insert\n :param pos: starts from 1 ie., begining\n :return: None\n '''\n temp = Node(item)\n i = 2\n curr = self.head\n while i<pos and curr.next != None:\n curr = curr.next\n i = i + 1\n temp.next = curr.next\n\n curr.next = temp\n\n def print_list(self):\n '''\n Prints all the elements in the list\n :return: None\n '''\n curr = self.head\n while curr:\n print(curr.data,end=' ')\n curr = curr.next\n print()\n\n\n def delete_item(self,item,singly):\n '''\n Checks wheater a given element is present in the list or not\n and delete the element if it is present\n\n :param item: Item to be deleted\n :param singly: List on which the item has to be deleted\n :return: Updated list if the item is present else do nothing\n '''\n\n if singly.find_item(item):\n curr = self.head\n last = self.head\n if curr.data == item:\n self.head = curr.next\n else:\n while (curr.next and curr.data != item):\n last = curr\n curr = curr.next\n last.next = curr.next\n else:\n print(\"Entered element can't be deleted\")\n\n def find_item(self,item):\n '''\n Check wheater given element is present in the list or not\n :param item: item which has to be check\n :return: True if the item is present else False\n '''\n curr = self.head\n while curr.next and curr.data != item:\n curr = curr.next\n if curr.data == item:\n return True\n else:\n return False\n\n\n def length(self):\n '''\n Length of the list\n :return: count of the list\n '''\n count = 0\n curr = self.head\n\n while(curr != None):\n curr = curr.next\n count = count + 1\n return count\n\n def print_reverse(self):\n '''\n Print a list in reversed order. List remains same\n :return: None\n '''\n curr = self.head\n l = []\n while curr:\n l.append(curr.data)\n curr = curr.next\n print(l[::-1])\n\n def reverse_list(self):\n '''\n Reverses a linked list\n :return:\n '''\n curr = self.head\n prev = None\n up = curr.next\n while(up):\n #print(curr.data)\n curr.next = prev\n prev = curr\n curr = up\n up = curr.next\n curr.next = prev\n self.head = curr\n\n def count_occurances(self,item,singly):\n '''\n Count number of times item occures in the list\n :param item: item of the list\n :return: number of times item occured in the list\n '''\n count = 0\n if singly.find_item(item):\n curr = self.head\n while(curr):\n if curr.data == item:\n count = count + 1\n curr = curr.next\n\n return count\n\n" }, { "alpha_fraction": 0.5916230082511902, "alphanum_fraction": 0.5994764566421509, "avg_line_length": 23.645160675048828, "blob_id": "bfec67667b1adf3ae097d1432c188581da52bb9e", "content_id": "7dc0cef638397a25237a46ef78c02b6621138e95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 766, "license_type": "no_license", "max_line_length": 124, "num_lines": 31, "path": "/Algorithms/mathematics/GCD.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#https://www.geeksforgeeks.org/c-program-find-gcd-hcf-two-numbers/\n'''\nGCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest number that divides both of them.\n\nAn efficient solution is to use Euclidean algorithm which is the main algorithm used for this purpose.\nThe idea is, GCD of two numbers doesn’t change if smaller number is subtracted from a bigger number.\n'''\n\n\ndef gcd(a,b):\n '''\n :param a: int\n :param b: int\n :return: GCD of a and b\n '''\n if a == 0:\n return b\n if b == 0:\n return a\n if a == b:\n return a\n else:\n if a > b:\n return gcd(a-b,b)\n else:\n return gcd(a,b-a)\n\na = 15\nb = 45\n\nprint('GCD of %d and %d id %d' % (a,b,gcd(a,b)))\n" }, { "alpha_fraction": 0.5034802556037903, "alphanum_fraction": 0.5074245929718018, "avg_line_length": 26.80645179748535, "blob_id": "02dfecb5970841afd1cb018d9a8decadb700e9a7", "content_id": "9faef5ea3c9bc63f7bf02937650f7e07ad4cc1eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4310, "license_type": "no_license", "max_line_length": 96, "num_lines": 155, "path": "/trees/binary_search_tree.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "class Node:\n def __init__(self,data=None):\n self.data = data\n self.left = None\n self.right = None\n \nclass BST:\n def __init__(self):\n self.root = None\n\n def insert(self,data):\n if self.root == None:\n self.root = Node(data)\n else:\n self._insert(self.root,data)\n\n def _insert(self,curr,data):\n if data < curr.data:\n if curr.left is None:\n curr.left = Node(data)\n else:\n self._insert(curr.left,data)\n elif data > curr.data:\n if curr.right is None:\n curr.right = Node(data)\n else:\n self._insert(curr.right,data)\n else:\n print(\"Value is already present in the tree\")\n\n \n def find(self,data):\n is_found = False\n if self.root.data is None:\n print(\"Tree is empty\")\n is_found = False\n else:\n is_found = self._find(data,self.root)\n\n if is_found:\n print(\"value is present\")\n else:\n print(\"value is not present\")\n\n def delete(self,data):\n parent, child = self.get_parent1(data)\n print(parent.data, child.data)\n #case 1 = leaf\n if child.left == None and child.right == None:\n if data > parent.data:\n parent.right = None\n else:\n parent.left = None\n #case 2 = single child\n elif child.left == None or child.right == None:\n if data > parent.data:\n if child.left:\n parent.right = child.left\n else:\n parent.right = child.right\n\n else:\n if child.left:\n parent.left = child.left\n else:\n parent.left = child.right\n else:\n #case3 --> node with two children\n current = self.get_min_right(child)\n self.delete(current.data)\n print('-->',current.data)\n if data > parent.data:\n parent.right = current\n elif data < parent.data:\n parent.left = current\n else:\n self.root = current\n\n current.left, current.right = child.left, child.right\n\n def get_min_right(self,current):\n\n while current.left != None or current.right != None:\n if current.right:\n current = current.right\n elif current.left:\n current = current.left\n return current\n\n\n def get_parent1(self,data):\n if self.root.data == data:\n return self.root,self.root\n else:\n parent,child = self.root, self.root\n while child.data != data:\n if child.data > data:\n parent = child\n child = child.left\n elif child.data < data:\n parent = child\n child = child.right\n\n return parent,child\n\n def get_parent(self,parent,child):\n if parent:\n if parent.left and parent.left.data == child:\n return parent,child\n if parent.right and parent.right.data == child:\n return parent,child\n else:\n return self.get_parent(parent.left,child) or self.get_parent(parent.right,child)\n\n def _find(self,data,curr):\n if curr.data == data:\n return True\n elif data < curr.data and curr.left:\n return self._find(data,curr.left)\n\n elif data > curr.data and curr.right:\n return self._find(data, curr.right)\n\n def preorder(self,start):\n if start:\n print(start.data)\n self.preorder(start.left)\n self.preorder(start.right)\n return\n\n def inorder(self,start):\n if start:\n self.inorder(start.left)\n print(start.data)\n self.inorder(start.right)\n return\n\n\nbst = BST()\nbst.insert(5)\n\nbst.insert(2)\nbst.insert(15)\nbst.insert(20)\nbst.insert(8)\nbst.insert(18)\n#print(\"Pre-order is :\")\n#bst.preorder(bst.root)\n#print(\"Inorder is :\")\n#bst.inorder(bst.root)\nbst.find(50)\nbst.delete(5)\n\n#print(bst.root.right.right.left.data)\nbst.preorder(bst.root)\n" }, { "alpha_fraction": 0.5133333206176758, "alphanum_fraction": 0.5799999833106995, "avg_line_length": 17.79166603088379, "blob_id": "daa15f78311ba08c2cfea0f08df9ac60f8c06736", "content_id": "f484d3e74865e6e864f27f68e8839c7455223437", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 450, "license_type": "no_license", "max_line_length": 43, "num_lines": 24, "path": "/Algorithms/bit_manipulation/toggle_kth_bit.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#RBR interview prep\n#toggle kth bit of a number\n'''\nwe assume that index of LSB is 0 here k = 3\nex: 1000010\nxor 0001000 (to get this: 1 << k)\n-------------\nans 1001010 ----> return\n-------------\nTIME: O(log n)\n'''\n\n\ndef toggle_kth_bit(num, k):\n '''\n :param num: integer, number to test\n :param k: integer, position to test\n :return: integer, with kth bit set\n '''\n num2 = 1 << k\n return num ^ num2\n\n\nprint(toggle_kth_bit(89, 2))" }, { "alpha_fraction": 0.6941176652908325, "alphanum_fraction": 0.7176470756530762, "avg_line_length": 16, "blob_id": "5190239453cdbbb4ff940c3d5c6183fcdca87bd4", "content_id": "e624cf4ee2fe8a15e92e66eb47e0011213f60d0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 170, "license_type": "no_license", "max_line_length": 48, "num_lines": 10, "path": "/circular linked list/josephus problem.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "# Josephus problem\n# https://en.wikipedia.org/wiki/Josephus_problem\n\nfrom circular_list import circular\nc = circular.circular_list()\nn = 7\nk = 3\n\n\nfor i in range(1,n+1):\n" }, { "alpha_fraction": 0.5011337995529175, "alphanum_fraction": 0.5691609978675842, "avg_line_length": 17.41666603088379, "blob_id": "b48247821c7f8de6b9fe518f114ade72612de919", "content_id": "7b9bbfe22abb8db92f5a25c328dc820c7cfde71d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 441, "license_type": "no_license", "max_line_length": 43, "num_lines": 24, "path": "/Algorithms/bit_manipulation/set_kth_bit.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#RBR interview prep\n#set kth bit of a number\n'''\nwe assume that index of LSB is 0 here k = 3\nex: 1000010\nor 0001000 (to get this: 1 << k)\n-------------\nans 1001010 ----> return\n-------------\nTIME: O(log n)\n'''\n\n\ndef set_kth_bit(num, k):\n '''\n :param num: integer, number to test\n :param k: integer, position to test\n :return: integer, with kth bit set\n '''\n num2 = 1 << k\n return num | num2\n\n\nprint(set_kth_bit(89, 2))" }, { "alpha_fraction": 0.597046434879303, "alphanum_fraction": 0.6434599161148071, "avg_line_length": 30.53333282470703, "blob_id": "ea00672f73fcc3cfb4e511d6ef24fac4ec75820b", "content_id": "93d4f8b170c9c9021399a5734d2407aba36bd521", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 474, "license_type": "no_license", "max_line_length": 174, "num_lines": 15, "path": "/Algorithms/bit_manipulation/number_occuring_odd_times.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "#https://www.geeksforgeeks.org/find-the-number-occurring-odd-number-of-times\n'''\nGiven an array of positive integers. All numbers occur even number of times except one number which occurs odd number of times. Find the number in O(n) time & constant space.\n\nInput : arr = {1, 2, 3, 2, 3, 1, 3}\nOutput : 3\n'''\n\ndef odd_ocuurance(arr):\n res = 0\n for i in arr:\n res = res ^ i\n return res\narr = [ 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2]\nprint(odd_ocuurance(arr))\n\n" }, { "alpha_fraction": 0.5536193251609802, "alphanum_fraction": 0.5764074921607971, "avg_line_length": 18.657894134521484, "blob_id": "ac256e05d322a78ee05825bca910c75b613f25e4", "content_id": "c438e94114540d9bfbc6193197db57f4a3fc5562", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 746, "license_type": "no_license", "max_line_length": 97, "num_lines": 38, "path": "/Algorithms/sorting/count.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "'''\ncount sort: Count the coccurances in a list, and convert occurances list to form a original list.\n\nBEST CASE: O(n+k)\nAVG CASE: O(n+k)\nWORST CASE: O(n+k)\nSPCAE : O(n+k)\n\nExample: consider array in range (0,9)\n'''\n\n\ndef counting(arr,low,high):\n '''\n Perform counting sort on the given array.\n :param arr: integers\n :param low: least number\n :param high: higher number\n :return: sorted array\n '''\n sort = []\n count = [0 for i in range(low,high+1)]\n for i in arr:\n count[i] = count[i] + 1\n\n\n j = 0\n for i in range(len(count)):\n while count[i] > 0:\n sort.append(i)\n count[i] -= 1\n return sort\n\n\narr = [1, 4, 1, 2, 7, 5, 2]\nlow = 0\nhigh = 9\n#print(counting(arr, low, high))" }, { "alpha_fraction": 0.4642857015132904, "alphanum_fraction": 0.5338345766067505, "avg_line_length": 18, "blob_id": "04b7eeda5ad7df885258deda129b3db0d18708fc", "content_id": "aec452954d12cd4a663bc4004e8e509ca7212ae2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 532, "license_type": "no_license", "max_line_length": 52, "num_lines": 28, "path": "/Algorithms/bit_manipulation/check_kth_bit_is_set.py", "repo_name": "somasekharreddy1119/DS-Algo-with-python", "src_encoding": "UTF-8", "text": "# RBR Interview Prep\n# Check kth bit is set or not\n'''\nwe assume that index of LSB is 0 here k = 3\nex: 1001010\nand 0001000 (to get this: 1 << k)\n-------------\nans 0001000 ----> if set then sol > 0; else sol = 0\n-------------\nTIME: O(logn)\n'''\n\n\ndef check_kth_bit(num, k):\n '''\n :param num: integer, number to test\n :param k: integer, position to test\n :return: 0 if not set\n 1 if set\n '''\n num2 = 1 << k\n if num & num2 > 0:\n return 1\n else:\n return 0\n\n\nprint(check_kth_bit(89, 2))\n" } ]
63
Abhinaya-Venigalla/s1498572
https://github.com/Abhinaya-Venigalla/s1498572
a0908f3f2ab4c5a8441a5cdb2fd4fbcef16198a0
e8098489be4beb7bc7469f680266fe0afdb70c98
23f448e2e6991f344dc083e6cd6d96172dabf246
refs/heads/master
2021-01-27T15:02:38.530060
2020-02-27T09:37:28
2020-02-27T09:37:28
243,482,231
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5750300288200378, "alphanum_fraction": 0.5762304663658142, "avg_line_length": 22.441177368164062, "blob_id": "21aeb2bf113ccfd0cf12e25d481b9d0c53dfb9c9", "content_id": "eb737508e4eb305fcf9ffe098fa13545ccc67d74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 833, "license_type": "no_license", "max_line_length": 61, "num_lines": 34, "path": "/intro.py", "repo_name": "Abhinaya-Venigalla/s1498572", "src_encoding": "UTF-8", "text": "#strings and output\r\nmsg= \"Hello World\"\r\nprint(msg)\r\n# lists\r\npets = [\"Dog\", \"Cat\", \"Fish\"]\r\nthepet = pets[1]\r\nprint (thepet)\r\n# length $ Types\r\nsize = len(pets)\r\nmsg = \"there are\" + str(size)+ \"pets\"\r\nprint (msg)\r\n#loops\r\nfor anml in pets:\r\n print(\"I wish I had a \" + anml)\r\n#user input\r\nans = input(\"What kind of a pet do you have?\")\r\nprint (\"you have a \" + ans)\r\n# booleans\r\nknown = ans in pets\r\nprint (\" it is \" + str(known) + \" that i have seen a \" + ans)\r\n#branching\r\nif known:\r\n msg = \"My friend has a \" + ans\r\nelse:\r\n msg = \"I don't know anyone with a \" + ans\r\nprint(msg)\r\n#dictonary\r\nfeels = {\"Cat\":\"selfish\" , \"Dog\":\"loyal\" , \"Fish\":\"wet\"}\r\nif known:\r\n pre = \"e\" if ans == \"Fish\" else \"\"\r\n msg = ans + pre + \"s are very \" + feels.get(ans)\r\nelse:\r\n msg = \"I don't know anyone with a \" + ans\r\nprint(msg)\r\n\r\n" } ]
1
podgorniy/alfred-translate
https://github.com/podgorniy/alfred-translate
4c57d24a1d5dc819644dba37aeeae6a570c9a811
c9051a206dfa4778f180b8fa858032a4431124ab
7beefa765f3ce5a4f7de48a19123a1df5477fdfd
refs/heads/master
2022-06-25T15:51:47.969929
2022-06-17T10:40:48
2022-06-17T10:40:48
15,757,388
165
13
MIT
2014-01-09T05:19:10
2022-06-15T15:11:55
2022-06-17T10:40:48
Python
[ { "alpha_fraction": 0.6089228391647339, "alphanum_fraction": 0.6354501843452454, "avg_line_length": 32.18000030517578, "blob_id": "90ce0918b99d527201ac24e36b907e226bcda360", "content_id": "45df24b5416cfd30a75fcd2314ae84d32803f215", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4976, "license_type": "permissive", "max_line_length": 117, "num_lines": 150, "path": "/src/translate.py", "repo_name": "podgorniy/alfred-translate", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport urllib.parse\nimport urllib.request\nimport json\nimport feedback\nfrom multiprocessing import Pool\nimport re\nimport sys\n\ndict_api_key = 'dict.1.1.20140108T003739Z.52c324b8a4eea3ac.5767100e8cc7b997dad88353e47aa4857e786beb'\ntranslate_api_key = 'trnsl.1.1.20130512T104455Z.8a0ed400b0d249ba.48af47e72f40c8991e4185556b825273d104af68'\n\n\ndef is_ascii(s):\n \"\"\"http://stackoverflow.com/questions/196345/how-to-check-if-a-string-in-python-is-in-ascii\"\"\"\n return all(ord(c) < 128 for c in s)\n\n\ndef get_translation_direction(text):\n \"\"\"Returns direction of translation. en-ru or ru-en\"\"\"\n if is_ascii(text):\n return 'en-ru'\n else:\n return 'ru-en'\n\n\ndef get_lang(text):\n \"\"\"Returns either 'ru' or 'en' corresponding for text\"\"\"\n if is_ascii(text):\n return 'en'\n else:\n return 'ru'\n\n\ndef convert_spelling_suggestions(spelling_suggestions):\n res = []\n if len(spelling_suggestions) != 0:\n for spelling_suggestion in spelling_suggestions:\n res.append({\n 'title': spelling_suggestion,\n 'autocomplete': spelling_suggestion\n })\n return res\n\n\ndef get_spelling_suggestions(spelling_suggestions):\n \"\"\"Returns spelling suggestions from JSON if any \"\"\"\n res = []\n if spelling_suggestions and spelling_suggestions[0] and spelling_suggestions[0]['s']:\n res = spelling_suggestions[0]['s']\n return res\n\n\ndef get_translation_suggestions(input_string, spelling_suggestions, vocabulary_article):\n \"\"\"Returns XML with translate suggestions\"\"\"\n res = []\n if len(spelling_suggestions) == 0 and len(vocabulary_article) == 0:\n return res\n\n if len(vocabulary_article['def']) != 0:\n for article in vocabulary_article['def']:\n for translation in article['tr']:\n if 'ts' in article.keys():\n subtitle = article['ts']\n elif 'ts' in translation.keys():\n subtitle = translation['ts']\n else:\n subtitle = ''\n res.append({\n 'translation': translation['text'],\n 'transcription': subtitle,\n })\n\n return res\n\n\ndef process_response_as_json(request_url):\n \"\"\"Accepts request url returns response as \"\"\"\n request = urllib.request.urlopen(request_url)\n response_json = json.loads(request.read())\n return response_json\n\n\ndef get_output(input_string):\n \"\"\"Main entry point\"\"\"\n pool = Pool(processes=3)\n fb = feedback.Feedback()\n input_string = input_string.strip()\n if not input_string:\n fb.add_item(title=\"Translation not found\", valid=\"no\")\n return fb\n\n # Building urls\n translationDirection = get_translation_direction(input_string)\n\n # Build spell check url\n spellCheckParams = {\n 'text': input_string,\n 'lang': get_lang(input_string)\n }\n spellCheckUrl = 'https://speller.yandex.net/services/spellservice.json/checkText' + '?' + urllib.parse.urlencode(\n spellCheckParams)\n\n # Build article url\n articleParams = {\n 'key': dict_api_key,\n 'lang': translationDirection,\n 'text': input_string,\n 'flags': 4\n }\n articleUrl = 'https://dictionary.yandex.net/api/v1/dicservice.json/lookup' + '?' + urllib.parse.urlencode(\n articleParams)\n\n # Making requests in parallel\n requestsUrls = [spellCheckUrl, articleUrl]\n responses = pool.map(process_response_as_json, requestsUrls)\n\n spelling_suggestions_items = get_spelling_suggestions(responses[0])\n # Generate possible xml outputs\n formatted_spelling_suggestions = convert_spelling_suggestions(spelling_suggestions_items)\n formated_translation_suggestions = get_translation_suggestions(input_string, spelling_suggestions_items,\n responses[1])\n words_in_phase = len(re.split(' ', input_string))\n\n # Output\n if len(formatted_spelling_suggestions) == 0 and len(formated_translation_suggestions) == 0:\n fb.add_item(title=\"Translation not found\", valid=\"no\")\n return fb\n\n # Prepare suggestions output\n # Spellcheck error\n if words_in_phase <= 2 and len(formatted_spelling_suggestions) != 0:\n for spelling_suggestion in formatted_spelling_suggestions:\n fb.add_item(title=spelling_suggestion['title'],\n autocomplete=spelling_suggestion['autocomplete'],\n icon='spellcheck.png')\n\n # Translations output\n for formatted_translated_suggestion in formated_translation_suggestions:\n fb.add_item(\n title=formatted_translated_suggestion['translation'],\n arg=formatted_translated_suggestion['translation'],\n subtitle=formatted_translated_suggestion['transcription']\n )\n return fb\n\n\nif __name__ == '__main__':\n print(get_output(sys.argv[1]))" }, { "alpha_fraction": 0.7433276772499084, "alphanum_fraction": 0.7756956219673157, "avg_line_length": 26.515625, "blob_id": "01dad4ac0ae08552d3619acc58c07a13fa03c500", "content_id": "224b059ab2e427f3d1549fe2bbec45072e119558", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2679, "license_type": "permissive", "max_line_length": 119, "num_lines": 64, "path": "/README.md", "repo_name": "podgorniy/alfred-translate", "src_encoding": "UTF-8", "text": "# RU-EN EN-RU Translating Alfred Workflow\n\n[Скачать](https://github.com/podgorniy/alfred-translate/raw/master/Translate.alfredworkflow)\n> Работает с версией macOs 12.4 и выше\n> Работа на более поздних версиях подразумевает использования python3 \n\nУдобный перевод текстов в en-ru ru-en направлениях.\n\n- Переводит русский текст на английский. Английский текс в русский. Не нужно указывать направление перевода.\n- Работает как с вводимым текстом, так и с выделенным.\n- Показывает варианты перевода для одного слова.\n- Показывает транскрипцию при переводе с английского.\n- Исправляет ошибки в словах.\n- Переводит как слова так и предложения.\n- Копирует результат перевода в буфер обмена.\n- Не работает без интернет соединения.\n\n\nПеревод слова, запуск из строки Альфреда по ключевому слову `t` или `e`:\n\n![Скриншот](screenshot-1.png)\n\n\nПеревод выделенного предложения по хоткею. Для себя настроил сочетание `ctrl+shift+t`.\n\n![Скриншот](screenshot-2.png)\n\nВарианты автодополнения при ошибке в написании слова.\n\n![Скриншот](screenshot-3.png)\n\nЗа иконку спасибо [Artem Beztsinnyi](http://bezart.ru).\n\nАльтернативные workflow для перевода:\n\n- [AlfredGoogleTranslateWorkflow](https://github.com/thomashempel/AlfredGoogleTranslateWorkflow)\n\n## Changelog\n\n**2020.10.06\n\n- [denisborovikov](https://github.com/denisborovikov) убрал запрос к неработающему API yandex, и плагин снова работает.\n\n**2020.06.13**\n\n- Исправлена [экранизация пробелов](https://github.com/podgorniy/alfred-translate/issues/10).\n\n**2019.06.27**\n\n- Подхватываются настройки прокси из `.bashrc`\n\n\n**2018.08.21**\n\n- Добавлен перевод по русской букве `е`.\n\n\n**2017.04.02**\n\n- Улучшена производительность.\n- Добавлена подсказка ошибок вместе с вариантами перевода.\n\n2015.10.05\n- Добавлено экранирование кавычек `'`.\n" }, { "alpha_fraction": 0.5722580552101135, "alphanum_fraction": 0.5729032158851624, "avg_line_length": 32, "blob_id": "53cf82ca7bdac07eb1414763d50c221ee004b879", "content_id": "77446f2cad0bcb21bfdc80ab52a630194abd9da5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1550, "license_type": "permissive", "max_line_length": 122, "num_lines": 47, "path": "/src/feedback.py", "repo_name": "podgorniy/alfred-translate", "src_encoding": "UTF-8", "text": "#author: Peter Okma\nimport xml.etree.ElementTree as et\n\n\nclass Feedback():\n \"\"\"Feeback used by Alfred Script Filter\n\n Usage:\n fb = Feedback()\n fb.add_item('Hello', 'World')\n fb.add_item('Foo', 'Bar')\n print fb\n\n \"\"\"\n\n def __init__(self):\n self.feedback = et.Element('items')\n\n def __repr__(self):\n \"\"\"XML representation used by Alfred\n\n Returns:\n XML string\n \"\"\"\n return str(et.tostring(self.feedback), \"utf-8\")\n\n def add_item(self, title, subtitle=\"\", arg=\"\", valid=\"yes\", autocomplete=\"\", icon=\"icon.png\"):\n \"\"\"\n Add item to alfred Feedback\n\n Args:\n title(str): the title displayed by Alfred\n Keyword Args:\n subtitle(str): the subtitle displayed by Alfred\n arg(str): the value returned by alfred when item is selected\n valid(str): whether or not the entry can be selected in Alfred to trigger an action\n autcomplete(str): the text to be inserted if an invalid item is selected. This is only used if 'valid' is 'no'\n icon(str): filename of icon that Alfred will display\n \"\"\"\n item = et.SubElement(self.feedback, 'item', uid=str(len(self.feedback)),\n arg=arg, valid=valid, autocomplete=autocomplete)\n _title = et.SubElement(item, 'title')\n _title.text = title\n _sub = et.SubElement(item, 'subtitle')\n _sub.text = subtitle\n _icon = et.SubElement(item, 'icon')\n _icon.text = icon" } ]
3
Shraddhaaj/GIT_Assignment
https://github.com/Shraddhaaj/GIT_Assignment
f8205fa9c90b1b9b11cee51d846171da19e136e0
69fe1c107ab4f74dd7d8293001c3de72b6c4e8de
144b2c0dd96247bf366030c3fe17fcdd4f4ba745
refs/heads/main
2023-07-13T20:42:56.538367
2021-08-26T21:34:51
2021-08-26T21:34:51
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8181818127632141, "alphanum_fraction": 0.8181818127632141, "avg_line_length": 15.5, "blob_id": "6918e3df0b0833d8ea42a73fab0711f00abda8f4", "content_id": "058a7d065a53d6b9b7a03cf14663160923dc89f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 33, "license_type": "no_license", "max_line_length": 16, "num_lines": 2, "path": "/README.md", "repo_name": "Shraddhaaj/GIT_Assignment", "src_encoding": "UTF-8", "text": "# GIT_Assignment\nGit_assignments\n" }, { "alpha_fraction": 0.4749999940395355, "alphanum_fraction": 0.574999988079071, "avg_line_length": 9, "blob_id": "783cab4e42b2becd351e78f96433bc6f37953650", "content_id": "309005650f8c9e30979b1a69e750c3fb75fd71ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 40, "license_type": "no_license", "max_line_length": 22, "num_lines": 4, "path": "/recording1.py", "repo_name": "Shraddhaaj/GIT_Assignment", "src_encoding": "UTF-8", "text": "x=20\ny=30\nz =x+y\nprint(\"Total sum:\", z)\n" } ]
2
chiarabianchin/NaturalCycles
https://github.com/chiarabianchin/NaturalCycles
95f551a6f781ff6e3452955144fab983deb9b829
08ef521168d06b9c6f0573193133fc0ea563221d
4a207e7cd9fdfeff8ec3cb209c326ffac6a3fbf2
refs/heads/master
2020-03-11T04:18:12.543310
2018-04-16T16:25:46
2018-04-16T16:25:46
129,773,486
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6494035720825195, "alphanum_fraction": 0.6682902574539185, "avg_line_length": 39.894309997558594, "blob_id": "f9ee72b70ca243f1d456e09cafbe73e9f5fcfac9", "content_id": "84bdb5cb5cd0d80f1ac7e758596811ffe828161d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10060, "license_type": "no_license", "max_line_length": 222, "num_lines": 246, "path": "/root/natural_cycles.C", "repo_name": "chiarabianchin/NaturalCycles", "src_encoding": "UTF-8", "text": "#include <TTree.h>\n#include <TH2F.h>\n#include <TF2.h>\n#include <TCanvas.h>\n#include <TGraph.h>\n#include <TLatex.h>\n#include <TCut.h>\n#include <TLegend.h>\n#include <TStyle.h>\n#include <TPaveText.h>\n\nvoid natural_cycles(){\n\n gStyle->SetPalette(kLightTemperature);\n \n TTree *db = new TTree(); db->ReadFile(\"anafile_challenge_170522.csv\", \"Country/C:Age/I:NumBMI/F:Pill/C:NCbefore:FPlength:Weight/F:CycleVar/C:TempLogFreq/F:SexLogFreq:DaysTrying/I:CyclesTrying:ExitStatus/C:AnovCycles/I\");\n\n // general look\n TCanvas *c_country = new TCanvas(\"c_country\", \"Countries\");\n c_country->cd();\n db->Draw(\"Country\");\n TCanvas *c_days = new TCanvas(\"c_days\", \"Days Trying\");\n c_days->cd();\n db->Draw(\"DaysTrying\");\n TCanvas *c_cicles = new TCanvas(\"c_cicles\", \"Cycles Trying\");\n c_cicles->cd();\n db->Draw(\"CyclesTrying\");\n TCanvas *c_weight = new TCanvas(\"c_weight\", \"Weight\");\n c_weight->cd();\n db->Draw(\"Weight\");\n TCanvas *c_bmi = new TCanvas(\"c_bmi\", \"NumBMI\");\n c_bmi->cd();\n db->Draw(\"NumBMI\");\n\n TCanvas *c_fpl = new TCanvas(\"c_fpl\", \"FPlength\");\n c_fpl->cd();\n db->Draw(\"FPlength\");\n\n TCanvas *c_tlogf = new TCanvas(\"c_tlogf\", \"Temperature logging frequency\");\n c_tlogf->cd();\n db->Draw(\"TempLogFreq\");\n\n // distributions for pregnant and trying\n TCut preg = TCut(\"ExitStatus==\\\"Pregnant\\\"\");\n TCut right = TCut(\"ExitStatus==\\\"Right\\\"\");\n TCut dout = TCut(\"ExitStatus==\\\"Dropout\\\"\");\n \n TCanvas *c_days_cut = new TCanvas(\"c_days_cut\", \"Days Trying\");\n c_days_cut->cd();\n db->Draw(\"DaysTrying\", preg);\n gPad->ls();\n TH1F *hdays_trying_preg = (TH1F*)gPad->GetPrimitive(\"htemp\");\n cout<<\"Pointer\" << hdays_trying_preg;\n hdays_trying_preg->SetNameTitle(\"hdays_trying_preg\", \"DaysTrying;Days Trying; Fraction per day\");\n hdays_trying_preg->Scale(1./ hdays_trying_preg->Integral());\n hdays_trying_preg->SetMarkerStyle(kFullCircle);\n hdays_trying_preg->SetMarkerSize(1.6);\n hdays_trying_preg->SetMarkerColor(kGreen+2);\n \n db->Draw(\"DaysTrying\", right, \"sames\");\n TH1F *hdays_trying_right = (TH1F*)gPad->GetPrimitive(\"htemp\");\n hdays_trying_right->SetName(\"hdays_trying_right\");\n cout<<\"Pointer\" << hdays_trying_right;\n hdays_trying_right->Scale(1./ hdays_trying_right->Integral());\n hdays_trying_right->SetMarkerStyle(kFullStar);\n hdays_trying_right->SetMarkerSize(1.6);\n hdays_trying_right->SetMarkerColor(kRed);\n\n \n db->Draw(\"DaysTrying\", dout, \"sames\");\n TH1F *hdays_trying_dout = (TH1F*)gPad->GetPrimitive(\"htemp\");\n hdays_trying_dout->SetName(\"hdays_trying_dout\");\n hdays_trying_dout->Scale(1./ hdays_trying_dout->Integral());\n hdays_trying_dout->SetMarkerStyle(kOpenCircle);\n hdays_trying_dout->SetMarkerSize(1.6);\n hdays_trying_dout->SetMarkerColor(kOrange);\n\n \n TLegend *leg = new TLegend(0.3, 0.7, 0.6, 0.9, \"Normalized to integral\");\n leg->AddEntry(hdays_trying_preg, \"Pregnant\");\n leg->AddEntry(hdays_trying_right, \"Right\");\n leg->AddEntry(hdays_trying_dout, \"Dropout\");\n \n leg->Draw();\n\n TCanvas *c_cycles_cut = new TCanvas(\"c_cycles_cut\", \"Cycles Trying\");\n c_cycles_cut->cd();\n db->Draw(\"CyclesTrying\", preg);\n gPad->ls();\n TH1F *hcycles_trying_preg = (TH1F*)gPad->GetPrimitive(\"htemp\");\n cout<<\"Pointer\" << hcycles_trying_preg;\n hcycles_trying_preg->SetNameTitle(\"hcycles_trying_preg\", \"Cycles Trying; Cycles Trying; Fraction per cycle\");\n hcycles_trying_preg->Scale(1./ hcycles_trying_preg->Integral());\n hcycles_trying_preg->SetMarkerStyle(kFullCircle);\n hcycles_trying_preg->SetMarkerSize(1.6);\n hcycles_trying_preg->SetMarkerColor(kGreen+2);\n \n db->Draw(\"CyclesTrying\", right, \"sames\");\n TH1F *hcycles_trying_right = (TH1F*)gPad->GetPrimitive(\"htemp\");\n hcycles_trying_right->SetName(\"hcycles_trying_right\");\n cout<<\"Pointer\" << hcycles_trying_right;\n hcycles_trying_right->Scale(1./ hcycles_trying_right->Integral());\n hcycles_trying_right->SetMarkerStyle(kFullStar);\n hcycles_trying_right->SetMarkerSize(1.6);\n hcycles_trying_right->SetMarkerColor(kRed);\n\n \n db->Draw(\"CyclesTrying\", dout, \"sames\");\n TH1F *hcycles_trying_dout = (TH1F*)gPad->GetPrimitive(\"htemp\");\n hcycles_trying_dout->SetName(\"hcycles_trying_dout\");\n hcycles_trying_dout->Scale(1./ hcycles_trying_dout->Integral());\n hcycles_trying_dout->SetMarkerStyle(kOpenCircle);\n hcycles_trying_dout->SetMarkerSize(1.6);\n hcycles_trying_dout->SetMarkerColor(kOrange);\n leg->Draw();\n\n TH1F* h_int_preg =new TH1F(*hcycles_trying_preg);\n h_int_preg->SetNameTitle(\"h_int_preg\", \"Cumulative integral\");\n TH1F* h_int_right =new TH1F(*hcycles_trying_right);\n h_int_right->SetName(\"h_int_right\");\n TH1F* h_int_dout =new TH1F(*hcycles_trying_dout);\n h_int_dout->SetName(\"h_int_dout\");\n\n // look at the integral of eache class for different cuts in cycles trying\n Double_t c_p = 0;\n Double_t c_r = 0;\n Double_t c_d = 0;\n for(Int_t i=0; i<hcycles_trying_preg->GetNbinsX(); i++){\n c_p += hcycles_trying_preg->GetBinContent(i);\n c_r += hcycles_trying_right->GetBinContent(i);\n c_d += hcycles_trying_dout->GetBinContent(i);\n \n h_int_preg->SetBinContent(i,c_p);\n h_int_right->SetBinContent(i,c_r);\n h_int_dout->SetBinContent(i,c_d);\n }\n TCanvas *c_integral = new TCanvas(\"c_integral\");\n c_integral->cd();\n h_int_preg->Draw();\n h_int_right->Draw(\"sames\");\n h_int_dout->Draw(\"sames\");\n leg->Draw();\n \n TH1F* h_intdays_dout =new TH1F(*hdays_trying_dout);\n h_intdays_dout->SetNameTitle(\"h_intdays_dout\", \"Days Trying;Days Trying; Cumulative integral of drop outs\");\n c_d = 0;\n for(Int_t i=0; i<hdays_trying_dout->GetNbinsX(); i++){\n c_d += hdays_trying_dout->GetBinContent(i);\n h_intdays_dout->SetBinContent(i, c_d);\n \n }\n\n TCanvas *c_integral_days = new TCanvas(\"c_integral_days\");\n c_integral_days->cd();\n h_intdays_dout->Draw();\n\n // time trying vs age for pregnant women, trying dropout\n TCanvas *c_cycle_vs_age_preg = new TCanvas(\"c_cycle_vs_age_preg\");\n db->Draw(\"CyclesTrying:Age\", preg, \"colz\");\n TH2F* hcycle_vs_age_preg = (TH2F*)gPad->GetPrimitive(\"htemp\");\n hcycle_vs_age_preg->SetNameTitle(\"hcycle_vs_age_preg\", \"Pregnant\");\n //projection selecting the fisrt two cycles\n TH1F* hproj_age_pred = (TH1F*)hcycle_vs_age_preg->ProjectionX(\"hproj_age_pred\", 1, 2);\n hproj_age_pred->SetTitle(\"\");\n TPad *pad_inset_pjx = new TPad(\"pad_inset_pjx\", \"\", 0.6, 0.5, 0.9, 0.9);\n pad_inset_pjx->Draw();\n pad_inset_pjx->cd();\n hproj_age_pred->Draw();\n //TPad *stat_pjx = new TPad(\"stat_pjx\", \"\", 0.6, 0.5, 0.9, 0.9);\n //stat_pjx->Draw();\n TPaveText *text_stat = new TPaveText(0.4, 0.6, 0.9,0.98, \"NDC\");\n text_stat->AddText(TString::Format(\"#splitline{N cycles = [1, 2]}{#splitline{#mu = %.1f y}{#sigma = %.1f y}}\", hproj_age_pred->GetMean(), hproj_age_pred->GetRMS()));\n text_stat->SetFillStyle(0);\n text_stat->SetBorderSize(0);\n text_stat->DrawClone();\n \n \n TCanvas *c_cycle_vs_age_right = new TCanvas(\"c_cycle_vs_age_right\");\n db->Draw(\"CyclesTrying:Age\", right, \"colz\");\n TH2F* hcycle_vs_age_right = (TH2F*)gPad->GetPrimitive(\"htemp\");\n hcycle_vs_age_right->SetNameTitle(\"hcycle_vs_age_right\", \"Right\");\n //projection selecting the all cycles\n TH1F* hproj_age_right = (TH1F*)hcycle_vs_age_right->ProjectionX(\"hproj_age_right\", 0, -1);\n hproj_age_right->SetTitle(\"\");\n TPad *pad_inset_pjx_r = new TPad(\"pad_inset_pjx_r\", \"\", 0.6, 0.5, 0.9, 0.9);\n pad_inset_pjx_r->Draw();\n pad_inset_pjx_r->cd();\n hproj_age_right->Draw();\n //TPad *stat_pjx = new TPad(\"stat_pjx\", \"\", 0.6, 0.5, 0.9, 0.9);\n //stat_pjx->Draw();\n TPaveText *text_stat_r = new TPaveText(0.4, 0.6, 0.9,0.98, \"NDC\");\n text_stat_r->AddText(TString::Format(\"#splitline{N cycles = all}{#splitline{#mu = %.1f y}{#sigma = %.1f y}}\", hproj_age_right->GetMean(), hproj_age_right->GetRMS()));\n text_stat_r->SetFillStyle(0);\n text_stat_r->SetBorderSize(0);\n text_stat_r->DrawClone();\n \n TCanvas *c_cycle_vs_age_dout = new TCanvas(\"c_cycle_vs_age_dout\");\n db->Draw(\"CyclesTrying:Age\", dout, \"colz\");\n TH2F* hcycle_vs_age_dout = (TH2F*)gPad->GetPrimitive(\"htemp\");\n hcycle_vs_age_dout->SetNameTitle(\"hcycle_vs_age_dout\", \"Drop out\");\n //projection selecting the the first cycle\n TH1F* hproj_age_dout = (TH1F*)hcycle_vs_age_dout->ProjectionX(\"hproj_age_dout\", 0, -1);\n hproj_age_dout->SetTitle(\"\");\n TPad *pad_inset_pjx_d = new TPad(\"pad_inset_pjx_d\", \"\", 0.6, 0.5, 0.9, 0.9);\n pad_inset_pjx_d->Draw();\n pad_inset_pjx_d->cd();\n hproj_age_dout->Draw();\n //TPad *stat_pjx = new TPad(\"stat_pjx\", \"\", 0.6, 0.5, 0.9, 0.9);\n //stat_pjx->Draw();\n TPaveText *text_stat_d = new TPaveText(0.4, 0.6, 0.9,0.98, \"NDC\");\n text_stat_d->AddText(TString::Format(\"#splitline{N cycles = all}{#splitline{#mu = %.1f y}{#sigma = %.1f y}}\", hproj_age_dout->GetMean(), hproj_age_dout->GetRMS()));\n text_stat_d->SetFillStyle(0);\n text_stat_d->SetBorderSize(0);\n text_stat_d->DrawClone();\n \n // anovulary cycles\n TCut anov_g0 = TCut(\"AnovCycles>-1\");\n TCanvas *c_anov = new TCanvas(\"c_anov\");\n db->Draw(\"AnovCycles\", preg+anov_g0);\n TH1F* hanov_preg = (TH1F*)gPad->GetPrimitive(\"htemp\");\n hanov_preg->SetNameTitle(\"hanov_preg\", \"Anovulatory Cycles; # anovulatory cycles; fraction of the population\");\n hanov_preg->Scale(1./ hanov_preg->Integral());\n hanov_preg->SetMarkerStyle(kFullCircle);\n hanov_preg->SetMarkerSize(1.6);\n hanov_preg->SetMarkerColor(kGreen+2);\n\n db->Draw(\"AnovCycles\", right+anov_g0, \"sames\");\n TH1F* hanov_right = (TH1F*)gPad->GetPrimitive(\"htemp\");\n hanov_right->SetNameTitle(\"hanov_right\", \"Anovulatory Cycles; # anovulatory cycles; fraction of the population\");\n hanov_right->Scale(1./ hanov_right->Integral());\n hanov_right->SetMarkerStyle(kFullStar);\n hanov_right->SetMarkerSize(1.6);\n hanov_right->SetMarkerColor(kRed);\n\n db->Draw(\"AnovCycles\", dout+anov_g0, \"sames\");\n TH1F* hanov_dout = (TH1F*)gPad->GetPrimitive(\"htemp\");\n hanov_dout->SetNameTitle(\"hanov_dout\", \"Anovulatory Cycles; # anovulatory cycles; fraction of the population\");\n hanov_dout->Scale(1./ hanov_dout->Integral());\n hanov_dout->SetMarkerStyle(kOpenCircle);\n hanov_dout->SetMarkerSize(1.6);\n hanov_dout->SetMarkerColor(kOrange);\n leg->Draw();\n \n \n \n}\n" }, { "alpha_fraction": 0.525375247001648, "alphanum_fraction": 0.5834524631500244, "avg_line_length": 46.03361511230469, "blob_id": "9e7408ca05e7b233c7e1c0701016220f93f4da28", "content_id": "fb5f6946250826b9f4bec20666abce675c806425", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5596, "license_type": "no_license", "max_line_length": 91, "num_lines": 119, "path": "/python/natural_cycles.py", "repo_name": "chiarabianchin/NaturalCycles", "src_encoding": "UTF-8", "text": "# generl\nimport numpy as np\n\n# import for data frame\nfrom pandas import read_csv, read_json, Series\nimport pandas as pd\n\n# drawing\nfrom matplotlib import pyplot as plt\nimport seaborn\n\ndef natural_cycles():\n df = read_csv('anafile_challenge_170522.csv') # 'df_100.csv')\n df = df.rename(columns={'Country': 'Country', ' Age': 'Age', ' NumBMI': 'NumBMI',\n ' Pill': 'Pill', ' NCbefore': 'NCbefore',\n ' FPlength': 'FPlength', ' Weight': 'Weight',\n ' CycleVar': 'CycleVar', ' TempLogFreq': 'TempLogFreq',\n ' SexLogFreq': 'SexLogFreq', ' DaysTrying': 'DaysTrying',\n ' CyclesTrying': 'CyclesTrying',\n ' ExitStatus': 'ExitStatus',\n ' AnovCycles ': 'AnovCycles'})\n print(df.columns)\n print(\"len\", len(df))\n\n df_status = df.groupby('ExitStatus')\n print(\"Counts\", df_status.count())\n print(\"average Age\", df_status['Age'].mean())\n print(df.pivot_table(index='ExitStatus', columns='Pill',\n aggfunc={'Age': 'mean', 'CyclesTrying': 'mean'}))\n print(df.pivot_table(index='ExitStatus', columns='NCbefore',\n aggfunc={'Age': 'mean', 'CyclesTrying': 'mean'}))\n print(df.pivot_table(index='ExitStatus',\n aggfunc={'SexLogFreq': 'mean', 'TempLogFreq': 'mean'}))\n print(df.pivot_table(index='ExitStatus', columns='FPlength',\n aggfunc={'CyclesTrying': 'mean' }))\n print(df.pivot_table(index='ExitStatus', columns='FPlength',\n aggfunc={'Weight': 'mean' }))\n print(df.pivot_table(index='ExitStatus', columns='CycleVar',\n aggfunc={'CyclesTrying': 'mean'}))\n\n df_preg = df[df['ExitStatus'] == ' Pregnant']\n age_bins = pd.cut(df_preg['Age'], [20, 25, 30, 35, 40, 45])\n #print(age_bins)\n df_preg.head\n print(len(df_preg))\n plt.figure(\"Cycles trying vs Age -Pill / no pill- Pregnant\")\n ax3 = plt.subplot(111)\n df_preg.pivot_table('CyclesTrying', index=age_bins, columns=['Pill']).plot(ax=ax3)\n ax3.set_ylabel(\"Mean Cycles Trying\")\n plt.xticks(np.arange(5), ('20-25', '25-30', '30-35', '35-40', '40-45'))\n plt.figure(\"Cycles trying vs Age -NCbefore- Pregnant\")\n ax4 = plt.subplot(111)\n df_preg.pivot_table('CyclesTrying', index=age_bins, columns=['NCbefore']).plot(ax=ax4)\n ax4.set_ylabel(\"Mean Cycles Trying\")\n plt.xticks(np.arange(5), ('20-25', '25-30', '30-35', '35-40', '40-45'))\n plt.figure(\"Cycles trying vs Age -Cycle Var- Pregnant\")\n ax5 = plt.subplot(111)\n df_preg.pivot_table('CyclesTrying', index=age_bins, columns=['CycleVar']).plot(ax=ax5)\n ax5.set_ylabel(\"Mean Cycles Trying\")\n plt.xticks(np.arange(5), ('20-25', '25-30', '30-35', '35-40', '40-45'))\n plt.figure(\"Cycles trying vs Age -FPlength- Pregnant\")\n ax5 = plt.subplot(111)\n df_preg.pivot_table('CyclesTrying', index=age_bins, columns=['FPlength']).plot(ax=ax5)\n ax5.set_ylabel(\"Mean Cycles Trying\")\n plt.xticks(np.arange(5), ('20-25', '25-30', '30-35', '35-40', '40-45'))\n\n age_bins_all = pd.cut(df['Age'], [20, 25, 30, 35, 40, 45])\n plt.figure(\"TempLogFreq vs Age -ExitStatus\")\n fig78, (ax7, ax8) = plt.subplots(2, 1)\n df.pivot_table('TempLogFreq', index=age_bins_all, columns=['ExitStatus'],\n aggfunc='mean').plot(ax=ax7)\n ax7.set_ylabel(\"Mean TemplogFreq\")\n df.pivot_table('TempLogFreq', index=age_bins_all, columns=['ExitStatus'],\n aggfunc='std').plot(ax=ax8)\n ax8.set_ylabel(\"sigma TemplogFreq\")\n #plt.xticks(np.arange(5), ('20-25', '25-30', '30-35', '35-40', '40-45'))\n\n df_1cycle = df[df['CyclesTrying'] == 1]\n age_bins_1c = pd.cut(df_1cycle['Age'], [20, 25, 30, 35, 40, 45])\n plt.figure(\"TempLogFreq vs Age -ExitStatus - 1 cycle\")\n ax9 = plt.subplot(111)\n df_1cycle.pivot_table('TempLogFreq', index=age_bins_1c, columns=['ExitStatus'],\n aggfunc='mean').plot(ax=ax9)\n ax9.set_ylabel(\"Mean TemplogFreq\")\n plt.xticks(np.arange(5), ('20-25', '25-30', '30-35', '35-40', '40-45'))\n df_preg_do = df[(df['ExitStatus'].isin([' Pregnant', ' Dropout']))]\n bin_logt = pd.cut(df_preg_do['TempLogFreq'],\n pd.IntervalIndex.from_tuples([(0, 0.4), (0.8, 1)],\n closed='right'))\n plt.figure(\"CyclesTrying-TempLogFreq\")\n ax10 = plt.subplot(111)\n df_preg_do.pivot_table('Age', index='CyclesTrying', columns = [bin_logt, 'ExitStatus'],\n aggfunc='count').plot(logy=True, ax=ax10, colormap='Accent')\n ax10.set_ylabel(\"# per cycle\")\n\n sex_f = pd.cut(df_preg['SexLogFreq'], [0.05, 0.15, 0.30, 0.45, 0.60, 0.8, 1])\n plt.figure(\"Cycles trying vs Age -SexLogFreq- Pregnant\")\n ax5 = plt.subplot(111)\n df_preg.pivot_table('CyclesTrying', index=age_bins, columns=[sex_f]).plot(ax=ax5)\n ax5.set_ylabel(\"Mean Cycles Trying\")\n plt.xticks(np.arange(5), ('20-25', '25-30', '30-35', '35-40', '40-45'))\n\n temp_f = pd.cut(df_preg['TempLogFreq'], [0.05, 0.15, 0.30, 0.45, 0.60, 0.8, 1])\n plt.figure(\"Cycles trying vs Age -TempLogFreq- Pregnant\")\n ax6 = plt.subplot(111)\n df_preg.pivot_table('CyclesTrying', index=age_bins, columns=[temp_f]).plot(ax=ax6)\n ax6.set_ylabel(\"Mean Cycles Trying\")\n plt.xticks(np.arange(5), ('20-25', '25-30', '30-35', '35-40', '40-45'))\n\n\n\ndef main():\n seaborn.set()\n #seaborn.set_palette(seaborn.color_palette(\"YlOrBr\", 11))\n natural_cycles()\n plt.show()\n\nif __name__ == \"__main__\":\n main()" } ]
2
ielecer/Python-3
https://github.com/ielecer/Python-3
56f40b1b49c6e1c2b2415650586947aa96ebd5b5
96d5c9fa6d452827fe6d901e34b881d557b6c76d
774644ec65d82c91269eeca74a8ab29f6433702c
refs/heads/master
2020-03-25T03:23:39.787690
2018-08-06T21:25:36
2018-08-06T21:25:36
143,339,164
0
0
null
2018-08-02T19:55:53
2018-07-01T11:16:38
2015-10-22T06:52:06
null
[ { "alpha_fraction": 0.7166666388511658, "alphanum_fraction": 0.7166666388511658, "avg_line_length": 16.285715103149414, "blob_id": "297186288f204a3b2847ac41ba9e3384c487b1a1", "content_id": "044d8bf339b42ef624561de02d4ef0959219be89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 120, "license_type": "no_license", "max_line_length": 35, "num_lines": 7, "path": "/pywhois/pywhois_example.py", "repo_name": "ielecer/Python-3", "src_encoding": "UTF-8", "text": "import whois\n\ndata = raw_input(\"Enter a domain:\")\nw = whois.whois(data)\nprint w\n# print w.expiration_date\n# print w.text" }, { "alpha_fraction": 0.7605321407318115, "alphanum_fraction": 0.7727272510528564, "avg_line_length": 52.05882263183594, "blob_id": "5f22a19dc9f71acd71db4d05bff6fddc0ed69c94", "content_id": "b07e6017a257e08b152fba78f80840738b2f1296", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 902, "license_type": "no_license", "max_line_length": 272, "num_lines": 17, "path": "/README.md", "repo_name": "ielecer/Python-3", "src_encoding": "UTF-8", "text": "# Python-3\nSome new scripts will be added soon! A twitter bot would be added soon too!\n\nSome python scripts for beginners, written for the book Automating The Internet with Python\n\nHere's some detailed information on the scripts.\n\nFileDif.py - Returns the diferrence in two file's contents.\n\nvirus.py - Creates folders: spam + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" with a **for** loop. \n\nMagic8Ball.py - The magic 8 ball cloned in a program, the cool thing about this program is that it has only 4 lines still works as a regular Magic 8 Ball program written in Python. My fellow programmers had written a Magic 8 Ball program (in python) which had 10-16 lines.\n\n\nPasswordDetection.py - What this program does is to ask the user for their password and prints \"That's one strong password\" if the len() function returns 8 and if it doesn't it prints out \"May god have mercy on your account\". \n\npoetry.py - Generates random poetry\n" }, { "alpha_fraction": 0.6476190686225891, "alphanum_fraction": 0.723809540271759, "avg_line_length": 34, "blob_id": "1f895f7b561b6dde48a9dc872877c476f9c8de29", "content_id": "29d0102d72f9167d4574fe3dd85f9f0c4aa2299f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 105, "license_type": "no_license", "max_line_length": 55, "num_lines": 3, "path": "/virus.py", "repo_name": "ielecer/Python-3", "src_encoding": "UTF-8", "text": "import os\nfor letters in (\"ABCDEFGHIJKLMNOPQRSTUVWXYZ^01234567\"):\n os.makedirs(\"C:\\\\spam\" + letters)\n" }, { "alpha_fraction": 0.7200000286102295, "alphanum_fraction": 0.7236363887786865, "avg_line_length": 29.55555534362793, "blob_id": "d8dba460d2cc183c103b2ffe8c96ae5ca813e0e9", "content_id": "9b7b730c6402bf2b54c858f37c0626c019f8160b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 275, "license_type": "no_license", "max_line_length": 50, "num_lines": 9, "path": "/passwordDetection.py", "repo_name": "ielecer/Python-3", "src_encoding": "UTF-8", "text": "#Password Detection (The world's simplest)\n#Written by Anupam\n#For the book: Automating The Internet with Python\n\npassword = input(\"Enter your password: \")\nif len(password) > 8:\n print(\"That is one strong password\")\nelse:\n print(\"May god have mercy on your account\")\n" }, { "alpha_fraction": 0.606217622756958, "alphanum_fraction": 0.606217622756958, "avg_line_length": 16.545454025268555, "blob_id": "b28af32ef84f0c9537fc12b4eff8c6ad4e2102e7", "content_id": "678ad15b41613f5ac13f7ca862578b6007894968", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 193, "license_type": "no_license", "max_line_length": 27, "num_lines": 11, "path": "/filedif.py", "repo_name": "ielecer/Python-3", "src_encoding": "UTF-8", "text": "import os\n\ndef diff(source,target):\n f = open(source,'r')\n g = open(target,'r')\n\n reference = f.readlines()\n done = g.readlines()\n for i in reference:\n if i not in done:\n print(i)\n" }, { "alpha_fraction": 0.7518247961997986, "alphanum_fraction": 0.7566909790039062, "avg_line_length": 33.25, "blob_id": "4682cd2c3601661a9e09b3fa98f34bce9c793cac", "content_id": "d7812af91c92e0a931e19b3a02266eaf24234576", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 411, "license_type": "no_license", "max_line_length": 110, "num_lines": 12, "path": "/pywhois/README.md", "repo_name": "ielecer/Python-3", "src_encoding": "UTF-8", "text": "# Using pywhois for retrieving WHOIS information\n\n## Introduction\n### pywhois is a Python module for retrieving WHOIS information of domains.\n### pywhois works with Python 2.4+\n\n## Installation\n### Through pip command: pip install python-whois\n### Remember to import it first: import whois\n\n## Usage\n### We can use the pywhois module to query a WHOIS server directly and to parse WHOIS data for a given domain.\n" } ]
6
voxlet/twixip
https://github.com/voxlet/twixip
7ae690496d6e39abf0c10c35771f78da9c39a4cc
71d4218ca1aa4ef10d8933d0f7c30ab5eb2dc4c4
49e88745408b8a9c2f18df1a6a870bed5785e005
refs/heads/master
2020-04-12T22:49:01.825971
2010-12-06T10:31:59
2010-12-06T10:31:59
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.746666669845581, "alphanum_fraction": 0.746666669845581, "avg_line_length": 14, "blob_id": "953da1381d61d531e3ca839bc0b08e13d208a65d", "content_id": "ee7353319e34e911021d1fcc6411c189dbb5eb91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 75, "license_type": "no_license", "max_line_length": 20, "num_lines": 5, "path": "/twixi/__init__.py", "repo_name": "voxlet/twixip", "src_encoding": "UTF-8", "text": "def Encrypt(string):\n return string\n\ndef Decrypt(string):\n return string\n" }, { "alpha_fraction": 0.6014053821563721, "alphanum_fraction": 0.6106130480766296, "avg_line_length": 31.488189697265625, "blob_id": "3cd733430777331d7c9916a35121654adffd9f8b", "content_id": "8ea62de79d1f64f5c0c7f61ac8510b373e1279b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4133, "license_type": "no_license", "max_line_length": 99, "num_lines": 127, "path": "/twixi/handler.py", "repo_name": "voxlet/twixip", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom google.appengine.ext import webapp\nfrom twixi.model import TwixiUser\nfrom mixi import mixi\nimport twixi\nimport urllib2\nimport logging\nfrom xml.etree import ElementTree\nimport datetime\nimport pytz\n\nclass SyncHandler(webapp.RequestHandler):\n usertl_url_format = ('http://twitter.com/statuses/'\n 'user_timeline.%s?'\n 'screen_name=%s')\n title_date_format = '%Y-%m-%d'\n date_format = '%H:%M'\n body_format = u' %(content)s (%(date)s)\\n\\n'\n\n def newTweets(self, user, format):\n screen_name = user.twitter_screen_name\n url = self.usertl_url_format % (format, screen_name)\n if user.last_tweetid is not None:\n url = url+'&since_id='+user.last_tweetid \n try:\n logging.debug('opening timeline: %s', url)\n feed = urllib2.urlopen(url)\n except urllib2.URLError:\n logging.error(\"Cant fetch %s's timeline\" % screen_name)\n return None\n logging.debug(feed)\n (tweets, lastid) = self.parseAtom(feed)\n if tweets is None:\n logging.error(\"Bad Feed\")\n return None\n if (lastid is not None):\n user.last_tweetid = str(lastid)\n user.put()\n return tweets\n \n\n def parseAtom(self, atom):\n tweets = dict()\n tree = ElementTree.parse(atom)\n logging.debug(tree)\n entries = tree.findall('{http://www.w3.org/2005/Atom}entry')\n lastid = None\n for entry in entries:\n datestring = entry.find('{http://www.w3.org/2005/Atom}published').text.replace('+00:00', 'Z')\n published = datetime.datetime.strptime(datestring,\n \"%Y-%m-%dT%H:%M:%SZ\")\n tweets[published] = entry.find('{http://www.w3.org/2005/Atom}content').text\n id = entry.find('{http://www.w3.org/2005/Atom}id').text\n id = int(id.rsplit('/', 1)[1]);\n if id > lastid or lastid is None:\n lastid = id\n return (tweets, lastid)\n\n\n def prettyFormat(self, tweets, user):\n usertz = pytz.timezone(user.timezone)\n dates = tweets.keys()\n dates.sort()\n logging.debug(dates)\n title = usertz.localize(dates[0]).strftime(self.title_date_format)\n \n header = user.twitter_screen_name+': '\n body = ''\n for date in dates:\n fmtdate = pytz.utc.localize(date)\n fmtdate = fmtdate.astimezone(usertz).strftime(self.date_format)\n content = tweets[date]\n if content.startswith(header):\n content = content[len(header):len(content)]\n if content.startswith('@'):\n continue\n body += (self.body_format.encode('utf-8') %\n {'date':fmtdate, 'content':content.encode('utf-8')})\n return (title, body)\n\n\n def get(self, screen_name):\n query = TwixiUser.all()\n user = query.filter('twitter_screen_name =', screen_name).get()\n if user is None:\n self.error(500)\n logging.error(\"No user with twitter screen name %s\" % screen_name)\n return\n\n tweets = self.newTweets(user, 'atom')\n logging.debug(tweets)\n if not tweets or len(tweets) == 0:\n self.response.out.write('No new tweets\\n')\n return\n\n (title, body) = self.prettyFormat(tweets, user)\n logging.debug(title)\n logging.debug(body)\n if not body:\n self.response.out.write('Nothing to post\\n')\n return\n \n service = mixi.Service(user.mixi_username,\n twixi.Decrypt(user.mixi_password),\n user.mixi_memberid)\n entry = mixi.DiaryEntry(title, body)\n (response, rbody) = service.postDiary(entry);\n\n self.response.set_status(response.status, response.reason.encode('utf-8'))\n self.response.out.write(rbody)\n\nclass AddUserHandler(webapp.RequestHandler):\n def get(self):\n logging.info('adding user')\n tsn = self.request.get('tsn')\n mun = self.request.get('mun')\n mpw = self.request.get('mpw')\n mid = self.request.get('mid')\n tz = self.request.get('tz')\n user = TwixiUser(twitter_screen_name=tsn,\n mixi_username=mun,\n mixi_password=mpw,\n mixi_memberid=mid,\n timezone=tz)\n user.put()\n self.response.out.write('OK\\n')\n\n" }, { "alpha_fraction": 0.7793295979499817, "alphanum_fraction": 0.7793295979499817, "avg_line_length": 38.66666793823242, "blob_id": "3dd74615ce6665267a6d6026f010d9f644299437", "content_id": "3045b2b9e7231f362749569723a22c85c7a3f045", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 358, "license_type": "no_license", "max_line_length": 56, "num_lines": 9, "path": "/twixi/model.py", "repo_name": "voxlet/twixip", "src_encoding": "UTF-8", "text": "from google.appengine.ext import db\n\nclass TwixiUser(db.Model):\n twitter_screen_name = db.StringProperty(required=True)\n mixi_username = db.StringProperty(required=True)\n mixi_password = db.StringProperty(required=True)\n mixi_memberid = db.StringProperty(required=True)\n timezone = db.StringProperty(required=True)\n last_tweetid = db.StringProperty()\n\n" }, { "alpha_fraction": 0.7544910311698914, "alphanum_fraction": 0.7544910311698914, "avg_line_length": 54.66666793823242, "blob_id": "19dfe396314d6e17ddc7b8e1467f54b2bebf1ead", "content_id": "950d498e1a835df78cb2e6572a692b479be6bf2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 167, "license_type": "no_license", "max_line_length": 154, "num_lines": 3, "path": "/error_check.sh", "repo_name": "voxlet/twixip", "src_encoding": "UTF-8", "text": "#! /bin/sh\n\nPYTHONPATH=/usr/local/google_appengine:/usr/local/google_appengine/lib/yaml/lib:/usr/local/google_appengine/lib/webob pylint --indent-string=\" \" -e twixi\n" } ]
4
ckmah/project-template
https://github.com/ckmah/project-template
df948149c78962a6851af5ca2e244d80ce0c62c0
d7723514ca8b17b2db10e2895fca25749267778b
a526c3c08f6f3cd42d228820fa500ee8aff2db0e
refs/heads/master
2021-06-01T16:21:19.196063
2021-01-21T18:44:02
2021-01-21T18:44:02
91,506,077
6
0
null
null
null
null
null
[ { "alpha_fraction": 0.4992150664329529, "alphanum_fraction": 0.4992150664329529, "avg_line_length": 27.311111450195312, "blob_id": "64c5aee486c07d89d379768c83f045178efd5b35", "content_id": "3a7fac31e2c6c5cb09a089cbcfe1f5898c5962b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1274, "license_type": "no_license", "max_line_length": 84, "num_lines": 45, "path": "/scripts/notify.py", "repo_name": "ckmah/project-template", "src_encoding": "UTF-8", "text": "from slacker import Slacker\n\n\nclass Notify:\n '''\n A class for posting Slack messages.\n '''\n\n def __init__(self, token=None, username='beep', channel='beep'):\n '''\n username : str, default 'beep'\n description\n\n channel : str, default 'beep'\n description\n '''\n if not token:\n print('Token not specified.')\n return\n\n self.slack = Slacker(token)\n self.username = username\n self.channel = channel\n self.token = token\n\n def msg_start(self):\n self.msg('Start :slack:')\n\n def msg_end(self):\n self.msg('Finished :ok_hand:')\n\n def msg(self, msg='Hello :v:'):\n '''\n msg : str, default 'Hello :v:'\n Message to post to slack. Emojis can be used with standard Slack syntax.\n '''\n response = self.slack.chat.post_message(channel=self.channel,\n text=msg,\n username=self.username)\n\n def msg_file(self, fname=None):\n response = self.slack.files.upload(file_=fname,\n channels=self.channel,\n initial_comment=fname)\n assert response[\"ok\"]\n" }, { "alpha_fraction": 0.6096654534339905, "alphanum_fraction": 0.6257745027542114, "avg_line_length": 28.88888931274414, "blob_id": "7a1f33c4d850284067f7e34d71a7cd7f152aa028", "content_id": "5f1ec45988676e2923fd44c15f1a26e8870b93cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 807, "license_type": "no_license", "max_line_length": 105, "num_lines": 27, "path": "/scripts/slurm.py", "repo_name": "ckmah/project-template", "src_encoding": "UTF-8", "text": "def new_slurm_script(script_name, cpus_per_task='1', mem_per_cpu='5G', array_t='1-9000', array_tc='250'):\n\n with open(script_name, 'w') as f:\n f.write(f'''#! /bin/bash\n\n#SBATCH --job-name={script_name}\n#SBATCH --output=/cellar/users/ckmah/logs/%A_%a.out\n#SBATCH --error=/cellar/users/ckmah/logs/%A_%a.err\n#SBATCH --cpus-per-task={cpus_per_task}\n#SBATCH --mem-per-cpu={mem_per_cpu}\n#SBATCH --array={array_t}%{array_tc}\n\n''')\n\n\ndef map_slurm_task_id(script_name, file_list, var_name):\n\n # generate file list with ' '\n file_list_str = ' '.join(file_list)\n\n # 1. Save file list to bash array\n # 2. Get current file according to array task id\n with open(script_name, 'a') as f:\n f.write(f'''\n{var_name}s=({file_list_str})\n{var_name}=${{{var_name}s[$SLURM_ARRAY_TASK_ID -1]}}\n''')\n" }, { "alpha_fraction": 0.7654411792755127, "alphanum_fraction": 0.7654411792755127, "avg_line_length": 51.30769348144531, "blob_id": "aca75cbd047affe0ca2b478be44a29888238802b", "content_id": "545c1e0df47c3d1c47e90235254f020e0a63ac3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1360, "license_type": "no_license", "max_line_length": 341, "num_lines": 26, "path": "/README.md", "repo_name": "ckmah/project-template", "src_encoding": "UTF-8", "text": "# project-template\nA template for Jupyter Notebook based research projects. I try to describe the project goals, organization, and data here.\n\n## Notebooks: the project narrative\n- `*.ipynb` | The core of your project narrative and analyses. TODO create template notebook `Template.ipynb`.\n\n- `presentation.mplstyle` | My custom `matplotlib` stylesheet for default plot properties How to use in notebooks:\n ```\n import matplotlib.pyplot as plt\n >>> plt.style.use('presentation.mplstyle.py')\n ```\n\n- `environment.yml` | The project virtual environment generated with `conda env export --no-builds > environment.yml`. I strongly recommend documenting the packages you use for analyses for the sake of reproducibility. [conda](https://www.anaconda.com/products/individual) is a cross-platform package manager that allows you to do so easily.\n\n## Stay organized with a couple folders\n- `data` | Store data here. Provide instructions to access data if it's too big, sensitive, etc. and is stored somewhere else.\n\n- `plots` | Save generated figures here; this way, figures can be viewed without rendering notebooks.\n\n- `scripts` | I usually store bash scripts and utility functions/classes here.\n\n## References\n\nInspiration taken from googling many blog posts (and dealing with clutter over the years).\n\nhttps://github.com/outlierbio/ob-project-template\n" } ]
3
Wooble/advent2018
https://github.com/Wooble/advent2018
f5aadb2fff0a71108e1cd49dd862f4f155051c95
28d18eb0c5edf675f446fe73c84a80176c43c3ad
f167fef77b591527c2aed886c53ef5a03c07ea24
refs/heads/master
2020-04-09T03:50:05.580029
2018-12-20T19:59:27
2018-12-20T19:59:27
159,998,663
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5214285850524902, "alphanum_fraction": 0.545918345451355, "avg_line_length": 16.5, "blob_id": "00cbaad4a299b97eae0ff52ac2fa9744340a8f35", "content_id": "ca92492a766a2bedaec590742f056021ee47e363", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 980, "license_type": "no_license", "max_line_length": 67, "num_lines": 56, "path": "/02_inventory.py", "repo_name": "Wooble/advent2018", "src_encoding": "UTF-8", "text": "import collections\nimport itertools\n\n\ndef checksum(data):\n two = 0\n three = 0\n\n for line in data:\n c = collections.Counter(line)\n if any(v == 2 for v in c.values()):\n two += 1\n if any(v == 3 for v in c.values()):\n three += 1\n\n return two * three\n\n\ndef common(data):\n for pair in itertools.combinations(data, 2):\n differences = 0\n for c1, c2 in zip(*pair):\n if c1 != c2:\n differences += 1\n if differences == 1:\n return \"\".join(c1 for c1, c2 in zip(*pair) if c1 == c2)\n\n\ndef test_common():\n data = \"\"\"abcde\nfghij\nklmno\npqrst\nfguij\naxcye\nwvxyz\"\"\".splitlines()\n assert common(data) == \"fgij\"\n\n\ndef test_checksum():\n data = \"\"\"abcdef\nbababc\nabbcde\nabcccd\naabcdd\nabcdee\nababab\"\"\".splitlines()\n\n assert checksum(data) == 12\n\n\nif __name__ == \"__main__\":\n with open(\"02_input.txt\") as f:\n print(checksum(f))\n f.seek(0)\n print(common(f))\n" }, { "alpha_fraction": 0.5371900796890259, "alphanum_fraction": 0.5647382736206055, "avg_line_length": 24.034482955932617, "blob_id": "c23fd735264e4e5492b6fe1b3d7a27475a7d3ecf", "content_id": "3f01b5f9938d1e2a14830398a736810d15e1cd85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 726, "license_type": "no_license", "max_line_length": 66, "num_lines": 29, "path": "/01_1_chronal_calibration.py", "repo_name": "Wooble/advent2018", "src_encoding": "UTF-8", "text": "import re\nimport pytest\n\n\ndef frequency(changes: str) -> int:\n \"\"\"Calculate final frequency from changes.\"\"\"\n current_freq = 0\n changes_list = re.split(r\"[,\\n]\", changes, flags=re.MULTILINE)\n for change in (int(x) for x in changes_list if x):\n current_freq += change\n return current_freq\n\n\[email protected](\n \"freq_changes,expected\",\n [\n (\"+1, +1, +1\", 3),\n (\"+1, +1, -2\", 0),\n (\"-1, -2, -3\", -6),\n (\"+1\\n+1\\n+1\", 3), # actual input is \\n separated\n ],\n)\ndef test_frequency(freq_changes: str, expected: int):\n assert frequency(freq_changes) == expected\n\n\nif __name__ == \"__main__\":\n with open(\"01_1_input.txt\") as f:\n print(frequency(f.read()))\n" }, { "alpha_fraction": 0.5637819170951843, "alphanum_fraction": 0.6088044047355652, "avg_line_length": 25.65333366394043, "blob_id": "6a8a57dc122ffd41612ac95e245430e51c961f87", "content_id": "8523ef685e7e722d7ec82f95fa3180013cc88b9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1999, "license_type": "no_license", "max_line_length": 88, "num_lines": 75, "path": "/day_11_charge.py", "repo_name": "Wooble/advent2018", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pytest\n\n\[email protected](\n \"loc,serial,expected\",\n [((3, 5), 8, 4), ((122, 79), 57, -5), ((217, 196), 39, 0), ((101, 153), 71, 4)],\n)\ndef test_power_level(loc, serial, expected):\n assert power_level(loc, serial) == expected\n\n\[email protected](\"serial,expected\", [(18, (33, 45)), (42, (21, 61))])\ndef test_biggest_total(serial, expected):\n assert biggest_total(serial) == expected\n\n\[email protected](\"num,expected\", [(12345, 3), (5, 0)])\ndef test_hundreds(num, expected):\n assert hundreds(num) == expected\n\n\ndef hundreds(num: int) -> int:\n \"\"\"Get hundreds digit from a number\"\"\"\n return (num // 100) % 10\n\n\ndef power_level(loc: tuple, serial: int) -> int:\n \"\"\"Calculate power level of a single cell.\"\"\"\n x, y = loc\n rack_id = x + 10\n power = rack_id * y\n power += serial\n power *= rack_id\n power = hundreds(power)\n return power - 5\n\n\ndef make_grid(serial):\n grid = np.zeros((301, 301))\n for (x, y), _ in np.ndenumerate(grid):\n if x * y:\n grid[x][y] = power_level((x, y), serial)\n return grid\n\n\ndef biggest_total_and_total(serial, size):\n grid = make_grid(serial)\n\n def keyfunc(item):\n x, y = item[0]\n if x + size > 300 or y + size > 300:\n return float(\"-Inf\")\n return np.sum(grid[x : x + size, y : y + size])\n\n element = max(np.ndenumerate(grid), key=keyfunc)\n return element[0], keyfunc(element)\n\n\ndef biggest_total(serial: int, size: int = 3) -> tuple:\n \"\"\"Find the coordinates of the upper left corner of the highest power 3x3 region.\"\"\"\n return biggest_total_and_total(serial, size)[0]\n\n\ndef biggest_total_anysize(serial):\n solutions = []\n for size in range(1, 301):\n solutions.append((biggest_total_and_total(serial, size), size))\n solution = max(solutions, key=lambda item: item[0][1])\n return solution\n\n\nif __name__ == \"__main__\":\n print(biggest_total(9810))\n print(biggest_total_anysize(9810))\n" }, { "alpha_fraction": 0.5432242751121521, "alphanum_fraction": 0.5759345889091492, "avg_line_length": 24.176469802856445, "blob_id": "8d98bb15d1479dcf521ca065a25096a1d3f43776", "content_id": "f65821c5579d4dfa63a3342c07a2e82c4b877853", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 856, "license_type": "no_license", "max_line_length": 70, "num_lines": 34, "path": "/01_2_chronal_calibration_repeated.py", "repo_name": "Wooble/advent2018", "src_encoding": "UTF-8", "text": "import itertools\nimport typing\nimport pytest\n\n\ndef frequency(changes: typing.Iterable[int]) -> int:\n \"\"\"Calculate final frequency from changes.\"\"\"\n seen_freqs = {0}\n current_freq = 0\n\n for change in itertools.cycle(changes):\n current_freq += change\n if current_freq in seen_freqs:\n return current_freq\n seen_freqs.add(current_freq)\n raise ValueError(\"no frequency found\")\n\n\[email protected](\n \"freq_changes,expected\",\n [\n ([+1, -1], 0),\n ([+3, +3, +4, -2, -4], 10),\n ([-6, +3, +8, +5, -6], 5),\n ([+7, +7, -2, -7, -4], 14),\n ],\n)\ndef test_frequency(freq_changes: typing.Iterable[int], expected: int):\n assert frequency(freq_changes) == expected\n\n\nif __name__ == \"__main__\":\n with open(\"01_1_input.txt\") as f:\n print(frequency(int(line) for line in f))\n" }, { "alpha_fraction": 0.875, "alphanum_fraction": 0.875, "avg_line_length": 7, "blob_id": "292f8a245ca4676288d3c21525260cd806c54297", "content_id": "c04d57f50e3cdc65120f858a429b1eb9588c930a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 32, "license_type": "no_license", "max_line_length": 11, "num_lines": 4, "path": "/requirements.txt", "repo_name": "Wooble/advent2018", "src_encoding": "UTF-8", "text": "pytest\nnumpy\npytesseract\npillow\n" }, { "alpha_fraction": 0.4541763365268707, "alphanum_fraction": 0.5214617252349854, "avg_line_length": 28.724138259887695, "blob_id": "96d693d44c0906147bf6cb13455c2360e2e9624f", "content_id": "847f2e519dffe3896b65a976d0205ff090ea3317", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1724, "license_type": "no_license", "max_line_length": 86, "num_lines": 58, "path": "/day14_chocolate.py", "repo_name": "Wooble/advent2018", "src_encoding": "UTF-8", "text": "import pytest\n\n\ndef ten_scores(after):\n elves = [0, 1]\n board = [3, 7]\n while len(board) < after + 10:\n new_recipies = sum(board[elves[x]] for x in (0,1))\n for digit in str(new_recipies):\n board.append(int(digit))\n for idx, elf in enumerate(elves):\n elves[idx] = (elf + 1 + board[elf]) % len(board)\n #print(board, elves)\n return ''.join(str(digit) for digit in board[after:after+10])\n\n\[email protected](\"after,expected\",\n [\n (9, \"5158916779\"),\n (5, \"0124515891\"),\n (18, \"9251071085\"),\n (2018, \"5941429882\"),\n ])\ndef test_ten_scores(after, expected):\n assert ten_scores(after) == expected\n\n\[email protected](\"searchscore,expected\", [\n (\"51589\", 9),\n (\"01245\", 5),\n (\"92510\", 18),\n (\"59414\", 2018),\n (\"515891\", 9)\n])\ndef test_search(searchscore,expected):\n assert search(searchscore) == expected\n\n\ndef search(searchscore):\n # refactorme\n elves = [0, 1]\n board = [3, 7]\n search = [int(x) for x in searchscore]\n while (board[-len(search):] != search) and (board[-(len(search)+1):-1] != search):\n new_recipies = sum(board[elves[x]] for x in (0,1))\n for digit in str(new_recipies):\n board.append(int(digit))\n for idx, elf in enumerate(elves):\n elves[idx] = (elf + 1 + board[elf]) % len(board)\n if board[-len(search):] == search:\n return len(board) - len(search)\n else:\n return len(board) - len(search) - 1\n\n\nif __name__ == \"__main__\":\n print(ten_scores(909441))\n print(search(\"909441\"))\n" }, { "alpha_fraction": 0.5579284429550171, "alphanum_fraction": 0.5942338705062866, "avg_line_length": 28.265625, "blob_id": "640d1ca023154330153607469a50c3b7d975c2a1", "content_id": "b46c6e94854a71bfd7fe625e4423f0948788d6a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1873, "license_type": "no_license", "max_line_length": 83, "num_lines": 64, "path": "/day_06_coordinates.py", "repo_name": "Wooble/advent2018", "src_encoding": "UTF-8", "text": "import collections\nimport itertools\n\n\ndef manhattan(p1, p2):\n return sum(abs(x - y) for x, y in zip(p1, p2))\n\n\ndef nearest_to(point, data):\n data_with_dist = ((i, pt, manhattan(point, pt)) for i, pt in enumerate(data))\n distances = sorted(data_with_dist, key=lambda pt: pt[2])\n\n if distances[0][2] == distances[1][2]:\n return None\n return distances[0][0]\n\n\ndef largest_area(data, bound):\n possibles = set(range(len(data)))\n mapping = {}\n for pt in itertools.product(range(bound), repeat=2):\n mapping[pt] = nearest_to(pt, data)\n\n for pt in ((0, y) for y in range(bound)):\n possibles.discard(mapping[pt])\n for pt in ((bound - 1, y) for y in range(bound)):\n possibles.discard(mapping[pt])\n for pt in ((x, 0) for x in range(bound)):\n possibles.discard(mapping[pt])\n for pt in ((x, bound - 1) for x in range(bound)):\n possibles.discard(mapping[pt])\n\n c = collections.Counter(v for v in mapping.values() if v in possibles)\n return c.most_common(1)[0][1]\n\n\ndef total_dist(point, data):\n return sum(manhattan(point, p) for p in data)\n\n\ndef safe_region(data, dist, bound):\n mapping = {}\n for pt in itertools.product(range(bound), repeat=2):\n mapping[pt] = total_dist(pt, data) < dist\n return sum(1 for v in mapping.values() if v)\n\n\ndef test_largest_data():\n example = [(1, 1), (1, 6), (8, 3), (3, 4), (5, 5), (8, 9)]\n assert largest_area(example, 20) == 17\n\n\ndef test_safe_region():\n example = [(1, 1), (1, 6), (8, 3), (3, 4), (5, 5), (8, 9)]\n assert safe_region(example, 32, 20) == 16\n\n\nif __name__ == \"__main__\":\n with open(\"06_input.txt\") as f:\n coordinates = [\n pair for pair in (tuple(int(x) for x in line.split(\",\")) for line in f)\n ]\n print(largest_area(coordinates, 500))\n print(safe_region(coordinates, 10000, 500))\n" }, { "alpha_fraction": 0.5278944373130798, "alphanum_fraction": 0.5476904511451721, "avg_line_length": 20.9342098236084, "blob_id": "012463a504321ee2c1238f85cc7ed6118b42ff5a", "content_id": "85665dbef000183128a73ff017e476cbfe5ff92c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1667, "license_type": "no_license", "max_line_length": 113, "num_lines": 76, "path": "/day_12_life.py", "repo_name": "Wooble/advent2018", "src_encoding": "UTF-8", "text": "\"\"\"1-D Game of life, essentially.\"\"\"\n\n\nEXAMPLE_INPUT = \"\"\"initial state: #..#.#..##......###...###\n\n...## => #\n..#.. => #\n.#... => #\n.#.#. => #\n.#.## => #\n.##.. => #\n.#### => #\n#.#.# => #\n#.### => #\n##.#. => #\n##.## => #\n###.. => #\n###.# => #\n####. => #\n\"\"\"\n\n\ndef parse_input(input_data):\n lines = input_data.splitlines()\n state_string = lines[0].split(\": \")[1].strip()\n state = {idx: True for idx, c in enumerate(state_string) if c == \"#\"}\n rules = set()\n for line in lines[2:]:\n if \"=> #\" in line:\n rules.add(tuple(c == \"#\" for c in line[:5]))\n return state, rules\n\n\ndef test_checksum():\n assert checksum(EXAMPLE_INPUT) == 325\n\n\ndef state_after(data, iterations):\n state, rules = parse_input(data)\n\n for _ in range(iterations):\n state = apply_rules(state, rules)\n\n return state\n\n\ndef checksum(data):\n state = state_after(data, 20)\n\n return sum(k for k, v in state.items() if v)\n\n\ndef apply_rules(state, rules):\n newstate = {}\n\n for cell in range(min(state.keys()) - 4, max(state.keys()) + 4):\n rule = tuple(state.get(slot, False) for slot in range(cell - 2, cell + 3))\n if rule in rules:\n newstate[cell] = True\n\n return newstate\n\n\ndef calculated_checksum(data, iterations):\n state = state_after(data, 500)\n # assumption: stable pattern moves right one space per iteration after this, based on observation in debugger\n\n return sum(k + iterations - 500 for k in state.keys())\n\n\nif __name__ == \"__main__\":\n with open(\"12_input.txt\") as f:\n real_input = f.read()\n\n print(checksum(real_input))\n print(calculated_checksum(real_input, 50_000_000_000))\n" }, { "alpha_fraction": 0.5726795196533203, "alphanum_fraction": 0.6187974214553833, "avg_line_length": 24.954545974731445, "blob_id": "19f98ace4d37d78e689fa874babcdf2e2c2b8ade", "content_id": "99b2d5b9e07fe231435b7a51005c9658034d9fe0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1713, "license_type": "no_license", "max_line_length": 65, "num_lines": 66, "path": "/day_09_marbles.py", "repo_name": "Wooble/advent2018", "src_encoding": "UTF-8", "text": "import collections\n\nimport pytest\n\n\[email protected](\n params=[\n (\"9 players; last marble is worth 25 points\", 32),\n (\"10 players; last marble is worth 1618 points\", 8317),\n (\"13 players; last marble is worth 7999 points\", 146373),\n (\"17 players; last marble is worth 1104 points\", 2764),\n (\"21 players; last marble is worth 6111 points\", 54718),\n (\"30 players; last marble is worth 5807 points\", 37305),\n ]\n)\ndef exampledata(request):\n return request.param\n\n\ndef test_highscore(exampledata):\n assert highscore(exampledata[0]) == exampledata[1]\n\n\ndef parse_data(data):\n parts = data.split()\n return int(parts[0]), int(parts[-2])\n\n\ndef highscore(data):\n num_players, last_marble = parse_data(data)\n\n scores = calc_scores(last_marble, num_players)\n return max(scores)\n\n\ndef highscore_big(data):\n num_players, last_marble = parse_data(data)\n last_marble *= 100\n\n scores = calc_scores(last_marble, num_players)\n return max(scores)\n\n\ndef calc_scores(last_marble, num_players):\n board = collections.deque([0])\n scores = [0] * num_players\n current_player = 0\n for current_marble in range(1, last_marble + 1):\n if current_marble % 23:\n board.rotate(-1)\n board.append(current_marble)\n else:\n scores[current_player] += current_marble\n board.rotate(7)\n scores[current_player] += board.pop()\n board.rotate(-1)\n current_player += 1\n current_player %= num_players\n return scores\n\n\nif __name__ == \"__main__\":\n with open(\"09_input.txt\") as f:\n data = f.readline().strip()\n print(highscore(data))\n print(highscore_big(data))\n" }, { "alpha_fraction": 0.5528882145881653, "alphanum_fraction": 0.5753938555717468, "avg_line_length": 21.593219757080078, "blob_id": "207b2b7e99b81e6b8c4501576a46ced9813199d1", "content_id": "ab0592f5df6de6403afb43c9de4d9270069b8c60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1333, "license_type": "no_license", "max_line_length": 69, "num_lines": 59, "path": "/day_08_tree.py", "repo_name": "Wooble/advent2018", "src_encoding": "UTF-8", "text": "import collections\nimport pytest\n\n\[email protected]\ndef exampledata():\n return collections.deque(\n int(x) for x in \"2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2\".split()\n )\n\n\ndef test_metadata_sum(exampledata):\n assert metadata_sum(exampledata) == 138\n\n\ndef test_rootval(exampledata):\n assert rootval(exampledata) == 66\n\n\ndef metadata_sum(data):\n num_children = data.popleft()\n num_metadata = data.popleft()\n mdsum = 0\n for _ in range(num_children):\n mdsum += metadata_sum(data)\n for _ in range(num_metadata):\n mdsum += data.popleft()\n return mdsum\n\n\ndef rootval(data):\n num_children = data.popleft()\n num_metadata = data.popleft()\n children = []\n metadata = []\n\n for _ in range(num_children):\n children.append(rootval(data))\n for _ in range(num_metadata):\n metadata.append(data.popleft())\n\n if not children:\n return sum(metadata)\n else:\n rv = 0\n for x in metadata:\n if x:\n try:\n rv += children[x - 1]\n except IndexError:\n pass\n return rv\n\n\nif __name__ == \"__main__\":\n with open(\"08_input.txt\") as f:\n data = [int(x) for x in f.read().split()]\n print(metadata_sum(collections.deque(data)))\n print(rootval(collections.deque(data)))\n" }, { "alpha_fraction": 0.5641025900840759, "alphanum_fraction": 0.5753846168518066, "avg_line_length": 18.5, "blob_id": "09d7f49a3829c8cb08e9df6b5aaf9170a0a10a0b", "content_id": "1cce814236685bf41a1cb366f00c5d7700c7eb42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 975, "license_type": "no_license", "max_line_length": 87, "num_lines": 50, "path": "/day_05_alchemy.py", "repo_name": "Wooble/advent2018", "src_encoding": "UTF-8", "text": "import itertools\nimport string\n\nTESTDATA = \"dabAcCaCBAcCcaDA\"\n\n\ndef one_pass(data):\n pairs = itertools.zip_longest(data, data[1:])\n output = []\n for p1, p2 in pairs:\n if p1.swapcase() == p2:\n next(pairs)\n else:\n output.append(p1)\n return \"\".join(output)\n\n\ndef alchemy(data):\n old = data\n while True:\n new = one_pass(old)\n if len(new) == len(old):\n return new\n old = new\n\n\ndef drop_letter(c, data):\n return data.replace(c, \"\").replace(c.upper(), \"\")\n\n\ndef best_removed(data):\n return min(\n len(a) for a in (alchemy(drop_letter(c, data)) for c in string.ascii_lowercase)\n )\n\n\ndef test_alchemy():\n assert len(alchemy(TESTDATA)) == 10\n\n\ndef test_best_removed():\n assert best_removed(TESTDATA) == 4\n\n\nif __name__ == \"__main__\":\n with open(\"05_input.txt\") as f:\n real_data = f.read().strip()\n\n print(len(alchemy(real_data)))\n print(best_removed(real_data))\n" }, { "alpha_fraction": 0.5202364921569824, "alphanum_fraction": 0.6343792676925659, "avg_line_length": 27.558441162109375, "blob_id": "a6276653a3f2e3d96fee4ca0aad352c8ab7cf5b3", "content_id": "f5a6f2579830d4054078adf41d31e7965c4cd19d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2199, "license_type": "no_license", "max_line_length": 81, "num_lines": 77, "path": "/04_repose.py", "repo_name": "Wooble/advent2018", "src_encoding": "UTF-8", "text": "import collections\nimport dataclasses\n\nTEST_DATA = \"\"\"[1518-11-01 00:00] Guard #10 begins shift\n[1518-11-01 00:05] falls asleep\n[1518-11-01 00:25] wakes up\n[1518-11-01 00:30] falls asleep\n[1518-11-01 00:55] wakes up\n[1518-11-01 23:58] Guard #99 begins shift\n[1518-11-02 00:40] falls asleep\n[1518-11-02 00:50] wakes up\n[1518-11-03 00:05] Guard #10 begins shift\n[1518-11-03 00:24] falls asleep\n[1518-11-03 00:29] wakes up\n[1518-11-04 00:02] Guard #99 begins shift\n[1518-11-04 00:36] falls asleep\n[1518-11-04 00:46] wakes up\n[1518-11-05 00:03] Guard #99 begins shift\n[1518-11-05 00:45] falls asleep\n[1518-11-05 00:55] wakes up\"\"\".splitlines()\n\n\[email protected]\nclass Guard:\n total_sleep: int = 0\n hours_slept: collections.Counter = dataclasses.field(\n default_factory=collections.Counter\n )\n\n\ndef make_guards(data):\n guards = collections.defaultdict(Guard)\n current_guard = None\n data_iter = iter(data)\n for line in data_iter:\n if \"Guard #\" in line:\n current_guard = int(line.partition(\"Guard #\")[2].split()[0])\n continue\n assert \"falls asleep\" in line\n start_time = int(line.partition(\":\")[2][:2])\n line2 = next(data_iter)\n assert \"wakes up\" in line2\n end_time = int(line2.partition(\":\")[2][:2])\n guard = guards[current_guard]\n for t in range(start_time, end_time):\n guard.total_sleep += 1\n guard.hours_slept[t] += 1\n return guards\n\n\ndef most_freq(data):\n guards = make_guards(data)\n chosen_guard = max(\n guards.items(), key=lambda item: item[1].hours_slept.most_common(1)[0][1]\n )\n return chosen_guard[0] * chosen_guard[1].hours_slept.most_common(1)[0][0]\n\n\ndef findtime(data):\n guards = make_guards(data)\n chosen_guard = max(guards.items(), key=lambda item: item[1].total_sleep)\n return chosen_guard[0] * chosen_guard[1].hours_slept.most_common(1)[0][0]\n\n\ndef test_findtime():\n assert findtime(TEST_DATA) == 240\n\n\ndef test_most_freq():\n assert most_freq(TEST_DATA) == 4455\n\n\nif __name__ == \"__main__\":\n with open(\"04_input.txt\") as f:\n print(findtime(sorted(f)))\n f.seek(0)\n print(most_freq(sorted(f)))\n" }, { "alpha_fraction": 0.47555556893348694, "alphanum_fraction": 0.4880000054836273, "avg_line_length": 22.275861740112305, "blob_id": "53df3cb2f7cff26b3143a43d7edc4ed652cb5340", "content_id": "6a48841312763af173f24a30494db07cc456fabf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3375, "license_type": "no_license", "max_line_length": 100, "num_lines": 145, "path": "/day_13_minecarts.py", "repo_name": "Wooble/advent2018", "src_encoding": "UTF-8", "text": "import collections\nfrom dataclasses import dataclass\n\nCART_DIRS = {\n \"^\": ((0, -1), \"|\"),\n \"v\": ((0, 1,), \"|\"),\n \"<\": ((-1, 0), \"-\"),\n \">\": ((1, 0), \"-\"),\n}\n\nNEXT_TURN = {\n \"L\": \"S\",\n \"S\": \"R\",\n \"R\": \"L\",\n}\n\ndef test_straight():\n testdata = \"\"\"|\nv\n|\n|\n|\n^\n|\n\"\"\"\n assert collision_loc(testdata) == (0, 3)\n\n\ndef test_example_two():\n testdata = r\"\"\"/->-\\ \n| | /----\\\n| /-+--+-\\ |\n| | | | v |\n\\-+-/ \\-+--/\n \\------/ \n \"\"\"\n assert collision_loc(testdata) == (7, 3)\n\n\ndef test_last_cart():\n testdata = r\"\"\"/>-<\\ \n| | \n| /<+-\\\n| | | v\n\\>+</ |\n | ^\n \\<->/\n \"\"\"\n assert last_cart_loc(testdata) == (6, 4)\n\n\n@dataclass\nclass Cart:\n location: tuple\n direction: tuple\n next_turn: str = \"L\"\n exists: bool = True\n\n def process_move(self, tracks):\n if not self.exists:\n return\n self.location = (self.location[0] + self.direction[0], self.location[1] + self.direction[1])\n self.change_direction(tracks[self.location])\n\n def change_direction(self, symbol):\n if symbol == \"+\":\n if self.next_turn == \"L\":\n self.turn_left()\n elif self.next_turn == \"R\":\n self.turn_right()\n self.next_turn = NEXT_TURN[self.next_turn]\n elif symbol == \"/\":\n if self.direction[0] == 0:\n self.turn_right()\n else:\n self.turn_left()\n elif symbol == \"\\\\\":\n if self.direction[0] == 0:\n self.turn_left()\n else:\n self.turn_right()\n\n def turn_left(self):\n x, y = self.direction\n self.direction = (y, -x)\n\n def turn_right(self):\n x, y = self.direction\n self.direction = (-y, x)\n\n\ndef parse_data(data):\n tracks = {}\n carts = []\n\n for y, line in enumerate(data.splitlines()):\n for x, char in enumerate(line):\n if char in CART_DIRS:\n carts.append(Cart(location=(x, y), direction=CART_DIRS[char][0]))\n char = CART_DIRS[char][1]\n if char.strip():\n tracks[(x, y)] = char\n return tracks, carts\n\n\ndef collision_loc(data):\n tracks, carts = parse_data(data)\n\n while True:\n for cart in sorted(carts, key=lambda c: (c.location[1], c.location[0])):\n cart.process_move(tracks)\n\n loc_count = collections.Counter(cart.location for cart in carts)\n maxloc = loc_count.most_common(1)[0]\n if maxloc[1] > 1:\n return maxloc[0]\n\n\ndef last_cart_loc(data):\n tracks, carts = parse_data(data)\n\n while True:\n for cart in sorted(carts, key=lambda c: (c.location[1], c.location[0])):\n cart.process_move(tracks)\n\n loc_count = collections.Counter(cart.location for cart in carts if cart.exists)\n maxloc = loc_count.most_common(1)[0]\n if maxloc[1] > 1:\n for c in carts:\n if c.location == maxloc[0]:\n c.exists = False\n carts = [c for c in carts if c.exists]\n if len(carts) == 1:\n return carts[0].location\n if not carts:\n raise ValueError(\"Out of carts\")\n\n\n\n\nif __name__ == \"__main__\":\n with open(\"13_input.txt\") as f:\n data = f.read()\n print(collision_loc(data))\n print(last_cart_loc(data))\n" }, { "alpha_fraction": 0.4895758330821991, "alphanum_fraction": 0.5327102541923523, "avg_line_length": 29.91111183166504, "blob_id": "70fd0255dbf7d10284ce57e7e39e5e2d9db84233", "content_id": "dbeaf9d6218b734433ad77776cac85c5177878be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1391, "license_type": "no_license", "max_line_length": 74, "num_lines": 45, "path": "/03_slice_it.py", "repo_name": "Wooble/advent2018", "src_encoding": "UTF-8", "text": "import collections\nimport itertools\nimport re\n\n\ndef overlap(data):\n placement = collections.Counter()\n for line in data:\n numbers = re.search(r\"@ (\\d+),(\\d+): (\\d+)x(\\d+)\", line)\n x, y, w, h = (int(i) for i in numbers.group(1, 2, 3, 4))\n for x1, y1 in itertools.product(range(x, x + w), range(y, y + h)):\n placement[(x1, y1)] += 1\n return sum(1 for count in placement.values() if count > 1)\n\n\ndef no_overlap(data):\n claims = []\n placement = collections.defaultdict(list)\n overlaps = set()\n for line in data:\n numbers = re.search(r\"(\\d+) @ (\\d+),(\\d+): (\\d+)x(\\d+)\", line)\n claim, x, y, w, h = (int(i) for i in numbers.group(1, 2, 3, 4, 5))\n claims.append(claim)\n for x1, y1 in itertools.product(range(x, x + w), range(y, y + h)):\n placement[(x1, y1)].append(claim)\n if len(placement[(x1, y1)]) > 1:\n overlaps.update(placement[(x1, y1)])\n return (set(claims) - overlaps).pop()\n\n\ndef test_overlap():\n data = [\"#1 @ 1,3: 4x4\", \"#2 @ 3,1: 4x4\", \"#3 @ 5,5: 2x2\"]\n assert overlap(data) == 4\n\n\ndef test_no_overlap():\n data = [\"#1 @ 1,3: 4x4\", \"#2 @ 3,1: 4x4\", \"#3 @ 5,5: 2x2\"]\n assert no_overlap(data) == 3\n\n\nif __name__ == \"__main__\":\n with open(\"03_input.txt\") as infile:\n print(overlap(infile))\n infile.seek(0)\n print(no_overlap(infile))\n" }, { "alpha_fraction": 0.7933333516120911, "alphanum_fraction": 0.8199999928474426, "avg_line_length": 49.33333206176758, "blob_id": "d759c17880b644b2e3f6e6dafeb8132d7f1de9c5", "content_id": "085afa91246e4139a6e44ac10d7c1183b98ef465", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 150, "license_type": "no_license", "max_line_length": 88, "num_lines": 3, "path": "/README.md", "repo_name": "Wooble/advent2018", "src_encoding": "UTF-8", "text": "Solutions to Advent of Code 2018 (probably mostly in Python)\n\nWarning: contains AOC spoilers; solve the problems yourself before viewing my solutions!" }, { "alpha_fraction": 0.5745019912719727, "alphanum_fraction": 0.5844621658325195, "avg_line_length": 28.52941131591797, "blob_id": "a11026646d47488d9c612ffb5b2eb48cb2ed73d0", "content_id": "a4b5a84d6d5b180a80ad496d51958196ab331857", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2510, "license_type": "no_license", "max_line_length": 80, "num_lines": 85, "path": "/day_07_parts.py", "repo_name": "Wooble/advent2018", "src_encoding": "UTF-8", "text": "import collections\nimport pytest\nimport itertools\n\n\[email protected]\ndef data():\n lines = \"\"\"Step C must be finished before step A can begin.\nStep C must be finished before step F can begin.\nStep A must be finished before step B can begin.\nStep A must be finished before step D can begin.\nStep B must be finished before step E can begin.\nStep D must be finished before step E can begin.\nStep F must be finished before step E can begin.\"\"\".splitlines()\n return lines\n\n\ndef test_step_order(data):\n assert step_order(data) == \"CABDFE\"\n\n\ndef step_order(lines):\n final_order = []\n deps = get_deps(lines)\n\n while deps:\n doing = sorted(dep for dep in deps.items() if not len(dep[1]))[0][0]\n final_order.append(doing)\n for step in deps.values():\n step.discard(doing)\n del deps[doing]\n return \"\".join(final_order)\n\n\ndef get_deps(lines):\n deps = collections.defaultdict(set)\n for line in lines:\n parts = line.partition(\" must be finished before step \")\n before = parts[0][-1]\n then = parts[2][0]\n deps[then].add(before)\n deps[before] # Create an empty set to cover the first item with no deps\n return deps\n\n\ndef test_time(data):\n assert (time(data, 2, 0)) == 15\n\n\ndef time_for_task(t: str, delay: int) -> int:\n return ord(t) - ord(\"A\") + 1 + delay\n\n\ndef time(data, workers: int, delay: int):\n deps = get_deps(data)\n worker_pool = [None] * workers\n for current_time in itertools.count():\n # work on existing tasks\n for i, worker in enumerate(worker_pool):\n if worker is not None:\n worker[1] -= 1\n if not worker[1]:\n # Worker is finished;\n for step in deps.values():\n step.discard(worker[0])\n worker_pool[i] = None\n\n # queue up some more tasks\n available_tasks = sorted(dep for dep in deps.items() if not len(dep[1]))\n if not deps and all(w is None for w in worker_pool):\n return current_time\n for task in available_tasks:\n for i, worker in enumerate(worker_pool):\n if worker is None:\n worker_pool[i] = [task[0], time_for_task(task[0], delay)]\n del deps[task[0]]\n break\n\n\nif __name__ == \"__main__\":\n test_time(data())\n with open(\"07_input.txt\") as f:\n lines = f.readlines()\n print(step_order(lines))\n print(time(lines, 5, 60))\n" }, { "alpha_fraction": 0.5347179174423218, "alphanum_fraction": 0.5874147415161133, "avg_line_length": 26.3389835357666, "blob_id": "0e8748a1aec57aaf996d0a4aad01f4618c26e67d", "content_id": "13b9d94cd0197ec46e51084c1ea1550edfe1f046", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3226, "license_type": "no_license", "max_line_length": 87, "num_lines": 118, "path": "/day_10_message.py", "repo_name": "Wooble/advent2018", "src_encoding": "UTF-8", "text": "import dataclasses\nimport re\nfrom typing import Iterable\n\nimport pytest\n\nfrom PIL import Image\nimport pytesseract\n\npytesseract.pytesseract.tesseract_cmd = (\n r\"C:\\Program Files (x86)\\Tesseract-OCR\\tesseract\"\n)\n\n\[email protected]\ndef exampledata():\n return \"\"\"position=< 9, 1> velocity=< 0, 2>\nposition=< 7, 0> velocity=<-1, 0>\nposition=< 3, -2> velocity=<-1, 1>\nposition=< 6, 10> velocity=<-2, -1>\nposition=< 2, -4> velocity=< 2, 2>\nposition=<-6, 10> velocity=< 2, -2>\nposition=< 1, 8> velocity=< 1, -1>\nposition=< 1, 7> velocity=< 1, 0>\nposition=<-3, 11> velocity=< 1, -2>\nposition=< 7, 6> velocity=<-1, -1>\nposition=<-2, 3> velocity=< 1, 0>\nposition=<-4, 3> velocity=< 2, 0>\nposition=<10, -3> velocity=<-1, 1>\nposition=< 5, 11> velocity=< 1, -2>\nposition=< 4, 7> velocity=< 0, -1>\nposition=< 8, -2> velocity=< 0, 1>\nposition=<15, 0> velocity=<-2, 0>\nposition=< 1, 6> velocity=< 1, 0>\nposition=< 8, 9> velocity=< 0, -1>\nposition=< 3, 3> velocity=<-1, 1>\nposition=< 0, 5> velocity=< 0, -1>\nposition=<-2, 2> velocity=< 2, 0>\nposition=< 5, -2> velocity=< 1, 2>\nposition=< 1, 4> velocity=< 2, 1>\nposition=<-2, 7> velocity=< 2, -2>\nposition=< 3, 6> velocity=<-1, -1>\nposition=< 5, 0> velocity=< 1, 0>\nposition=<-6, 0> velocity=< 2, 0>\nposition=< 5, 9> velocity=< 1, -2>\nposition=<14, 7> velocity=<-2, 0>\nposition=<-3, 6> velocity=< 2, -1>\"\"\".splitlines()\n\n\ndef test_message(exampledata):\n assert message(exampledata) == \"HI\"\n\n\[email protected]\nclass Light:\n position: tuple\n velocity: tuple\n\n\ndef get_lights(data: Iterable[str]):\n lights = []\n for line in data:\n results = re.match(r\"position=<(.*),(.*)> velocity=<(.*),(.*)>\", line)\n numbers = [int(x) for x in results.groups()]\n lights.append(Light(position=tuple(numbers[0:2]), velocity=tuple(numbers[2:])))\n return lights\n\n\ndef getsize(lights):\n width = max(light.position[0] for light in lights) - min(\n light.position[0] for light in lights\n )\n length = max(light.position[1] for light in lights) - min(\n light.position[1] for light in lights\n )\n return width + 10, length + 10\n\n\ndef get_adjustment(lights):\n xadj = min(light.position[0] for light in lights) * -1\n yadj = min(light.position[1] for light in lights) * -1\n return xadj + 4, yadj + 4\n\n\ndef adjust(pos, adj):\n return (pos[0] + adj[0], pos[1] + adj[1])\n\n\ndef new_pos(light):\n return light.position[0] + light.velocity[0], light.position[1] + light.velocity[1]\n\n\ndef message(data):\n lights = get_lights(data)\n time = 0\n while True:\n size = getsize(lights)\n adjustment = get_adjustment(lights)\n print(size[0])\n if size[0] < 100:\n im = Image.new(\"1\", size, 1)\n for light in lights:\n location = adjust(light.position, adjustment)\n im.putpixel(location, 0)\n # im.show()\n\n msg = pytesseract.image_to_string(im)\n if msg:\n return msg, time\n for light in lights:\n light.position = new_pos(light)\n time += 1\n\n\nif __name__ == \"__main__\":\n with open(\"10_input.txt\") as f:\n data = f.readlines()\n print(message(data))\n" } ]
17
cgarwood/homeassistant-zwave_mqtt
https://github.com/cgarwood/homeassistant-zwave_mqtt
b0173bd74a5ce38129ebdd6417f7409164532371
9081785b5da943e127b62342ceae35b29aeb55e3
3205be4bc723c8439f552898605483ffd8b0bec8
refs/heads/master
2020-11-29T16:26:21.545621
2020-07-27T12:17:28
2020-07-27T12:17:28
230,167,541
91
22
null
2019-12-26T00:13:50
2020-06-29T20:25:03
2020-05-13T03:13:21
Python
[ { "alpha_fraction": 0.5864151120185852, "alphanum_fraction": 0.6090565919876099, "avg_line_length": 28.44444465637207, "blob_id": "e95f39b44ea161a948241c2f161090c9b01cedba", "content_id": "d12defe65dc553adf3682ef1c6f2f28d4674c715", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1325, "license_type": "no_license", "max_line_length": 71, "num_lines": 45, "path": "/tests/test_light.py", "repo_name": "cgarwood/homeassistant-zwave_mqtt", "src_encoding": "UTF-8", "text": "\"\"\"Test Z-Wave Lights.\"\"\"\nfrom custom_components.zwave_mqtt.light import byte_to_zwave_brightness\n\nfrom tests.common import setup_zwave\n\n\nasync def test_light(hass, sent_messages):\n \"\"\"Test setting up config entry.\"\"\"\n await setup_zwave(hass, \"generic_network_dump.csv\")\n\n # Test loaded\n state = hass.states.get(\"light.led_bulb_6_multi_colour_level\")\n assert state is not None\n assert state.state == \"off\"\n\n # Test turning on\n new_brightness = 45\n await hass.services.async_call(\n \"light\",\n \"turn_on\",\n {\n \"entity_id\": \"light.led_bulb_6_multi_colour_level\",\n \"brightness\": new_brightness,\n },\n blocking=True,\n )\n assert len(sent_messages) == 1\n msg = sent_messages[0]\n assert msg[\"topic\"] == \"OpenZWave/1/command/setvalue/\"\n assert msg[\"payload\"] == {\n \"Value\": byte_to_zwave_brightness(new_brightness),\n \"ValueIDKey\": 659128337,\n }\n\n # Test turning off\n await hass.services.async_call(\n \"light\",\n \"turn_off\",\n {\"entity_id\": \"light.led_bulb_6_multi_colour_level\"},\n blocking=True,\n )\n assert len(sent_messages) == 2\n msg = sent_messages[1]\n assert msg[\"topic\"] == \"OpenZWave/1/command/setvalue/\"\n assert msg[\"payload\"] == {\"Value\": 0, \"ValueIDKey\": 659128337}\n" }, { "alpha_fraction": 0.684733510017395, "alphanum_fraction": 0.684733510017395, "avg_line_length": 22.553192138671875, "blob_id": "2de64fc205d67aaff6db6c5223a39daab657b38b", "content_id": "62d0aa199905f304a72b50d4919395175f0ee366", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1107, "license_type": "no_license", "max_line_length": 70, "num_lines": 47, "path": "/tests/conftest.py", "repo_name": "cgarwood/homeassistant-zwave_mqtt", "src_encoding": "UTF-8", "text": "\"\"\"Helpers for tests.\"\"\"\nimport json\nimport logging\nfrom pathlib import Path\n\nfrom asynctest import patch\nimport pytest\n\nfrom homeassistant import config_entries, core\n\nfrom tests.common import mock_storage\n\nlogging.basicConfig(level=logging.DEBUG)\n\n\[email protected]\nasync def hass(loop, hass_storage, sent_messages):\n \"\"\"Home Assistant instance.\"\"\"\n hass = core.HomeAssistant()\n\n hass.config.config_dir = str(Path(__file__).parent.parent)\n hass.config.skip_pip = True\n\n hass.config_entries = config_entries.ConfigEntries(hass, {})\n await hass.config_entries.async_initialize()\n return hass\n\n\[email protected]\ndef hass_storage():\n \"\"\"Fixture to mock storage.\"\"\"\n with mock_storage() as stored_data:\n yield stored_data\n\n\[email protected]\ndef sent_messages():\n \"\"\"Fixture to capture sent messages.\"\"\"\n sent_messages = []\n\n with patch(\n \"homeassistant.components.mqtt.async_publish\",\n side_effect=lambda hass, topic, payload: sent_messages.append(\n {\"topic\": topic, \"payload\": json.loads(payload)}\n ),\n ):\n yield sent_messages\n" }, { "alpha_fraction": 0.5459640026092529, "alphanum_fraction": 0.5480018258094788, "avg_line_length": 37.911895751953125, "blob_id": "7b6781f23831138ee152661e108f5559497e8e3f", "content_id": "e19fd3dc887ecb5e1f43ea45282984922562be34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17666, "license_type": "no_license", "max_line_length": 87, "num_lines": 454, "path": "/custom_components/zwave_mqtt/discovery.py", "repo_name": "cgarwood/homeassistant-zwave_mqtt", "src_encoding": "UTF-8", "text": "\"\"\"Map Z-Wave nodes and values to Home Assistant entities.\"\"\"\n\nimport logging\n\nimport openzwavemqtt.const as const_ozw\nfrom openzwavemqtt.const import CommandClass, ValueGenre, ValueIndex, ValueType\n\nfrom . import const\n\n_LOGGER = logging.getLogger(__name__)\n\nDISCOVERY_SCHEMAS = [\n { # Binary sensors\n const.DISC_COMPONENT: \"binary_sensor\",\n const.DISC_GENERIC_DEVICE_CLASS: [\n const_ozw.GENERIC_TYPE_ENTRY_CONTROL,\n const_ozw.GENERIC_TYPE_SENSOR_ALARM,\n const_ozw.GENERIC_TYPE_SENSOR_BINARY,\n const_ozw.GENERIC_TYPE_SWITCH_BINARY,\n const_ozw.GENERIC_TYPE_METER,\n const_ozw.GENERIC_TYPE_SENSOR_MULTILEVEL,\n const_ozw.GENERIC_TYPE_SWITCH_MULTILEVEL,\n const_ozw.GENERIC_TYPE_THERMOSTAT,\n const_ozw.GENERIC_TYPE_SENSOR_NOTIFICATION,\n ],\n const.DISC_VALUES: {\n const.DISC_PRIMARY: {\n const.DISC_COMMAND_CLASS: [CommandClass.SENSOR_BINARY],\n const.DISC_TYPE: ValueType.BOOL,\n const.DISC_GENRE: ValueGenre.USER,\n },\n \"off_delay\": {\n const.DISC_COMMAND_CLASS: [CommandClass.CONFIGURATION],\n const.DISC_INDEX: [9],\n const.DISC_OPTIONAL: True,\n },\n },\n },\n { # Notification CommandClass translates to binary_sensor\n const.DISC_COMPONENT: \"binary_sensor\",\n const.DISC_VALUES: {\n const.DISC_PRIMARY: {\n const.DISC_COMMAND_CLASS: [CommandClass.NOTIFICATION],\n const.DISC_GENRE: ValueGenre.USER,\n const.DISC_TYPE: [ValueType.BOOL, ValueType.LIST],\n }\n },\n },\n { # thermostat without COMMAND_CLASS_THERMOSTAT_MODE\n const.DISC_COMPONENT: \"climate\",\n const.DISC_GENERIC_DEVICE_CLASS: [\n const_ozw.GENERIC_TYPE_THERMOSTAT,\n const_ozw.GENERIC_TYPE_SENSOR_MULTILEVEL,\n ],\n const.DISC_SPECIFIC_DEVICE_CLASS: [\n const_ozw.SPECIFIC_TYPE_THERMOSTAT_HEATING,\n const_ozw.SPECIFIC_TYPE_SETPOINT_THERMOSTAT,\n const_ozw.SPECIFIC_TYPE_NOT_USED,\n ],\n const.DISC_VALUES: {\n const.DISC_PRIMARY: {\n const.DISC_COMMAND_CLASS: [CommandClass.THERMOSTAT_SETPOINT]\n },\n \"temperature\": {\n const.DISC_COMMAND_CLASS: [CommandClass.SENSOR_MULTILEVEL],\n const.DISC_INDEX: [ValueIndex.SENSOR_MULTILEVEL_AIR_TEMPERATURE],\n const.DISC_OPTIONAL: True,\n },\n \"mode\": {\n const.DISC_COMMAND_CLASS: [CommandClass.THERMOSTAT_MODE],\n const.DISC_OPTIONAL: True,\n },\n \"fan_mode\": {\n const.DISC_COMMAND_CLASS: [CommandClass.THERMOSTAT_FAN_MODE],\n const.DISC_OPTIONAL: True,\n },\n \"operating_state\": {\n const.DISC_COMMAND_CLASS: [CommandClass.THERMOSTAT_OPERATING_STATE],\n const.DISC_OPTIONAL: True,\n },\n \"fan_action\": {\n const.DISC_COMMAND_CLASS: [CommandClass.THERMOSTAT_FAN_STATE],\n const.DISC_OPTIONAL: True,\n },\n },\n },\n { # # thermostat with COMMAND_CLASS_THERMOSTAT_MODE\n const.DISC_COMPONENT: \"climate\",\n const.DISC_GENERIC_DEVICE_CLASS: [\n const_ozw.GENERIC_TYPE_THERMOSTAT,\n const_ozw.GENERIC_TYPE_SENSOR_MULTILEVEL,\n ],\n const.DISC_SPECIFIC_DEVICE_CLASS: [\n const_ozw.SPECIFIC_TYPE_THERMOSTAT_GENERAL,\n const_ozw.SPECIFIC_TYPE_THERMOSTAT_GENERAL_V2,\n const_ozw.SPECIFIC_TYPE_SETBACK_THERMOSTAT,\n ],\n const.DISC_VALUES: {\n const.DISC_PRIMARY: {\n const.DISC_COMMAND_CLASS: [CommandClass.THERMOSTAT_MODE]\n },\n \"setpoint_heating\": {\n const.DISC_COMMAND_CLASS: [CommandClass.THERMOSTAT_SETPOINT],\n const.DISC_INDEX: [1],\n const.DISC_OPTIONAL: True,\n },\n \"setpoint_cooling\": {\n const.DISC_COMMAND_CLASS: [CommandClass.THERMOSTAT_SETPOINT],\n const.DISC_INDEX: [2],\n const.DISC_OPTIONAL: True,\n },\n \"setpoint_furnace\": {\n const.DISC_COMMAND_CLASS: [CommandClass.THERMOSTAT_SETPOINT],\n const.DISC_INDEX: [7],\n const.DISC_OPTIONAL: True,\n },\n \"setpoint_dry_air\": {\n const.DISC_COMMAND_CLASS: [CommandClass.THERMOSTAT_SETPOINT],\n const.DISC_INDEX: [8],\n const.DISC_OPTIONAL: True,\n },\n \"setpoint_moist_air\": {\n const.DISC_COMMAND_CLASS: [CommandClass.THERMOSTAT_SETPOINT],\n const.DISC_INDEX: [9],\n const.DISC_OPTIONAL: True,\n },\n \"setpoint_auto_changeover\": {\n const.DISC_COMMAND_CLASS: [CommandClass.THERMOSTAT_SETPOINT],\n const.DISC_INDEX: [10],\n const.DISC_OPTIONAL: True,\n },\n \"setpoint_eco_heating\": {\n const.DISC_COMMAND_CLASS: [CommandClass.THERMOSTAT_SETPOINT],\n const.DISC_INDEX: [11],\n const.DISC_OPTIONAL: True,\n },\n \"setpoint_eco_cooling\": {\n const.DISC_COMMAND_CLASS: [CommandClass.THERMOSTAT_SETPOINT],\n const.DISC_INDEX: [12],\n const.DISC_OPTIONAL: True,\n },\n \"setpoint_away_heating\": {\n const.DISC_COMMAND_CLASS: [CommandClass.THERMOSTAT_SETPOINT],\n const.DISC_INDEX: [13],\n const.DISC_OPTIONAL: True,\n },\n \"setpoint_away_cooling\": {\n const.DISC_COMMAND_CLASS: [CommandClass.THERMOSTAT_SETPOINT],\n const.DISC_INDEX: [14],\n const.DISC_OPTIONAL: True,\n },\n \"setpoint_full_power\": {\n const.DISC_COMMAND_CLASS: [CommandClass.THERMOSTAT_SETPOINT],\n const.DISC_INDEX: [15],\n const.DISC_OPTIONAL: True,\n },\n \"temperature\": {\n const.DISC_COMMAND_CLASS: [CommandClass.SENSOR_MULTILEVEL],\n const.DISC_INDEX: [1],\n const.DISC_OPTIONAL: True,\n },\n \"fan_mode\": {\n const.DISC_COMMAND_CLASS: [CommandClass.THERMOSTAT_FAN_MODE],\n const.DISC_OPTIONAL: True,\n },\n \"operating_state\": {\n const.DISC_COMMAND_CLASS: [CommandClass.THERMOSTAT_OPERATING_STATE],\n const.DISC_OPTIONAL: True,\n },\n \"fan_action\": {\n const.DISC_COMMAND_CLASS: [CommandClass.THERMOSTAT_FAN_STATE],\n const.DISC_OPTIONAL: True,\n },\n \"zxt_120_swing_mode\": {\n const.DISC_COMMAND_CLASS: [CommandClass.CONFIGURATION],\n const.DISC_INDEX: [33],\n const.DISC_OPTIONAL: True,\n },\n },\n },\n { # Rollershutter\n const.DISC_COMPONENT: \"cover\",\n const.DISC_GENERIC_DEVICE_CLASS: [\n const_ozw.GENERIC_TYPE_SWITCH_MULTILEVEL,\n const_ozw.GENERIC_TYPE_ENTRY_CONTROL,\n ],\n const.DISC_SPECIFIC_DEVICE_CLASS: [\n const_ozw.SPECIFIC_TYPE_CLASS_A_MOTOR_CONTROL,\n const_ozw.SPECIFIC_TYPE_CLASS_B_MOTOR_CONTROL,\n const_ozw.SPECIFIC_TYPE_CLASS_C_MOTOR_CONTROL,\n const_ozw.SPECIFIC_TYPE_MOTOR_MULTIPOSITION,\n const_ozw.SPECIFIC_TYPE_SECURE_BARRIER_ADDON,\n const_ozw.SPECIFIC_TYPE_SECURE_DOOR,\n ],\n const.DISC_VALUES: {\n const.DISC_PRIMARY: {\n const.DISC_COMMAND_CLASS: [CommandClass.SWITCH_MULTILEVEL],\n const.DISC_INDEX: [ValueIndex.SWITCH_MULTILEVEL_LEVEL],\n const.DISC_GENRE: ValueGenre.USER,\n },\n \"open\": {\n const.DISC_COMMAND_CLASS: [CommandClass.SWITCH_MULTILEVEL],\n const.DISC_INDEX: [ValueIndex.SWITCH_MULTILEVEL_BRIGHT],\n const.DISC_OPTIONAL: True,\n },\n \"close\": {\n const.DISC_COMMAND_CLASS: [CommandClass.SWITCH_MULTILEVEL],\n const.DISC_INDEX: [ValueIndex.SWITCH_MULTILEVEL_DIM],\n const.DISC_OPTIONAL: True,\n },\n \"fgrm222_slat_position\": {\n const.DISC_COMMAND_CLASS: [CommandClass.MANUFACTURER_PROPRIETARY],\n const.DISC_INDEX: [0],\n const.DISC_OPTIONAL: True,\n },\n \"fgrm222_tilt_position\": {\n const.DISC_COMMAND_CLASS: [CommandClass.MANUFACTURER_PROPRIETARY],\n const.DISC_INDEX: [1],\n const.DISC_OPTIONAL: True,\n },\n },\n },\n { # Garage Door Switch\n const.DISC_COMPONENT: \"cover\",\n const.DISC_GENERIC_DEVICE_CLASS: [\n const_ozw.GENERIC_TYPE_SWITCH_MULTILEVEL,\n const_ozw.GENERIC_TYPE_ENTRY_CONTROL,\n ],\n const.DISC_SPECIFIC_DEVICE_CLASS: [\n const_ozw.SPECIFIC_TYPE_CLASS_A_MOTOR_CONTROL,\n const_ozw.SPECIFIC_TYPE_CLASS_B_MOTOR_CONTROL,\n const_ozw.SPECIFIC_TYPE_CLASS_C_MOTOR_CONTROL,\n const_ozw.SPECIFIC_TYPE_MOTOR_MULTIPOSITION,\n const_ozw.SPECIFIC_TYPE_SECURE_BARRIER_ADDON,\n const_ozw.SPECIFIC_TYPE_SECURE_DOOR,\n ],\n const.DISC_VALUES: {\n const.DISC_PRIMARY: {\n const.DISC_COMMAND_CLASS: [CommandClass.SWITCH_BINARY],\n const.DISC_GENRE: ValueGenre.USER,\n }\n },\n },\n { # Garage Door Barrier\n const.DISC_COMPONENT: \"cover\",\n const.DISC_GENERIC_DEVICE_CLASS: [\n const_ozw.GENERIC_TYPE_SWITCH_MULTILEVEL,\n const_ozw.GENERIC_TYPE_ENTRY_CONTROL,\n ],\n const.DISC_SPECIFIC_DEVICE_CLASS: [\n const_ozw.SPECIFIC_TYPE_CLASS_A_MOTOR_CONTROL,\n const_ozw.SPECIFIC_TYPE_CLASS_B_MOTOR_CONTROL,\n const_ozw.SPECIFIC_TYPE_CLASS_C_MOTOR_CONTROL,\n const_ozw.SPECIFIC_TYPE_MOTOR_MULTIPOSITION,\n const_ozw.SPECIFIC_TYPE_SECURE_BARRIER_ADDON,\n const_ozw.SPECIFIC_TYPE_SECURE_DOOR,\n ],\n const.DISC_VALUES: {\n const.DISC_PRIMARY: {\n const.DISC_COMMAND_CLASS: [CommandClass.BARRIER_OPERATOR],\n const.DISC_INDEX: [ValueIndex.BARRIER_OPERATOR_LABEL],\n }\n },\n },\n { # Fan\n const.DISC_COMPONENT: \"fan\",\n const.DISC_GENERIC_DEVICE_CLASS: [const_ozw.GENERIC_TYPE_SWITCH_MULTILEVEL],\n const.DISC_SPECIFIC_DEVICE_CLASS: [const_ozw.SPECIFIC_TYPE_FAN_SWITCH],\n const.DISC_VALUES: {\n const.DISC_PRIMARY: {\n const.DISC_COMMAND_CLASS: [CommandClass.SWITCH_MULTILEVEL],\n const.DISC_INDEX: [ValueIndex.SWITCH_MULTILEVEL_LEVEL],\n const.DISC_TYPE: ValueType.BYTE,\n }\n },\n },\n { # Light\n const.DISC_COMPONENT: \"light\",\n const.DISC_GENERIC_DEVICE_CLASS: [\n const_ozw.GENERIC_TYPE_SWITCH_MULTILEVEL,\n const_ozw.GENERIC_TYPE_SWITCH_REMOTE,\n ],\n const.DISC_SPECIFIC_DEVICE_CLASS: [\n const_ozw.SPECIFIC_TYPE_POWER_SWITCH_MULTILEVEL,\n const_ozw.SPECIFIC_TYPE_SCENE_SWITCH_MULTILEVEL,\n const_ozw.SPECIFIC_TYPE_NOT_USED,\n ],\n const.DISC_VALUES: {\n const.DISC_PRIMARY: {\n const.DISC_COMMAND_CLASS: [CommandClass.SWITCH_MULTILEVEL],\n const.DISC_INDEX: [ValueIndex.SWITCH_MULTILEVEL_LEVEL],\n const.DISC_TYPE: ValueType.BYTE,\n },\n \"dimming_duration\": {\n const.DISC_COMMAND_CLASS: [CommandClass.SWITCH_MULTILEVEL],\n const.DISC_INDEX: [ValueIndex.SWITCH_MULTILEVEL_DURATION],\n const.DISC_OPTIONAL: True,\n },\n \"color\": {\n const.DISC_COMMAND_CLASS: [CommandClass.SWITCH_COLOR],\n const.DISC_INDEX: [ValueIndex.SWITCH_COLOR_COLOR],\n const.DISC_OPTIONAL: True,\n },\n \"color_channels\": {\n const.DISC_COMMAND_CLASS: [CommandClass.SWITCH_COLOR],\n const.DISC_INDEX: [ValueIndex.SWITCH_COLOR_CHANNELS],\n const.DISC_OPTIONAL: True,\n },\n },\n },\n { # Lock\n const.DISC_COMPONENT: \"lock\",\n const.DISC_GENERIC_DEVICE_CLASS: [const_ozw.GENERIC_TYPE_ENTRY_CONTROL],\n const.DISC_SPECIFIC_DEVICE_CLASS: [\n const_ozw.SPECIFIC_TYPE_DOOR_LOCK,\n const_ozw.SPECIFIC_TYPE_ADVANCED_DOOR_LOCK,\n const_ozw.SPECIFIC_TYPE_SECURE_KEYPAD_DOOR_LOCK,\n const_ozw.SPECIFIC_TYPE_SECURE_LOCKBOX,\n ],\n const.DISC_VALUES: {\n const.DISC_PRIMARY: {\n const.DISC_COMMAND_CLASS: [CommandClass.DOOR_LOCK],\n const.DISC_INDEX: [ValueIndex.DOOR_LOCK_LOCK],\n },\n \"access_control\": {\n const.DISC_COMMAND_CLASS: [CommandClass.ALARM],\n const.DISC_INDEX: [ValueIndex.ALARM_ACCESS_CONTROL],\n const.DISC_OPTIONAL: True,\n },\n \"alarm_type\": {\n const.DISC_COMMAND_CLASS: [CommandClass.ALARM],\n const.DISC_INDEX: [ValueIndex.ALARM_TYPE],\n const.DISC_OPTIONAL: True,\n },\n \"alarm_level\": {\n const.DISC_COMMAND_CLASS: [CommandClass.ALARM],\n const.DISC_INDEX: [ValueIndex.ALARM_LEVEL],\n const.DISC_OPTIONAL: True,\n },\n \"v2btze_advanced\": {\n const.DISC_COMMAND_CLASS: [CommandClass.CONFIGURATION],\n const.DISC_INDEX: [12],\n const.DISC_OPTIONAL: True,\n },\n },\n },\n { # All other text/numeric sensors\n const.DISC_COMPONENT: \"sensor\",\n const.DISC_VALUES: {\n const.DISC_PRIMARY: {\n const.DISC_COMMAND_CLASS: [\n CommandClass.SENSOR_MULTILEVEL,\n CommandClass.METER,\n CommandClass.ALARM,\n CommandClass.SENSOR_ALARM,\n CommandClass.INDICATOR,\n CommandClass.BATTERY,\n CommandClass.NOTIFICATION,\n CommandClass.BASIC,\n ],\n const.DISC_TYPE: [\n ValueType.DECIMAL,\n ValueType.INT,\n ValueType.STRING,\n ValueType.BYTE,\n ValueType.LIST,\n ],\n }\n },\n },\n { # Switch platform\n const.DISC_COMPONENT: \"switch\",\n const.DISC_GENERIC_DEVICE_CLASS: [\n const_ozw.GENERIC_TYPE_METER,\n const_ozw.GENERIC_TYPE_SENSOR_ALARM,\n const_ozw.GENERIC_TYPE_SENSOR_BINARY,\n const_ozw.GENERIC_TYPE_SWITCH_BINARY,\n const_ozw.GENERIC_TYPE_ENTRY_CONTROL,\n const_ozw.GENERIC_TYPE_SENSOR_MULTILEVEL,\n const_ozw.GENERIC_TYPE_SWITCH_MULTILEVEL,\n const_ozw.GENERIC_TYPE_GENERIC_CONTROLLER,\n const_ozw.GENERIC_TYPE_SWITCH_REMOTE,\n const_ozw.GENERIC_TYPE_REPEATER_SLAVE,\n const_ozw.GENERIC_TYPE_THERMOSTAT,\n const_ozw.GENERIC_TYPE_WALL_CONTROLLER,\n ],\n const.DISC_VALUES: {\n const.DISC_PRIMARY: {\n const.DISC_COMMAND_CLASS: [CommandClass.SWITCH_BINARY],\n const.DISC_TYPE: ValueType.BOOL,\n const.DISC_GENRE: ValueGenre.USER,\n }\n },\n },\n]\n\n\ndef check_node_schema(node, schema):\n \"\"\"Check if node matches the passed node schema.\"\"\"\n if const.DISC_NODE_ID in schema and node.node_id not in schema[const.DISC_NODE_ID]:\n return False\n if (\n const.DISC_GENERIC_DEVICE_CLASS in schema\n and node.node_generic\n not in ensure_list(schema[const.DISC_GENERIC_DEVICE_CLASS])\n ):\n return False\n if (\n const.DISC_SPECIFIC_DEVICE_CLASS in schema\n and node.node_specific\n not in ensure_list(schema[const.DISC_SPECIFIC_DEVICE_CLASS])\n ):\n return False\n return True\n\n\ndef check_value_schema(value, schema):\n \"\"\"Check if the value matches the passed value schema.\"\"\"\n if (\n const.DISC_COMMAND_CLASS in schema\n and value.parent.command_class_id not in schema[const.DISC_COMMAND_CLASS]\n ):\n return False\n if const.DISC_TYPE in schema and value.type not in ensure_list(\n schema[const.DISC_TYPE]\n ):\n return False\n if const.DISC_GENRE in schema and value.genre not in ensure_list(\n schema[const.DISC_GENRE]\n ):\n return False\n if const.DISC_INDEX in schema and value.index not in ensure_list(\n schema[const.DISC_INDEX]\n ):\n return False\n if const.DISC_INSTANCE in schema and value.instance not in ensure_list(\n schema[const.DISC_INSTANCE]\n ):\n return False\n if const.DISC_SCHEMAS in schema:\n found = False\n for schema_item in schema[const.DISC_SCHEMAS]:\n found = found or check_value_schema(value, schema_item)\n if not found:\n return False\n\n return True\n\n\ndef ensure_list(value):\n \"\"\"Convert a value to a list if needed.\"\"\"\n if isinstance(value, list):\n return value\n return [value]\n" }, { "alpha_fraction": 0.6384583115577698, "alphanum_fraction": 0.6480938196182251, "avg_line_length": 28.109756469726562, "blob_id": "6cf92f09ecf7bc52c231df306615007f9343d939", "content_id": "5976d326f040a1501b15fff3f8dd2d460502102f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2387, "license_type": "no_license", "max_line_length": 81, "num_lines": 82, "path": "/custom_components/zwave_mqtt/fan.py", "repo_name": "cgarwood/homeassistant-zwave_mqtt", "src_encoding": "UTF-8", "text": "\"\"\"Support for Z-Wave fans.\"\"\"\nimport math\n\nfrom homeassistant.components.fan import (\n SPEED_HIGH,\n SPEED_LOW,\n SPEED_MEDIUM,\n SPEED_OFF,\n SUPPORT_SET_SPEED,\n FanEntity,\n)\nfrom homeassistant.core import callback\nfrom homeassistant.helpers.dispatcher import async_dispatcher_connect\n\nfrom .const import DATA_UNSUBSCRIBE, DOMAIN\nfrom .entity import ZWaveDeviceEntity\n\nSPEED_LIST = [SPEED_OFF, SPEED_LOW, SPEED_MEDIUM, SPEED_HIGH]\n\nSUPPORTED_FEATURES = SUPPORT_SET_SPEED\n\n# Value will first be divided to an integer\nVALUE_TO_SPEED = {0: SPEED_OFF, 1: SPEED_LOW, 2: SPEED_MEDIUM, 3: SPEED_HIGH}\n\nSPEED_TO_VALUE = {SPEED_OFF: 0, SPEED_LOW: 1, SPEED_MEDIUM: 50, SPEED_HIGH: 99}\n\n\nasync def async_setup_entry(hass, config_entry, async_add_entities):\n \"\"\"Set up Z-Wave Fan from Config Entry.\"\"\"\n\n @callback\n def async_add_fan(values):\n \"\"\"Add Z-Wave Fan.\"\"\"\n fan = ZwaveFan(values)\n async_add_entities([fan])\n\n hass.data[DOMAIN][config_entry.entry_id][DATA_UNSUBSCRIBE].append(\n async_dispatcher_connect(hass, \"zwave_new_fan\", async_add_fan)\n )\n\n await hass.data[DOMAIN][config_entry.entry_id][\"mark_platform_loaded\"](\"fan\")\n\n\nclass ZwaveFan(ZWaveDeviceEntity, FanEntity):\n \"\"\"Representation of a Z-Wave fan.\"\"\"\n\n async def async_set_speed(self, speed):\n \"\"\"Set the speed of the fan.\"\"\"\n self.values.primary.send_value(SPEED_TO_VALUE[speed])\n\n async def async_turn_on(self, speed=None, **kwargs):\n \"\"\"Turn the device on.\"\"\"\n if speed is None:\n # Value 255 tells device to return to previous value\n self.values.primary.send_value(255)\n else:\n await self.async_set_speed(speed)\n\n async def async_turn_off(self, **kwargs):\n \"\"\"Turn the device off.\"\"\"\n self.values.primary.send_value(0)\n\n @property\n def is_on(self):\n \"\"\"Return true if device is on (speed above 0).\"\"\"\n return self.values.primary.value > 0\n\n @property\n def speed(self):\n \"\"\"Return the current speed.\"\"\"\n value = math.ceil(self.values.primary.value * 3 / 100)\n return VALUE_TO_SPEED[value]\n\n @property\n def speed_list(self):\n \"\"\"Get the list of available speeds.\"\"\"\n return SPEED_LIST\n\n @property\n def supported_features(self):\n \"\"\"Flag supported features.\"\"\"\n return SUPPORTED_FEATURES\n" }, { "alpha_fraction": 0.7832996249198914, "alphanum_fraction": 0.7887893915176392, "avg_line_length": 66.86274719238281, "blob_id": "204a240f98716ced90791a0e1b6530b08dc8a0d8", "content_id": "ec6e6de593c05f050b3f3c5615b9ffee1c756993", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3461, "license_type": "no_license", "max_line_length": 297, "num_lines": 51, "path": "/README.md", "repo_name": "cgarwood/homeassistant-zwave_mqtt", "src_encoding": "UTF-8", "text": "# Notice - Repository Archived\n**This component has been merged into the Home Assistant Core as the OpenZWave/ozw component. Please submit bug reports to the [Home Assistant Core repository](https://github.com/home-assistant/core).**\n\n\n\n# Home Assistant Z-Wave over MQTT Integration (Pre-Release)\n[![hacs_badge](https://img.shields.io/badge/HACS-Custom-orange.svg)](https://github.com/custom-components/hacs)\n\nThis integration allows you to utilize OpenZWave's qt-openzwave to control a Z-Wave network over MQTT. It is currently available as a custom component through HACS and will be submitted as an official Home Assistant component once it has matured a bit.\n\nSome info about differences between previous current Z-Wave implementation, zwave2mqtt etc. can be found here:\nhttps://community.home-assistant.io/t/update-on-the-z-wave-integration-home-assistant-dev-docs/169045/41\n\n\n**This is an early beta/pre-release and there are still significant limitations**\n\n\n## Requirements\n\n- MQTT server and the MQTT integration set up in Home Assistant\n- QT-OpenZwave daemon (https://github.com/OpenZWave/qt-openzwave)\n- Supported Z-wave dongle compatible with OpenZWave 1.6 ([list](https://www.home-assistant.io/docs/z-wave/controllers/#supported-z-wave-usb-sticks--hardware-modules))\n\n## Quick start\n1. Remove the current/previous Z-Wave integration from your setup (if present).\n --> If you had the current/previous Z-Wave integration runninhg, please restart Home Assistant after you remove it.\n2. Install the Mosquittto broker addon and configure MQTT in HomeAssistant integrations page.\n3. Make sure you have HACS set-up (https://github.com/custom-components/hacs).\n4. Install `Z-Wave over MQTT (Pre-Release)` from HACS Integrations Page.\n5. Install custom Home Assistant add-on repository to get the OpenZWave daemon: https://github.com/marcelveldt/hassio-addons-repo\n6. Install the OpenZWave Daemon from add-on repository, configure and start.\n7. Carefully check the logs of the daemon if it started successfully!\n8. Go to the HomeAssistant integrations page, add Zwave MQTT integration.\n\n## Features and Limitations\n- Currently already supports binary_sensor, cover, fan, sensor, and switch platforms\n- Scenes support for both Central scenes and node/network scenes:\n Will fire HomeAssistant event zwave_mqtt.scene_activated.\n- Light support is currently limited to dimmers only, RGB bulbs are not yet implemented.\n- Other platforms will be added soon!\n- There is no migration path from the normal/current Z-Wave integration, you will have to reconfigure Home Assistant entities. Your Z-Wave mesh is stored on your stick and will stay intact though, no need to re-add devices.\n\n## Contributing\nContributions are welcome! If you'd like to contribute, feel free to pick up anything on the current [GitHub issues](https://github.com/cgarwood/homeassistant-zwave_mqtt/issues) list!\n\n### Code Formatting\nWe try to follow the core Home Assistant style guidelines. Code should be formatted with `black` and imports sorted with `isort`. We have pre-commit hooks to help automate this process. Run `pip install pre-commit` and then `pre-commit install` to install the pre-commit hooks for code formatting.\n\n## Upstream Resources Used\n- [python-openzwave-mqtt](https://github.com/cgarwood/python-openzwave-mqtt) - Converts qt-openzwave MQTT messages to Python objects and events\n- [qt-openzwave](https://github.com/OpenZWave/qt-openzwave) - OpenZWave MQTT Daemon\n" }, { "alpha_fraction": 0.6541996002197266, "alphanum_fraction": 0.671938419342041, "avg_line_length": 32.42142868041992, "blob_id": "7ccc2ac7207f63c8bc743c60b82d66837b70f057", "content_id": "021f52f3c85ab9326e04a9eab08061ee40a624fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4679, "license_type": "no_license", "max_line_length": 121, "num_lines": 140, "path": "/custom_components/zwave_mqtt/cover.py", "repo_name": "cgarwood/homeassistant-zwave_mqtt", "src_encoding": "UTF-8", "text": "\"\"\"Support for Z-Wave cover.\"\"\"\nimport logging\n\nfrom openzwavemqtt.const import CommandClass\n\nfrom homeassistant.components.cover import (\n ATTR_POSITION,\n ATTR_TILT_POSITION,\n SUPPORT_CLOSE,\n SUPPORT_CLOSE_TILT,\n SUPPORT_OPEN,\n SUPPORT_OPEN_TILT,\n SUPPORT_SET_POSITION,\n SUPPORT_SET_TILT_POSITION,\n CoverDevice,\n)\nfrom homeassistant.core import callback\nfrom homeassistant.helpers.dispatcher import async_dispatcher_connect\n\nfrom .const import DATA_UNSUBSCRIBE, DOMAIN\nfrom .entity import ZWaveDeviceEntity\n\n_LOGGER = logging.getLogger(__name__)\n\nSUPPORTED_FEATURES_POSITION = SUPPORT_OPEN | SUPPORT_CLOSE | SUPPORT_SET_POSITION\nSUPPORTED_FEATURES_TILT = (\n SUPPORT_OPEN_TILT | SUPPORT_CLOSE_TILT | SUPPORT_SET_TILT_POSITION\n)\n\nMANUFACTURER_ID_FIBARO = \"0x010f\"\nPRODUCT_TYPE_FIBARO_FGRM222 = \"0x0302\"\n\n\nasync def async_setup_entry(hass, config_entry, async_add_entities):\n \"\"\"Set up Z-Wave Cover from Config Entry.\"\"\"\n\n @callback\n def async_add_cover(values):\n \"\"\"Add Z-Wave Cover.\"\"\"\n # Specific Cover Types\n if values.primary.command_class != CommandClass.SWITCH_MULTILEVEL:\n _LOGGER.warning(\"Cover not implemented for values %s\", values.primary)\n return\n\n if (\n values.primary.node.node_manufacturer_id == MANUFACTURER_ID_FIBARO\n and values.primary.node.node_product_type == PRODUCT_TYPE_FIBARO_FGRM222\n ):\n cover = FibaroFGRM222Cover(values)\n else:\n cover = ZWaveCover(values)\n\n async_add_entities([cover])\n\n hass.data[DOMAIN][config_entry.entry_id][DATA_UNSUBSCRIBE].append(\n async_dispatcher_connect(hass, \"zwave_new_cover\", async_add_cover)\n )\n\n await hass.data[DOMAIN][config_entry.entry_id][\"mark_platform_loaded\"](\"cover\")\n\n\nclass ZWaveCover(ZWaveDeviceEntity, CoverDevice):\n \"\"\"Representation of a Z-Wave cover.\"\"\"\n\n @property\n def supported_features(self):\n \"\"\"Flag supported features.\"\"\"\n return SUPPORTED_FEATURES_POSITION\n\n @property\n def is_closed(self):\n \"\"\"Return true if cover is closed.\"\"\"\n return self.values.primary.value < 5\n\n @property\n def current_cover_position(self):\n \"\"\"Return the current position of cover where 0 means closed and 100 is fully open.\"\"\"\n return self.values.primary.value\n\n async def async_set_cover_position(self, **kwargs):\n \"\"\"Move the cover to a specific position.\"\"\"\n self.values.primary.send_value(kwargs[ATTR_POSITION])\n\n async def async_open_cover(self, **kwargs):\n \"\"\"Open the cover.\"\"\"\n self.values.primary.send_value(99)\n\n async def async_close_cover(self, **kwargs):\n \"\"\"Close cover.\"\"\"\n self.values.primary.send_value(0)\n\n\nclass FibaroFGRM222Cover(ZWaveDeviceEntity, CoverDevice):\n \"\"\"Representation of a Fibaro FGRM-222 cover.\"\"\"\n\n @property\n def supported_features(self):\n \"\"\"Flag supported features.\"\"\"\n return SUPPORTED_FEATURES_POSITION | SUPPORTED_FEATURES_TILT\n\n @property\n def is_closed(self):\n \"\"\"Return true if cover is closed.\"\"\"\n return self.values.fgrm222_slat_position.value < 5\n\n @property\n def current_cover_position(self):\n \"\"\"Return the current position of cover where 0 means closed and 100 is fully open.\"\"\"\n return self.values.fgrm222_slat_position.value\n\n @property\n def current_cover_tilt_position(self):\n \"\"\"Return the current tilt position of the cover where 0 means closed/no tilt and 100 means open/maximum tilt.\"\"\"\n return self.values.fgrm222_tilt_position.value\n\n async def async_open_cover(self, **kwargs):\n \"\"\"Open the cover.\"\"\"\n self.values.fgrm222_slat_position.send_value(99)\n self.values.fgrm222_tilt_position.send_value(99)\n\n async def async_close_cover(self, **kwargs):\n \"\"\"Close cover.\"\"\"\n self.values.fgrm222_slat_position.send_value(0)\n self.values.fgrm222_tilt_position.send_value(0)\n\n async def async_set_cover_position(self, **kwargs):\n \"\"\"Move the cover to a specific position.\"\"\"\n self.values.fgrm222_slat_position.send_value(kwargs[ATTR_POSITION])\n\n async def async_set_cover_tilt_position(self, **kwargs):\n \"\"\"Move the cover tilt to a specific position.\"\"\"\n self.values.fgrm222_tilt_position.send_value(kwargs[ATTR_TILT_POSITION])\n\n async def async_open_cover_tilt(self, **kwargs):\n \"\"\"Open the cover tilt.\"\"\"\n self.values.fgrm222_tilt_position.send_value(99)\n\n async def async_close_cover_tilt(self, **kwargs):\n \"\"\"Close the cover tilt.\"\"\"\n self.values.fgrm222_tilt_position.send_value(0)\n" }, { "alpha_fraction": 0.7478344440460205, "alphanum_fraction": 0.7478344440460205, "avg_line_length": 42.29166793823242, "blob_id": "111f335bcdbd2202498029a9c083dd71ea2961e5", "content_id": "c156fea6696cd162d4020d85169e0106a3f55cb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1039, "license_type": "no_license", "max_line_length": 87, "num_lines": 24, "path": "/tests/test_init.py", "repo_name": "cgarwood/homeassistant-zwave_mqtt", "src_encoding": "UTF-8", "text": "\"\"\"Test integration initialization.\"\"\"\n\nfrom custom_components.zwave_mqtt import DOMAIN, PLATFORMS, const\n\nfrom tests.common import setup_zwave\n\n\nasync def test_init_entry(hass):\n \"\"\"Test setting up config entry.\"\"\"\n await setup_zwave(hass, \"generic_network_dump.csv\")\n\n # Verify integration + platform loaded.\n assert \"zwave_mqtt\" in hass.config.components\n for platform in PLATFORMS:\n assert platform in hass.config.components, platform\n assert f\"{platform}.{DOMAIN}\" in hass.config.components, f\"{platform}.{DOMAIN}\"\n\n # Verify services registered\n assert hass.services.has_service(DOMAIN, const.SERVICE_ADD_NODE)\n assert hass.services.has_service(DOMAIN, const.SERVICE_REMOVE_NODE)\n assert hass.services.has_service(DOMAIN, const.SERVICE_REMOVE_FAILED_NODE)\n assert hass.services.has_service(DOMAIN, const.SERVICE_REPLACE_FAILED_NODE)\n assert hass.services.has_service(DOMAIN, const.SERVICE_CANCEL_COMMAND)\n assert hass.services.has_service(DOMAIN, const.SERVICE_SET_CONFIG_PARAMETER)\n" }, { "alpha_fraction": 0.7183098793029785, "alphanum_fraction": 0.7295774817466736, "avg_line_length": 28.58333396911621, "blob_id": "819915b66d486592d6a78eef906ee56620a02000", "content_id": "05237c24e89849a138edbbe24d238ba335c1383f", "detected_licenses": [], "is_generated": false, "is_vendor": true, "language": "Markdown", "length_bytes": 355, "license_type": "no_license", "max_line_length": 62, "num_lines": 12, "path": "/.github/ISSUE_TEMPLATE.md", "repo_name": "cgarwood/homeassistant-zwave_mqtt", "src_encoding": "UTF-8", "text": "- Home Assistant version:\n- ozwdaemon version or add-on version:\n- homeassistant-zwave_mqtt version:\n\n<!--\n Describe your problem here.\n \n If you run Home Assistant 0.105+, please attach a dump\n of your MQTT instance using the `mqtt.dump` service.\n You can attach it to this message by clicking \"attach files\"\n at the bottom of this text field.\n-->\n" }, { "alpha_fraction": 0.5604729056358337, "alphanum_fraction": 0.5615913271903992, "avg_line_length": 35.60234069824219, "blob_id": "cad2b670714ae1c069b5d255869a070169ab7ddd", "content_id": "1810a85b352537a18c242eca4d87573a955d3998", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6259, "license_type": "no_license", "max_line_length": 92, "num_lines": 171, "path": "/custom_components/zwave_mqtt/services.py", "repo_name": "cgarwood/homeassistant-zwave_mqtt", "src_encoding": "UTF-8", "text": "\"\"\"Methods and classes related to executing Z-Wave commands and publishing these to hass.\"\"\"\nimport logging\n\nfrom openzwavemqtt.const import CommandClass, ValueType\nimport voluptuous as vol\n\nfrom homeassistant.core import callback\nimport homeassistant.helpers.config_validation as cv\n\nfrom . import const\n\n_LOGGER = logging.getLogger(__name__)\n\n\nclass ZWaveServices:\n \"\"\"Class that holds our services ( Zwave Commands) that should be published to hass.\"\"\"\n\n def __init__(self, hass, manager, data_nodes):\n \"\"\"Initialize with both hass and ozwmanager objects.\"\"\"\n self._hass = hass\n self._manager = manager\n self._data_nodes = data_nodes\n\n @callback\n def register(self):\n \"\"\"Register all our services.\"\"\"\n self._hass.services.async_register(\n const.DOMAIN,\n const.SERVICE_ADD_NODE,\n self.add_node,\n schema=vol.Schema(\n {\n vol.Optional(const.ATTR_INSTANCE_ID, default=1): vol.Coerce(int),\n vol.Optional(const.ATTR_SECURE, default=False): vol.Coerce(bool),\n }\n ),\n )\n self._hass.services.async_register(\n const.DOMAIN,\n const.SERVICE_REMOVE_NODE,\n self.remove_node,\n schema=vol.Schema(\n {vol.Optional(const.ATTR_INSTANCE_ID, default=1): vol.Coerce(int)}\n ),\n )\n self._hass.services.async_register(\n const.DOMAIN,\n const.SERVICE_REMOVE_FAILED_NODE,\n self.remove_failed_node,\n schema=vol.Schema(\n {\n vol.Required(const.ATTR_NODE_ID): vol.Coerce(int),\n vol.Optional(const.ATTR_INSTANCE_ID, default=1): vol.Coerce(int),\n }\n ),\n )\n self._hass.services.async_register(\n const.DOMAIN,\n const.SERVICE_REPLACE_FAILED_NODE,\n self.replace_failed_node,\n schema=vol.Schema(\n {\n vol.Required(const.ATTR_NODE_ID): vol.Coerce(int),\n vol.Optional(const.ATTR_INSTANCE_ID, default=1): vol.Coerce(int),\n }\n ),\n )\n self._hass.services.async_register(\n const.DOMAIN,\n const.SERVICE_CANCEL_COMMAND,\n self.cancel_command,\n schema=vol.Schema(\n {vol.Optional(const.ATTR_INSTANCE_ID, default=1): vol.Coerce(int)}\n ),\n )\n self._hass.services.async_register(\n const.DOMAIN,\n const.SERVICE_SET_CONFIG_PARAMETER,\n self.set_config_parameter,\n schema=vol.Schema(\n {\n vol.Required(const.ATTR_NODE_ID): vol.Coerce(int),\n vol.Required(const.ATTR_CONFIG_PARAMETER): vol.Coerce(int),\n vol.Required(const.ATTR_CONFIG_VALUE): vol.Any(\n vol.Coerce(int), cv.string\n ),\n vol.Optional(const.ATTR_CONFIG_SIZE, default=2): vol.Coerce(int),\n vol.Optional(const.ATTR_INSTANCE_ID, default=1): vol.Coerce(int),\n }\n ),\n )\n\n @callback\n def add_node(self, service):\n \"\"\"Enter inclusion mode on the controller.\"\"\"\n instance_id = service.data[const.ATTR_INSTANCE_ID]\n secure = service.data[const.ATTR_SECURE]\n instance = self._manager.get_instance(instance_id)\n instance.add_node(secure)\n\n @callback\n def remove_node(self, service):\n \"\"\"Enter exclusion mode on the controller.\"\"\"\n instance_id = service.data[const.ATTR_INSTANCE_ID]\n instance = self._manager.get_instance(instance_id)\n instance.remove_node()\n\n @callback\n def remove_failed_node(self, service):\n \"\"\"Remove a failed node from the controller.\"\"\"\n instance_id = service.data[const.ATTR_INSTANCE_ID]\n node_id = service.data[const.ATTR_NODE_ID]\n instance = self._manager.get_instance(instance_id)\n instance.remove_failed_node(node_id)\n\n @callback\n def replace_failed_node(self, service):\n \"\"\"Replace a failed node from the controller with a new device.\"\"\"\n instance_id = service.data[const.ATTR_INSTANCE_ID]\n node_id = service.data[const.ATTR_NODE_ID]\n instance = self._manager.get_instance(instance_id)\n instance.replace_failed_node(node_id)\n\n @callback\n def cancel_command(self, service):\n \"\"\"Cancel in Controller Commands that are in progress.\"\"\"\n instance_id = service.data[const.ATTR_INSTANCE_ID]\n instance = self._manager.get_instance(instance_id)\n instance.cancel_controller_command()\n\n @callback\n def set_config_parameter(self, service):\n \"\"\"Set a config parameter to a node.\"\"\"\n node_id = service.data[const.ATTR_NODE_ID]\n node = self._data_nodes[node_id]\n param = service.data.get(const.ATTR_CONFIG_PARAMETER)\n selection = service.data.get(const.ATTR_CONFIG_VALUE)\n # enumerate values untill we find the param within configuration items\n for value in node.values():\n if value.index != param:\n continue\n if value.command_class != CommandClass.CONFIGURATION:\n continue\n _LOGGER.info(\n \"Setting config parameter %s on Node %s with selection %s\",\n param,\n node_id,\n selection,\n )\n # Bool value\n if value.type == ValueType.BOOL:\n return value.send_value(int(selection == \"True\"))\n # List value\n if value.type == ValueType.LIST:\n return value.send_value(str(selection))\n # Button\n if value.type == ValueType.BUTTON:\n value.send_value(True)\n value.send_value(False)\n return\n # Byte value\n value.send_value(int(selection))\n return\n\n # Parameter-index not found!\n _LOGGER.warning(\n \"Unknown config parameter %s on Node %s with selection %s\",\n param,\n node_id,\n selection,\n )\n" }, { "alpha_fraction": 0.6090256571769714, "alphanum_fraction": 0.6141256093978882, "avg_line_length": 33.13562774658203, "blob_id": "12982ca7e8051df088cbff764c80bc83398934a4", "content_id": "74dcfa03908103b4d04ac357fe92e56b53a3f33c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16863, "license_type": "no_license", "max_line_length": 106, "num_lines": 494, "path": "/custom_components/zwave_mqtt/climate.py", "repo_name": "cgarwood/homeassistant-zwave_mqtt", "src_encoding": "UTF-8", "text": "\"\"\"Support for Z-Wave climate devices.\"\"\"\nfrom enum import IntEnum\nfrom typing import Optional, Tuple\n\nfrom openzwavemqtt.const import CommandClass\n\nfrom homeassistant.components.climate import ClimateDevice\nfrom homeassistant.components.climate.const import (\n ATTR_TARGET_TEMP_HIGH,\n ATTR_TARGET_TEMP_LOW,\n CURRENT_HVAC_COOL,\n CURRENT_HVAC_FAN,\n CURRENT_HVAC_HEAT,\n CURRENT_HVAC_IDLE,\n CURRENT_HVAC_OFF,\n HVAC_MODE_AUTO,\n HVAC_MODE_COOL,\n HVAC_MODE_DRY,\n HVAC_MODE_FAN_ONLY,\n HVAC_MODE_HEAT,\n HVAC_MODE_HEAT_COOL,\n HVAC_MODE_OFF,\n PRESET_AWAY,\n PRESET_NONE,\n SUPPORT_FAN_MODE,\n SUPPORT_PRESET_MODE,\n SUPPORT_TARGET_TEMPERATURE,\n SUPPORT_TARGET_TEMPERATURE_RANGE,\n)\nfrom homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT\nfrom homeassistant.core import callback\nfrom homeassistant.helpers.dispatcher import async_dispatcher_connect\n\nfrom .const import DATA_UNSUBSCRIBE, DOMAIN\nfrom .entity import ZWaveDeviceEntity\n\nVALUE_LIST = \"List\"\nVALUE_ID = \"Value\"\nVALUE_LABEL = \"Label\"\nVALUE_SELECTED = \"Selected_id\"\n\nATTR_FAN_ACTION = \"fan_action\"\n\n\nclass ThermostatMode(IntEnum):\n \"\"\"Enum with all (known/used) Z-Wave ThermostatModes.\"\"\"\n\n # https://github.com/OpenZWave/open-zwave/blob/master/cpp/src/command_classes/ThermostatMode.cpp\n OFF = 0\n HEAT = 1\n COOl = 2\n AUTO = 3\n AUXILIARY = 4\n RESUME_ON = 5\n FAN = 6\n FURNANCE = 7\n DRY = 8\n MOIST = 9\n AUTO_CHANGE_OVER = 10\n HEATING_ECON = 11\n COOLING_ECON = 12\n AWAY = 13\n FULL_POWER = 14\n\n\nMODE_SETPOINT_MAPPINGS = {\n ThermostatMode.OFF: (),\n ThermostatMode.HEAT: (\"setpoint_heating\",),\n ThermostatMode.COOl: (\"setpoint_cooling\",),\n ThermostatMode.AUTO: (\"setpoint_heating\", \"setpoint_cooling\"),\n ThermostatMode.AUXILIARY: (\"setpoint_heating\",),\n ThermostatMode.FURNANCE: (\"setpoint_furnace\",),\n ThermostatMode.DRY: (\"setpoint_dry_air\",),\n ThermostatMode.MOIST: (\"setpoint_moist_air\",),\n ThermostatMode.AUTO_CHANGE_OVER: (\"setpoint_auto_changeover\",),\n ThermostatMode.HEATING_ECON: (\"setpoint_eco_heating\",),\n ThermostatMode.COOLING_ECON: (\"setpoint_eco_cooling\",),\n ThermostatMode.AWAY: (\"setpoint_away_heating\", \"setpoint_away_cooling\"),\n ThermostatMode.FULL_POWER: (\"setpoint_full_power\",),\n}\n\n\n# strings, OZW and/or qt-ozw does not send numeric values\n# https://github.com/OpenZWave/open-zwave/blob/master/cpp/src/command_classes/ThermostatOperatingState.cpp\nHVAC_CURRENT_MAPPINGS = {\n \"idle\": CURRENT_HVAC_IDLE,\n \"heat\": CURRENT_HVAC_HEAT,\n \"pending heat\": CURRENT_HVAC_IDLE,\n \"heating\": CURRENT_HVAC_HEAT,\n \"cool\": CURRENT_HVAC_COOL,\n \"pending cool\": CURRENT_HVAC_IDLE,\n \"cooling\": CURRENT_HVAC_COOL,\n \"fan only\": CURRENT_HVAC_FAN,\n \"vent / economiser\": CURRENT_HVAC_FAN,\n \"off\": CURRENT_HVAC_OFF,\n}\n\nDEFAULT_HVAC_MODES = [\n HVAC_MODE_HEAT_COOL,\n HVAC_MODE_HEAT,\n HVAC_MODE_COOL,\n HVAC_MODE_FAN_ONLY,\n HVAC_MODE_DRY,\n HVAC_MODE_OFF,\n HVAC_MODE_AUTO,\n]\n\n# Map Z-Wave HVAC Mode to Home Assistant value\nZW_HVAC_MODE_MAPPINGS = {\n 0x00: HVAC_MODE_OFF,\n 0x01: HVAC_MODE_HEAT,\n 0x02: HVAC_MODE_COOL,\n 0x03: HVAC_MODE_AUTO,\n 0x04: HVAC_MODE_HEAT,\n 0x06: HVAC_MODE_FAN_ONLY,\n 0x07: HVAC_MODE_HEAT,\n 0x08: HVAC_MODE_DRY,\n 0x0A: HVAC_MODE_HEAT_COOL,\n 0x0B: HVAC_MODE_HEAT,\n 0x0C: HVAC_MODE_COOL,\n 0x0D: HVAC_MODE_HEAT_COOL,\n 0x0F: HVAC_MODE_HEAT_COOL,\n}\n\n# Map Home Assistant HVAC Mode to Z-Wave value\nHVAC_MODE_ZW_MAPPINGS = {\n HVAC_MODE_OFF: 0x00,\n HVAC_MODE_HEAT: 0x01,\n HVAC_MODE_COOL: 0x02,\n HVAC_MODE_AUTO: 0x03,\n HVAC_MODE_FAN_ONLY: 0x06,\n HVAC_MODE_DRY: 0x08,\n HVAC_MODE_HEAT_COOL: 0x0A,\n}\n\n\nasync def async_setup_entry(hass, config_entry, async_add_entities):\n \"\"\"Set up Z-Wave Climate from Config Entry.\"\"\"\n\n @callback\n def async_add_climate(values):\n \"\"\"Add Z-Wave Climate.\"\"\"\n climate = None\n if values.primary.command_class == CommandClass.THERMOSTAT_SETPOINT:\n climate = ZWaveClimateSingleSetpoint(values)\n elif values.primary.command_class == CommandClass.THERMOSTAT_MODE:\n climate = ZWaveClimateMultipleSetpoint(values)\n\n if climate is not None:\n async_add_entities([climate])\n\n hass.data[DOMAIN][config_entry.entry_id][DATA_UNSUBSCRIBE].append(\n async_dispatcher_connect(hass, \"zwave_new_climate\", async_add_climate)\n )\n await hass.data[DOMAIN][config_entry.entry_id][\"mark_platform_loaded\"](\"climate\")\n\n\nclass ZWaveClimateBase(ZWaveDeviceEntity, ClimateDevice):\n \"\"\"Representation of a Z-Wave Climate device.\"\"\"\n\n def __init__(self, values):\n \"\"\"Initialize the Z-Wave climate device.\"\"\"\n super().__init__(values)\n self._target_temperature = None\n self._target_temperature_range = (None, None)\n self._current_temperature = None\n self._hvac_action = None\n self._hvac_list = None\n self._zw_hvac_mode = None\n self._default_hvac_mode = None\n self._preset_list = None\n self._preset_mode = None\n self._current_fan_mode = None\n self._fan_modes = None\n self._fan_action = None\n self._unit = None\n self.update_properties()\n\n @callback\n def on_value_update(self):\n \"\"\"Update after value change.\"\"\"\n self.update_properties()\n\n def _mode(self) -> None:\n \"\"\"Return thermostat mode Z-Wave value.\"\"\"\n raise NotImplementedError()\n\n def _current_mode_setpoints(self) -> Tuple:\n \"\"\"Return a tuple of current setpoint Z-Wave value(s).\"\"\"\n raise NotImplementedError()\n\n def update_properties(self):\n \"\"\"Handle the data changes for node values.\"\"\"\n self._update_operation_mode()\n self._update_current_temp()\n self._update_fan_mode()\n self._update_target_temp()\n self._update_operating_state()\n self._update_fan_state()\n\n @property\n def supported_features(self):\n \"\"\"Return the list of supported features.\"\"\"\n support = SUPPORT_TARGET_TEMPERATURE\n if self._hvac_list and HVAC_MODE_HEAT_COOL in self._hvac_list:\n support |= SUPPORT_TARGET_TEMPERATURE_RANGE\n if self._preset_list and PRESET_AWAY in self._preset_list:\n support |= SUPPORT_TARGET_TEMPERATURE_RANGE\n if len(self._current_mode_setpoints()) > 1:\n support |= SUPPORT_TARGET_TEMPERATURE_RANGE\n if self.values.fan_mode:\n support |= SUPPORT_FAN_MODE\n if self._preset_list:\n support |= SUPPORT_PRESET_MODE\n return support\n\n def _update_operation_mode(self):\n \"\"\"Update hvac and preset modes.\"\"\"\n if not self._mode():\n return\n self._hvac_list = []\n self._preset_list = []\n self._hvac_value_label_mapping = {}\n self._hvac_label_value_mapping = {}\n values_list = self._mode().value[VALUE_LIST]\n mode_values = [value[VALUE_ID] for value in values_list]\n for value in mode_values:\n ha_mode = ZW_HVAC_MODE_MAPPINGS.get(value)\n if ha_mode is not None and ha_mode not in self._hvac_list:\n self._hvac_list.append(ha_mode)\n else:\n self._preset_list.append(value)\n label = next(\n (\n entry[VALUE_LABEL]\n for entry in values_list\n if value == entry[VALUE_ID]\n )\n )\n self._hvac_value_label_mapping[value] = label\n self._hvac_label_value_mapping[label.lower()] = value\n\n for mode in DEFAULT_HVAC_MODES:\n if mode in self._hvac_list:\n self._default_hvac_mode = mode\n break\n\n current_mode_value = self._mode().value[VALUE_SELECTED]\n if current_mode_value in ZW_HVAC_MODE_MAPPINGS:\n self._zw_hvac_mode = current_mode_value\n self._preset_mode = PRESET_NONE\n else:\n current_mode_label = self._hvac_value_label_mapping[current_mode_value]\n if (\n \"heat\" in current_mode_label.lower()\n and HVAC_MODE_HEAT in self._hvac_list\n ):\n self._zw_hvac_mode = HVAC_MODE_ZW_MAPPINGS[HVAC_MODE_HEAT]\n elif (\n \"cool\" in current_mode_label.lower()\n and HVAC_MODE_COOL in self._hvac_list\n ):\n self._zw_hvac_mode = HVAC_MODE_ZW_MAPPINGS[HVAC_MODE_COOL]\n else:\n self._zw_hvac_mode = self._default_hvac_mode\n self._preset_mode = current_mode_value\n\n def _update_current_temp(self):\n \"\"\"Update current temperature.\"\"\"\n if not self.values.temperature:\n return\n self._current_temperature = self.values.temperature.value\n device_unit = self.values.temperature.units\n if device_unit is not None:\n self._unit = device_unit\n\n def _update_fan_mode(self):\n \"\"\"Update fan mode.\"\"\"\n if not self.values.fan_mode:\n return\n self._fan_value_label_mapping = {}\n self._fan_label_value_mapping = {}\n self._fan_modes = []\n for entry in self.values.fan_mode.value[VALUE_LIST]:\n self._fan_value_label_mapping[entry[VALUE_ID]] = entry[VALUE_LABEL]\n self._fan_label_value_mapping[entry[VALUE_LABEL]] = entry[VALUE_ID]\n self._fan_modes.append(entry[VALUE_ID])\n self._current_fan_mode = self.values.fan_mode.value[VALUE_SELECTED]\n\n def _update_target_temp(self):\n \"\"\"Update target temperature.\"\"\"\n current_setpoints = self._current_mode_setpoints()\n self._target_temperature = None\n self._target_temperature_range = (None, None)\n if len(current_setpoints) == 1:\n setpoint = current_setpoints[0]\n if setpoint is not None:\n self._target_temperature = round((float(setpoint.value)), 1)\n elif len(current_setpoints) == 2:\n (setpoint_low, setpoint_high) = current_setpoints\n target_low, target_high = None, None\n if setpoint_low is not None:\n target_low = round((float(setpoint_low.value)), 1)\n if setpoint_high is not None:\n target_high = round((float(setpoint_high.value)), 1)\n self._target_temperature_range = (target_low, target_high)\n\n def _update_operating_state(self):\n \"\"\"Update operating state.\"\"\"\n if not self.values.operating_state:\n return\n mode = self.values.operating_state.value\n self._hvac_action = HVAC_CURRENT_MAPPINGS.get(str(mode).lower())\n\n def _update_fan_state(self):\n \"\"\"Update fan state.\"\"\"\n if not self.values.fan_action:\n return\n self._fan_action = self.values.fan_action.value\n\n @property\n def fan_mode(self):\n \"\"\"Return the fan speed set.\"\"\"\n if self._current_fan_mode is None:\n return None\n return self._fan_value_label_mapping[self._current_fan_mode]\n\n @property\n def fan_modes(self):\n \"\"\"Return a list of available fan modes.\"\"\"\n if not self._fan_modes:\n return None\n fan_mode_labels = []\n for mode_value in self._fan_modes:\n fan_mode_labels.append(self._fan_value_label_mapping[mode_value])\n return fan_mode_labels\n\n @property\n def temperature_unit(self):\n \"\"\"Return the unit of measurement.\"\"\"\n if self._unit == \"F\":\n return TEMP_FAHRENHEIT\n return TEMP_CELSIUS\n\n @property\n def current_temperature(self):\n \"\"\"Return the current temperature.\"\"\"\n return self._current_temperature\n\n @property\n def hvac_mode(self):\n \"\"\"Return hvac operation ie. heat, cool mode.\n\n Needs to be one of HVAC_MODE_*.\n \"\"\"\n if not self._mode():\n return self._default_hvac_mode\n return ZW_HVAC_MODE_MAPPINGS[self._zw_hvac_mode]\n\n @property\n def hvac_modes(self):\n \"\"\"Return the list of available hvac operation modes.\n\n Need to be a subset of HVAC_MODES.\n \"\"\"\n if not self._mode():\n return []\n return self._hvac_list\n\n @property\n def hvac_action(self):\n \"\"\"Return the current running hvac operation if supported.\n\n Needs to be one of CURRENT_HVAC_*.\n \"\"\"\n return self._hvac_action\n\n @property\n def preset_mode(self):\n \"\"\"Return preset operation ie. eco, away.\n\n Needs to be one of PRESET_*.\n \"\"\"\n if not self._mode() or self._preset_mode == PRESET_NONE:\n return PRESET_NONE\n return self._hvac_value_label_mapping[self._preset_mode]\n\n @property\n def preset_modes(self):\n \"\"\"Return the list of available preset operation modes.\n\n Need to be a subset of PRESET_MODES.\n \"\"\"\n if not self._mode():\n return []\n preset_labels = []\n for value in self._preset_list:\n preset_labels.append(self._hvac_value_label_mapping[value])\n preset_labels.append(PRESET_NONE)\n return preset_labels\n\n @property\n def target_temperature(self):\n \"\"\"Return the temperature we try to reach.\"\"\"\n return self._target_temperature\n\n @property\n def target_temperature_low(self) -> Optional[float]:\n \"\"\"Return the lowbound target temperature we try to reach.\"\"\"\n return self._target_temperature_range[0]\n\n @property\n def target_temperature_high(self) -> Optional[float]:\n \"\"\"Return the highbound target temperature we try to reach.\"\"\"\n return self._target_temperature_range[1]\n\n async def async_set_temperature(self, **kwargs):\n \"\"\"Set new target temperature.\n\n Must know if single or double setpoint.\n \"\"\"\n current_setpoints = self._current_mode_setpoints()\n if len(current_setpoints) == 1:\n setpoint = current_setpoints[0]\n target_temp = kwargs.get(ATTR_TEMPERATURE)\n if setpoint is not None and target_temp is not None:\n setpoint.send_value(target_temp)\n elif len(current_setpoints) == 2:\n (setpoint_low, setpoint_high) = current_setpoints\n target_temp_low = kwargs.get(ATTR_TARGET_TEMP_LOW)\n target_temp_high = kwargs.get(ATTR_TARGET_TEMP_HIGH)\n if setpoint_low is not None and target_temp_low is not None:\n setpoint_low.send_value(target_temp_low)\n if setpoint_high is not None and target_temp_high is not None:\n setpoint_high.send_value(target_temp_high)\n\n async def async_set_fan_mode(self, fan_mode):\n \"\"\"Set new target fan mode.\"\"\"\n if not self.values.fan_mode:\n return\n fan_mode_value = self._fan_label_value_mapping[fan_mode]\n self.values.fan_mode.send_value(fan_mode_value)\n\n async def async_set_hvac_mode(self, hvac_mode):\n \"\"\"Set new target hvac mode.\"\"\"\n if not self._mode():\n return\n hvac_mode_value = HVAC_MODE_ZW_MAPPINGS[hvac_mode]\n self._preset_mode = PRESET_NONE\n self._mode().send_value(hvac_mode_value)\n\n async def async_set_preset_mode(self, preset_mode):\n \"\"\"Set new target preset mode.\"\"\"\n if not self._mode():\n return\n if preset_mode == PRESET_NONE:\n self._mode().send_value(self._zw_hvac_mode)\n else:\n preset_mode_value = self._hvac_label_value_mapping[preset_mode.lower()]\n self._mode().send_value(preset_mode_value)\n\n @property\n def device_state_attributes(self):\n \"\"\"Return the optional state attributes.\"\"\"\n data = super().device_state_attributes\n if self._fan_action:\n data[ATTR_FAN_ACTION] = self._fan_action\n return data\n\n\nclass ZWaveClimateSingleSetpoint(ZWaveClimateBase):\n \"\"\"Representation of a single setpoint Z-Wave thermostat device.\"\"\"\n\n def _mode(self) -> None:\n \"\"\"Return thermostat mode Z-Wave value.\"\"\"\n return self.values.mode\n\n def _current_mode_setpoints(self) -> Tuple:\n \"\"\"Return a tuple of current setpoint Z-Wave value(s).\"\"\"\n return (self.values.primary,)\n\n\nclass ZWaveClimateMultipleSetpoint(ZWaveClimateBase):\n \"\"\"Representation of a multiple setpoint Z-Wave thermostat device.\"\"\"\n\n def _mode(self) -> None:\n \"\"\"Return thermostat mode Z-Wave value.\"\"\"\n return self.values.primary\n\n def _current_mode_setpoints(self) -> Tuple:\n \"\"\"Return a tuple of current setpoint Z-Wave value(s).\"\"\"\n current_mode = self.values.primary.value[\"Selected_id\"]\n setpoints_names = MODE_SETPOINT_MAPPINGS.get(current_mode, ())\n return tuple(getattr(self.values, name, None) for name in setpoints_names)\n" }, { "alpha_fraction": 0.6057662963867188, "alphanum_fraction": 0.6075872778892517, "avg_line_length": 28.159292221069336, "blob_id": "eb796e92688ab58676d12a7ff25767e682fe3299", "content_id": "682688b34b9dfb4378310d521621cca4cfdd515c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3295, "license_type": "no_license", "max_line_length": 83, "num_lines": 113, "path": "/tests/common.py", "repo_name": "cgarwood/homeassistant-zwave_mqtt", "src_encoding": "UTF-8", "text": "\"\"\"Helpers for tests.\"\"\"\nfrom contextlib import contextmanager\nimport json\nimport logging\nfrom pathlib import Path\nfrom unittest.mock import Mock\n\nfrom asynctest import patch\nfrom custom_components.zwave_mqtt.const import DOMAIN\n\nfrom homeassistant import config_entries, core as ha\nfrom homeassistant.helpers import storage\n\n_LOGGER = logging.getLogger(__name__)\n\n\n@contextmanager\ndef mock_storage(data=None):\n \"\"\"Mock storage.\n\n Data is a dict {'key': {'version': version, 'data': data}}\n\n Written data will be converted to JSON to ensure JSON parsing works.\n \"\"\"\n if data is None:\n data = {}\n\n orig_load = storage.Store._async_load\n\n async def mock_async_load(store):\n \"\"\"Mock version of load.\"\"\"\n if store._data is None:\n # No data to load\n if store.key not in data:\n return None\n\n mock_data = data.get(store.key)\n\n if \"data\" not in mock_data or \"version\" not in mock_data:\n _LOGGER.error('Mock data needs \"version\" and \"data\"')\n raise ValueError('Mock data needs \"version\" and \"data\"')\n\n store._data = mock_data\n\n # Route through original load so that we trigger migration\n loaded = await orig_load(store)\n _LOGGER.info(\"Loading data for %s: %s\", store.key, loaded)\n return loaded\n\n def mock_write_data(store, path, data_to_write):\n \"\"\"Mock version of write data.\"\"\"\n _LOGGER.info(\"Writing data to %s: %s\", store.key, data_to_write)\n # To ensure that the data can be serialized\n data[store.key] = json.loads(json.dumps(data_to_write, cls=store._encoder))\n\n with patch(\n \"homeassistant.helpers.storage.Store._async_load\",\n side_effect=mock_async_load,\n autospec=True,\n ), patch(\n \"homeassistant.helpers.storage.Store._write_data\",\n side_effect=mock_write_data,\n autospec=True,\n ):\n yield data\n\n\nasync def setup_zwave(hass, fixture=None):\n \"\"\"Set up Z-Wave and load a dump.\"\"\"\n hass.config.components.add(\"mqtt\")\n\n with patch(\"homeassistant.components.mqtt.async_subscribe\") as mock_subscribe:\n await hass.config_entries.async_add(\n config_entries.ConfigEntry(\n 1,\n DOMAIN,\n \"Z-Wave\",\n {},\n config_entries.SOURCE_USER,\n config_entries.CONN_CLASS_LOCAL_PUSH,\n {},\n )\n )\n await hass.async_block_till_done()\n\n assert \"zwave_mqtt\" in hass.config.components\n assert len(mock_subscribe.mock_calls) == 1\n receive_message = mock_subscribe.mock_calls[0][1][2]\n\n if fixture is not None:\n data = Path(__file__).parent / \"fixtures\" / fixture\n\n with data.open(\"rt\") as fp:\n for line in fp:\n topic, payload = line.strip().split(\",\", 1)\n receive_message(Mock(topic=topic, payload=payload))\n\n await hass.async_block_till_done()\n\n return receive_message\n\n\ndef async_capture_events(hass, event_name):\n \"\"\"Create a helper that captures events.\"\"\"\n events = []\n\n @ha.callback\n def capture_events(event):\n events.append(event)\n\n hass.bus.async_listen(event_name, capture_events)\n\n return events\n" }, { "alpha_fraction": 0.6861110925674438, "alphanum_fraction": 0.6861110925674438, "avg_line_length": 28.387754440307617, "blob_id": "6a8dd98ebc04d734a751a5c5c3cb357b7ff49627", "content_id": "0b85d9e041a0f0151d0957f4e46aa413fed24ae3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1440, "license_type": "no_license", "max_line_length": 84, "num_lines": 49, "path": "/custom_components/zwave_mqtt/switch.py", "repo_name": "cgarwood/homeassistant-zwave_mqtt", "src_encoding": "UTF-8", "text": "\"\"\"Representation of Z-Wave switchs.\"\"\"\n\nimport logging\n\nfrom homeassistant.components.switch import SwitchDevice\nfrom homeassistant.const import STATE_OFF, STATE_ON\nfrom homeassistant.core import callback\nfrom homeassistant.helpers.dispatcher import async_dispatcher_connect\n\nfrom .const import DATA_UNSUBSCRIBE, DOMAIN\nfrom .entity import ZWaveDeviceEntity\n\n_LOGGER = logging.getLogger(__name__)\n\n\nasync def async_setup_entry(hass, config_entry, async_add_entities):\n \"\"\"Set up Z-Wave switch from config entry.\"\"\"\n\n @callback\n def async_add_switch(value):\n \"\"\"Add Z-Wave Switch.\"\"\"\n switch = ZWaveSwitch(value)\n\n async_add_entities([switch])\n\n hass.data[DOMAIN][config_entry.entry_id][DATA_UNSUBSCRIBE].append(\n async_dispatcher_connect(hass, \"zwave_new_switch\", async_add_switch)\n )\n\n await hass.data[DOMAIN][config_entry.entry_id][\"mark_platform_loaded\"](\"switch\")\n\n\nclass ZWaveSwitch(ZWaveDeviceEntity, SwitchDevice):\n \"\"\"Representation of a Z-Wave switch.\"\"\"\n\n @property\n def state(self):\n \"\"\"Return the state of the switch.\"\"\"\n if self.values.primary.value:\n return STATE_ON\n return STATE_OFF\n\n async def async_turn_on(self, **kwargs):\n \"\"\"Turn the switch on.\"\"\"\n self.values.primary.send_value(True)\n\n async def async_turn_off(self, **kwargs):\n \"\"\"Turn the switch off.\"\"\"\n self.values.primary.send_value(False)\n" }, { "alpha_fraction": 0.6879084706306458, "alphanum_fraction": 0.6944444179534912, "avg_line_length": 33, "blob_id": "a8fd39e11db9f3578eb0de58d77d4f1eb5f645eb", "content_id": "ee5f738af589644cba905b63700d07b35417a846", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 612, "license_type": "no_license", "max_line_length": 84, "num_lines": 18, "path": "/tests/test_sensor.py", "repo_name": "cgarwood/homeassistant-zwave_mqtt", "src_encoding": "UTF-8", "text": "\"\"\"Test Z-Wave Sensors.\"\"\"\nfrom tests.common import setup_zwave\n\n\nasync def test_sensor(hass, sent_messages):\n \"\"\"Test setting up config entry.\"\"\"\n await setup_zwave(hass, \"generic_network_dump.csv\")\n\n # Test standard sensor\n state = hass.states.get(\"sensor.smart_plug_electric_v\")\n assert state is not None\n assert state.state == \"123.9\"\n assert state.attributes[\"unit_of_measurement\"] == \"V\"\n\n # Test list sensor converted to binary sensor\n state = hass.states.get(\"binary_sensor.trisensor_home_security_motion_detected\")\n assert state is not None\n assert state.state == \"off\"\n" }, { "alpha_fraction": 0.707530677318573, "alphanum_fraction": 0.7092819809913635, "avg_line_length": 26.190475463867188, "blob_id": "1c4c3b587291606b560960b1480fc3d2f40896d8", "content_id": "0f698225efd1a9802381ccebbf7194845acd433f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 571, "license_type": "no_license", "max_line_length": 65, "num_lines": 21, "path": "/custom_components/zwave_mqtt/config_flow.py", "repo_name": "cgarwood/homeassistant-zwave_mqtt", "src_encoding": "UTF-8", "text": "\"\"\"Config flow for zwave_mqtt integration.\"\"\"\nimport logging\n\nfrom homeassistant import config_entries\n\nfrom .const import DOMAIN # pylint:disable=unused-import\n\n_LOGGER = logging.getLogger(__name__)\n\nTITLE = \"Z-Wave MQTT\"\n\n\nclass DomainConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):\n \"\"\"Handle a config flow for zwave_mqtt.\"\"\"\n\n VERSION = 1\n CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_PUSH\n\n async def async_step_user(self, user_input=None):\n \"\"\"Handle the initial step.\"\"\"\n return self.async_create_entry(title=TITLE, data={})\n" }, { "alpha_fraction": 0.6203883290290833, "alphanum_fraction": 0.6436893343925476, "avg_line_length": 33.33333206176758, "blob_id": "2a066ea05f99ab5a31efdb2f1d1c5b9e66eadce1", "content_id": "5f830ac42dc6134c1f8ddf0118153254a4721df1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1030, "license_type": "no_license", "max_line_length": 86, "num_lines": 30, "path": "/tests/test_switch.py", "repo_name": "cgarwood/homeassistant-zwave_mqtt", "src_encoding": "UTF-8", "text": "\"\"\"Test Z-Wave Switches.\"\"\"\nfrom tests.common import setup_zwave\n\n\nasync def test_switch(hass, sent_messages):\n \"\"\"Test setting up config entry.\"\"\"\n await setup_zwave(hass, \"generic_network_dump.csv\")\n\n # Test loaded\n state = hass.states.get(\"switch.smart_plug_switch\")\n assert state is not None\n assert state.state == \"off\"\n\n # Test turning on\n await hass.services.async_call(\n \"switch\", \"turn_on\", {\"entity_id\": \"switch.smart_plug_switch\"}, blocking=True\n )\n assert len(sent_messages) == 1\n msg = sent_messages[0]\n assert msg[\"topic\"] == \"OpenZWave/1/command/setvalue/\"\n assert msg[\"payload\"] == {\"Value\": True, \"ValueIDKey\": 541671440}\n\n # Test turning off\n await hass.services.async_call(\n \"switch\", \"turn_off\", {\"entity_id\": \"switch.smart_plug_switch\"}, blocking=True\n )\n assert len(sent_messages) == 2\n msg = sent_messages[1]\n assert msg[\"topic\"] == \"OpenZWave/1/command/setvalue/\"\n assert msg[\"payload\"] == {\"Value\": False, \"ValueIDKey\": 541671440}\n" } ]
15